473,686 Members | 2,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Tough Correlated Subquery issue

I am running 2 versions of a correlated subquery. The two version
differ slightly in design but differ tremendously in performance.... if
anyone can answer this, you would be awesome.

The "bad" query attempts to build a result set using a correlated
subquery. The part causing the error is that the correlated subquery
is part of a derived table (joining 3 tables). Trying to run the query
takes a long time and the more records in the source table, the
performance is exponentially worse. When i change the derived table to
a fixed table, the query runs fast.

I look at the Execution Plan in Query Analyzer and the majority of time
is taken by the Clustered Index Seek and by the Nested Loops/Inner
Join.
*************** *************** *************** *************** *************** *************** *************** *
here is the "bad" query:
*************** *************** *************** *************** *************** *************** *************** *
SELECT licenseKey, (
SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identit yid
INNER JOIN licenses l on i.licenseid=l.i d
WHERE l.licenseKey = t1.licenseKey AND category = 'usage'
ORDER BY mi.created DESC
) as messageid
FROM licenses T1
*************** *************** *************** *************** *************** *************** *************** *
here is the "good" query
*************** *************** *************** *************** *************** *************** *************** *
SELECT licenseKey, (
SELECT TOP 1 t2.id FROM temptable T2
WHERE t2.licenseKey = t1.licenseKey
ORDER BY t2.created DESC
) as messageid
FROM licenses T1
*************** *************** *************** *************** *************** *************** *************** *

Thank you in advance

Aug 29 '06 #1
5 2236
it might be that the optimizer underestimates the cardinality of the
subquery:

SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identit yid
INNER JOIN licenses l on i.licenseid=l.i d
WHERE l.licenseKey = t1.licenseKey AND category = 'usage'
ORDER BY mi.created DESC

and comes up with a plan more appropriate for a small number of orws.
How many rows are there in the temporary table?
Are licenseKey AND category columns in one and the same table?
If yes, you could try to create a computed column named
licenseKey_cate gory AS CAST(licenseKey AS VARCHAR(...)) + ' ' +
category,
create an index on it, and rewrite your subquery instead of

WHERE l.licenseKey = t1.licenseKey AND category = 'usage'

try to use

WHERE l1.licenseKey_c ategory = CAST(licenseKey AS
VARCHAR(...)) + ' usage'

That's just one possibility.

Aug 29 '06 #2
Thank you for your response...here is a little more information:
1. there are about 170,000 records in the temptable/derived table
2. i accidentally included the "category" criteria...it does affect
the performance either way...sorry, i didn't want to confuse the
issue...
3. The main source table "licenses" contains about 10,000 records
4. When i look at the Execution Plan, it seems to be taking a long
time on the clustered index of the "identities " table. Which seems
weird that is it slowing down dealing with one of the indexes for the
derived table. I wasn't expecting this.

You may be right about the optimizer not assessing this query
correctly. I do not know much about how the optimizer makes
determinations about execution of the query. My hope is that is would
do the following:
1. Retrieve all the rows from the "licenses" table
2. For each row in the "licenses" table, join out to the result
of the derived table using the WHERE clause to restrict the number of
rows in each correlated query.
3. Return the TOP 1 of that correlated query.

here is the "bad" query again (simplified):
*************** *************** *************** *************** *************** *
SELECT licenseKey, (
SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identit yid
INNER JOIN licenses l on i.licenseid=l.i d
WHERE l.licenseKey = t1.licenseKey
ORDER BY mi.created DESC
) as messageid
FROM licenses T1
*************** *************** *************** *************** *************** *

- Steve

Alexander Kuznetsov wrote:
it might be that the optimizer underestimates the cardinality of the
subquery:

SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identit yid
INNER JOIN licenses l on i.licenseid=l.i d
WHERE l.licenseKey = t1.licenseKey AND category = 'usage'
ORDER BY mi.created DESC

and comes up with a plan more appropriate for a small number of orws.
How many rows are there in the temporary table?
Are licenseKey AND category columns in one and the same table?
If yes, you could try to create a computed column named
licenseKey_cate gory AS CAST(licenseKey AS VARCHAR(...)) + ' ' +
category,
create an index on it, and rewrite your subquery instead of

WHERE l.licenseKey = t1.licenseKey AND category = 'usage'

try to use

WHERE l1.licenseKey_c ategory = CAST(licenseKey AS
VARCHAR(...)) + ' usage'

