0% found this document useful (1 vote)
130 views

SQL Cheat Sheet

SQL is a language for managing structured data in relational database management systems. It uses commands like SELECT, INSERT, UPDATE, and DELETE to fetch, add, edit, and remove data. SQL is strongly typed, requiring specification of data types like integers, strings, and dates that determine how data is stored and operated on. Common SQL data types include VARCHAR for variable-length strings, DATE for dates, and INT or FLOAT for numbers.

Uploaded by

diceplayaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
130 views

SQL Cheat Sheet

SQL is a language for managing structured data in relational database management systems. It uses commands like SELECT, INSERT, UPDATE, and DELETE to fetch, add, edit, and remove data. SQL is strongly typed, requiring specification of data types like integers, strings, and dates that determine how data is stored and operated on. Common SQL data types include VARCHAR for variable-length strings, DATE for dates, and INT or FLOAT for numbers.

Uploaded by

diceplayaa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

SQL Cheat Sheet

What Is SQL?
SQL is short for Structured Query Language. Its chief function is managing structured data
on a relational database management system (RDBMS), usually arranged in tables. SQL is
case-insensitive, but it’s common to capitalize SQL keywords such as SELECT and FROM.

Suppose you want to execute multiple SQL statements in the same server call. In that case,
\
some database administration tools, such as MySQL Workbench, require a semicolon (;) at
the end of each SQL statement to separate them.
Screenshot of MySQL Workbench in action

\ Basic SQL Syntax


This section is the essential SQL syntax cheat sheet. If you’re short on time, read this
section first.

Command Syntax Description


ALTER TABLE ALTER TABLE Add columns of a specified
table_name ADD datatype to a table in a
column_name datatype; database
AS SELECT column_name AS A keyword in SQL to
'Alias' FROM rename a column or table
table_name; using an alias name
CASE SELECT column_name, Create different outputs
CASE WHEN condition inside a SELECT statement
THEN 'Result_1' WHEN
condition THEN
'Result_2' ELSE
'Result_3' END FROM
table_name;
CREATE TABLE CREATE TABLE Create a new table in a
table_name (column_1 database and specify the
datatype, column_2 name of the table and
datatype, column_3 columns of a specified
datatype); datatype inside it
DELETE DELETE FROM Remove the rows from a
table_name WHERE table
some_column =
some_value;
HAVING SELECT column_name, Use it like the WHERE
COUNT(*) FROM keyword in aggregating
table_name GROUP BY functions such as GROUP
column_name HAVING BY
COUNT(*) > value;
INSERT INSERT INTO Add new rows to a table
table_name (column_1, with specified values
column_2, column_3)
VALUES (value_1,
'value_2', value_3);
SELECT SELECT column_name Fetch data from a database;
FROM table_name; the column_name can be a
function applied to an
existing column
SELECT DISTINCT SELECT DISTINCT Return unique, non-
column_name FROM repeating values in specified
table_name; columns
UPDATE UPDATE table_name SET Edit rows in a table
some_column =
some_value WHERE
some_column =
some_value;
WITH WITH temporary_name Process the result of a
AS (SELECT * FROM query (SELECT * FROM
table_name) SELECT * table_name) stored in a
\ FROM temporary_name temporary table referenced
WHERE column_name by the alias
operator value; temporary_name
/* */ -- /* multi-line comment Enclose comments:
explaining the code ● For comments
*/ --single-line spanning several
comment lines: /* */
● For comments on
the same line as the
command: --

Data Types in SQL


The data type of a SQL column identifies how SQL will interact with the stored data. SQL is
a strongly typed language, so it’s important to tell apart various data types.

Strongly Typed Languages vs Weakly Typed Languages


In computer programming, a programming language is strongly typed if it demands the
specification of data types.
In strongly typed languages, once a type is assigned to a variable at runtime or compile time,
it retains that type and can’t be intermingled in expressions with other types easily. You
cannot assign an integer to a string variable in a strongly typed language. Boolean variables
can only hold Boolean values, and writing any other value to it may throw errors.

In weakly typed languages, once a type is assigned to a variable at runtime or compile time,
it can be intermingled in expressions with other types easily. Here, an integer assigned to a
string variable may get converted into the character(s) representing the integer. You can
also assign a string or integer to a variable previously used to hold a Boolean value.

The same name may map to different data types in other SQL implementations. Therefore,
always consult the relevant documentation (MySQL, PostgreSQL).

MySQL Data Types (Version 8.0)


MySQL has three main data types: string, numeric, and date and time:

String
Data type Description

