How to get last inserted N rows with oracle SQL

With rownum you can generally get the row you want, but the rownum must be specified in conditions section (where clause) which means you cannot order records, before selecting first N of them. Nested select is the solution:

SELECT * FROM ( SELECT * FROM tablename WHERE var1 = val1 AND var2 = val2 ORDER BY tablename_id DESC ) WHERE rownum <>

If you want just the last record you can write:

SELECT * FROM ( SELECT * FROM tablename WHERE var1 = val1 AND var2 = val2 ORDER BY tablename_id DESC ) WHERE rownum = 1;


Previous: Strange behavior of multiple assignment in visual basic
Next: Expected identifier for Function Get in ASP