That's just one possibility.
Aug 29 '06 #3
I have also observed that breaking a query with subqueries into two or
more steps with tables for the interfaces can outperform subqueries by
a substantial amount. Apparently the query planner has much better
knowledge of the scope of the queries. Having discrete tables also
allows building indexes (effectively cross-table indexes) specially
tailored for the final query.

Aug 29 '06 #4
(st**********@g mail.com) writes:
SELECT licenseKey, (
SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identit yid
INNER JOIN licenses l on i.licenseid=l.i d
WHERE l.licenseKey = t1.licenseKey AND category = 'usage'
ORDER BY mi.created DESC
) as messageid
FROM licenses T1
Correlated subqueries in the SELECT list is rarely good for performance.
Try:

SELECT m.licenseKey, m.id
FROM messages m
JOIN (SELECT l.licenseKey, maxcreated = (mi.created)
FROM messages mi
JOIN identities i ON i.id=mi.identit yid
JOIN licenses l on i.licenseid=l.i d
GROUP BY l.licenseKey) AS m1 ON m.created = m1.maxcreated

This may or may not yield the same result, depending on how unique
messages.create d is. Also, I'm assuming here that every license will
have a match in identities/messages.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Aug 29 '06 #5
Regarding performance of correlated subqueries, I could not agree more.
But your query will not retrieve licenses without messages, and
Steven's query does that. Steven, what are your requirements?

Aug 30 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
14998
by: Murali | last post by:
Hi All I was reading thro the posting(s) of Thomas Kyte and his nifty approach to doing updates without the need for unnecessary correlated subqueries. An alternative to correlated subquery using this technique is: update ( select columnName, value from name, lookup
1
5396
by: Jason | last post by:
Hello All, I have a SQL Query with multiple correlated Subqueries in it. When it gets executed it runs rather slow due to the size of the QT table. Does anybody have any suggestions how to alter this query to make it run faster, or any index suggestions to assist it with. Query is as follows: SELECT SH_ORDER, SH_CUST, SH_ADD_DATE, SH_CUST_REF, SH_DESC, SH_EXCL,
8
5099
by: Venkata C | last post by:
Hi! Does anyone here know of a way to goad DB2 into converting a correlated subquery to a non-correlated one? Does DB2 ever do such a conversion? We have a query of the form SELECT .. FROM A WHERE EXISTS (SELECT 'X' FROM B, C WHERE B.COL1 = A.COL1 AND B.COL2 = A.COL2
1
2399
by: Mike MacSween | last post by:
tblProductions one to many to tblEvents tblEvents contains StartDate I want a report where the data are grouped by tblProductions.ProdID, and sorted by the earliest date in each Production. So this as a query (I've stripped out surplus fields): SELECT qryEvent.EventName, qryProduction.ProdName, qryEvent.ProdID,
14
5706
by: mike | last post by:
I'm using postgresl 7.3.2 and have a query that executes very slowly. There are 2 tables: Item and LogEvent. ItemID (an int4) is the primary key of Item, and is also a field in LogEvent. Some ItemIDs in LogEvent do not correspond to ItemIDs in Item, and periodically we need to purge the non-matching ItemIDs from LogEvent. The query is: delete from LogEvent where EventType != 'i' and ItemID in
4
3179
by: sql_server_user | last post by:
Hi, I have a history table with about 400 million rows, with a unique composite nonclustered index on two columns (object id and time period) which is used for most of the queries into the table, and an identity column for the clustered primary key. Many of my queries use correlated subqueries to pull unique history rows from the history table for each of a set of objects from the object table, for instance, pulling the earliest...
4
2954
by: muzu1232004 | last post by:
Can anyone explain me when we use correlated subqueries rather than nested subqueries. Do all the correlated subqueries can be written in nested subqueries form as well ? What are the major conditions that apply whenever we write a correlated subquery and why we go for it ? Please let me know about this as i am not clear which to use when.
1
2877
by: lizandra | last post by:
Greetings, I am a newbie, I have been working to extract data from a basic sales db and trying to decide when I should use joins and when I should use subqueries. Much of what I read online says use subqueries only as a last resort, especially correlated ones as they do a record by record data evaluation and are very resource intensive. Are joins and WHERE and HAVING clauses the preferred method for extracting related data? But in SQL...
4
7194
by: lopez | last post by:
hi dere, i'm new to oracle.. can anybody help me with correlated subquery thanks in advance. regards, lopez (knowledge is power)
0
8584
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8516
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8932
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8768
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7599
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6440
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2945
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.