MySQL Tutorial
MySQL is a widely used relational database management system (RDBMS).
MySQL is free and open-source.
MySQL is ideal for both small and large applications.
Introduction to MySQL
MySQL is a very popular open-source relational database management system
(RDBMS).
What is MySQL?
MySQL is a relational database management system
MySQL is open-source
MySQL is free
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, scalable, and easy to use
MySQL is cross-platform
MySQL is compliant with the ANSI SQL standard
MySQL was first released in 1995
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: MY and SQL
Who Uses MySQL?
Huge websites like Facebook, Twitter, Airbnb, Booking.com, Uber, GitHub,
YouTube, etc.
Content Management Systems like WordPress, Drupal, Joomla! Contao, etc.
A very large number of web developers around the world.
What is RDBMS?
RDBMS stands for Relational Database Management System.
RDBMS is a program used to maintain a relational database.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL
Server, Oracle, and Microsoft Access.
RDBMS uses SQL queries to access the data in the database.
What is a Database Table?
A table is a collection of related data entries, and it consists of columns and rows.
A column holds specific information about every record in the table.
A record (or row) is each individual entry that exists in a table.
Look at a selection from the Northwind "Customers" table:
Customer Postal
Customer Name Contact Name Address City Country
ID Code
1 Alfreds Futterkiste Maria Anders
Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Ana Trujillo Avda. de la
México
2 Emparedados y Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
4 Around the Horn Thomas 120 Hanover WA1
London UK
Hardy Sq. 1DP
Berglunds Christina Berguvsvägen S-958
5 Lulea Sweden
snabbköp Berglund 8 22
What is a Relational Database?
A relational database defines database relationships in the form of tables. The tables
are related to each other - based on data common to each.
Look at the following three tables "Customers", "Orders", and "Shippers" from the
Northwind database:
Customers Table
Customer Postal
Customer Name Contact Name Address City Country
ID Code
1 Alfreds Futterkiste Maria Anders
Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Ana Trujillo Avda. de la
México
2 Emparedados y Constitución 05021 Mexico
D.F.
helados 2222
Antonio Moreno Antonio Mataderos México
3 05023 Mexico
Taquería Moreno 2312 D.F.
4 Around the Horn Thomas 120 Hanover WA1
London UK
Hardy Sq. 1DP
Berglunds Christina Berguvsvägen S-958
5 Lulea Sweden
snabbköp Berglund 8 22
The relationship between the "Customers" table and the "Orders" table is the
CustomerID column:
Orders Table
OrderID CustomerID EmployeeID OrderDate ShipperID
10278 5 8 1996-08-12 2
10280 5 2 1996-08-14 1
10308 2 7 1996-09-18 3
10355 4 6 1996-11-15 1
10365 3 3 1996-11-27 2
10383 4 8 1996-12-16 3
10384 5 3 1996-12-16 3
The relationship between the "Orders" table and the "Shippers" table is the ShipperID
column:
Shippers Table
ShipperID ShipperName Phone
1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931
What is SQL?
SQL is the standard language for dealing with Relational Databases.
SQL is used to insert, search, update, and delete database records.
How to Use SQL
The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems
that allow more than one SQL statement to be executed in the same call to the server.
Some of The Most Important SQL Commands
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index
MySQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
SELECT Columns Example
The following SQL statement selects the "CustomerName", "City", and "Country"
columns from the "Customers" table:
Example
SELECT CustomerName, City, Country FROM Customers;
SELECT * Example
The following SQL statement selects ALL the columns from the "Customers" table:
Example
SELECT * FROM Customers;
The MySQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfil a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used
in UPDATE, DELETE, etc.!
WHERE Clause Example
The following SQL statement selects all the customers from "Mexico":
Example
SELECT * FROM Customers
WHERE Country = 'Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow
double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID = 1;
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:
Example
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal. Note: In some versions of SQL this operator may be written as
!=
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
The MySQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
The AND operator displays a record if all the conditions separated by AND are
TRUE.
The OR operator displays a record if any of the conditions separated by OR is
TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Combining AND, OR and NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "Stuttgart" (use parenthesis to form complex
expressions):
Example
SELECT * FROM Customers
WHERE Country = 'Germany' AND (City = 'Berlin' OR City = 'Stuttgart');
The MySQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted
by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
ORDER BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted
by the "Country" and the "CustomerName" column. This means that it orders by
Country, but if some rows have the same Country, it orders them by CustomerName:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
ORDER BY Several Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted
ascending by the "Country" and descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
The MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify
the column names in the SQL query. However, make sure the order of the values is in
the same order as the columns in the table. Here, the INSERT INTO syntax would be as
follows:
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
INSERT INTO Example
The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',
'Norway');
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the
"CustomerName", "City", and "Country" columns (CustomerID will be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
What is a NULL Value?
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record
without adding a value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A
field with a NULL value is one that has been left blank during record creation!
It is not possible to test for NULL values with comparison operators, such as =, <, or
<>.
We will have to use the IS NULL and IS NOT NULL operators instead.
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;
The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
The MySQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in
the UPDATE statement. The WHERE clause specifies which record(s) that should be
updated. If you omit the WHERE clause, all records in the table will be updated!
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new
contact person and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the PostalCode to 00000 for all records where
country is "Mexico":
Example
UPDATE Customers
SET PostalCode = 00000
WHERE Country = 'Mexico';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be
updated!
Example
UPDATE Customers
SET PostalCode = 00000;
The MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in
the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If
you omit the WHERE clause, all records in the table will be deleted!
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the
"Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that
the table structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting
the table:
Example
DELETE FROM Customers;
MySQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MIN() Example
The following SQL statement finds the price of the cheapest product:
Example
SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS LargestPrice
FROM Products;
MySQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
COUNT() Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the
"OrderDetails" table:
Example
SELECT SUM(Quantity)
FROM OrderDetails;
The MySQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign (%) represents zero, one, or multiple characters
The underscore sign (_) represents one, single character
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Tip: You can also combine any number of conditions using AND or OR operators.
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
LIKE Operator Description
WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second
'_r%' position
WHERE CustomerName LIKE Finds any values that start with "a" and are at least
'a_%' 2 characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at least
'a__%' 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with
"o"
SQL LIKE Examples
The following SQL statement selects all customers with a CustomerName starting with
"a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
The following SQL statement selects all customers with a CustomerName ending with
"a":
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
The following SQL statement selects all customers with a CustomerName that have
"or" in any position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
The following SQL statement selects all customers with a CustomerName that have "r"
in the second position:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
The following SQL statement selects all customers with a CustomerName that starts
with "a" and are at least 3 characters in length:
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
The following SQL statement selects all customers with a ContactName that starts with
"a" and ends with "o":
Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
The following SQL statement selects all customers with a CustomerName that does
NOT start with "a":
Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
MySQL Wildcard Characters
A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the LIKE operator. The LIKE operator is used in
a WHERE clause to search for a specified pattern in a column.
Wildcard Characters in MySQL
Symbol Description Example
% Represents zero or more characters bl% finds bl, black, blue, and blob
_ Represents a single character h_t finds hot, hat, and hit
Using the % Wildcard
The following SQL statement selects all customers with a City starting with "ber":
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern
"es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
Using the _ Wildcard
The following SQL statement selects all customers with a City starting with any
character, followed by "ondon":
Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';
The following SQL statement selects all customers with a City starting with "L",
followed by any character, followed by "n", followed by any character, followed by
"on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
The MySQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as
the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
The MySQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Example
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN Example
The following SQL statement selects all products with a price between 10 and 20. In
addition; do not show products with a CategoryID of 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName between
"Carnarvon Tigers" and "Mozzarella di Giovanni":
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
The following SQL statement selects all products with a ProductName between
"Carnarvon Tigers" and "Chef Anton's Cajun Seasoning":
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun Seasoning"
ORDER BY ProductName;
NOT BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName not between
"Carnarvon Tigers" and "Mozzarella di Giovanni":
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
BETWEEN Dates Example
The following SQL statement selects all orders with an OrderDate between '01-July-
1996' and '31-July-1996':
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
MySQL Aliases
Aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
Alias Column Syntax
SELECT column_name AS alias_name
FROM table_name;
Alias Table Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
Alias for Columns Examples
The following SQL statement creates two aliases, one for the CustomerID column and
one for the CustomerName column:
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
The following SQL statement creates two aliases, one for the CustomerName column
and one for the ContactName column. Note: Single or double quotation marks are
required if the alias name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS "Contact Person"
FROM Customers;
The following SQL statement creates an alias named "Address" that combine four
columns (Address, PostalCode, City and Country):
Example
SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City,
Country) AS Address
FROM Customers;
Alias for Tables Example
The following SQL statement selects all the orders from the customer with
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and
give them the table aliases of "c" and "o" respectively (Here we use aliases to make
the SQL shorter):
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
The following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;
Aliases can be useful when:
There are more than one table involved in a query
Functions are used in the query
Column names are big or not very readable
Two or more columns are combined together