Question:
SQL: Way to select 2nd largest ID?
Rob
2006-10-06 08:04:06 UTC
I have a SQL table with two fields that matter for this select:

ID - unique numeric ID
NAME

I want to select the row having the 2nd largest ID where the NAME equals a known value. Is there a way to do this with a SQL statement or do I need to select all rows with NAME = to my value and parse out the row I want in a loop?

I know I can order the results by ID and just loop to the 2nd result, but I'd rather have the answer returned to me with a single SQL call.
Three answers:
Paryank Kansara
2006-10-06 08:41:55 UTC
SELECT MAX(ID) FROM table_name WHERE ID IN (SELECT ID FROM table_name MINUS SELECT MAX(ID) FROM table_name)
Norman
2006-10-06 08:29:21 UTC
You can use the MAX keyword to retrieve the largest item in a row so your sql can be as follows:



SELECT MAX(ID) FROM TABLENAME WHERE NAME='value'
2006-10-06 10:57:23 UTC
select name, max(ID) from MyTable where ID <> (select max(ID) from MyTable) and name = 'string'

GO


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...