QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › SELECT and filtering

How is a SELECT query structured?

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

SELECT email, countrywhat to show: columns, expressions, aliasesFROM userswhere the rows come fromWHERE country = 'PL'which rows to keepGROUP BY countrycollapse rows into groupsHAVING COUNT(*) > 1which groups to keepORDER BY emailin which order to returnLIMIT 10how many rows to return
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 position
SELECT * 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 limit
SELECT id, email, phone
FROM users
WHERE country = 'PL'
ORDER BY id
LIMIT 5;

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.

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.

More articles in this chapter