I have to write a query which will return the latest timestamp column’s value from a table if rows exist.
If there is no row(s) in table then it return the default value.
I have write the following query in MS-SQL which is working fine for me.
IF Exists (select * from employees)
Begin
select TOP 1 timestamp from employees order by timestamp desc;
End
Else
Begin
select '1900-01-01 00:00:00.000' as timestamp;
End
But , now I need to write this query in MySQL.
I have tried a-lot of methods but no luck.
In MySQL:
IF (select EXISTS (select * from employees))
BEGIN
select timestamp from employees order by timestamp desc LIMIT 1
END
ELSE
BEGIN
select '1900-01-01 00:00:00.000' as timestamp
END
Can anyone please comment how can I do this.
3
Answers
Is the below sql meet your demand?
Use
UNION ALL
:or, if
timestamp
is not nullable:See the demo.
For these types of queries, you can use CASE statements in MY-SQL