How to count unique values in SQL column

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

  • SELECT DISTINCT product_name FROM products;
  • SELECT product_name FROM products GROUP BY product_name;

But I need to get the total count of how many unique values exist in that column. Do I have to use a nested query for this? What would be the best approach to count distinct entries instead of just showing them?

honestly i used to overcomplicate this too lol. just slap COUNT around your DISTINCT and your good to go. something like SELECT COUNT(DISTINCT product_name) FROM products; does exactly what you need. way simpler than nested queries and runs faster too in my experiance.

The COUNT(DISTINCT column_name) approach mentioned above is indeed the standard solution. However, there are performance considerations depending on your dataset size. For large tables with millions of rows, this can be resource-intensive since the database must scan through all records and maintain uniqueness tracking. In such cases, you might consider creating an index on the column beforehand. Additionally, if you need to count unique values across multiple columns simultaneously, you can use COUNT(DISTINCT CONCAT(column1, column2)) or similar concatenation methods. Some database systems also support COUNT(DISTINCT column1, column2) syntax directly. The single COUNT(DISTINCT) query will always outperform nested approaches in terms of both readability and execution efficiency.

oh thats actually pretty straighforward! you just need to wrap your distinct in a COUNT() function like SELECT COUNT(DISTINCT product_name) FROM products; - no nested queries needed. works great for getting exact numbers. have you tried this approach yet? curious what database system your working with too?