CodeBlanks Logo Icon CodeBlanks

Rewriting queries

Make the query sargable.

Rewrite the query

In the fourth step you turn a non-sargable condition like DATE(created_at) = '2026-01-01' into a form the index can use: created_at >= ... AND created_at < ....

-- YANLIŞ: WHERE DATE(created_at) = '2026-01-01'
-- DOĞRU: WHERE created_at >= '2026-01-01'
--        AND created_at < '2026-01-02'

Sargable uses the index.

Rewrite the query — details

Wrapping a column in a function disables the index. Instead of DATE(created_at) you write a range condition. The index kicks back in and the plan speeds up.

Practice Rewrite the query

Write a sargable query: use created_at >= '2026-01-01' AND created_at < '2026-01-02'.

Starter code

query.sql
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  customer_id INT,
  amount NUMERIC,
  created_at TIMESTAMP
);
-- read plan
EXPLAIN SELECT * FROM orders WHERE customer_id = 5;
-- add index
CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (amount);
-- sargable rewrite
SELECT * FROM orders WHERE

Sample solution

query.sql
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  customer_id INT,
  amount NUMERIC,
  created_at TIMESTAMP
);
-- read plan
EXPLAIN SELECT * FROM orders WHERE customer_id = 5;
-- add index
CREATE INDEX idx_orders_customer ON orders (customer_id) INCLUDE (amount);
-- sargable rewrite
SELECT * FROM orders WHERE created_at >= '2026-01-01' AND created_at < '2026-01-02';

Expected output

Index Scan on orders using idx_orders_customer

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Rewriting queries: match the terms

Term Meaning
sargable sargable
function function
range range
index index

2 Range condition

Question
created_at >= '2026-01-01' AND created_at ____
Answer
created_at >= '2026-01-01' AND created_at < '2026-01-02'

Explanation: < '2026-01-02' is the right answer.

3 What does a non-sargable condition do?

  • Speeds up the index
  • Drops the table
  • It adds a column
  • Prevents the index from being used Correct answer

Explanation: A non-sargable condition disables the index.

All lessons in Expert