Skip to main content

Databases · Beginner · 20 min

Query a table in SQL with SELECT, WHERE and ORDER BY

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7

You will load 500 market stall sales into PostgreSQL 18 and answer ten questions about them with SELECT, WHERE, ORDER BY, LIMIT, DISTINCT and CASE, saved in a .sql file you can run again with psql -f.

On this page

Most of the SQL you will ever write is reading: asking a table a question and getting back exactly the rows and columns that answer it. That is the job of SELECT. In this tutorial you load a small table of sales from market stalls into PostgreSQL 18, then answer questions about it one clause at a time: which columns to show, which rows to keep, what order to put them in and how many to return.

Every question comes with a count you can check, because the practice data is generated by a fixed pattern rather than at random. If your count matches, your query is right. At the end you put ten questions and their queries into one .sql file and run it with psql -f, which is how you keep a set of queries you trust.

You need PostgreSQL 18 on Ubuntu 26.04, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 came out on 19 November 2026; every statement here works the same on it. If you have only used SQLite so far, as in /tutorials/hello-world-in-sql, the SQL below will look familiar. The differences are noted where they matter.

Step 1 · Create a practice database and load the sales

Work in a throwaway folder and give yourself a PostgreSQL role with the same name as your Linux user. On Ubuntu the local socket uses peer authentication, so a role that matches your login lets you run psql without sudo and without a password. Then create a database called market that you own.

Bash
mkdir -p ~/sql-select-demo
cd ~/sql-select-demo
sudo -u postgres createuser "$USER"
sudo -u postgres createdb -O "$USER" market

Your role is not a superuser. It owns market, which is enough to create and query tables in it.

Now write the data file. It creates one table, sales, and fills it with 500 rows. Instead of 500 separate INSERT lines, it uses generate_series(1, 500), which produces the numbers 1 to 500, and builds each row from its number with simple arithmetic. That is why everyone who runs it gets the same rows and the same counts.

Bash
cat > ~/sql-select-demo/sales.sql <<'SQL'
\set ON_ERROR_STOP on
DROP TABLE IF EXISTS sales;

CREATE TABLE sales (
  id         integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sold_on    date          NOT NULL,
  market     text          NOT NULL,
  product    text          NOT NULL,
  quantity   integer       NOT NULL,
  unit_price numeric(10,2) NOT NULL,
  payment    text          -- NULL when the trader did not record it
);

INSERT INTO sales (sold_on, market, product, quantity, unit_price, payment)
SELECT
  date '2026-10-01' + (g % 31),
  (ARRAY['Balogun', 'Makola', 'Gikomba', 'Kejetia', 'Oshodi'])[1 + g % 5],
  (ARRAY['Tomatoes', 'tomato paste', 'Rice 5 kg', 'Palm oil',
         'Plantain', 'Onions', 'Garri', 'Groundnut oil'])[1 + (g * 3) % 8],
  1 + (g * 7) % 10,
  (ARRAY[1200, 900, 8500, 3000, 1500, 800, 2000, 3500])[1 + (g * 3) % 8] + (g % 3) * 100,
  CASE WHEN g % 11 = 0 THEN NULL
       ELSE (ARRAY['cash', 'mobile money', 'card', 'bank transfer'])[1 + (g * 5) % 4]
  END
FROM generate_series(1, 500) AS g;
SQL

Each row is one sale on one day in October 2026 at one of five markets: the product, how many units, the price per unit in the local currency, and how the customer paid. About one sale in eleven has no payment method recorded, which you will need later. One product name, tomato paste, is deliberately in lower case.

The first line, \set ON_ERROR_STOP on, is a psql command rather than SQL. It makes psql stop at the first error instead of carrying on, so a mistake cannot go unnoticed in a long file. Load the file:

Bash
psql -d market -f ~/sql-select-demo/sales.sql

psql prints what each statement did: a notice that the table did not exist yet (the first time only), then DROP TABLE, CREATE TABLE and INSERT 0 500. The 500 is the number of rows inserted.

Check it worked

Count the rows:

Bash
psql -d market -c "SELECT count(*) FROM sales;"

The answer is 500. If you see FATAL: role "..." does not exist, the createuser line did not run; run it again. If createuser says the role already exists, you made one earlier, and that is fine.

Step 2 · Choose columns and give them names

From here on, work in an interactive session. Open one on the market database:

