Home > Database > Mysql Tutorial > How to Delete Duplicate Rows in SQL Without a Unique Identifier?

How to Delete Duplicate Rows in SQL Without a Unique Identifier?

Patricia Arquette
Release: 2025-01-23 01:37:08
Original
927 people have browsed it

How to Delete Duplicate Rows in SQL Without a Unique Identifier?

Remove duplicate rows without unique identifier

To remove duplicate rows from a table that do not have a unique identifier column, you can use a CTE (common table expression) in conjunction with ROW_NUMBER().

Solution:

Please consider the following inquiry:

<code class="language-sql">WITH CTE AS (
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER() OVER (PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1;</code>
Copy after login

This query does the following:

  1. Create CTE: It creates a CTE named "CTE", assigns each row a unique ROW_NUMBER(), counting starting from 1 of the "col1" column in each unique value partition .
  2. Identify duplicates: The query identifies duplicate rows by checking if ROW_NUMBER() is greater than 1.
  3. Remove Duplicates: It then removes all rows in the CTE that have duplicate ROW_NUMBER() values.

Result:

The result of the query is a table with duplicate rows removed, retaining only the first occurrence of each unique row. This is achieved without requiring a unique identifier column in the original table.

The above is the detailed content of How to Delete Duplicate Rows in SQL Without a Unique Identifier?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template