MSSQLCity.Com - All about MS SQL
     
About Us  
SSWUG Articles  
Articles  
Administering  
Comparison  
General  
Know How  
Replication  
Tuning  
Undocumented  
UDF  
SQL 6.5  
FAQ  
Scripts  
Tips  
Test Exams  
Advertise  
Download  
History  
Search  
Traffic  
Related Links  
     
Your button logo
Add to Favorites
 
     
 

Using UNION ALL statement in SQL Server 6.5

Alexander Chigrik
chigrik@mssqlcity.com


If you use OR logical operation to find rows from a SQL Server 6.5 table, and there is index on the field for which values you use OR operation, then SQL Server 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 tbTest (
  field1 int identity primary key,
  field2 char(10)
)
GO
DECLARE @i int
SELECT @i = 1
WHILE @i <= 10000
  BEGIN
    INSERT INTO tbTest VALUES (LTRIM(str(@i)))
    SELECT @i = @i + 1
  END
GO
CREATE INDEX ind_field2 ON tbTest (field2)
GO
If you want to find all rows from the table tbTest where field2 = '1000' or field2 = '5000', you can use the following select statement:

SELECT * FROM tbTest WHERE field2 = '1000' OR field2 = '5000'

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 tbTest WHERE field2 = '1000' OR field2 = '5000' 
GO
SELECT * FROM tbTest WHERE field2 = '1000'
UNION ALL
SELECT * FROM tbTest WHERE field2 = '5000'
GO
SET STATISTICS IO OFF
GO

 

 
Visit The SQL Server Worldwide User's Group for all the latest news and information about SQL Server, Oracle, DB2 and XML for developers and administrators.

(c) 1997, 2010 Bits on the Wire, Inc