Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello experts,

how to fetch last n records from mytable.
any query for that,please inform immediatle
Posted
Comments
RaisKazi 26-Oct-11 5:21am    
What do you mean by "sorting"? Does it mean "Order By"? What is a harm/disadvantage of "Order By" clause?
Amir Mahfoozi 26-Oct-11 5:22am    
what is your criteria for "Last N" ? is the autoincrement key ok for you ?

Assuming ID is an identity column, I would do something like this:
SQL
SELECT TOP 10 
[ID] ,[Name]
  FROM [dbo].[myTable]
  ORDER BY ID DESC


As you are asking for "last" you are imposing order - the whole thing would be meaningless without ordering the result.

Best regards
Espen Harlinn
 
Share this answer
 
Comments
RaisKazi 26-Oct-11 5:31am    
A 5! Exactly, their is no point in avoiding "Order By".
Espen Harlinn 26-Oct-11 6:16am    
Thanks RaisKazi!
sravani.v 2-Nov-11 6:30am    
My 5!
Amir Mahfoozi 2-Nov-11 6:35am    
+5
Espen Harlinn 2-Nov-11 6:36am    
Thank you, Amir!
Solution 2 is fine............
 
Share this answer
 
Comments
DeepikaSrivastava 21-Nov-11 2:15am    
Please mark it as answer...
To fetch last n records from mytable
SQL
Declare @n int
Set @n=5

select * from mytable
         where mytableid not in (
                                   select top ((select count(*) 
                                    from mytable) - @n ) mytableid
        from mytable
 
Share this answer
 
v2
Comments
Member 12649531 10-Aug-16 8:16am    
i have script like this in stored procedure
<pre lang="SQL">USE [Reporting_Tool]
GO
/****** Object: StoredProcedure [dbo].[asdf] Script Date: 2016-08-10 5:07:56 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[asdf]
As
begin
declare @rowcount as integer
declare @deletecount as integer
declare @Totalrows as integer
set @Totalrows=50
select @rowcount=count (*) from Table1;
IF (@rowcount > @Totalrows)
begin
select @deletecount=@rowcount-@Totalrows
print @Totalrows
print @rowcount
print @deletecount
delete top (@deletecount) from Table1
End
End
--select * from Table1
--EXEC asdf</pre>
but i want to delete old record not top records and how to fix number of rows into 50 that is first in first out automatically but not in statement scripts..
thanq..

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