Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.44/5 (4 votes)
I have been asked a question in an interview :

How to get second last record of a SQL table ?...WITHOUT USING "ORDER BY" , and assuming there is no identity column 
Posted
Updated 27-Feb-18 0:10am
v4
Comments
Mehdi Gholam 18-Nov-11 1:28am    
What's wrong with using order by, some things are there to be used.

Hi kiran,

If you are using an identity in your table , following query will be useful,
select * from gallery where GalleryItemid=(ident_current('gallery')-1)

I hope it helps you.
 
Share this answer
 
Comments
kiran dangar 18-Nov-11 1:34am    
but Not having Identity
i found a solution but there is a small limitation, however it will work in 99% cases..

SQL
select top 1* from (
select * from [TableName] EXCEPT
select top (select (COUNT(1)-2) from [TableName]) * from [TableName]) A


Limitation : If last 2 rows/ second last row is duplicate of any row then it will give wrong result... but such cases are very rare in real scenarios.
 
Share this answer
 
SQL
select * 
from emp
where empid not in (
    select top (
        (select count(*) from emp) - 2
    ) empid
    from emp
)
 
Share this answer
 
v2
make use of max() in sql .have look at at the following query:
SQL
select * from emp where id=(select max(id)-1 from emp)
 
Share this answer
 
Comments
Janardhanam Julapalli 21-Oct-14 5:59am    
This is working fine.@member60
Jubinjj007 7-Nov-17 4:38am    
Its wrong solution, bcoz id is not always in sequential, sometime we delete the previous record
 
Share this answer
 
Comments
Maciej Los 15-Dec-14 5:44am    
It's really old question. Why did you answered it?
Kornfeld Eliyahu Peter 15-Dec-14 5:46am    
Because of solution 5!
It made the question jump to the top of the list...
/\jmot 15-Dec-14 5:49am    
it show on the top, that's why i answered.
Maciej Los 15-Dec-14 6:01am    
So, delete it to avoid down-voting.
/\jmot 15-Dec-14 6:06am    
why down vote?
is that a wrong answer or anything else??
i saw the question on top and answered it.if you thing my answer is wrong or you didn't like this way then down vote it.
it's not the issue. :)

SQL
select TOP 1 *
from [User]
where [Id] not in (
    select top ((select count(*) from [User]) - 2) [Id]
    from [User]
)
 
Share this answer
 
with out id number we find the detail




select top 01 * from (select top 2 * from [dbo].[offbeat]) as a order by id desc
 
Share this answer
 
Comments
Richard MacCutchan 27-Feb-18 6:41am    
SIX years too late, and already answered.
Richard Deeming 27-Feb-18 11:36am    
Not only far too late, but you didn't even bother to read the question: WITHOUT USING "ORDER BY"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900