SQL Count Distinct Select Query Example
To count distinct values in a database table or sql view, Transact-SQL developers can use SQL Count Distinct Select command as shown in this SQL tutorial. Sometimes you wonder the count of distinct values stored in a column rather than the total rows count. In this case running a SELECT statement with Count Distinct functions will give you the desired result.
Here is DDL (Data Definition Language) commands for our SQL count distinct query example database table. The sample sql table name is SalesOrders where ordered products are stored. I keep it sample like ignoring foreign keys etc. This table will store different orders for each seperate product. So sales people can request database administrators or SQL developers the number of differet product codes ordered within a certain period of time. In this case, SQL programmers can execute SQL Count Distinct query on SalesOrders table.
Let's populate sample Count Distinct SQL table with sample data.
If you build your SQL SELECT statement to fetch the number of distinct product values inserted into sample database table, you can use the following SQL SELECT COUNT DISTINCT statement.
Although we have insert 7 rows into sample sql table, there are only 4 different products used. And the last SQL Server Count Distinct query returns 4 as the distinct count Select statement.
What you should take care is using the Count and Distinct functions in wrong order. If you use the SQL Count Distinct Select statement as follows, the returned result will be false. So take care to the syntax.