Concept · Basic queries

SQL query

A SQL query asks the database for a result. SELECT picks the columns, FROM supplies the rows and WHERE lets you filter them.

SQL query example

This query shows the three most expensive products:

SQL
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;

What to look for: In this example, ORDER BY price DESC first decides which are the most expensive and LIMIT 3 shows only three. Without sorting, “the first three” does not necessarily mean “the three most expensive”.

Check the result with small data

A query is the specific request we make of a set of data.

Self-contained query · SQLite
WITH employees(name, active) AS (
  VALUES ('Amy',1),('Liam',0),('Eva',1)
)
SELECT name FROM employees WHERE active = 1
ORDER BY name;
Query result
name
Amy
Eva

Here the query reads two rows and returns their names; it does not insert, delete or update any employees. The same table can answer different queries depending on what you need.

Check your understanding: Which clause would you remove to show both active and inactive employees?

Show answer

WHERE active = 1. Without that clause, the query would return Amy, Eva and Liam.

What changes from case to case

You do not need to understand the whole statement at once. Read each clause as a question:

  1. SELECT: which columns or calculations do I want to see?
  2. FROM: which table does the data come from?
  3. WHERE: which rows should get through the filter?
  4. ORDER BY: in what order do I want them?
  5. LIMIT: how many rows do I need at most?

The result is not the original table. A read query produces a temporary result with the columns and rows you asked for. The stored data does not change.

Common mix-ups with SQL queries

Reading the query only from left to right

A query is written starting with SELECT, but to understand it, it often helps to think about the source first, then the filters and finally the result columns. Put each clause on its own line and predict the output before running it.