Mctaba Labs logo
BootcampData ScienceThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book CallApply

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
Mctaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • Coding Bootcamp in Nairobi
  • Data Science to AI Engineering
  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • Kids & Teens
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Data Science Guides
  • African Payments Reference
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Software & AI Studio
  • Our Work
  • Outcomes

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2026 Mctaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Data Science in Kenya
  3. SQL for Data Analysis: Queries You Will Use Every Week
Bonaventure OgetoBy Bonaventure Ogeto|Updated November 3, 2026

Last checked 3 November 2026

SQL for Data Analysis: Queries You Will Use Every Week

Most weekly analysis uses five patterns: filtering with WHERE, totals with GROUP BY, JOIN to attach names, window functions for running balances, and date buckets for trends. Learn these five on one table you understand, such as a mobile money transactions table, before anything else.

In this article

  1. 1. The table we will use
  2. 2. Query 1 and 2: filter, then total
  3. 3. Query 3: JOIN to attach names
  4. 4. Query 4: a running balance with a window function
  5. 5. Query 5: date buckets for a trend
  6. 6. How to practise

The table we will use

McTaba runs coding and data bootcamps in Kenya. This guide is written to be useful whether or not you ever join one.

Picture a Safaricom statement PDF, turned into rows. Every payment in, every payment out, one line each. That is a transactions table, and it is the table most Kenyan analysts meet first. Our walk-through of the data science career in Kenya explains where SQL fits in the job.

All data here is made up. Imagine two tables in PostgreSQL:

CREATE TABLE customers (
  customer_id  integer PRIMARY KEY,
  name         text,
  town         text
);

CREATE TABLE transactions (
  txn_id       integer PRIMARY KEY,
  customer_id  integer REFERENCES customers,
  txn_time     timestamp,
  kind         text,       -- 'receive', 'send', 'paybill', 'airtime'
  amount       numeric     -- shillings, always positive
);

Five sample rows of transactions, also made up:

txn_idcustomer_idtxn_timekindamount
1102026-10-01 08:12receive5,000
2102026-10-01 12:40paybill1,200
3112026-10-02 09:05receive800
4102026-10-03 18:22send1,500
5112026-10-03 19:01airtime100

Learning SQL on a table you can picture is faster than learning it on abstract ones. If you want a class around it, the Data Science to AI Engineering programme teaches SQL and PostgreSQL in its data handling phase.

Query 1 and 2: filter, then total

Every analysis starts by narrowing. How much money came in during October?

SELECT SUM(amount) AS received_october
FROM transactions
WHERE kind = 'receive'
  AND txn_time >= '2026-10-01'
  AND txn_time <  '2026-11-01';

Use "greater than or equal" for the start and "less than" for the next month's first day. It avoids losing the last day or double counting midnight.

Now the pattern you will type most: GROUP BY. Total sent and received per kind of transaction.

SELECT kind,
       COUNT(*)    AS n,
       SUM(amount) AS total,
       AVG(amount) AS average
FROM transactions
GROUP BY kind
ORDER BY total DESC;

Add HAVING when you want to filter on the total itself, such as only kinds with more than 100 rows. It is WHERE for groups.

You can do the same grouping in Python. Our first 30 days of Python shows the loop version.

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Query 3: JOIN to attach names

Customer ids are useless in a report. Managers want names and towns. A JOIN pulls them from the other table.

SELECT c.town,
       COUNT(*)      AS payments,
       SUM(t.amount) AS total
FROM transactions t
JOIN customers c ON c.customer_id = t.customer_id
WHERE t.kind = 'paybill'
GROUP BY c.town
ORDER BY total DESC;

Two habits save hours. Alias tables with short letters. And know the difference between JOIN and LEFT JOIN. A plain JOIN drops customers with no rows. LEFT JOIN keeps them, with empty cells. To list customers who never transacted:

SELECT c.name
FROM customers c
LEFT JOIN transactions t ON t.customer_id = c.customer_id
WHERE t.txn_id IS NULL;

Always count rows before and after a JOIN. If the count grows, one side has duplicate keys, and your totals are wrong.

Query 4: a running balance with a window function

A statement shows a balance after every line. You can rebuild it. Treat receives as plus and everything else as minus, then add up as you go.

SELECT txn_id,
       txn_time,
       kind,
       amount,
       SUM(CASE WHEN kind = 'receive' THEN amount ELSE -amount END)
         OVER (PARTITION BY customer_id ORDER BY txn_time) AS running_balance
FROM transactions
WHERE customer_id = 10
ORDER BY txn_time;

