Here is schema of table:-
INSERT INTO cars(id,model,brand,color,make)
VALUES
(1, 'Model S', 'Tesla', 'Blue', 2018),
(2, 'EQS', 'Mercedes-Benz', 'Black', 2022),
(3, 'iX', 'BMW', 'Red', 2022),
(4, 'Ioniq 5', 'Hyundai', 'White', 2021),
(5, 'Model S', 'Tesla', 'Silver', 2018),
(6, 'Ioniq 5', 'Hyundai', 'Green', 2021);
I am trying to delete only duplicate rows but my query is deleting all the records.
Below is the query i am using.
DELETE
FROM cars
WHERE id IN(
SELECT id FROM(
SELECT MAX(id)
FROM cars
GROUP BY model,brand)AS X);
I tried deleting only duplicate records but it is deleting all the records
2
Answers
Whoops… your query is actually treated as:
That is because:
id
is looked up starting from current level, then parent(s)The query will match all rows.
To delete duplicates I personally use
exists
:This will delete rows with duplicate model and brand. Rows with higher id will be deleted.