473,406 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

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.identityid
INNER JOIN licenses l on i.licenseid=l.id
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 2216
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.identityid
INNER JOIN licenses l on i.licenseid=l.id
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_category 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_category = 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.identityid
INNER JOIN licenses l on i.licenseid=l.id
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.identityid
INNER JOIN licenses l on i.licenseid=l.id
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_category 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_category = 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**********@gmail.com) writes:
SELECT licenseKey, (
SELECT TOP 1 mi.id FROM messages mi
INNER JOIN identities i ON i.id=mi.identityid
INNER JOIN licenses l on i.licenseid=l.id
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.identityid
JOIN licenses l on i.licenseid=l.id
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.created is. Also, I'm assuming here that every license will
have a match in identities/messages.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.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
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...
1
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...
8
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...
1
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. ...
14
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...
4
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...
4
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...
1
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...
4
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.