PostgreSQL SELECT Statement: WHERE, ORDER BY, LIMIT and DISTINCT ON

If you’ve run the same postgresql select twice and gotten rows in a different order, nothing is broken. A SELECT has no order until you ask for one. Here’s the full shape of the statement:

SELECT column_list
FROM table_name
WHERE condition
ORDER BY column [DESC] [NULLS LAST]
LIMIT n OFFSET m;

The catch I hit while testing: one UPDATE that changed nothing moved order 1 from the first row to the last in a query without ORDER BY. Same table, same query, different answer.

Below: columns and aliases, WHERE, ORDER BY with NULLS LAST, LIMIT, OFFSET and FETCH FIRST, DISTINCT ON, SELECT without FROM, and three common errors.

Tested on PostgreSQL 18.6 on Windows with psql, in a demo database with an en-US locale.

The sample orders table for every PostgreSQL SELECT example

Eight orders from three states. Two rows matter later: orders 3 and 6 have no ship date (NULL), and both cost $412.00, a tie.

CREATE TABLE orders (
  order_id   int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer   varchar(20) NOT NULL,
  city       varchar(15) NOT NULL,
  state      char(2) NOT NULL,
  amount     numeric(8,2) NOT NULL,
  ordered_on date NOT NULL,
  shipped_on date
);

INSERT INTO orders (customer, city, state, amount, ordered_on, shipped_on) VALUES
  ('Hannah Brooks',  'Austin',     'TX', 249.99, '2026-03-02', '2026-03-04'),
  ('Tyler Reed',     'Columbus',   'OH',  89.50, '2026-03-03', '2026-03-09'),
  ('Grace Miller',   'Dallas',     'TX', 412.00, '2026-03-05', NULL),
  ('Marcus Bennett', 'San Diego',  'CA',  89.50, '2026-03-06', '2026-03-07'),
  ('Olivia Hayes',   'Houston',    'TX', 135.25, '2026-03-09', '2026-03-12'),
  ('Ethan Cole',     'Sacramento', 'CA', 412.00, '2026-03-10', NULL),
  ('Ava Foster',     'Cleveland',  'OH',  64.00, '2026-03-11', '2026-03-13'),
  ('Hannah Brooks',  'Austin',     'TX',  58.75, '2026-03-12', '2026-03-16');

psql replies:

CREATE TABLE
INSERT 0 8

New to CREATE TABLE? See creating a table in PostgreSQL.

PostgreSQL SELECT syntax: all columns vs specific columns

I want every column for the California orders. SELECT * returns all columns in table order (the WHERE just keeps the output short):

SELECT * FROM orders
WHERE state = 'CA';

Output:

 order_id |    customer    |    city    | state | amount | ordered_on | shipped_on
----------+----------------+------------+-------+--------+------------+------------
        4 | Marcus Bennett | San Diego  | CA    |  89.50 | 2026-03-06 | 2026-03-07
        6 | Ethan Cole     | Sacramento | CA    | 412.00 | 2026-03-10 |
(2 rows)

That returns 2 rows and all 7 columns. Ethan Cole’s blank shipped_on cell is a NULL.

In app code, list the columns you need instead, like SELECT customer, state, amount FROM orders. A column added later then can’t change your result. The PostgreSQL data types guide explains what each column holds.

Column aliases and computed columns in a postgres select query

I want Texas orders with 8.25% sales tax added. Expressions go right in the column list, and AS names them:

SELECT customer,
       amount,
       round(amount * 0.0825, 2) AS sales_tax,
       amount + round(amount * 0.0825, 2) AS total
FROM orders
WHERE state = 'TX';

Output:

   customer    | amount | sales_tax | total
---------------+--------+-----------+--------
 Hannah Brooks | 249.99 |     20.62 | 270.61
 Grace Miller  | 412.00 |     33.99 | 445.99
 Olivia Hayes  | 135.25 |     11.16 | 146.41
 Hannah Brooks |  58.75 |      4.85 |  63.60
(4 rows)

That returns 4 Texas rows. Grace Miller’s $412.00 order comes to $445.99 with tax.

How does this work? round(amount * 0.0825, 2) runs once per row, and the alias becomes the column header. Text works the same way: to glue city and state into one column, use PostgreSQL CONCAT or the || operator.

Important: AS is required when the alias is any PostgreSQL keyword, such as year or order. I write it every time.

PostgreSQL SELECT WHERE: filter rows with IN, BETWEEN, ILIKE and IS NULL

I want Brooks orders from Texas or Ohio between $60 and $250, then every unshipped order. Same orders table:

SELECT order_id, customer, state, amount
FROM orders
WHERE state IN ('TX', 'OH')
  AND amount BETWEEN 60 AND 250
  AND customer ILIKE '%brooks%';

SELECT order_id, customer, ordered_on
FROM orders
WHERE shipped_on IS NULL;

Output:

 order_id |   customer    | state | amount
----------+---------------+-------+--------
        1 | Hannah Brooks | TX    | 249.99
 order_id |   customer   | ordered_on
