SQL Query Puzzles

Updated · 12 min read
mediumPostgreSQL 18sqlpuzzlesinterviewassessment

Each puzzle is a short query on the Fee Tracker. Decide exactly what it returns before you open the answer. These are the cases where SQL surprises people: NULL logic, joins that drop or repeat rows, grouping, window frames and failed transactions. Every answer runs in Try it, so you can change the query and see what happens.

How to Use This Page

  • Write down your prediction: the columns, the number of rows and the values.
  • Open Show solution to see the query's real output and why.
  • If you got it wrong, read the linked lesson, then change the query in Try it until the result makes sense.

NULL and Logic

Puzzle 1: NULL equals NULL?. What does this return?

SQL
SELECT NULL = NULL AS equal, NULL IS NULL AS is_null;
Show solution
SQL▶ Try it
SELECT NULL = NULL AS equal, NULL IS NULL AS is_null;
Output
 equal | is_null
-------+---------
 NULL  | t
(1 row)

A comparison with NULL is unknown, shown as NULL; IS NULL is the test that works. See NULL Values.

Puzzle 2: NOT IN with a NULL. What does this return?

SQL
SELECT count(*) AS students
FROM students
WHERE student_id NOT IN (101, NULL);
Show solution
SQL▶ Try it
SELECT count(*) AS students
FROM students
WHERE student_id NOT IN (101, NULL);
Output
 students
----------
        0
(1 row)

student_id <> NULL is unknown for every row, so NOT IN keeps nothing. See EXISTS.

Puzzle 3: Counting columns. What does this return?

SQL
SELECT count(*) AS all_rows, count(email) AS with_email, count(DISTINCT city) AS cities
FROM students;
Show solution
SQL▶ Try it
SELECT count(*) AS all_rows, count(email) AS with_email, count(DISTINCT city) AS cities
FROM students;
Output
 all_rows | with_email | cities
----------+------------+--------
        3 |          1 |      2
(1 row)

count(email) skips the two students without an email. See Aggregate Functions.

Puzzle 4: Average with NULL. What does this return?

SQL
SELECT avg(mentor_id) AS avg_mentor, sum(mentor_id) AS total
FROM students;
Show solution
SQL▶ Try it
SELECT avg(mentor_id) AS avg_mentor, sum(mentor_id) AS total
FROM students;
Output
      avg_mentor      | total
----------------------+-------
 101.5000000000000000 |   203
(1 row)

Aggregates skip the NULL mentor: (101 + 102) / 2. See Aggregate Functions.

Puzzle 5: Integer division. What does this return?

SQL
SELECT 7 / 2 AS a, 7 / 2.0 AS b, 7 % 2 AS c;
Show solution
SQL▶ Try it
SELECT 7 / 2 AS a, 7 / 2.0 AS b, 7 % 2 AS c;
Output
 a |         b          | c
---+--------------------+---
 3 | 3.5000000000000000 | 1
(1 row)

Two integers divide as integers in PostgreSQL. See SQL Operators.

Puzzle 6: AND before OR. What does this return?

SQL
SELECT count(*) AS courses
FROM courses
WHERE technology = 'Java' OR technology = 'SQL' AND fee_usd > 500;
Show solution
SQL▶ Try it
SELECT count(*) AS courses
FROM courses
WHERE technology = 'Java' OR technology = 'SQL' AND fee_usd > 500;
Output
 courses
---------
       3
(1 row)

AND binds first: all Java courses, plus SQL courses over $500 (none). See AND, OR and NOT.

Joins and Sets

Puzzle 7: LEFT JOIN then WHERE. What does this return?

SQL
SELECT s.first_name
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id
WHERE p.method = 'card'
GROUP BY s.first_name
ORDER BY s.first_name;
Show solution
SQL▶ Try it
SELECT s.first_name
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id
WHERE p.method = 'card'
GROUP BY s.first_name
ORDER BY s.first_name;
Output
 first_name
------------
 Navika
 Srihitha
(2 rows)

The WHERE removes Advitha's NULL row, so the LEFT JOIN acts like an inner join. See LEFT JOIN.

Puzzle 8: LEFT JOIN, condition in ON. What does this return?

SQL
SELECT s.first_name, count(p.payment_id) AS card_payments
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id AND p.method = 'card'
GROUP BY s.first_name
ORDER BY s.first_name;
Show solution
SQL▶ Try it
SELECT s.first_name, count(p.payment_id) AS card_payments
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id AND p.method = 'card'
GROUP BY s.first_name
ORDER BY s.first_name;
Output
 first_name | card_payments
------------+---------------
 Advitha    |             0
 Navika     |             1
 Srihitha   |             3
(3 rows)

