Show Menu
Cheatography

SQL Cheat Sheet (DRAFT) by

SQL reference, cheatsheet

This is a draft cheat sheet. It is a work in progress and is not finished yet.

General Commands

SELECT
Select data from a database.
SELECT columns
FROM table;
SELECT DISTINCT
Return only distinct values.
SELECT DISTINCT columns
FROM table;
WHERE
Extract records that fulfill a specified condition.
SELECT columns
FROM table
WHERE condition;
ORDER BY
Sort the result-set in ascending or descending order.
Ascending order is by default.
SELECT columns
FROM table
ORDER BY column ASC|DESC;
LIMIT
Specify the number of records to return. OFFSET is used to skip a specified number of rows.
SELECT columns
FROM table
WHERE condition
LIMIT number
OFFSET number;
AND, OR and NOT
Filter records based on more than one condition. Combined with WHERE.
The AND operator displays a record if all the conditions separated by AND are TRUE.
SELECT columns
FROM table
WHERE cond1 AND cond2;
The OR operator displays a record if any of the conditions separated by OR is TRUE.
SELECT columns
FROM table
WHERE cond1 OR cond2;
The NOT operator displays a record if the condit­ion(s) is NOT TRUE
SELECT columns
FROM table
WHERE NOT cond;
BETWEEN
Selects values within a given range. The values can be numbers, text, or dates. Is inclusive.
SELECT columns
FROM table
WHERE column
BETWEEN value1 AND value2;
IN
Allows to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR condit­ions.
SELECT columns
FROM table
WHERE col IN (value1, value2);
GROUP BY
Groups rows that have the same values into summary rows. Is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.
SELECT columns
FROM table
WHERE condition
GROUP BY columns
ORDER BY columns;
LIKE
Is used in a WHERE clause to search for a specified pattern in a column.
SELECT columns,
FROM table
WHERE column LIKE pattern;
1.The percent sign (%) represents zero, one, or multiple characters
2.The underscore sign (_) represents one, single character
CASE
Goes through conditions and returns a value when the first condition is met (like an if-the­n-else statem­ent). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
HAVING
Was added to SQL because the WHERE keyword cannot be used with aggregate functions.
SELECT columns
FROM table
WHERE condition
GROUP BY columns
HAVING condition
ORDER BY columns;

DATABA­SE/­TABLE

CREATE SCHEMA
Create a new SQL schema
CREATE SCHEMA sch;
CREATE DATABASE
Create a new SQL schema
CREATE SCHEMA sch;
DROP SCHEMA
Drop a SQL schema
DROP SCHEMA Sch;
DROP DATABASE
Drop a SQL database
DROP DATABASE db;
SHOW DATABASES
Check the list of databases
SHOW DATABASES
BACKUP DATABASE
Create a full back up of an existing SQL database. Ex: 'E:\te­stD­B.bak'
BACKUP DATABASE db
TO DISK = 'filepath';
 
A differ­ential back up only backs up the parts of the database that have changed since the last full database backup.
BACKUP DATABASE db
TO DISK = 'filepath'
WITH DIFFER­ENTIAL;
CREATE TABLE
Create a new table in a database
CREATE TABLE tb (
col1 datatype,
col2 datatype,
col3 datatype
);
A copy of an existing table can also be created using CREATE TABLE. The new table will be filled with the existing values from the old table
CREATE TABLE tb AS
SELECT col1, col2,...
FROM existing tb
WHERE ....;
DROP TABLE
Drop an existing table in a database
DROP TABLE tb;
TRUNCATE TABLE
Delete the data inside a table, but not the table itself.
TRUNCATE TABLE tb;
ALTER TABLE
Is used to add, delete, or modify columns in an existing table
Add a column in a table
ALTER TABLE tb
ADD col datatype;
Delete a column in a table
ALTER TABLE tb
DROP COLUMN col;
Rename a column in a table
ALTER TABLE tb
RENAME COLUMN old_name
TO new_name;
Rename a column in a table in SQL Server
EXEC sp_rename 'tb_na­me.o­ld­_name',
'new_name', 'COLUMN';
Change the data type of a column in a table
SQL Server / MS Access
ALTER TABLE tb_name
ALTER COLUMN col_name datatype;
 
My SQL / Oracle
ALTER TABLE tb_name
MODIFY COLUMN col_name datatype;
 
Oracle 10G and later
ALTER TABLE tb_name
MODIFY col_name datatype;
Constr­aints
Constr­aints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement.
CREATE TABLE tb_name
(
col1 datatype constr­aint,
col2 datatype constraint

);
 

Numeric Functions

MIN()
Returns the minimum value in a set of values.
MAX()
Returns the maximum value in a set of values.
COUNT()
Returns the number of records. NULL values are not counted.
AVG()
Returns the average value of an expres­sion. NULL values are ignored.
SUM()
Calculates the sum of a set of values. NULL values are ignored.

Arithmetic Operators

+
Add
-
Subtract
*
Multiply
/
Divide
%
Modulo

Bitwise Operators

&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR

Comparison Operators

=
Equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
<>
Not equal to

Compound Operators

+=
Add equals
-=
Subtract equals
*=
Multiply equals
/=
Divide equals
%=
Modulo equals
&=
Bitwise AND equals
^-=
Bitwise exclusive equals
|*=
Bitwise OR equals

Logical Operators

