tags:

views:

63

answers:

3

For example, given this table of sparse ids:

|id|
| 1|
| 2|
| 3|
| 6|
| 7|

I can obtain the highest "id" from my table using this query:

SELECT max(id) FROM Comics

I get:

|id|
| 7|

How can I get the "id" just preceding the highest "id" (even if the values aren't continuous)?

+2  A: 

In general terms, you could first find the maximum id (which you've done), then find the maximum id that is less than (<) the maximum.

Specifically,

select max(id) from Comics where id < 7

Alternately, you can order the results in descending order:

select id from Comics order by id desc

and then look at the second row returned.

Greg Hewgill
or sort in descending order use `OFFSET` to skip to the second row and `LIMIT` to return just the 1.
Mark E
+1  A: 
SELECT max(id) FROM Comics

is the same as

SELECT TOP 1 id FROM Comics ORDER BY ID DESC

note: this is transact sql syntax, use rownum or limit depending on your vendor

to get row 2 you can do

SELECT TOP 1 ID 
FROM 
    (SELECT TOP 2 id 
     FROM Comics 
     ORDER BY ID DESC) 
ORDER BY ID ASC
Paul Creasey
I didnt know you can have SQL inside SQL like that, thank you.
Joseph Robidoux
@Joseph this technique is known as a derived table or an inline view.
Paul Creasey
If your using mysql or postgre the query is much simpler just use the offest functionality
Paul Creasey
A: 

this would do it as well ..

SELECT
    max(id)
FROM
    Comics 
WHERE id < (SELECT max(id) FROM Comics)
Gaby