In ON, the condition filters payments, not students: everyone stays. See LEFT JOIN.

Puzzle 9: count(*) after a LEFT JOIN. What does this return?

SQL
SELECT s.first_name, count(*) AS rows, count(p.payment_id) AS payments
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id
GROUP BY s.first_name
ORDER BY s.first_name;
Show solution
SQL▶ Try it
SELECT s.first_name, count(*) AS rows, count(p.payment_id) AS payments
FROM students s
LEFT JOIN payments p ON p.student_id = s.student_id
GROUP BY s.first_name
ORDER BY s.first_name;
Output
 first_name | rows | payments
------------+------+----------
 Advitha    |    1 |        0
 Navika     |    2 |        2
 Srihitha   |    5 |        5
(3 rows)

Advitha has one row with NULLs: count(*) says 1, count(p.payment_id) says 0. See LEFT JOIN.

Puzzle 10: A join that multiplies. What does this return?

SQL
SELECT sum(p.amount_usd) AS total
FROM payments p
JOIN enrollments e ON e.student_id = p.student_id;
Show solution
SQL▶ Try it
SELECT sum(p.amount_usd) AS total
FROM payments p
JOIN enrollments e ON e.student_id = p.student_id;
Output
  total
---------
 7250.00
(1 row)

Each payment repeats once per enrollment of its student, inflating the total from 2150.00. See Joining Many Tables.

Puzzle 11: CROSS JOIN size. What does this return?

SQL
SELECT count(*) AS pairs FROM students CROSS JOIN courses;
Show solution
SQL▶ Try it
SELECT count(*) AS pairs FROM students CROSS JOIN courses;
Output
 pairs
-------
    18
(1 row)

3 students × 6 courses. See CROSS JOIN.

Puzzle 12: UNION vs UNION ALL. What does this return?

SQL
SELECT count(*) AS union_rows FROM (SELECT student_id FROM enrollments UNION SELECT student_id FROM payments) u;
SELECT count(*) AS union_all_rows FROM (SELECT student_id FROM enrollments UNION ALL SELECT student_id FROM payments) u;
Show solution
SQL▶ Try it
SELECT count(*) AS union_rows FROM (SELECT student_id FROM enrollments UNION SELECT student_id FROM payments) u;
SELECT count(*) AS union_all_rows FROM (SELECT student_id FROM enrollments UNION ALL SELECT student_id FROM payments) u;
Output
 union_rows
------------
          3
(1 row)
 
 union_all_rows
----------------
             14
(1 row)

UNION removes duplicates: three students; UNION ALL keeps all 14 rows. See UNION and UNION ALL.

Puzzle 13: INTERSECT and EXCEPT. What does this return?

SQL
SELECT student_id FROM enrollments EXCEPT SELECT student_id FROM payments
ORDER BY student_id;
Show solution
SQL▶ Try it
SELECT student_id FROM enrollments EXCEPT SELECT student_id FROM payments
ORDER BY student_id;
Output
 student_id
------------
        102
(1 row)

Students who enrolled but never paid. See INTERSECT and EXCEPT.

Grouping and Functions

Puzzle 14: GROUP BY and NULL. What does this return?

SQL
SELECT method, count(*) AS payments
FROM payments
GROUP BY method
ORDER BY method NULLS FIRST;
Show solution
SQL▶ Try it
SELECT method, count(*) AS payments
FROM payments
GROUP BY method
ORDER BY method NULLS FIRST;
Output
 method | payments
--------+----------
 NULL   |        1
 card   |        4
 check  |        2
(3 rows)

NULLs form one group of their own. See GROUP BY.

Puzzle 15: HAVING without GROUP BY. What does this return?

SQL
SELECT count(*) AS payments FROM payments HAVING count(*) > 5;
Show solution
SQL▶ Try it
SELECT count(*) AS payments FROM payments HAVING count(*) > 5;
Output
 payments
----------
        7
(1 row)

The whole table is one group; 7 > 5, so one row comes back. See HAVING.

Puzzle 16: DISTINCT on two columns. What does this return?

SQL
SELECT count(*) FROM (SELECT DISTINCT student_id, course_id FROM payments) d;
Show solution
SQL▶ Try it
SELECT count(*) FROM (SELECT DISTINCT student_id, course_id FROM payments) d;
Output
 count
-------
     5
(1 row)

Distinct pairs: Srihitha paid twice for Java OOP and Navika twice for JavaScript Basics. See SELECT DISTINCT.

Puzzle 17: ORDER BY with NULLs. What does this return?

SQL
SELECT payment_id, method
FROM payments
ORDER BY method, payment_id
LIMIT 3;
Show solution
SQL▶ Try it
SELECT payment_id, method
FROM payments
ORDER BY method, payment_id
LIMIT 3;
Output
 payment_id | method
