Math


There is one more class of obfuscations that is smart and prevents proper index usage. Instead of using logic expressions it is using a calculation.

Consider the following statement. Can it use an index on NUMERIC_NUMBER?

SELECT numeric_number
  FROM table_name
 WHERE numeric_number - 1000 > ?

Similarly, can the following statement use an index on A and B—you choose the order?

SELECT a, b
  FROM table_name
 WHERE 3*a + 5 = b

Let’s put these questions into a different perspective; if you were developing an SQL database, would you add an equation solver? Most database vendors just say “No!” and thus, neither of the two examples uses the index.

About our book “SQL Performance Explained”
Probably the best book on SQL performance I've read
Guillaume Lelarge on Amazon.co.uk (5 stars)

You can even use math to obfuscate a condition intentionally—as we did it previously for the full text LIKE search. It is enough to add zero, for example:

SELECT numeric_number
  FROM table_name
 WHERE numeric_number + 0 = ?

Nevertheless we can index these expressions with a function-based index if we use calculations in a smart way and transform the where clause like an equation:

SELECT a, b
  FROM table_name
 WHERE 3*a - b = -5

We just moved the table references to the one side and the constants to the other. We can then create a function-based index for the left hand side of the equation:

CREATE INDEX math ON table_name (3*a - b)

If you like my way of explaining things, you’ll love my book.

About the Author

Photo of Markus Winand
Markus Winand tunes developers for high SQL performance. He also published the book SQL Performance Explained and offers in-house training as well as remote coaching at http://winand.at/

?Recent questions at
Ask.Use-The-Index-Luke.com

2
votes
1
answer
1.5k
views
0
votes
2
answers
876
views

different execution plans after failing over from primary to standby server

Sep 17 at 11:46 Markus Winand ♦♦ 771
oracle index update
1
vote
1
answer
310
views

Generate test data for a given case

Sep 14 at 18:11 Markus Winand ♦♦ 771
testcase postgres