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 pageshowhide
explore
- Logical Clause Evaluation Order4 questions
- SELECT List and Column Expressions6 questions
- Comparison and Boolean Predicates5 questions
- IN and BETWEEN Predicates5 questions
- LIKE and Pattern Matching4 questions
- NULL and Three-Valued Logic6 questions
- DISTINCT Semantics4 questions
- CASE Expressions6 questions
- ORDER BY and Sorting Semantics5 questions
- LIMIT, FETCH FIRST and OFFSET5 questions
- Set Operations: UNION, INTERSECT, EXCEPT6 questions
- Aliases and Scoping Rules4 questions
- AI & Data Scientistrole
- AI Engineerrole
- BI Analystrole
- Backend Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- Full Stack Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- SQLskill
questions
page 2 of 2How does SQL compare two character strings with = and <, and what varies by engine?
basics
~20 sCharacter 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.
What does SELECT DISTINCT country FROM users return when four rows have a NULL country?
basics
~20 sAll 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.
Why does SELECT DISTINCT city FROM users ORDER BY created_at raise an error?
basics
~20 sWith 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.
Is the SQL LIKE predicate case-sensitive, and what actually decides that?
basics
~20 sLIKE 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.
How do you make LIKE match a literal % or _ character in SQL?
basics
~20 sNominate 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.
How do you write row limiting in standard SQL instead of LIMIT and OFFSET?
basics
~20 sStandard 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.
In SQL, how do you compare two nullable columns so that two NULLs count as equal?
basics
~20 sUse 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).
Where do NULLs sort in an ORDER BY, and how do you control their placement portably?
basics
~20 sThe 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.
Can ORDER BY sort by an expression or by a select-list position such as ORDER BY 2?
basics
~20 sYes 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.
How do you derive a year column and a due date from order_date in the SELECT list?
basics
~20 sStandard 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.
What exactly does SELECT * expand to, and what happens when two joined tables share a column name?
basics
~20 sSELECT * 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.
How do you build a full-name column from first_name and last_name, and how portable is that expression?
basics
~20 sStandard 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.
Does UNION treat two rows containing NULL as duplicates, given NULL = NULL is unknown?
basics
~20 sYes. 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.
Where can ORDER BY appear in a UNION query, and what does it sort?
basics
~20 sOne 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.
Why can dynamically composed AND/OR filter fragments leak rows, and how do you compose them safely?
basics
~20 sAND 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.
Why is adding SELECT DISTINCT to a join that returns duplicate rows a fragile fix?
basics
~20 sDISTINCT 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.
An application builds WHERE id IN (...) with 20,000 literal ids. What breaks, and how would you rewrite it?
basics
~20 sVery 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.
Users paging with LIMIT and OFFSET see the same row on two pages — why?
basics
~20 sOFFSET 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.
Does SQL's logical clause order describe how the engine actually executes the query?
basics
~20 sNo. 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.
Why don't the counts from status = 'active' and status <> 'active' add up to the table total?
basics
~10 sRows 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.
What does WHERE (dept_id, grade) IN ((1,'A'),(2,'B')) match, and how does it differ from two IN lists?
basics
~20 sThat 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.
What does FETCH FIRST 10 ROWS WITH TIES return that FETCH FIRST 10 ROWS ONLY does not?
basics
~20 sWITH 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.
What does NULLIF(x, 0) return, and why is it the portable division-by-zero guard?
basics
~10 sNULLIF(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.
Does an ORDER BY inside a derived table, CTE or view fix the outer query's row order?
basics
~20 sNo. 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.
What does ORDER BY resolve to when a SELECT alias reuses an existing column's name?
basics
~20 sA 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.
What determines the data type of a CASE expression whose branches return different types?
basics
~20 sA 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.
In WHERE name LIKE '%'||:term||'%', what breaks when the user's term contains % or _?
basics
~20 sThe 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.
Why can a query still fail with division by zero when WHERE excludes the zero rows?
basics
~20 sThe 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.
Why can the SELECT-list expression price * quantity * 1.08 return unexpected decimals, and how should money arithmetic be written?
basics
~20 sMultiplying 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.
In a query mixing UNION, INTERSECT and EXCEPT, which operator is evaluated first?
basics
~20 sINTERSECT 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.
showing 31–60 of 60