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

SQL Query to delete duplicate records but keep latest

I need a query to delete all the duplicate records but just to keep one latest record based on valid_until date column. I tried with the below but it says An expression of non-boolean type specified in a context where a condition is expected, near ','.

DELETE FROM tableOne
WHERE (id, valid_until ) NOT IN (
  SELECT id, MAX(valid_until )
  FROM tableOne
  GROUP BY id
)

>Solution :

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

This is example code for that. Can you check this answer please.

CREATE TABLE Employees (
  id INT,
  name VARCHAR(50),
  valid_until DATE
);

INSERT INTO Employees (id, name, valid_until) VALUES
  (1, 'John Doe', '2022-06-30'),
  (2, 'Jane Smith', '2023-01-15'),
  (3, 'Michael Johnson', '2021-12-31'),
  (1, 'John Doe', '2023-06-30'),
  (2, 'Jane Smith', '2024-03-22');

WITH CTE AS (
  SELECT id, valid_until, ROW_NUMBER() OVER (PARTITION BY id ORDER BY valid_until DESC) AS row_num
  FROM Employees
)
DELETE FROM CTE WHERE row_num > 1;

Click this

http://sqlfiddle.com/#!18/342c4/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