Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interleaving the rows of two different SQL tables, sorting by date

Tags:

sql

postgresql

In Postgres I've got two different tables that have almost nothing in common, save for the fact that they both have a creation date. I'd like to use that creation date in order to display instances of both of those models on a timeline. To do that, I imagine I need to first somehow select all of the created_at timestamps from BOTH of the tables in one statement, then sort them in descending order, paginate the resulting set, and then go through and detect which model each of the rows corresponds to in order to properly display the data.

Any idea if this is possible?

like image 229
Stephen Corwin Avatar asked Oct 14 '25 03:10

Stephen Corwin


1 Answers

Maybe smth like this

select created_at, 'a' as tab_name from table_a 
union all
select created_at, 'b' as tab_name from table_b
order by created_at
like image 121
Dmitry Grekov Avatar answered Oct 17 '25 04:10

Dmitry Grekov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!