We wrote 34 SQL interview questions for data analyst, analytics engineer and data scientist roles and, on 3 December 2026, ran every answer in DuckDB 2.0.1 and PostgreSQL 16.15, with a script comparing the two engines' rows. Twenty-three use an invented table of 4,734 sales orders, the sample every new Fastero account starts with; the classics use three tiny invented tables printed in full. We also timed three answers to one question on 1,000 to 1,000,000 rows.
The short answer: the 34 questions here run from COUNT and HAVING through window functions, self-joins, NULL traps and recursive CTEs to gaps and islands and cohorts, each with SQL that ran, its real output and the idea it tests. Every answer runs unchanged in both DuckDB 2.0.1 and PostgreSQL 16, and 33 of 34 returned identical rows. The traps worth learning: NOT IN returned 0 rows where NOT EXISTS returned 5, LIMIT 1 OFFSET 1 returned the top salary when two people tie, and on 40,000 rows a correlated subquery took 171 seconds in PostgreSQL where a window function took 27 ms. DuckDB's browser shell and PostgreSQL in Docker are free places to practise. Checked 3 December 2026.
Fastero
Connect your database. Ask questions. Get dashboards.
Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.
Try free →Where to practise SQL interview questions free
Five free places to run the answers, read or measured on 3 December 2026:
| Where | Engine | Account | Limits | These answers |
|---|---|---|---|---|
| DuckDB in Python or its command line | DuckDB 2.0.1 | None | Your computer's memory | All 34 ran as printed |
| DuckDB shell in the browser | DuckDB-Wasm | None | WebAssembly caps memory at 4 GB | Same dialect; not run there by us |
| PostgreSQL in Docker | PostgreSQL 16.15 | None | The postgres:16-alpine image used 420 MB of disk | All 34 ran as printed |
| db<>fiddle | Postgres 8.4 to 19, DuckDB 1.4 and 2.0, MySQL, SQL Server, Oracle and more | None; it sets no cookies | Not published | Paste the table setup first |
| Fastero Free plan | DuckDB SQL, plus your own database connections | Free, no card | 500 MB storage, 100 MB a file | Questions 1 to 23 on the built-in sales table |
More online editors: online SQL compilers compared. Syntax on one page: the SQL cheat sheet.
The sample sales table
sales is invented: one row per order, with order_id, order_date, region (4 values), channel (3), segment (3), category (4), product (13), quantity, unit_price and revenue, from 1 November 2024 to 31 October 2026. It isn't a public download but comes with every new Fastero account; elsewhere, point questions 1 to 23 at any orders table with a date, a category and an amount. Loading the file:
-- DuckDB
CREATE TABLE sales AS SELECT * FROM read_csv('sample-sales.csv');
SELECT COUNT(*) AS orders, ROUND(SUM(revenue), 2) AS revenue FROM sales;
-- PostgreSQL 16, in psql
CREATE TABLE sales (order_id integer, order_date date, region text, channel text,
segment text, category text, product text, quantity integer,
unit_price numeric(10,2), revenue numeric(12,2));
\copy sales FROM 'sample-sales.csv' WITH (FORMAT csv, HEADER true)┌────────┬────────────┐
│ orders │ revenue │
│ int64 │ double │
├────────┼────────────┤
│ 4734 │ 1473700.87 │
└────────┴────────────┘
COPY 4734DuckDB reads revenue as DOUBLE; for PostgreSQL we declared NUMERIC, as for money. Outputs below are DuckDB's (its Python package), printed by our script; PostgreSQL returned the same rows unless noted.
Easy SQL interview questions
1. How many orders are there, and what dates do they cover? Tests: aggregates without GROUP BY return one row for the whole table.
SELECT COUNT(*) AS orders, MIN(order_date) AS first_day, MAX(order_date) AS last_day
FROM sales;orders | first_day | last_day
-------+------------+-----------
4734 | 2024-11-01 | 2026-10-312. What is total revenue by region, highest first? Tests: GROUP BY with SUM, sorted by an alias.
SELECT region, ROUND(SUM(revenue), 2) AS total_revenue
FROM sales
GROUP BY region
ORDER BY total_revenue DESC;region | total_revenue
-------+--------------
North | 417482.48
West | 413523.32
East | 336183.61
South | 306511.463. Which products have more than 500 orders? Tests: WHERE filters rows before grouping; HAVING filters groups after it.
SELECT product, COUNT(*) AS orders
FROM sales
GROUP BY product
HAVING COUNT(*) > 500
ORDER BY orders DESC;product | orders
-------------+-------
Cable kit | 565
Label rolls | 548
Notebook set | 5154. What do COUNT(*), COUNT(column) and COUNT(DISTINCT column) each count? Tests: rows, non-NULL values and distinct values are three different numbers.
SELECT COUNT(*) AS all_rows,
COUNT(product) AS non_null_products,
COUNT(DISTINCT product) AS products,
COUNT(DISTINCT order_date) AS order_days
FROM sales;all_rows | non_null_products | products | order_days
---------+-------------------+----------+-----------
4734 | 4734 | 13 | 729The range has 730 days and 729 have orders; question 17 finds the missing one.
5. What are the five largest orders? Tests: ORDER BY with LIMIT, plus a tie-breaker.
SELECT order_id, order_date, product, revenue
FROM sales
ORDER BY revenue DESC, order_id
LIMIT 5;order_id | order_date | product | revenue
---------+------------+---------------+--------
11957 | 2025-10-04 | Standing desk | 1811.0
11012 | 2025-05-14 | Standing desk | 1809.48
14121 | 2026-08-09 | Standing desk | 1808.6
13830 | 2026-07-06 | Standing desk | 1806.56
12703 | 2026-02-10 | Standing desk | 1806.48Two orders are worth exactly 1,806.48, so without order_id in the sort, which one is fifth is undefined. PostgreSQL's docs warn that a LIMIT without a unique order returns "an unpredictable subset of the query's rows."
6. What is revenue by month? Tests: bucketing dates.
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
ROUND(SUM(revenue), 2) AS revenue
FROM sales
GROUP BY month
ORDER BY month;month | revenue
-----------+---------
2024-11-01 | 45671.13
2024-12-01 | 40801.7
2025-01-01 | 39506.29
...
2026-10-01 | 57517.58
(24 rows)On a date, date_trunc returns a TIMESTAMP in DuckDB and a timestamp with time zone in PostgreSQL, hence the cast.
7. Label each order small, medium or large, and count each band. Tests: CASE takes the first branch that matches, so the order of the WHENs matters.
SELECT CASE WHEN revenue < 100 THEN 'small'
WHEN revenue < 500 THEN 'medium'
ELSE 'large' END AS size_band,
COUNT(*) AS orders,
ROUND(SUM(revenue), 2) AS revenue
FROM sales
GROUP BY size_band
ORDER BY MIN(revenue);size_band | orders | revenue
----------+--------+----------
small | 1179 | 73504.76
medium | 2730 | 632908.06
large | 825 | 767288.058. Why does WHERE size_band = 'large' fail? Tests: the logical order of a query: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY. The alias doesn't exist yet when WHERE runs.
SELECT order_id, revenue,
CASE WHEN revenue >= 500 THEN 'large' ELSE 'other' END AS size_band
FROM sales
WHERE size_band = 'large';ERROR: column "size_band" does not exist
LINE 4: WHERE size_band = 'large';
^That is PostgreSQL 16. DuckDB 2.0.1 ran it, because its friendly SQL allows "Column aliases in WHERE, GROUP BY, and HAVING." The portable form filters outside a subquery:
SELECT * FROM (
SELECT order_id, revenue,
CASE WHEN revenue >= 500 THEN 'large' ELSE 'other' END AS size_band
FROM sales
) t
WHERE size_band = 'large'
ORDER BY revenue DESC
LIMIT 3;order_id | revenue | size_band
---------+---------+----------
11957 | 1811.0 | large
11012 | 1809.48 | large
14121 | 1808.6 | large9. Show Online, Partner and Sales team revenue side by side for each region. Tests: conditional aggregation, the usual way to pivot.
SELECT region,
ROUND(SUM(revenue) FILTER (WHERE channel = 'Online'), 2) AS online,
ROUND(SUM(revenue) FILTER (WHERE channel = 'Partner'), 2) AS partner,
ROUND(SUM(CASE WHEN channel = 'Sales team' THEN revenue END), 2) AS sales_team
FROM sales
GROUP BY region
ORDER BY region;region | online | partner | sales_team
-------+-----------+----------+-----------
East | 151487.88 | 64769.19 | 119926.54
North | 213296.95 | 88855.29 | 115330.24
South | 142073.15 | 67118.34 | 97319.97
West | 201271.42 | 83591.83 | 128660.07Both engines accept FILTER; SUM(CASE WHEN ...) works almost anywhere.
10. How much revenue came in during the last 30 days? Tests: anchoring the 30 days to the data's last date, with a scalar subquery.
SELECT COUNT(*) AS orders, ROUND(SUM(revenue), 2) AS revenue
FROM sales
WHERE order_date > (SELECT MAX(order_date) FROM sales) - INTERVAL '30 days';orders | revenue
-------+--------
197 | 56189.0The same filter on CURRENT_DATE found 0 orders, because the sample ends on 31 October 2026.
Intermediate SQL interview questions
Window functions do most of the work from here; more patterns in window functions for business analytics.
11. What are the top 3 products by revenue in each region? Tests: ROW_NUMBER() partitioned by group, filtered in an outer query.
SELECT region, product, revenue
FROM (
SELECT region, product, ROUND(SUM(revenue), 2) AS revenue,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY SUM(revenue) DESC) AS rn
FROM sales
GROUP BY region, product
) t
WHERE rn <= 3
ORDER BY region, revenue DESC;region | product | revenue
-------+---------------+----------
East | Standing desk | 76548.25
East | Office chair | 54286.35
East | Team plan | 44459.13
North | Standing desk | 112052.44
North | Team plan | 59077.48
North | Office chair | 49135.3
...
(12 rows)DuckDB can skip the subquery with QUALIFY ROW_NUMBER() OVER (...) <= 3, which returned the same 12 rows; PostgreSQL 16 answered syntax error at or near "QUALIFY". Use RANK() if tied products should all make the list.
12. What is month-over-month revenue growth? Tests: LAG() reads the previous row.
WITH monthly AS (
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
SUM(revenue) AS revenue
FROM sales
GROUP BY 1
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(100 * (revenue / LAG(revenue) OVER (ORDER BY month) - 1), 1) AS mom_pct
FROM monthly
ORDER BY month;month | revenue | mom_pct
-----------+----------+--------
2024-11-01 | 45671.13 | NULL
2024-12-01 | 40801.7 | -10.7
...
2026-09-01 | 64819.38 | -25.7
2026-10-01 | 57517.58 | -11.3
(24 rows)The first month has nothing before it, so LAG returns NULL. A zero-revenue month would make PostgreSQL stop with division by zero and DuckDB return inf, so wrap the divisor in NULLIF(..., 0). Missing months and year-over-year: month-over-month metrics in SQL.
13. Show a running total of revenue, and one that restarts each year. Tests: SUM() OVER (ORDER BY ...), and PARTITION BY to reset it.
WITH monthly AS (
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
SUM(revenue) AS revenue
FROM sales
GROUP BY 1
)
SELECT month,
ROUND(revenue, 2) AS revenue,
ROUND(SUM(revenue) OVER (ORDER BY month), 2) AS running_total,
ROUND(SUM(revenue) OVER (PARTITION BY EXTRACT(YEAR FROM month)
ORDER BY month), 2) AS year_to_date
FROM monthly
ORDER BY month;month | revenue | running_total | year_to_date
-----------+----------+---------------+-------------
...
2025-12-01 | 62095.0 | 781649.81 | 695176.98
2026-01-01 | 56809.65 | 838459.46 | 56809.65
2026-02-01 | 52737.99 | 891197.45 | 109547.64
...
2026-10-01 | 57517.58 | 1473700.87 | 692051.06
(24 rows)With ORDER BY and no frame clause, the window runs from the first row through the current one and any rows tied with it.
14. What share of total revenue does each category bring? Tests: an aggregate inside a window; an empty OVER () spans the whole result.
SELECT category,
ROUND(SUM(revenue), 2) AS revenue,
ROUND(100 * SUM(revenue) / SUM(SUM(revenue)) OVER (), 1) AS pct_of_total
FROM sales
GROUP BY category
ORDER BY revenue DESC;category | revenue | pct_of_total
---------+-----------+-------------
Hardware | 704343.33 | 47.8
Software | 374298.41 | 25.4
Supplies | 198371.68 | 13.5
Services | 196687.45 | 13.315. What was the first order in each segment? Tests: one row per group, with a tie-breaker.
SELECT segment, order_id, order_date, product
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY segment
ORDER BY order_date, order_id) AS rn
FROM sales
) t
WHERE rn = 1
ORDER BY segment;segment | order_id | order_date | product
---------------+----------+------------+-------------
Enterprise | 10002 | 2024-11-01 | Training day
Mid-market | 10003 | 2024-11-01 | Starter plan
Small business | 10001 | 2024-11-01 | Team planSix orders share the first day, so order_id decides. DISTINCT ON (segment) with the same ORDER BY returned the same rows in both engines.
16. Find possible duplicate orders. Tests: choosing the key that defines a duplicate, then grouping on it.
SELECT order_date, region, product, quantity, COUNT(*) AS copies,
STRING_AGG(CAST(order_id AS VARCHAR), ', ' ORDER BY order_id) AS order_ids
FROM sales
GROUP BY order_date, region, product, quantity
HAVING COUNT(*) > 1
ORDER BY copies DESC, order_date
LIMIT 4;order_date | region | product | quantity | copies | order_ids
-----------+--------+---------------+----------+--------+--------------------
2026-07-28 | South | Office chair | 2 | 3 | 14026, 14032, 14033
2024-11-12 | North | Cable kit | 9 | 2 | 10056, 10060
2024-12-03 | West | Label rolls | 1 | 2 | 10162, 10163
2024-12-12 | North | Setup session | 1 | 2 | 10210, 10211In all, 81 groups (163 rows) share a date, region, product and quantity, yet grouping on every column except order_id finds none: they differ in channel, segment or price. Say which key you used. Clean-up patterns: finding duplicate records.
17. Which dates have no orders? Tests: generating a calendar and anti-joining it to the data.
SELECT CAST(d AS DATE) AS missing_day
FROM generate_series(DATE '2024-11-01', DATE '2026-10-31', INTERVAL '1 day') AS t(d)
WHERE NOT EXISTS (
SELECT 1 FROM sales s WHERE s.order_date = CAST(t.d AS DATE)
);missing_day
-----------
2026-03-0718. What is the median order value, overall and by category? Tests: median against mean on skewed data, and ROLLUP for a total row.
SELECT COALESCE(category, 'All') AS category,
ROUND(AVG(revenue), 2) AS mean,
ROUND(CAST(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY revenue) AS NUMERIC), 2)
AS median
FROM sales
GROUP BY ROLLUP (category)
ORDER BY GROUPING(category), category;category | mean | median
---------+--------+-------
Hardware | 515.62 | 280.85
Services | 485.65 | 345.60
Software | 280.37 | 223.84
Supplies | 121.85 | 107.28
All | 311.3 | 192.83A few big orders pull the mean ($311.30) well above the median ($192.83). PostgreSQL has no MEDIAN(), which DuckDB has, and its PERCENTILE_CONT returns a double that ROUND(x, 2) rejects, hence the cast. The cast helps DuckDB too: rounding the double 192.825 gave 192.82.
19. Calculate a 7-day moving average of daily revenue. Tests: ROWS counts rows and RANGE counts days, and they differ when a day is missing.
WITH daily AS (
SELECT order_date, SUM(revenue) AS revenue
FROM sales
GROUP BY order_date
), smoothed AS (
SELECT order_date, revenue,
AVG(revenue) OVER (ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7_rows,
AVG(revenue) OVER (ORDER BY order_date
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW)
AS avg_7_days
FROM daily
)
SELECT order_date, ROUND(revenue, 2) AS revenue,
ROUND(avg_7_rows, 2) AS avg_7_rows, ROUND(avg_7_days, 2) AS avg_7_days
FROM smoothed
WHERE order_date BETWEEN DATE '2026-03-05' AND DATE '2026-03-15'
ORDER BY order_date;order_date | revenue | avg_7_rows | avg_7_days
-----------+---------+------------+-----------
2026-03-05 | 762.53 | 2120.36 | 2120.36
2026-03-06 | 2859.68 | 1989.08 | 1989.08
2026-03-08 | 824.7 | 1761.8 | 1902.55
2026-03-09 | 1466.67 | 1840.28 | 1548.46
2026-03-10 | 2558.29 | 1692.72 | 1952.53
2026-03-11 | 998.79 | 1816.29 | 1578.44
2026-03-12 | 1085.87 | 1508.08 | 1632.33
2026-03-13 | 978.73 | 1538.96 | 1318.84
2026-03-14 | 2045.09 | 1422.59 | 1422.59
2026-03-15 | 529.32 | 1380.39 | 1380.39With 7 March missing, the ROWS window spans eight calendar days from 8 to 13 March, and the RANGE window averages six days; to count the empty day as zero, join to a calendar first. Filter after the window: a WHERE in the same query removes rows before averaging. PostgreSQL printed 1952.54 for 10 March where DuckDB printed 1952.53 (NUMERIC against DOUBLE), the one difference between the engines' answers here.
20. Compare each month with the same month a year earlier. Tests: a self-join on a shifted date, which stays right when a month is missing.
WITH monthly AS (
SELECT CAST(date_trunc('month', order_date) AS DATE) AS month,
SUM(revenue) AS revenue
FROM sales
GROUP BY 1
)
SELECT cur.month,
ROUND(cur.revenue, 2) AS revenue,
ROUND(prev.revenue, 2) AS year_before,
ROUND(100 * (cur.revenue / prev.revenue - 1), 1) AS yoy_pct
FROM monthly cur
JOIN monthly prev ON prev.month = cur.month - INTERVAL '1 year'
ORDER BY cur.month;month | revenue | year_before | yoy_pct
-----------+----------+-------------+--------
2025-11-01 | 62583.78 | 45671.13 | 37.0
2025-12-01 | 62095.0 | 40801.7 | 52.2
...
2026-10-01 | 57517.58 | 53121.51 | 8.3
(12 rows)21. Which products grew revenue in 2026? Tests: comparing like-for-like periods.
SELECT COUNT(*) FILTER (WHERE y2026 > y2025) AS grew_vs_full_2025,
COUNT(*) FILTER (WHERE y2026 > jan_oct_2025) AS grew_like_for_like,
COUNT(*) AS products
FROM (
SELECT product,
SUM(revenue) FILTER (WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31')
AS y2025,
SUM(revenue) FILTER (WHERE order_date BETWEEN '2026-01-01' AND '2026-12-31')
AS y2026,
SUM(revenue) FILTER (WHERE order_date BETWEEN '2025-01-01' AND '2025-10-31')
AS jan_oct_2025
FROM sales
GROUP BY product
) t;grew_vs_full_2025 | grew_like_for_like | products
------------------+--------------------+---------
5 | 11 | 13The data stops at October 2026. Against all twelve months of 2025, 5 of 13 products grew; against January to October 2025, 11 did. Only Reporting add-on and Training day fell.
22. Which products sold in every region in every month? Tests: relational division, where you count the combinations, not each part.
SELECT product, COUNT(*) AS region_months
FROM (
SELECT DISTINCT product, region,
CAST(date_trunc('month', order_date) AS DATE) AS month
FROM sales
) t
GROUP BY product
HAVING COUNT(*) = 4 * 24
ORDER BY product;product | region_months
----------+--------------
Cable kit | 96Checking the parts separately, with COUNT(DISTINCT region) = 4 and 24 distinct months, returned 12 products. Only Cable kit sold in all 96 region-months.
23. Which orders are above their region's average? Tests: comparing each row with its group, by a window function or a correlated subquery.
-- Window function
SELECT COUNT(*) AS above_region_avg
FROM (
SELECT revenue, AVG(revenue) OVER (PARTITION BY region) AS region_avg
FROM sales
) t
WHERE revenue > region_avg;
-- Correlated subquery
SELECT COUNT(*) AS above_region_avg
FROM sales s
WHERE revenue > (SELECT AVG(revenue) FROM sales s2 WHERE s2.region = s.region);above_region_avg
----------------
1439Both return 1,439. The difference is speed.
Connect any database. Ask in plain English.
Start free →Window function vs correlated subquery: which is faster?
We timed question 23's two answers, plus a join to a per-region GROUP BY, on 1,000 to 1,000,000 rows: the sample repeated with shifted ids and slightly scaled revenue, no indexes, the same rows in both engines. All three answers agreed at every size.

Median of 3 to 7 runs per point, measured 3 December 2026 on a shared Windows 11 laptop with DuckDB 2.0.1 and PostgreSQL 16.15. We stopped PostgreSQL at 100,000 rows to save disk.
| Answer | PostgreSQL, 5,000 rows | PostgreSQL, 40,000 rows | DuckDB, 1,000,000 rows |
|---|---|---|---|
| Window function | 19 ms | 27 ms | 25 ms |
| Join to a per-region aggregate | 15 ms | 23 ms | 37 ms |
| Correlated subquery | 5.6 s | 171 s | 26 ms |
PostgreSQL ran the subquery once per outer row, so its time grew roughly with the square of the table: 14 seconds at 10,000 rows, 62 at 20,000, 171 at 40,000. DuckDB's blog explains its flat line: "In DuckDB, subqueries are always decorrelated," rewritten as joins before they run. So the correlated subquery is slow in one engine and harmless in the other; in an interview, write the window function and say why.
Advanced SQL interview questions
The classics need employees, departments and logins: three invented tables, small enough to check by eye, created by the same SQL in both engines. For volume, the MySQL employees database has 2.8 million salary rows: see sample databases.
CREATE TABLE departments (id INTEGER, name VARCHAR);
INSERT INTO departments VALUES (1, 'Executive'), (2, 'Engineering'), (3, 'Sales'), (4, 'Legal');
CREATE TABLE employees (id INTEGER, name VARCHAR, department_id INTEGER,
manager_id INTEGER, salary INTEGER);
INSERT INTO employees VALUES
(1, 'Avery', 1, NULL, 180000),
(2, 'Blake', 2, 1, 150000),
(3, 'Casey', 2, 2, 150000),
(4, 'Drew', 2, 2, 180000),
(5, 'Emery', 3, 1, 120000),
(6, 'Finley', 3, 5, 125000),
(7, 'Gray', 3, 5, 95000),
(8, 'Harper', 2, 3, 110000),
(9, 'Jules', 3, 5, 125000);
CREATE TABLE logins (user_id INTEGER, login_date DATE);
INSERT INTO logins VALUES
(1, '2026-01-05'), (1, '2026-01-06'), (1, '2026-01-07'), (1, '2026-01-09'),
(1, '2026-02-02'), (1, '2026-03-01'),
(2, '2026-01-20'), (2, '2026-01-21'), (2, '2026-03-03'),
(3, '2026-02-10'), (3, '2026-02-11'), (3, '2026-02-12'), (3, '2026-02-13'),
(3, '2026-03-15'),
(4, '2026-02-25'),
(5, '2026-03-02'), (5, '2026-03-03');24. What is the second-highest salary? Tests: ties, and returning NULL when there is no second value.
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);second_highest
--------------
150000The shortcut ORDER BY salary DESC LIMIT 1 OFFSET 1 returned 180000, because Avery and Drew tie at the top; SELECT DISTINCT salary with the same OFFSET returned 150000. With no second salary, the MAX form returns a NULL and the OFFSET form no rows.
25. What is the third-highest salary (the Nth)? Tests: DENSE_RANK() numbers distinct values.
SELECT DISTINCT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dr
FROM employees
) t
WHERE dr = 3;salary
------
12500026. What is the difference between ROW_NUMBER, RANK and DENSE_RANK? Tests: how each numbers ties.
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC, name) AS row_num,
RANK() OVER (ORDER BY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rnk
FROM employees
ORDER BY salary DESC, name;name | salary | row_num | rnk | dense_rnk
-------+--------+---------+-----+----------
Avery | 180000 | 1 | 1 | 1
Drew | 180000 | 2 | 1 | 1
Blake | 150000 | 3 | 3 | 2
Casey | 150000 | 4 | 3 | 2
Finley | 125000 | 5 | 5 | 3
Jules | 125000 | 6 | 5 | 3
Emery | 120000 | 7 | 7 | 4
Harper | 110000 | 8 | 8 | 5
Gray | 95000 | 9 | 9 | 6ROW_NUMBER never repeats, RANK repeats then skips (1, 1, 3), and DENSE_RANK repeats without skipping (1, 1, 2). So RANK() <= 3 can return more than three rows, never fewer when three exist: here, four.
27. Which employees earn more than their manager? Tests: a self-join, one table under two aliases.
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary
ORDER BY e.name;employee | salary | manager | manager_salary
---------+--------+---------+---------------
Drew | 180000 | Blake | 150000
Finley | 125000 | Emery | 120000
Jules | 125000 | Emery | 120000Casey earns exactly what Blake does, so > leaves her out.
28. Who is the highest-paid person in each department, ties included? Tests: RANK() keeps ties where ROW_NUMBER() drops one.
SELECT d.name AS department, e.name, e.salary
FROM (
SELECT *, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rnk
FROM employees
) e
JOIN departments d ON d.id = e.department_id
WHERE e.rnk = 1
ORDER BY department, e.name;department | name | salary
------------+--------+-------
Engineering | Drew | 180000
Executive | Avery | 180000
Sales | Finley | 125000
Sales | Jules | 125000With ROW_NUMBER(), Sales kept only one of the tied pair, and nothing in the query says which: DuckDB kept Finley, PostgreSQL Jules. A correlated subquery matching each department's MAX(salary) returned these four rows too.
29. Which employees manage nobody? Tests: NOT IN against a column that holds a NULL.
-- Returns no rows
SELECT name FROM employees
WHERE id NOT IN (SELECT manager_id FROM employees)
ORDER BY name;
-- Returns the five
SELECT name FROM employees e
WHERE NOT EXISTS (SELECT 1 FROM employees r WHERE r.manager_id = e.id)
ORDER BY name;name
----
(0 rows)
name
------
Drew
Finley
Gray
Harper
Jules
(5 rows)Avery has no manager, so the subquery's list includes a NULL. PostgreSQL's docs give the rule: when no value is equal "and at least one right-hand row yields null, the result of the NOT IN construct will be null, not true." Both engines returned 0 rows. NOT EXISTS is safe; so is adding WHERE manager_id IS NOT NULL inside the NOT IN.
30. Which departments have no employees? Tests: the LEFT JOIN ... IS NULL anti-join.
SELECT d.name
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
WHERE e.id IS NULL;name
-----
Legal31. Count employees earning over $130,000 in every department, including those with none. Tests: in a LEFT JOIN, a condition on the right-hand table belongs in ON, not WHERE.
SELECT d.name, COUNT(e.id) AS high_earners, COUNT(*) AS count_star
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id AND e.salary > 130000
GROUP BY d.name
ORDER BY d.name;name | high_earners | count_star
------------+--------------+-----------
Engineering | 3 | 3
Executive | 1 | 1
Legal | 0 | 1
Sales | 0 | 1With the salary test in WHERE instead, Legal and Sales vanished: their NULL salaries fail it, which turns the outer join into an inner one. And count a right-hand column: COUNT(*) counted 1 for Legal, the NULL row itself.
32. Show each employee's level and chain of managers. Tests: a recursive CTE, an anchor row plus a step that joins back to the CTE.
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS depth, CAST(name AS TEXT) AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.depth + 1, c.path || ' > ' || e.name
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT name, depth, path FROM chain ORDER BY depth, name;name | depth | path
-------+-------+-------------------------------
Avery | 0 | Avery
Blake | 1 | Avery > Blake
Emery | 1 | Avery > Emery
Casey | 2 | Avery > Blake > Casey
Drew | 2 | Avery > Blake > Drew
Finley | 2 | Avery > Emery > Finley
Gray | 2 | Avery > Emery > Gray
Jules | 2 | Avery > Emery > Jules
Harper | 3 | Avery > Blake > Casey > Harper33. What is each user's longest streak of consecutive login days? Tests: gaps and islands. A date minus its row number stays constant along a run of consecutive days.
WITH numbered AS (
SELECT user_id, login_date,
login_date - CAST(ROW_NUMBER() OVER (PARTITION BY user_id
ORDER BY login_date) AS INTEGER) AS island
FROM logins
), islands AS (
SELECT user_id, MIN(login_date) AS first_day, MAX(login_date) AS last_day,
COUNT(*) AS days
FROM numbered
GROUP BY user_id, island
)
SELECT user_id, first_day, last_day, days
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id
ORDER BY days DESC, first_day) AS rn
FROM islands
) t
WHERE rn = 1
ORDER BY user_id;user_id | first_day | last_day | days
--------+------------+------------+-----
1 | 2026-01-05 | 2026-01-07 | 3
2 | 2026-01-20 | 2026-01-21 | 2
3 | 2026-02-10 | 2026-02-13 | 4
4 | 2026-02-25 | 2026-02-25 | 1
5 | 2026-03-02 | 2026-03-03 | 2Without the cast, both engines refused: ROW_NUMBER() returns a bigint, and each has date - integer but no date - bigint.
34. Of the users who first logged in each month, how many came back in later months? Tests: a cohort table, built from each user's first month and the months since.
WITH firsts AS (
SELECT user_id, MIN(CAST(date_trunc('month', login_date) AS DATE)) AS cohort
FROM logins
GROUP BY user_id
), activity AS (
SELECT DISTINCT l.user_id, f.cohort,
(EXTRACT(YEAR FROM l.login_date) - EXTRACT(YEAR FROM f.cohort)) * 12
+ EXTRACT(MONTH FROM l.login_date) - EXTRACT(MONTH FROM f.cohort)
AS month_number
FROM logins l
JOIN firsts f ON f.user_id = l.user_id
)
SELECT cohort,
COUNT(*) FILTER (WHERE month_number = 0) AS users,
COUNT(*) FILTER (WHERE month_number = 1) AS month_1,
COUNT(*) FILTER (WHERE month_number = 2) AS month_2
FROM activity
GROUP BY cohort
ORDER BY cohort;cohort | users | month_1 | month_2
-----------+-------+---------+--------
2026-01-01 | 2 | 1 | 2
2026-02-01 | 2 | 1 | 0
2026-03-01 | 1 | 0 | 0The sales sample has no customer column, hence logins. More on retention in cohort retention in SQL.

