Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to select row with added_date and updated_date

Tags:

sql

mysql

I am trying to select a row order by added_date or if row is updated then order by updated_date.

Default the updated date is Null.

For the above table date given in (dd-mm-yy).

For the below table the first row is added at 2 feb and second is added at 1 feb so by using ,

select * from tablename order by added_date desc;

I get the latest row, but if any row is updated then this updated row becomes latest row.

For second row, row added at 1st feb but it's updated at 3rd feb so its becomes latest row.

How can I get the record with added and updated date ??

    id   title    name   added_date   updated_date
     1   asd      rff     02-02-2013    NULL
     2   fsfs     rwr     01-02-2013    03-02-2012
     3   ddd      wwrr    30-01-2013    04-02-2013

Edit:using MYSQL

like image 509
Kango Avatar asked Feb 23 '26 18:02

Kango


1 Answers

You didn't specify which RDBMS you use. For Oracle you can try this:

SELECT * FROM tablename ORDER BY NVL(updated_date,added_date) DESC;

SQL Server:

SELECT * FROM tablename ORDER BY ISNULL(updated_date,added_date) DESC

MySQL:

select * from tablename order by ifnull(updated_date,added_date) desc;
like image 133
Andrey Gordeev Avatar answered Feb 26 '26 08:02

Andrey Gordeev