A SELECT query describes the result, not the steps, and its parts are written in a fixed order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Apart from SELECT and, usually, FROM, every part is optional. In autotests, columns are listed explicitly instead of an asterisk and read by name, so a migration does not break the test, and string values go in single quotes.
SQL · SELECT and WHERE
An autotest read a field by column position and started failing after a migration. The query "did not change": what went wrong?
An autotest runs SELECT * FROM users WHERE … and takes the phone as the third value of the row. Everything is green for a week, then a migration adds a column before phone and the test compares a phone with a timestamp. The test code and the query text did not change, the table did. This lesson covers the parts a SELECT consists of, what each one does and why the "handy asterisk" stops being handy exactly in autotests.
How it works and why. SELECT does not describe steps, it describes a result: "give me the rows of the table that satisfy the condition, and these columns". How to find those rows is up to the database planner. That is why the language is strict about grammar: the parts of a query go in a fixed order and each answers its own question. The written order is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Every part except SELECT and FROM is optional (in PostgreSQL even FROM can be omitted: SELECT 1, SELECT now()), but you cannot swap them: WHERE before FROM is a syntax error.
The parts of a query in written order
Figure 1. The highlighted parts are needed in almost every query. The written order is not the execution order, which is covered in the next lesson.
The list after SELECT is not only column names. It can hold expressions (amount * 0.25), function calls (lower(email)), literals and aliases via AS. An alias only names the result column: it does not create a column in the table. The asterisk * expands to all columns of the table in the order they currently have in the schema. That order is what broke the test from the introduction.
Example: from SELECT * to explicit columns.
-- the test reads a value by column positionSELECT * FROM users WHERE country = 'PL';
-- row[2] was phone; after a migration the column order changed
The query is valid and even returns the right rows, but the test depends on the shape of a table it does not control. There are two more hidden problems: * pulls all columns (including large text and service ones), and without ORDER BY the first row can be any row. The fixed version:
-- explicit columns, a stable order and a limitSELECT id, email, phone
FROM users
WHERE country = 'PL'ORDERBY id
LIMIT5;
Asterisk or explicit columns
In a test
SELECT *
The shape of the result depends on the schema. A new column or a different order breaks access by position, extra data travels over the network.
In a test
id, email, phone
The result is described in the query itself. A migration that adds a column does not touch it, and a removed column gives a clear error.
Figure 2. For manual exploration the asterisk is fine. For code that someone will maintain, list the columns.
Limits and alternatives. Two more things trip people up at the start. String values take single quotes: 'PL'. Double quotes in standard SQL and in PostgreSQL mean an identifier (a column or table name), so "PL" is read as a column:
SELECT email FROM users WHERE country = "PL";
-- PostgreSQL: ERROR: column "PL" does not exist (shortened)-- a string takes single quotes: country = 'PL'
In MySQL, double quotes work as a string by default, which hides this error, and backticks serve for names; in ANSI_QUOTES mode the behaviour matches the standard. The second thing: keywords are case-insensitive, and PostgreSQL folds an unquoted name to lower case, so Users and users are the same table while "Users" is a different one. Limiting the row count also depends on the dialect: LIMIT n in PostgreSQL, MySQL and SQLite, TOP n in SQL Server, and the standard FETCH FIRST n ROWS ONLY in PostgreSQL and Oracle 12c+.
Common mistakes.
SELECT * in autotests and reports: the test depends on the schema.
Reading a result by column position instead of by name.
A string in double quotes: a "column does not exist" error, or a silently different meaning in MySQL.
A query without ORDER BY assuming "the first row is the oldest".
Exploring a large table without LIMIT on a shared environment.
Check yourself
Why is SELECT * convenient in DBeaver or psql but risky in an autotest?
Answer
By hand you see all columns and notice a new one yourself. In a test the result is read by code: when the schema changes (a column is added, renamed or reordered), access by position or the expected object shape breaks without any change in the test code. The asterisk also pulls extra data.
In PostgreSQL the query SELECT email FROM users WHERE country = "PL" fails. What should be fixed?
Answer
Replace the double quotes with single ones: 'PL'. In double quotes PostgreSQL sees an identifier and looks for a column named PL, which does not exist.
Can you write WHERE before FROM if the condition is simple?
Answer
No. The order of the written parts is fixed by the grammar: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Otherwise you get a syntax error. The actual execution order is different, the next lesson covers it.
Related lessons: “In what order is a query actually executed?”, “Which operators are used in WHERE?”, “How do ORDER BY and LIMIT work?”.
In an interview.Junior: A query starts with SELECT and a list of columns, then FROM with a table, then if needed WHERE for a filter, GROUP BY and HAVING for groups, ORDER BY for sorting and LIMIT to cap the count. For quick exploration I write SELECT asterisk, and in autotests I list the columns explicitly. Middle/Senior: SELECT describes a result, not steps, so the written order is fixed and differs from the execution order. In autotests I take only the needed columns and read them by name so a migration does not break the test. I watch the dialect: quotes for strings versus identifiers, LIMIT versus TOP versus FETCH FIRST, and I always add ORDER BY when I compare a result with an expectation.
In what order is a query actually executed?
A query is processed in a logical order: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. Each step sees only the result of the earlier ones, so an alias from SELECT is visible in ORDER BY but not in WHERE, and a condition on an aggregate goes in HAVING. This is a model, not the literal plan: the planner chooses the physical order.
SQL · SELECT and WHERE
The same alias fails in WHERE and works in ORDER BY. Why does SQL not read a query the way it is written?
You compute an amount in dollars, name it amount_usd and immediately filter WHERE amount_usd > 100. The database says there is no such column, although it was just written in SELECT. The next line with the same alias in ORDER BY works. This lesson explains the logical order in which a query is processed: it answers "why is the alias visible here but not there" and "why can an aggregate not go in WHERE".
How it works and why. The SQL standard defines a query as a pipeline in which each step takes a table and returns a table. The next step sees only what the earlier ones created. The order is: FROM and JOIN build rows, WHERE drops rows, GROUP BY merges them into groups, HAVING drops groups, SELECT computes expressions and sets aliases, DISTINCT removes duplicates, ORDER BY sorts, LIMIT with OFFSET cut. Window functions (OVER) are computed between HAVING and the final SELECT, so they cannot go in WHERE either.
The logical processing order
Figure 1. The alias appears at step 5, so WHERE (step 2) does not see it and ORDER BY (step 7) does.
This is a logical model, not what the server literally does. The planner freely changes the physical steps: it pushes a filter before a JOIN, uses an index, sorts by an index. It is only obliged to return the same result as if the steps ran in the logical order. For a tester the model is useful twice: it explains query errors and tells where to put a condition so that it means what you need.
Example: from an error to a working query.
-- an illustrative rate of 0.25; the alias does not exist in WHERE yetSELECT amount * 0.25AS amount_usd
FROM transactions
WHERE amount_usd > 100;
-- PostgreSQL: ERROR: column "amount_usd" does not exist
Step 2 (WHERE) runs before step 5 (SELECT), where amount_usd is born, so the name does not exist in WHERE yet. There are two ways out:
-- option 1: repeat the expressionSELECT amount * 0.25AS amount_usd
FROM transactions
WHERE amount * 0.25 > 100ORDERBY amount_usd DESC; -- the alias is visible here-- option 2: compute in a subquery and filter outsideSELECT *
FROM (SELECT id, amount * 0.25AS amount_usd FROM transactions) x
WHERE amount_usd > 100;
The same goes for aggregates. A sum exists only after grouping (step 3), and WHERE works at step 2, so a condition on an aggregate is written in HAVING:
-- an aggregate in WHERE: rows are not grouped yetSELECT user_id FROM transactions
WHERESUM(amount) > 1000GROUPBY user_id;
-- PostgreSQL: ERROR: aggregate functions are not allowed in WHERESELECT user_id FROM transactions
GROUPBY user_id
HAVINGSUM(amount) > 1000;
Where to put the condition
step 2
WHERE
A filter on individual rows before grouping. Sees no aggregates and no aliases. Shrinks the input of GROUP BY, so it is usually faster.
step 4
HAVING
A filter on groups after grouping. Sees aggregates (SUM, COUNT). A condition on a plain column is better not placed here.
Figure 2. A condition that does not need an aggregate belongs in WHERE: rows are dropped before they are grouped.
Reading the error: an alias in WHERE
1ERROR: column "amount_usd" does not exist
LINE 3: WHERE amount_usd > 100;
^ 2
What: the database looks for a column amount_usd in the table and does not find it. The alias appears at the SELECT step, and WHERE runs earlier.
Where:LINE 3 and ^ point at the name in the WHERE condition, not at the place where the alias is defined.
What to do
Repeat the expression in WHERE or compute it in a subquery and filter outside. There is no need to add a column to the table.
Figure 3. The PostgreSQL error text (shortened) for the query in the example.
Limits and alternatives. Dialects relax the rules in different ways, and you should not rely on it. PostgreSQL and MySQL allow an alias in GROUP BY, MySQL also in HAVING, SQL Server accepts an alias only in ORDER BY. Even where an alias is allowed in ORDER BY, it has to be a standalone name: in PostgreSQL ORDER BY amount_usd works while ORDER BY amount_usd + 1 does not, you must repeat the expression. If you need an alias in a filter, the reliable path is a subquery or a CTE (WITH), as in option 2. For conditions around a LEFT JOIN the order matters even more: a condition in ON works at step 1 and in WHERE at step 2, and the results differ (a separate lesson covers it). The real execution plan (it differs from the logical one) is shown by EXPLAIN.
Common mistakes.
A SELECT alias in WHERE: "column does not exist".
An aggregate in WHERE instead of HAVING: "aggregate functions are not allowed in WHERE".
A condition on a grouping column in HAVING: it works but drops less before grouping and reads confusingly.
Assuming the server runs the query in written order or literally in logical order: it is a model of meaning, not a plan.
Relying on an alias in GROUP BY or HAVING because "it works in MySQL": another database will fail the query.
Check yourself
Why is a SELECT alias visible in ORDER BY but not in WHERE?
Answer
ORDER BY runs after SELECT (step 7 versus step 5), when the alias already exists. WHERE runs at step 2, before SELECT, so the alias is not there yet.
How do you keep only users whose transactions sum to more than 1000?
Answer
Group by user_id and put the condition on the aggregate in HAVING: GROUP BY user_id HAVING SUM(amount) > 1000. An aggregate does not work in WHERE because the groups do not exist at that stage.
A query with GROUP BY user_id has WHERE status = 'completed' and HAVING SUM(amount) > 500. In what order are they applied?
Answer
First WHERE drops the rows that are not completed, then they are grouped, then HAVING drops the groups where the sum of the completed ones is below 500. Simply moving the status condition into HAVING does not work: status is not in GROUP BY, so PostgreSQL rejects the query. A condition on rows belongs in WHERE.
Related lessons: “How is a SELECT query structured?”, “How does WHERE differ from HAVING?”, “What is the difference between a condition in ON and in WHERE with a LEFT JOIN?”, “What is EXPLAIN and how do you use it?”.
In an interview.Junior: FROM and JOIN run first, then WHERE, GROUP BY, HAVING, and only then SELECT, ORDER BY and LIMIT. That is why a SELECT alias cannot be used in WHERE but can be in ORDER BY, and why aggregates are filtered through HAVING. Middle/Senior: It is the logical order from the standard: each step sees only the result of the previous ones. The physical order is chosen by the planner and visible in EXPLAIN, but the result must match the logical model. If I need an alias in a filter, I move the computation into a subquery or a CTE instead of relying on one database's extension.
Which operators are used in WHERE?
WHERE uses comparisons, AND, OR, NOT, IN, BETWEEN, LIKE and IS NULL, and only rows where the condition is true reach the result. Precedence is NOT first, then AND, then OR, so mixed AND and OR are put in parentheses. A precedence mistake raises no error; it shows only on data where every branch of the condition has its own row.
SQL · SELECT and WHERE
A query for failed deposits and withdrawals also returned a successful deposit. It looks like a database bug, but it is not.
A report must show failed transactions of two types: deposit and withdrawal. The query is written the way it sounds in words and it returns rows with status completed. The database is not wrong: it did exactly what was written. This lesson is about the WHERE operators and one precedence rule that separates "what I meant" from "what I wrote".
How it works and why.WHERE is a predicate checked for every row. A row reaches the result only if the predicate is true. False and unknown (when a comparison involves NULL) rows are dropped the same way. A predicate is built from these groups of operators:
Group
Operators
Nuance
Comparison
=<>!=><>=<=
<> is standard, != is supported by the main databases. With NULL they give unknown, not true or false.
Logical
NOTANDOR
In priority order: NOT, then AND, then OR.
List and range
INBETWEEN
IN replaces a chain of OR, BETWEEN includes both bounds. A separate lesson.
Pattern
LIKEILIKE
ILIKE is not standard, it is a PostgreSQL extension. A separate lesson.
NULL
IS NULLIS NOT NULLIS DISTINCT FROM
The only correct way to test for an empty value.
Complex conditions are assembled from AND, OR and NOT, and the language has precedence: first NOT, then AND, then OR. It is the same logic as in arithmetic: multiplication before addition. In the phrase "deposit or withdrawal, and failed" the words do not show what "failed" refers to. SQL parses without hints: AND binds tighter, so status = 'failed' attaches only to withdrawal.
Example: an extra row in the report. The transactions table has five rows: failed and successful deposits and withdrawals plus one failed transfer. The goal is to get rows 1 and 3.
-- intended: failed deposit or withdrawalSELECT id, type, status
FROM transactions
WHERE type = 'deposit'OR type = 'withdrawal'AND status = 'failed';
-- is read as: deposit OR (withdrawal AND failed)
The same query without and with parentheses
without parentheses
id
type
status
1
deposit
failed
2
deposit
completed extra
3
withdrawal
failed
with parentheses
id
type
status
1
deposit
failed
3
withdrawal
failed
Figure 1. Without parentheses every deposit reaches the result regardless of status, so row 2 is extra.
The query produced no error and returned "plausible" data, and the problem can be found only by comparing with the expected result. The fix is parentheses or IN, which removes the ambiguity itself:
SELECT id, type, status
FROM transactions
WHERE (type = 'deposit'OR type = 'withdrawal') AND status = 'failed';
-- the same, shorter, with no parentheses neededSELECT id, type, status
FROM transactions
WHERE type IN ('deposit', 'withdrawal') AND status = 'failed';
How to check that a condition does what was intended. Build a minimal data set with one row for each combination: a type from the condition and one outside it, a status from the condition and one outside it. Here that is 2 × 2 plus a foreign type. A query with the right condition returns exactly rows 1 and 3, and an error in the logic gives a different set. Compare ids, not only the count: a condition with status <> 'failed' also returns 2 rows. You do not need a big database: you need one where each branch of the condition has "its own" row.
Limits and alternatives. Parentheses cost nothing, so in mixed AND and OR you always add them, even when the precedence matches the intent: the next reader will not have to guess. NOT also binds only to the nearest predicate: NOT a = 1 AND b = 2 means (NOT a = 1) AND b = 2. For several values of one column IN is shorter and safer than a chain of OR. A separate trap is string comparison: in PostgreSQL 'Failed' = 'failed' is false, while in MySQL with a typical collation (for example utf8mb4_0900_ai_ci in MySQL 8) such a comparison is case-insensitive, so the same test can behave differently across databases. Comparing a number with a string also depends on the database: PostgreSQL casts the literal '5' to a number, but comparing a text column with a number gives a type error. Conditions with NULL are covered separately in the IS NULL lesson.
Common mistakes.
OR together with AND without parentheses: the condition reads differently from how it sounds.
A condition on a date or string checked only on "good" values: the branches of the condition did not get their own rows.
A chain of OR on one column instead of IN.
Comparing with NULL through = or <>.
Moving a query between databases without checking case and types in comparisons.
Check yourself
How will SQL read WHERE a = 1 OR b = 2 AND c = 3?
Answer
As a = 1 OR (b = 2 AND c = 3): AND has higher precedence than OR. If you meant (a = 1 OR b = 2) AND c = 3, you need parentheses.
What minimal test data is needed to find an error in the condition (type IN (...)) AND status = 'failed'?
Answer
A row for each combination: a type from the condition and one outside it, status failed and not failed. Then the right condition returns exactly the intended rows, and a missing parenthesis or AND gives an extra or a missing row, visible in the set of ids.
Why does a query with a precedence mistake not fail with an error?
Answer
It is syntactically valid and has clear semantics, just not the ones the author meant. The database does not know the intent, so the error shows only by comparing the result with the expectation.
Related lessons: “How do IN, BETWEEN and LIKE work?”, “How do you find rows where the value is NULL?”, “In what order is a query actually executed?”.
In an interview.Junior: In WHERE I use comparisons, the logical AND, OR, NOT, and also IN, BETWEEN, LIKE and IS NULL. The main trap is precedence: AND runs before OR, so when I combine them I add parentheses. Middle/Senior: WHERE keeps rows where the predicate is true, and false and unknown ones are dropped. A query with a precedence mistake is valid and plausible, so it is invisible without a check on data where each branch of the condition has its own row. For several values I choose IN, I always add parentheses and I remember the differences in case and types between databases.
How do IN, BETWEEN and LIKE work?
IN checks a match against a list, BETWEEN sets a range with both bounds included, and LIKE searches by pattern (% is any characters, _ is one). Traps: BETWEEN on a timestamp cuts off the last day, so a half-open interval is used; NOT IN with a NULL in the list returns zero rows; LIKE is case-sensitive in PostgreSQL, and a pattern with a leading % usually cannot use a regular index.
SQL · SELECT and WHERE
The September report does not show transactions from 30 September. The data is there and the range is "inclusive". Where did they go?
The September report is written with BETWEEN '2026-09-01' AND '2026-09-30'. A transaction from 30 September at 14:20 is in the database and not in the report, and nobody notices because the total is just slightly lower. This lesson covers three operators that look simple: IN, BETWEEN and LIKE, and each has its own trap.
How it works and why. All three are shorthands for conditions you could write by hand, and that makes their behaviour clear.
IN checks a match against a list: status IN ('pending', 'failed') is the same as status = 'pending' OR status = 'failed'. Two conclusions follow: a comparison with a NULL in the list also gives unknown, and NOT IN turns this into a trap (below).
BETWEEN a AND b is the same as >= a AND <= b: both bounds are included. If you swap them (BETWEEN 500 AND 100) the result is empty because the condition is impossible. PostgreSQL has BETWEEN SYMMETRIC for that case.
LIKE compares a string with a pattern: % is any number of characters (even zero), _ is exactly one character. Everything else is taken literally.
Pattern
Matches
Does not match
a%
a, ab, abc
ba
%@gmail.com
anna@gmail.com
anna@gmail.com.ua
a_c
abc, a1c
ac, abbc
100\%
100% (escaped %)
1000
Example: from BETWEEN to a half-open range. The created_at column is a time type. The literal '2026-09-30' compared with it means 2026-09-30 00:00:00, so everything that happened that day after midnight lies beyond the bound.
-- created_at is a timestamp; the row 2026-09-30 14:20 disappearsSELECT id, created_at
FROM transactions
WHERE created_at BETWEEN'2026-09-01'AND'2026-09-30';
What BETWEEN cuts off with dates
BETWEEN … AND 2026-09-30
id
created_at
1
09-01 00:00
2
09-15 10:05
3
09-30 14:20 lost
>= 09-01 AND < 10-01
id
created_at
1
09-01 00:00
2
09-15 10:05
3
09-30 14:20
Figure 1. A half-open range does not depend on whether the column has a time and does not need to know how many days the month has.
A half-open range fixes it: the start is included, the next day is excluded.
-- a half-open range: includes the start, excludes the next daySELECT id, created_at
FROM transactions
WHERE created_at >= '2026-09-01'AND created_at < '2026-10-01';
SELECT email FROM users WHERE email ILIKE '%@gmail.com';
-- ILIKE: a PostgreSQL extension; else lower(email) LIKE ...
The same applies to numbers with a fractional part: BETWEEN 0 AND 10 will not catch 10.5 but will catch 10, so choose the bounds deliberately.
Limits and alternatives. For timestamptz a literal without a time zone is taken in the current session's zone, so the month bound shifts with the client setting: a report run from another zone gives different numbers. That is why you set the bound explicitly ('2026-09-01 00:00+00') or agree on the session zone. See the lesson on dates and time zones. In LIKE case depends on the database: in PostgreSQL LIKE is case-sensitive and ILIKE is not; in MySQL the column's collation decides. A pattern with a leading % usually cannot use a regular index: the search scans the whole table (PostgreSQL has the pg_trgm extension for such cases). To find a literal % or _ you escape it: in PostgreSQL the default escape character is the backslash, and you can set another with ESCAPE. And about NOT IN:
SELECT * FROM transactions WHERE status IN ('pending', 'failed');
-- the same as-- status = 'pending' OR status = 'failed'SELECT * FROM transactions WHERE status NOTIN ('completed', NULL);
-- always 0 rows: a NULL in the list makes the condition unknown
The zero rows here come from the NULL in the list: status <> NULL is unknown for every row. The same trap appears when NOT IN takes values from a subquery that contains a NULL, and the lesson on NOT IN with a subquery covers it.
Common mistakes.
BETWEEN on a timestamp ending on "the 30th": the last day is cut off.
Swapped bounds BETWEEN 500 AND 100: an empty result.
_ in a pattern taken as an ordinary character: LIKE 'user_1' also finds userX1.
LIKE ignoring case in a database where it is case-sensitive: "no data".
NOT IN with a list or subquery that contains NULL.
Check yourself
Does amount BETWEEN 100 AND 500 include the values 100 and 500?
Answer
Yes, both bounds are included: it is amount >= 100 AND amount <= 500. If a bound must not be in the result, use separate >= and <.
A transaction was created at 2026-09-30 23:59 in a timestamp column. Will it get into WHERE created_at BETWEEN '2026-09-01' AND '2026-09-30'?
Answer
No. The literal '2026-09-30' means 2026-09-30 00:00:00, so anything later lies above the upper bound. The right way: created_at >= '2026-09-01' AND created_at < '2026-10-01'.
How do you find emails that contain a literal underscore?
Answer
Escape it: email LIKE '%\_%'. Without escaping the underscore means any single character and the condition matches almost everything.
Related lessons: “Which operators are used in WHERE?”, “How do you find rows where the value is NULL?”, “Why can NOT IN return zero rows?”, “What should you pay attention to when working with dates and time zones?”.
In an interview.Junior: IN checks membership in a list, BETWEEN is a range including both bounds, and LIKE searches by a pattern where percent is any number of characters and underscore is one character. I do not use BETWEEN with dates: instead I write "greater than or equal to the start and less than the next day". Middle/Senior: All three are shorthands for ordinary conditions, so their traps are predictable: BETWEEN includes the bounds and cuts the last day for a timestamp, NOT IN with a NULL gives an empty result, LIKE is case-sensitive in PostgreSQL and cannot use an index with a leading percent. I set period bounds as a half-open range and account for the time zone.
How do you find rows where the value is NULL?
Rows where the value is NULL are found with IS NULL, because a comparison with NULL always gives UNKNOWN. So WHERE phone = NULL returns zero rows without an error. The reverse trap: not-equal (<>) and NOT IN also drop rows with NULL, so they are added explicitly with OR IS NULL or IS DISTINCT FROM is used. COALESCE supplies a default value.
SQL · SELECT and WHERE
WHERE phone = NULL returned 0 rows although thousands of phones are empty. Did the database lie?
A tester looks for users without a phone: WHERE phone = NULL. The query runs without an error and returns zero rows. There are two conclusions: "there are no such users" (wrong) or "the database is broken" (also wrong). This lesson explains what NULL means in query logic, why a comparison with it is never true and where two reverse traps hide.
How it works and why. NULL means "the value is unknown or missing", not "zero" or "an empty string" (the type basics lesson covers the difference). That is why SQL uses three-valued logic: any comparison can give true, false or "unknown". A comparison with NULL always gives "unknown": asking whether an unknown value equals 5, or equals another unknown, has no answer. The WHERE filter keeps only true rows, so "unknown" is dropped just like false. The logical operators also work in three values:
Expression
Result
Why
NULL = NULL
unknown
unknown equals unknown: cannot tell
TRUE AND NULL
unknown
depends on the unknown
FALSE AND NULL
false
already known that AND cannot be true
TRUE OR NULL
true
already known that OR is true
NOT NULL
unknown
the negation of unknown stays unknown
For testing emptiness there are separate predicates that always answer true or false: IS NULL and IS NOT NULL. For a comparison "does the value differ, taking NULL into account" PostgreSQL has IS DISTINCT FROM (and MySQL's equivalent for equality is <=>).
SELECT * FROM users WHERE phone ISNULL; -- correctSELECT * FROM users WHERE phone = NULL; -- always 0 rows, no error
Example: a row that "disappeared". The second trap mirrors the first. The condition "status is not failed" looks like a full complement of "status is failed", but rows with a NULL status fall into neither selection: in the first the status is unknown, in the second as well.
A row with a NULL status vanishes from both sides
status <> 'failed'
id
status
1
completed
2
pending
3
NULLlost
IS DISTINCT FROM 'failed'
id
status
1
completed
2
pending
3
NULL
Figure 1. Row 4 with status failed is not shown: neither query returns it. Row 3 is returned only by the second.
The fix is to mention NULL explicitly or use IS DISTINCT FROM:
-- everything except failed, including NULLSELECT id, status FROM transactions
WHERE status ISDISTINCTFROM'failed';
-- the same without IS DISTINCT FROMSELECT id, status FROM transactions
WHERE status <> 'failed'OR status ISNULL;
Limits and alternatives. The same principle holds wherever a comparison appears. NOT (status = 'failed') is also unknown for NULL and is dropped. An operation on NULL gives NULL: NULL + 1, concatenation ('a' || NULL). To substitute a default there is COALESCE(x, 0) (the lesson on aggregates with NULL), and for the reverse NULLIF(a, b), which returns NULL when the values are equal. In some constructs NULL behaves "like a value": DISTINCT and GROUP BY treat all NULLs as the same and give one row or group. And the UNIQUE constraint in PostgreSQL allows several NULLs in a column because they are "not equal"; since PostgreSQL 15 this can be changed with UNIQUE NULLS NOT DISTINCT. This inconsistency exists: when checking a specific database, do not guess, check with a query. Also remember that an empty string and NULL are different values, except in Oracle, where an empty string is stored as NULL.
-- both NULL and an empty string can mean "empty"SELECT id FROM users
WHERE phone ISNULLOR phone = '';
-- protection against division by zero: NULLIF gives NULLSELECT total / NULLIF(items, 0) FROM orders;
Common mistakes.
= NULL or <> NULL instead of IS NULL and IS NOT NULL.
<> or NOT IN on a column that has NULLs: those rows silently disappear.
Searching for "empty" values only by NULL or only by ''.
Assuming UNIQUE forbids several NULLs (in PostgreSQL by default it does not).
Carrying a conclusion about NULL from one database to another (Oracle, empty string).
Check yourself
What does SELECT 1 WHERE NULL = NULL return?
Answer
Zero rows. NULL = NULL gives unknown, and WHERE keeps only true. To test for NULL you need IS NULL, and to compare taking NULL into account IS NOT DISTINCT FROM.
A table has 100 transactions: 20 failed, 70 completed, 10 with status NULL. How many does WHERE status <> 'failed' return?
Answer
70. The rows with NULL are dropped because the comparison gives unknown. To get 80 you need to add OR status IS NULL or write status IS DISTINCT FROM 'failed'.
Why should a tester look for empty fields both through IS NULL and through = ''?
Answer
Data can arrive by different paths: a form sends an empty string, an API a missing field. The column will hold both variants, and checking only one misses bugs. The correct application behaviour (what counts as empty) is clarified in the requirements.
Related lessons: “What is NULL and how does it differ from 0 and an empty string?”, “How do aggregates behave with NULL? What is COALESCE?”, “Why can NOT IN return zero rows?”, “Which operators are used in WHERE?”.
In an interview.Junior: I look for empty values only through IS NULL, because a comparison "equals NULL" always gives "unknown" and returns zero rows without an error. I remember the reverse trap too: a "not equal" condition also skips rows with NULL, so if they are needed I add OR IS NULL. Middle/Senior: SQL works in three-valued logic: a comparison with NULL is unknown and WHERE keeps only true. So NULL disappears from both sides of the pair "=" and "<>", and NOT IN with a NULL gives an empty result. For a safe comparison I use IS DISTINCT FROM, for defaults COALESCE, and I check UNIQUE specifics, the empty string and database differences with a query, not from memory.
What does DISTINCT do?
DISTINCT removes repeated rows from the finished result; uniqueness is counted over the whole combination of columns, and NULLs are treated as equal. A tester uses it to see the real set of values in a column, for example all statuses. Adding DISTINCT to hide row multiplication after a JOIN is a mistake: the cause remains. It is better to change the query (EXISTS or aggregate before the JOIN).
SQL · SELECT and WHERE
A report shows 120 users while the database has 85. Someone added DISTINCT and the numbers matched. Is that a fix?
A report on users with orders shows 120 rows although there are 85 users. A developer adds DISTINCT after SELECT, the number becomes 85 and the ticket is closed. But why was it 120 in the first place? This lesson explains what DISTINCT does, where a tester really needs it, and why "just add DISTINCT" often hides a bug instead of removing it.
How it works and why.DISTINCT runs after SELECT (step 6 in the logical order) and removes repeated rows from the finished result. Uniqueness is counted over the whole combination of columns in the list, not the first one: SELECT DISTINCT currency, status keeps one of each pair. For comparing values NULLs are treated as equal, so several rows with NULL merge into one. To do this the database has to find repeats: sort the result or build a hash table, so on large result sets it is not free.
SELECTDISTINCT country FROM users; -- the list of countriesSELECTDISTINCT currency, status FROM accounts; -- unique pairsSELECTCOUNT(DISTINCT user_id) FROM accounts; -- how many users have an account-- for exploration GROUP BY is better: the count is visible tooSELECT status, COUNT(*) AS n
FROM transactions
GROUPBY status
ORDERBY n DESC;
The standard case for a tester: see the set of real values of a column, for example all statuses that actually exist in the table. It is a quick way to notice a value missing from the documentation ('canceled' and 'cancelled' at the same time). The variant with GROUP BY and COUNT(*) also shows how rare each value is.
What DISTINCT does with a pair of columns
accounts (input)
id
currency
status
1
PLN
active
2
PLN
active dup
3
EUR
active
4
EUR
closed
5
PLN
active dup
DISTINCT currency, status
currency
status
PLN
active
EUR
active
EUR
closed
Figure 1. Uniqueness is by the pair: the pairs with ids 1, 2 and 5 are identical and one stays. The two different EUR pairs both stay.
Example: DISTINCT as a patch. A developer sees that users repeat after a JOIN and adds DISTINCT. The row count becomes right, but the cause remains: in a JOIN a user's row multiplies by the number of their orders (the lesson on row growth after a JOIN has the details). If the query has a sum, DISTINCT no longer saves it, because it was computed over the multiplied set. It is better to understand why there are too many rows and join through EXISTS or aggregate before the JOIN.
What to do about duplicates after a JOIN
Typical
add DISTINCT
The row count matched, but sums over the multiplied set stay wrong and the cause is hidden. The query is also slower.
Better
find the cause
Find out by which key the rows multiplied and fix the query: EXISTS instead of JOIN or an aggregate before the join.
Figure 2. DISTINCT is right when duplicates are expected and unimportant (a list of unique values), not to mask a mistake.
Limits and alternatives. PostgreSQL has DISTINCT ON (col): it keeps the first row for each value of col in ORDER BY order, which is handy for "the user's latest transaction". Other databases do it with the window function ROW_NUMBER() (the lesson on top N per group). COUNT(DISTINCT col) ignores NULL and counts unique values. DISTINCT and ORDER BY together have a restriction: in PostgreSQL the sort expressions must be in the SELECT list, otherwise it is an error. To merge two queries without duplicates there is UNION (unlike UNION ALL, which keeps repeats): the lesson on UNION covers the difference.
-- PostgreSQL: one row per user_id, the newest transactionSELECTDISTINCTON (user_id) user_id, id, created_at
FROM transactions
ORDERBY user_id, created_at DESC;
SELECTDISTINCT status FROM transactions ORDERBY created_at;
-- PostgreSQL: ERROR: for SELECT DISTINCT, ORDER BY expressions-- must appear in select list
Common mistakes.
DISTINCT to fix row multiplication after a JOIN: sums and query logic stay wrong.
Thinking DISTINCT a, b makes only a unique.
DISTINCT on a large table without need: extra sorting or hashing.
Expecting COUNT(DISTINCT col) to count NULL too.
Sorting by a column that is not in the SELECT DISTINCT list: an error in PostgreSQL.
Check yourself
What does SELECT DISTINCT currency, status return if the table has (PLN, active) three times and (EUR, active) once?
Answer
Two rows: (PLN, active) and (EUR, active). Uniqueness is counted by the pair, not by individual columns.
After a JOIN users repeat in a report and a colleague suggests adding DISTINCT. What do you check first?
Answer
Why the rows multiplied: by which key one user has several pairs. If the query has a sum or a counter, DISTINCT will not fix them. It is better to change the query (EXISTS or an aggregate before the JOIN) than to mask the duplicates.
How does COUNT(DISTINCT user_id) differ from COUNT(user_id)?
Answer
COUNT(user_id) counts all non-NULL values, repeats included. COUNT(DISTINCT user_id) counts only different values. Both ignore NULL.
Related lessons: “Why did the row count grow after a JOIN and the sum double?”, “How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?”, “How do you find the top N records in each group?”, “How does UNION differ from UNION ALL? What are INTERSECT and EXCEPT?”.
In an interview.Junior: DISTINCT removes duplicates from the result, and uniqueness is counted over the whole combination of columns. I use it to see the set of possible values, for example all statuses in a table: it is easy to notice a value that is not in the documentation. Middle/Senior: DISTINCT runs after SELECT and needs sorting or hashing, and it treats NULLs as equal. I do not use it to hide row multiplication after a JOIN: sums and logic stay wrong. For the latest record per group I take DISTINCT ON in PostgreSQL or ROW_NUMBER in other databases.
How do ORDER BY and LIMIT work?
ORDER BY is the only thing that defines row order: without it a table is a set, and LIMIT 1 returns an arbitrary row. LIMIT runs after sorting, and rows with an equal key come in arbitrary order, so a unique key goes at the end of the sort. NULL is placed differently (PostgreSQL treats it as greater than everything, MySQL as smaller), so its position is set explicitly.
SQL · SELECT and WHERE
A test takes the first record and fails once every few runs. Same data, same code. Where does the randomness come from?
An autotest checks "the user's latest transaction" and fails about once in ten runs. The database has the same data set and the query did not change. The cause is simple and sly: the query does not define an order and the database does not have to return rows the same way each time. This lesson covers ORDER BY and LIMIT: what they guarantee and what they do not.
How it works and why. In the relational model a table is a set of rows, not a list. The order in which SELECT returns them without ORDER BY depends on the execution plan, the physical layout and parallel scanning, and can change after an UPDATE or after the planner chooses another index. The standard promises nothing. ORDER BY sorts by one or several columns (ASC by default, DESC), and LIMIT (and OFFSET) runs after sorting: the first n rows of the sorted set are taken. So "LIMIT 1 without ORDER BY" means "one random row".
The second half of the guarantee is subtler: sorting defines an order only for different key values. Rows with the same value (two transactions with the same created_at) stand in an arbitrary order, and LIMIT 1 may take either of them. That is the source of the random failures. It is reliable only when the end of the sort list has a unique key.
-- no ORDER BY: the "first" transaction can be anySELECT id, amount FROM transactions LIMIT1;
-- ORDER BY exists but created_at repeats: the order of equal rows is undefinedSELECT id, amount FROM transactions
ORDERBY created_at DESCLIMIT1;
How much a query guarantees
Unstable
LIMIT 1 without ORDER BY, or with a non-unique key
Any row among those with a matching key. The test passes until the execution plan changes and then fails.
Stable
ORDER BY created_at DESC, id DESC
The unique id settles ties. The same data set always gives the same result.
Figure 1. For a "first record" test the order must be fully defined, otherwise the result is random.
Example: NULL in sorting. The second cause of instability between environments: where NULLs are placed. In PostgreSQL and Oracle NULL counts as larger than every value, so with ASC it comes last and with DESC first. In MySQL, SQL Server and SQLite it is the opposite: NULL is smaller than everything. A test that worked on PostgreSQL will change its order on another database.
The same ASC, different databases
PostgreSQL
id
balance
2
10
1
50
3
NULL
MySQL
id
balance
3
NULL
2
10
1
50
Figure 2. The same data and the same ORDER BY balance ASC. Set the NULL position explicitly: NULLS FIRST or NULLS LAST where it is supported.
The fixed query:
-- a unique second key makes the order stableSELECT id, amount
FROM transactions
ORDERBY created_at DESC, id DESCLIMIT10;
-- NULL explicitly: PostgreSQL, Oracle, SQLite 3.30+SELECT id, balance FROM accounts ORDERBY balance ASC NULLS LAST;
-- MySQL: ORDER BY balance IS NULL, balance-- SQL Server: ORDER BY CASE WHEN balance IS NULL-- THEN 1 ELSE 0 END, balance
Database
Row limit
NULL with ASC
PostgreSQL
LIMIT, FETCH FIRST
last
MySQL
LIMIT
first
SQL Server
TOP, OFFSET … FETCH
first
Oracle
FETCH FIRST (12c+)
last
SQLite
LIMIT
first
Limits and alternatives. Text sorting depends on the collation: the order of the letters "a", "B", "Z" and letters with diacritics differs between settings. And if a number is stored as text, '10' comes before '9': the sort is lexicographic. PostgreSQL's LIMIT has the standard synonym FETCH FIRST n ROWS ONLY, and FETCH FIRST n ROWS WITH TIES also returns the rows equal to the last one by key. In SQL Server OFFSET … FETCH requires ORDER BY. OFFSET k is expensive for large values: the database still walks through and discards k rows, and if new data appears between queries the pages shift and give repeats or gaps. For large lists where stability matters, keyset pagination is used: a condition on the value of the last seen row instead of OFFSET.
-- the next page after the last seen row (keyset)SELECT id, created_at
FROM transactions
WHERE (created_at, id) < ('2026-09-15 10:05', 4021)
ORDERBY created_at DESC, id DESCLIMIT10;
Common mistakes.
LIMIT without ORDER BY: a random "first" row and unstable tests.
Sorting by a non-unique key without an extra one: equal rows swap places.
Relying on the NULL position without checking the database.
Sorting a number stored as text.
A deep OFFSET on large tables or on lists that change.
Check yourself
Why can a test that takes LIMIT 1 with ORDER BY created_at DESC fail once every few runs?
Answer
Two transactions may have the same created_at, and the database returns them in an arbitrary order. You need a unique second key, for example ORDER BY created_at DESC, id DESC.
Where will the row with NULL be in ORDER BY balance ASC in PostgreSQL and MySQL?
Answer
Last in PostgreSQL (NULL counts as the largest), first in MySQL (NULL is the smallest). To not depend on the database you need an explicit NULLS FIRST or NULLS LAST or an expression with IS NULL.
Why does ORDER BY name return '10' before '9'?
Answer
The column is text and the sort is lexicographic: characters are compared left to right and '1' is less than '9'. Store the number as a numeric type or cast it in the query.
Related lessons: “How is a SELECT query structured?”, “In what order is a query actually executed?”, “What is NULL and how does it differ from 0 and an empty string?”, “How do you find the top N records in each group?”.
In an interview.Junior: ORDER BY sorts ascending or descending and LIMIT caps the row count. Without ORDER BY the order is not guaranteed, so LIMIT without sorting gives arbitrary rows and unstable tests. Middle/Senior: A table is a set and only ORDER BY gives an order, while equal keys come in an arbitrary order, so I put a unique key such as id at the end of the sort. NULL sorts differently depending on the database: in PostgreSQL it is larger than everything and in MySQL smaller, so I set the position explicitly. For large lists I prefer keyset pagination, because a deep OFFSET is slow and shifts pages.