CHAR(size) A fixed-length string: can contain letters, numbers, and


special characters. The size parameter specifies the
column length in characters, from 0 to 255. The default is 1.
\
VARCHAR(size) A variable-length string: can contain letters, numbers, and
special characters. The size parameter specifies the
maximum string length in characters, from 0 to 65535.

BINARY(size) Equal to CHAR() but stores binary byte strings. The size
parameter specifies the column length in bytes. The default
is 1.
VARBINARY(size) Equal to VARCHAR() but stores binary byte strings. The
size parameter specifies the maximum column length in
bytes.
TINYBLOB For BLOBs (Binary Large Objects). Max length: 255 bytes.

TINYTEXT Hold a string with a maximum length of 255 characters.

TEXT(size) Hold a string with a maximum length of 65,535 bytes.

BLOB(size) For BLOBs (Binary Large Objects). Hold up to 65,535 bytes


of data.
MEDIUMTEXT Hold a string with a maximum length of 16,777,215
characters.
MEDIUMBLOB For BLOBs (Binary Large Objects). Hold up to 16,777,215
bytes of data.
LONGTEXT Hold a string with a maximum length of 4,294,967,295
characters.
LONGBLOB For BLOBs (Binary Large Objects). Hold up to
4,294,967,295 bytes of data.
ENUM(val1, val2, A string object that can have only one value, chosen from a
val3, ...) list of possible values. You can list up to 65535 values in an
ENUM list. If you insert a value that is not in the list, you
insert a blank value. SQL sorts the values in the order you
enter them.
SET(val1, val2, A string object that can have 0 or more values, chosen from
val3, ...) a list of possible values. You can list up to 64 values in a
SET list.

Numeric
We leave the “Alias” field blank if a data type has no alias.

Data type Alias Description

BIT(size) A bit-value type. The size parameter


specifies the number of bits per value and
can hold a value from 1 to 64. The default
value for size is 1.
TINYINT(size) A tiny integer. The signed is from -128 to
127. The unsigned range is from 0 to 255.
The size parameter specifies the maximum
display width (which is 255).
\
BOOLEAN BOOL Zero = false, nonzero values = true.

SMALLINT(size) A small integer. The signed range is from -


32768 to 32767. The unsigned range is from
0 to 65535. The size parameter specifies
the maximum display width (which is 255).
MEDIUMINT(size) A medium-sized integer. The signed range is
from -8388608 to 8388607. The unsigned
range is from 0 to 16777215. The size
parameter specifies the maximum display
width (which is 255).
INTEGER(size) INT(size) A medium-sized integer. The signed range is
from -2147483648 to 2147483647. The
unsigned range is from 0 to 4294967295.
The size parameter specifies the maximum
display width (which is 255).
BIGINT(size) A large integer. The signed range is from -
9223372036854775808 to
9223372036854775807. The unsigned
range is from 0 to 18446744073709551615.
The size parameter specifies the maximum
display width (which is 255).
FLOAT(size, d), Floating point number. The parameter size
DOUBLE(size, d), specifies the total number of digits. The d
DOUBLE parameter sets the number of digits.
PRECISION(size, d)
Future MySQL versions (beyond MySQL
8.0.17) will remove this syntax.
FLOAT(p) Floating point number. MySQL uses the p
value to determine whether to use FLOAT or
DOUBLE for the resulting data type. If p is
from 0 to 24, the data type becomes
FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE().
DECIMAL(size, d) DEC(size, Fixed-point number. The parameter size
d) specifies the total number of digits. The d
parameter sets the number of digits after the
decimal point. The maximum number for
size is 65. The maximum number for d is
30. The default value for size is 10. The
default value for d is 0.

Note: All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you
add the UNSIGNED option, MySQL disallows negative values for the column. If you add the
ZEROFILL option, MySQL automatically adds the UNSIGNED attribute to the column.

Date and time


Adding DEFAULT and ON UPDATE in the column definition helps you get automatic
\ initialization and updating to the current date and time.

Below, the fsp (fractional seconds precision, in microseconds) value must be 0–6. For
example, set fsp to 1 to encapsulate 0.1–0.9 seconds and 2 for 0.01–0.99 seconds. A value
of 0 indicates the absence of a fractional part. If omitted, the default precision is 0.

Data type Description

DATE Date. Format: YYYY-MM-DD. The supported range is from


