At times, a select statement can give us duplicate values in the result set. For instance, in our library database, the author table has a column called "country" which lists the two-letter country code of the author's country. If we select only the country column, we will get a list of all the countries. For example, if we use the SQL statement "select country from author order by 1", we will get a result set with the countries listed alphabetically.
SQL Statement:
SELECT country
FROM author
ORDER BY 1;
However, since some authors come from the same country, the result set will have duplicate values. In this case, we don't need duplicates, we just want a list of unique countries. To eliminate duplicates, we can use the "distinct" keyword. By adding "distinct" to our SQL statement, the result set will only show six unique rows representing the countries the authors come from.
SQL Statement:
SELECT DISTINCT country
FROM author
ORDER BY 1;
But what if we also want to know how many authors come from each country? To display the country along with the number of authors from that country, we can use the "group by" clause. The "group by" clause groups the result set into subsets based on matching values in one or more columns. In this example, we are grouping the countries and counting the authors using the "count" function.
SQL Statement:
SELECT country, COUNT(*) as Count
FROM author
GROUP BY country
ORDER BY 1;
Notice that the second column in the result set shows the count of authors from each country. The value "2" is used as the column name because the column name isn't directly available in the table. We can rename this column to "Count" using the "as" keyword, which makes the result set easier to understand.
SQL Statement:
SELECT country, COUNT(*) as Count
FROM author
GROUP BY country
ORDER BY 1;
Now, if we want to further restrict the result set to only show countries with more than four authors, we can use the "having" keyword. The "having" clause is used in combination with the "group by" clause, and it allows us to set conditions on the grouped data. In this case, we add the condition "having count(country) > 4". This means that only countries with five or more authors will be included in the result set.
SQL Statement:
SELECT country, COUNT(*) as Count
FROM author
GROUP BY country
HAVING COUNT(country) > 4
ORDER BY 1;
In this example, the result set will only show countries with six authors, which are China and India.
SQL Statement:
SELECT country, COUNT(*) as Count
FROM author
GROUP BY country
HAVING COUNT(country) > 4
ORDER BY 1;