Counts each answer returned on the invented tables, in DuckDB 2.0.1; PostgreSQL 16.15 returned the same counts. Measured 3 December 2026.
Where DuckDB and PostgreSQL differ
The differences we hit on the way, tested on 3 December 2026:
| What you write | DuckDB 2.0.1 | PostgreSQL 16.15 |
|---|---|---|
A column alias in WHERE (question 8) |
Works | Error: column does not exist |
QUALIFY ROW_NUMBER() OVER (...) <= 3 |
Works | Syntax error |
SELECT 7 / 2 |
3.5 (7 // 2 is 3) |
3 |
SELECT 1 / 0 |
inf | Error: division by zero |
MEDIAN(revenue) |
192.825 | Error: no function median(numeric) |
ROUND(PERCENTILE_CONT(0.5) ..., 2) |
192.82 | Error: no round(double precision, integer) |
date_trunc('month', a_date) |
TIMESTAMP | timestamp with time zone |
a_date - ROW_NUMBER() OVER (...) |
Error | Error |
DISTINCT ON (segment) |
Works | Works |
DuckDB's compatibility page says: "PostgreSQL performs integer division, while DuckDB performs float division."
Where Fastero fits
Fastero is an AI and data platform where people and AI agents work together on a team's data, in the browser on a Mac, Windows or Linux. Every new account comes with the invented sales table used in questions 1 to 23, so you can run them in the SQL editor straight away, in DuckDB SQL. For the employee and login questions, save the three tables as small CSV files and upload them to a project (up to 100 MB a file, within the Free plan's 500 MB of storage), then query them with SQL.

