SQL Cheatsheet
DDL - Data Definition Language
| Command |
Function |
Example |
CREATE TABLE |
Creates a new table |
CREATE TABLE t (id INT PRIMARY KEY); |
ALTER TABLE |
Modifies table structure |
ALTER TABLE t ADD column VARCHAR(50); |
DROP TABLE |
Drops a table |
DROP TABLE t; |
TRUNCATE TABLE |
Removes all data |
TRUNCATE TABLE t; |
CREATE INDEX |
Creates an index |
CREATE INDEX idx ON t(column); |
CREATE VIEW |
Creates a view |
CREATE VIEW v AS SELECT * FROM t; |
DML - Data Manipulation Language
| Command |
Function |
Example |
SELECT |
Retrieves data |
SELECT * FROM employee; |
INSERT INTO |
Adds data |
INSERT INTO t VALUES (1, 'James'); |
UPDATE |
Modifies data |
UPDATE t SET column = 'new';; |
DELETE |
Deletes data |
DELETE FROM t WHERE id = 1; |
JOIN |
Combines tables |
SELECT * FROM a JOIN b ON a.id = b.id; |
GROUP BY |
Groups data |
SELECT dept, COUNT(*) FROM t GROUP BY dept; |
ORDER BY |
Sorts data |
SELECT * FROM t ORDER BY name ASC; |
HAVING |
Filters after GROUP BY |
HAVING COUNT(*) > 5 |
UNION |
Combines results |
SELECT * FROM a UNION SELECT * FROM b; |
DCL - Data Control Language
| Command |
Function |
Example |
GRANT |
Grants access rights |
GRANT SELECT ON t TO user1; |
REVOKE |
Revokes access rights |
REVOKE SELECT ON t FROM user1; |
TCL - Transaction Control Language
| Command |
Function |
Example |
BEGIN TRANSACTION |
Starts a transaction |
BEGIN; |
COMMIT |
Saves changes |
COMMIT; |
ROLLBACK |
Reverts changes |
ROLLBACK; |
SAVEPOINT |
Creates a rollback point |
SAVEPOINT sp1; |
Aggregate Functions
| Function |
Description |
COUNT() |
Counts the number of rows |
SUM() |
Sums the values |
AVG() |
Average |
MIN() |
Minimum value |
MAX() |
Maximum value |
Main Query Structure
SELECT column
FROM table
WHERE condition
GROUP BY column
HAVING condition
ORDER BY column ASC/DESC
LIMIT count;
SQL Execution Order
FROM / JOIN
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
LIMIT
Important Tips
- Always back up before DDL operations in production
- Use
EXPLAIN to analyze query performance
- Indexes speed up SELECT but slow down INSERT/UPDATE
- Transactions ensure data integrity
- Use aliases for complex queries
Happy Learning, SQL!
You have completed the entire SQL tutorial, from basics to advanced. Keep practicing and applying it in real projects. SQL is an important foundation in application development and data analysis.
Happy learning, and good luck!