SQL Cheat Sheet

SQL Cheat Sheet

Hello, friends!

Learning this cheat sheet will not make you a SQL master, but it will give you a general understanding of this programming language and the capabilities it provides. The capabilities discussed in the cheat sheet are common to all or most SQL dialects.

For a more complete immersion in SQL, I recommend studying these MySQL and PostgreSQL guides from Metanit. They are good because they are easy to learn and allow you to quickly get started with the mentioned DBMSs.

What is SQL?

SQL is a Structured Query Language that allows you to store, manipulate, and retrieve data from relational databases (hereinafter - RDB, DB).

Why SQL?

SQL allows you to:

SQL Process

When any SQL command is executed in any RDBMS (Relational Database Management System - such as PostgreSQL, MySQL, MSSQL, SQLite, etc.), the system determines the best way to execute the query, and the SQL engine determines how to interpret the task.

Several components participate in this process:

The classic engine handles all non-SQL queries, while the SQL query engine does not process logical files.

SQL Commands

The standard commands for interacting with an RDB are CREATE, SELECT, INSERT, UPDATE, DELETE, and DROP. These commands can be classified as follows:

NCommandDescription
1CREATECreates a new table, table view, or other object in the database
2ALTERModifies an existing object in the database, such as a table
3DROPDeletes an existing table, table view, or other object in the database
NCommandDescription
1SELECTRetrieves records from one or more tables
2INSERTCreates records
3UPDATEModifies records
4DELETEDeletes records
NCommandDescription
1GRANTGrants user permissions
2REVOKERevokes user permissions

Note: Using uppercase in SQL command names is just a convention; most DBMSs are case-insensitive. Nevertheless, the practice of writing instructions with command names in uppercase and table names, columns, etc. in lowercase makes it easy to quickly determine the purpose of the operation being performed on the data.

What is a table?

Data in a DBMS is stored in database objects called tables. A table usually consists of a collection of related data and consists of a certain number of columns and rows.

A table is the most common and simple form of storing data in an RDB. Here is an example of a table with users:

userIduserNameagecitystatus
1Igor25Moscowactive
2Vika26Ekaterinburginactive
3Elena27Ekaterinburgactive
4Oleg28Moscowinactive

What is a field?

Each table consists of small parts called fields. The fields in the users table are userId, userName, age, city, and status. A field is a column in the table intended to store specific information about each record in the table.

Note: Instead of userId and userName, you could use id and name, respectively. But when working with multiple objects that have an id property, it can be difficult to understand which object the identifier belongs to, especially if, like me, you often use destructuring. As for the word name, it is often reserved, i.e., already used in the environment where the code is executed, so I try not to use it.

What is a record or row?

A record or row is any single occurrence that exists in a table. The users table has 5 records. In other words, a record is a horizontal entry in a table.

What is a column?

A column is a vertical entry in a table that contains all information related to a specific field. In the users table, one of the columns is city, which contains the names of cities where users live.

What is a NULL value?

A NULL value is a field value that is empty, i.e., a NULL value is a field value that has no value. It is important to understand that a NULL value is different from the value 0 and from a field value containing spaces. A field with a NULL value is a field that remained empty when the record was created. Also note that in some DBMSs an empty string is NULL, while in others they are different values.

Constraints

Constraints are rules applied to data. They are used to restrict the data that can be written to a table. This ensures the accuracy and reliability of data in the database.

Constraints can be set at both the column level and the table level.

Among the most common constraints are:

Any constraint can be removed using the ALTER TABLE command and DROP CONSTRAINT + constraint name. Some implementations provide shortcuts for removing constraints and the ability to disable constraints instead of removing them.

Data Integrity

Each DBMS has the following categories of data integrity:

Database Normalization

Normalization is the process of efficiently organizing data in a database. There are two main reasons for the need for normalization:

Normalization involves following several forms. A form is a database structuring format. There are three main forms: first, second, and third. I will not go into detail about these forms; if you wish, you can easily find the necessary information.

SQL Syntax

Syntax is a unique set of rules and recommendations. All SQL statements must begin with a keyword such as SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW, etc., and end with a semicolon (;) (the semicolon is not part of SQL syntax, but console DBMS clients usually require it to mark the end of command input). SQL is case-insensitive, i.e., SELECT, select, and SeLeCt are identical statements. An exception to this rule is MySQL, where the case of table names is taken into account.

Syntax examples

SQL
-- selection
SELECT col1, col2, ...colN FROM tableName;
SELECT DISTINCT col1, col2, ...colN FROM tableName;
SELECT col1, col2, ...colN FROM tableName WHERE condition;
SELECT col1, col2, ...colN FROM tableName WHERE condition1 AND|OR condition2;
SELECT col2, col2, ...colN FROM tableName WHERE colName IN (val1, val2, ...valN);
SELECT col1, col2, ...colN FROM tableName WHERE colName BETWEEN val1 AND val2;
SELECT col1, col2, ...colN FROM tableName WHERE colName LIKE pattern;
SELECT col1, col2, ...colN FROM tableName WHERE condition ORDER BY colName [ASC|DESC];
SELECT SUM(colName) FROM tableName WHERE condition GROUP BY colName;
SELECT COUNT(colName) FROM tableName WHERE condition;
SELECT SUM(colName) FROM tableName WHERE condition GROUP BY colName HAVING (function condition);

