Utilizing DISTINCT for Uniqueness Exploration
Introduction to the DISTINCT Clause
Welcome back! In the previous lesson, we explored the COUNT function for quantitative analysis in PostgreSQL. Today, we'll dive into another essential SQL feature: the DISTINCT clause.
The DISTINCT clause is used to return unique values from a column, helping you find and filter out duplicate data. For example, the characters table has 243 rows, but some of those characters appear in multiple movies. Therefore, they appear multiple times in the table. To find out how many distinct character names there are, we can use the DISTINCT function.
Dataset Review
For convenience, the tables and columns in our Marvel movies dataset are:
Movies Table
Movie Details Table
Characters Table
Basic Syntax of DISTINCT
Let's start by understanding the syntax of the DISTINCT clause:
Here's a quick breakdown of the syntax:
SELECT DISTINCT: This part of the command tells PostgreSQL that you want to select unique values from a specific column.column_name: Replace this with the name of the column you want to filter for unique values.FROM table_name: Replace this with the name of the table containing the data.
Now, let's see it in action with a practical example.
Selecting Unique Character Names
Suppose we want to get a list of unique character names. The SQL query is:
SELECT DISTINCT character_name: This part selects uniquecharacter_namevalues from thecharacterstable.FROM characters: Specifies thecharacterstable where the data is located.
When you run this query, you will get a table of unique character names. The first 20 entries of the output are:
By using the DISTINCT clause, we eliminate the duplicate entries and get a list of unique character names. The output tells us that there are 147 unique character names in the characters table.
