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

How to handle ties in SQL

SELECT
    employee_id,
    department_id,
    first_name,
    last_name,
    hire_date,
    job_id
FROM employees e
WHERE hire_date IN 
     (
         SELECT max(hire_date)
         FROM employees
         WHERE e.department_id = department_id 
     )
ORDER BY hire_date ASC

Result of the query

So this is my query and the result of it. There are two tied results for SA_REP department and I should have only one result – for instance the one with the lower employee_id. I’ve googled the problem but can’t seem to find any related results…

Thanks for any help!

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 :

You can use a not exists query which gives you more flexibility:

SELECT *
FROM employees e
WHERE NOT EXISTS (                                                  -- no x exists that...
    SELECT *
    FROM employees x
    WHERE x.department_id = e.department_id                         -- belongs to same department 
    AND (
        x.hire_date > e.hire_date OR                                -- but hired later than e
        x.hire_date = e.hire_date AND x.employee_id < e.employee_id -- hired on same date but has lesser employee id than e
    )
)
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