Bash
psql -d market

The prompt is market=>. Type each statement and end it with ;. A statement can span several lines; psql waits for the semicolon. Type \q to leave.

SELECT * returns every column. That is fine for a first look, but in real queries name the columns you want, in the order you want them:

SQL
SELECT id, sold_on, market, product, quantity
FROM sales
ORDER BY id
LIMIT 5;
Text
 id |  sold_on   |  market  |    product    | quantity
----+------------+----------+---------------+----------
  1 | 2026-10-02 | Makola   | Palm oil      |        8
  2 | 2026-10-03 | Gikomba  | Garri         |        5
  3 | 2026-10-04 | Kejetia  | tomato paste  |        2
  4 | 2026-10-05 | Oshodi   | Plantain      |        9
  5 | 2026-10-06 | Balogun  | Groundnut oil |        6
(5 rows)

LIMIT 5 keeps the output short. The ORDER BY id matters more than it looks: without it, PostgreSQL may return rows in any order it likes, and the "first five" can change after updates. Whenever you want particular rows from the top, sort first.

A column in the select list does not have to be a stored column. It can be an expression, and AS gives it a name:

SQL
SELECT id,
       product,
       quantity,
       unit_price,
       quantity * unit_price AS total,
       upper(market) AS market_name
FROM sales
ORDER BY id
LIMIT 3;

The first row shows total as 24800.00 (8 units at 3100.00) and market_name as MAKOLA. Without AS, PostgreSQL would call the computed column ?column? and the other one upper. If a name needs spaces or capitals, put it in double quotes: AS "Total value". Single quotes are for text values, double quotes are for names, the same rule as in SQLite.

Check it worked

Your second query returns three rows and six columns, with headers id, product, quantity, unit_price, total and market_name. If the total header reads ?column?, the AS total is missing.

Step 3 · Keep only the rows you want with WHERE

WHERE takes a condition and keeps the rows where it is true. Start with one market:

SQL
SELECT count(*) FROM sales WHERE market = 'Makola';

That returns 100. Text comparisons with = are exact, including case: 'makola' would match nothing.

Combine conditions with AND (both must be true) and OR (either is enough). Makola sales of eight or more units:

SQL
SELECT count(*) FROM sales WHERE market = 'Makola' AND quantity >= 8;

That is 50. Now a trap. You want sales at Makola or Kejetia, of more than five units:

SQL
SELECT count(*) FROM sales
WHERE market = 'Makola' OR market = 'Kejetia' AND quantity > 5;

This returns 150, not what you meant. AND binds tighter than OR, so PostgreSQL reads it as "every Makola sale, plus Kejetia sales of more than five". Put brackets around the OR:

SQL
SELECT count(*) FROM sales
WHERE (market = 'Makola' OR market = 'Kejetia') AND quantity > 5;

Now the answer is 100. When a condition mixes AND and OR, always add the brackets, even when you think you do not need them.

Two shorter forms save typing. IN tests against a list, and BETWEEN tests a range that includes both ends:

SQL
SELECT count(*) FROM sales WHERE market IN ('Balogun', 'Oshodi');

SELECT count(*) FROM sales
WHERE sold_on BETWEEN '2026-10-01' AND '2026-10-07';

The first returns 200, the second 116, the sales in the first week of October. Because BETWEEN includes both ends, it suits whole dates like these. For a column that holds a date and a time, write sold_at >= '2026-10-01' AND sold_at < '2026-10-08' instead, or you lose everything after midnight on the last day.

Check it worked

Your counts are 100, 50, 150, 100, 200 and 116, in that order. If the bracketed query also gives 150, check that the closing bracket comes before AND.

Step 4 · Match text patterns with LIKE and ILIKE

LIKE compares text with a pattern. % stands for any run of characters, including none, and _ for exactly one character.

SQL
SELECT count(*) FROM sales WHERE product LIKE '%oil';
SELECT count(*) FROM sales WHERE product LIKE 'Tomato%';

The first finds palm oil and groundnut oil, 125 sales. The second returns 62: it matches Tomatoes but not tomato paste, because LIKE is case-sensitive. PostgreSQL's ILIKE ignores case:

SQL
SELECT count(*) FROM sales WHERE product ILIKE 'tomato%';
SELECT DISTINCT product FROM sales WHERE product ILIKE 'tomato%';

