Welcome to SQL Task 5 of my Elevate Labs internship! This project demonstrates intermediate SQL querying techniques, focusing on aggregate functions, grouping data, and filtering grouped results.
The primary goal of this task is to:
- Aggregate Data: Use functions like
COUNT,SUM,AVG,MIN, andMAXto perform statistical analysis. - Group Data: Group rows that have the same values using
GROUP BY. - Filter Groups: Apply the
HAVINGclause to filter aggregated results. - Differentiate Filtering: Understand the difference between
WHERE(filters rows before grouping) andHAVING(filters groups). - Handle Nulls: Understand how aggregate functions handle
NULLvalues.
To successfully run the scripts in this project, ensure you have the following:
- SQL Server: MySQL, MariaDB, or any compatible SQL engine.
- SQL Client: A command-line interface (CLI) or a graphical tool like MySQL Workbench.
The project uses a students table to demonstrate aggregation and grouping techniques.
students Table Structure
| Column Name | Data Type | Description |
|---|---|---|
id |
INT | Primary Key (Auto Increment) |
name |
VARCHAR(50) | Student Name |
age |
INT | Student Age |
email |
VARCHAR(100) | Email Address |
department |
VARCHAR(50) | Department Name |
marks |
INT | Student Marks |
- Open your SQL client.
- Load the
task5.sqlscript. - Execute the script sequentially to:
- Create the
task5database. - Create the
studentstable. - Insert the sample data.
- Run the various aggregate and grouping queries.
- Create the
SELECT COUNT(*) AS total_students FROM students;
SELECT SUM(marks) AS total_marks FROM students;
SELECT AVG(marks) AS average_marks FROM students;
SELECT MIN(marks) AS minimum_marks, MAX(marks) AS maximum_marks FROM students;SELECT department, COUNT(*) AS total_students FROM students GROUP BY department;
SELECT department, AVG(marks) AS avg_marks FROM students GROUP BY department;SELECT department, COUNT(*) AS total_students FROM students GROUP BY department HAVING COUNT(*) > 2;
SELECT department, AVG(marks) AS avg_marks FROM students GROUP BY department HAVING AVG(marks) > 80;-- WHERE filters rows BEFORE grouping
SELECT department, COUNT(*) AS total_students FROM students WHERE age > 18 GROUP BY department;
-- HAVING filters AFTER grouping
SELECT department, COUNT(*) AS total_students FROM students GROUP BY department HAVING COUNT(*) > 1;-- COUNT ignores NULL values in specific columns
SELECT COUNT(marks) AS marks_count FROM students;Tip
You can execute the different SELECT queries individually to observe how aggregate functions calculate values and how GROUP BY and HAVING manipulate the result set.