SQL Tutorial for Beginners
Structured Query Language (SQL) is a standard language for managing and
manipulating relational databases. This tutorial will cover all the essential
topics in SQL, from basic to advanced, with detailed explanations and examples.
Table of Contents
Introduction to SQL
Setting Up Your Environment
Basic SQL Commands
SELECT
INSERT
UPDATE
DELETE
Data Types in SQL
Constraints
PRIMARY KEY
FOREIGN KEY
UNIQUE
NOT NULL
CHECK
DEFAULT
Filtering Data
WHERE Clause
AND, OR, NOT Operators
IN, BETWEEN, LIKE Operators
Sorting Data
ORDER BY Clause
Aggregate Functions
COUNT, SUM, AVG, MIN, MAX
Grouping Data
GROUP BY Clause
HAVING Clause
Joins
INNER JOIN
LEFT JOIN
RIGHT JOIN
FULL JOIN
CROSS JOIN
Subqueries
Set Operations
UNION
INTERSECT
EXCEPT
Views
Indexes
Transactions
Stored Procedures and Functions
Triggers
Advanced SQL Topics
Window Functions
Common Table Expressions (CTEs)
Pivot Tables
1. Introduction to SQL
SQL is used to communicate with a database. It is the standard language for
relational database management systems (RDBMS) like MySQL, PostgreSQL, SQL Server,
Oracle, and SQLite.
Key Concepts:
Database: A collection of data.
Table: A collection of related data entries stored in rows and columns.
Column: A set of data values of a particular type.
Row: A single record in a table.
2. Setting Up Your Environment
To practice SQL, you need a database management system (DBMS). Here are a few
options:
MySQL: Open-source RDBMS.
PostgreSQL: Advanced open-source RDBMS.
SQLite: Lightweight, file-based RDBMS.
Installing MySQL:
Download MySQL from the official website.
Follow the installation instructions.
Use a client like MySQL Workbench to interact with the database.
3. Basic SQL Commands
SELECT
The SELECT statement is used to select data from a database.
sql
Copy
SELECT column1, column2 FROM table_name;
Example:
sql
Copy
SELECT first_name, last_name FROM employees;
INSERT
The INSERT statement is used to insert new records into a table.
sql
Copy
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
Example:
sql
Copy
INSERT INTO employees (first_name, last_name) VALUES ('John', 'Doe');
UPDATE
The UPDATE statement is used to modify existing records.
sql
Copy
UPDATE table_name SET column1 = value1 WHERE condition;
Example:
sql
Copy
UPDATE employees SET last_name = 'Smith' WHERE first_name = 'John';
DELETE
The DELETE statement is used to delete existing records.
sql
Copy
DELETE FROM table_name WHERE condition;
Example:
sql
Copy
DELETE FROM employees WHERE first_name = 'John';
4. Data Types in SQL
SQL supports various data types, including:
INT: Integer.
VARCHAR(n): Variable-length string.
CHAR(n): Fixed-length string.
DATE: Date value.
FLOAT: Floating-point number.
BOOLEAN: True or False.
Example:
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE
);
5. Constraints
Constraints are rules applied to columns.
PRIMARY KEY
Uniquely identifies each record.
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50)
);
FOREIGN KEY
Ensures referential integrity.
sql
Copy
CREATE TABLE orders (
order_id INT PRIMARY KEY,
employee_id INT,
FOREIGN KEY (employee_id) REFERENCES employees(id)
);
UNIQUE
Ensures all values in a column are unique.
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
NOT NULL
Ensures a column cannot have a NULL value.
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL
);
CHECK
Ensures all values in a column satisfy a specific condition.
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
age INT CHECK (age >= 18)
);
DEFAULT
Sets a default value for a column.
sql
Copy
CREATE TABLE employees (
id INT PRIMARY KEY,
hire_date DATE DEFAULT CURRENT_DATE
);
6. Filtering Data
WHERE Clause
Filters records based on a condition.
sql
Copy
SELECT * FROM employees WHERE age > 30;
AND, OR, NOT Operators
Combine multiple conditions.
sql
Copy
SELECT * FROM employees WHERE age > 30 AND salary > 50000;
IN, BETWEEN, LIKE Operators
IN: Matches any value in a list.
BETWEEN: Matches values within a range.
LIKE: Matches a pattern.
sql
Copy
SELECT * FROM employees WHERE age IN (25, 30, 35);
SELECT * FROM employees WHERE salary BETWEEN 30000 AND 50000;
SELECT * FROM employees WHERE first_name LIKE 'J%';
7. Sorting Data
ORDER BY Clause
Sorts the result set.
sql
Copy
SELECT * FROM employees ORDER BY last_name ASC;
8. Aggregate Functions
COUNT, SUM, AVG, MIN, MAX
Perform calculations on a set of values.
sql
Copy
SELECT COUNT(*) FROM employees;
SELECT AVG(salary) FROM employees;
SELECT MAX(salary) FROM employees;
9. Grouping Data
GROUP BY Clause
Groups rows that have the same values.
sql
Copy
SELECT department, AVG(salary) FROM employees GROUP BY department;
HAVING Clause
Filters groups based on a condition.
sql
Copy
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING
AVG(salary) > 50000;
10. Joins
INNER JOIN
Returns records with matching values in both tables.
sql
Copy
SELECT employees.first_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
LEFT JOIN
Returns all records from the left table and matched records from the right table.
sql
Copy
SELECT employees.first_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
RIGHT JOIN
Returns all records from the right table and matched records from the left table.
sql
Copy
SELECT employees.first_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.id;
FULL JOIN
Returns all records when there is a match in either left or right table.
sql
Copy
SELECT employees.first_name, departments.department_name
FROM employees
FULL JOIN departments ON employees.department_id = departments.id;
CROSS JOIN
Returns the Cartesian product of the two tables.
sql
Copy
SELECT employees.first_name, departments.department_name
FROM employees
CROSS JOIN departments;
11. Subqueries
A subquery is a query within another query.
sql
Copy
SELECT first_name FROM employees WHERE salary > (SELECT AVG(salary) FROM
employees);
12. Set Operations
UNION
Combines the result sets of two or more SELECT statements.
sql
Copy
SELECT first_name FROM employees
UNION
SELECT first_name FROM managers;
INTERSECT
Returns common records from two SELECT statements.
sql
Copy
SELECT first_name FROM employees
INTERSECT
SELECT first_name FROM managers;
EXCEPT
Returns records from the first SELECT statement that are not in the second.
sql
Copy
SELECT first_name FROM employees
EXCEPT
SELECT first_name FROM managers;
13. Views
A view is a virtual table based on the result set of an SQL statement.
sql
Copy
CREATE VIEW high_salary_employees AS
SELECT first_name, last_name FROM employees WHERE salary > 70000;
14. Indexes
Indexes are used to speed up the retrieval of rows.
sql
Copy
CREATE INDEX idx_last_name ON employees (last_name);
15. Transactions
Transactions ensure that a set of SQL operations are executed reliably.
sql
Copy
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
16. Stored Procedures and Functions
Stored Procedure
A stored procedure is a prepared SQL code that you can save.
sql
Copy
CREATE PROCEDURE GetEmployee(IN emp_id INT)
BEGIN
SELECT * FROM employees WHERE id = emp_id;
END;
Function
A function returns a value and can be used in SQL statements.
sql
Copy
CREATE FUNCTION GetEmployeeName(emp_id INT) RETURNS VARCHAR(100)
BEGIN
DECLARE emp_name VARCHAR(100);
SELECT first_name INTO emp_name FROM employees WHERE id = emp_id;
RETURN emp_name;
END;
17. Triggers
A trigger is a stored procedure that automatically executes when an event occurs.
sql
Copy
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
SET NEW.hire_date = NOW();
END;
18. Advanced SQL Topics
Window Functions
Perform calculations across a set of table rows related to the current row.
sql
Copy
SELECT first_name, salary, RANK() OVER (ORDER BY salary DESC) AS rank FROM
employees;
Common Table Expressions (CTEs)
A temporary result set that you can reference within a SELECT, INSERT, UPDATE, or
DELETE statement.
sql
Copy
WITH HighSalaryEmployees AS (
SELECT * FROM employees WHERE salary > 70000
)
SELECT * FROM HighSalaryEmployees;
Pivot Tables
Transform rows into columns.
sql
Copy
SELECT department,
SUM(CASE WHEN year = 2020 THEN salary END) AS "2020",
SUM(CASE WHEN year = 2021 THEN salary END) AS "2021"
FROM employees
GROUP BY department;
This tutorial covers the fundamental and advanced topics in SQL. Practice these
concepts by writing queries and experimenting with different datasets. Happy
querying!