Postgresql select last row

To select the last row in PostgreSQL, you can use the “ORDER BY” clause in combination with the “LIMIT” clause in a descending order. This will allow you to fetch the last row based on a specific column or set of columns.

Let’s suppose you have a table named “employees” with columns “id”, “name”, and “salary”. To select the last row based on the “id” column, you can use the following query:

       SELECT * FROM employees ORDER BY id DESC LIMIT 1;
   

This query will retrieve the row with the highest “id” value, which is effectively the last row in the table.

Another example is to select the last row based on a specific column, such as “created_at” timestamp. Assuming you have a table named “orders” with column “created_at” timestamp type, the query would be:

      SELECT * FROM orders ORDER BY created_at DESC LIMIT 1;
   

This query will retrieve the row with the latest “created_at” timestamp, which represents the last row chronologically.

The “ORDER BY” clause is used to sort the result set in descending order based on the specified column. The “LIMIT” clause helps to limit the result set to only one row, thus fetching the last row.

Leave a comment