The count is now 125, and the second query lists both spellings. ILIKE is a PostgreSQL addition. In other databases the portable form is lower(product) LIKE 'tomato%', which also works here.

ILIKE uses the database's own rules for upper and lower case, so it also matches names written in other alphabets in either case. It does not treat letters with and without accents as the same, so ILIKE 'cafe%' does not find Café. Keep that in mind when you search names typed by people in several languages.

A pattern that starts with % has to read every row, because there is no fixed beginning to look up. On 500 rows that does not matter; on millions it does, which /tutorials/speed-up-slow-postgres-queries-with-explain covers.

Check it worked

Your counts are 125, 62 and 125, and the DISTINCT query prints two rows, Tomatoes and tomato paste.

Step 5 · Find missing values with IS NULL

NULL means "no value recorded". It is not zero and not an empty string, and it behaves differently from every other value. Try the obvious query for sales with no payment method:

SQL
SELECT count(*) FROM sales WHERE payment = NULL;

It returns 0, even though there are missing values. Any comparison with NULL gives an unknown result rather than true, and WHERE keeps only rows where the condition is true. Use IS NULL instead:

SQL
SELECT count(*) FROM sales WHERE payment IS NULL;
SELECT count(*) FROM sales WHERE payment IS NOT NULL;

These return 45 and 455, which add up to 500.

The same rule catches people out with "not equal". Count the sales not paid in cash:

SQL
SELECT count(*) FROM sales WHERE payment <> 'cash';

That gives 341. But 114 sales were cash, and 500 minus 114 is 386. The 45 rows with no payment are missing, because NULL <> 'cash' is unknown too. If you want them included, say so:

SQL
SELECT count(*) FROM sales WHERE payment IS DISTINCT FROM 'cash';

That returns 386. IS DISTINCT FROM works like <> but treats NULL as an ordinary value. Whenever a column can be NULL, decide on purpose whether those rows belong in the answer.

Check it worked

Your five counts are 0, 45, 455, 341 and 386. If the first one is not 0, check you typed = NULL and not IS NULL.

Step 6 · Sort with ORDER BY and page with LIMIT and OFFSET

ORDER BY sorts the result. It sorts ascending (smallest first) unless you add DESC. List several columns and PostgreSQL sorts by the first, then uses the second to break ties, and so on. The latest day's sales, biggest first:

SQL
SELECT id, sold_on, market, product, quantity * unit_price AS total
FROM sales
ORDER BY sold_on DESC, total DESC, id
LIMIT 5;

The first row is sale 278, rice at Kejetia on 2026-10-31, worth 60900.00. Notice that ORDER BY can use the name total from the select list. WHERE cannot, because PostgreSQL works out which rows to keep before it computes the select list. In WHERE, repeat the expression: WHERE quantity * unit_price >= 20000.

The last key, id, is a tie-breaker. Several sales can have the same date and total, and without a final unique column their order between runs is not guaranteed.

Sorting a column with NULL in it needs a decision. In ascending order PostgreSQL puts NULL last; with DESC it puts them first, which is rarely what a report wants. Say where they go:

SQL
SELECT id, payment
FROM sales
ORDER BY payment DESC NULLS LAST, id
LIMIT 3;

The rows start with mobile money instead of empty payments. NULLS FIRST does the opposite.

LIMIT and OFFSET together give you pages. With five rows per page, page 2 skips the first five:

SQL
SELECT id, market, product, quantity * unit_price AS total
FROM sales
ORDER BY total DESC, id
LIMIT 5 OFFSET 5;

Page 2 starts with sale 94, worth 77400.00. Small pages matter on the screens your data ends up on: a phone on a slow or prepaid connection loads 20 rows quickly and 5,000 rows slowly, if at all. Keep in mind that PostgreSQL still works through the rows it skips, so OFFSET 100000 is slow on a big table. Paging by the last value seen (WHERE id > 1234 ORDER BY id LIMIT 20) avoids that.

Check it worked

The first query starts with sale 278, the NULLS LAST query starts with mobile money, and page 2 lists sales 94, 214, 334, 454 and 54. Remove NULLS LAST from the second query and run it again: the first rows now have an empty payment.

Step 7 · Remove duplicates with DISTINCT and label rows with CASE

DISTINCT removes repeated rows from the result. Which markets are in the table?

SQL
SELECT DISTINCT market FROM sales ORDER BY market;

