Certainly! Creating a SQL Syntax Cheat Sheet is a great idea to help others learn and reference SQL commands quickly. Below is a comprehensive cheat sheet formatted in Markdown, suitable for a GitHub repository.
A quick reference guide to SQL syntax, commands, and functions.
- Data Definition Language (DDL)
- Data Manipulation Language (DML)
- Data Control Language (DCL)
- Transaction Control Language (TCL)
- Constraints
- Operators
- Functions
- Joins
- Subqueries
- Views
- Indexes
- Stored Procedures and Functions
- Common Clauses
- Data Types
- Additional Resources
Create a Database
CREATE DATABASE database_name;
Create a Table
CREATE TABLE table_name (
column1 datatype [constraints],
column2 datatype [constraints],
...
);
Example:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
CreatedDate DATE DEFAULT CURRENT_DATE
);
Add a Column
ALTER TABLE table_name
ADD column_name datatype [constraints];
Modify a Column
ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;
Drop a Column
ALTER TABLE table_name
DROP COLUMN column_name;
Drop a Table
DROP TABLE table_name;
Drop a Database
DROP DATABASE database_name;
Basic Syntax
SELECT column1, column2, ...
FROM table_name
[WHERE condition]
[GROUP BY column1, column2, ...]
[HAVING condition]
[ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...];
Example:
SELECT FirstName, LastName
FROM Customers
WHERE CreatedDate > '2023-01-01'
ORDER BY LastName ASC;
Insert Into All Columns
INSERT INTO table_name
VALUES (value1, value2, ...);
Insert Into Specific Columns
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Example:
INSERT INTO Customers (FirstName, LastName, Email)
VALUES ('Alice', 'Smith', 'alice@example.com');
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
UPDATE Customers
SET Email = 'newemail@example.com'
WHERE CustomerID = 1;
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM Customers
WHERE CustomerID = 1;
GRANT privilege_type ON object_name TO user [WITH GRANT OPTION];
Example:
GRANT SELECT, INSERT ON Customers TO 'db_user';
REVOKE privilege_type ON object_name FROM user;
Example:
REVOKE INSERT ON Customers FROM 'db_user';
COMMIT;
ROLLBACK;
SAVEPOINT savepoint_name;
Rollback to Savepoint
ROLLBACK TO SAVEPOINT savepoint_name;
- NOT NULL: Ensures a column cannot have a NULL value.
- UNIQUE: Ensures all values in a column are unique.
- PRIMARY KEY: Uniquely identifies each record in a table.
- FOREIGN KEY: Ensures referential integrity between tables.
- CHECK: Ensures that all values in a column satisfy a specific condition.
- DEFAULT: Sets a default value for a column if none is specified.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE NOT NULL,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
- Arithmetic Operators:
+
,-
,*
,/
,%
- Comparison Operators:
=
,<>
or!=
,>
,<
,>=
,<=
- Logical Operators:
AND
,OR
,NOT
- Other Operators:
BETWEEN
,IN
,LIKE
,IS NULL
,EXISTS
Example:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 50;
SELECT * FROM Customers
WHERE Email LIKE '%@example.com';
- COUNT(): Counts the number of rows.
- SUM(): Calculates the sum of a numeric column.
- AVG(): Calculates the average value.
- MIN(): Finds the minimum value.
- MAX(): Finds the maximum value.
Example:
SELECT COUNT(*) FROM Orders;
SELECT CustomerID, SUM(TotalAmount) as TotalSpent
FROM Orders
GROUP BY CustomerID;
- UPPER(string): Converts to uppercase.
- LOWER(string): Converts to lowercase.
- SUBSTRING(string, start, length): Extracts a substring.
- TRIM(string): Removes whitespace.
- CONCAT(string1, string2, ...): Concatenates strings.
Example:
SELECT UPPER(FirstName), LOWER(LastName)
FROM Customers;
- NOW(): Returns current date and time.
- CURDATE(): Returns current date.
- DATE_ADD(date, INTERVAL value unit): Adds a time interval to a date.
- DATEDIFF(date1, date2): Returns the difference between two dates.
Example:
SELECT NOW();
SELECT DATE_ADD(CURDATE(), INTERVAL 7 DAY);
Returns records with matching values in both tables.
SELECT columns
FROM table1
INNER JOIN table2 ON table1.column = table2.column;
Example:
SELECT Orders.OrderID, Customers.FirstName, Customers.LastName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Returns all records from the left table, and matched records from the right table.
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.column = table2.column;
Returns all records from the right table, and matched records from the left table.
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.column = table2.column;
Returns all records when there is a match in either left or right table.
SELECT columns
FROM table1
FULL OUTER JOIN table2 ON table1.column = table2.column;
A query nested inside another query.
SELECT column1
FROM table1
WHERE column2 = (SELECT column FROM table2 WHERE condition);
Example:
SELECT FirstName, LastName
FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders WHERE TotalAmount > 1000);
A virtual table based on the result set of an SQL statement.
Create a View
CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE condition;
Example:
CREATE VIEW HighValueOrders AS
SELECT OrderID, CustomerID, TotalAmount
FROM Orders
WHERE TotalAmount > 1000;
Used to speed up the retrieval of data.
Create an Index
CREATE INDEX index_name
ON table_name (column1, column2, ...);
Create a Unique Index
CREATE UNIQUE INDEX index_name
ON table_name (column);
A set of SQL statements that can be stored and executed on the database server.
Create a Stored Procedure
CREATE PROCEDURE procedure_name (parameters)
BEGIN
-- SQL statements
END;
Example:
CREATE PROCEDURE GetCustomerOrders(IN custID INT)
BEGIN
SELECT * FROM Orders WHERE CustomerID = custID;
END;
A function that returns a single value.
Create a Function
CREATE FUNCTION function_name (parameters)
RETURNS datatype
BEGIN
DECLARE variable datatype;
-- SQL statements
RETURN variable;
END;
Filters records that meet specific conditions.
SELECT * FROM table_name
WHERE condition;
Groups rows that have the same values in specified columns.
SELECT column1, AGG_FUNC(column2)
FROM table_name
GROUP BY column1;
Filters groups according to specified conditions.
SELECT column1, AGG_FUNC(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Sorts the result set.
SELECT * FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Limits the number of records returned.
-
MySQL, PostgreSQL, SQLite
SELECT * FROM table_name LIMIT number OFFSET offset;
-
SQL Server
SELECT TOP number * FROM table_name;
-
Oracle
SELECT * FROM table_name FETCH FIRST number ROWS ONLY;
INT
DECIMAL(p, s)
FLOAT
DOUBLE
CHAR(n)
VARCHAR(n)
TEXT
DATE
TIME
DATETIME
TIMESTAMP
BINARY
VARBINARY
BLOB
BOOLEAN
orBIT
- Official Documentation
- Online Tutorials
- Practice Platforms
- AI2sql: Generate SQL queries from natural language descriptions using AI.
- Learning: Use this guide as a starting point to learn SQL syntax and concepts.
- Reference: Quickly look up syntax for SQL commands and functions.
- Contribution: Feel free to contribute by suggesting improvements or adding new sections.
This cheat sheet is released under the MIT License.
Note: SQL syntax may vary slightly between different database systems (e.g., MySQL, PostgreSQL, SQL Server, Oracle). Always refer to the official documentation of the database you are using for exact syntax and additional features.