How to use SELECT DISTINCT and COUNT? SQL Part 3

SELECT Distinct:

When you need all the unique values from a column than we use SELECT DISTINCT.

For example:

Table 1
C1C2C3
ARedPen
BBluePencil
CRedPencil
DRedPen
EBluePen

If we want unique values from C2 than we will write:

SELECT DISTINCT C2 FROM Table 1

Red
Blue

Result:

Try this yourself on SQL dvdrental database:

Find all the unique ratings of the films:

COUNT:

This function allows us to count the number of rows in a column.

For example:

Table 1
C1C2C3
ARedPen
BBluePencil
CRedPencil
DRedPen
EBluePen

If we want rows of C2 than we can write:

SELECT COUNT (C2) FROM Table 1

Remember: Count is a function so we will always use parentheses after using COUNT. 

Result: 5

Try this yourself on SQL dvdrental database:

Find all the count of rows in table films:

Now let us combine SELECT DISTINCT and COUNT:

It will give us the count of unique values in a column.

For example:

Table 1
C1C2C3
ARedPen
BBluePencil
CRedPencil
DRedPen
EBluePen

If we want the count of unique values of C2:

SELECT COUNT(DISTINCT C2) FROM Table 1

Result: 2

Try this yourself on SQL dvdrental database:

Find the count of unique ratings of the films:

Credits: The concepts and materials are taken from the Udemy course:The complete SQL Bootcamp 2022: Go from Zero to Hero

Check out the other parts in the SQL series:

Previous:

 Why do we need Structured Query Language (SQL)? SQL PART 2

 Why do we need Structured Query Language (SQL)? SQL PART 1

One thought on “How to use SELECT DISTINCT and COUNT? SQL Part 3”
  1. obviously like your website but you need to test the spelling on quite a few of your posts Several of them are rife with spelling problems and I to find it very troublesome to inform the reality on the other hand Ill certainly come back again

Leave a Reply

Your email address will not be published. Required fields are marked *