Search code examples
sqlsql-servert-sql

SQL query to determine that values in a column are unique


How to write a query to just determine that the values in a column are unique?


Solution

  • 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 'col1' does not have the data type 'ntext' or 'text'. If you have one of these data types, use 'distinct CAST(col1 AS nvarchar(4000))' (or similar) instead of 'distinct col1'.