Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROWID equivalent in postgres 9.2

Tags:

Is there any way to get rowid of a record in postgres??

In oracle i can use like

SELECT MAX(BILLS.ROWID) FROM BILLS   
like image 384
jobi88 Avatar asked Jan 31 '13 13:01

jobi88


People also ask

What is the equivalent of Rowid in PostgreSQL?

To clarify, in Oracle, rowid is the physical location of the row. It has nothing to do with the order of insertion and cannot be used to identify the most recently inserted record. The closest equivalent in PostgreSQL would be the ctid.

Does PostgreSQL have a Rowid?

ROWID is an indicator in Oracle of the order of rows on disk for a given table. In PostgreSQL, this is implemented with a page and leaf identifier. The identifier is visible in a query as a pseudo column with the name of “ctid”.

What is Rowid in SQL?

A row ID is a value that uniquely identifies a row in a table. A column or a host variable can have a row ID data type. A ROWID column enables queries to be written that navigate directly to a row in the table because the column implicitly contains the location of the row.

What is Ctid in Postgres?

ctid. The physical location of the row version within its table. Note that although the ctid can be used to locate the row version very quickly, a row's ctid will change if it is updated or moved by VACUUM FULL . Therefore ctid is useless as a long-term row identifier.


2 Answers

Yes, there is ctid column which is equivalent for rowid. But is useless for you. Rowid and ctid are physical row/tuple identifiers => can change after rebuild/vacuum.

See: Chapter 5. Data Definition > 5.4. System Columns

like image 99
baklarz2048 Avatar answered Oct 26 '22 00:10

baklarz2048


The PostgreSQL row_number() window function can be used for most purposes where you would use rowid. Whereas in Oracle the rowid is an intrinsic numbering of the result data rows, in Postgres row_number() computes a numbering within a logical ordering of the returned data. Normally if you want to number the rows, it means you expect them in a particular order, so you would specify which column(s) to order the rows when numbering them:

select client_name, row_number() over (order by date) from bills; 

If you just want the rows numbered arbitrarily you can leave the over clause empty:

select client_name, row_number() over () from bills; 

If you want to calculate an aggregate over the row number you'll have to use a subquery:

select max(rownum) from (     select row_number() over () as rownum from bills ) r; 

If all you need is the last item from a table, and you have a column to sort sequentially, there's a simpler approach than using row_number(). Just reverse the sort order and select the first item:

select * from bills  order by date desc limit 1; 
like image 38
Oliver Crow Avatar answered Oct 25 '22 22:10

Oliver Crow