DEV Community

giveinterview.com
giveinterview.com

Posted on Originally published at giveinterview.com

SQL interview guide: why it matters, core concepts, practice plan

Why interviewers ask about it

SQL appears in 17 of today’s 90 new software roles. Companies ask because data is the backbone of most products. A candidate who can retrieve, aggregate, and transform data reliably demonstrates three things:

  1. Problem‑solving with real data – they can turn a business question into a query.
  2. Understanding of relational design – they know how tables relate, which affects performance and correctness.
  3. Ability to work with existing codebases – most legacy systems expose data through SQL, so a developer must read and modify queries daily. Interviewers use SQL to gauge both theoretical knowledge (normal forms, joins) and practical skill (writing clear, efficient queries). Even for roles that focus on front‑end or systems programming, data‑driven decisions are common, so a baseline SQL competence is expected.

The core ideas

1. Relational fundamentals

  • Tables, rows, columns – the basic storage unit. Each column has a type; each row is a record.
  • Primary keys uniquely identify rows; foreign keys enforce relationships.
  • Normalization reduces redundancy. First normal form (1NF) eliminates repeating groups; higher forms address functional dependencies. ### 2. Query building blocks
  • SELECT – choose columns.
  • FROM – specify source tables.
  • WHERE – filter rows.
  • GROUP BY – aggregate rows sharing a key.
  • HAVING – filter aggregated results.
  • ORDER BY – sort output. ### 3. Joins
  • INNER JOIN returns rows with matching keys in both tables.
  • LEFT (OUTER) JOIN keeps all rows from the left table, filling NULLs when no match.
  • RIGHT JOIN and FULL OUTER JOIN are less common but useful for completeness. Understanding join order and join conditions is crucial for both correctness and performance. ### 4. Set operations
  • UNION / UNION ALL combine result sets.
  • INTERSECT and EXCEPT (or MINUS) find common or distinct rows. ### 5. Window functions
  • OVER (PARTITION BY … ORDER BY …) lets you compute running totals, ranks, or moving averages without collapsing rows. ### 6. Indexes and execution plans
  • Indexes speed lookups on columns used in WHERE, JOIN, ORDER BY.
  • Over‑indexing hurts write performance; under‑indexing leads to full table scans.
  • Use EXPLAIN (or equivalent) to see how the engine will execute a query. ### 7. Common pitfalls
  • Implicit type conversion can cause unexpected NULLs.
  • Forgetting to alias columns when two tables have the same name.
  • Using SELECT * in production code – it hides column changes and can waste I/O.
  • Not handling NULL correctly in predicates (= vs IS NULL).

A worked example

Task: A company stores user activity in two tables.

-- users table
CREATE TABLE users (
    user_id   INT PRIMARY KEY,
    email     VARCHAR(255) NOT NULL,
    signup_dt DATE NOT NULL
);

-- events table
CREATE TABLE events (
    event_id   INT PRIMARY KEY,
    user_id    INT REFERENCES users(user_id),
    event_type VARCHAR(50),
    event_ts   TIMESTAMP NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

Requirement: For each user who signed up in the last 30 days, list the total number of login events and the date of their most recent purchase event. Show users with zero logins as 0 and users with no purchases as NULL.
Solution:

WITH recent_users AS (
    SELECT user_id, email
    FROM users
    WHERE signup_dt >= CURRENT_DATE - INTERVAL '30 day'
),
login_counts AS (
    SELECT user_id, COUNT(*) AS login_cnt
    FROM events
    WHERE event_type = 'login'
    GROUP BY user_id
),
last_purchase AS (
    SELECT user_id, MAX(event_ts) AS last_purchase_dt
    FROM events
    WHERE event_type = 'purchase'
    GROUP BY user_id
)
SELECT ru.user_id,
       ru.email,
       COALESCE(lc.login_cnt, 0) AS login_cnt,
       lp.last_purchase_dt
FROM recent_users ru
LEFT JOIN login_counts lc   ON ru.user_id = lc.user_id
LEFT JOIN last_purchase lp  ON ru.user_id = lp.user_id
ORDER BY ru.user_id;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. recent_users isolates the target cohort.
  2. login_counts aggregates login events per user.
  3. last_purchase finds the most recent purchase timestamp.
  4. Two LEFT JOINs keep every recent user, inserting 0 for missing login rows via COALESCE and leaving NULL for missing purchases.
  5. The final ORDER BY gives deterministic output.

5 questions you will be asked

  1. Explain the difference between INNER JOIN and LEFT JOIN.
    • Inner returns only rows with matches in both tables.
    • Left keeps all rows from the left side, filling NULLs when no match.
    • Use left when you need to preserve rows that may lack related data.
  2. How would you find duplicate rows based on a column email in a users table?
    • Group by email and filter groups having COUNT(*) > 1.
    • Example: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;
  3. What is a window function and when is it preferable to GROUP BY?
    • Computes values across a set of rows related to the current row without collapsing rows.
    • Preferable for running totals, rankings, or moving averages where you still need the original row context.
  4. Describe how an index on events(user_id, event_ts) would affect the query in the worked example.
    • The composite index supports the WHERE user_id = … lookup and ordering by event_ts for the MAX(event_ts) aggregation, reducing scan time.
    • It also helps the join condition on user_id.
  5. Why is SELECT * discouraged in production code?
    • It hides column changes, can return unnecessary data, and may cause performance penalties.
    • Explicit column lists make intent clear and protect against schema drift.

Common mistakes

  • Missing join condition – leads to Cartesian product and huge result sets.
  • Using WHERE to filter after a LEFT JOIN – inadvertently turns it into an inner join; move the predicate to the ON clause instead.
  • Aggregating before filtering – e.g., applying HAVING without proper GROUP BY can give wrong totals.
  • Neglecting NULL handling – COUNT(column) ignores NULLs; COUNT(*) counts rows regardless.
  • Over‑using subqueries – sometimes a simple join or window function is more efficient.
  • Assuming indexes are always used – the optimizer may skip an index if the predicate is not selective or if functions are applied to indexed columns.

A 3‑day practice plan

Day 1 – Foundations

  • Review relational theory: primary/foreign keys, normal forms.
  • Write basic SELECT statements with WHERE, ORDER BY, and simple aggregates.
  • Solve 5 beginner‑level problems (e.g., filter users by signup date, count rows per category).
  • End with the worked example: implement it, then modify it to add a COUNT(DISTINCT event_type) column.

Day 2 – Joins and Window Functions

  • Practice inner, left, and full outer joins using two‑table schemas.
  • Convert a problem that uses a subquery into a join and vice‑versa.
  • Learn one window function (ROW_NUMBER) and apply it to rank users by activity.
  • Complete 5 intermediate questions that combine joins with aggregates.

Day 3 – Performance and Edge Cases

  • Study index basics; create an index on a column and compare EXPLAIN plans before and after.
  • Write queries that deliberately produce NULLs and practice COALESCE and IS NULL checks.
  • Attempt 5 advanced questions: duplicate detection, hierarchical data with recursive CTEs, and optimizing a slow query.
  • Review all mistakes listed above; for each, write a short “bad query → corrected query” pair.

By the end of the three days you will have reinforced the core ideas, seen how they appear in realistic tasks, and built a checklist of pitfalls to avoid during an interview.

Roles hiring for SQL now

Each has its own mock interview, built from the real job description.

More tech roles today

Practise it out loud

Knowing the answer is not the same as explaining it under follow-up questions. Try a free mock interview on giveinterview.com.

Top comments (0)