Skip to the page

DBMS · core

Joins, GROUP BY and common queries

Joins combine tables. The join type decides which unmatched rows survive. GROUP BY with HAVING counts and filters groups.

The notes

What you must know

  • Inner join: only matching rows. Left join: all left rows, with NULL on the right when no match. Right join is the mirror. Full outer join: all rows from both sides. Cross join: every pair (4 x 3 = 12 rows).
  • Example: 4 students and 3 courses, with 3 matches. Inner gives 3 rows, left gives 4, right gives 4, full outer gives 5 (not 4 + 3 = 7).
  • NULL is never equal to anything, not even another NULL, so a NULL key does not match.
  • Courses with no students: a LEFT JOIN with WHERE s.id IS NULL, or NOT EXISTS.
  • A WHERE filter on the right table can turn a left join into an inner join, so put that condition in the ON clause.
  • A join gives one row per match, so a student with three registrations appears three times. That is how joins work. Fix with DISTINCT, or better WHERE EXISTS, or GROUP BY.
  • WHERE filters rows before grouping; HAVING filters groups after. Use COUNT(e.id), not COUNT(*), with a left join, so empty groups count as 0.
  • Second highest salary: SELECT MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) FROM employee). It handles ties at the top and returns NULL if there is no second value.

The red pen

Common traps: mistake → fix

  • Mistake: Full outer join returns 4 + 3 rows

    Fix: it returns each matched row once plus the unmatched ones.

  • Mistake: NULL matches NULL in a join

    Fix: it never does.

  • Mistake: COUNT(*) with a left join gives 0 for empty groups

    Fix: it gives 1; use COUNT of the right column.

  • Mistake: The database duplicated rows by itself

    Fix: the join produced one row per match.

Easy to hard

Questions interviewers ask, easy to hard

  1. How many rows does each join type return for these two small tables?
  2. The query shows some students three times. Why, and how do you fix it?
  3. Write a query for the department-wise employee count, including empty departments.
  4. Write a query for the second highest salary.

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview