Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
1. Introduction
Exercises

Instruction

Welcome to the second part of the SQL Practice Set. Now we will focus on aggregation and grouping. However, we'll start with a quick recap.

  • SQL offers aggregate functions that can help with computing statistics: count(), sum(), min(), max(), avg(), etc.
  • In order to create more sophisticated statistics with aggregate functions, you have to use the GROUP BY clause. This groups together all rows that have the same values.
  • You can use the HAVING clause, if you need to filter the result of an aggregate function.

Take a look at the example below. This query selects every client_id and the average value of all items a given client ordered. It takes into consideration only those clients who ordered at least twice.

SELECT 
  client_id,
  avg(order_price)
FROM client_orders
GROUP BY client_id
HAVING count(client_id) >= 2
  • The DISTINCT keyword eliminates duplicate results.
  • In order to sort table rows, you need to use the ORDER BY clause. For example:
    SELECT 
      client_id,
      name
    FROM client_orders
    ORDER BY name DESC
    

Exercise

Click the Next exercise button to continue.