For customer 10, the made-up rows give 5,000, then 3,800 after the paybill, then 2,300 after the send. PARTITION BY restarts the sum for each customer. ORDER BY decides the order of adding.

Two more window tools worth knowing:

  • LAG(amount) OVER (...) reads the previous row, so you can find the gap between two payments.
  • ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY txn_time DESC) numbers each customer's rows from newest, so filtering to 1 gives the latest one.

Window functions are where many learners stall. If it feels strange, that is normal. Read it as "for each row, look at a group of rows and calculate something, without collapsing them".

Query 5: date buckets for a trend

Managers ask "is it going up?" You answer with one row per day, week or month. In PostgreSQL, date_trunc does the bucketing.

SELECT date_trunc('week', txn_time)::date AS week_start,
       COUNT(*)    AS payments,
       SUM(amount) AS total
FROM transactions
WHERE kind = 'paybill'
GROUP BY week_start
ORDER BY week_start;

Two traps. A week with no payments simply does not appear, so a chart may skip it. And time zones: a timestamp stored in UTC puts a 1 AM Nairobi payment on the previous day. Check how your database stores time before you trust a daily count.

Once you can write these five patterns, the next skill is deciding which numbers deserve trust. That is the subject of the statistics you actually need for data science. Turning the output into a decision is covered in data storytelling.

How to practise

  1. Install PostgreSQL, or use a free browser tool such as SQLBolt for the basics.
  2. Create the two tables above and add about fifty made-up rows.
  3. Write each of the five queries from memory, then compare.
  4. Invent three questions a shop or chama treasurer would ask, and answer each in SQL.

No school can promise you a job, and SQL alone does not make a data career. It is the skill nearly every analyst role asks you to show. The Data Science to AI Engineering programme starts on 11 January 2027 and costs KES 140,000; the SQL you practise here is the base it builds on.

Key Takeaways

  • ✓Five patterns cover most weekly work: WHERE, GROUP BY, JOIN, window functions and date buckets.
  • ✓Learn them on one table you can picture, such as a mobile money statement.
  • ✓Count rows before and after every JOIN.
  • ✓Check how time zones are stored before trusting a daily count.

Frequently Asked Questions

Which SQL should I learn for data analysis?
Start with PostgreSQL. Its syntax is close to the standard, it is free, and the window functions and date tools here work in most other databases with small changes.
How long does it take to learn SQL for analysis?
The five patterns here take most beginners three to five weeks of regular practice. Window functions usually take the longest.
What is the difference between WHERE and HAVING?
WHERE filters rows before they are grouped. HAVING filters the groups after totals are calculated.
Do I need SQL if I know Python?
Yes. Business data usually lives in a database, and SQL is the fastest way to pull the slice you need before Python takes over.

Learn data science on African data

KES 140,000

Data Science to AI Engineering: 5 months full time or 8 months part time, hybrid in Nairobi. Fraud, credit and M-Pesa data from Week 1, and every model deployed. Starts 11 January 2027.

See the Data Science programme

Need it live by next month? Our studio builds it

Related guides

  • Data Engineering Basics: Build a Pipeline with Airflow and Docker
  • Forecast a Shop's Stock from Till Data
  • From Excel to Python: A Migration Plan for Analysts

Keep reading

Python for Data Science: Your First 30 Days

Thirty days, four weeks, one small script a week. Learn only the parts of Python that data work uses, with examples on made-up Kenyan shop data.

Read more

The Statistics You Actually Need for Data Science

Five statistics ideas do most of the work in data jobs. Each one comes with a small worked example you can check on paper.

Read more

Data Storytelling: Turning a Chart into a Decision

A chart is not the finish line. This guide shows the one-page memo, a simple way to pick a chart, and a before and after on made-up shop data.

Read more

Data Science Roadmap for Beginners: 6 Months, Week by Week

Twenty-six weeks, free resources only, and one small project a month built on African data. Follow it alone or use it to check any course you are paying for.

Read more

Explore related topics

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

Tech Salary Data

Transparent salary data for tech roles in Africa and worldwide, updated regularly with real market research.

AI Skills & Tools

Practical AI knowledge for developers. Build your first agent, get good at RAG, and pick the right AI coding tools for real work.

Bonaventure Ogeto

Bonaventure Ogeto

Founder and CEO, Mctaba Labs

Software engineer for 8+ years. He runs a Nairobi studio that ships products on M-Pesa, WhatsApp and AI, and teaches what the studio ships. He holds a BSc in Mathematics and Computer Science.

More about the author