Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL query to get only one record: either when end_date is null or max(end_date)

I have the following table (employee_organization):

ID employee_id organization_id start_date end_date
1 77 16 2021-01-01 2021-06-30
2 11 23 2020-01-01 2021-05-27
3 77 16 2021-08-01 2021-08-31
4 77 16 2021-09-01 NULL

I need a query to filter out records where employee_id = 77, organization_id = 16 and end_date is null. If no matching row has been found, than return a row with max(end_date). So, in the above sample table only row with id=4 should be returned.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

SELECT *
FROM table
WHERE {needed conditions}
ORDER BY end_date IS NULL DESC, end_date DESC LIMIT 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading