SQL query to determine if values โ€‹โ€‹in a column are unique

How to write a query to simply determine that the column values โ€‹โ€‹are unique?

+16
sql sql-server tsql
source share
7 answers

Try this:

SELECT CASE WHEN count(distinct col1)= count(col1) THEN 'column values are unique' ELSE 'column values are NOT unique' END FROM tbl_name; 

Note. This only works if the column "col1" does not have a data type of "ntext" or "text". If you have one of these data types, use "separate CAST (col1 AS nvarchar (4000))" (or similar) instead of "excellent col1".

+14
source share
 select count(distinct column_name), count(column_name) from table_name; 

If # unique values โ€‹โ€‹is equal to the total number of values, then all values โ€‹โ€‹are unique.

+13
source share
 IF NOT EXISTS ( SELECT column_name FROM your_table GROUP BY column_name HAVING COUNT(*)>1 ) PRINT 'All are unique' ELSE PRINT 'Some are not unique' 

If you want to list those that are not unique, just take an internal query and run it. NTN.

+5
source share

With this next query, you have the advantage of not only seeing if your columns are unique, but you can also see which combination is most unique. In addition, since you still see frequency 1, your key is unique, you know that your results are good, and not, for example, simply missing; something is less clear when using the HAVING clause.

 SELECT Col1, Col2, COUNT(*) AS Freq FROM Table GROUP BY Col1, Col2 ORDER BY Freq DESC 
+2
source share

If you want to check if all values โ€‹โ€‹are unique and you care about NULL values โ€‹โ€‹then do something like this:

 select (case when count(distinct column_name) = count(column_name) and (count(column_name) = count(*) or count(column_name) = count(*) - 1) then 'All Unique' else 'Duplicates' end) from table t; 
+1
source share

Are you trying to return only individual column values? If so, you can use the DISTINCT keyword. Syntax:

 SELECT DISTINCT column_name,column_name FROM table_name; 
0
source share

Use the DISTINCT keyword inside the COUNT aggregation function, as shown below:

 SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name 

The above query will give you the number of different values โ€‹โ€‹in this column.

0
source share

All Articles