Five rows, Balogun to Oshodi. DISTINCT applies to the whole row you select, so SELECT DISTINCT market, product returns each combination once: 40 rows, since every market sold every product.

CASE picks a value by testing conditions in order, like if and else in other languages. Label each sale by size:

SQL
SELECT id,
       quantity * unit_price AS total,
       CASE
         WHEN quantity * unit_price < 5000  THEN 'small'
         WHEN quantity * unit_price < 20000 THEN 'medium'
         ELSE 'large'
       END AS size
FROM sales
ORDER BY id
LIMIT 4;

Sale 1 is large, sale 2 medium, sale 3 small and sale 4 medium. The first WHEN that is true wins, so the second test only needs the upper limit. A CASE without ELSE returns NULL for rows that match nothing.

A CASE expression can go anywhere a value can, including WHERE. To count the large sales, filter on the same rule:

SQL
SELECT count(*) FROM sales WHERE quantity * unit_price >= 20000;

That is 113.

Check it worked

You see five markets, 40 market and product pairs, the labels large, medium, small, medium for sales 1 to 4, and a count of 113. Type \q to leave psql.

Step 8 · Save ten answers in a file and run it with psql -f

Queries typed at a prompt are gone when you close it. Put the ones you want to keep in a file, with a label before each answer. \echo is a psql command that prints a line of text.

Bash
cat > ~/sql-select-demo/answers.sql <<'SQL'
\set ON_ERROR_STOP on

\echo '1. How many sales are there?'
SELECT count(*) FROM sales;

\echo '2. How many sales were at Makola?'
SELECT count(*) FROM sales WHERE market = 'Makola';

\echo '3. How many Makola sales were of 8 or more units?'
SELECT count(*) FROM sales WHERE market = 'Makola' AND quantity >= 8;

\echo '4. How many sales were at Balogun or Oshodi?'
SELECT count(*) FROM sales WHERE market IN ('Balogun', 'Oshodi');

\echo '5. How many sales were in the first week of October?'
SELECT count(*) FROM sales WHERE sold_on BETWEEN '2026-10-01' AND '2026-10-07';

\echo '6. How many sales were of a tomato product, in any spelling?'
SELECT count(*) FROM sales WHERE product ILIKE '%tomato%';

\echo '7. How many sales have no payment method recorded?'
SELECT count(*) FROM sales WHERE payment IS NULL;

\echo '8. What were the five biggest sales?'
SELECT id, market, product, quantity * unit_price AS total
FROM sales
ORDER BY total DESC, id
LIMIT 5;

\echo '9. Which markets are in the data?'
SELECT DISTINCT market FROM sales ORDER BY market;

\echo '10. How many sales were large (20000 or more)?'
SELECT count(*) FROM sales WHERE quantity * unit_price >= 20000;
SQL

Run it:

Bash
psql -d market -f ~/sql-select-demo/answers.sql

To keep the answers, send them to a file as well: psql -d market -f ~/sql-select-demo/answers.sql > ~/sql-select-demo/answers.txt. Because the file starts with ON_ERROR_STOP, a typo in any query stops the run with an error and a line number, instead of printing nine answers and a message you might scroll past.

Check it worked

The output prints each question followed by its answer: 500, 100, 50, 200, 116, 125, 45, five rows led by sale 14 at 78300.00, five market names, and 113. If a count differs, compare that query with the one in the step that introduced it.

Step 9 · Remove the practice database

When you are done, delete the database and the folder. If you want to keep practising with the joins tutorial first, leave them until later.

Bash
dropdb market
rm -rf ~/sql-select-demo

The next command deletes the PostgreSQL role named after your Linux user. Run it only if you created that role in the first step and nothing else uses it.

Bash
sudo -u postgres dropuser "$USER"

Check it worked

Bash
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_database WHERE datname = 'market';"

The answer is 0, and ls ~/sql-select-demo reports that the folder does not exist.

Next steps

  • Answer questions that need two tables at once: /tutorials/combine-tables-with-sql-joins.
  • See why a query is slow and make it fast with an index: /tutorials/speed-up-slow-postgres-queries-with-explain.
  • Go back over the basics in a file-based database: /tutorials/hello-world-in-sql.
  • Set up PostgreSQL on another server with an app user and password: /tutorials/install-postgresql-18-on-ubuntu-26-04.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.