Skip to content
SQL

SQL Query Optimization: A Practical Checklist

Ihsan Ullah · 16 min read
Query Optimization, Lesson 33 of the SQL course: A practical checklist for faster SQL

SQL course · Module 9: Performance · Lesson 33 of 40

Quick answer: SQL query optimization means helping the database read less data. Write filters the index can use (no function, maths or type cast on the indexed column), select only the columns you need, keep statistics fresh with ANALYZE, replace many small queries with one set-based query, and page through results with keyset pagination instead of a large OFFSET. Check every change with EXPLAIN (ANALYZE, BUFFERS) on realistic data.

In this lesson you will learn:

  • sargable vs non-sargable filters: functions, leading wildcards and implicit casts
  • why SELECT * and missing statistics hurt
  • EXISTS vs IN vs JOIN, and how to avoid the N+1 query pattern
  • ORDER BY with LIMIT and an index, and keyset vs OFFSET pagination
  • a numbered checklist you can use on any slow query

Before you start: Lesson 31, How SQL Indexes Work: B-tree, Composite, Covering and Partial Indexes and Lesson 32, PostgreSQL EXPLAIN and EXPLAIN ANALYZE: Read a Query Plan.

We ran every example on PostgreSQL 16.15 with the shop database from Lesson 3 and checked the current PostgreSQL 18 manual. Most plans are shown with COSTS OFF, so they show the plan shape, not timings. On PostgreSQL 18, EXPLAIN ANALYZE also prints Buffers and Index Searches lines and shows rows with decimals. We never claim a fixed speedup: how much faster a change makes a query depends on your data and your server.

Setup

Create the practice tables with the same script as in Lessons 31 and 32 (it is safe to run again):

DROP TABLE IF EXISTS big_orders, big_customers;

CREATE TABLE big_customers (
    id          integer PRIMARY KEY,
    email       text    NOT NULL,
    country     text    NOT NULL,
    signup_date date    NOT NULL
);

CREATE TABLE big_orders (
    id          integer PRIMARY KEY,
    customer_id integer NOT NULL REFERENCES big_customers (id),
    order_date  date    NOT NULL,
    status      text    NOT NULL,
    total       numeric(10,2) NOT NULL
);

SELECT setseed(0.31);   -- fixed seed: everyone gets the same "random" data

INSERT INTO big_customers
SELECT i,
       CASE WHEN i % 3 = 0 THEN 'Customer' || i || '@Example.com'
            ELSE 'customer' || i || '@example.com' END,
       (ARRAY['Pakistan','India','UK','USA','Canada','Germany','France','Italy'])[1 + floor(random() * 8)::int],
       DATE '2023-01-01' + floor(random() * 1000)::int
FROM generate_series(1, 20000) AS i;

INSERT INTO big_orders
SELECT i,
       1 + floor(random() * 20000)::int,
       DATE '2024-01-01' + floor(random() * 1035)::int,
       CASE WHEN r < 0.80 THEN 'delivered'
            WHEN r < 0.90 THEN 'shipped'
            WHEN r < 0.95 THEN 'cancelled'
            ELSE 'pending' END,
       round((5 + random() * 495)::numeric, 2)
FROM (SELECT i, random() AS r FROM generate_series(1, 200000) AS i) AS s;

VACUUM ANALYZE big_customers, big_orders;

Then add three indexes and turn off parallel plans for this session, as in Lesson 32:

CREATE INDEX big_orders_customer_id_idx ON big_orders (customer_id);
CREATE INDEX big_orders_date_id_idx ON big_orders (order_date, id);
CREATE INDEX big_customers_email_idx ON big_customers (email text_pattern_ops);
SET max_parallel_workers_per_gather = 0;
CREATE INDEX
CREATE INDEX
CREATE INDEX
SET

text_pattern_ops is explained in the LIKE section below.

Sargable vs non-sargable filters

A filter is sargable (from “search argument”) when the database can use an index to find the matching rows. The rule is simple: leave the indexed column alone on one side of the comparison, and do the work on the other side.

A function on the column

Both queries count the orders of March 2026:

EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders
WHERE EXTRACT(YEAR FROM order_date) = 2026 AND EXTRACT(MONTH FROM order_date) = 3;

EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
                                                       QUERY PLAN                                                        
-------------------------------------------------------------------------------------------------------------------------
 Aggregate
   ->  Seq Scan on big_orders
         Filter: ((EXTRACT(year FROM order_date) = '2026'::numeric) AND (EXTRACT(month FROM order_date) = '3'::numeric))
