SQL Fundamentals

The building blocks of every query: SELECT, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT, the order they run in, and how NULL changes each one.

Overview

Almost every SQL interview question is built from six clauses: SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY, plus LIMIT. You write them in one order, but the database runs them in another. Most wrong answers come from forgetting that order, or from forgetting what NULL does.

This page uses one tiny table, so every query below comes with its exact result. All the SQL runs on PostgreSQL.

The sample table

Each row is an employee. Two values are missing on purpose: Eli has no salary and Fay has no department. Missing values are stored as NULL, which means 'unknown'.

Here is the table those statements build. Keep it in view: every result below comes from these six rows.

  • 1 — Ana — Eng — 150000 — NULL
  • 2 — Ben — Eng — 120000 — 1
  • 3 — Cai — Eng — 120000 — 1
  • 4 — Dee — Sales — 90000 — 1
  • 5 — Eli — Sales — NULL — 4
  • 6 — Fay — NULL — 70000 — 1

Interview questions

  • Explain the logical order of a SELECT and why it matters.
  • What is the difference between WHERE and HAVING?
  • How do you handle NULL values in SQL?

Sign up free to read the full topic

More Databases & SQL topics

Start free on Cariara · Coding problems · System design studio