'1000-01-01' to '9999-12-31'
DATETIME(fsp) Date and time combination. Format: YYYY-MM-DD
hh:mm:ss.
TIMESTAMP(fsp) Timestamp. MySQL stores TIMESTAMP values as the
number of seconds since the Unix epoch ('1970-01-01
00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss.
TIME(fsp) Time. Format: hh:mm:ss.

YEAR Year in four-digit format. MySQL 8.0 does not support a


two-digit year format.

PostGreSQL Data Types (Version 15)


We leave the “Aliases” field blank if a data type has no alias.
Data type Aliases Description

BIGINT INT8 Signed eight-byte integer

BIGSERIAL SERIAL8 Auto-incrementing eight-byte


integer
BIT [ (n) ] Fixed-length bit string

BIT VARYING [ (n) ] VARBIT [ (n) ] Variable-length bit string

BOOLEAN BOOL Logical Boolean (true/false)

BOX Rectangular box on a plane

BYTEA Binary data (“byte array”)

CHARACTER [ (n) ] CHAR [ (n) ] Fixed-length character string

CHARACTER VARYING [ VARCHAR [ (n) ] Variable-length character string


(n) ]

CIDR IPv4 or IPv6 network address

CIRCLE Circle on a plane

DATE Calendar date (year, month, day)

DOUBLE PRECISION FLOAT8 Double precision floating-point


number (eight bytes)
\ INET IPv4 or IPv6 host address

INTEGER INT, INT4 Signed four-byte integer

INTERVAL [ fields ] [ Time span


(p) ]

JSON Textual JSON data

JSONB Binary JSON data, decomposed

LINE Infinite line on a plane

LSEG Line segment on a plane

MACADDR MAC (Media Access Control)


address

MACADDR8 MAC (Media Access Control)


address (EUI-64 format)
MONEY Currency amount

NUMERIC [ (p, s) ] DECIMAL [ (p, Exact numeric of selectable


s) ] precision

PATH Geometric path on a plane


PG_LSN PostgreSQL Log Sequence
Number

PG_SNAPSHOT User-level transaction ID snapshot

POINT Geometric point on a plane

POLYGON Closed geometric path on a plane

REAL FLOAT4 Single precision floating-point


number (four bytes)

SMALLINT INT2 Signed two-byte integer

SMALLSERIAL SERIAL2 Auto-incrementing two-byte integer

SERIAL SERIAL4 Auto-incrementing four-byte integer

TEXT Variable-length character string

TIME [ (p) ] [ without Time of day (no time zone)


time zone ]

TIME [ (p) ] WITH TIME TIMETZ Time of day, including time zone
ZONE
\ TIMESTAMP [ (p) ] [ Date and time (no time zone)
without time zone ]

TIMESTAMP [ (p) ] WITH TIMESTAMPTZ Date and time, including time zone
TIME ZONE
TSQUERY Text search query

TSVECTOR Text search document

UUID Universally unique identifier

XML XML data

SQL Operators
This subsection is a basic SQL operators cheat sheet, where you learn to create complex
Boolean expressions in SQL queries.

Command Syntax Description


AND SELECT column_name(s) Combine two conditions
FROM table_name WHERE
column_1 = value_1
AND column_2 =
value_2;
BETWEEN SELECT column_name(s) Filter the result within a
FROM table_name WHERE certain range
column_name BETWEEN
value_1 AND value_2;
IS NULL SELECT column_name(s) Check for empty values in
FROM table_name WHERE conjunction with the WHERE
column_name IS NULL; clause
IS NOT NULL SELECT column_name(s) Check for the absence of
FROM table_name WHERE empty values in conjunction
column_name IS NOT with the WHERE clause
NULL;
LIKE SELECT column_name(s) Search for a specific pattern
FROM table_name WHERE in a column in conjunction
column_name LIKE with the WHERE clause
pattern;
OR SELECT column_name Filter the result set to
FROM table_name WHERE contain only the rows where
column_name = value_1 either condition is TRUE
OR column_name =
value_2;
UNION SELECT column_name(s) Combine the results of two
FROM table1 UNION or more SELECT statements
SELECT column_name(s) and select only distinct
FROM table2; values
UNION ALL SELECT column_name(s) Combine the results of two
FROM table1 UNION ALL or more SELECT
SELECT column_name(s) statements, allowing
\ FROM table2; duplicate values

SQL Functions
SQL functions help you compute and analyze the contents of database tables.

Here are some common SQL functions:

Command Syntax Description


AVG() SELECT Aggregate a numeric
AVG(column_name) FROM column and return its
table_name; arithmetic mean, ignoring
NULL values
CASE() CASE WHEN condition1 The CASE expression goes
THEN result1 WHEN through conditions and
condition2 THEN returns a value when the
result2 WHEN first condition is met (like an
conditionN THEN if-then-else statement).
resultN ELSE result
END; 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.

Without an ELSE part and


with all conditions FALSE, it
returns NULL.
CAST() SELECT CAST(value AS Convert a value (of any
datatype); type) into the specified
datatype.
CHAR_LENGTH() SELECT (MySQL) Return the length
CHAR_LENGTH(string) of a string in characters
AS LengthOfString;
COALESCE() SELECT COALESCE([list Return the first non-null
of values including value in a list
NULL separated by
commas]);
COUNT() SELECT Take the name of a column
COUNT(column_name) as an argument and count
FROM table_name; the number of rows when
the column is not NULL
FIRST() SELECT Return the first value of the
FIRST(column_name) selected column
FROM table_name;
LAST() SELECT Return the last value of the
LAST(column_name) selected column
FROM table_name;
LCASE() SELECT Convert string values in the
LCASE(column_name) selected column to
\ FROM table_name; lowercase
LEN() SELECT LEN(string); (SQL Server) Return the
length of a string
MAX() SELECT Take at least one column as
MAX(column_name) FROM an argument and return the
table_name; largest value among them
MIN() SELECT Take at least one column as
MIN(column_name) FROM an argument and return the
table_name; smallest value among them
NULLIF() SELECT NULLIF(expr1, Return NULL if two
expr2); expressions expr1,
expr2 are equal.
Otherwise, it returns the first
expression.
ROUND() SELECT Take the column name and
ROUND(column_name, an integer as an argument,
integer) FROM and round the values in a
table_name; column to the number of
decimal places specified by
an integer
SUBSTRING() SELECT Extract some characters
SUBSTRING(string, from a string, where start
start, length) AS is the starting position (one-
ExtractString; indexed) and length is the
number of characters to
extract.

Aliases: MID(),
SUBSTR()
SUM() SELECT Return the sum of values
SUM(column_name) FROM from a particular column
table_name;
UCASE() SELECT Convert string values in the
UCASE(column_name) selected column to
FROM table_name; uppercase
VAR() SELECT Return the statistical
VAR(column_name) FROM variance
table_name;

SQL Clauses
A SQL clause presents the results of a SQL query in a way you specify.

Command Syntax Description


LIMIT SELECT column_name(s) Specify the maximum
FROM table_name LIMIT number of rows the result
number; set must have. Some SQL
implementations have
SELECT TOP playing a
similar role.
\ GROUP BY SELECT column_name, Used for aggregate
COUNT(*) FROM functions in collaboration
table_name GROUP BY with the SELECT statement
column_name;
ORDER BY SELECT column_name Sort the result set by a
FROM table_name ORDER particular column either
BY column_name ASC | numerically or
DESC; alphabetically.

ASC means “in ascending


order;” DESC, “descending.”
WHERE SELECT column_name(s) Filter the result set to
FROM table_name WHERE include the rows where the
column_name operator condition is TRUE
value;

SQL Joins
Combining two tables in SQL is easy:
\
Command Syntax Description
INNER JOIN SELECT column_name(s) Select records that have
FROM table_1 JOIN matching values in both
table_2 ON tables
table_1.column_name =
table_2.column_name;
LEFT JOIN SELECT column_name(s) Combine all records from
FROM table_1 LEFT the left side and any
JOIN table_2 ON matching rows from the right
table_1.column_name = table.
table_2.column_name;
LEFT OUTER JOIN and
LEFT JOIN are the same.
RIGHT JOIN SELECT column_name(s) Combine all rows from the
FROM table_1 RIGHT right side and any matching
JOIN table_2 ON rows from the left table.
table_1.column_name =
table_2.column_name; RIGHT OUTER JOIN and
RIGHT JOIN are the same.
FULL JOIN SELECT column_name(s) Return all records whether
FROM table1 FULL the records in the left
OUTER JOIN table2 ON (table1) and right
table1.column_name = (table2) tables match.
table2.column_name FULL OUTER JOIN and
WHERE condition; FULL JOIN are the same.
CROSS JOIN SELECT * FROM table1 Combine each row of the
CROSS JOIN table2 first table (table1) with
each row of the second
table (table2).

SQL Views
In SQL, a view is a virtual table based on the results of an SQL query. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables
in the database. You can add SQL statements and functions to a view and present the data
as if the data were coming from a single table.

Here are the most important functions for manipulating SQL views:

Command Syntax Description


CREATE VIEW CREATE VIEW view_name Create a view from the SQL
AS SELECT column1, query beginning with
column2, ... FROM SELECT
table_name WHERE
condition;
CREATE OR REPLACE CREATE OR REPLACE Update a view created from
VIEW VIEW view_name AS the SQL query beginning
SELECT column1, with SELECT
\ column2, ... FROM
table_name WHERE
condition;
DROP VIEW DROP VIEW view_name; Delete a view

SQL Indexes
Indexes are for speeding up data retrieval from a database. The users cannot see the
indexes. Updating a table with indexes takes longer than updating a table without (because
the indexes also need an update). So, only create indexes on the columns against which
users frequently search.

Command Syntax Description


CREATE INDEX CREATE INDEX Creates a unique index on a
index_name ON table, allowing duplicate
table_name (column1, values
column2, ...);
CREATE UNIQUE INDEX CREATE UNIQUE INDEX Create a unique index on a
index_name ON table, forbidding duplicate
table_name (column1, values
column2, ...);
DROP INDEX /* MS Access */ Delete an index in a table
DROP INDEX index_name
ON table_name;

/* SQL Server */
DROP INDEX
table_name.index_name
;
/* DB2/Oracle */
DROP INDEX
index_name;

/* MySQL */
ALTER TABLE
table_name DROP INDEX
index_name;

SQL Constraints
Constraints are for specifying rules for data in a table. Use them with the CREATE TABLE
statement for a new table or the ALTER TABLE statement for an existing table.

The syntax is:


[CREATE|ALTER] TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
\ );