(3 rows)

                                           QUERY PLAN                                           
------------------------------------------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using big_orders_date_id_idx on big_orders
         Index Cond: ((order_date >= '2026-03-01'::date) AND (order_date < '2026-04-01'::date))
(3 rows)
SELECT
  (SELECT COUNT(*) FROM big_orders
   WHERE EXTRACT(YEAR FROM order_date) = 2026 AND EXTRACT(MONTH FROM order_date) = 3) AS with_extract,
  (SELECT COUNT(*) FROM big_orders
   WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01') AS with_range;
 with_extract | with_range 
--------------+------------
         5956 |       5956
(1 row)

Same answer, but the index stores order_date, not EXTRACT(...), so the first query must compute the function for all 200,000 rows. The range version reads only March from the index. If you really need a function, an expression index (Lesson 31) is the other fix.

LIKE with a leading wildcard

EXPLAIN (COSTS OFF)
SELECT id, email FROM big_customers WHERE email LIKE 'customer1234@%';

EXPLAIN (COSTS OFF)
SELECT id, email FROM big_customers WHERE email LIKE '%1234@example.com';
                                        QUERY PLAN                                        
------------------------------------------------------------------------------------------
 Index Scan using big_customers_email_idx on big_customers
   Index Cond: ((email ~>=~ 'customer1234@'::text) AND (email ~<~ 'customer1234A'::text))
   Filter: (email ~~ 'customer1234@%'::text)
(3 rows)

                   QUERY PLAN                   
------------------------------------------------
 Seq Scan on big_customers
   Filter: (email ~~ '%1234@example.com'::text)
(2 rows)

A B-tree can serve LIKE only when “the pattern is a constant and is anchored to the beginning of the string”, as in col LIKE 'foo%' but “not col LIKE '%bar'” (PostgreSQL docs: Index Types). Unless your database uses the C locale, the index also needs the text_pattern_ops operator class (PostgreSQL docs: Operator Classes). In our database, a plain index on email was not used for the prefix search.

Implicit casts

EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242.0;

EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE customer_id = 4242;
                 QUERY PLAN                  
---------------------------------------------
 Seq Scan on big_orders
   Filter: ((customer_id)::numeric = 4242.0)
(2 rows)

                      QUERY PLAN                       
-------------------------------------------------------
 Bitmap Heap Scan on big_orders
   Recheck Cond: (customer_id = 4242)
   ->  Bitmap Index Scan on big_orders_customer_id_idx
         Index Cond: (customer_id = 4242)
(4 rows)

4242.0 is a numeric value, so PostgreSQL converts the integer column to numeric for every row ((customer_id)::numeric), and the integer index no longer fits. Compare columns with values of the same type, for example when your application code builds the query.

Select only the columns you need

EXPLAIN (COSTS OFF)
SELECT * FROM big_orders WHERE order_date = '2026-10-30';

EXPLAIN (COSTS OFF)
SELECT id, order_date FROM big_orders WHERE order_date = '2026-10-30';
                      QUERY PLAN                       
-------------------------------------------------------
 Bitmap Heap Scan on big_orders
   Recheck Cond: (order_date = '2026-10-30'::date)
   ->  Bitmap Index Scan on big_orders_date_id_idx
         Index Cond: (order_date = '2026-10-30'::date)
(4 rows)

                         QUERY PLAN                         
------------------------------------------------------------
 Index Only Scan using big_orders_date_id_idx on big_orders
   Index Cond: (order_date = '2026-10-30'::date)
(2 rows)

SELECT * needs status and total, so PostgreSQL must visit the table. Asking only for id and order_date lets it answer from the index alone. Fewer columns also means less data sent over the network.

ANALYZE and statistics

The planner chooses plans from statistics. On our freshly loaded shop database, the customers table had none yet:

EXPLAIN
SELECT * FROM customers;

ANALYZE customers;

EXPLAIN
SELECT * FROM customers;
                          QUERY PLAN                          
--------------------------------------------------------------
 Seq Scan on customers  (cost=0.00..14.90 rows=490 width=136)
(1 row)

ANALYZE
                        QUERY PLAN                         
-----------------------------------------------------------
 Seq Scan on customers  (cost=0.00..1.10 rows=10 width=58)
(1 row)

Without statistics, the planner guessed 490 rows; after ANALYZE it knows there are 10. (If you ran ANALYZE in Lesson 32, you already see rows=10.) The autovacuum daemon runs ANALYZE “whenever the content of a table has changed sufficiently” (PostgreSQL docs: Routine Vacuuming). By default that means 50 changed rows plus 10% of the table (PostgreSQL docs: Automatic Vacuuming), so a 10-row table can wait a long time. Run ANALYZE yourself after loading or changing a lot of data.

EXISTS vs IN vs JOIN

Which customers have at least one pending order? Three ways to ask (Lesson 20):

SELECT
  (SELECT COUNT(*) FROM big_customers c
   WHERE EXISTS (SELECT 1 FROM big_orders o
                 WHERE o.customer_id = c.id AND o.status = 'pending')) AS with_exists,
  (SELECT COUNT(*) FROM big_customers c
   WHERE c.id IN (SELECT o.customer_id FROM big_orders o
                  WHERE o.status = 'pending')) AS with_in,
  (SELECT COUNT(*) FROM big_customers c
   JOIN big_orders o ON o.customer_id = c.id
   WHERE o.status = 'pending') AS with_join;
 with_exists | with_in | with_join 
-------------+---------+-----------
        7831 |    7831 |      9948
(1 row)

The JOIN returns one row per pending order, so a customer with two pending orders is counted twice. EXISTS and IN return each customer once, and here PostgreSQL gave them the same plan:

EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_customers c
WHERE EXISTS (SELECT 1 FROM big_orders o
              WHERE o.customer_id = c.id AND o.status = 'pending');

EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_customers c
WHERE c.id IN (SELECT o.customer_id FROM big_orders o
               WHERE o.status = 'pending');
                          QUERY PLAN                          
--------------------------------------------------------------
 Aggregate
   ->  Hash Join
         Hash Cond: (c.id = o.customer_id)
         ->  Seq Scan on big_customers c
         ->  Hash
               ->  HashAggregate
                     Group Key: o.customer_id
                     ->  Seq Scan on big_orders o
                           Filter: (status = 'pending'::text)
(9 rows)

                          QUERY PLAN                          
--------------------------------------------------------------
 Aggregate
   ->  Hash Join
         Hash Cond: (c.id = o.customer_id)
         ->  Seq Scan on big_customers c
         ->  Hash
               ->  HashAggregate
                     Group Key: o.customer_id
                     ->  Seq Scan on big_orders o
                           Filter: (status = 'pending'::text)
(9 rows)

So choose by meaning: EXISTS or IN for “has any”, JOIN when you need columns from both tables. For “has none”, use NOT EXISTS: if the subquery returns a NULL and nothing matches, NOT IN returns NULL instead of true (PostgreSQL docs: Subquery Expressions).

Avoid the N+1 query pattern

N+1 means one query for a list, then one more query for each row of the list. It often hides in application loops:

SELECT id FROM big_customers ORDER BY signup_date DESC, id DESC LIMIT 3;
SELECT COUNT(*) FROM big_orders WHERE customer_id = 19135;
SELECT COUNT(*) FROM big_orders WHERE customer_id = 18948;
SELECT COUNT(*) FROM big_orders WHERE customer_id = 18825;
  id   
-------
 19135
 18948
 18825
(3 rows)

 count 
-------
     7
(1 row)

 count 
-------
     8
(1 row)

 count 
-------
    13
(1 row)

Four round trips for three customers; a page of 100 customers would need 101. One query with a LEFT JOIN (Lesson 13) and GROUP BY gives the same answer:

SELECT c.id, COUNT(o.id) AS orders
FROM (SELECT id, signup_date FROM big_customers
      ORDER BY signup_date DESC, id DESC LIMIT 3) AS c
LEFT JOIN big_orders o ON o.customer_id = c.id
GROUP BY c.id, c.signup_date
ORDER BY c.signup_date DESC, c.id DESC;
  id   | orders 
-------+--------
 19135 |      7
 18948 |      8
 18825 |     13
(3 rows)

LIMIT with ORDER BY and an index

“The latest 10 orders” is fast when an index has the same order as ORDER BY. Compare it with sorting by total, which has no index:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, order_date, total FROM big_orders
ORDER BY order_date DESC, id DESC LIMIT 10;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, order_date, total FROM big_orders
ORDER BY total DESC LIMIT 10;
                                          QUERY PLAN                                           
-----------------------------------------------------------------------------------------------
 Limit (actual rows=10 loops=1)
   ->  Index Scan Backward using big_orders_date_id_idx on big_orders (actual rows=10 loops=1)
(2 rows)

                           QUERY PLAN                            
-----------------------------------------------------------------
 Limit (actual rows=10 loops=1)
   ->  Sort (actual rows=10 loops=1)
         Sort Key: total DESC
         Sort Method: top-N heapsort  Memory: 25kB
         ->  Seq Scan on big_orders (actual rows=200000 loops=1)
(5 rows)

The index is read backwards and stops after 10 rows. Without an index, all 200,000 rows are scanned and sorted. Always use a unique order: without an ORDER BY that gives one, you “will get an unpredictable subset of the query’s rows” (PostgreSQL docs: LIMIT and OFFSET).

Pagination: keyset vs OFFSET

OFFSET pagination (Lesson 7) skips rows, but “the rows skipped by an OFFSET clause still have to be computed inside the server”. Keyset pagination remembers the last row of the previous page and continues after it with a row comparison, (order_date, id) > (...), which compares “left-to-right” (PostgreSQL docs: Row Constructor Comparison). Row 100,000 in (order_date, id) order is order 157215 on 2025-06-02, so both queries below return the next page (5 rows to keep it short):

SELECT id, order_date FROM big_orders
ORDER BY order_date, id
LIMIT 5 OFFSET 100000;

SELECT id, order_date FROM big_orders
WHERE (order_date, id) > ('2025-06-02', 157215)
ORDER BY order_date, id
LIMIT 5;
   id   | order_date 
--------+------------
 157260 | 2025-06-02
 157865 | 2025-06-02
 158437 | 2025-06-02
 162570 | 2025-06-02
 163298 | 2025-06-02
(5 rows)

   id   | order_date 
--------+------------
 157260 | 2025-06-02
 157865 | 2025-06-02
 158437 | 2025-06-02
 162570 | 2025-06-02
 163298 | 2025-06-02
(5 rows)

Same rows. Now look at the work:

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, order_date FROM big_orders
ORDER BY order_date, id
LIMIT 5 OFFSET 100000;

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, order_date FROM big_orders
WHERE (order_date, id) > ('2025-06-02', 157215)
ORDER BY order_date, id
LIMIT 5;
                                          QUERY PLAN                                           
-----------------------------------------------------------------------------------------------
 Limit (actual rows=5 loops=1)
   ->  Index Only Scan using big_orders_date_id_idx on big_orders (actual rows=100005 loops=1)
         Heap Fetches: 0
(3 rows)

                                        QUERY PLAN                                        
------------------------------------------------------------------------------------------
 Limit (actual rows=5 loops=1)
   ->  Index Only Scan using big_orders_date_id_idx on big_orders (actual rows=5 loops=1)
         Index Cond: (ROW(order_date, id) > ROW('2025-06-02'::date, 157215))
         Heap Fetches: 0
(4 rows)
SQL query optimization in Lesson 33: to return the same 5 orders, OFFSET 100000 reads 100,005 index entries while keyset pagination with (order_date, id) > ('2025-06-02', 157215) reads only 5.
OFFSET reads and throws away every earlier row; keyset pagination jumps straight to the last row seen.

OFFSET read 100,005 index entries to return 5; keyset read 5, and it stays at 5 on any page. The trade-off: keyset cannot jump straight to page 5,000, only to the next or previous page.

The SQL query optimization checklist

  1. Measure first: run EXPLAIN (ANALYZE, BUFFERS) on realistic data, not a toy table.
  2. Keep statistics fresh: ANALYZE after big loads or changes.
  3. Keep filters sargable: no functions, maths or casts on indexed columns; use ranges for dates.
  4. Avoid leading wildcards in LIKE; use prefixes with a text_pattern_ops index.
  5. Compare columns with values of the same type.
  6. Select only the columns you need.
  7. Index the columns you filter, join and sort on, including foreign keys.
  8. Use EXISTS for “has any” and NOT EXISTS for “has none”.
  9. Replace N+1 loops with one set-based query.
  10. Pair LIMIT with a unique ORDER BY that an index can serve.
  11. Paginate with keyset, not large OFFSET values.
  12. Change one thing at a time and check the plan again.

Try it yourself

Use the practice tables, indexes and SET from the setup.

Exercise 1: Make a filter sargable

Rewrite WHERE order_date + 30 > '2026-10-31' so it can use the index, and prove both versions count the same rows.

Exercise 2: Keyset pagination for customers

The last customer on the current page is 12345 (signed up 2023-12-17). Order customers by signup_date, id, add a fitting index, and fetch the next 5.

Exercise 3: EXISTS

Count the customers in Italy who have at least one cancelled order.

Solutions

Solution 1

EXPLAIN (COSTS OFF)
SELECT COUNT(*) FROM big_orders WHERE order_date > DATE '2026-10-31' - 30;

SELECT
  (SELECT COUNT(*) FROM big_orders WHERE order_date + 30 > '2026-10-31') AS before,
  (SELECT COUNT(*) FROM big_orders WHERE order_date > DATE '2026-10-31' - 30) AS after;
                            QUERY PLAN                            
------------------------------------------------------------------
 Aggregate
   ->  Index Only Scan using big_orders_date_id_idx on big_orders
         Index Cond: (order_date > '2026-10-01'::date)
(3 rows)

 before | after 
--------+-------
   5882 |  5882
(1 row)

Move the arithmetic to the constant side; PostgreSQL computes DATE '2026-10-31' - 30 once.

Solution 2

CREATE INDEX big_customers_signup_id_idx ON big_customers (signup_date, id);

SELECT id, signup_date FROM big_customers
WHERE (signup_date, id) > ('2023-12-17', 12345)
ORDER BY signup_date, id
LIMIT 5;
CREATE INDEX
  id   | signup_date 
-------+-------------
 12640 | 2023-12-17
 12860 | 2023-12-17
 13243 | 2023-12-17
 13395 | 2023-12-17
 13889 | 2023-12-17
(5 rows)

The next customers signed up on the same day with higher ids; EXPLAIN ANALYZE shows an index-only scan that reads 5 rows.

Solution 3

SELECT COUNT(*) FROM big_customers c
WHERE c.country = 'Italy'
  AND EXISTS (SELECT 1 FROM big_orders o
              WHERE o.customer_id = c.id AND o.status = 'cancelled');
 count 
-------
   936
(1 row)

EXPLAIN shows a Hash Semi Join: each customer is returned once, however many cancelled orders they have.

When you finish, drop the practice tables:

DROP TABLE big_orders, big_customers;
DROP TABLE

Common mistakes

  • Wrapping the indexed column. EXTRACT(...), lower(...), order_date + 30 or a cast on the column turn an index scan into a seq scan. There is no error message, only a slow plan.
  • Keyset with AND. WHERE order_date > '2025-06-02' AND id > 157215 is not the same as (order_date, id) > ('2025-06-02', 157215): in our data it matched 21,466 rows instead of 100,000, so pages silently lose rows.
  • NOT IN with a NULL. WHERE id NOT IN (VALUES (1), (NULL)) returned 0 customers. Use NOT EXISTS.
  • Comparing a number column with text. A string that looks like a number works (customer_id = '4242' still used the index), but customer_id = 'abc' fails with invalid input syntax for type integer: "abc". Validate input in your application.
  • Large OFFSET values. Every page reads all the rows before it; use keyset pagination for deep pages.

Frequently asked questions

What does sargable mean in SQL?

A sargable condition can use an index to find rows. In practice, it compares a plain column with a value, such as order_date >= '2026-03-01'. A condition that changes the column first, such as EXTRACT(YEAR FROM order_date) = 2026, is non-sargable unless you have an index on that exact expression.

Is EXISTS faster than IN in PostgreSQL?

For “has any” checks, PostgreSQL can plan both the same way, as it did here. The real difference is NOT IN vs NOT EXISTS: NOT IN behaves unexpectedly when the subquery returns a NULL, so prefer NOT EXISTS.

Why is OFFSET slow for large page numbers?

The database still has to find and skip every row before the offset. Our page at OFFSET 100000 read 100,005 index entries to return 5 rows. Keyset pagination continues from the last row seen, so each page costs about the same.

Summary

  • SQL query optimization starts with EXPLAIN (ANALYZE, BUFFERS): measure, change one thing, measure again.
  • Keep filters sargable: no functions, arithmetic or type casts on indexed columns, and no leading % in LIKE.
  • Select only needed columns and keep statistics fresh with ANALYZE.
  • Use EXISTS / NOT EXISTS for existence checks and one set-based query instead of N+1 queries.
  • Serve ORDER BY ... LIMIT from an index and paginate with keyset instead of a large OFFSET.

Next lesson

Next: Lesson 34, Transaction Isolation Levels, Locks and Deadlocks.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *