You are on page 1of 1

72 Chapter 3: Selecting

CREATE TABLE t1 (
key_1 INTEGER NOT NULL,
non_key_1 INTEGER NOT NULL,
PRIMARY KEY ( key_1 ) );

CREATE TABLE t2 (
key_1 INTEGER NOT NULL,
key_2 INTEGER NOT NULL,
PRIMARY KEY ( key_1, key_2 ),
FOREIGN KEY fk_t1 ( key_1 ) REFERENCES t1 ( key_1 ) );

CREATE TABLE t3 (
key_1 INTEGER NOT NULL,
non_key_1 INTEGER NOT NULL,
PRIMARY KEY ( key_1 ) );

INSERT t1 VALUES ( 1, 1 );
INSERT t1 VALUES ( 2, 2 );

INSERT t2 VALUES ( 2, 21 );
INSERT t2 VALUES ( 2, 22 );
INSERT t2 VALUES ( 2, 23 );

INSERT t3 VALUES ( 3, 333 );


INSERT t3 VALUES ( 4, 333 );
INSERT t3 VALUES ( 5, 0 );
INSERT t3 VALUES ( 6, 333 );

SELECT DISTINCT
TOP 4 START AT 2
t1.key_1 * 100 AS a,
t3.key_1 * 1000 AS b,
COUNT(*) AS c,
SUM ( t3.non_key_1 ) AS d
FROM ( t1 LEFT OUTER JOIN t2 ON t1.key_1 = t2.key_1 )
CROSS JOIN t3
WHERE b <= 5000
AND t3.non_key_1 = 333
GROUP BY ROLLUP ( t1.key_1, t3.key_1 )
HAVING COUNT(*) > 1
ORDER BY 1, 2;
The result set produced by the above SELECT looks like this:
a b c d
==== ==== = ====
100 NULL 2 666
200 NULL 6 1998
200 3000 3 999
200 4000 3 999
Heres how that SELECT is processed, with each logical step presented in more
detail:
Step 1: The FROM clause is evaluated to produce the candidate result set con-
sisting of all the columns returned by the FROM clause. These are called virtual
columns because they may or may not be the same as any select list items.
These virtual columns are required at this point because other clauses (WHERE,
ORDER BY, etc.) may refer to them even if they dont appear in the select list.
Each virtual column is named t.c, where t is a table, view, or correlation name,
and c is a column or alias name.

You might also like