ALL
TRUE if all of the subquery values meet the condition
AND
TRUE if all the conditions separated by AND is TRUE
ANY
TRUE if any of the subquery values meet the condition
BETWEEN
TRUE if the operand is within the range of compar­isons
EXISTS
TRUE if the subquery returns one or more records
IN
TRUE if the operand is equal to one of a list of expres­sions
LIKE
TRUE if the operand matches a pattern
NOT
Displays a record if the condit­ion(s) is NOT TRUE
OR
TRUE if any of the conditions separated by OR is TRUE
SOME
TRUE if any of the subquery values meet the condition

Joining Tables

INNER JOIN
Selects records that have matching values in both tables.
SELECT columns
FROM table1
INNER JOIN table2
ON table1.col = table2.col;
LEFT JOIN
Returns all records from the left table (table1), and the matching records (if any) from the right table (table2).
SELECT column­_na­me(s)
FROM table1
LEFT JOIN table2
ON table1.co­lum­n_name =
table2.co­lum­n_name;
RIGHT JOIN
Returns all records from the right table (table2), and the matching records (if any) from the left table (table1).
SELECT column­_na­me(s)
FROM table1
RIGHT JOIN table2
ON table1.co­lum­n_name =
table2.co­lum­n_name;
CROSS JOIN
Returns all records from both tables (table1 and table2).
SELECT column­_na­me(s)
FROM table1
CROSS JOIN table2;
SELF JOIN
A self join is a regular join, but the table is joined with itself.
SELECT column­_na­me(s)
FROM table1 T1, table1 T2
WHERE condition;
UNION
Combine the result-set of two or more SELECT statem­ents. 1) Every SELECT statement within UNION must have the same number of columns 2) The columns must also have similar data types 3) The columns in every SELECT statement must also be in the same order
UNION Syntax. Selects only distinct values by default. To allow duplicate values, use UNION ALL
SELECT column­_na­me(s) FROM table1
UNION
SELECT column­_na­me(s) FROM table2;
UNION ALL
SELECT column­_na­me(s) FROM table1
UNION ALL
SELECT column­_na­me(s) FROM table2;

Date Functions

ADDDATE() OR DATE_ADD()
adds a time/date interval to a date and then returns the date.
ADDDAT­E(date, INTERVAL value addunit)
ADDDAT­E(date, days)
DATE_A­DD(­date, INTERVAL value addunit)
ADDTIME()
Adds a time interval to a time/d­atetime and then returns the time/d­ate­time. ADDTIM­E(d­ate­time, addtime)
CURDATE()
Returns the current date. The date is returned as "­YYY­Y-M­M-D­D" (string) or as YYYYMMDD (numeric). This function equals the CURDATE() function. CURDATE()
CURREN­T_D­ATE()
Returns the current date. The date is returned as "­YYY­Y-M­M-D­D" (string) or as YYYYMMDD (numeric). This function equals the CURREN­T_D­ATE() function. CURREN­T_D­ATE()
CURREN­T_T­IME()
Returns the current time. The time is returned as "­HH-­MM-­SS" (string) or as HHMMSS.uuuuuu (numeric). This function equals the CURTIME() function. CURREN­T_T­IME()
CURTIME()
Returns the current time. The time is returned as "­HH-­MM-­SS" (string) or as HHMMSS.uuuuuu (numeric). This function equals the CURREN­T_T­IME() function. CURTIME()
CURREN­T_T­IME­STAMP()
Returns the current date and time. The date and time is returned as "­YYY­Y-MM-DD HH-MM-­SS" (string) or as YYYYMM­DDH­HMM­SS.u­uuuuu (numeric). CURREN­T_T­IME­STAMP()
DATE()
Extracts the date part from a datetime expres­sion. DATE(e­xpr­ession)
DATEDIFF()
Returns the number of days between two date values. DATEDI­FF(­date1, date2)
DATE_F­ORMAT()
Formats a date as specified. DATE_F­ORM­AT(­date, format)
DATE_SUB()
Subtracts a time/date interval from a date and then returns the date. DATE_S­UB(­date, INTERVAL value interval)
DAY() OR DAYOFMONTH
returns the day of the month for a given date (a number from 1 to 31). DAY(date) DAYOFM­ONT­H(date)
DAYNAME()
returns the weekday name for a given date. DAYNAM­E(date)
DAYOFW­EEK()
returns the weekday index for a given date (a number from 1 to 7). 1=Sunday, 2=Monday, 3=Tuesday, 4=Wedn­esday, 5=Thur­sday, 6=Friday, 7=Satu­rday. DAYOFW­EEK­(date)
DAYOFW­EEK­(date)
returns the day of the year for a given date (a number from 1 to 366). DAYOFY­EAR­(date)
EXTRACT()
extracts a part from a given date. EXTRAC­T(part FROM date)
FROM_D­AYS()
returns a date from a numeric dateva­lue.is to be used only with dates within the Gregorian calendar. is the opposite of the TO_DAYS() function. FROM_D­AYS­(nu­mber)
HOUR()
returns the hour part for a given date (from 0 to 838). HOUR(d­ate­time)
LAST_DAY()
extracts the last day of the month for a given date. LAST_D­AY(­date)
LOCALT­IME() OR LOCALT­IME­STAMP()
returns the current date and time. The date and time is returned as "­YYY­Y-MM-DD HH-MM-­SS" (string) or as YYYYMM­DDH­HMM­SS.u­uuuuu (numeric). LOCALT­IME()
MAKEDATE()
creates and returns a date based on a year and a number of days value. MAKEDA­TE(­year, day)
MAKETIME()
Create and return a time value based on an hour, minute, and second value. MAKETI­ME(­hour, minute, second)
MICROS­ECOND()
Return the micros­econd part of a datetime. MICROS­ECO­ND(­dat­etime)