Skip to content

AI and data interviews

SQL interview questions for data and ML internships, worked

SQL rounds for data and machine learning internships mostly test four things: joins, grouping, window functions and the traps around NULLs and duplicate rows. This page works each one on small tables you can run yourself, then gives five original practice problems whose answers a separate program recomputes. The queries use standard SQL that runs in PostgreSQL.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

Where SQL shows up in intern loops

When a posting for a data or machine learning internship lists SQL, expect the work to involve queries, and expect that an assessment or an interview round may ask you to write some. The format varies by employer and by team, so read the posting and your recruiter’s note, and do not rely on a forum’s account of what a named employer does. We say nothing here about what any employer asks. The practice problems on this page are our own.

What transfers across formats is the same short list. You are given a few small tables, you write a query, and you explain what it returns and why. A correct query with a clear explanation beats a clever one you cannot explain.

The sample tables

The worked queries below use these small tables, which you can type into any PostgreSQL or SQLite session. SQLite is a good way to practice at home because it needs no setup.

Table users has the rows (1, Ana), (2, Ben), (3, Cy) and (4, Dee), with columns id and name.

Table orders has columns id, user_id and amount, with six rows: (10, 1, 30), (11, 1, 20), (12, 3, 50), (13, 3, 10), (14, 3, 40) and (15, NULL, 15). The last order has no user, which is deliberate.

Joins and grouping: worked queries

The PostgreSQL documentation’s chapter on queries covers joins, grouping and combining results. The two ideas to hold are these. A join forms every pair of rows that satisfy the join condition. A GROUP BY then collapses rows that share a value into one row, and aggregates such as SUM and COUNT are computed per group.

Inner join with grouping and HAVING:

The query: SELECT u.id, SUM(o.amount) AS total FROM users u JOIN orders o ON o.user_id = u.id GROUP BY u.id HAVING SUM(o.amount) > 40 ORDER BY u.id;

The result has two rows: user 1 with a total of 50 and user 3 with a total of 100. User 2 and user 4 have no orders, so the inner join drops them. HAVING filters after the sums are computed, which is why a condition on a SUM goes there and not in WHERE.

Left join, keeping users with no orders:

The query: SELECT u.id, COUNT(*) AS n_star, COUNT(o.id) AS n_orders, COALESCE(SUM(o.amount), 0) AS total FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id ORDER BY u.id;

Left join result, with COUNT(*) and COUNT(column)
idn_starn_orderstotal
12250
2100
333100
4100

Look at users 2 and 4. COUNT(*) shows 1 because the unmatched row itself is counted, and COUNT(o.id) shows 0 because it counts only non-NULL values. When the question is how many orders each user has, count a column from the right-hand table.

Window functions: worked queries

The PostgreSQL window functions tutorial describes a window function as a calculation across a set of rows related to the current row. Unlike a plain aggregate, it does not collapse rows into one output row: each row keeps its identity. The OVER clause says how rows are split into partitions, with PARTITION BY, and ordered inside each one, with ORDER BY. The tutorial also notes that a row removed by WHERE is not seen by any window function, because windows work on the rows that remain after filtering.

Take a table staff with columns id, dept and salary, and the seven rows (1, A, 50), (2, A, 70), (3, A, 70), (4, B, 60), (5, B, 40), (6, B, 60) and (7, B, 90).

The query: SELECT id, dept, salary, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS r, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS dr, ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC, id) AS rn FROM staff ORDER BY dept, salary DESC, id;

Ranking functions on the same rows
iddeptsalaryrdrrn
2A70111
3A70112
1A50323
7B90111
4B60222
6B60223
5B40434

The three ranking functions differ only when there are ties. RANK gives tied rows the same number and skips the next ones, DENSE_RANK gives them the same number and skips nothing, and ROW_NUMBER numbers every row differently, so it needs a tie-breaker such as the id to be repeatable. If a question asks for the top earner in each department, say which function you chose and what it does on a tie.

A running total uses an ordered window. With a table scores of student_id, term and points, SUM(points) OVER (PARTITION BY student_id ORDER BY term) gives each student’s total so far. By default, when ORDER BY is given, the frame runs from the first row of the partition up through the current row, plus any later rows that tie with it on the ORDER BY value, which is why the total grows with each term and why two rows in the same term get the same running total.

Common traps

Common SQL traps and how to avoid them
TrapWhat happensHow to avoid it
Comparing to NULL with =WHERE user_id = NULL matches nothing, because a comparison with NULL is unknown, so the count is 0 even though one order has no userUse IS NULL, which returns the 1 row
NOT IN with a NULL in the listSELECT id FROM users WHERE id NOT IN (SELECT user_id FROM orders) returns no rows, because one NULL makes every test unknownFilter the NULLs out of the list, or use NOT EXISTS. With the NULLs filtered out, the query returns users 2 and 4
COUNT(*) against COUNT(column)COUNT(*) counts rows and COUNT(column) counts non-NULL values: on orders, COUNT(*) is 6 and COUNT(user_id) is 5Choose the one that matches the question
AVG ignores NULLAVG skips NULL values, so a missing value does not count as zeroState what a missing value means before you average
Duplicates multiply in a joinIf both sides repeat a join value, the rows multiply, and a SUM taken after the join can overcountCount matches per value first, or aggregate one side before joining
WHERE against HAVINGA condition on an aggregate in WHERE is an error, and a row-level filter in HAVING works but filters latePut row filters in WHERE and group filters in HAVING

