← Back
LESSON 10
SQL (Core) - Queries with aggregates (Pt. 1)
Prereq: None | Progress: 0%
Course Syllabus
Lesson 0 📖 What is SQL? Lesson 1 📖 SELECT queries 101 Lesson 2 📖 Queries with constraints (Pt. 1) Lesson 3 📖 Queries with constraints (Pt. 2) Lesson 4 📖 Filtering & sorting results Review 1 📖 Simple SELECT Queries Lesson 6 📖 Multi-table queries with JOINs Lesson 7 📖 OUTER JOINs Lesson 8 📖 A short note on NULLs Lesson 9 📖 Queries with expressions Lesson 10 📖 Queries with aggregates (Pt. 1) Lesson 11 📖 Queries with aggregates (Pt. 2) Lesson 12 📖 Order of execution of a Query Lesson 13 📖 Inserting rows Lesson 14 📖 Updating rows Lesson 15 📖 Deleting rows Lesson 16 📖 Creating tables Lesson 17 📖 Altering tables Lesson 18 📖 Dropping tables Lesson 19 📖 Subqueries & Nested Queries Lesson 20 📖 Set Operations Summary 🎓 Course Completion
Aggregate Functions Syntax
SELECT AGG_FUNC(column_or_expression) AS aggregate_description FROM mytable WHERE constraint_expression;
Without a specified grouping, each aggregate function runs on the entire set of result rows and returns a single aggregate summary value.
Common Aggregate Functions
| Function | Description |
|---|---|
| COUNT(*), COUNT(col) | Counts the number of rows in the group (or non-NULL column values). |
| MIN(column) | Finds the smallest numerical or chronological value in the group. |
| MAX(column) | Finds the largest numerical or chronological value in the group. |
| AVG(column) | Calculates the average numerical value across rows in the group. |
| SUM(column) | Calculates the sum of all numerical values in the group. |
Grouped Aggregates: GROUP BY Syntax
SELECT AGG_FUNC(column_or_expression) AS aggregate_description FROM mytable WHERE constraint_expression GROUP BY column;
The GROUP BY clause splits rows into distinct sub-groups based on matching column values, applying aggregate calculations to each sub-group separately.
💡
Group By Tip
When using GROUP BY, all non-aggregated columns in your SELECT clause should also be included in the GROUP BY clause.
🗄️ Schema Explorer SELECTABLE
› employees
|
🎯 Exercises Checklist:
☐ 1. Find the longest time that an employee has been at the studio
☐ 2. For each role, find the average number of years employed by employees in that role
☐ 3. Find the total number of employee years worked in each building
⚡ Practice Console
💡 Hint:
Loading hint...
🔑 Solution SQL:
SELECT * FROM movies; Data Output
No results. Run query to fetch data.