----------+--------------+------------
        3 | Grace Miller | 2026-03-05
        6 | Ethan Cole   | 2026-03-10
PostgreSQL SELECT WHERE with IN, BETWEEN and ILIKE returns order 1, and WHERE shipped_on IS NULL returns orders 3 and 6
One Brooks order passes the filters; two orders haven’t shipped.

The first query returns 1 row, order 1 at $249.99. Hannah’s second order, $58.75, falls under the BETWEEN floor of 60.

How does this work? Every AND must be true. BETWEEN includes both ends, and ILIKE ignores case, so '%brooks%' matches Brooks.

The second query returns orders 3 and 6. Write IS NULL, never = NULL, because a comparison with NULL is never true.

More operators are in the PostgreSQL WHERE clause guide, and wildcards in PostgreSQL LIKE and ILIKE.

PostgreSQL ORDER BY with NULLS FIRST and NULLS LAST

I want the latest shipments first. Without help, the unshipped orders jump to the top:

SELECT order_id, customer, shipped_on
FROM orders
ORDER BY shipped_on DESC
LIMIT 3;

SELECT order_id, customer, shipped_on
FROM orders
ORDER BY shipped_on DESC NULLS LAST
LIMIT 3;

Output:

 order_id |   customer    | shipped_on
----------+---------------+------------
        6 | Ethan Cole    |
        3 | Grace Miller  |
        8 | Hannah Brooks | 2026-03-16
 order_id |   customer    | shipped_on
----------+---------------+------------
        8 | Hannah Brooks | 2026-03-16
        7 | Ava Foster    | 2026-03-13
        5 | Olivia Hayes  | 2026-03-12
PostgreSQL ORDER BY shipped_on DESC puts NULL rows 6 and 3 first, while NULLS LAST LIMIT 3 returns orders 8, 7 and 5
DESC puts NULLs first; NULLS LAST moves them down.

In the first result, orders 6 and 3 lead with blank dates, because PostgreSQL sorts NULL as if it were larger than any value. It lands last in ASC and first in DESC.

Adding NULLS LAST fixes it. The second query returns orders 8, 7 and 5, shipped 03/16/2026, 03/13/2026 and 03/12/2026.

Multi-column sorts and custom orders are in PostgreSQL ORDER BY examples.

PostgreSQL SELECT LIMIT, OFFSET and FETCH FIRST

I want page 2 of orders, three per page. Then the most expensive order, ties included:

SELECT order_id, customer, ordered_on
FROM orders
ORDER BY ordered_on
LIMIT 3 OFFSET 3;

SELECT order_id, customer, amount
FROM orders
ORDER BY amount DESC
FETCH FIRST 1 ROW WITH TIES;

Output:

 order_id |    customer    | ordered_on
----------+----------------+------------
        4 | Marcus Bennett | 2026-03-06
        5 | Olivia Hayes   | 2026-03-09
        6 | Ethan Cole     | 2026-03-10
(3 rows)
 order_id |   customer   | amount
----------+--------------+--------
        6 | Ethan Cole   | 412.00
        3 | Grace Miller | 412.00
(2 rows)

Page 2 holds orders 4, 5 and 6, the fourth through sixth orders by date. FETCH FIRST 1 ROW WITH TIES returned 2 rows, because Ethan Cole and Grace Miller both spent $412.00.

How does this work? OFFSET 3 skips three rows and LIMIT 3 keeps the next three. FETCH FIRST is the SQL-standard spelling, and WITH TIES needs ORDER BY and PostgreSQL 13 or later.

Pro Tip: a big OFFSET still reads every skipped row. Deep pages? Filter on the last key you saw.

Need a numbered list instead of a page? Use ROW_NUMBER in PostgreSQL.

SELECT DISTINCT in PostgreSQL vs DISTINCT ON

I want each state once, then the biggest order per state. Same eight rows:

SELECT DISTINCT state
FROM orders
ORDER BY state;

SELECT DISTINCT ON (state)
       state, customer, amount
FROM orders
ORDER BY state, amount DESC, order_id;

Output:

 state
-------
 CA
 OH
 TX
 state |   customer   | amount
-------+--------------+--------
 CA    | Ethan Cole   | 412.00
 OH    | Tyler Reed   |  89.50
 TX    | Grace Miller | 412.00
PostgreSQL SELECT DISTINCT returns CA, OH and TX, and DISTINCT ON (state) keeps Ethan Cole, Tyler Reed and Grace Miller
DISTINCT ON keeps the first row of each state.

DISTINCT returns 3 states. DISTINCT ON returns one row per state: Ethan Cole for CA, Tyler Reed for OH and Grace Miller for TX.

How does this work? DISTINCT ON keeps the first row of each group, and ORDER BY decides which row comes first. amount DESC puts the top order first; order_id keeps the pick repeatable if two orders ever tie.

DISTINCT ON is PostgreSQL-only. For counts or totals per state, PostgreSQL GROUP BY is the better fit.

Can you SELECT without FROM in PostgreSQL?

Yes. Leave FROM out when you only want to compute a value, test a function on a literal or check a date calculation before you put it in a real query:

