Programming·
SQL Cheat Sheet
A quick reference for SQL,covers the fundamental aspects of SQL. You can expand on these basics as needed for more advanced SQL functionality.
Basics
Creating a Database:
CREATE DATABASE database_name;
Using a Database:
USE database_name;
Creating a Table:
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
);
Dropping a Table:
DROP TABLE table_name;
Data Types
Numeric:
INT
FLOAT
DECIMAL
String:
CHAR(size)
VARCHAR(size)
TEXT
Date and Time:
DATE
TIME
DATETIME
TIMESTAMP
CRUD Operations
Inserting Data:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Selecting Data:
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column ASC|DESC
LIMIT number;
Updating Data:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Deleting Data:
DELETE FROM table_name
WHERE condition;
Constraints
Primary Key:
CREATE TABLE table_name (
column_name datatype PRIMARY KEY
);
Foreign Key:
CREATE TABLE table_name (
column_name datatype,
FOREIGN KEY (column_name) REFERENCES other_table(column_name)
);
Unique:
CREATE TABLE table_name (
column_name datatype UNIQUE
);
Not Null:
CREATE TABLE table_name (
column_name datatype NOT NULL
);
Check:
CREATE TABLE table_name (
column_name datatype,
CHECK (condition)
);
Default:
CREATE TABLE table_name (
column_name datatype DEFAULT default_value
);
Joins
Inner Join:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
Left Join:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
Right Join:
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
Full Outer Join:
SELECT columns
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
Aggregation
Count:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Sum:
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Average:
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Max:
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Min:
SELECT MIN(column_name)
FROM table_name
WHERE condition;
Group By and Having
Group By:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
Having:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Indexes
Creating an Index:
CREATE INDEX index_name
ON table_name (column_name);
Dropping an Index:
DROP INDEX index_name
ON table_name;