SQL Reference Guide
1. Introduction to SQL
SQL (Structured Query Language) is used to interact with relational databases.
2. SQL Data Types
- INT - Integer
- VARCHAR(n) - Variable-length string
- CHAR(n) - Fixed-length string
- TEXT - Large text data
- BOOLEAN - True or False
- DATE - Date value
- DATETIME - Date and time
- FLOAT - Floating-point number
- DECIMAL(p, s) - Fixed-point number
3. SQL Commands
- CREATE - Creates a new database or table.
- ALTER - Modifies an existing table structure.
- DROP - Deletes a database or table.
- TRUNCATE - Deletes all records from a table.
Example:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
department VARCHAR(50)
);
4. Data Manipulation Language (DML)
- INSERT - Adds new records.
- UPDATE - Modifies existing records.
- DELETE - Removes records.
Example:
INSERT INTO employees (id, name, age, department) VALUES (1, 'John Doe', 30, 'HR');
5. Data Query Language (DQL)
- SELECT - Retrieves data from tables.
Example:
SELECT name, age FROM employees WHERE department = 'HR';
6. Data Control Language (DCL)
- GRANT - Gives permissions.
- REVOKE - Removes permissions.
Example:
GRANT SELECT, INSERT ON employees TO user1;
7. Joins in SQL
- INNER JOIN - Matches records in both tables.
- LEFT JOIN - Includes all records from the left table.
- RIGHT JOIN - Includes all records from the right table.
- FULL JOIN - Includes all records from both tables.
Example:
SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.id;
8. Indexing in SQL
- CREATE INDEX - Creates an index.
- DROP INDEX - Removes an index.
Example:
CREATE INDEX idx_employee_name ON employees(name);
9. Views in SQL
- CREATE VIEW - Defines a view.
- DROP VIEW - Removes a view.
Example:
CREATE VIEW employee_details AS
SELECT name, age, department FROM employees;
10. Stored Procedures and Functions
Stored procedures and functions execute SQL code.
Stored Procedure:
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT * FROM employees;
END;
Function:
CREATE FUNCTION GetTotalEmployees()
RETURNS INT
BEGIN
DECLARE total INT;
SELECT COUNT(*) INTO total FROM employees;
RETURN total;
END;
11. SQL Triggers
Triggers execute automatically on data changes.
Example:
CREATE TRIGGER before_employee_insert
BEFORE INSERT ON employees
FOR EACH ROW
SET NEW.created_at = NOW();
12. SQL Optimization Tips
- Use indexes to speed up searches.
- Avoid SELECT *; instead, specify columns.
- Use joins efficiently.
- Normalize databases to reduce redundancy.
- Optimize queries with EXPLAIN ANALYZE.