skip to content

SELECT and Filtering

The core of every query: the SELECT list, WHERE predicates, NULL and its three-valued logic, DISTINCT, CASE, ORDER BY, LIMIT and OFFSET, and the set operations. Interviewers start here because most wrong answers come from NULL handling or from assuming clauses evaluate in the order you typed them.

part ofSQLoverview, primer and where to startread it →
on this pageshow

questions

page 2 of 2

How does SQL compare two character strings with = and <, and what varies by engine?

level: middleimportance: should knowfreq 40%

basics

~20 s

Character comparison follows the collation in effect, not numeric value: the collation decides case sensitivity, accent handling and sort order. So '10' < '9' is true because '1' sorts before '9', and whether 'ANNA' = 'anna' holds depends on the collation.

open as a page

What does SELECT DISTINCT country FROM users return when four rows have a NULL country?

level: middleimportance: should knowfreq 50%

basics

~20 s

All four NULL rows collapse into a single row whose country is NULL. Duplicate elimination treats two NULLs as the same value, so the result is one NULL row plus one row per distinct non-null country.

open as a page

Why does SELECT DISTINCT city FROM users ORDER BY created_at raise an error?

level: middleimportance: should knowfreq 42%

basics

~20 s

With SELECT DISTINCT, ORDER BY may only sort by expressions that appear in the select list. After deduplication one city row stands for many users with different created_at values, so that sort key no longer has a single well-defined value.

open as a page

Is the SQL LIKE predicate case-sensitive, and what actually decides that?

level: middleimportance: should knowfreq 50%

basics

~20 s

LIKE itself decides nothing about case. The comparison follows the collation of the strings involved, and engines ship different defaults, so the same LIKE query can be case-sensitive on one database and not on another.

open as a page

How do you make LIKE match a literal % or _ character in SQL?

level: middleimportance: should knowfreq 55%

basics

~20 s

Nominate an escape character with the ESCAPE clause and put it in front of the wildcard you want taken literally, as in code LIKE '%!_%' ESCAPE '!'. Standard SQL defines no default escape character, so always declare one.

open as a page

How do you write row limiting in standard SQL instead of LIMIT and OFFSET?

level: middleimportance: should knowfreq 45%

basics

~20 s

Standard SQL writes the slice as OFFSET n ROWS FETCH NEXT m ROWS ONLY, placed after ORDER BY. LIMIT is a widely implemented extension, not the ISO spelling; FIRST and NEXT, and ROW and ROWS, are interchangeable.

open as a page

In SQL, how do you compare two nullable columns so that two NULLs count as equal?

level: middleimportance: should knowfreq 42%

basics

~20 s

Use the standard NULL-safe comparison IS NOT DISTINCT FROM, which returns TRUE when both sides are NULL and never yields UNKNOWN. Where an engine lacks it, write a = b OR (a IS NULL AND b IS NULL).

open as a page

Where do NULLs sort in an ORDER BY, and how do you control their placement portably?

level: middleimportance: should knowfreq 64%

basics

~20 s

The standard leaves it implementation-defined: an engine treats NULLs as either all-highest or all-lowest, so they cluster at one end. NULLS FIRST or NULLS LAST on a sort key states it explicitly; where the engine lacks that clause, sort by a CASE flag first.

open as a page

Can ORDER BY sort by an expression or by a select-list position such as ORDER BY 2?

level: middleimportance: should knowfreq 48%

basics

~20 s

Yes to both. ORDER BY accepts any expression over the row, including one the query does not return, and an integer literal that refers to the nth column of the select list. Ordinals are brittle: editing the SELECT list silently changes the sort.

open as a page

How do you derive a year column and a due date from order_date in the SELECT list?

level: middleimportance: should knowfreq 46%

basics

~20 s

Standard SQL uses EXTRACT(YEAR FROM order_date) for a date part and interval arithmetic such as order_date + INTERVAL '30' DAY for a derived date. Both spellings are dialect-sensitive: SQL Server uses DATEPART and DATEADD instead.

open as a page

What exactly does SELECT * expand to, and what happens when two joined tables share a column name?

level: middleimportance: should knowfreq 58%

basics

~20 s

SELECT * expands to every column of every table in the FROM clause, in FROM order and then table-definition order. Joined tables that share a name yield two result columns with the same name, which breaks name-based client access.

open as a page

How do you build a full-name column from first_name and last_name, and how portable is that expression?

level: middleimportance: should knowfreq 50%

basics

~20 s

Standard SQL concatenates with the || operator: first_name || ' ' || last_name. A NULL operand makes the whole result NULL, so wrap parts in COALESCE. SQL Server uses + or CONCAT, and MySQL treats || as OR by default.

open as a page

Does UNION treat two rows containing NULL as duplicates, given NULL = NULL is unknown?

level: middleimportance: should knowfreq 38%

basics

~20 s

Yes. Duplicate elimination in UNION, INTERSECT and EXCEPT compares rows with NULLs treated as equal, so two rows that are NULL in the same column collapse into one — unlike the = operator, which yields UNKNOWN for NULL = NULL.

open as a page

Where can ORDER BY appear in a UNION query, and what does it sort?

level: middleimportance: should knowfreq 50%

basics

~20 s

One ORDER BY may appear at the very end of the statement, and it sorts the whole combined result rather than an individual branch. It can reference only the result's column names, taken from the first branch, or ordinal positions.

open as a page

