Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last row of an Oracle a table

I want to get the last row, which I inserted into a table in an Oracle 11g Express database. How can I do this?

like image 770
sky scraper Avatar asked Sep 11 '12 21:09

sky scraper


People also ask

How do I fetch the last row in a table?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do you find the last inserted record in a table in Oracle?

You could use ORA_ROWSCN to get the last scn for each block on the table as an *approximate* means of seeing when things happened, or the flashback query syntax to get transaction information, but you are limited to the undo_retention settings on your database.

What is the query to fetch last record from the table in Oracle?

Records are not returned in order of anything. and rownum = 1; will get the "last" record. It is the ONLY way.

How do I get the last element of a table in SQL?

We can use the ORDER BY statement and LIMT clause to extract the last data. The basic idea is to sort the sort the table in descending order and then we will limit the number of rows to 1. In this way, we will get the output as the last row of the table. And then we can select the entry which we want to retrieve.


2 Answers

There is no such thing as the "last" row in a table, as an Oracle table has no concept of order.

However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this:

select *
  from ( select a.*, max(pk) over () as max_pk
           from my_table a
                )
 where pk = max_pk

If you have the date that each row was created this would become, if the column is named created:

select *
  from ( select a.*, max(created) over () as max_created
           from my_table a
                )
 where created = max_created

Alternatively, you can use an aggregate query, for example:

select *
  from my_table
 where pk = ( select max(pk) from my_table )

Here's a little SQL Fiddle to demonstrate.

like image 145
Ben Avatar answered Oct 24 '22 11:10

Ben


SELECT * FROM (
    SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;
like image 26
rtaft Avatar answered Oct 24 '22 09:10

rtaft