SELECT 2 + 2 AS answer,
       upper('ohio') AS state_name,
       DATE '2026-11-19' + 30 AS due_date;

Output:

 answer | state_name |  due_date
--------+------------+------------
      4 | OHIO       | 2026-12-19
(1 row)

One row: 4, OHIO and 2026-12-19. PostgreSQL now() works the same way and returns the transaction’s start time.

Does PostgreSQL SELECT return rows in order without ORDER BY?

No. Proof on the same orders table: a query, an UPDATE that changes nothing, then the query again:

SELECT order_id, customer FROM orders LIMIT 3;

UPDATE orders SET amount = amount WHERE order_id = 1;

SELECT order_id, customer FROM orders LIMIT 3;

Output:

 order_id |   customer
----------+---------------
        1 | Hannah Brooks
        2 | Tyler Reed
        3 | Grace Miller
 order_id |    customer
----------+----------------
        2 | Tyler Reed
        3 | Grace Miller
        4 | Marcus Bennett
PostgreSQL SELECT LIMIT 3 without ORDER BY returns orders 1, 2, 3, then 2, 3, 4 after a no-op UPDATE of order 1
Same query, different rows after one UPDATE.

The first run returns orders 1, 2 and 3. After the UPDATE, it returns 2, 3 and 4.

How does this work? A PostgreSQL UPDATE writes a new row version, even when no value changes, so a plain scan now meets order 1 later. If order matters, write ORDER BY.

Common PostgreSQL SELECT errors: 42703, DISTINCT ON and “FirstName”

Three errors. All real, all in one script:

\set ON_ERROR_STOP off
SELECT customer, amount * 1.0825 AS total
FROM orders WHERE total > 400;
\echo SQLSTATE :LAST_ERROR_SQLSTATE

SELECT DISTINCT ON (state) state, customer
FROM orders ORDER BY amount DESC;

CREATE TEMP TABLE web_users ("FirstName" text);
SELECT FirstName FROM web_users;
SELECT "FirstName" FROM web_users;

Output:

psql:select-common-errors.sql:3: ERROR:  column "total" does not exist
LINE 2: FROM orders WHERE total > 400;
                          ^
SQLSTATE 42703
psql:select-common-errors.sql:7: ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON (state) state, customer
                            ^
psql:select-common-errors.sql:10: ERROR:  column "firstname" does not exist
LINE 1: SELECT FirstName FROM web_users;
               ^
HINT:  Perhaps you meant to reference the column "web_users.FirstName".
 FirstName
-----------
(0 rows)
PostgreSQL SELECT errors: column total does not exist SQLSTATE 42703, DISTINCT ON must match ORDER BY, column firstname does not exist
Three real errors and the quoted fix.
  • column “total” does not exist (42703): WHERE runs before the SELECT list, so the alias doesn’t exist yet. Repeat the expression, or wrap the query in a subquery. Aliases do work in ORDER BY and GROUP BY.
  • DISTINCT ON expressions must match initial ORDER BY expressions: start ORDER BY with the DISTINCT ON column.
  • column “firstname” does not exist: unquoted names fold to lowercase. A column created as "FirstName" needs the quotes every time, as the last query shows.

Things to Keep in Mind

  • No ORDER BY, no promised order. LIMIT doesn’t change that.
  • DESC puts NULLs first. Add NULLS LAST.
  • Aliases can’t appear in WHERE; repeat the expression instead.
  • Create lowercase names, or you’ll quote mixed-case ones forever.

Here’s a copy-ready query that combines them: one row per state, total with tax.

SELECT DISTINCT ON (state)
       state,
       customer,
       amount + round(amount * 0.0825, 2) AS total
FROM orders
WHERE ordered_on >= DATE '2026-03-01'
ORDER BY state, amount DESC, order_id
LIMIT 10;

Output:

 state |   customer   | total
-------+--------------+--------
 CA    | Ethan Cole   | 445.99
 OH    | Tyler Reed   |  96.88
 TX    | Grace Miller | 445.99
(3 rows)

That returns 3 rows, with Ethan Cole and Grace Miller tied at $445.99. Next step: pull columns from more tables with PostgreSQL joins.

Two more PostgreSQL reads, plus the MariaDB version:

Frequently Asked Questions

What is the difference between WHERE and HAVING in PostgreSQL?

WHERE filters single rows before grouping. HAVING filters groups after GROUP BY, so it can test aggregates such as count(*) > 2.

How does UNION differ from UNION ALL in PostgreSQL?

UNION removes duplicate rows, which costs a sort or hash step. UNION ALL keeps every row, so it’s faster.

Why is SELECT count(*) slow on a large PostgreSQL table?

PostgreSQL has to check which row versions your transaction can see, so it scans the table or an index. For a quick estimate, read reltuples from pg_class.

Can I save SELECT results into a new table?

Yes. Use CREATE TABLE new_table AS SELECT ..., or INSERT INTO existing_table SELECT .... The PostgreSQL 18 SELECT docs also describe SELECT INTO, but CREATE TABLE AS is the recommended form.