-- creating a table
CREATE TABLE tableName (
  col1 datatype,
  col2 datatype,
  ...
  colN datatype,
  PRIMARY KEY (one or more columns)
);

-- deleting a table
DROP TABLE tableName;

-- creating an index
CREATE UNIQUE INDEX indexName ON tableName (col1, col2, ...colN);

-- deleting an index
ALTER TABLE tableName DROP INDEX indexName;

-- getting table structure description
DESC tableName;

-- clearing a table
TRUNCATE TABLE tableName;

-- adding/deleting/modifying columns
ALTER TABLE tableName ADD|DROP|MODIFY colName [datatype];

-- renaming a table
ALTER TABLE tableName RENAME TO newTableName;

-- inserting values
INSERT INTO tableName (col1, col2, ...colN) VALUES (val1, val2, ...valN)

-- updating records
UPDATE tableName SET col1 = val1, col2 = val2, ...colN = valN [WHERE condition];

-- deleting records
DELETE FROM tableName WHERE condition;

-- creating a database
CREATE DATABASE [IF NOT EXISTS] dbName;

-- deleting a database
DROP DATABASE [IF EXISTS] dbName;

-- selecting a database
USE dbName;

-- completing a transaction
COMMIT;

-- canceling changes
ROLLBACK;
Click to expand and view more

Data Types

Each column, variable, and expression in SQL has a specific data type. The main categories of data types:

Exact numeric

Data typeFromTo
bigint-9,223,372,036,854,775,8089,223,372,036,854,775,807
int-2,147,483,6482,147,483,647
smallint-32,76832,767
tinyint0255
bit01
decimal-10^38 +110^38 -1
numeric-10^38 +110^38 -1
money-922,337,203,685,477.5808+922,337,203,685,477.5807
smallmoney-214,748.3648+214,748.3647

Approximate numeric

Data typeFromTo
float-1.79E + 3081.79E + 308
real-3.40E + 383.40E + 38

Date and time

Data typeFromTo
datetimeJan 1, 1753Dec 31, 9999
smalldatetimeJan 1, 1900Jun 6, 2079
dateDate is stored as June 30, 1991
timeTime is stored as 12:30 P.M.

Character strings

NData typeDescription
1charString up to 8,000 characters (non-Unicode characters, fixed length)
2varcharString up to 8,000 characters (non-Unicode characters, variable length)
3textNon-Unicode data of variable length, up to 2,147,483,647 characters

Character strings (Unicode)

NData typeDescription
1ncharString up to 4,000 characters (Unicode characters, fixed length)
2nvarcharString up to 4,000 characters (Unicode characters, variable length)
3ntextUnicode data of variable length, up to 1,073,741,823 characters

Binary

NData typeDescription
1binaryData up to 8,000 bytes (fixed length)
2varbinaryData up to 8,000 bytes (variable length)
3imageData up to 2,147,483,647 bytes (variable length)

Mixed

NData typeDescription
1timestampUnique numbers updated on each row change
2uniqueidentifierGlobally unique identifier (GUID)
3cursorCursor object
4tableIntermediate result for further processing

Operators

An operator is a keyword or symbol that is mainly used in WHERE statements to perform operations. They are used both to define conditions and to combine multiple conditions in a statement.

In the following examples, we will assume that the variable a has a value of 10, and b - 20.

Arithmetic

OperatorDescriptionExample
+ (addition)Adding valuesa + b = 30
- (subtraction)Subtracting the right operand from the leftb - a = 10
* (multiplication)Multiplying valuesa * b = 200
/ (division)Dividing the left operand by the rightb / a = 2
% (modulo/division with remainder)Dividing the left operand by the right with remainder (returns the remainder)b % a = 0

Comparison operators

OperatorDescriptionExample
=Determines equality of valuesa = b -> false
!=Determines inequality of valuesa != b -> true
<>Determines inequality of valuesa <> b -> true
>Is the value of the left operand greater than the value of the right operand?a > b -> false
<Is the value of the left operand less than the value of the right operand?a < b -> true
>=Is the value of the left operand greater than or equal to the value of the right operand?a >= b -> false
<=Is the value of the left operand less than or equal to the value of the right operand?a <= b -> true
!<Is the value of the left operand NOT less than the value of the right operand?a !< b -> false
!>Is the value of the left operand NOT greater than the value of the right operand?a !> b -> true

Logical operators

NOperatorDescription
1ALLCompares all values
2ANDCombines conditions (all conditions must match)
3ANYCompares one value with another if the latter matches the condition
4BETWEENChecks if a value falls in a range from minimum to maximum
5EXISTSDetermines the existence of a row matching a certain criterion
6INSearches for a value in a list of values
7LIKECompares a value with similar using wildcard operators
8NOTInverts (reverses) the meaning of other logical operators, for example, NOT EXISTS, NOT IN, etc.
9ORCombines conditions (one of the conditions must match)
10IS NULLDetermines if a value is NULL
11UNIQUEDetermines the uniqueness of a row