------------+--------
          1 | card
          2 | card
          4 | card
(3 rows)

PostgreSQL sorts NULLs last in ascending order, so they don't appear in the first three. See ORDER BY.

Puzzle 18: CASE without ELSE. What does this return?

SQL
SELECT title, CASE WHEN fee_usd > 500 THEN 'premium' END AS tier
FROM courses
ORDER BY course_id
LIMIT 3;
Show solution
SQL▶ Try it
SELECT title, CASE WHEN fee_usd > 500 THEN 'premium' END AS tier
FROM courses
ORDER BY course_id
LIMIT 3;
Output
      title       |  tier
------------------+---------
 Java Basics      | NULL
 Java OOP         | NULL
 Java Collections | premium
(3 rows)

No matching WHEN and no ELSE gives NULL. See CASE Expressions.

Puzzle 19: COALESCE order. What does this return?

SQL
SELECT first_name, coalesce(email, phone, 'no contact') AS contact
FROM students
ORDER BY student_id;
Show solution
SQL▶ Try it
SELECT first_name, coalesce(email, phone, 'no contact') AS contact
FROM students
ORDER BY student_id;
Output
 first_name |            contact
------------+--------------------------------
 Srihitha   | srihitha.anamaneni@example.com
 Advitha    | (415) 555-0178
 Navika     | no contact
(3 rows)

The first non-NULL value wins. See NULL Functions.

Puzzle 20: Text and numbers. What does this return?

SQL
SELECT '10' < '9' AS as_text, 10 < 9 AS as_numbers;
Show solution
SQL▶ Try it
SELECT '10' < '9' AS as_text, 10 < 9 AS as_numbers;
Output
 as_text | as_numbers
---------+------------
 t       | f
(1 row)

Text compares character by character: "1" sorts before "9". See Type Conversion.

Puzzle 21: Dates minus dates. What does this return?

SQL
SELECT DATE '2026-01-05' - DATE '2025-12-03' AS days,
       DATE '2025-12-03' + 30 AS plus_30;
Show solution
SQL▶ Try it
SELECT DATE '2026-01-05' - DATE '2025-12-03' AS days,
       DATE '2025-12-03' + 30 AS plus_30;
Output
 days |  plus_30
------+------------
   33 | 2026-01-02
(1 row)

Subtracting dates gives days; adding an integer adds days. See Dates and Times.

Window Functions

Puzzle 22: ROW_NUMBER vs RANK. What does this return?

SQL
SELECT payment_id, amount_usd,
       ROW_NUMBER() OVER (ORDER BY amount_usd DESC, payment_id) AS rn,
       RANK()       OVER (ORDER BY amount_usd DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY amount_usd DESC) AS drnk
FROM payments
ORDER BY rn;
Show solution
SQL▶ Try it
SELECT payment_id, amount_usd,
       ROW_NUMBER() OVER (ORDER BY amount_usd DESC, payment_id) AS rn,
       RANK()       OVER (ORDER BY amount_usd DESC) AS rnk,
       DENSE_RANK() OVER (ORDER BY amount_usd DESC) AS drnk
FROM payments
ORDER BY rn;
Output
 payment_id | amount_usd | rn | rnk | drnk
------------+------------+----+-----+------
          4 |     550.00 |  1 |   1 |    1
          1 |     450.00 |  2 |   2 |    2
          2 |     250.00 |  3 |   3 |    3
          3 |     250.00 |  4 |   3 |    3
          6 |     225.00 |  5 |   5 |    4
          7 |     225.00 |  6 |   5 |    4
          5 |     200.00 |  7 |   7 |    5
(7 rows)

Ties share a rank; RANK skips numbers afterwards, DENSE_RANK doesn't. See Ranking Functions.

Puzzle 23: Running total with ties. What does this return?

SQL
SELECT paid_on, amount_usd,
       sum(amount_usd) OVER (ORDER BY amount_usd) AS running
FROM payments
ORDER BY amount_usd, paid_on;
Show solution
SQL▶ Try it
SELECT paid_on, amount_usd,
       sum(amount_usd) OVER (ORDER BY amount_usd) AS running
FROM payments
ORDER BY amount_usd, paid_on;
Output
  paid_on   | amount_usd | running
------------+------------+---------
 2026-01-05 |     200.00 |  200.00
 2025-11-14 |     225.00 |  650.00
 2025-12-19 |     225.00 |  650.00
 2025-10-30 |     250.00 | 1150.00
 2025-12-03 |     250.00 | 1150.00
 2025-08-28 |     450.00 | 1600.00
 2025-12-29 |     550.00 | 2150.00
(7 rows)