The SQL editor in Fastero, running the question 9 pattern on a demo connection with invented marketing data, not the sample a new account gets.
The Free plan has no end date and needs no card. You can also connect PostgreSQL, MySQL, SQL Server, Redshift, Oracle or BigQuery and query your own data, turn saved queries into charts and dashboards, and share them with colleagues, who view for free. Fastero isn't an interview-prep site: there are no graded exercises or hints, just a place to run SQL on data. Plans: pricing.
FAQ
What SQL questions are asked in a data analyst interview?
Expect grouping and filtering (GROUP BY, HAVING, CASE), joins including self-joins and left joins, window functions such as ROW_NUMBER, RANK, LAG and running totals, and dates: month buckets, gaps and period comparisons. Analytics engineer interviews tend to add deduplication, recursive CTEs and performance.
How do you find the second-highest salary in SQL?
Take the MAX(salary) below the overall MAX(salary), or keep rows where DENSE_RANK() is 2, which extends to the Nth; both handle ties. Avoid LIMIT 1 OFFSET 1 without DISTINCT: on our table it returned the top salary, because two people share it.
What is the difference between RANK and DENSE_RANK?
Both give tied rows the same number. RANK then skips (1, 1, 3) and DENSE_RANK doesn't (1, 1, 2). Use DENSE_RANK for the Nth highest value and RANK for a top N with ties included; ROW_NUMBER gives every row its own number.
Why does NOT IN return no rows?
If the subquery returns a NULL, NOT IN is never true for any row. Our query for employees who manage nobody returned 0 rows because one manager_id is NULL, where NOT EXISTS returned the right 5. Use NOT EXISTS, or filter the NULLs out of the subquery.
What is the difference between WHERE and HAVING?
WHERE filters rows before GROUP BY and can't use aggregates; HAVING filters the groups after, so it can test COUNT(*) > 500. A filter that needs no aggregate belongs in WHERE, where it also cuts the rows to group.
Can I practise in DuckDB if the interview uses PostgreSQL?
Yes: every answer on this page ran unchanged in both. Avoid the DuckDB extras PostgreSQL rejects, such as QUALIFY, MEDIAN() and aliases in WHERE, and remember that 7 / 2 is 3.5 in DuckDB and 3 in PostgreSQL.
Sources
Read on 3 December 2026.
PostgreSQL 16 documentation
- Subquery expressions
- Window functions, window tutorial, window frames
- SELECT, GROUP BY, LIMIT and OFFSET
- Aggregates, dates, generate_series, WITH RECURSIVE
DuckDB 2.0 documentation and blog
- QUALIFY, SELECT, friendly SQL
- PostgreSQL compatibility, numeric functions
- Window functions, aggregates, dates
- Subqueries, IN, DuckDB-Wasm
- Correlated subqueries in SQL, DuckDB blog
Other
- db<>fiddle home page
Our run: Windows 11, Python 3.14.3, DuckDB 2.0.1 (Python package), PostgreSQL 16.15 (postgres:16-alpine in Docker), psycopg 3.3.9.
Try Fastero free: run questions 1 to 23 on the sample sales table in the SQL editor, then the same SQL on your own data. No credit card required.
Fastero Dev Team