Expressions

An expression is a combination of values, operators, and functions for evaluating (calculating) a value. Expressions are similar to formulas written in a query language. They can be used to retrieve a specific set of data from the database.

The basic syntax of an expression looks like this:

SQL
SELECT col1, col2, ...colN
FROM tableName
WHERE [condition|expression];
Click to expand and view more

There are different types of expressions: logical, numeric, and date expressions.

Logical

Logical expressions retrieve data based on matching a single value.

SQL
SELECT col1, col2, ...colN
FROM tableName
WHERE expression for finding a match with a single value;
Click to expand and view more

Suppose the users table has the following records:

userIduserNameagecitystatus
1Igor25Moscowactive
2Vika26Ekaterinburginactive
3Elena27Ekaterinburgactive
4Oleg28Moscowinactive

Let’s search for active users:

SQL
SELECT * FROM users WHERE status = active;
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor25Moscowactive
3Elena27Ekaterinburgactive

Numeric

Used to perform arithmetic operations in a query.

SQL
SELECT numericalExpression as operationName[FROM tableNameWHERE condition];
Click to expand and view more

A simple example of using a numeric expression:

PLAINTEXT
SELECT (10 + 5) AS addition;
Click to expand and view more

Result:

addition
15

There are several built-in functions such as count(), sum(), avg(), min(), max(), etc. for performing so-called aggregate calculations of table data or a column.

SQL
SELECT COUNT(*) AS records FROM users;
Click to expand and view more

Result:

records
4

There are also several built-in functions for working with strings:

Functions for working with numbers:

Date expressions

These expressions usually return the current date and time.

SQL
SELECT CURRENT_TIMESTAMP;
Click to expand and view more

Result:

Current\_Timestamp
2021-06-20 12:45:00

CURRENT_TIMESTAMP is both an expression and a function (CURRENT_TIMESTAMP()). Another function for getting the current date and time is NOW().

Other functions for getting the current date and time:

Functions for parsing date and time:

Functions for manipulating dates:

The functions DATE_FORMAT(date, format) and TIME_FORMAT(date, format) are used for formatting date and time, respectively.

Creating a Database

To create a database, use the CREATE DATABASE statement.

SQL
CREATE DATABASE dbName;

-- or

CREATE DATABASE IF NOT EXISTS dbName;
Click to expand and view more

The IF NOT EXISTS condition helps avoid getting an error when attempting to create a database that already exists.

The database name must be unique within the DBMS.

Let’s create the testDB database:

SQL
CREATE DATABASE testDB;
Click to expand and view more

Get a list of databases:

SQL
SHOW DATABASES;
Click to expand and view more

Result:

Database
information\_schema
postgres
testDB

Deleting a Database

To delete a database, use the DROP DATABASE statement.

SQL
DROP DATABASE dbName;

-- or

DROP DATABASE IF EXISTS dbName;
Click to expand and view more

The IF EXISTS condition helps avoid getting an error when attempting to delete a non-existent database.

Delete the testDB database:

SQL
DROP DATABASE testDB;
Click to expand and view more

Note: When you delete a database, all data stored in it is destroyed, so be very careful when using this command.

Check that the database is deleted:

SQL
SHOW DATABASES;
Click to expand and view more

To get a list of tables, use the SHOW TABLES statement.

Result:

Database
information\_schema
postgres

Selecting a Database

If there are multiple databases, before performing any operations, you need to select a database. To do this, use the USE statement.

SQL
USE dbName;
Click to expand and view more

Suppose we did not delete testDB. Then we can select it like this:

SQL
USE testDB;
Click to expand and view more

Creating a Table

Creating a table involves specifying the table name and defining the table columns and their data types. To create a table, use the CREATE TABLE statement.

SQL
CREATE TABLE tableName (
  col1 datatype,
  col2 datatype,
  ...
  colN datatype,
  PRIMARY KEY (one or more columns)
);
Click to expand and view more

To create a table by copying another table, use the combination of CREATE TABLE and SELECT.

An example of creating a users table where the primary key is user identifiers, and the fields for the user’s name and age cannot be NULL:

SQL
CREATE TABLE users (
  userId INT,
  userName VARCHAR(20) NOT NULL,
  age INT NOT NULL,
  city VARCHAR(20),
  status VARCHAR(8),
  PRIMARY KEY (id)
);
Click to expand and view more

Check that the table was created:

SQL
DESC users;
Click to expand and view more

Result:

FieldTypeNullKeyDefaultExtra
userIdint(11)NOPRI
userNamevarchar(20)NO
ageint(11)NO
cityvarchar(20)NO
statusvarchar(8)YESNULL

Deleting a Table

To delete a table, use the DROP TABLE statement.

Note: When you delete a table, all data stored in it, indexes, triggers, constraints, and permissions are permanently deleted, so be very careful when using this command.

Delete the users table:

