Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Indexes on expressions
2. Indexing problems – example 1
Partial indexes
Clustered indexes
Summary

Instruction

Let's assume we've got the following table and index:

CREATE TABLE invoice (
  id integer PRIMARY KEY,
  issued date,
  net_amount decimal(8, 2),
  final_amount decimal(8, 2)
);

CREATE INDEX date_ind
ON invoice(issued);

We're asked to retrieve all invoices from 2017:

SELECT
  *
FROM invoice
WHERE EXTRACT(year FROM issued) = 2017;

The above query would work, but our index won't be used! That's because the column issued is hidden in an EXTRACT() function call. Your database treats the expression EXTRACT(year FROM issued) as a black box – it doesn't understand what EXTRACT(...) does, it just knows that there is no index created for this black box.

If we want to use the index, we should rewrite the query so that the column is visible to the database:

SELECT
  *
FROM invoice
WHERE issued >= '2017-01-01'
  AND issued < '2018-01-01';

This query yields the same results. But since the column isn't hidden inside a function call, the database can use the index.

Exercise

Click Next exercise to continue.