SQL
SQL (Structured Query Language) is a standardized programming language used to manage
and manipulate relational databases. SQL allows users to create, read, update, and delete data
(often referred to as CRUD operations) within a database. It is used to interact with a database,
retrieve information, insert data, update records, and manage the structure of database objects
like tables and views.
SQL Commands: It can be categorized into several types based on their functionality:
1. Data Query Language (DQL)
These commands are used to query or retrieve data from a database.
SELECT: Used to query data from a table.
SELECT * FROM employees;
2. Data Definition Language (DDL)
These commands are used to define, modify, and delete database objects such as tables, indexes,
and schemas.
CREATE: Used to create database objects like tables, views, etc.
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
ALTER: Used to modify the structure of an existing database object.
ALTER TABLE employees ADD email VARCHAR(100);
DROP: Used to delete an existing database object.
DROP TABLE employees;
TRUNCATE: Deletes all the rows in a table but doesn't remove the table itself.
TRUNCATE TABLE employees;
3. Data Manipulation Language (DML)
These commands are used for manipulating the data stored in the database (inserting, updating,
and deleting records).
INSERT: Used to insert new rows into a table
INSERT INTO employees (employee_id, first_name, last_name, department)
VALUES (1, 'John', 'Doe', 'HR');
UPDATE: Used to modify existing records in a table.
UPDATE employees SET department = 'Finance' WHERE employee_id = 1;
DELETE: Used to delete records from a table.
DELETE FROM employees WHERE employee_id = 1;
4. Data Control Language (DCL)
These commands are used to control access to data within the database.
GRANT: Used to provide access privileges to users.
GRANT SELECT, INSERT ON employees TO user1;
REVOKE: Used to remove access privileges from users.
REVOKE SELECT ON employees FROM user1;
5. Transaction Control Language (TCL)
These commands manage the changes made by DML commands. They are used to ensure data
integrity and control transaction behavior.
COMMIT: Saves the changes made in the current transaction.
COMMIT;
ROLLBACK: Rolls back (undoes) the changes made in the current transaction.
ROLLBACK;
SAVEPOINT: Sets a point within a transaction to which you can later roll back.
SAVEPOINT savepoint1;
SET TRANSACTION: Used to set specific properties for the transaction, like isolation
level.
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
1. SQL Basics
a. SELECT: This statement is used to query a database and retrieve data from one or more
tables.
SELECT column1, column2 FROM table_name;
Example:
SELECT first_name, last_name FROM employees;
b. WHERE: This clause is used to filter records that meet specific conditions.
SELECT column1, column2 FROM table_name WHERE condition;
Example:
SELECT * FROM employees WHERE age > 30;
c. AND, OR, NOT: Used to combine multiple conditions.
SELECT * FROM employees WHERE age > 30 AND department = 'HR';
SELECT * FROM employees WHERE age < 30 OR department = 'Finance';
SELECT * FROM employees WHERE NOT department = 'HR';
d. ORDER BY: This clause is used to sort the result set in ascending or descending order.
SELECT column1, column2 FROM table_name ORDER BY column1 ASC|DESC;
Example:
SELECT * FROM employees ORDER BY last_name ASC;
2. Aggregate Functions
a. COUNT(): Counts the number of rows that match a specified condition.
SELECT COUNT(*) FROM employees;
b. SUM(): Calculates the sum of a numeric column.
SELECT SUM(salary) FROM employees;
c. AVG(): Calculates the average value of a numeric column.
SELECT AVG(salary) FROM employees;
d. MIN() and MAX(): Finds the minimum or maximum value in a column.
SELECT MIN(age) FROM employees;
SELECT MAX(salary) FROM employees;
e. GROUP BY: This clause groups rows sharing a property (like values in a column) into
summary rows.
SELECT department, COUNT(*) FROM employees GROUP BY department;
f. HAVING: HAVING is used to filter records after the GROUP BY clause.
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING
AVG(salary) > 50000;
3. Join Operations
a. INNER JOIN: Returns rows when there is a match in both tables.
SELECT employees.first_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
b. LEFT JOIN (LEFT OUTER JOIN): Returns all rows from the left table and matched rows
from the right table.
SELECT employees.first_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;
c. RIGHT JOIN (RIGHT OUTER JOIN): Returns all rows from the right table and matched
rows from the left table.
SELECT employees.first_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
d. FULL JOIN (FULL OUTER JOIN): Returns rows when there is a match in either left or
right table.
SELECT employees.first_name, departments.department_name
FROM employees
FULL OUTER JOIN departments ON employees.department_id =
departments.department_id;
e. CROSS JOIN: Returns the Cartesian product of two tables (all combinations).
SELECT * FROM employees CROSS JOIN departments;
4. Subqueries
a. Subquery in SELECT: You can use a subquery in the SELECT statement to return a value.
SELECT first_name, (SELECT department_name FROM departments WHERE
department_id = employees.department_id)
FROM employees;
b. Subquery in WHERE: You can use subqueries in the WHERE clause to filter results.
SELECT first_name FROM employees WHERE department_id = (SELECT department_id
FROM departments WHERE department_name = 'HR');
c. Subquery in FROM
You can use a subquery in the FROM clause to treat the result as a table
SELECT department, COUNT(*)
FROM (SELECT department FROM employees WHERE age > 30) AS filtered_employees
GROUP BY department;
5. Creating Tables and Modifying Data
a. CREATE TABLE: Used to create a new table.
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
department VARCHAR(50)
);
b. ALTER TABLE: Used to modify an existing table.
ALTER TABLE employees ADD email VARCHAR(100);
ALTER TABLE employees DROP COLUMN age;
c. INSERT INTO: Used to insert new records into a table.
INSERT INTO employees (employee_id, first_name, last_name, department)
VALUES (1, 'John', 'Doe', 'HR');
d. UPDATE: Used to update existing records.
UPDATE employees SET department = 'Finance' WHERE employee_id = 1;
e. DELETE: Used to delete records.
DELETE FROM employees WHERE employee_id = 1;
6. Indexes and Constraints
a. INDEX: Used to create an index on a table to improve search speed.
CREATE INDEX idx_last_name ON employees (last_name);
b. PRIMARY KEY: A column or set of columns that uniquely identify each row in the table.
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50)
);
c. FOREIGN KEY
A column that creates a relationship between two tables.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
employee_id INT,
FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
);
d. UNIQUE: Ensures all values in a column are unique.
CREATE TABLE employees (
email VARCHAR(100) UNIQUE
);
e. CHECK: Ensures that a value meets a specified condition.
CREATE TABLE employees (
age INT CHECK (age >= 18)
);
f. NOT NULL: Ensures that a column cannot have NULL values.
CREATE TABLE employees (
first_name VARCHAR(50) NOT NULL
);
7. Transactions
a. BEGIN TRANSACTION
BEGIN TRANSACTION;
b. COMMIT: Commits a transaction, saving the changes.
COMMIT;
c. ROLLBACK: Rolls back a transaction, undoing changes.
ROLLBACK;
8. SQL Data Types
INT: Integer numbers.
VARCHAR(n): Variable-length string with a maximum length of n.
CHAR(n): Fixed-length string.
DATE: Date in the format YYYY-MM-DD.
DECIMAL(p,s): Fixed-point numbers with precision p and scale s.
FLOAT: Floating-point numbers.
TEXT: Long text strings.