SQL
DROP TABLE users;
Click to expand and view more

Now, if we try to get a description of users, we will get an error:

SQL
DESC users;
-- ERROR 1146 (42S02): Table 'testDB.users' doesn't exist
Click to expand and view more

Adding Columns

To add columns to a table, use the INSERT INTO statement.

SQL
INSERT INTO tableName (col1, col2, ...colN)
VALUES (val1, val2, ...valN);
Click to expand and view more

Column names can be omitted, but in this case, values must be listed in the correct order.

SQL
INSERT INTO tableName VALUES (val1, val2, ...valN);
Click to expand and view more

To avoid errors, it is recommended to always list the column names.

Suppose we did not delete the users table. Let’s fill it with users:

SQL
INSERT INTO users (userId, userName, age, city, status)
VALUES (1, 'Igor', 25, 'Moscow', 'active');

INSERT INTO users (userId, userName, age, city, status)
VALUES (2, 'Vika', 26, 'Ekaterinburg', 'inactive');

INSERT INTO users (userId, userName, age, city, status)
VALUES (3, 'Elena', 27, 'Ekaterinburg', 'active');
Click to expand and view more

You can add multiple rows at once to a table.

SQL
INSERT INTO users (userId, userName, age, city, status)
VALUES
  (1, 'Igor', 25, 'Moscow', 'active'),
  (2, 'Vika', 26, 'Ekaterinburg', 'inactive'),
  (3, 'Elena', 27, 'Ekaterinburg', 'active');
Click to expand and view more

Also, as noted, when adding a row, field names can be omitted:

SQL
INSERT INTO users
VALUES (4, 'Oleg', 28, 'Moscow', 'inactive');
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor25Moscowactive
2Vika26Ekaterinburginactive
3Elena27Ekaterinburgactive
4Oleg28Moscowinactive

Filling a table using another table

SQL
INSERT INTO tableName [(col1, col2, ...colN)]
SELECT col1, col2, ...colN
FROM anotherTable
[WHERE condition];
Click to expand and view more

Selecting Fields

To select fields from a table, use the SELECT statement. It returns data as a result table (result set).

PLAINTEXT
SELECT col1, col2, ...colNFROM tableName;
Click to expand and view more

To select all fields, use this syntax:

SQL
SELECT * FROM tableName;
Click to expand and view more

Let’s select the fields userId, userName, and age from the users table:

SQL
SELECT userId, userName, age FROM users;
Click to expand and view more

Result:

userIduserNameage
1Igor25
2Vika26
3Elena27
4Oleg28

The WHERE Clause

The WHERE clause is used to filter returned data. It is used together with SELECT, UPDATE, DELETE, and other statements.

SQL
SELECT col1, col2, ...col2
FROM tableName
WHERE condition;
Click to expand and view more

The condition that returned records must satisfy is defined using comparison operators or logical operators such as >, <, =, NOT, LIKE, etc.

Let’s select the fields userId, userName, and age of active users:

SQL
SELECT userId, userName, age
FROM users
WHERE status = 'active';
Click to expand and view more

Result:

userIduserNameage
1Igor25
3Elena27

Let’s select the fields userId, age, and city of a user named Vika.

SQL
SELECT userId, age, city
FROM users
WHERE userName = 'Vika';
Click to expand and view more

Result:

userIdagecity
226Ekaterinburg

