You do not need to memorise hundreds of SQL functions to work as a data analyst. Most day-to-day questions, and most interview tasks, are combinations of a small set of patterns. If you can write the 15 queries below without looking anything up, and explain why each one works, you have a solid base.
The examples use the same tables as the free SQL Practice Lab: an online shop (shop_customers, shop_orders, shop_order_items, shop_products), a bank (bank_accounts, bank_transactions), a telecom company (tel_plans, tel_subscribers, tel_monthly_usage, tel_bills) and an HR system (hr_employees, hr_departments). The queries are written in standard SQL and were checked on the lab's SQLite database; notes mark the few places where MySQL differs.
The basics: filter, sort, search
1. Filter and sort
Which active chequing accounts have a balance under $500, lowest first?
SELECT account_id, customer_id, balance
FROM bank_accounts
WHERE account_type = 'Chequing' AND status = 'Active' AND balance < 500
ORDER BY balance ASC;
The habit to build: read the question and translate each condition into the WHERE clause before you write anything else.
2. Search text with LIKE
Which products are wireless, Bluetooth or "smart" devices?
SELECT product_name, brand, unit_price
FROM shop_products
WHERE product_name LIKE '%Wireless%'
OR product_name LIKE '%Bluetooth%'
OR product_name LIKE '%Smart%'
ORDER BY unit_price DESC;
% matches any number of characters. Watch out: whether LIKE is case-sensitive depends on the database and its settings.
3. Handle NULLs correctly
How many transactions have no merchant category, by transaction type?
SELECT txn_type, COUNT(*) AS transactions
FROM bank_transactions
WHERE merchant_category IS NULL
GROUP BY txn_type
ORDER BY transactions DESC;
= NULL never matches anything; always use IS NULL or IS NOT NULL. This is one of the most common interview traps.
Aggregation: summarise the data
4. GROUP BY with HAVING
Which cities have at least 20 shop customers?
SELECT city, COUNT(*) AS customers
FROM shop_customers
GROUP BY city
HAVING COUNT(*) >= 20
ORDER BY customers DESC;
WHERE filters rows before grouping; HAVING filters groups after. Be ready to explain the difference.
5. COUNT vs COUNT(DISTINCT)
For each order status, how many orders and how many different customers?
SELECT status,
COUNT(*) AS orders,
COUNT(DISTINCT customer_id) AS customers
FROM shop_orders
GROUP BY status;
Mixing these up is a classic mistake in reports: "number of orders" and "number of customers who ordered" are different metrics.
Joins: combine tables
6. INNER JOIN
Show the most recent shipped orders (up to 20) with the customer's name and loyalty tier.
SELECT o.order_id, o.order_date, c.first_name, c.last_name, c.loyalty_tier
FROM shop_orders AS o
JOIN shop_customers AS c ON c.customer_id = o.customer_id
WHERE o.status = 'Shipped'
ORDER BY o.order_date DESC
LIMIT 20;
Use short table aliases (o, c) and always qualify column names once more than one table is involved.
7. LEFT JOIN to find what's missing
Which customers signed up but have never placed an order?
SELECT c.customer_id, c.first_name, c.last_name, c.signup_date
FROM shop_customers AS c
LEFT JOIN shop_orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
This "anti-join" pattern answers a whole family of questions: products never sold, employees without a manager record, accounts with no transactions. NOT EXISTS is an equally good alternative.
8. Self-join
List current employees in Data & Analytics with their manager's name.
SELECT e.first_name || ' ' || e.last_name AS employee,
e.job_title,
m.first_name || ' ' || m.last_name AS manager
FROM hr_employees AS e
LEFT JOIN hr_employees AS m ON m.employee_id = e.manager_id
JOIN hr_departments AS d ON d.department_id = e.department_id
WHERE d.department_name = 'Data & Analytics'
AND e.termination_date IS NULL
ORDER BY manager, employee;
The same table appears twice with different aliases. MySQL note: use CONCAT(e.first_name, ' ', e.last_name) instead of ||.
Logic inside queries
9. CASE to create categories
Group delivered orders into delivery-speed bands.
SELECT CASE
WHEN delivery_days <= 2 THEN 'Fast (1-2 days)'
WHEN delivery_days <= 5 THEN 'Standard (3-5 days)'
ELSE 'Slow (6+ days)'
END AS delivery_speed,
COUNT(*) AS orders
FROM shop_orders
WHERE status = 'Delivered'
GROUP BY delivery_speed
ORDER BY MIN(delivery_days);
CASE conditions are checked in order, so the second line only sees orders that were not already "Fast".
10. Conditional aggregation
For prepaid and postpaid plans, how many subscribers are active and how many have churned?
SELECT p.plan_type,
SUM(CASE WHEN s.status = 'Active' THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN s.status = 'Churned' THEN 1 ELSE 0 END) AS churned,
COUNT(*) AS total
FROM tel_subscribers AS s
JOIN tel_plans AS p ON p.plan_id = s.plan_id
GROUP BY p.plan_type;
This turns rows into columns, which is exactly what most summary tables and dashboards need.
11. Working with dates
For each bill month, how many bills were paid late or not at all?
SELECT bill_month,
COUNT(*) AS bills,
SUM(CASE WHEN paid_date > due_date OR paid_date IS NULL THEN 1 ELSE 0 END) AS late_or_unpaid
FROM tel_bills
GROUP BY bill_month
ORDER BY bill_month;
Comparing dates is straightforward; extracting parts of dates is where databases differ (strftime in SQLite, DATE_FORMAT or YEAR()/MONTH() in MySQL). Know the version you will be tested on.
Subqueries and CTEs
12. Subquery in WHERE
Which products cost more than the average product?
SELECT product_name, category, unit_price
FROM shop_products
WHERE unit_price > (SELECT AVG(unit_price) FROM shop_products)
ORDER BY unit_price DESC;
You cannot write WHERE unit_price > AVG(unit_price) directly; the aggregate has to be calculated first, in a subquery.
13. CTE for a top-N list
Who are the top 5 customers by revenue, excluding cancelled orders?
WITH customer_revenue AS (
SELECT o.customer_id,
SUM(i.quantity * i.unit_price) AS revenue
FROM shop_orders AS o
JOIN shop_order_items AS i ON i.order_id = o.order_id
WHERE o.status <> 'Cancelled'
GROUP BY o.customer_id
)
SELECT c.first_name, c.last_name, ROUND(r.revenue, 2) AS revenue
FROM customer_revenue AS r
JOIN shop_customers AS c ON c.customer_id = r.customer_id
ORDER BY r.revenue DESC
LIMIT 5;
A WITH block (common table expression) names an intermediate result so the final query stays readable. Interviewers like CTEs because they show you can break a problem into steps.
Window functions
Window functions calculate across related rows without collapsing them into one row per group. SQLite added them in version 3.25, and MySQL supports them in version 8.0.
14. ROW_NUMBER to pick one row per group
What was each customer's first order?
WITH ranked AS (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date, order_id) AS rn
FROM shop_orders
)
SELECT customer_id, order_id AS first_order_id, order_date AS first_order_date
FROM ranked
WHERE rn = 1
ORDER BY customer_id;
The same pattern gives "latest salary per employee", "most recent login per user" and similar questions. Know the difference between ROW_NUMBER, RANK and DENSE_RANK when there are ties.
15. LAG for change over time
How did one subscriber's data use change from month to month?
SELECT subscriber_id, usage_month, data_gb,
LAG(data_gb) OVER (PARTITION BY subscriber_id ORDER BY usage_month) AS previous_gb,
ROUND(data_gb - LAG(data_gb) OVER (PARTITION BY subscriber_id ORDER BY usage_month), 1) AS change_gb
FROM tel_monthly_usage
WHERE subscriber_id = 10001
ORDER BY usage_month;
LAG looks at the previous row and LEAD at the next one. The first month has no previous value, so it returns NULL; say so if asked.
How to practise these
- Write each query from the question alone, then compare with the example. Typing it yourself is what builds the skill.
- Check your result makes sense. Count rows, spot-check a few values and ask whether the number is plausible. Analysts are trusted for correct numbers, not clever syntax.
- Explain it out loud as if to a manager: what question it answers and what the result means.
- Change one thing at a time: a different filter, a different grouping, a different table. That is how interview variations work too.
The SQL Practice Lab is free with an account and runs in your browser on these tables, with tasks from beginner to advanced that it checks for you. For interview preparation, see the free Data Analytics interview questions with model answers.
Sources
- SQLite 3.25 adds window functions and improves ALTER TABLE, Xojo blog
- Window Functions, MySQL 8.0 Reference Manual