The table below lists common constraints in SQL:

Command Description
NOT NULL Ensure that a column cannot have a NULL
value
UNIQUE Ensure that all values in a column are
different
PRIMARY KEY A combination of NOT NULL and UNIQUE:
uniquely identifies each row in a table.
FOREIGN KEY Prevent actions that would destroy links
between tables
CHECK Ensure that the values in a column satisfy a
specific condition
DEFAULT Set a default value for a column that
contains no specified value
AUTO_INCREMENT Allow the automatic generation of a unique
number when inserting a new record into a
table.
SQL Transactions
A transaction is the propagation of one or more changes to the database. For example, you
perform a transaction if you perform create, update, and delete operations on a table.

Below we list the top SQL transactional commands:

Command Syntax Description


COMMIT COMMIT; Save changes invoked by a
transaction to the database
ROLLBACK ROLLBACK; Undo transactions not yet
saved to the database
/* Roll back a given
SAVEPOINT */
ROLLBACK TO
SAVEPOINT_NAME;
SAVEPOINT SAVEPOINT Roll the transaction back to
SAVEPOINT_NAME; a certain point without rolling
back the entire transaction
/* remove a SAVEPOINT
that you have created
*/
RELEASE SAVEPOINT
SAVEPOINT_NAME;
SET TRANSACTION SET TRANSACTION [ Initiate a database
READ WRITE | READ transaction, and specify
ONLY ]; characteristics for the
transaction that follows.
\
For example, you can
specify a transaction to be
READ ONLY or READ
WRITE.