Note: Strings in the WHERE clause must be enclosed in single quotes ('), while numbers are specified as they are.

The AND and OR Operators

The conjunctive operator AND and the disjunctive operator OR are used to join multiple conditions when filtering data.

AND

SQL
SELECT col1, col2, ...colN
FROM tableName
WHERE condition1 AND condition2 ... AND conditionN;
Click to expand and view more

Returned records must satisfy all specified conditions.

Let’s select the fields userId, userName, and age of active users over 26 years old:

SQL
SELECT userId, userName, age
FROM users
WHERE status = active AND age > 26;
Click to expand and view more

Result:

userIduserNameage
3Elena27

OR

SQL
SELECT col1, col2, ...colN
FROM tableName
WHERE condition1 OR condition2 ... OR conditionN;
Click to expand and view more

Returned records must satisfy at least one condition.

Let’s select the same fields of inactive users or users under 27 years old:

SQL
SELECT userId, userName, age
FROM users
WHERE status = inactive OR age < 27;
Click to expand and view more

Result:

userIduserNameage
1Igor25
2Vika26

Updating Fields

To update fields, use the UPDATE ... SET statement. This statement is usually used in conjunction with the WHERE clause.

SQL
UPDATE tableName
SET col1 = val1, col2 = val2, ...colN = valN
[WHERE condition];
Click to expand and view more

Let’s update the age of a user named Igor:

SQL
UPDATE users
SET age = 30
WHERE username = 'Igor';
Click to expand and view more

If we omit the WHERE clause in this case, the age of all users will be updated.

Deleting Records

To delete records, use the DELETE statement. This statement is also usually used in conjunction with the WHERE clause.

SQL
DELETE FROM tableName
[WHERE condition];
Click to expand and view more

Delete inactive users:

SQL
DELETE FROM users
WHERE status = 'inactive';
Click to expand and view more

If we omit the WHERE clause in this case, all records will be deleted from the users table.

The LIKE and REGEX Clauses

LIKE

The LIKE clause is used to compare values using wildcard operators. There are two types of such operators:

% means 0, 1, or more characters. _ means exactly 1 character.

SQL
SELECT col1, col2, ...colN FROM tableName
WHERE col LIKE 'xxx%'
-- or
WHERE col LIKE '%xxx%'
-- or
WHERE col LIKE '%xxx'
-- or
WHERE col LIKE 'xxx_'
-- and so on.
Click to expand and view more

Examples:

NStatementResult
1WHERE col LIKE 'foo%'Any values starting with foo
2WHERE col LIKE '%foo%'Any values containing foo
3WHERE col LIKE '_oo%'Any values containing oo in the second and third positions
4WHERE col LIKE 'f_%_%'Any values starting with f and consisting of at least 1 character
5WHERE col LIKE '%oo'Any values ending with oo
6WHERE col LIKE '_o%o'Any values containing o in the second position and ending with o
7WHERE col LIKE 'f_o'Any values containing f and o in the first and third positions, respectively, and consisting of three characters

Let’s select inactive users:

SQL
SELECT * FROM users
WHERE status LIKE 'in%';
Click to expand and view more

Result:

userIduserNameagecitystatus
2Vika26Ekaterinburginactive
4Oleg28Moscowinactive

Let’s select users 30 years old and older:

SQL
SELECT * FROM users
WHERE age LIKE '3_';
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor30Moscowactive

REGEX

The REGEX clause allows you to define a regular expression that a record must match.

SQL
SELECT col1, col2, ...colN FROM tableName
WHERE colName REGEXP regular expression;
Click to expand and view more

The following special characters can be used in a regular expression:

Let’s select users named Igor and Vika:

SQL
SELECT * FROM users
WHERE userName REGEXP 'Igor|Vika';
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor30Moscowactive
2Vika26Ekaterinburginactive

The TOP/LIMIT/ROWNUM Clause

These clauses allow you to extract a specified number or percentage of records from the beginning of a table. Different DBMSs support different clauses.

SQL
SELECT TOP number|percent col1, col2, ...colN
FROM tableName
[WHERE condition];
Click to expand and view more

Let’s select the first three users:

SQL
SELECT TOP 3 * FROM users;
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor30Moscowactive
2Vika26Ekaterinburginactive
3Elena27Ekaterinburgactive

In mysql:

SQL
SELECT * FROM users
LIMIT 3, [offset];
Click to expand and view more

The offset parameter determines the number of records to skip. For example, you can extract the first two users starting from the third:

SQL
SELECT * FROM users
LIMIT 2, 2;
Click to expand and view more

In oracle:

SQL
SELECT * FROM users
WHERE ROWNUM <= 3;
Click to expand and view more

The ORDER BY and GROUP BY Clauses

ORDER BY

The ORDER BY clause is used to sort data in ascending (ASC) or descending (DESC) order. Most DBMSs sort in ascending order by default.

SQL
SELECT col1, col2, ...colN
FROM tableName
[WHERE condition]
[ORDER BY col1, col2, ...colN] [ASC | DESC];
Click to expand and view more

Note: The columns to sort by must be specified in the list of columns for selection.

Let’s select users sorted by city and age:

SQL
SELECT * FROM users
ORDER BY city, age;
Click to expand and view more

Result:

userIduserNameagecitystatus
2Vika26Ekaterinburginactive
3Elena27Ekaterinburgactive
1Igor25Moscowactive
4Oleg28Moscowinactive

Now let’s perform sorting in descending order:

SQL
SELECT * FROM users
ORDER BY city, age DESC;
Click to expand and view more

Let’s define our own sort order in descending order:

SQL
SELECT * FROM users
ORDER BY (CASE
  WHEN city = 'Ekaterinburg' THEN 1
  WHEN city = 'Moscow' THEN 2
  ELSE 100
END) ASC, city DESC;
Click to expand and view more

GROUP BY

The GROUP BY clause is used together with the SELECT statement to group records. It is specified after WHERE and before ORDER BY.

SQL
SELECT col1, col2, ...colN
FROM tableName
WHERE condition
GROUP BY col1, col2, ...colN
ORDER BY col1, col2, ...colN;
Click to expand and view more

Let’s group active users by city:

SQL
SELECT city, COUNT(city) AS amount FROM users
WHERE status = active
GROUP BY city
ORDER BY city;
Click to expand and view more

Result:

cityamount
Ekaterinburg2
Moscow2

The DISTINCT Keyword

The DISTINCT keyword is used together with the SELECT statement to return only unique records (without duplicates).

SQL
SELECT DISTINCT col1, col2, ...colN
FROM tableName
[WHERE condition];
Click to expand and view more

Let’s select the cities where users live:

SQL
SELECT DISTINCT city
FROM users;
Click to expand and view more

Result:

city
Ekaterinburg
Moscow

Joins

Joins are used to combine records from two or more tables.

Suppose we have a table orders with user orders in addition to users:

orderIddateuserIdamount
1012021-06-21 00:00:0023000
1022021-06-20 00:00:0021500
1032021-06-19 00:00:0032000
1042021-06-18 00:00:0031000

Let’s select the fields userId, userName, age, and amount from our tables by joining them:

SQL
SELECT userId, userName, age, amount
FROM users, orders
WHERE users.userId = orders.userId;
Click to expand and view more

Result:

userIduserNameageamount
2Vika263000
2Vika261500
3Elena272000
3Elena271000

When joining tables, operators such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT can be used, but = is the most common.

There are different types of joins:

The UNION Clause

The UNION clause is used to combine the results of two or more SELECT statements. Only unique records are returned.

With UNION, each SELECT statement must have:

However, they can be of different lengths.

SQL
SELECT col1, col2, ...colN
FROM table1
[WHERE condition]
UNION
SELECT col1, col2, ...colN
FROM table2
[WHERE condition];
Click to expand and view more

Let’s combine our users and orders tables:

SQL
SELECT userId, userName, amount, date
FROM users
LEFT JOIN orders
ON users.useId = orders.userId
UNION
SELECT userId, userName, amount, date
FROM users
RIGHT JOIN orders
ON users.userId = orders.userId;
Click to expand and view more

Result:

userIduserNameamountdate
1IgorNULLNULL
2Vika30002021-06-21 00:00:00
2Vika15002021-06-20 00:00:00
3Elena20002021-06-19 00:00:00
3Elena10002021-06-18 00:00:00
4AlexNULLNULL

The UNION ALL Clause

The UNION ALL clause is also used to combine the results of two or more SELECT statements. All records are returned, including duplicates.

SQL
SELECT col1, col2, ...colN
FROM table1
[WHERE condition]
UNION ALL
SELECT col1, col2, ...colN
FROM table2
[WHERE condition];
Click to expand and view more

There are two more clauses similar to UNION:

Aliases

Aliases allow you to temporarily change the names of tables and columns. “Temporarily” means that the new name is used only in the current query, and the name in the database remains the same.

Syntax for table alias:

SQL
SELECT col1, col2, ...colN
FROM tableName AS aliasName
[WHERE condition];
Click to expand and view more

Syntax for column alias:

SQL
SELECT colName AS aliasName
FROM tableName
[WHERE condition];
Click to expand and view more

Example of using table aliases:

SQL
SELECT U.userId, U.userName, U.age, O.amount
FROM users AS U, orders AS O
WHERE U.userId = O.userId;
Click to expand and view more

Result:

userIduserNameageamount
2Vika263000
2Vika261500
3Elena272000
3Elena271000

Example of using column aliases:

SQL
SELECT userId AS user_id, userName AS user_name, age AS user_age
FROM users
WHERE status = active;
Click to expand and view more

Result:

user\_iduser\_nameuser\_age
1Igor30
3Elena27

Indexes

Creating indexes

Indexes are special lookup tables used by the database engine to retrieve data more quickly. In other words, an index is a pointer or reference to data in a table.

Indexes speed up the SELECT statement and the WHERE clause, but slow down UPDATE and INSERT statements. Indexes can be created and deleted without affecting the data.

To create an index, use the CREATE INDEX statement, which allows you to define the index name, indexed columns, and the order of indexing (ascending or descending).

The UNIQUE constraint can be applied to indexes to ensure their uniqueness.

Syntax for creating an index:

SQL
CREATE INDEX indexName ON tableName;
Click to expand and view more

Syntax for creating an index for one column:

SQL
CREATE INDEX indexName ON tableName (colName);
Click to expand and view more

Syntax for creating unique indexes (such indexes are used not only to improve performance but also to ensure data consistency):

SQL
CREATE UNIQUE INDEX indexName ON tableName (colName);
Click to expand and view more

Syntax for creating indexes for multiple columns (composite index):

SQL
CREATE INDEX indexName ON tableName (col1, col2, ...colN);
Click to expand and view more

The decision to create indexes for one or more columns should be based on which columns will often be used in the WHERE query as a condition for sorting rows.

Implicit indexes are automatically created for PRIMARY KEY and UNIQUE constraints.

Deleting indexes

To delete indexes, use the DROP INDEX statement:

SQL
DROP INDEX indexName;
Click to expand and view more

Although indexes are designed to improve database performance, there are situations where their use is best avoided.

Such situations include:

Updating a Table

The ALTER TABLE command is used to add, delete, and modify columns in an existing table. This command is also used to add and delete constraints.

Syntax:

SQL
-- adding a new column
ALTER TABLE tableName ADD colName datatype;

-- deleting a column
ALTER TABLE tableName DROP COLUMN colName;

-- changing the data type of a column
ALTER TABLE tableName MODIFY COLUMN colName newDatatype;

-- adding a `NOT NULL` constraint
ALTER TABLE tableName MODIFY colName datatype NOT NULL;

-- adding a `UNIQUE` constraint
ALTER TABLE tableName
ADD CONSTRAINT myUniqueConstraint UNIQUE (col1, col2, ...colN);

-- adding a `CHECK` constraint
ALTER TABLE tableName
ADD CONSTRAINT myUniqueConstraint CHECK (condition);

-- adding a primary key
ALTER TABLE tableName
ADD CONSTRAINT myPrimaryKey PRIMARY KEY (col1, col2, ...colN);

-- deleting a constraint
ALTER TABLE tableName
DROP CONSTRAINT myUniqueContsraint;

-- mysql
ALTER TABLE tableName
DROP INDEX myUniqueContsraint;

-- deleting a primary key
ALTER TABLE tableName
DROP CONSTRAINT myPrimaryKey;

-- mysql
ALTER TABLE tableName
DROP PRIMARY KEY;
Click to expand and view more

Let’s add a new column to the users table - the user’s gender:

SQL
ALTER TABLE users ADD sex char(1);
Click to expand and view more

Delete this column:

SQL
ALTER TABLE users DROP sex;
Click to expand and view more

Clearing a Table

The TRUNCATE TABLE command is used to clear a table. Its difference from DROP TABLE is that the table structure is preserved (DROP TABLE completely removes the table and all its data).

SQL
TRUNCATE TABLE tableName;
Click to expand and view more

Let’s clear the users table:

SQL
TRUNCATE TABLE users;
Click to expand and view more

Check that users is empty:

SQL
SELECT * FROM users;
-- Empty set (0.00 sec)
Click to expand and view more

Views

A view is nothing more than a statement stored in a database under a specific name. In other words, a view is a composition of a table in the form of a pre-defined query.

Views can contain all or only some rows of a table. A view can be created based on one or more tables (depending on the query to create the view).

Views are virtual tables that allow you to:

Creating a view

To create a view, use the CREATE VIEW statement. As noted, views can be created based on one or more tables, and even based on another view.

SQL
CREATE VIEW viewName AS
SELECT col1, col2, ...colN
FROM tableName
[WHERE condition];
Click to expand and view more

Let’s create a view for user names and ages:

SQL
CREATE VIEW usersView AS
SELECT userName, age
FROM users;
Click to expand and view more

Get data using the view:

SQL
SELECT * FROM usersView;
Click to expand and view more

Result:

userNameage
Igor30
Vika26
Elena27
Oleg28

WITH CHECK OPTION

WITH CHECK OPTION is a setting for the CREATE VIEW statement. It ensures that all UPDATE and INSERT operations comply with the condition defined in the view.

If the condition is not satisfied, an exception is raised.

SQL
CREATE VIEW usersView AS
SELECT userName, age
FROM users
WHERE age IS NOT NULL
WITH CHECK OPTION;
Click to expand and view more

Updating a view

A view can be updated if the following conditions are met:

Example of updating the age of a user named Igor in a view:

SQL
UPDATE usersView
SET age = 31
WHERE userName = 'Igor';
Click to expand and view more

Note: Updating a row in a view results in it being updated in the base table.

New rows can be added to a view using the INSERT command. When executing this command, the same rules apply as when executing the UPDATE command.

Rows can be deleted from a view using the DELETE command.

Delete from the view a user whose age is 26:

SQL
DELETE FROM usersView
WHERE age = 26;
Click to expand and view more

Note: Deleting a row from a view results in it being deleted from the base table.

Deleting a view

To delete a view, use the DROP VIEW statement:

SQL
DROP VIEW viewName;
Click to expand and view more

Delete the usersView view:

SQL
DROP VIEW usersView;
Click to expand and view more

HAVING

The HAVING clause is used to filter grouping results. WHERE is used to apply conditions to columns, and HAVING - to groups created with GROUP BY.

HAVING must be specified after GROUP BY but before ORDER BY (if present).

SQL
SELECT col1, col2, ...colN
FROM table1, table2, ...tableN
[WHERE condition]
GROUP BY col1, col2, ...colN
HAVING condition
ORDER BY col1, col2, ...colN;
Click to expand and view more

Transactions

A transaction is a unit of work or operation performed on a database. It is a sequence of operations performed in logical order. These operations can be initiated either by a user or by a program running in the database.

A transaction is the application of one or more changes to a database. For example, when we create/update/delete a record, we perform a transaction. It is important to control the execution of such operations to ensure data consistency and handle possible errors.

In practice, queries are usually not sent to the database one by one; they are grouped and executed as part of a transaction.

Transaction properties

Transactions have 4 standard properties (ACID):

Transaction management

The following commands are used to manage transactions:

Transaction management commands can only be used together with queries such as INSERT, UPDATE, and DELETE. They cannot be used during table creation and deletion, as these operations are automatically sent to the database.

Delete a user whose age is 26 and send the changes to the database:

SQL
BEGIN TRANSACTION
DELETE FROM users
WHERE age = 26;
COMMIT;
Click to expand and view more

Delete a user named Oleg and cancel this operation:

SQL
BEGIN
DELETE FROM users
WHERE username = 'Oleg';
ROLLBACK;
Click to expand and view more

Checkpoints are created using this syntax:

SQL
SAVEPOINT savepointName;
Click to expand and view more

Return to a checkpoint like this:

SQL
ROLLBACK TO savepointName;
Click to expand and view more

Let’s execute three delete queries on users, creating checkpoints before each deletion:

SQL
START TRANSACTION
SAVEPOINT sp1;
DELETE FROM users
WHERE age = 26;
SAVEPOINT sp2;
DELETE FROM users
WHERE userName = 'Oleg';
SAVEPOINT sp3;
DELETE FROM users
WHERE status = 'inactive';
Click to expand and view more

Let’s undo the last two deletions by returning to checkpoint sp2 created after the first deletion:

SQL
ROLLBACK TO sp2;
Click to expand and view more

Let’s select users:

SQL
SELECT * FROM users;
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor31Moscowactive
3Elena27Ekaterinburgactive
4Oleg28Moscowinactive

As we can see, only the user aged 26 was deleted from the table.

To delete a checkpoint, use the RELEASE SAVEPOINT command. Naturally, after deleting a checkpoint, you cannot return to it using ROLLBACK TO.

The SET TRANSACTION command is used to initialize a transaction, i.e., to start its execution. In this case, you can define certain characteristics of the transaction. For example, you can define the transaction access level (read-only or for writing too):

SQL
SET TRANSACTION [READ WRITE | READ ONLY];
Click to expand and view more

Temporary Tables

Some DBMSs support so-called temporary tables. Such tables allow you to store and process intermediate results using the same queries as when working with regular tables.

Temporary tables can be very useful when you need to store temporary data. One of the main features of such tables is that they are deleted when the current session ends. When running a script, the temporary table is deleted after the script finishes executing. When accessing the database using a client program, the table will be deleted after the program is closed.

A temporary table is created using the CREATE TEMPORARY TABLE statement; otherwise, the syntax for creating such tables is identical to the syntax for creating regular tables.

A temporary table is deleted in the same way as a regular table, using the DROP TABLE statement.

Cloning a Table

There may be a situation where you need to get an exact copy of an existing table, and CREATE TABLE or SELECT may not be sufficient because you want to get not only an identical structure, but also indexes, default values, etc. of the copied table.

In mysql, for example, you can do this like this:

Subqueries

A subquery is an inner (nested) query of another query embedded using WHERE or other statements.

A subquery is used to get data that will be used by the main query as a condition for filtering returned records.

Subqueries can be used in SELECT, INSERT, UPDATE, and DELETE statements, as well as with operators such as =, <, >, >=, <=, IN, BETWEEN, etc.

Rules for using subqueries:

Subqueries are usually used in a SELECT statement.

SQL
SELECT col1, col2, ...colN
FROM table1, table2, ...tableN
WHERE colName operator (
  SELECT col1, col2, ...colN
  FROM table1, table2, tableN
  [WHERE condition]
);
Click to expand and view more

Example:

SQL
SELECT * FROM users
WHERE userId IN (
  SELECT userId FROM users
  WHERE status = 'active'
);
Click to expand and view more

Result:

userIduserNameagecitystatus
1Igor30Moscowactive
3Elena27Ekaterinburgactive

Subqueries can be used in an INSERT statement. This statement adds data returned by the subquery to the table. In this case, the data returned by the subquery can be modified in any way.

SQL
INSERT INTO tableName (col1, col2, ...colN)
SELECT col1, col2, ...colN
FROM table1, table2, ...tableN
[WHERE operator [value]];
Click to expand and view more

Subqueries can be used in an UPDATE statement. In this case, data from the subquery can be used to update any number of columns.

SQL
UPDATE tableName
SET col = newVal
[WHERE operator [value] (
  SELECT colName
  FROM tableName
  [WHERE condition]
)];
Click to expand and view more

Data returned by a subquery can also be used to delete records.

SQL
DELETE FROM tableName
[WHERE operator [value] (
  SELECT colName
  FROM tableName
  [WHERE condition]
)];
Click to expand and view more

Sequences

A sequence is a set of integers (1, 2, 3, etc.) generated automatically. Sequences are often used in databases because many applications need unique values used to identify rows.

The examples below are designed for mysql.

The simplest way to define a sequence is to use AUTO_INCREMENT when creating a table:

SQL
CREATE TABLE tableName (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (id),
  -- other rows
);
Click to expand and view more

To renumber rows using automatically generated values (for example, when deleting a large number of rows), you can delete the column containing these values and create it again. Note: such a table should not be part of a join.

SQL
ALTER TABLE tableName DROP id;

ALTER TABLE tableName
ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (id);
Click to expand and view more

By default, values generated using AUTO_INCREMENT start from 1. To set a different starting value, simply specify, for example, AUTO_INCREMENT = 100 - in this case, the numbering of rows will start from 100.

Copyright Notice

Author: Ivan Cherniy

Link: https://r4ven.me/en/clippings/pamyatka-shpargalka-po-sql/

License: CC BY-NC-SA 4.0

Blog materials may be used with attribution to the author and source, for non-commercial purposes, and under the same license.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut