Chapter 13 12a
Chapter 13 12a
This chapter covers advanced SQL techniques for organizing and retrieving data from relational
databases. Students will learn how to group records, apply aggregate functions, and join tables to
extract meaningful insights from multiple datasets.
SQL functions are special commands used to perform calculations or operations on data. They can be
categorized as:
1. Aggregate Functions: Operate on multiple rows of a table to return a single summary value.
2. Scalar Functions: Operate on individual values and return a single result per row.
The GROUP BY clause in SQL is used to arrange identical data into groups. It’s typically used with
aggregate functions to provide summaries for groups of data.
Syntax:
FROM table_name
GROUP BY column1;
Example:
FROM employees
GROUP BY department;
This example groups employees by department and calculates the average salary for each
department.
Grouping can also be done on multiple columns, allowing for nested grouping.
Example:
FROM employees
The HAVING clause filters groups after the GROUP BY operation, which is different from the WHERE
clause (which filters rows before grouping).
Syntax:
FROM table_name
GROUP BY column1
HAVING condition;
Example:
FROM employees
GROUP BY department
When using GROUP BY, only grouped columns and aggregate functions should be included in the
SELECT statement. Any non-aggregated column in the SELECT must also be in the GROUP BY clause.
13.4 Joins
Joins are SQL operations that allow combining data from two or more tables based on a related
column.
The Cartesian Product (or Cross Join) occurs when every row of one table is paired with every row of
another table.
Syntax:
Example:
If employees has 10 rows and departments has 5 rows, the result will have 50 rows.
Aliases simplify table references in complex queries and are assigned using the AS keyword.
Syntax:
SELECT alias.column_name
Example:
Here, e and d are aliases for the employees and departments tables, respectively.
13.4.3 Equi-Join and Natural Join
These joins are used to retrieve related data based on a common column.
1. Equi-Join: A join that uses equality conditions (=) between columns in two tables.
o Syntax:
SELECT column_list
o Example:
2. Natural Join: An implicit join that automatically matches columns with the same name and
compatible data types.
o Syntax:
o Example:
In this case, the join automatically matches columns with the same name in both tables.
SQL allows additional conditions in joins to filter data further, such as using comparison operators (>,
<) or other columns.
Example:
This query retrieves the names and departments of employees with a salary greater than 50,000.