The default frame is RANGE: rows with the same amount_usd are added together. See Running Totals, LAG and LEAD.

Puzzle 24: LAG at the start. What does this return?

SQL
SELECT payment_id, amount_usd,
       lag(amount_usd) OVER (ORDER BY payment_id) AS previous
FROM payments
ORDER BY payment_id
LIMIT 3;
Show solution
SQL▶ Try it
SELECT payment_id, amount_usd,
       lag(amount_usd) OVER (ORDER BY payment_id) AS previous
FROM payments
ORDER BY payment_id
LIMIT 3;
Output
 payment_id | amount_usd | previous
------------+------------+----------
          1 |     450.00 |     NULL
          2 |     250.00 |   450.00
          3 |     250.00 |   250.00
(3 rows)

The first row has no previous row, so NULL. See Running Totals, LAG and LEAD.

Puzzle 25: Window vs GROUP BY. What does this return?

SQL
SELECT student_id, amount_usd,
       sum(amount_usd) OVER (PARTITION BY student_id) AS student_total
FROM payments
ORDER BY student_id, payment_id;
Show solution
SQL▶ Try it
SELECT student_id, amount_usd,
       sum(amount_usd) OVER (PARTITION BY student_id) AS student_total
FROM payments
ORDER BY student_id, payment_id;
Output
 student_id | amount_usd | student_total
------------+------------+---------------
        101 |     450.00 |       1700.00
        101 |     250.00 |       1700.00
        101 |     250.00 |       1700.00
        101 |     550.00 |       1700.00
        101 |     200.00 |       1700.00
        103 |     225.00 |        450.00
        103 |     225.00 |        450.00
(7 rows)

Every row stays; each gets its student's total. See Window Functions.

Puzzle 26: Recursive countdown. What does this return?

SQL
WITH RECURSIVE n(x) AS (SELECT 3 UNION ALL SELECT x - 1 FROM n WHERE x > 1)
SELECT x FROM n ORDER BY x;
Show solution
SQL▶ Try it
WITH RECURSIVE n(x) AS (SELECT 3 UNION ALL SELECT x - 1 FROM n WHERE x > 1)
SELECT x FROM n ORDER BY x;
Output
 x
---
 1
 2
 3
(3 rows)

It stops when the recursive part returns no rows. See Recursive CTEs.

Subqueries and Transactions

Puzzle 27: Scalar subquery with no rows. What does this return?

SQL
SELECT (SELECT title FROM courses WHERE course_id = 99) AS title;
Show solution
SQL▶ Try it
SELECT (SELECT title FROM courses WHERE course_id = 99) AS title;
Output
 title
-------
 NULL
(1 row)

A scalar subquery that finds nothing returns NULL, not an error. See Subqueries.

Puzzle 28: ANY and ALL. What does this return?

SQL
SELECT 300 > ANY (SELECT fee_usd FROM courses) AS any_cheaper,
       300 > ALL (SELECT fee_usd FROM courses) AS all_cheaper;
Show solution
SQL▶ Try it
SELECT 300 > ANY (SELECT fee_usd FROM courses) AS any_cheaper,
       300 > ALL (SELECT fee_usd FROM courses) AS all_cheaper;
Output
 any_cheaper | all_cheaper
-------------+-------------
 t           | f
(1 row)

Some courses cost less than 300; not all do. See ANY and ALL.

Puzzle 29: LIKE and case. What does this return?

SQL
SELECT 'Navika' LIKE 'nav%' AS like_result, 'Navika' ILIKE 'nav%' AS ilike_result;
Show solution
SQL▶ Try it
SELECT 'Navika' LIKE 'nav%' AS like_result, 'Navika' ILIKE 'nav%' AS ilike_result;
Output
 like_result | ilike_result
-------------+--------------
 f           | t
(1 row)

LIKE is case-sensitive in PostgreSQL; ILIKE isn't. See LIKE and Wildcards.

Puzzle 30: A transaction that fails. What does this return?

SQL
BEGIN;
UPDATE courses SET fee_usd = 999 WHERE course_id = 1;
SELECT 1 / 0;
COMMIT;
SELECT fee_usd FROM courses WHERE course_id = 1;
Show solution
SQL▶ Try it
BEGIN;
UPDATE courses SET fee_usd = 999 WHERE course_id = 1;
SELECT 1 / 0;
COMMIT;
SELECT fee_usd FROM courses WHERE course_id = 1;
Output
BEGIN
 
UPDATE 1
 
ERROR:  division by zero
 
ROLLBACK
 
 fee_usd
---------
  450.00
(1 row)

The error aborts the transaction, so COMMIT rolls back and the fee is unchanged. See Transactions.

Was this tutorial helpful?