SQL sublanguage: DQL (Data Query Language)
Aggregate functions in SQL are functions which preform operations on multiple rows to produce a single output.
For instance, COUNT()
is an aggregate function. Count will return the number of rows of data in the result set.
So if we query a table with 12 rows using a statement like this:
SELECT COUNT(*) FROM table_name;
We should get the value 12
Aggregate functions "aggregate" data, combining and changing it into some output based on the input. Regardless of how large that input is, the output will always be a single value. If we repeated the above query but the table had 10,000 rows, the result would still be a single value: 10,000.
There are many aggregate functions built into SQL, some commonly used ones include:
SUM()
- outputs the sum of the values in a single column from the result setAVG()
- outputs the average (mean) value of the values in a single column from the result setMIN()
- outputs the least value among the values in a single column from the result setMAX()
- similar to MIN but outputs the greatest valueFIRST()
- outputs the first value found in a column of the result setLAST()
- outputs the last value found in a column of the result set
Example: You might use the SUM()
function to find the total of all employee salaries:
SELECT SUM(salary) FROM employee;
Additional reference material if needed:
- https://www.w3schools.com/sql/sql_count_avg_sum.asp
- https://www.postgresql.org/docs/9.5/functions-aggregate.html
employee table
id | first_name | last_name | salary |
---|---|---|---|
1 | 'Steve' | 'Garcia' | 67400.00 |
2 | 'Alexa' | 'Smith' | 42500.00 |
3 | 'Steve' | 'Jones' | 99890.99 |
4 | 'Brandon' | 'Smith' | 120000 |
5 | 'Adam' | 'Jones' | 55050.50 |
Note: the output should not contain any other info but the sum.
employee table
id | first_name | last_name | salary |
---|---|---|---|
1 | 'Steve' | 'Garcia' | 67400.00 |
2 | 'Alexa' | 'Smith' | 42500.00 |
3 | 'Steve' | 'Jones' | 99890.99 |
4 | 'Brandon' | 'Smith' | 120000 |
5 | 'Adam' | 'Jones' | 55050.50 |
Problem 2: use the COUNT()
aggregate function to output the number of employees with the last name "Smith".
Note: the output should not contain any other info but the count
employee table
id | first_name | last_name | salary |
---|---|---|---|
1 | 'Steve' | 'Garcia' | 67400.00 |
2 | 'Alexa' | 'Smith' | 42500.00 |
3 | 'Steve' | 'Jones' | 99890.99 |
4 | 'Brandon' | 'Smith' | 120000 |
5 | 'Adam' | 'Jones' | 55050.50 |
Note: the output should not contain any other info but the salary.
employee table
id | first_name | last_name | salary |
---|---|---|---|
1 | 'Steve' | 'Garcia' | 67400.00 |
2 | 'Alexa' | 'Smith' | 42500.00 |
3 | 'Steve' | 'Jones' | 99890.99 |
4 | 'Brandon' | 'Smith' | 120000 |
5 | 'Adam' | 'Jones' | 55050.50 |
Note: the output should not contain any other info but the salary.