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 column1, column2
FROM table_­name;
SELECT DISTINCT
Return only distinct values.
SELECT DISTINCT column1, column2
FROM table_­name;
WHERE
Extract records that fulfill a specified condition.
SELECT column1, column2
FROM table_name
WHERE condition;
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 column1, column2
FROM table_name
WHERE condition1 AND condit­ion2;
The OR operator displays a record if any of the conditions separated by OR is TRUE.
SELECT column1, column2
FROM table_name
WHERE condition1 OR condit­ion2;
The NOT operator displays a record if the condit­ion(s) is NOT TRUE
SELECT column1, column2
FROM table_name
WHERE NOT condition;
ORDER BY
Sort the result-set in ascending or descending order.
Ascending order is by default.
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC;
INSERT INTO
Insert new records in a table.
1. Specify both the column names and the values.
INSERT INTO table_name
(column1, column2, column3)
VALUES (value1, value2)
If you are adding values for all the columns of the table, no need to specify the column names.
INSERT INTO table_name
VALUES (value1, value2);
NULL
A field with a NULL value is a field with no value. A field with a NULL value is one that has been left blank during record creation.
IS NULL Syntax
SELECT column­_names
FROM table_name
WHERE column­_name IS NULL;
IS NOT NULL Syntax
SELECT column­_names
FROM table_name
WHERE column­_name IS NOT NULL;
UPDATE
Modify the existing records in a table.
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
DELETE
Delete existing records in a table.
DELETE FROM table_name
WHERE condition;
LIMIT
Specify the number of records to return.
SELECT column­_na­me(s)
FROM table_name
WHERE condition
LIMIT number;
IN
Allows to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR condit­ions.
SELECT column­_na­me(s)
FROM table_name
WHERE column­_name IN (value1, value2);
 
SELECT column­_na­me(s)
FROM table_name
WHERE column­_name
IN (SELECT STATEM­ENT);
BETWEEN
Selects values within a given range. The values can be numbers, text, or dates. Is inclusive.
SELECT column­_na­me(s)
FROM table_name
WHERE column­_name
BETWEEN value1 AND 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 column­_na­me(s)
FROM table_name
WHERE condition
GROUP BY column­_na­me(s)
ORDER BY column­_na­me(s);
HAVING
Was added to SQL because the WHERE keyword cannot be used with aggregate functions
SELECT column­_na­me(s)
FROM table_name
WHERE condition
GROUP BY column­_na­me(s)
HAVING condition
ORDER BY column­_na­me(s);
EXISTS
Test for the existence of any record in a subquery. Returns TRUE if the subquery returns one or more records.
SELECT column­_na­me(s)
FROM table_name
WHERE EXISTS
(SELECT column­_name
FROM table_name WHERE condit­ion);
ANY
Allow to perform a comparison between a single column value and a range of other values.
1.Returns a boolean value as a result 2. Returns TRUE if ANY of the subquery values meet the condition.
ANY means that the condition will be true if the operation is true for any of the values in the range.
SELECT column­_na­me(s)
FROM table_name
WHERE column­_name operator ANY
(SELECT column­_name
FROM table_name
WHERE condit­ion);
ALL
Returns:
1. A boolean value as a result
2. Returns TRUE if ALL of the subquery values meet the condition
3. Is used with SELECT, WHERE and HAVING statem­ents.

ALL means that the condition will be true only if the operation is true for all values in the range.
ALL Syntax With SELECT
SELECT ALL column­_na­me(s)
FROM table_name
WHERE condition;
ALL Syntax With WHERE or HAVING
SELECT column­_na­me(s)
FROM table_name
WHERE column­_name operator ALL
(SELECT column­_name
FROM table_name
WHERE condit­ion);
INSERT INTO SELECT
Copies data from one table and Inserts it into another table. Requires that the data types in source and target tables matche­s.The existing records in the target table are unaffe­cted.
 
Copy all columns from one table to another table
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
 
Copy only some columns from one table into another table
INSERT INTO table2 (col1, col2 ...)
SELECT col1, col2 ...
FROM table1
WHERE condition;
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;

DATABA­SE/­TABLE

CREATE SCHEMA
Create a new SQL schema
CREATE SCHEMA sch;
DROP SCHEMA
Drop a SQL schema
DROP SCHEMA Sch;
SET search­_path = sch;
CREATE DATABASE
Create a new SQL database
CREATE DATABASE db;
DROP DATABASE
Drop a SQL database
DROP DATABASE db;
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 column­_na­me(s)
FROM table1
INNER JOIN table2
ON table1.co­lum­n_name =
table2.co­lum­n_name;
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)