how to count unique records with sql
question
let’s say i have a table with one column containing the following 6 records:
| 3 |
| 3 |
| 4 |
| 5 |
| 5 |
| 6 |
is there a way with a single standard SQL query to count the unique records in that column? (the query should return “4″)
answer
the following sql works in MySQL, Oracle, and SQL Server:
SELECT COUNT(DISTINCT column_name) FROM table_name
the following sql works where ever subqueries are accepted (like Microsoft Access):
SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) /* or */ SELECT COUNT(*) FROM (SELECT column_name FROM table_name GROUP BY column_name)
NB: Access’s Query by Example (QBE) UI will transform the first query above into:
SELECT Count(*) AS Expr1 FROM [SELECT DISTINCT column_name FROM table_name]. AS [%$##@_Alias];
the %$##@_Alias is just some whacked out alias (i’m sure there’s a story behind that), but it could be anything. however the “.” (period) after the bracket closing the subquery, well, apparently that’s required. i’m not sure why.


Not really an answer, but given a file named z.txt containing the column one per line, then “cat < z.txt | uniq | wc -l” returns 4.