Pranav Malhotra Pranav Malhotra - 6 months ago 7
SQL Question

SQL Query: Remove duplicates in column that is not primary key

I have a table with multiple columns, namely, Title, Url, Description and an integer Id which serves as the primary key.

In the tables, there are multiple entries with the same title but different url, description and of course different Ids.

What would be the SQL query to obtain the rows that have unique Titles. With rows with the same title, it doesnt matter which row is return.

Answer

You can use a query like this:

SELECT t1.Title, t1.Url, t1.Description, t1.id
FROM mytable AS t1
JOIN (
   SELECT MIN(id) AS min_id
   FROM mytable
   GROUP BY title
) AS t2 ON t1.id = t2.min_id

This will pick the record having the minimum id for each distinct value of Title.