SQL Performance Tuning Tips


As this article is a SQL basics cheat sheet, we present the following SQL performance
optimization tips without elaboration.
✓ Add missing indexes and check for unused indexes
✓ Use SELECT fields instead of SELECT *
✓ Avoid SELECT DISTINCT
✓ Avoid using multiple OR in the FILTER predicate
✓ Create joins with INNER JOIN (not WHERE)
✓ Avoid too many JOINs
✓ Use WHERE instead of HAVING to define filters
✓ Use wildcards at the end of a phrase only
✓ Use TOP and LIMIT to sample query results
✓ Minimize the usage of query hints
✓ Minimize large write operations
✓ Run the query during off-peak hours and analyze wait statistics

Conclusion
This SQL command cheat sheet covers most SQL database tasks. We hope it has helped
you solve your problems at hand. Bookmark the documentation links for your SQL
implementation, such as MySQL or PostgreSQL. Remember to check out our articles on
SQL and our beginner-friendly cyber security courses, which cover SQL injection attacks:

● Complete Python 3 Ethical Hacking Course: Zero To Mastery


○ https://courses.stationx.net/p/complete-python-3-ethical-hacking-course-zero-
to-mastery
● Learn Ethical Hacking From Scratch
○ https://courses.stationx.net/p/learn-ethical-hacking-from-scratch
● Learn Website Hacking / Penetration Testing From Scratch
○ https://courses.stationx.net/p/learn-website-hacking-penetration-testing-from-
scratch

You might also like