473,856 Members | 1,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subquery -> slowness

I have some queries that involve subqueries to select the appropriate
record from a bunch of candidates. For example the following, which
selects the most recent transaction for a given customer:

CREATE TABLE #Customer (CustID int, OtherInfo int)
INSERT #Customer SELECT 1,7
INSERT #Customer SELECT 2,8
INSERT #Customer SELECT 3,9

CREATE TABLE #Event (CustID int, EventID int, EventAmt int, EventDt
INSERT #Event SELECT 1,1,1000,'20060 224'
INSERT #Event SELECT 2,1,2000,'20060 224'
INSERT #Event SELECT 3,2,3000,'20060 224'
INSERT #Event SELECT 3,1,5000,'20060 225'

SELECT c.CustID,c.Othe rInfo ,e.EventAmt,e.E ventDt
FROM #Customer c JOIN #Event e ON c.CustID=e.Cust ID
WHERE EventDt = (SELECT MAX(EventDt) FROM #Event WHERE CustID=c.CustID )

Over millions of customers and events, this takes forever. Creating a
temp table which identifies the appropriate dates, and then joining to
that, speeds things up considerably -- the following two queries
together take a lot less time the the one above.

CREATE TABLE #Temp (CustID int,EventDt smalldatetime)

SELECT c.CustID,c.Othe rInfo ,e.EventAmt,e.E ventDt
FROM #Customer c
JOIN #Temp t ON t.CustID=c.Cust ID
JOIN #Event e ON c.CustID=e.Cust ID AND t.EventDt=e.Eve ntDt

This seems pretty simple, and I would assume the query planner should
be able to figure it out without assistance. Is there a better way to
forumulate the original query? BTW, as far as I can tell the indexes
are appropriate for these queries; however the subqueries seem to be
done one at a time.

Feb 24 '06 #1
2 1414

you are correct: although sometimes the optimizer will refactor queries
with subqueries as joins, do not rely on it doing that in all the

Try this:

SELECT c.CustID,c.Othe rInfo ,e.EventAmt,e.E ventDt
FROM #Customer c JOIN #Event e ON c.CustID=e.Cust ID
(SELECT MAX(EventDt) maxEventDt, CustID FROM #Event e group by CustID)
m ON c.CustID=e.Cust ID and .EventDt = m.maxEventDt

Good luck!

Feb 24 '06 #2
Thanks, Alexander. I'll try that.


Feb 24 '06 #3

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

Similar topics

by: lev | last post by:
CREATE TABLE . ( NULL , , (44) ) ID is non-unique. I want to select all IDs where the last entry for that ID is of type 11.
by: Andrew Mayo | last post by:
Here's a really weird one for any SQL Server gurus out there... We have observed (SQL Server 2000) scenarios where a stored procedure which (a) begins a transaction (b) inserts some rows into a table (c) re-queries another table using a subquery which references the inserted table (correlated or not)
by: Greg Stark | last post by:
Postgresql 7.4b2 (approximately, compiled out of CVS) When I have a subquery that has a complex subquery as one of the result columns, and then that result column is used multiple times in the parent query, the subquery is inlined for each one. This means multiple redundant executions of the subquery. I recall there was a way to defeat this optimization involving introducing an extra subquery layer somewhere. But I'm failing to be able...
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
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a couple of tables in my database using INNER JOINS and the WHERE clause to specify the required constraints. However, I also want to read two fields from a *single* record from a table called 'Locations' and then apply one of these field's values...
by: K. Crothers | last post by:
I administer a mechanical engineering database. I need to build a query which uses the results from a subquery as its input or criterion. I am attempting to find all of the component parts of which a part may be composed. I have a table of parts and their subparts. The problem is that each of those subparts may be composed of smaller component parts. The subpart would then be listed in the Part field linked to each of its subparts in...
by: Rod | last post by:
I have a client site where the code below has been working happily for at least four months. The site is using SQL Server 7. The code is ASP.NET Last week an error appeared related to the following SQL statement. INSERT INTO OrderItems (ClientID, ProductID, OrderHeaderID, Quantity, Dispatched, BackOrdered) SELECT ClientID, ProductID, 1371 AS OrderHeaderID, Quantity, Dispatched, BackOrdered FROM Basket WHERE RequisitionID = 1369 The...
by: Kevin Murphy | last post by:
I'm using PG 7.4.3 on Mac OS X. I am disappointed with the performance of queries like 'select foo from bar where baz in (subquery)', or updates like 'update bar set foo = 2 where baz in (subquery)'. PG always seems to want to do a sequential scan of the bar table. I wish there were a way of telling PG, "use the index on baz in your plan, because I know that the subquery will return very few results". Where it really matters, I have...
by: Anne | last post by:
Hello! Here is the statement in question: --STATEMENT A SELECT * FROM dbo.myTable WHERE colX in (SELECT colX FROM dbo.sourceTable) The problem with Statement A is that 'colX' does not exist in 'dbo.sourceTable'. It does, however, certainly exist in 'dbo.myTable'. Breaking the statement down, we have:
by: jcf378 | last post by:
Hi all-- Does anyone have any insight as to how I might create a search form that allows a user to select criteria based on any related table in the whole database. The search form I have now only allows me to filter based on variables in a single table. I would like to have a search form where I can select multiple variables (from various linked tables) to filter by, and return results based on this multi-table filter. Allen Browne...
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,...
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
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,...
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
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();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
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.