SQL course · 20 question practice

20 SQL Interview Questions with Tested Answers

Practise 20 runnable PostgreSQL interview queries, from filtering and joins to top-three-per-region windows, with expected output.

Original PostgreSQL examples · Learn the method, test the output, explain the result.

SQL LEARNING PREVIEW
20 question practicePostgreSQL

Core idea

Predict the rows first; run the query second.

SELECT → JOIN → GROUP BY
OVER (PARTITION BY region)
Compare expected output
First understand the query.Then try the next variation without copying the answer.

The direct answer

Twenty questions that test query writing and reasoning.

These 20 original SQL interview questions use one small dataset so that every answer can be checked. They cover filtering, grouping, joins, correlated subqueries, windows, ranking, LAG and result prediction. Read the prompt, write or trace the query yourself, and predict the output before opening the result. The code uses PostgreSQL syntax.

The value is in explaining why the rows appear. A memorised query can fail as soon as one customer has no order, a status changes or two totals tie. This practice page is distinct from the course overview: it supplies executable tasks and expected output rather than a syllabus. Course options appear just after this introduction.

Course access

Choose your next step in SQL.

Review the current course options and access details here.

Heycademy Courses · Coming Soon

Master SQL with Heycademy

We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.

Launching soon!
We’re putting the finishing touches on this course. Please check back for updates.

Shared input data

Run the dataset once.

There are seven customers in two regions and nine orders. One customer has no orders; one has only a refunded order; one has both a paid and a pending order. Those cases expose mistakes that a clean dataset would hide. Copy the setup into a PostgreSQL session before running the questions.

CREATE TEMP TABLE q_customers (id integer PRIMARY KEY,name text,region text);
CREATE TEMP TABLE q_orders (id integer PRIMARY KEY,customer_id integer,amount integer,status text,order_date text);
INSERT INTO q_customers VALUES (1,'Ada','North'),(2,'Ben','North'),(3,'Cleo','North'),(4,'Dina','South'),(5,'Eli','South'),(6,'Faye','South'),(7,'Gus','South');
INSERT INTO q_orders VALUES (101,1,100,'paid','2026-01-05'),(102,1,40,'paid','2026-02-02'),(103,2,80,'paid','2026-01-08'),(104,2,20,'pending','2026-02-05'),(105,3,120,'paid','2026-01-11'),(106,4,50,'paid','2026-01-13'),(107,4,70,'paid','2026-02-13'),(108,5,110,'paid','2026-02-17'),(109,6,30,'refunded','2026-02-21');
Human-readable dataset summary
customerregionorders / status
AdaNorth101 paid 100; 102 paid 40
BenNorth103 paid 80; 104 pending 20
CleoNorth105 paid 120
DinaSouth106 paid 50; 107 paid 70
EliSouth108 paid 110
FayeSouth109 refunded 30
GusSouthnone

The order date is ISO-formatted text in this compact exercise set. Real applications should model dates with an appropriate date or timestamp type and handle time zones when needed.

Foundations

Questions 1–7: select, filter and aggregate.

Question 1 · Filter rows

Which customers are in the North?

SELECT name FROM q_customers WHERE region='North' ORDER BY id;
Expected output and explanation
Question 1 result
name
Ada
Ben
Cleo

WHERE selects the three North rows before display.

Question 2 · Combine predicates

Which paid orders are at least 100?

SELECT id FROM q_orders WHERE status='paid' AND amount>=100 ORDER BY id;
Expected output and explanation
Question 2 result
id
101
105
108

Both conditions must be true for each order.

Question 3 · Count customers

How many customer rows exist?

SELECT COUNT(*) AS customers FROM q_customers;
Expected output and explanation
Question 3 result
customers
7

COUNT(*) counts all seven customer rows.

Question 4 · Sum paid revenue

What is the paid-order amount total?

SELECT SUM(amount) AS paid_total FROM q_orders WHERE status='paid';
Expected output and explanation
Question 4 result
paid_total
570

The pending 20 and refunded 30 are excluded.

Question 5 · Count paid orders

How many orders have paid status?

SELECT COUNT(*) AS paid_orders FROM q_orders WHERE status='paid';
Expected output and explanation
Question 5 result
paid_orders
7

