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

Instruction

Let's take a look at another example. We've got the same table and two new indexes:

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

CREATE INDEX net_am
ON invoice(net_amount);

CREATE INDEX final_am
ON invoice(final_amount);

We issued some invoices in a country where the final amount is 115% of the net amount plus a fixed fee of 30.0 for every invoice. We want to estimate the number of invoices that follow this pattern:

SELECT
  COUNT(id)
FROM invoice
WHERE net_amount * 1.15 + 30.0 = final_amount;

In other words, we count the invoices where the final amount is 115% of the net amount, plus a fixed fee of 30.0. While the query looks completely legit, the indexes can't be used. Why not? Because there are indexed columns on both sides of the equation. Databases can't handle that. However, we can use a simple trick to get around this problem:

SELECT
  COUNT(id)
FROM invoice
WHERE net_amount * 1.15 - final_amount = -30;

We used simple mathematical rules to put all columns on a single side of the equation. In this part we'll learn how to use an expression like this in an index.

Exercise

Click Next exercise to continue.