Optimization Tip for SQL 6.5: Using UNION ALL Statement


If you use OR logical operation to find rows from a MS SQL 6.5
table, and there is index on the field for which values you use OR
operation, then MS SQL 6.5 can use worktable with dynamic index
on searchable field instead simple index search. You can check it by
setting SET SHOWPLAN ON. So, if the table is very big, it can take
a lot of time. This is the example of simple table creation and addition
of new rows into this table:


CREATE TABLE TestTable (
f1 int identity primary key,
f2 char(50)
)
GO
DECLARE @i int
SELECT @i = 1
WHILE @i <= 1000 BEGIN INSERT INTO TestTable VALUES (LTRIM(str(@i))) SELECT @i = @i + 1 END GO CREATE INDEX ind_f2 ON TestTable (f2) GO

If you want to find all rows from the table TestTable where f2 = ‘100’
or f2 = ‘500’, you can use the following select statement:


SELECT * FROM TestTable WHERE f2 = ‘100’ OR f2 = ‘500’

You can increase the speed of this query by divide it into to select
statement and union this statements with UNION ALL operator. For each
query the appropriate index will be used, and this way can increase
the speed of the new select statement in several times in comparison
with the first one.

There are physical read and logical read operations. A logical read occurs
if the page is currently in the cache. If the page is not currently in the
cache, a physical read is performed to read the page into the cache.To see
how many logical or physical read operations were made, you can use
SET STATISTICS IO ON command. This is the example:


SET NOCOUNT ON
GO
SET STATISTICS IO ON
GO
SELECT * FROM TestTable WHERE f2 = ‘100’ OR f2 = ‘500’
GO
SELECT * FROM TestTable WHERE f2 = ‘100’
UNION ALL
SELECT * FROM TestTable WHERE f2 = ‘500’
GO
SET STATISTICS IO OFF
GO

These are the results:


f1 f2
———– ————————————————–
500 500
100 100
Table: TestTable scan count 2, logical reads: 8, physical reads: 0, read
ahead reads: 0
Table: Worktable scan count 3, logical reads: 11, physical reads: 3, read ahead reads: 0
f1 f2
———– ————————————————–
100 100
Table: TestTable scan count 1, logical reads: 3, physical reads: 0, read
ahead reads: 0
500 500
Table: TestTable scan count 1, logical reads: 3, physical reads: 0, read
ahead reads: 0


»


See All Articles by Columnist
Alexander Chigrik

Alexander Chigrik
Alexander Chigrik
I am the owner of MSSQLCity.Com - a site dedicated to providing useful information for IT professionals using Microsoft SQL Server. This site contains SQL Server Articles, FAQs, Scripts, Tips and Test Exams.

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles