How to Count Distinct Values in SQL Database: SQL PostgreSQL MS SQL Server Oracle MySQL SQLite Operators: DISTINCT COUNT Table of Contents Problem: Example: Solution: Discussion: Problem: You’d like to count how many different non-NULL values there are in a given column. Example: Our database has a table named customer with data in the following columns: id, first_name, last_name, and city. idfirst_namelast_namecity 1JohnWilliamsChicago 2TomBrownAustin 3LucyMillerChicago 4EllieSmithDallas 5BrianJonesAustin 6AllanDavisNULL Let’s find the number of different (and non-NULL) cities. Solution: SELECT COUNT(DISTINCT city) as cities FROM customer; This query returns number of cities where customers live: cities 3 Discussion: To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT. When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values. Recommended courses: SQL Basics SQL Practice Set Recommended articles: What is the Difference Between COUNT(*), COUNT(1), COUNT(column), and COUNT(DISTINCT)? What Is the Role of DISTINCT in SQL? What’s the Difference Between UNIQUE and DISTINCT in SQL? SQL Aggregate Functions Cheat Sheet See also: How to Eliminate Duplicate Rows in SQL How to Order by Count in SQL? Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query