To remove duplicate rows in MySQL, you can use the DISTINCT keyword or the GROUP BY clause. However, if you want to permanently remove duplicates from your table, you'll need to use a combination of CREATE TABLE, SELECT DISTINCT, and DROP TABLE or use ALTER IGNORE TABLE with a unique index.
Here are a few methods:
Method 1: Using SELECT DISTINCT
If you just want to select unique rows without modifying the original table:
SELECT DISTINCT id, name, gender
FROM your_table;
Method 2: Creating a New Table Without Duplicates
To create a new table without duplicates:
CREATE TABLE new_table AS
SELECT DISTINCT id, name, gender
FROM your_table;
Then, you can drop the original table and rename the new table:
DROP TABLE your_table;
RENAME TABLE new_table TO your_table;
Method 3: Using ALTER IGNORE TABLE
If your version of MySQL supports it (MySQL 5.7 and later), you can add a unique index to your table, which automatically removes duplicates:
ALTER IGNORE TABLE your_table
ADD UNIQUE (id, name, gender);
Note: This method modifies the original table by removing duplicates based on the unique index you create.
Method 4: Using ROW_NUMBER() or RANK() (MySQL 8.0 and later)
If you're using MySQL 8.0 or later, you can use window functions like ROW_NUMBER() to remove duplicates based on certain conditions:
WITH cte AS (
SELECT id, name, gender,
ROW_NUMBER() OVER (PARTITION BY id, name, gender ORDER BY id) as row_num
FROM your_table
)
SELECT id, name, gender
FROM cte
WHERE row_num = 1;
This method doesn't modify the original table but allows you to select unique rows based on your criteria.
Choosing the Right Method
- Use
SELECT DISTINCT for one-time queries where you don't need to modify the original table.
- Create a new table or use
ALTER IGNORE TABLE when you want to permanently remove duplicates from your table.
- Consider the version of MySQL you're using, as some features like window functions are only available in MySQL 8.0 and later.