Comprehensive SQL Study Guide with
Examples
Introduction to SQL
Structured Query Language (SQL) is the standard language for relational database
management systems. It acts as the bridge between the user and the database, allowing
for data retrieval, insertion, updating, and structural definition.
1. SQL Data Definition Language (DDL)
[Image of SQL DDL schema structure]
DDL is used to define or modify the database schema (the skeleton of the database).
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Salary DECIMAL(10, 2),
DepartmentID INT
);
2. Basic Structure of SQL Queries
[Image of SQL SELECT query execution order]
The SELECT statement is the workhorse of SQL. It retrieves data based on specified
criteria.
SELECT Name, Salary
FROM Employees
WHERE DepartmentID = 101;
3. Set Operations
[Image of SQL set operations Venn diagram]
Set operations combine the results of two or more SELECT statements into a single result
set.
SELECT Name FROM Customers
UNION
SELECT Name FROM Suppliers;
4. Null Values
NULL represents unknown or missing data. Note that comparisons with NULL cannot use
'='.
SELECT Name
FROM Employees
WHERE Email IS NULL;
5. Aggregate Functions
Aggregate functions summarize data (e.g., COUNT, SUM, AVG) and are often used with
GROUP BY.
SELECT DepartmentID, AVG(Salary)
FROM Employees
GROUP BY DepartmentID;
6. Nested Subqueries
[Image of SQL subquery logic]
A subquery is a query nested inside a larger query. The inner query runs first and passes
its result to the outer query.
SELECT Name, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);