Is there any way to find the last 500 records from a table with out using union, union all or minus function?
Can we achieve this using rank, row_number or dense_rank functions in sql.
Thanks Rakesh
Is there any way to find the last 500 records from a table with out using union, union all or minus function?
Can we achieve this using rank, row_number or dense_rank functions in sql.
Thanks Rakesh
Teradata uses TOP
SELECT TOP 500 * FROM table ORDER BY your_column
Oracle 12c+ uses FETCH:
SELECT * FROM TABLE ORDER BY your_column DESC FETCH FIRST 500 ROWS ONLY
Older oracle uses rownum, and the orderby must be done in a subquery:
SELECT * FROM (SELECT * FROM TABLE ORDER BY your_column DESC) WHERE rownum <= 500
You could use ROW_NUMBER in a DB that supports it:
SELECT * FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY your_column DESC) rn FROM TABLE) WHERE rn <= 500
your_column
is used to determine "last"ness.. It needs to be something that sorts sensibly, like a numeric id, date etc
Edit:
Your interviewer expected you to use analytical functions. Here's what it would look like:
SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER(ORDER BY your_column DESC) as rn
FROM table
) x
WHERE x.rn < 501
Not that it still needs an order by; here's what happens when you skip it:
You can use the SQL limit with orderby desc to get the last N number of records.
select * from tbl_name order by id desc limit N;