Why can dynamically composed AND/OR filter fragments leak rows, and how do you compose them safely?

level: seniorimportance: should knowfreq 38%

basics

~20 s

AND binds tighter than OR, so an unparenthesized OR fragment escapes the conditions concatenated before it — including tenant or ownership scoping. Wrap every generated fragment in its own parentheses and join fragments with AND.

open as a page

Why is adding SELECT DISTINCT to a join that returns duplicate rows a fragile fix?

level: seniorimportance: should knowfreq 52%

basics

~20 s

DISTINCT only collapses rows that match in every selected column, so a one-to-many join's duplicates reappear the moment you select any column from the many side. It hides a wrong join grain rather than correcting it.

open as a page

An application builds WHERE id IN (...) with 20,000 literal ids. What breaks, and how would you rewrite it?

level: seniorimportance: should knowfreq 34%

basics

~20 s

Very large literal lists hit statement-size and bind-parameter limits, and every different list length is a different statement text the engine must parse afresh. Stage the ids as a set the query can join or test against, or send them in bounded batches.

open as a page

Users paging with LIMIT and OFFSET see the same row on two pages — why?

level: seniorimportance: should knowfreq 50%

basics

~20 s

OFFSET counts positions in a result recomputed from scratch for every request. Rows inserted ahead of the offset between requests push everything later, so a row already shown reappears on the next page; deletions shift rows earlier and hide them entirely.

open as a page

Does SQL's logical clause order describe how the engine actually executes the query?

level: seniorimportance: should knowfreq 48%

basics

~20 s

No. The logical order defines what a query means; it is an as-if rule. An engine may do the work in any order, with any algorithm, or skip it entirely, as long as the rows returned match what the logical order specifies.

open as a page

Why don't the counts from status = 'active' and status <> 'active' add up to the table total?

level: seniorimportance: should knowfreq 47%

basics

~10 s

Rows with a NULL status make both predicates UNKNOWN, and WHERE keeps only TRUE, so those rows fall out of both buckets. A predicate and its negation are not exhaustive over a nullable column.

open as a page

What does WHERE (dept_id, grade) IN ((1,'A'),(2,'B')) match, and how does it differ from two IN lists?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

That is a row-value IN predicate: it matches only the exact pairs (1,'A') and (2,'B'). Two separate IN lists on dept_id and grade would form the cross product and also match (1,'B') and (2,'A'). Engine support varies.

open as a page

What does FETCH FIRST 10 ROWS WITH TIES return that FETCH FIRST 10 ROWS ONLY does not?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

WITH TIES also returns every further row whose ORDER BY key equals the tenth row's, so the result can exceed ten rows. ONLY stops at exactly ten. WITH TIES requires an ORDER BY, since peers are defined by the sort key.

open as a page

What does NULLIF(x, 0) return, and why is it the portable division-by-zero guard?

level: middleimportance: nice to knowfreq 33%

basics

~10 s

NULLIF(x, 0) returns NULL when x equals 0 and x otherwise. Dividing by it turns a would-be division-by-zero error into a NULL result, since any arithmetic with a NULL operand yields NULL.

open as a page

Does an ORDER BY inside a derived table, CTE or view fix the outer query's row order?

level: middleimportance: nice to knowfreq 33%

basics

~20 s

No. A subquery, CTE or view yields a table, and a table has no order, so only the statement's outermost ORDER BY constrains the result. An inner ORDER BY is at best ignored and some engines reject it outright.

open as a page

What does ORDER BY resolve to when a SELECT alias reuses an existing column's name?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

A bare name in ORDER BY resolves to the select-list alias first, while WHERE and GROUP BY see only input columns, so one identifier can mean two different things in a single statement. Qualify the base column, or do not reuse the name.

open as a page

What determines the data type of a CASE expression whose branches return different types?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

A CASE yields one value of one type, so the engine derives a single result type from all THEN and ELSE results. Branches must be type-compatible; unrelated types such as text and timestamp are a type error in strictly typed engines.

open as a page

In WHERE name LIKE '%'||:term||'%', what breaks when the user's term contains % or _?

level: seniorimportance: nice to knowfreq 40%

basics

~20 s

The user's own characters are still pattern metacharacters, so the filter silently over-matches: a term of _ matches every non-empty value. Escape the term's %, _ and escape character before concatenating, and declare an ESCAPE character.

open as a page

Why can a query still fail with division by zero when WHERE excludes the zero rows?

level: seniorimportance: nice to knowfreq 33%

basics

~20 s

The logical clause order defines which rows come back, not which expressions get evaluated. An engine may compute a select-list expression for rows a filter would have removed, so guard the arithmetic itself with NULLIF or CASE.

open as a page

Why can the SELECT-list expression price * quantity * 1.08 return unexpected decimals, and how should money arithmetic be written?

level: seniorimportance: nice to knowfreq 36%

basics

~20 s

Multiplying exact numerics adds their scales, so a two-decimal price times a two-decimal rate yields four decimals; if the columns are binary floating point instead, the value is inexact from the start. Use DECIMAL columns and round once, deliberately.

open as a page

In a query mixing UNION, INTERSECT and EXCEPT, which operator is evaluated first?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

INTERSECT binds more tightly than UNION and EXCEPT, which have equal precedence and associate left to right. Because engines have not always agreed on this, parenthesize any query that mixes set operators rather than relying on the default.

open as a page

showing 31–60 of 60