SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Subquery performace
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

xalpha
Starting Member

13 Posts

Posted - 09/24/2012 :  04:47:59  Show Profile  Reply with Quote
Hello,
I have a little question about the subquery performace. I have a statement like this on a really big database:

SELECT *
FROM [Users] where User_ID in (SELECT MAX([User_ID]) FROM [Users] GROUP BY USERGROUP)

The result should be the newest user of each usergroup. The result is right but it is really really slow on a big database. Is there a possibility to design this query with a better performace?

Thank you for every hint.

Ifor
Aged Yak Warrior

622 Posts

Posted - 09/24/2012 :  06:00:51  Show Profile  Reply with Quote
1. Check there is an index on Users.[User_id]
(Or even better [UserGroup], [User_Id])

2. Try the usual variations:

SELECT *
FROM Users U
WHERE EXISTS
(
	SELECT *
	FROM Users U1
	GROUP BY U1.UserGroup
	HAVING U.[User_Id] = MAX(U1.[User_Id])
);

WITH MaxUsers
AS
(
	SELECT MAX([User_Id]) AS [User_Id]
	FROM Users
	GROUP BY UserGroup
)
SELECT U.*
FROM Users U
	JOIN MaxUsers M
		ON U.[User_Id] = M.[User_Id];

SELECT U.*
FROM Users U
	CROSS APPLY
	(
		SELECT MAX(U1.[User_Id])
		FROM Users U1
		WHERE U1.UserGroup = U.UserGroup
	) D
WHERE U.[User_Id] = D.[User_Id];


Edited by - Ifor on 09/24/2012 06:02:15
Go to Top of Page

xalpha
Starting Member

13 Posts

Posted - 09/24/2012 :  08:34:43  Show Profile  Reply with Quote
Thank you! I'm very impressed about the speed of your Statement. With my version it was so slowly and now it is completely executed right after clicking the button. A great Solution.

Matthias
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000