Solved

T-SQL: Making an ugly query better

Posted on 2009-07-02
4
307 Views
Last Modified: 2012-06-27
I can usually get by when it comes to SQL, but I'm no whiz. In the example I've included, the task is to end up with a list of:

* all search records that match the user's search criterion (lastname starts with T), OR
* that have email addresses matching records in the first group.

I have a query that seems (after minimal testing) to work. First I get the name matches; then supplement my results with the matching non-blank emails; then, for cases of multiple identical emails, I show only the record with the best (lowest) Priority score.

My question is: is there a more concise way to rephrase this query? (I don't have the option to restructure the database.) Something that left me with about three less WITH's -- i.e., a lone query -- would be ideal, but any improvement would be good.

WITH
NarrowedTable AS
(select id, email from tmp_test
where (lastname like 't%')),
 
ExtraEmailsTable AS
(select id from NarrowedTable
union
select id from tmp_test tt
where (coalesce(tt.email, '') > '')
and (tt.email in (select email from narrowedtable))),
 
InnerTable AS(
SELECT row_number() over(partition by email order by priority) as myrank,
id,
email,
lastname
from tmp_test tt
where (coalesce(Email, '') > '')
and (tt.id in (select id from ExtraEmailsTable))
union
SELECT 1 as myrank,
id,
email,
lastname
from tmp_test tt
where (coalesce(Email, '') = '')
and (tt.id in (select id from ExtraEmailsTable)))
 
select * from InnerTable
where myrank = 1
order by Email, lastname;

Open in new window

0
Comment
Question by:180246
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 167 total points
ID: 24768276
seems fine to me, except to put some comments into the code, and to use UNION ALL instead of UNION to avoid the implicit Distinct...
0
 
LVL 26

Assisted Solution

by:Chris Luttrell
Chris Luttrell earned 167 total points
ID: 24768432
I agree with angelIII that it seems fine logically.  Getting rid of some of your CTE "withs" will add to the complexity of the final query by having to do extra subselects or joins there so that is matter of oppion if that is a "better" query or not.  If something in the query is not performing right or too slow then if you share some table structure and sample data that is causing a problem we could evaluate it better.
0
 
LVL 15

Assisted Solution

by:rob_farley
rob_farley earned 166 total points
ID: 24769095
The WITHs are good - they modularise your query nicely.

As the others say, there are other ways to improve the query, but you should embrace the WITH. I've helped many complex queries by introduce a bunch of CTEs.

Rob
0
 

Author Closing Comment

by:180246
ID: 31599388
Thank you all for the feedback! It's good to know I wasn't too far out in left field. I'm not aware of any performance problems with it at this point -- just figured that since I was using some features I haven't touched before, I should get a sanity check. I hope an even split of points (as even as I could make it) will be OK with you all.
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to insert gas or chemical names in SQL server. For e.g. CO2 to CO₂. 5 86
SSRS 2013 - Overlapping reports 2 38
What is this datetime? 1 27
How can I find this data? 3 25
Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

756 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