Skip to content
Advertisement

How to filter by comparing the dates in MySQL Workbench

I have a table look like this:

I want to return everything but with a latest date of those three dates for each ID, and date02 cannot be later than date03, my current output will give me this where date02 > date03:

Expected output:

I tried this:

I’ve added WHERE 'date02' < 'date03' but why the output still have the records where date02>date03?? I’m very new to SQL, please help…

Advertisement

Answer

You can do this with a correlated subquery and tuple equality:

For performance with this query, you can create a compound index on (id, date01, date02, date03).

You can also use row_number(), if you are running MySQL 8.0:

Demo on DB Fiddle:

ID | B   | C    | date01     | date02     | date03    
-: | :-- | :--- | :--------- | :--------- | :---------
11 | xxx | xxxx | 2020-07-01 | 2020-07-03 | 2020-06-30
22 | xxx | xxxx | 2020-07-01 | 2020-07-03 | 2020-06-30
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement