Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql get some last rows from table

I have PostgreSQL table:

Username1 SomeBytes1

Username2 SomeBytes1

Username1 SomeBytes1

Username1 SomeBytes1

I need to get some rows from with name Username1 but from the end of the table. For example i need last to rows with Username1

select from my_table where user = Username1 LIMIT 2

Gives me first 2 rows, but i need last two.

How can i select it?

Thank you.

like image 319
0xAX Avatar asked Dec 27 '22 00:12

0xAX


1 Answers

first and last in a table is very arbitrary. In order to have a good predictable result you should always have an order by clause. And if you have that, then getting the last two rows will become easy.

For instance, if you have a primary key or something like an ID (which is populated by a sequence), then you can do:

select * from my_table where user = 'Username1' order by ID desc limit 2.

desc tells the database to sort the rows in reverse order, which means that last will be first.

like image 78
Jimmy Stenke Avatar answered Jan 09 '23 20:01

Jimmy Stenke