SQL interview questions
SQL rounds draw from a surprisingly small pool. The same ten or so patterns come back again and again, dressed in different tables: the second highest salary, the top three per department, customers who never ordered, duplicates, running totals, streaks. Learn the pattern behind each and you can answer the variations you have never seen.
Every answer below runs on Postgres, and on MySQL 8 except where noted. Each question is followed by the thinking, because the interviewer cares more about that than about the syntax.
Before reading on: how would you find the second highest salary in an employees table? Write the query you would give in an interview, and note what happens if two people share the top salary.
First, the order SQL actually runs in#
Half of the confusing errors in SQL come from reading a query top to bottom. The database runs it in this order:
FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMITThis explains three things interviewers love to ask. WHERE cannot use an aggregate like
COUNT(*), because grouping has not happened yet, which is what HAVING is for. WHERE cannot use
a column alias from SELECT, because SELECT runs later. And ORDER BY can use the alias, because it
runs after.