The average of the six order amounts is 27.5, because none of them is NULL. AVG(user_id) is 2.2, which is 11 divided by the five non-NULL ids and not by six. If an interviewer asks you to explain a result that looks wrong, check these traps before anything else.

Five practice problems

These are our own practice problems, written for this site. Work each one on paper first, then open the steps. They cover joins, grouping, window frames, ties and duplicates.

Problem 1. A table scores has one row per attempt. Its student_id column holds 1, 2, 1, 3, 2, 1, 3, 3, 2, 4 and its points column holds 5, 8, 7, 3, 9, 6, 4, 8, 2, 10, in the same row order. The query SELECT student_id, SUM(points) AS total FROM scores GROUP BY student_id HAVING SUM(points) > 15 runs. What is the sum of the total column over the rows it returns? Give an integer.

Show the answer and the working

Answer: 37

  1. GROUP BY makes one row per student. Student 1 has points 5, 7 and 6, so the total is 18. Student 2 has 8, 9 and 2, so 19. Student 3 has 3, 4 and 8, so 15. Student 4 has 10.
  2. HAVING filters after grouping, so it sees the totals. Totals above 15 are 18 and 19. Student 3 is exactly 15, which is not above 15.
  3. The query returns two rows, and their totals add to 18 + 19 = 37. A WHERE clause would have filtered single attempts before the sums, which is a different question.

Problem 2. A table users has one row for each id 1, 2, 3, 4, 5, 6. A table orders has one row per order, and its user_id column holds 1, 1, 3, 3, 3, 5. The query SELECT u.id, COUNT(o.user_id) AS orders FROM users u LEFT JOIN orders o ON o.user_id = u.id GROUP BY u.id runs. How many of the returned rows show orders equal to 0? Give an integer.

Show the answer and the working

Answer: 3

  1. A LEFT JOIN keeps every user, and a user with no matching order gets one row whose order columns are NULL.
  2. Users 1, 3 and 5 have orders. Users 2, 4 and 6 have none, so each appears once with NULL in o.user_id.
  3. COUNT(o.user_id) counts only non-NULL values, so those three users show 0. COUNT(*) would show 1 for them, because the unmatched row itself would be counted. An INNER JOIN would drop them and return only 3 rows.

Problem 3. A table a has a column id holding 1, 2, 2, 3. A table b has a column k holding 2, 2, 3, 3, 3, 4. The query SELECT a.id FROM a JOIN b ON b.k = a.id runs, with no DISTINCT. How many rows does it return? Give an integer.

Show the answer and the working

Answer: 7

  1. An inner join returns one row for every pair of rows, one from each table, whose values match. When both sides repeat a value, the matches multiply.
  2. The value 1 has no match in b. The value 2 appears twice in a and twice in b, so it gives 2 x 2 = 4 rows. The value 3 appears once in a and three times in b, so it gives 1 x 3 = 3 rows.
  3. The value 4 appears only in b and is dropped. The total is 4 + 3 = 7 rows, more than either table could suggest by its row count alone.

Problem 4. A table sales has one row for each day from 1 to 8, and its amount column holds 4, 7, 3, 9, 6, 2, 8, 5 in day order. The query SELECT day, AVG(amount) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS smooth FROM sales runs. What is smooth on day 5? Give a reduced fraction.

Show the answer and the working

Answer: 17/3

  1. The frame for a row is the row before it, the row itself and the row after it, when they exist, ordered by day.
  2. For day 5 the frame is days 4, 5 and 6, with amounts 9, 6 and 2.
  3. The average is (9 + 6 + 2) / 3 = 17/3. On day 1 the frame would have only two rows, days 1 and 2, because there is no row before it, and the average would use 2 as the divisor.

Problem 5. A table staff has nine rows. Its dept column holds 1, 1, 1, 2, 2, 3, 3, 3, 3 and its salary column holds 50, 70, 70, 60, 60, 40, 55, 55, 30, in the same row order. A query uses RANK() OVER (PARTITION BY dept ORDER BY salary DESC) and keeps the rows whose rank is 1. How many rows does it return? Give an integer.

Show the answer and the working

Answer: 6

  1. PARTITION BY dept ranks the rows inside each department. RANK gives tied rows the same rank, and the next rank skips ahead.
  2. In department 1 the top salary is 70 and two rows have it, so both have rank 1. In department 2 both rows have 60, so both have rank 1. In department 3 the top salary is 55 and two rows have it.
  3. That is 2 + 2 + 2 = 6 rows. ROW_NUMBER would number the tied rows 1 and 2 and return only 3 rows, one per department, so the choice of function changes the answer.

Every answer above is recomputed by a separate program that rebuilds the query result with plain loops over the table values. These are our own practice problems. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session. The data science internship interview guide covers the statistics and modeling rounds, and the data science internship role guide covers the field.

Questions

What SQL should I know for a data or ML internship?

Know joins, grouping with HAVING, window functions and how NULLs behave. Most queries you will be asked to write combine two of these.

What is the difference between WHERE and HAVING?

WHERE filters rows before grouping, and HAVING filters groups after the aggregates are computed. A condition on a sum or a count belongs in HAVING.

Why does a join sometimes return more rows than either table?

A join returns one row for every matching pair, so repeated values on both sides multiply. Count the matches per value before you trust a row count.

How a session helps

A session with George is a place to write a query aloud and have the reasoning questioned: what the join returns before grouping, what a NULL does to the count and why you chose one ranking function. You write every query yourself. See the packages page for the sessions, or book a session.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms