SQL
SQL syntax mainly
Some of The Most Important SQL Commands
SELECT
- extracts data from a databaseUPDATE
- updates data in a databaseDELETE
- deletes data from a database-
INSERT INTO
- inserts new data into a database CREATE DATABASE
- creates a new databaseALTER DATABASE
- modifies a databaseCREATE TABLE
- creates a new tableALTER TABLE
- modifies a tableDROP TABLE
- deletes a tableCREATE INDEX
- creates an index (search key)DROP INDEX
- deletes an index
SELECT
SYNTAX
SELECT column1, column2, ... FROM table_name;column1, column2, ... are the field names of the table you want to select data from.
The table_name represents the name of the table you want to select data from.
EXAMPLE
SELECT CustomerName, City FROM Customers;
SELECT DISTINCT
The SELECT DISTINCT statement is used to return only distinct (different) values.
SYNTAX
SELECT DISTINCT column1, column2, ... FROM table_name;
EXAMPLE
SELECT DISTINCT Country FROM Customers;
COUNT DISTINCT
By using the DISTINCT keyword in a function called COUNT, we can return the number of different countries.
SELECT COUNT(DISTINCT Country) FROM Customers;
Note: The COUNT(DISTINCT column_name) is not supported in Microsoft Access databases. LEARN WHY!!!
Workaround for MS Access:
SELECT Count(*) AS DistinctCountries FROM (SELECT DISTINCT Country FROM Customers);
WHERE
The WHERE clause is used to filter records based on specified conditions.
SYNTAX
SELECT column1, column2 FROM table_name WHERE condition;
EXAMPLE
SELECT * FROM Customers WHERE Country='Mexico';
OPERATORS
Common operators: =, <>, >, <, >=, <=, BETWEEN, LIKE, IN
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
ORDER BY
The ORDER BY keyword sorts the result set in ascending or descending order.
SYNTAX
SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];
EXAMPLE
SELECT * FROM Customers ORDER BY Country DESC;
MULTIPLE COLUMNS
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;
GROUP BY
The GROUP BY statement groups rows that have the same values into summary rows.
SYNTAX
SELECT column_name(s) FROM table_name GROUP BY column_name(s);
EXAMPLE
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;
WITH HAVING
HAVING filters groups after GROUP BY is applied
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5;
JOIN
JOINs combine rows from two or more tables based on related columns.
TYPES
- INNER JOIN: Returns matching records
- LEFT JOIN: All left table + matching right
- RIGHT JOIN: All right table + matching left
- FULL JOIN: All records when match in either
INNER JOIN EXAMPLE
SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
LEFT JOIN EXAMPLE
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName;
INSERT INTO
The INSERT INTO statement adds new records to a table.
SYNTAX
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
EXAMPLE
INSERT INTO Customers (CustomerName, ContactName, Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Norway');
INSERT MULTIPLE ROWS
INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway'), ('Greasy Burger', 'Bergen', 'Norway'), ('Tasty Tee', 'Oslo', 'Norway');
UPDATE
The UPDATE statement modifies existing records in a table.
SYNTAX
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
EXAMPLE
UPDATE Customers SET ContactName = 'Alfred Schmidt', City = 'Frankfurt' WHERE CustomerID = 1;
WARNING: Without a WHERE clause, all records will be updated!
UPDATE Customers SET ContactName='Juan'; -- Updates ALL records
DELETE
The DELETE statement removes existing records from a table.
SYNTAX
DELETE FROM table_name WHERE condition;
EXAMPLE
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
DANGER: Omitting WHERE clause will delete all records!
DELETE FROM Customers; -- Deletes ALL records
TRUNCATE
For deleting all records more efficiently:
TRUNCATE TABLE Customers;
CREATE TABLE
Creates a new table in the database with specified columns and constraints.
SYNTAX
CREATE TABLE table_name (column1 datatype constraints, column2 datatype constraints, ...);
EXAMPLE
CREATE TABLE Users (UserID INT PRIMARY KEY AUTO_INCREMENT, Username VARCHAR(50) NOT NULL UNIQUE, Email VARCHAR(100) CHECK (Email LIKE '%@%.%'), JoinDate DATETIME DEFAULT CURRENT_TIMESTAMP);
TECHNICAL NOTE: Behind the scenes, this creates:
- Table metadata in the data dictionary
- Storage allocation (data files, indexes)
- Primary key index (usually a B+ tree)
ALTER TABLE
Modifies an existing table structure (add/remove columns, change constraints).
SYNTAX
ALTER TABLE table_name ADD column_name datatype; -- or DROP COLUMN column_name; -- or MODIFY COLUMN column_name new_datatype;
EXAMPLE
ALTER TABLE Customers ADD Phone VARCHAR(15), MODIFY COLUMN Address VARCHAR(200);
WARNING: Some ALTER operations may lock the table or rewrite all rows!
INDEXES
Improve query performance by creating optimized data access paths.
SYNTAX
CREATE INDEX index_name ON table_name (column1, column2); -- or DROP INDEX index_name;
EXAMPLE
CREATE INDEX idx_customer_country ON Customers(Country); CREATE UNIQUE INDEX idx_product_code ON Products(ProductCode);
HOW IT WORKS: Most databases use B+ trees for indexes:
- Leaf nodes contain actual data (clustered) or pointers (non-clustered)
- Typically 3-4 levels deep for millions of records
- Maintenance overhead on INSERT/UPDATE/DELETE
TRANSACTION
Group SQL statements into atomic units of work.
SYNTAX
BEGIN TRANSACTION; -- SQL statements COMMIT; -- or ROLLBACK;
EXAMPLE
BEGIN TRANSACTION; UPDATE Accounts SET balance = balance - 100 WHERE id = 1; UPDATE Accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
UNDER THE HOOD: Databases implement this using:
- Write-Ahead Logging (WAL) for durability
- Locking or MVCC for isolation
- Transaction ID tracking for atomicity
STORED PROCEDURES
Precompiled SQL code stored in the database server.
SYNTAX
CREATE PROCEDURE procedure_name(parameters) AS BEGIN -- SQL statements END;
EXAMPLE
CREATE PROCEDURE GetCustomerOrders(IN customer_id INT) AS BEGIN SELECT * FROM Orders WHERE CustomerID = customer_id; END; -- -- Execute with: CALL GetCustomerOrders(5);
PERFORMANCE BENEFITS:
- Reduced network traffic (single call vs multiple queries)
- Execution plan caching
- Server-side processing
VIEWS
Virtual tables based on the result set of a SQL query.
SYNTAX
CREATE VIEW view_name AS SELECT column1, column2 FROM table_name WHERE condition;
EXAMPLE
CREATE VIEW ActiveCustomers AS SELECT CustomerName, ContactName FROM Customers WHERE Active = 1;
IMPLEMENTATION DETAILS:
- Some views are "materialized" (stored physically)
- Most are "virtual" (recomputed on each access)
- Can have indexes for performance (materialized views)
EXPLAIN
Shows the execution plan of a query (critical for optimization).
SYNTAX
EXPLAIN SELECT * FROM table WHERE condition;
EXAMPLE
EXPLAIN SELECT Customers.CustomerName, COUNT(Orders.OrderID) FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.CustomerName;
KEY PLAN ELEMENTS:
- Access method (index scan, full table scan)
- Join algorithms (nested loop, hash join, merge join)
- Estimated rows/cost
- Sort operations
BACKUP AND RESTORE
Critical database maintenance operations (syntax varies by DBMS).
MYSQL EXAMPLE
-- Backup mysqldump -u username -p database_name > backup.sql; -- Restore mysql -u username -p database_name < backup.sql;
POSTGRESQL EXAMPLE
-- Backup pg_dump -U username -d database_name -f backup.sql; -- Restore psql -U username -d database_name -f backup.sql;
TECHNICAL CONSIDERATIONS:
- Logical vs physical backups
- Point-in-time recovery (using WAL logs)
- Hot vs cold backups
UNION / UNION ALL
SYNTAX
SELECT column1, column2 FROM table1 UNION SELECT column1, column2 FROM table2;The UNION operator combines the results of two or more SELECT statements, excluding duplicates. Use UNION ALL to include duplicates.
EXAMPLE
SELECT city FROM customers UNION SELECT city FROM suppliers;
SUBQUERIES
SYNTAX
SELECT column1, column2 FROM table_name WHERE column1 = (SELECT column1 FROM table_name WHERE condition);A subquery is a query nested inside another query. It returns a result that can be used in the outer query.
EXAMPLE
SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name = 'HR');
LIMIT / OFFSET
SYNTAX
SELECT column1, column2 FROM table_name LIMIT 10 OFFSET 20;LIMIT restricts the number of rows returned, and OFFSET skips a specified number of rows.
EXAMPLE
SELECT * FROM employees LIMIT 5 OFFSET 10;
CASE
SYNTAX
SELECT column1, CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result3 END AS alias FROM table_name;The CASE statement allows you to return different values based on conditions.
EXAMPLE
SELECT name, CASE WHEN age > 30 THEN 'Senior' ELSE 'Junior' END AS experience_level FROM employees;
MERGE / UPSERT
SYNTAX
MERGE INTO target_table AS target USING source_table AS source ON target.id = source.id WHEN MATCHED THEN UPDATE SET target.column1 = source.column1 WHEN NOT MATCHED THEN INSERT (id, column1) VALUES (source.id, source.column1);MERGE (also known as UPSERT) combines the functionality of INSERT and UPDATE.
EXAMPLE
MERGE INTO employees AS target USING new_employees AS source ON target.id = source.id WHEN MATCHED THEN UPDATE SET target.salary = source.salary WHEN NOT MATCHED THEN INSERT (id, salary) VALUES (source.id, source.salary);
Triggers
SYNTAX
CREATE TRIGGER trigger_name AFTER INSERT ON table_name FOR EACH ROW BEGIN -- Trigger logic here END;Triggers are automatic actions that occur when specific database events (INSERT, UPDATE, DELETE) happen.
EXAMPLE
CREATE TRIGGER salary_update AFTER UPDATE ON employees FOR EACH ROW BEGIN -- Update audit log here END;
Normalization (1NF, 2NF, 3NF)
SYNTAX
-- No specific syntax for normalization, it's a process: -- Convert to 1NF: Ensure atomic columns -- Convert to 2NF: Remove partial dependencies -- Convert to 3NF: Remove transitive dependenciesNormalization is the process of organizing data to reduce redundancy and dependency.
EXAMPLE
-- Split address into a separate table (2NF) CREATE TABLE addresses ( id INT PRIMARY KEY, street VARCHAR, city VARCHAR, state VARCHAR );
PARTITIONING
SYNTAX
CREATE TABLE employees ( id INT, name VARCHAR, salary DECIMAL, department_id INT ) PARTITION BY RANGE (salary);Partitioning splits large tables into smaller, more manageable pieces based on specified criteria.
EXAMPLE
CREATE TABLE sales ( sale_id INT, amount DECIMAL ) PARTITION BY RANGE (amount);
REPLICATION
SYNTAX
-- No specific syntax for replication, usually configured at the DBMS level.Replication copies data across different servers for fault tolerance or load balancing.
EXAMPLE
-- Set up master-slave replication on MySQL or PostgreSQL
SHARDING
SYNTAX
-- No specific syntax for sharding, usually handled at the application level or by DBMS.Sharding distributes data across multiple servers, often based on a key such as user ID or region.
EXAMPLE
-- Shard data across multiple servers based on user region