Find and List Duplicate Rows and Values in SQL Server

by Al Beecy March 10, 2009
To simply find duplicate values in a table use the following query (replacing "[ColumnName]" and "[TableName]" with the actual values):

SELECT [ColumnName], COUNT(*) AS [DupeCount]
FROM [TableName]
GROUP BY [ColumnName]
HAVING COUNT(*) > 1

To find duplicate values and list the rows that contain them, use the following query:

SELECT *
FROM [TableName]
WHERE [ColumnName] IN
(
      SELECT [ColumnName]
      FROM [TableName]
      GROUP BY [ColumnName]
      HAVING COUNT(*) > 1
)
ORDER BY [ColumnName]

Applies to SQL Server 2005, SQL Server 2008.

Tags: , , ,

SQL Server | SQL Server

Comments

June 14, 2009 #

DotNetShoutout

Find and List Duplicate Rows and Values in SQL Server

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetShoutout

January 22, 2010 #

Anonymous

I tried to use this to find 3 records in the row consecutively but don't know how.  For example, I only want to find the records that are below 15, three records in a row consecutively.  Below is the eaxample.


TABLE 1
ID  Test_Data
1   20
2   10
3   5
4   8
5   17
6   2

DESIRED OUTPUT
ID  TEST_DATA
2   10
3   5
4   8

Anonymous United States

January 22, 2010 #

Al Beecy

That query won't work for that. Assuming that your sample data is similar to your actual data (id is sequential), I'd just use something like:

SELECT TOP 3 * FROM [Table1] WHERE [data] < 15 ORDER BY [id]

Al Beecy United States

January 22, 2010 #

Bob

Thank you so much for your quick response.  It works!

Bob United States

Powered by BlogEngine.NET1.5.0.7 | Theme by Mads Kristensen