Count order rows, not distinct customers.

Question 6 · Maximum value

What is the largest paid order amount?

SELECT MAX(amount) AS largest_paid FROM q_orders WHERE status='paid';
Expected output and explanation
Question 6 result
largest_paid
120

Order 105 has the maximum paid amount.

Question 7 · Distinct values

Which regions occur?

SELECT DISTINCT region FROM q_customers ORDER BY region;
Expected output and explanation
Question 7 result
region
North
South

DISTINCT removes repeated region values.

Relationships

Questions 8–13: absence, joins and groups.

Question 8 · No orders

Which customer has no order of any status?

SELECT c.name FROM q_customers c WHERE NOT EXISTS (SELECT 1 FROM q_orders o WHERE o.customer_id=c.id) ORDER BY c.id;
Expected output and explanation
Question 8 result
name
Gus

Faye has a refunded order, so only Gus has no order.

Question 9 · No paid orders

Which customers have no paid order?

SELECT c.name FROM q_customers c WHERE NOT EXISTS (SELECT 1 FROM q_orders o WHERE o.customer_id=c.id AND o.status='paid') ORDER BY c.id;
Expected output and explanation
Question 9 result
name
Faye
Gus

The subquery checks paid orders only.

Question 10 · Grouped paid totals

What is each paying customer’s total?

SELECT c.name,SUM(o.amount) AS paid_total FROM q_customers c JOIN q_orders o ON o.customer_id=c.id WHERE o.status='paid' GROUP BY c.id,c.name ORDER BY c.id;
Expected output and explanation
Question 10 result
namepaid_total
Ada140
Ben80
Cleo120
Dina120
Eli110

The INNER JOIN and paid filter omit Faye and Gus.

Question 11 · Filter groups

Whose paid total reaches 120?

SELECT c.name,SUM(o.amount) AS paid_total FROM q_customers c JOIN q_orders o ON o.customer_id=c.id WHERE o.status='paid' GROUP BY c.id,c.name HAVING SUM(o.amount)>=120 ORDER BY c.id;
Expected output and explanation
Question 11 result
namepaid_total
Ada140
Cleo120
Dina120

HAVING tests the completed customer total.

Question 12 · Left-join counts

How many orders of any status does each customer have?

SELECT c.name,COUNT(o.id) AS orders FROM q_customers c LEFT JOIN q_orders o ON o.customer_id=c.id GROUP BY c.id,c.name ORDER BY c.id;
Expected output and explanation
Question 12 result
nameorders
Ada2
Ben2
Cleo1
Dina2
Eli1
Faye1
Gus0

COUNT(o.id) gives zero for the preserved Gus row.

Question 13 · Global top three

Which three paid orders have the largest amounts?

SELECT id,amount FROM q_orders WHERE status='paid' ORDER BY amount DESC,id LIMIT 3;
Expected output and explanation
Question 13 result
idamount
105120
108110
101100

The secondary id order makes ties deterministic.

Keep building this skill

Apply the method on fresh SQL problems.

The course options are above. Return to the synced pricing block whenever you are ready.

Explore course options →

Complete worked scenario

Top three customers per region.

Question 14 · detailed reasoningAggregate before ranking

The requested grain is one customer. First sum only paid amounts for each customer; preserve customers with no paid orders and treat their total as zero. Then partition the customer rows by region and order each region by paid total descending. Add customer id as a tie-break, so two zero-total South customers do not switch places unpredictably. Finally keep row numbers one through three.

The North result is Ada 140, Cleo 120, Ben 80. The South result is Dina 120, Eli 110, Faye 0. Gus also has zero, but the id tie-break puts Faye first. A common wrong method ranks raw order rows and therefore allows Ada or Dina to occupy multiple places. The PostgreSQL window tutorial explains partitioned row numbering.

Question 14 · Top three per region

Which three customers per region have the highest paid totals?

