SQL for Interviews

Write the SQL asked in online assessments and interviews: joins, grouping, subqueries, window functions and classic questions like the Nth highest salary.

Beginner · about 10 hours · difficulty 2/5

Learn first: Relational Model and ER Design

Many online assessments include one or two SQL questions, and they are easy marks if you have practised. Learn to think in sets of rows, not loops.

Core syntax

  • SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT. Know the logical execution order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. That explains why you cannot use a SELECT alias in WHERE.
  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Aggregates: COUNT, SUM, AVG, MIN, MAX. COUNT(*) counts rows, COUNT(col) skips NULLs.
  • NULL is not equal to anything, including NULL. Use IS NULL.

Joins

  • INNER JOIN: matching rows only. LEFT JOIN: all rows from the left plus matches (NULLs otherwise). RIGHT and FULL OUTER joins, CROSS JOIN, and self joins (employee and manager in one table).
  • "Find customers with no orders" is a LEFT JOIN with WHERE o.id IS NULL, or NOT EXISTS.

Subqueries and window functions

  • Subqueries in WHERE (IN, EXISTS) and FROM; correlated subqueries run per row.
  • CTEs with WITH make complex queries readable.
  • Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and running totals with SUM(...) OVER (PARTITION BY ... ORDER BY ...). They solve "top N per group" cleanly.

Classic questions

Second or Nth highest salary (DENSE_RANK or LIMIT/OFFSET on distinct values), duplicate emails, department-wise highest salary, consecutive login days, and employees earning more than their managers.

Good enough to move on: you can solve the LeetCode SQL 50 study plan mostly without hints and explain the difference between RANK and DENSE_RANK.

Key concepts

  • SELECT, WHERE, ORDER BY, LIMIT
  • GROUP BY and HAVING
  • NULL handling
  • Inner, left, self and cross joins
  • Subqueries and EXISTS
  • CTEs
  • Window functions and ranking
  • Nth highest salary patterns
  • DDL, DML and DCL commands

Mini project

Load a sample employees or e-commerce dataset into PostgreSQL and write 20 queries: department-wise top 3 earners, monthly revenue with running totals, customers with no orders, month-over-month growth using LAG, and duplicate detection.

Check yourself

Why can you not use an alias defined in SELECT inside the WHERE clause, and how would you rewrite the query to filter on it?

Free resources