Languages
[Edit]
EN

MS SQL Server - find duplicated values

0 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to find duplicated values in MS SQL Server.

Quick solution:

SELECT [column_name], COUNT([column_name])
FROM [table_name]
GROUP BY [column_name]
HAVING COUNT([column_name]) > 1;

Practical example

To show how to find duplicated values, we will use the following table:

MS SQL Server - example data used to find duplicated values
MS SQL Server - example data used to find duplicated values

Note:

At the end of this article you can find database preparation SQL queries.

Example

In this example, we will display the number of names that are duplicated in users table.

Query:

SELECT [name], COUNT([name]) AS 'name_number'
FROM [users]
GROUP BY [name]
HAVING COUNT([name]) > 1;

Result:

MS SQL Server - find and count duplicated values
MS SQL Server - find and count duplicated values

Database preparation

create_tables.sql file:

CREATE TABLE [users] (
	[id] INT IDENTITY(1,1),
	[name] VARCHAR(100) NOT NULL,
	[email] VARCHAR(100) NOT NULL,
	[country] VARCHAR(15) NOT NULL,
	PRIMARY KEY ([id])
);

insert_data.sql file:

INSERT INTO [users]
	([name], [email], [country])
VALUES
	('Tom', 'tom1@email.com', 'Poland'),
	('Tom', 'tom2@email.com', 'Poland'),
    ('Tom', 'tom3@email.com', 'Poland'),
    ('Kim', 'kim1@email.com', 'Vietnam'),
    ('Kim', 'kim2@email.com', 'Vietnam'),
    ('Chris', 'chris1@email.com', 'Spain'),
	('Chris', 'chris2@email.com', 'Spain'),
	('Chris', 'chris3@email.com', 'USA');

MS SQL Server - problems

MS SQL Server - find duplicated values
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join