You are on page 1of 1

Chapter 1: Creating 15

In this example, the user can be expected to enter at least the first three charac-
ters of the desired postal code and the first two from street name before asking
for a list to be displayed, so a computed column called fast_search can be
added:
CREATE TABLE street (
pkey INTEGER NOT NULL DEFAULT AUTOINCREMENT,
fast_search VARCHAR ( 5 ) NOT NULL
COMPUTE ( STRING ( LEFT ( postal_code, 3 ),
LEFT ( street_name, 2 ) ) ),
street_name VARCHAR ( 100 ) NOT NULL,
range_part_1 INTEGER NOT NULL,
range_part_2 VARCHAR ( 100 ) NOT NULL,
postal_code VARCHAR ( 6 ) NOT NULL,
PRIMARY KEY ( pkey ) );
Now a beneficial index can be created and the new column added to the
WHERE clause; the optimizer will use the new index to speed things up.
CREATE CLUSTERED INDEX xfast ON street ( fast_search );

SELECT *
FROM street
WHERE fast_search = 'L6HGR'
AND street_name LIKE 'GRAND%'
AND postal_code LIKE 'L6H5%';
All the computed columns in a single row are automatically calculated when-
ever a row is inserted and they are recalculated when the row is updated. All the
computed columns in all the rows are recalculated whenever the table schema is
altered to change any column data type or COMPUTE clause, to add, delete, or
rename any column, or to rename the table. Computed columns are not recalcu-
lated when rows are retrieved; this makes them efficient for queries and indexes
but they may be unsuitable for time-dependent expressions.

Tip: A computed column with an index can be used to optimize existing que-
ries. For example, suppose many queries containing WHERE ( x + y + z ) would
benefit from an index on ( x + y + z ), where x, y, and z are columns in the same
table. You can have the query optimizer automatically replace the expression
with a reference to the computed column if you follow two rules. First, code the
COMPUTE expression in the same order of arguments and operators as it
appears in the WHERE clause. Second, make the data type of the computed col-
umn the same as that of the expression; use the EXPRTYPE function to figure out
what that is.

Here is a table that could benefit from a computed column because the SELECT
does a full-table scan:
CREATE TABLE t (
pkey INTEGER NOT NULL DEFAULT AUTOINCREMENT,
x INTEGER,
y INTEGER,
z INTEGER,
PRIMARY KEY ( pkey ) );

SELECT * FROM t WHERE ( x + y + z ) BETWEEN 1501 AND 1510;

You might also like