Fourteen short lessons on a mock payments database, from rusty to writing joins, CTEs and window functions from a blank page.
What you'll learn today: how to ask the database for the rows you want, keep only the ones that matter, and put them in order. By the end you'll be able to answer "show me every failed SGD transfer over S$1,000 last month, biggest first".
Every example below shows its real result underneath, straight from the practice data. Read the query, look at the result, and check it does what the explanation says. Click Open in console to copy it to the console on the right, then change something and run it again. Breaking things on purpose is the fastest way to learn.
A table is like one tab of a spreadsheet:
amount or status. Each column holds one kind of information.transfers table, each row is one money transfer.Here are the first 3 rows of transfers:
SELECT * FROM transfers LIMIT 3;
Some words you'll see a lot:
customers table. You'll connect the two tables on Day 4.The full list of columns is in the Tables box on the right. Keep glancing at it.
SELECT id, amount, status FROM transfers;
SELECT lists the columns you want, separated by commas. No comma after the last one.FROM says which table to look in.SELECT * means "every column". Handy for a quick look, like the first example.; marks the end. Capitals and line breaks don't matter to SQL; they just make it easier for people to read.Notice the result has all 1,500 rows, but only the 3 columns you asked for.
SELECT id, amount, status FROM transfers LIMIT 5;
Real tables can have millions of rows, so LIMIT is the polite way to take a first look. On its own it gives you some 5 rows, not the "top" 5. For "top 5", you also need to sort, which is section 9.
The database checks your condition against every row. Rows where it's true stay. Rows where it's false are thrown away.
SELECT id, amount, status FROM transfers WHERE status = 'FAILED';
Look at the status column in the result: every row says FAILED. The other statuses were filtered out.
'FAILED'. Without quotes, SQL thinks FAILED is a column name.'failed' finds nothing here.amount > 1000.=, not ==.SELECT id, status FROM transfers WHERE status = FAILED;
The database looks for a column called FAILED and gives an error.
SELECT id, status FROM transfers WHERE status = 'FAILED';
Now FAILED is treated as a value to match.
The comparison symbols:
| Symbol | Means | Example |
|---|---|---|
= | equals | source_currency = 'SGD' |
<> | does not equal | status <> 'COMPLETED' |
> / < | more than / less than | amount > 1000 |
>= / <= | at least / at most (includes the number itself) | amount >= 1000 includes exactly 1000 |
AND means both must be true, so each AND makes the result smaller:
SELECT id, source_currency, amount, status FROM transfers WHERE status = 'FAILED' AND source_currency = 'SGD';
OR means at least one must be true, so each OR makes the result bigger:
SELECT id, status FROM transfers WHERE status = 'FAILED' OR status = 'CANCELLED';
The trap: when you mix AND with OR, AND is worked out first, the way × happens before + in maths. Compare these two. They look almost the same:
SELECT id, status, target_currency FROM transfers WHERE status = 'FAILED' AND target_currency = 'USD' OR target_currency = 'EUR';
This means "(failed AND USD) OR any EUR transfer". Look at the result: COMPLETED EUR transfers sneak in.
SELECT id, status, target_currency FROM transfers WHERE status = 'FAILED' AND (target_currency = 'USD' OR target_currency = 'EUR');
Now it means "failed, AND going to USD or EUR". Every row is FAILED.
Rule of thumb: whenever AND and OR appear together, add brackets.
IN checks against a list. It's a tidier way to write several ORs, and it avoids the trap above:
SELECT id, status, target_currency
FROM transfers
WHERE status = 'FAILED'
AND target_currency IN ('USD', 'EUR');
This gives exactly the same rows as the "with brackets" version. NOT IN (...) is the opposite: everything except the list.
BETWEEN checks a range and includes both ends. BETWEEN 100 AND 500 means "100 or more, and 500 or less":
SELECT id, amount FROM transfers WHERE source_currency = 'SGD' AND amount BETWEEN 100 AND 500;
LIKE matches a pattern in text. % means "any characters, or none":
LIKE 'Tan%': starts with TanLIKE '%Tan': ends with TanLIKE '%Tan%': has Tan anywhereSELECT id, name FROM customers WHERE name LIKE '%Tan';
Some cells are empty. In SQL, empty is called NULL. It doesn't mean zero or blank text; it means "no value here". For example, completed_at is NULL for transfers that never completed:
SELECT id, status, completed_at FROM transfers WHERE status = 'FAILED';
To find NULLs you must use IS NULL. Using = doesn't work, because SQL treats NULL as "unknown", and "is unknown equal to unknown?" has no answer:
SELECT id, completed_at FROM transfers WHERE completed_at = NULL;
No rows, even though there are plenty of NULLs.
SELECT id, completed_at FROM transfers WHERE completed_at IS NULL;
IS NULL finds them. IS NOT NULL finds the ones that do have a value.
Dates here look like '2026-10-15 14:03:00': year, month, day, then time. Because the year comes first, sorting them as text also sorts them by time, so normal comparisons work. Everything in October 2026:
SELECT id, created_at FROM transfers WHERE created_at >= '2026-10-01' AND created_at < '2026-11-01';
Why < '2026-11-01' instead of <= '2026-10-31'? Because a transfer at '2026-10-31 18:00:00' counts as after '2026-10-31' when compared as text, so you'd lose everything on the last day. The safe habit: on or after the first day, and before the first day of the next period.
SELECT id, amount FROM transfers WHERE source_currency = 'SGD' ORDER BY amount DESC LIMIT 5;
DESC means biggest (or latest, or Z) first. Without it you get ASC, smallest first. Combined with LIMIT, this is "the 5 biggest SGD transfers".
You can sort by more than one column. The second only matters when the first is tied:
SELECT status, amount FROM transfers ORDER BY status, amount DESC LIMIT 8;
Rows are grouped A to Z by status, and within the same status, biggest amount first.
"Which countries do our customers come from?" Without DISTINCT you'd get 128 rows, one per customer. With it, each country appears once:
SELECT DISTINCT country FROM customers ORDER BY country;
You always write the parts in this order:
SELECT columns FROM table WHERE conditions ORDER BY columns LIMIT number
A full example: "the 5 biggest failed SGD transfers in October 2026, and why they failed":
SELECT id, amount, target_currency, failure_reason, created_at FROM transfers WHERE status = 'FAILED' AND source_currency = 'SGD' AND created_at >= '2026-10-01' AND created_at < '2026-11-01' ORDER BY amount DESC LIMIT 5;
Only 2 rows came back, not 5. That's fine: only 2 transfers match every condition, and LIMIT 5 means "at most 5", not "exactly 5".
| Error says | Usually means |
|---|---|
no such column: FAILED | You forgot the quotes. Write 'FAILED'. |
no such column: amout | A typo in a column name. Check the Tables box. |
near "FROM": syntax error | Often a comma after the last column in SELECT. |
incomplete input | A quote or bracket was opened but never closed. |
| No error, but 0 rows | Check the spelling and capitals of your text values, and whether you wrote = NULL. |
SELECT picks columns, FROM picks the table, WHERE picks rows.IS NULL, never = NULL.>= the start, < the start of the next period.ORDER BY … DESC LIMIT N.Click Work on this, write your query in the console, press Run to see what you get, then Check. Column names don't need to match mine; only the values, and the order where it says so.
What you'll learn today: how to turn thousands of rows into a few useful numbers. How many transfers? What's the total? What's the average, per currency, per month? This is the core of almost every operations question.
Yesterday every query returned rows from the table. An aggregate function works differently: it takes a whole column and squashes it into a single number, like the SUM or AVERAGE at the bottom of a spreadsheet column.
SELECT COUNT(*) FROM transfers;
One row, one number: the count of all rows. COUNT(*) literally means "count the rows".
| Function | What it gives you |
|---|---|
COUNT(*) | How many rows |
COUNT(DISTINCT customer_id) | How many different customers |
SUM(amount) | The total |
AVG(amount) | The average |
MIN(...) / MAX(...) | Smallest / largest. On dates: earliest / latest. |
You can use several at once. WHERE still runs first, so it decides which rows go into the numbers:
SELECT COUNT(*), SUM(fee), AVG(amount), MIN(created_at), MAX(created_at) FROM transfers WHERE source_currency = 'SGD' AND status = 'COMPLETED';
The headings above are ugly, and the average has too many decimals. AS gives a column a name (an alias), and ROUND(value, 2) rounds to 2 decimal places:
SELECT COUNT(*) AS transfers,
ROUND(SUM(fee), 2) AS total_fees,
ROUND(AVG(amount), 2) AS avg_amount
FROM transfers
WHERE source_currency = 'SGD'
AND status = 'COMPLETED';
Read ROUND(AVG(amount), 2) from the inside out: first average the amounts, then round the answer.
These answer different questions, and mixing them up is a very common mistake:
SELECT COUNT(*) AS transfers FROM transfers WHERE status = 'FAILED';
Counts every failed transfer, including several from the same customer.
SELECT COUNT(DISTINCT customer_id) AS customers FROM transfers WHERE status = 'FAILED';
A customer with 3 failures counts once. That's why this number is smaller.
So far you get one number for everything. Usually you want a number per something: per status, per currency, per customer. That's what GROUP BY does.
SELECT status, COUNT(*) AS transfers FROM transfers GROUP BY status;
Behind the scenes:
Compare it with what you'd get without GROUP BY:
SELECT COUNT(*) AS transfers FROM transfers;
One pile (the whole table), so one row.
SELECT status, COUNT(*) AS transfers FROM transfers GROUP BY status;
One pile per status, so one row per status. The counts add up to the total on the left.
Group by two columns and each combination becomes a pile:
SELECT source_currency, status, COUNT(*) AS transfers FROM transfers GROUP BY source_currency, status ORDER BY source_currency, status;
Every column in SELECT must either be in GROUP BY, or be inside an aggregate like COUNT or SUM.
Why? After grouping, each pile becomes one row. If you ask for amount on its own, the pile has hundreds of different amounts, and the database doesn't know which one to show. Wrap it in SUM or AVG and it knows what to do.
PostgreSQL gives an error if you break this rule. SQLite (this page) quietly shows a random value instead, which is worse because you won't notice. Follow the rule anyway.
You can sort by a count or total, using its alias:
SELECT target_currency, COUNT(*) AS transfers FROM transfers WHERE source_currency = 'SGD' GROUP BY target_currency ORDER BY transfers DESC, target_currency;
The second sort column, target_currency, breaks ties: if two currencies had the same count, they'd be listed A to Z. Many exercises ask for this so the order is always predictable.
Both filter, but at different moments:
So a condition on a count or total ("customers with 18 or more transfers") must go in HAVING, because before grouping, the counts don't exist yet.
SELECT customer_id, COUNT(*) AS n FROM transfers WHERE COUNT(*) >= 18 GROUP BY customer_id;
Error: at the WHERE stage, nothing has been counted yet.
SELECT customer_id, COUNT(*) AS n FROM transfers GROUP BY customer_id HAVING COUNT(*) >= 18 ORDER BY n DESC;
Group first, count, then keep only the piles with 18 or more.
You can use both in one query: WHERE to pick rows, HAVING to pick groups.
SELECT customer_id, COUNT(*) AS completed FROM transfers WHERE status = 'COMPLETED' -- 1. keep only completed rows GROUP BY customer_id -- 2. one pile per customer HAVING COUNT(*) >= 15 -- 3. keep piles with 15 or more ORDER BY completed DESC;
The order the database works in is now: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. Notice HAVING repeats COUNT(*) instead of using the alias: SELECT hasn't run yet when HAVING runs, so PostgreSQL wouldn't know the alias.
created_at is the full date and time, so grouping by it directly gives nearly one pile per row. You need just the month. substr(text, start, length) cuts out part of the text. substr(created_at, 1, 7) means "start at character 1, take 7 characters":
'2026-10-15 14:03:00' 1234567 └─────┘ → '2026-10'
Every October 2026 transfer becomes '2026-10', so they all land in the same pile:
SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS transfers FROM transfers GROUP BY month ORDER BY month;
In PostgreSQL you'd write DATE_TRUNC('month', created_at) instead, because dates are real date values there rather than text.
amount is in the source currency. Some rows are SGD, some are IDR (where S$1 is about Rp12,000). Adding them together gives a meaningless number. Group by currency so each total stays separate:
SELECT source_currency, ROUND(SUM(amount), 2) AS total_sent FROM transfers WHERE status = 'COMPLETED' GROUP BY source_currency;
Look at the IDR total next to the SGD one: you can see why mixing them would be nonsense. On Day 5 you'll convert everything to SGD properly.
| Problem | Usually means |
|---|---|
misuse of aggregate: COUNT() | An aggregate in WHERE. Move that condition to HAVING. |
| One row per transfer instead of per group | You grouped by something different on every row, like id or the full created_at. |
| Odd values in a column | That column isn't in GROUP BY or inside an aggregate. Check the golden rule. |
| Count looks too big | Did you need COUNT(DISTINCT …)? |
Before each one, say to yourself what one row of the answer stands for ("one row per status", "one row per customer"). That tells you what goes in GROUP BY.
What you'll learn today: how to label rows, how to count only certain rows without throwing the rest away, and how to turn counts into rates like "8% of transfers failed". Rates are what operations teams watch every day, so this is one of the most useful lessons in the course.
It works like an IF formula in a spreadsheet. Here every SGD transfer gets a size label:
SELECT id, amount,
CASE
WHEN amount < 400 THEN 'small'
WHEN amount < 1000 THEN 'medium'
ELSE 'large'
END AS size
FROM transfers
WHERE source_currency = 'SGD';
Check the result: amounts under 400 say small, 400 to 999.99 say medium, the rest say large.
WHEN from top to bottom and stops at the first one that's true. That's why the second line only needs amount < 1000: anything under 400 was already caught by the first line.ELSE catches everything left. Without it, unmatched rows get NULL.END, and name it with AS.Once a CASE has a name, you can group by it like any column. "How many SGD transfers are small, medium and large?":
SELECT CASE WHEN amount < 400 THEN 'small'
WHEN amount < 1000 THEN 'medium'
ELSE 'large' END AS size,
COUNT(*) AS transfers
FROM transfers
WHERE source_currency = 'SGD'
GROUP BY size;
Here's a common question: "How many transfers are there in total, and how many of them failed?"
Your first instinct might be WHERE. Let's see why that doesn't work for this question.
SELECT COUNT(*) AS failed FROM transfers WHERE status = 'FAILED';
This gets the failed count. But WHERE threw every other row away before counting, so the total is gone. To get the total you'd need a second query, and to compare them you'd have to do the maths by hand.
SELECT COUNT(*) AS total,
SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed
FROM transfers;
No WHERE, so all rows stay. COUNT(*) counts all of them, and the SUM(CASE…) counts just the failed ones. Both numbers in one row.
How the conditional count works. The CASE turns each row into a 1 or a 0: 1 if it's failed, 0 if not. SUM then adds them up. Adding up 1s for failed rows and 0s for the rest gives you... the number of failed rows. Picture five rows:
| status | CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END |
|---|---|
| COMPLETED | 0 |
| FAILED | 1 |
| COMPLETED | 0 |
| FAILED | 1 |
| CANCELLED | 0 |
| SUM | 2 failed, out of 5 rows |
Because nothing is thrown away, you can put several of these side by side, one per thing you want to count:
SELECT COUNT(*) AS total,
SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) AS completed,
SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed,
SUM(CASE WHEN status = 'CANCELLED' THEN 1 ELSE 0 END) AS cancelled
FROM transfers;
When to use which: use WHERE when you only care about the matching rows. Use a conditional count when you need the matching rows and something else (like the total) in the same result. Rates always need both, which is why the next section uses conditional counts.
PostgreSQL has a shorter way to write this: COUNT(*) FILTER (WHERE status = 'FAILED'). The SUM(CASE…) version works in every database, so it's the safe one to use in interviews.
A rate answers "out of all of them, how many?" It's part ÷ whole × 100. A raw count can mislead: 18 failures sounds worse than 4, but not if the 18 are out of 900 (2%) and the 4 are out of 26 (15%). Rates make groups of different sizes comparable.
The part is the conditional count, and the whole is COUNT(*):
SELECT COUNT(*) AS total,
SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed,
ROUND(SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) AS failure_rate
FROM transfers;
Read the rate from the inside out: count the failures, × 100.0, ÷ the total, round to 1 decimal. Check it against the first two columns with a calculator.
When both sides of a division are whole numbers, SQL does whole-number division and throws the decimals away. Here the sum is 115 × 100 = 11,500, then 11,500 ÷ 1,500. The true answer is 7.67, but whole-number division gives just 7. (If you divided first, 115 ÷ 1,500 would even come out as 0.) Writing 100.0 makes the calculation use decimals from the start:
SELECT SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100 / COUNT(*) AS rate FROM transfers;
The decimals are chopped off, so you only see a whole number.
SELECT SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS rate FROM transfers;
The full answer, decimals included.
Add GROUP BY and you get a rate for every group. This is the classic "which one is worst?" query:
SELECT source_currency,
COUNT(*) AS transfers,
ROUND(SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) AS failure_rate
FROM transfers
GROUP BY source_currency
ORDER BY failure_rate DESC;
Always show the count next to the rate. A high rate from a handful of transfers might just be bad luck; the same rate from hundreds is a real problem. Pointing that out in an interview shows good judgement.
A rate is worked out from a group, so filtering on it is a HAVING job. In PostgreSQL you repeat the calculation in HAVING, because the alias doesn't exist yet at that stage:
SELECT target_currency, COUNT(*) AS transfers,
ROUND(SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) AS failure_rate
FROM transfers
GROUP BY target_currency
HAVING COUNT(*) >= 50
AND SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) > 7
ORDER BY failure_rate DESC;
Repeating a long formula is clumsy. On Days 8 and 9 you'll learn CTEs, which let you calculate it once, give it a name, and filter on that name.
| Problem | Usually means |
|---|---|
| Every rate is 0 | Whole-number division. Use 100.0. |
| The total and the failed count are the same | You used WHERE status = 'FAILED', so only failed rows were left to count. |
| Some labels are NULL | No ELSE, and those rows matched no WHEN. |
| Everything lands in one label | Your WHEN lines are in the wrong order. Narrowest first. |
CASE WHEN … THEN … ELSE … END labels each row; the first true WHEN wins.SUM(CASE WHEN condition THEN 1 ELSE 0 END) counts matching rows while keeping all rows..0 matters.For each one, decide first: is it a label (plain CASE), a count of some rows (SUM of CASE), or a rate (that count × 100.0 ÷ COUNT(*))?
What you'll learn today: how to bring two tables together. The customer's name and country live in customers; the money lives in transfers. A JOIN puts them on the same row. Joins come up in nearly every interview, so take your time.
Every transfer has a customer_id. That number matches the id of exactly one customer. Look at transfer rows and then the matching customer:
SELECT id, customer_id, amount FROM transfers WHERE customer_id = 58 LIMIT 3;
SELECT id, name, country FROM customers WHERE id = 58;
All three transfers have customer_id 58, and customer 58 is one row in customers. The shared value is called a key. One customer can have many transfers, but each transfer belongs to one customer. That's a one-to-many relationship.
SELECT t.id, t.amount, c.name, c.country FROM transfers t JOIN customers c ON c.id = t.customer_id;
transfers t gives the table a short nickname, called an alias. t.amount means "amount from transfers".JOIN customers c ON c.id = t.customer_id says which table to bring in and how rows match.id, so you must say which: t.id or c.id. Plain id gives an "ambiguous column" error.Once you join, put the alias on every column. It's clearer and avoids surprises.
The joined result behaves like one wide table, so WHERE, GROUP BY and the rest work on columns from either side. "Average SGD transfer by customer country":
SELECT c.country, COUNT(*) AS transfers, ROUND(AVG(t.amount), 2) AS avg_amount FROM transfers t JOIN customers c ON c.id = t.customer_id WHERE t.source_currency = 'SGD' GROUP BY c.country;
The order of work is now: FROM and JOIN build the combined rows, then WHERE, GROUP BY and the rest.
Customers 121 to 128 signed up recently and haven't sent anything yet, so they have no rows in transfers. To see what each join does with them, both queries below look at just four customers: 120, who has transfers, and 121, 122 and 123, who don't. Results are sorted by customer id, highest first, so the customers without transfers show up at the top.
SELECT c.id, c.name, t.id AS transfer_id FROM customers c JOIN transfers t ON t.customer_id = c.id WHERE c.id BETWEEN 120 AND 123 ORDER BY c.id DESC, t.id;
Only customer 120 appears (once per transfer they made). Customers 121, 122 and 123 have no transfers, so there's nothing to match and JOIN drops them.
SELECT c.id, c.name, t.id AS transfer_id FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id WHERE c.id BETWEEN 120 AND 123 ORDER BY c.id DESC, t.id;
Customers 123, 122 and 121 are kept, with NULL in transfer_id, followed by customer 120's transfers. LEFT JOIN keeps every row from the first (left) table, matched or not.
When to use which: JOIN when you only want rows that have a match (most of the time). LEFT JOIN when the question says "every customer", "including those with none", or "who hasn't…".
That NULL is useful. "Which customers have never sent anything?" is a LEFT JOIN, then keep only the rows where the transfer side is empty:
SELECT c.id, c.name, c.signup_date FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id WHERE t.id IS NULL;
"How many transfers does each customer have, including zero?" Here the choice of COUNT matters:
SELECT c.id, c.name, COUNT(*) AS transfers FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id WHERE c.id >= 119 GROUP BY c.id, c.name;
New customers show 1, not 0. Their single row full of NULLs is still a row, and COUNT(*) counts rows.
SELECT c.id, c.name, COUNT(t.id) AS transfers FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id WHERE c.id >= 119 GROUP BY c.id, c.name;
New customers correctly show 0. COUNT(column) skips NULLs.
"Every customer and how many failed transfers they have." Where you put the status condition changes the answer:
SELECT c.id, COUNT(t.id) AS failed FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id WHERE t.status = 'FAILED' GROUP BY c.id;
Fewer than 128 rows. For customers with no failures, every joined row has a status like COMPLETED (or NULL, for customers with no transfers at all). WHERE throws those rows away, so those customers vanish. The LEFT JOIN has quietly become a normal JOIN.
SELECT c.id, COUNT(t.id) AS failed FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id AND t.status = 'FAILED' GROUP BY c.id;
All 128 customers. ON only decides which transfers get attached; customers with none are still kept, with 0.
This is a classic interview trap. Rule: a condition on the right-hand table of a LEFT JOIN goes in ON if you want to keep the unmatched rows.
| Problem | Usually means |
|---|---|
ambiguous column name: id | Both tables have it. Write t.id or c.id. |
| Far more rows than expected | The ON condition is wrong, so rows matched many times. |
| Some customers are missing | JOIN drops non-matches. Use LEFT JOIN. |
| LEFT JOIN behaves like JOIN | A WHERE condition on the right table. Move it into ON. |
| Customers with nothing show 1 | Use COUNT(t.id), not COUNT(*). |
JOIN table alias ON key = key puts matching rows side by side.WHERE right.id IS NULL.For each one ask: which table has the columns I need, and do I need to keep rows with no match?
What you'll learn today: how to chain several joins, and how to convert every amount to SGD so totals across currencies finally make sense.
fx_rates says how many Singapore dollars one unit of each currency is worth:
SELECT * FROM fx_rates;
So 1 USD = S$1.35, and 1 IDR is worth a tiny fraction of a dollar. countries turns a country code into a full name and region:
SELECT * FROM countries;
These rates are fixed, made-up numbers. A real system stores a rate per day and joins on the date too. Mentioning that in an interview shows you think about real data.
SELECT t.id, t.source_currency, t.amount, f.sgd_rate,
ROUND(t.amount * f.sgd_rate, 2) AS amount_sgd
FROM transfers t
JOIN fx_rates f ON f.currency = t.source_currency;
The key here is the currency code, not an id. Keys can be any column the two tables share.
Now you can total across currencies, which Day 2 warned you not to do with raw amounts:
SELECT ROUND(SUM(amount), 2) AS total FROM transfers WHERE status = 'COMPLETED';
Adds SGD, IDR, PHP and the rest as if they were the same money. The huge number comes mostly from rupiah.
SELECT ROUND(SUM(t.amount * f.sgd_rate), 2) AS total_sgd FROM transfers t JOIN fx_rates f ON f.currency = t.source_currency WHERE t.status = 'COMPLETED';
Every row is in SGD first, so the total is real.
Round the final total, not each row. Rounding first and adding later can drift by a few cents.
To get a transfer's country name, you go transfers → customers (for the country code) → countries (for the name). Each JOIN adds one more table to the rows you already have:
SELECT t.id, c.name AS customer, co.name AS country, co.region FROM transfers t JOIN customers c ON c.id = t.customer_id JOIN countries co ON co.code = c.country;
c.country, from customers.name column, so rename them with AS to keep the result clear."Completed volume in SGD by region" needs the amount (transfers), the rate (fx_rates), the link to the customer (customers) and the region (countries):
SELECT co.region, ROUND(SUM(t.amount * f.sgd_rate), 2) AS volume_sgd FROM transfers t JOIN customers c ON c.id = t.customer_id JOIN countries co ON co.code = c.country JOIN fx_rates f ON f.currency = t.source_currency WHERE t.status = 'COMPLETED' GROUP BY co.region;
How to build one of these: start from the table with one row per thing you're measuring (transfers), then add one join at a time, running the query after each to check it still looks right.
A join gives you one row per match. When one side has many matches, the other side's rows get repeated. Watch what happens if you count customers after joining transfers:
SELECT COUNT(*) AS customers FROM customers c JOIN transfers t ON t.customer_id = c.id;
1,500, not 120. Each customer appears once per transfer, so you've counted transfers.
SELECT COUNT(DISTINCT c.id) AS customers FROM customers c JOIN transfers t ON t.customer_id = c.id;
120 different customers who have transfers.
The same thing silently inflates SUMs. A quick safety check: count rows before and after your joins. If you joined lookup tables (like customers or fx_rates) onto transfers, the count should stay at 1,500:
SELECT (SELECT COUNT(*) FROM transfers) AS before_joins,
(SELECT COUNT(*) FROM transfers t
JOIN customers c ON c.id = t.customer_id
JOIN fx_rates f ON f.currency = t.source_currency) AS after_joins;
Saying "let me sanity-check the row count" in an interview is a strong habit.
| Problem | Usually means |
|---|---|
| Totals are suspiciously large | A join multiplied rows. Check counts before and after. |
no such column: c.country | Wrong alias, or that table isn't joined yet. |
| Two columns called name | Rename them with AS. |
| Fewer rows than expected | JOIN found no match for some rows (for example a currency missing from fx_rates). |
amount * sgd_rate before adding across currencies.What you'll learn today: how to pull out parts of a date (hour, weekday, month), do date arithmetic ("the last 30 days"), and measure the time between two events ("how long did it take?"). This is where SQLite and PostgreSQL differ most, so every section shows both.
In SQLite, strftime(format, date) pulls out the part you ask for:
SELECT created_at,
strftime('%Y-%m', created_at) AS month,
strftime('%H', created_at) AS hour,
strftime('%w', created_at) AS weekday
FROM transfers;
Look at the result: each part has been cut out of the same timestamp. Weekday is a number, 0 for Sunday to 6 for Saturday.
| You want | SQLite (this page) | PostgreSQL |
|---|---|---|
| Year and month | strftime('%Y-%m', created_at) | DATE_TRUNC('month', created_at) |
| Just the date | date(created_at) | created_at::date |
| Hour 00 to 23 | strftime('%H', created_at) | EXTRACT(HOUR FROM created_at) |
| Day of week | strftime('%w', created_at) | EXTRACT(DOW FROM created_at) |
Group by a part to see patterns. "When in the day do people send money?":
SELECT strftime('%H', created_at) AS hour, COUNT(*) AS transfers
FROM transfers
GROUP BY hour
ORDER BY hour;
date(start, change) moves a date forwards or backwards:
SELECT date('2026-11-01', '-30 days') AS thirty_days_before,
date('2026-11-01', '-1 month') AS a_month_before,
date('2026-11-01', '+7 days') AS a_week_later;
In PostgreSQL you'd write DATE '2026-11-01' - INTERVAL '30 days'. Put together with Day 1's date-range habit, "the 30 days before 1 November":
SELECT COUNT(*) AS transfers
FROM transfers
WHERE created_at >= date('2026-11-01', '-30 days')
AND created_at < '2026-11-01';
In real work you'd use today's date: date('now', '-30 days') in SQLite, or CURRENT_DATE - INTERVAL '30 days' in PostgreSQL. This page uses fixed dates so the answers never change.
You can't subtract text, so SQLite's julianday() turns a date into a number of days. Subtract two of those and you get the gap in days; × 24 turns it into hours:
SELECT id, created_at, completed_at,
julianday(completed_at) - julianday(created_at) AS days,
ROUND((julianday(completed_at) - julianday(created_at)) * 24, 1) AS hours
FROM transfers
WHERE status = 'COMPLETED';
Compare the days and hours columns: hours is always 24 times days. In PostgreSQL: EXTRACT(EPOCH FROM completed_at - created_at) / 3600 gives hours (EPOCH means "in seconds").
Only completed transfers have a completed_at. For the rest the gap is NULL, which AVG and friends simply skip.
"Average hours to complete, per corridor" is easy. But one transfer stuck for two days drags an average up, while a hundred fast ones hide it. So it's worth counting the slow ones too:
SELECT target_currency,
ROUND(AVG((julianday(completed_at) - julianday(created_at)) * 24), 1) AS avg_hours,
SUM(CASE WHEN (julianday(completed_at) - julianday(created_at)) * 24 > 24 THEN 1 ELSE 0 END) AS over_a_day
FROM transfers
WHERE status = 'COMPLETED' AND source_currency = 'SGD'
GROUP BY target_currency
ORDER BY avg_hours DESC;
Notice the Day 3 conditional count being reused for "how many took more than a day". Mentioning the median, or a count of slow cases like this, is a good interview habit.
The hours formula is long, and WHERE can't use its alias, so you have to repeat it. From Day 8, you'll work it out once in a named step and reuse it.
| Problem | Usually means |
|---|---|
| Durations are all NULL | Non-completed transfers are included. Filter to COMPLETED. |
| Durations look 24 times too small | You forgot × 24; julianday gaps are in days. |
| A date range misses the last day | Use < the start of the next period. |
strftime pulls out month, hour or weekday; group by it to find patterns.date(x, '-30 days') moves dates; PostgreSQL uses INTERVAL.(julianday(end) - julianday(start)) * 24 hours.What you'll practise today: nothing new. The exercises mix everything from Days 1 to 6, the way real questions do. The skill you're building is working out which tools a question needs without being told.
Say them out loud in an interview. It shows a clear method, and it stops you writing the wrong query fast.
| The question says… | Reach for… |
|---|---|
| "how many", "total", "average", "per X" | COUNT / SUM / AVG with GROUP BY X |
| "how many different" | COUNT(DISTINCT …) |
| "what %", "rate", "share" | SUM(CASE WHEN … THEN 1 ELSE 0 END) * 100.0 / COUNT(*) |
| "only groups with…" | HAVING |
| "customer name", "country", "region" | JOIN customers / countries |
| "including those with none", "never" | LEFT JOIN, maybe … IS NULL |
| "in SGD", "across currencies" | JOIN fx_rates, amount * sgd_rate |
| "how long", "took more than" | julianday() gap |
| "by month", "by hour" | strftime / substr |
| "top N", "the highest" | ORDER BY … DESC LIMIT N |
"Which SGD corridors had more than 5 failed transfers in 2026, and what were their failure rates?"
GROUP BY target_currency.SELECT target_currency,
SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed,
ROUND(SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) * 100.0 / COUNT(*), 1) AS failure_rate
FROM transfers
WHERE source_currency = 'SGD' AND created_at >= '2026-01-01'
GROUP BY target_currency
HAVING SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) > 5
ORDER BY failure_rate DESC, target_currency;
For anything with more than two parts, don't write it all at once:
SELECT * FROM transfers LIMIT 10 to see the data.Each step either looks right or shows you exactly where it went wrong.
After these exercises, open Weak spots in the top bar. After a week of tracking it knows which skills need work, so a few rounds there is the best use of the rest of today.
What you'll learn today: how to break a question into steps, where one step's result feeds the next. Some questions can't be answered in one pass. "Which months were above average?" needs the monthly numbers first, then their average, then a comparison. Wise's job ad names CTEs specifically.
"Which SGD transfers are bigger than the average SGD transfer?" You need the average before you can compare against it:
SELECT AVG(amount) FROM transfers WHERE source_currency = 'SGD';
Now put that query in brackets inside the main one. The inner query runs first and gives one number; the outer query uses it like a fixed value:
SELECT id, amount FROM transfers WHERE source_currency = 'SGD' AND amount > (SELECT AVG(amount) FROM transfers WHERE source_currency = 'SGD') ORDER BY amount DESC;
Every amount in the result is above the average you saw a moment ago. A subquery can also give a list, for use with IN:
SELECT id, name FROM customers WHERE id IN (SELECT customer_id FROM transfers WHERE failure_reason = 'COMPLIANCE_HOLD');
Subqueries get hard to read once they're nested inside each other. A CTE (Common Table Expression) moves the step to the top and gives it a name, using WITH.
"On average, how many transfers does a customer make?" That's an average of counts: first count per customer, then average those counts. One GROUP BY can't do both. Step 1 on its own:
SELECT customer_id, COUNT(*) AS n FROM transfers GROUP BY customer_id;
Wrap it in WITH, give it a name, and use that name like a table:
WITH per_customer AS ( SELECT customer_id, COUNT(*) AS n FROM transfers GROUP BY customer_id ) SELECT ROUND(AVG(n), 2) AS avg_transfers, MAX(n) AS most, MIN(n) AS fewest FROM per_customer;
WITH name AS ( … ) runs the inner query and calls the result per_customer.FROM per_customer."Months with more transfers than the average month":
SELECT month, n FROM (SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n FROM transfers GROUP BY month) WHERE n > (SELECT AVG(n) FROM (SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n FROM transfers GROUP BY month)) ORDER BY month;
Works, but the monthly query is written twice and it reads inside-out.
WITH monthly AS ( SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n FROM transfers GROUP BY month ) SELECT month, n FROM monthly WHERE n > (SELECT AVG(n) FROM monthly) ORDER BY month;
Same result. The step is written once, named, and read top to bottom.
A CTE can be joined like any table. Count failures per customer in a step, then bring in their names:
WITH fails AS ( SELECT customer_id, COUNT(*) AS failures FROM transfers WHERE status = 'FAILED' GROUP BY customer_id ) SELECT c.name, f.failures FROM fails f JOIN customers c ON c.id = f.customer_id ORDER BY f.failures DESC, c.name;
In interviews, lean on CTEs. You can test each step by running its SELECT on its own, and they make it easy to talk through your thinking.
| Problem | Usually means |
|---|---|
| Syntax error right after the CTE | A missing closing bracket, or an extra comma before the main SELECT. |
no such column in the main query | The CTE doesn't have that column. It only has what its SELECT lists. |
sub-select returns 2 columns | A subquery compared with > or = must return one value. |
no such table: monthly | The CTE only exists inside its own statement. |
WITH name AS (…) creates a named step you can use like a table.Write each step's SELECT on its own first, run it, check it, then wrap it in WITH.
What you'll learn today: how to chain several steps, each building on the one before. Count, then turn counts into rates, then compare. This is how analysts answer the messy real questions.
WITH step1 AS ( … reads the real tables … ),
step2 AS ( … reads step1 … ),
step3 AS ( … can read step1 and step2 … )
SELECT … FROM step3 …;
WITH at the top, then a comma between steps.monthly, rates, per_customer.Remember Day 3, where you had to repeat the long rate formula inside HAVING? Chaining fixes that. Step 1 counts. Step 2 turns counts into a rate, with a name. The final query just filters on that name:
WITH monthly AS (
SELECT substr(created_at, 1, 7) AS month,
COUNT(*) AS total,
SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) AS failed
FROM transfers
GROUP BY month
),
rates AS (
SELECT month, total, failed, ROUND(failed * 100.0 / total, 1) AS rate
FROM monthly
)
SELECT * FROM rates WHERE rate > 8 ORDER BY month;
Try running just the monthly step's SELECT on its own in the console: that's step 1's result. The rates step adds a column to it, and the last line filters it.
"How many customers are low, mid or high value?" Step 1 totals each customer. Step 2 labels each total with CASE. The final query counts each label:
WITH totals AS (
SELECT customer_id, SUM(amount) AS total
FROM transfers
WHERE status = 'COMPLETED' AND source_currency = 'SGD'
GROUP BY customer_id
),
tiers AS (
SELECT customer_id,
CASE WHEN total < 5000 THEN 'low' WHEN total < 20000 THEN 'mid' ELSE 'high' END AS tier
FROM totals
)
SELECT tier, COUNT(*) AS customers FROM tiers GROUP BY tier;
"What % of volume does each corridor have?" needs each corridor's number and the grand total on the same row. Put the total in its own step, which has exactly one row, and attach it to every row:
WITH vol AS ( SELECT target_currency, SUM(amount) AS volume FROM transfers WHERE status = 'COMPLETED' AND source_currency = 'SGD' GROUP BY target_currency ), total AS (SELECT SUM(volume) AS all_volume FROM vol) SELECT v.target_currency, ROUND(v.volume * 100.0 / t.all_volume, 1) AS share_pct FROM vol v, total t ORDER BY share_pct DESC;
FROM vol v, total t (with a comma and no ON) pairs every row of vol with every row of total. That's only safe because total has exactly one row. The shares add up to 100 (give or take 0.1 from rounding). Day 11 shows a shorter way to do this.
"Did failures go up or down from Q2 to Q3?" Step 1 labels each row with its quarter. The final query counts each quarter in its own column, using conditional counts:
WITH labelled AS (
SELECT failure_reason,
CASE WHEN created_at >= '2026-04-01' AND created_at < '2026-07-01' THEN 'Q2'
WHEN created_at >= '2026-07-01' AND created_at < '2026-10-01' THEN 'Q3' END AS q
FROM transfers WHERE status = 'FAILED'
)
SELECT failure_reason,
SUM(CASE WHEN q = 'Q2' THEN 1 ELSE 0 END) AS q2,
SUM(CASE WHEN q = 'Q3' THEN 1 ELSE 0 END) AS q3
FROM labelled
GROUP BY failure_reason;
Turning rows (one per quarter) into columns (q2, q3) is called pivoting. It comes up a lot, because people like comparisons side by side. Failures outside Q2 and Q3 get a NULL label and land in neither column.
Say the steps before writing them: "First I'll get monthly counts, then turn them into rates, then filter." Write one step, run it, check it, then add the next. If you run out of time, two correct steps still show clear thinking.
What you'll learn today: how to calculate something across a group of rows without squashing them into one row. This is how you answer "top 3 per currency", "each customer's first transfer" or "rank customers by volume".
SELECT customer_id, COUNT(*) AS n FROM transfers WHERE customer_id <= 2 AND created_at >= '2026-08-01' GROUP BY customer_id;
You get the count, but the individual transfers are gone.
SELECT id, customer_id, amount,
COUNT(*) OVER (PARTITION BY customer_id) AS n
FROM transfers
WHERE customer_id <= 2 AND created_at >= '2026-08-01'
ORDER BY customer_id, id;
Every transfer is still there, and each one also shows its customer's total count.
OVER ( … ) is what makes it a window function.PARTITION BY customer_id means "the group is all rows with the same customer". It's like GROUP BY, but without squashing.Add ORDER BY inside OVER and you can number the rows in each group. "Number each customer's transfers, oldest first":
SELECT customer_id, id, created_at,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at) AS nth
FROM transfers
WHERE customer_id <= 2 AND created_at >= '2026-08-01'
ORDER BY customer_id, nth;
Look at the nth column: it counts 1, 2, 3… and starts again at 1 when the customer changes. That restart is what PARTITION BY does.
This is the most common window question in interviews. "The 2 biggest SGD transfers to each target currency":
WITH ranked AS (
SELECT target_currency, id, amount,
ROW_NUMBER() OVER (PARTITION BY target_currency ORDER BY amount DESC) AS rn
FROM transfers
WHERE source_currency = 'SGD'
)
SELECT target_currency, id, amount
FROM ranked
WHERE rn <= 2
ORDER BY target_currency, amount DESC;
SELECT id,
ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM transfers
WHERE source_currency = 'SGD' AND rn <= 2;
WHERE runs before SELECT, so rn doesn't exist yet. Window functions are worked out in SELECT.
WITH r AS ( SELECT id, amount, ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn FROM transfers WHERE source_currency = 'SGD' ) SELECT id, amount FROM r WHERE rn <= 2;
The CTE finishes first, so rn is a normal column you can filter on.
"Each customer's first transfer" is the same pattern with ORDER BY created_at and WHERE rn = 1.
They only differ when there's a tie. Here are the three side by side on a small made-up list where B and C tie:
WITH scores(name, points) AS (
VALUES ('A', 90), ('B', 80), ('C', 80), ('D', 70)
)
SELECT name, points,
ROW_NUMBER() OVER (ORDER BY points DESC) AS row_number,
RANK() OVER (ORDER BY points DESC) AS rank,
DENSE_RANK() OVER (ORDER BY points DESC) AS dense_rank
FROM scores;
| Function | On a tie | Use when |
|---|---|---|
ROW_NUMBER | Gives different numbers anyway (2, 3) | You need exactly N rows |
RANK | Same number, then skips (2, 2, 4) | Like a sports table: "joint 2nd, then 4th" |
DENSE_RANK | Same number, no gap (2, 2, 3) | "Top 3 distinct values", ties included |
If you use ROW_NUMBER and ties are possible, add a tie-break like ORDER BY amount DESC, id so the result is the same every time.
You can rank the result of a GROUP BY. "Rank customers by number of transfers":
SELECT customer_id, COUNT(*) AS n,
RANK() OVER (ORDER BY COUNT(*) DESC) AS rnk
FROM transfers
GROUP BY customer_id
ORDER BY rnk, customer_id
LIMIT 10;
GROUP BY runs first and makes one row per customer. Then the window ranks those rows. Look at the ties: customers 71 and 103 share rank 2, so the next rank is 4.
PARTITION BY = "per group", ORDER BY inside OVER = "in this order".WHERE rn <= N outside.What you'll learn today: how to compare a row with the one before it ("up or down from last month?") and how to keep a running total. Both are everyday ops reporting questions.
LAG(x) means "the value of x on the row before this one". LEAD(x) means the row after.First get monthly counts in a CTE, then put last month's number next to this month's:
WITH monthly AS (
SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n
FROM transfers
GROUP BY month
)
SELECT month, n,
LAG(n) OVER (ORDER BY month) AS prev_n,
n - LAG(n) OVER (ORDER BY month) AS change
FROM monthly
ORDER BY month;
prev_n is NULL, and so is the change. That's correct, not a bug.ORDER BY month inside OVER decides what "before" means. Without it, LAG has no idea which row is previous.For a percentage change, divide by the previous value, using 100.0 so the maths keeps decimals:
WITH monthly AS (
SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n
FROM transfers GROUP BY month
)
SELECT month, n,
ROUND((n - LAG(n) OVER (ORDER BY month)) * 100.0 / LAG(n) OVER (ORDER BY month), 1) AS pct_change
FROM monthly
ORDER BY month;
Add PARTITION BY and LAG looks at the previous row for the same customer. "How many days since this customer's last transfer?":
SELECT customer_id, id, created_at,
ROUND(julianday(created_at) - julianday(LAG(created_at) OVER (PARTITION BY customer_id ORDER BY created_at)), 1) AS days_since_last
FROM transfers
WHERE customer_id <= 2 AND created_at >= '2026-08-01'
ORDER BY customer_id, created_at;
Each customer's first transfer shows NULL, because there's nothing before it for that customer.
A running total adds each row onto everything before it. SUM() with an ORDER BY inside OVER does exactly that. The ORDER BY is what makes the difference:
WITH monthly AS ( SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n FROM transfers GROUP BY month ) SELECT month, n, SUM(n) OVER () AS total FROM monthly ORDER BY month;
No ORDER BY: every row gets the same grand total.
WITH monthly AS ( SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n FROM transfers GROUP BY month ) SELECT month, n, SUM(n) OVER (ORDER BY month) AS running_total FROM monthly ORDER BY month;
With ORDER BY: each row adds up everything up to and including itself.
The first version is handy too: it's the short way to do Day 9's "share of total". n * 100.0 / SUM(n) OVER () gives each row's share without a separate step.
A moving average smooths out bumpy numbers by averaging each row with a few before it. You tell the window how many rows to include with ROWS BETWEEN:
WITH monthly AS (
SELECT substr(created_at, 1, 7) AS month, COUNT(*) AS n
FROM transfers GROUP BY month
)
SELECT month, n,
ROUND(AVG(n) OVER (ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 1) AS avg_3m
FROM monthly
ORDER BY month;
2 PRECEDING AND CURRENT ROW = this row and the 2 before it, so a 3-month average. The first two months average fewer rows, because there aren't 2 earlier months yet.
Add PARTITION BY and the running total restarts for each group. "Each customer's cumulative SGD sent":
SELECT customer_id, created_at, amount,
ROUND(SUM(amount) OVER (PARTITION BY customer_id ORDER BY created_at), 2) AS cumulative
FROM transfers
WHERE source_currency = 'SGD' AND customer_id <= 3 AND created_at >= '2026-07-01'
ORDER BY customer_id, created_at;
LAG(x) OVER (ORDER BY …) gives the previous row's value; the first row gets NULL.PARTITION BY to look back within each customer or currency only.SUM() OVER () = grand total on every row. SUM() OVER (ORDER BY …) = running total.ROWS BETWEEN 2 PRECEDING AND CURRENT ROW = a 3-row moving window.What you'll learn today: the small things that make a query run fine but give the wrong answer. Interviewers love these, because spotting them shows you check your numbers.
Question: "how many transfers do not have the failure reason INSUFFICIENT_FUNDS?" That should be almost all of them, since most transfers never failed. The obvious query misses rows:
SELECT COUNT(*) FROM transfers WHERE failure_reason <> 'INSUFFICIENT_FUNDS';
Successful transfers have a NULL reason. "NULL is not equal to X" is unknown, so they're all dropped.
SELECT COUNT(*) FROM transfers WHERE failure_reason <> 'INSUFFICIENT_FUNDS' OR failure_reason IS NULL;
Now the blanks are counted too. Compare the two numbers.
The same happens with NOT IN. Whenever you filter with <> or NOT IN on a column that can be NULL, ask yourself: "what should happen to the blanks?"
COUNT(column), SUM and AVG all skip NULLs. Usually that's what you want, but know it's happening:
SELECT COUNT(*) AS all_rows,
COUNT(completed_at) AS has_completed_at,
COUNT(failure_reason) AS has_reason
FROM transfers;
Three different numbers from the same table. AVG divides by the number of non-NULL values, so averaging a column with blanks is an average of the known ones only.
COALESCE(a, b) returns a, unless it's NULL, in which case it returns b. Use it to show a label instead of a blank, or 0 instead of NULL after a LEFT JOIN:
SELECT COALESCE(failure_reason, 'none') AS reason, COUNT(*) AS n FROM transfers GROUP BY reason ORDER BY n DESC;
SELECT c.id, c.name, COALESCE(SUM(t.amount), 0) AS sent FROM customers c LEFT JOIN transfers t ON t.customer_id = c.id AND t.source_currency = 'SGD' GROUP BY c.id, c.name ORDER BY sent, c.id;
Customers with no SGD transfers would show NULL without COALESCE. With it they show 0, which is what a reader expects.
When both numbers are whole numbers, SQL throws away the decimals. This is the trap from Day 3 again, because it really is that common:
SELECT 7 / 2 AS result, 3 * 100 / 7 AS pct;
Gives 3 and 42. The decimals are cut off, not rounded.
SELECT 7 / 2.0 AS result, 3 * 100.0 / 7 AS pct;
Gives 3.5 and 42.857… Just one decimal number in the calculation is enough.
Rule of thumb: in any rate or percentage, write 100.0, never 100.
And dividing by zero? SQLite returns NULL; PostgreSQL gives an error. Guard it with NULLIF(x, 0), which turns a 0 into NULL so the division quietly returns NULL instead:
SELECT 10 * 100.0 / NULLIF(0, 0) AS safe_pct;
Our dates are text like '2026-09-30 14:03:00'. A range that ends on '2026-09-30' misses most of that day:
SELECT COUNT(*) FROM transfers WHERE created_at BETWEEN '2026-09-01' AND '2026-09-30';
'2026-09-30 14:03' sorts after '2026-09-30', so the last day is (mostly) left out.
SELECT COUNT(*) FROM transfers WHERE created_at >= '2026-09-01' AND created_at < '2026-10-01';
Includes every moment of September and nothing of October. Use this form every time.
If one row on the left matches several on the right, it appears several times. Summing a left-side column then counts it more than once. The fix is usually to aggregate in a CTE first, then join (Day 8), or to count DISTINCT ids.
<> or NOT IN on a column with blanks?100.0? Could anything be divided by zero?>= and <?<> and NOT IN silently drop NULL rows. Add OR … IS NULL when you need them.COALESCE(x, 0) turns blanks into a default.100.0 in rates; guard division with NULLIF(x, 0).>= start AND < day after end.Four questions in the style of a Wise payments operations SQL test. Treat it like the real thing: set the timer, don't open hints until you've tried, and write a one-line takeaway for each answer, the way you'd explain it to a stakeholder.
The checker gives the same feedback as before, but try to solve each one without the hint first. Every try still counts toward your Weak spots, so the test also shows you what to revise on Day 14.
Four more interview-style questions: new versus returning customers, compliance holds by country, sign-up cohorts, and top transfers per currency. These lean on CTEs, LEFT JOINs and window functions together. Same rules as yesterday: timer on, hints last.
-- step 1: …). It costs a minute and saves ten.That's the full course. From here, the best practice is the Weak spots mode: it keeps bringing back whatever you find hardest, across all 14 days, until it sticks.