How to count unique values in a database column using SQL

I know how to get all unique values from a database column using these methods:

  • SELECT DISTINCT product_id FROM orders;
  • SELECT product_id FROM orders GROUP BY product_id;

But I need to find out how many unique values exist in total. Do I have to use a nested query to get this count? What’s the best way to achieve this?

just wrap ur distinct query with COUNT() like this: SELECT COUNT(DISTINCT product_id) FROM orders; - no need for nested queries or anything complicated. works perfectly every time I use it.

Using COUNT(DISTINCT product_id) is indeed the most straightforward approach for counting unique values in a column. It’s important to note that this function ignores null values by default, which is typically desired. If you do need to count nulls as unique, you would need to implement some additional logic. In terms of performance, most database systems efficiently optimize distinct counts, but for large datasets, indexing the column can significantly improve query speed. I’ve consistently relied on this method across various database systems with great results.

Oh interesting! Quick question though - does COUNT(DISTINCT product_id) handle nulls differently than those other methods? If some rows have null product_ids, does that mess with the count? And what about performance on huge tables?