Interview Q&A · SQL · 14 questions in this topic

Filtering: WHERE in Depth — SQL Interview Q&A

All SQL topics

Precise row selection — comparisons, LIKE, IN, BETWEEN, NULL checks and three-valued logic. Part of SELECT & Filtering · 192 questions in the SQL bank.

How does WHERE filter rows? What can it reference?

Answer

WHERE keeps rows where its predicate is TRUE (not FALSE, not UNKNOWN) and runs before SELECT — so it sees base columns and expressions over them, but not SELECT aliases or aggregates. One table predicate per concern, combined with AND/OR/NOT, beats clever mega-conditions.

Sargability matters: WHERE salary * 12 > x defeats indexes where WHERE salary > x / 12 does not.

Example

Example.sqlsql
SELECT name FROM employees
WHERE department = 'Engineering' AND salary > 70000;

💡 TRUE-only plus runs-before-SELECT explains nearly every WHERE error.

How do AND, OR, NOT combine, and why do parentheses matter?

Answer

Precedence: NOT, then AND, then OR. So a AND b OR c parses as (a AND b) OR c — mixing without parens silently widens/narrows the filter. Parenthesize mixed logic explicitly; -style review rules flag bare AND/OR mixes.

De Morgan helps invert: NOT (a AND b) is (NOT a) OR (NOT b).

Example

Example.sqlsql
-- intended: Engineering seniors OR any manager
SELECT * FROM employees
WHERE (department = 'Engineering' AND salary > 90000)
   OR title = 'Manager';

How does LIKE pattern matching work (% and _)?

Answer

% matches any run (including empty), _ matches exactly one character. LIKE is case-sensitive in PostgreSQL (ILIKE for insensitive) and case-insensitive in MySQL default collations — a classic portability trap. Leading % (LIKE '%x') defeats B-tree indexes; full-text/trigram indexes serve substring search.

Escape literals with ESCAPE when patterns contain % or _ themselves.

Example

Example.sqlsql
SELECT name FROM employees WHERE name LIKE 'A%';   -- starts with A
SELECT name FROM employees WHERE name LIKE '%son';  -- ends with son (slow)

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits