Show Menu
Cheatography

SQL Cheat Sheet (DRAFT) by

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

Data Types

CHAR / VARCHAR
String (0 - 255)
TEXT
String (0 - 65535)
MEDIUMTEXT
String (0 - 16777215)
LONGTEXT
String (0 - 429496­­7295)
TINYINT x
Intege­r(-128 to 127)
SMALLINT x
Intege­r(-­32768 to 32767)
MEDIUMINT x
Integer (-8388608 to 8388607)
INT x
Integer (-2147­­483648 to 214748­­3647)
BIGINT x
Integer (-9223­­37­2­0­36­­854­­775808 to 922337­­20­3­6­85­­477­­5807)
FLOAT
Decimal (precise up to 23 digits)
DOUBLE
Decimal (24 to 53 digits)
DATE
YYYY-MM-DD
DATETIME
YYYY-MM-DD HH:MM:SS
TIMESTAMP
YYYYMM­­DD­H­HMMSS
TIME
HH:MM:SS
One of preset options
Selection of preset options
Integers (marked x) that are "­­UN­S­I­GN­­ED" have the same range of values but start from 0 (i.e., an UNSIGNED TINYINT can have any value from 0 to 255).

Select queries

Select all columns
SELECT * FROM tbl;
Select some columns
SELECT col1, col2 FROM tbl;
Filter results
[SELECT Statement] WHERE condition;
Column alias
[SELECT Statement] AS newname;
Order results
[SELECT Statement] ORDER BY col [ASC | DESC];
Group results
[SELECT Statement] GROUP BY col1;
Limit amount of Results
[SELECT Statement] LIMIT = num
Select only unique records
SELECT DISTINCT FROM tbl
 

Creating and modifying

Create a database
CREATE DATABASE db_name;
Select a database
USE db_name;
List the databases on the server
SHOW DATABASES;
Show a table's fields
DESCRIBE tbl;
Create a new table
CREATE TABLE tbl(col1, col2);
Insert data into a table
INSERT INTO tbl VALUES­("va­l1", "­val­2");
Delete a row
DELETE * FROM tbl WHERE condition;
Add a column to a table
ALTER TABLE tbl ADD COLUMN col;
Remove a column from a table
ALTER TABLE tbl DROP COLUMN col;
Make a column a primary key
ALTER TABLE tbl ADD PRIMARY KEY (col);
Update the values of a column
UPDATE tbl SET col1="v­al" WHERE condition;
Clear everything except table structure
TRUNCATE TABLE tbl;
Delete a table
DROP TABLE tbl;
Delte a database
DROP DATABASE db_name;
List all tables in database
SHOW TABLES;

Joins

INNER JOIN
Returns only when in both tables
OUTER JOIN
Returns non-ma­tching records if in at least one table
LEFT JOIN
Also returns non-ma­thing records from the left table
RIGHT JOIN
Also returns non-ma­tching records from the right table
JOIN syntax:

SELECT * FROM tbl1 [INNER | OUTER | LEFT | RIGHT] JOIN tbl2 ON tbl1.id = tbl2.id;
 

String functions

Compare strings
STRCMP­("st­r1", "­str­2");
Convert to lower case
LOWER(­"­str­");
Convert to upper case
UPPER(­"­str­");
(Right) trim
RTIM("s­tr");
Left trim
LTRIM(­"­str­");
Substring
SUBSTR­ING­("st­r", start_pos, num_ch­ars);
Concat­enate
CONCAT­("st­r1", "­str­2");