SQL Cheat Sheet
SQL Cheat Sheet
SQL Cheat Sheet
org
QUERYING DATA FROM A TABLE
SELECT c1, c2
FROM t1
INNER JOIN t2 ON condition;
Inner join t1 and t2
SELECT c1, c2
FROM t1
LEFT JOIN t2 ON condition;
Left join t1 and t1
SELECT * FROM t;
Query all rows and columns from a table
SELECT c1, c2 FROM t
WHERE condition;
Query data and filter rows with a condition
SELECT DISTINCT c1 FROM t
WHERE condition;
Query distinct rows from a table
SELECT c1, c2 FROM t
ORDER BY c1 ASC [DESC];
Sort the result set in ascending or descending
order
SELECT c1, c2 FROM t
ORDER BY c1
LIMIT n OFFSET offset;
Skip offset of rows and return the next n rows
SELECT c1, aggregate(c2)
FROM t
GROUP BY c1;
Group rows using an aggregate function
SELECT c1, aggregate(c2)
FROM t
GROUP BY c1
HAVING condition;
Filter groups using HAVING clause
SELECT c1, c2
FROM t1
RIGHT JOIN t2 ON condition;
Right join t1 and t2
SELECT c1, c2
FROM t1
FULL OUTER JOIN t2 ON condition;
Perform full outer join
SELECT c1, c2
FROM t1
CROSS JOIN t2;
Produce a Cartesian product of rows in tables
SELECT c1, c2
FROM t1, t2;
Another way to perform cross join
SELECT c1, c2
FROM t1 A
INNER JOIN t2 B ON condition;
Join t1 to itself using INNER JOIN clause
MODIFYING DATA
CREATE TABLE t(
c1 INT, c2 INT, c3 VARCHAR,
PRIMARY KEY (c1,c2)
);
Set c1 and c2 as a primary key
MANAGING INDEXES
MANAGING TRIGGERS
CREATE OR MODIFY TRIGGER trigger_name
WHEN EVENT
ON table_name TRIGGER_TYPE
EXECUTE stored_procedure;
Create or modify a trigger
WHEN
BEFORE invoke before the event occurs
AFTER invoke after the event occurs
EVENT
INSERT invoke for INSERT
UPDATE invoke for UPDATE
DELETE invoke for DELETE
TRIGGER_TYPE
FOR EACH ROW
FOR EACH STATEMENT
CREATE TRIGGER before_insert_person
BEFORE INSERT
ON person FOR EACH ROW
EXECUTE stored_procedure;
Create a trigger invoked before a new row is
inserted into the person table
DROP TRIGGER trigger_name
Delete a specific trigger