Solved

Where to put the Where Clause

Posted on 2008-10-01
2
198 Views
Last Modified: 2010-03-20
This should be a simple question...

I am using UNION to join multiple tables with the same columns. At the end of the my UNION I am aliasing the whole thing as a tableX. After that I have a WHERE statement and a GROUP statement. Efficiency is of great importance! I want to know if it makes a difference from an effeciency standpoint if I repeat the WHERE and GROUP clause with each table in the union, or if I just have it at the end after the alais.
0
Comment
Question by:MapleMale
2 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 22615514
the WHERE clause should be per each SELECT.
SELECT ...
  FROM ...
 WHERE ...
 GROUP BY ...
UNION ALL
SELECT ...
  FROM ...
 WHERE ... 
 GROUP BY ...

Open in new window

0
 
LVL 39

Accepted Solution

by:
BrandonGalderisi earned 250 total points
ID: 22615530
If you put your where clause and group by in each part of the union, then the # of records returned will be lower in each part of the union.  Also, your where and group by can utilize the indexes of the table.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
CONVERT date time to a different time zone. 2 45
SQL Server R2 Stored procedure performance 8 44
Caste datetime 2 52
Oracle 10g - insert string with special characters 8 41
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now