Course contentsShow
← Databases & SQL
Lesson 635 of 1,9536. Query Performance and IndexingFree lesson

Expression Pre-calculation

Create virtual columns or materialized views to index complex expressions.

In this lesson, you will learn how to optimize queries by pre-calculating complex expressions so the database doesn't have to perform expensive math every time you search your data.

The Problem with On-the-Fly Calculations

When you write a query like SELECT * FROM Orders WHERE (Price * TaxRate) > 100, the database engine must calculate Price * TaxRate for every single row in the table before it can decide if that row matches your criteria. If you have millions of rows, this calculation happens millions of times. Because the result of this expression isn't stored in the table, the database is often forced to perform a "Full Table Scan"—looking at every record individually—because it cannot use a standard index to find the result.

The Solution: Pre-calculation

To speed this up, we "materialize" the result of that expression so it is physically stored on the disk. There are two primary ways to do this:

  1. Virtual Columns (or Computed Columns): You define a column that automatically calculates its value based on other columns. You can then create an index on this virtual column.

    -- Adding a computed column
    ALTER TABLE Orders ADD TotalCost AS (Price * TaxRate);
    
    -- Indexing it so the database can 'Seek' instead of 'Scan'
    CREATE INDEX idx_total_cost ON Orders(TotalCost);
    
  2. Materialized Views: If your expression involves complex joins or aggregations, you can store the result of the entire query in a materialized view. The database treats this view like a physical table, updating it periodically so your queries simply read the pre-calculated answer.

Why This Improves Performance

By pre-calculating the expression, you move the "work" from the moment of query execution to the moment of data insertion or update. When you run your WHERE clause, the database no longer sees a complex calculation; it sees a simple, indexed column. It can now navigate the index tree (an Index Seek) to find the relevant rows instantly, rather than reading and calculating every single row in your dataset. This transforms a heavy, linear operation into a fast, logarithmic one.

Key Takeaway: By pre-calculating complex expressions via virtual columns or materialized views, you allow the query optimizer to leverage indexes, dramatically reducing CPU load and disk I/O.