WITH totals AS (SELECT c.id,c.name,c.region,COALESCE(SUM(o.amount) FILTER (WHERE o.status='paid'),0) AS paid_total FROM q_customers c LEFT JOIN q_orders o ON o.customer_id=c.id GROUP BY c.id,c.name,c.region), ranked AS (SELECT name,region,paid_total,ROW_NUMBER() OVER (PARTITION BY region ORDER BY paid_total DESC,id) AS rn FROM totals) SELECT region,name,paid_total FROM ranked WHERE rn<=3 ORDER BY region,rn;
Expected output and explanation
Question 14 result
regionnamepaid_total
NorthAda140
NorthCleo120
NorthBen80
SouthDina120
SouthEli110
SouthFaye0

Aggregate first so one row means one customer; rank within each region; id resolves the zero-total tie.

Transfer check: add a paid order of 10 for Gus. His total becomes 10, so the South top three become Dina, Eli and Gus. The query changes its output without changing its logic.

Advanced variations

Questions 15–20: ties, LAG and dates.

Question 15 · Rank ties

What ranks do the paying customers receive by total?

WITH totals AS (SELECT c.name,SUM(o.amount) AS paid_total FROM q_customers c JOIN q_orders o ON o.customer_id=c.id WHERE o.status='paid' GROUP BY c.id,c.name) SELECT name,paid_total,RANK() OVER (ORDER BY paid_total DESC) AS rnk FROM totals ORDER BY paid_total DESC,name;
Expected output and explanation
Question 15 result
namepaid_totalrnk
Ada1401
Cleo1202
Dina1202
Eli1104
Ben805

RANK shares second place and skips third place.

Question 16 · Previous order

Which paid orders have a preceding paid order from the same customer?

WITH s AS (SELECT customer_id,id,LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date,id) AS previous_amount FROM q_orders WHERE status='paid') SELECT id,previous_amount FROM s WHERE previous_amount IS NOT NULL ORDER BY id;
Expected output and explanation
Question 16 result
idprevious_amount
102100
10750

Only Ada and Dina have second paid orders.

Question 17 · Status mix

How many orders are in each status?

SELECT status,COUNT(*) AS orders FROM q_orders GROUP BY status ORDER BY status;
Expected output and explanation
Question 17 result
statusorders
paid7
pending1
refunded1

Group the nine order rows by status.

Question 18 · Monthly revenue

How much paid revenue belongs to each month?

SELECT SUBSTRING(order_date,1,7) AS month,SUM(amount) AS revenue FROM q_orders WHERE status='paid' GROUP BY SUBSTRING(order_date,1,7) ORDER BY month;
Expected output and explanation
Question 18 result
monthrevenue
2026-01350
2026-02220

ISO date text makes the first seven characters the month here; a production schema should use a date type.

Question 19 · Repeated buyers

Who has more than one paid order?

SELECT c.name,COUNT(*) AS paid_orders FROM q_customers c JOIN q_orders o ON o.customer_id=c.id WHERE o.status='paid' GROUP BY c.id,c.name HAVING COUNT(*)>1 ORDER BY c.id;
Expected output and explanation
Question 19 result
namepaid_orders
Ada2
Dina2

Count after filtering out pending and refunded orders.

Question 20 · CASE expression

Which paid orders individually reach 100?

SELECT id,CASE WHEN amount>=100 THEN 'yes' ELSE 'no' END AS reaches_100 FROM q_orders WHERE status='paid' ORDER BY id;
Expected output and explanation
Question 20 result
idreaches_100
101yes
102no
103no
105yes
106no
107no
108yes

CASE labels each paid order; it does not aggregate by customer.

How to use the results

Turn a wrong output into a repair.

For every missed question, write the first point where your predicted intermediate rows differ from the actual rows. Name the issue: filter order, join cardinality, group grain, null handling, tie rule or window partition. Then change one input row and predict what should happen. The mistakes lesson gives focused repairs, while the window lesson expands ranking and LAG.

FAQ

Questions about this skill.

Are these official employer interview questions?

No. They are original learning exercises built to teach transferable SQL reasoning.

Should I memorise all 20 queries?

No. State the result grain, build a small input, predict output and explain the clauses.

Why does the top-three solution use ROW_NUMBER instead of RANK?

The task asks for exactly three rows per region; ROW_NUMBER with an explicit tie-break provides a deterministic three. A task that includes all tied customers needs a different rule.

Continue with the SQL course

Make this skill reliable on new data.

Return to the course options and choose the next learning step.

Take the next step →
Scroll to Top