Basic MySQL Tutorial
Basic MySQL Tutorial
This basic MySQL tutorial explains some of the basic SQL statements. If this is the first
time you have used a relational database management system, this tutorial gives you
everything you need to know to work with MySQL such as querying data, updating data,
managing databases, and creating tables.
If you’re already familiar with other relational database management systems such as
PostgreSQL, Oracle, or Microsoft SQL Server, etc., you can use this tutorial to refresh your
knowledge and understand how SQL dialect of MySQL is different from other systems.
This section helps you get started with MySQL. We will start installing MySQL,
downloading a sample database, and loading data into the MySQL server for practicing.
Installing MySQL database server – show you step by step how to install MySQL
database server on your computer.
Downloading MySQL sample database – introduce you to a MySQL sample database
named classicmodels. We also provide you links for downloading the sample database
and its diagrams.
Loading the sample database into your own MySQL database server – walk you
through steps of how to load the classicmodels sample database into your MySQL
database server for practicing.
This section helps you learn how to query data from the MySQL database server. We will
start with a simple SELECT statement that allows you to query data from a single table.
SELECT – show you how to use simple SELECT statement to query the data from a
single table.
SELECT DISTINCT – learn how to use the DISTINCT operator in the SELECT
statement to eliminate duplicate rows in a result set.
Section 3. Filtering data
WHERE – learn how to use the WHERE clause to filter rows based on specified
conditions.
AND – introduce you to the AND operator to combine Boolean expressions to form a
complex condition for filtering data.
OR– introduce you to the OR operator and show you how to combine the OR operator
with the AND operator to filter data.
IN – show you how to use the IN operator in the WHERE clause to determine if a value
matches any value in a list or a subquery.
BETWEEN – show you how to query data based on a range using BETWEEN operator.
LIKE – provide you with technique to query data based on a specific pattern.
LIMIT – use LIMIT to constrain the number of rows returned by SELECT statement
IS NULL – test whether a value is NULL or not by using IS NULL operator.
ORDER BY – show you how to sort the result set using ORDER BY clause. The
custom sort order with the FIELD function will be also covered.
Natural sorting using ORDER BY clause – walk you through various natural sorting
techniques in MySQL by using the ORDER BY clause.
MySQL alias – introduce you to table alias and aliases to improve the readability of
complex queries.
MySQL Join – give you an overview of joins supported in MySQL including cross
join, inner join, left join, and right join.
INNER JOIN – use inner join clause to query data from multiple related tables.
LEFT JOIN – learn how to apply left join clause in various contexts.
RIGHT JOIN – show you how to use right join to query data from two or more tables.
CROSS JOIN – make a Cartesian product of rows from multiple tables.
Self-join – joins a table to itself using table alias, and connects rows within the same
table using other kinds of joins including inner join and left join.
Section 6. Grouping data
GROUP BY clause – show you how to group rows into groups based on columns or
expressions.
HAVING – filter the groups by a specific condition.
MySQL subquery – show you how to nest a query (inner query) within another query
(outer query) and use the result of the inner query for the outer query.
MySQL derived table – introduce you the derived table concept and show you how to
use it to simplify complex queries.
MySQL CTE – explain you the common table expression concept and show you how
to use CTE for querying data from tables.
Recursive CTE – guide you how to use the recursive CTE to traverse the hierarchical
data.
UNION and UNION ALL – combine two or more result sets of multiple queries into
a single result set.
INTERSECT – show you a couple of ways to simulate the INTERSECT operator in
MySQL.
MINUS – explain to you the SQL MINUS operator and show you how to simulate it
in MySQL.
In this section, you will learn how to insert, update, and delete data from tables using various
MySQL statements.
INSERT – learn how to use various forms of the INSERT statement to insert data into
database tables.
INSERT IGNORE – explain you the INSERT IGNORE statement that inserts rows into
a table and ignore rows that cause errors or exceptions.
UPDATE – learn how to use UPDATE statement and its options to update data in
database tables.
UPDATE JOIN – show you how to perform cross table update using UPDATE JOIN
statement with INNER JOIN and LEFT JOIN.
DELETE – show you how to use the DELETE statement to remove data from one or
more tables.
ON DELETE CASCADE – learn how to use ON DELETE CASCADE referential action
for a foreign key to delete data from a child table automatically when you delete data
from a parent table.
DELETE JOIN – show you how to delete data from multiple tables.
REPLACE – learn how to insert or update data depends on whether data exists in the
table or not.
Prepared Statement – show you how to use the prepared statement to execute a query.
MySQL transaction – learn about MySQL transactions, and how to use COMMIT and
ROLLBACK to manage transactions in MySQL.
MySQL table locking – learn how to use MySQL locking for cooperating table access
between sessions.
This section shows you how to manage the most important database objects in MySQL
including database and tables.
Managing database in MySQL – you will learn various statements to manage MySQL
databases including creating a new database, removing an existing database, selecting
a database, and listing all databases.
Understanding MySQL Table Types – it is essential to understand the features of each
table type so that you can use them effectively to maximize the performance of your
databases.
CREATE TABLE – show you how to create new tables in a database using CREATE
TABLE statement.
MySQL sequence – show you how to use a sequence to generate unique numbers
automatically for the primary key column of a table.
ALTER TABLE – learn how to use the ALTER TABLE statement to change existing
table’s structure.
Renaming table – show you how to rename a table using RENAME TABLE statement.
Removing a column from a table – show you how to use the ALTER TABLE DROP
COLUMN statement to remove one or more columns from a table.
Adding a new column to a table – show you how to add one or more columns to an
existing table using ALTER TABLE ADD COLUMN statement.
DROP TABLE – show you how to remove existing tables using DROP TABLE
statement.
MySQL temporary table – discuss MySQL temporary table and show you how to
manage temporary tables.
TRUNCATE TABLE – show you how to use the TRUNCATE TABLE statement to
delete all data in a table fast.
Managing MySQL database indexes – learn how to work with MySQL indexes and
how to take advantages of indexes to speed up the data retrieval.
UNIQUE index – show you how to use the UNIQUE index to enforce the uniqueness
of value in one or more columns.
MySQL data types – show you various data types in MySQL so that you can apply
them effectively in designing database tables.
INT – show you how to use integer data type. We also show you how to use
ZEROFILL and display width attributes of the integer column.
DECIMAL – show you how to use DECIMAL data type to store exact values in
decimal format.
BIT – introduce you BIT data type and how to store bit values in MySQL.
BOOLEAN – explain to you how MySQL handles Boolean values by using
TINYINT(1) internally.
CHAR – guide to CHAR data type for storing the fixed-length string.
VARCHAR – give you the essential guide to VARCHAR data type.
TEXT – show you how to store text data using TEXT data type.
DATE – introduce you to the DATE data type and show you some date functions to
handle the date data effectively.
TIME – walk you through the features of TIME data type and show you how to
use some useful temporal functions to handle time data.
DATETIME – introduce you to the DATETIME data type and some useful functions to
manipulate DATETIME values.
TIMESTAMP – introduce you to TIMESTAMP and its features called automatic
initialization and automatic update that allows you to define auto-initialized and auto-
updated columns for a table.
JSON – show you how to use JSON data type to store JSON documents.
ENUM – learn how to use ENUM data type correctly to store enumeration values.
NOT NULL constraint – introduce you to the NOT NULL constraint and show you how
to define a NOT NULL constraint for a column or add the NOT NULL constraint to an
existing column.
Primary key constraint – guide you how to use primary key constraint to create the
primary key for a table.
Foreign key constraint – introduce you to the foreign key and show you step by step
how to create and drop foreign keys.
UNIQUE constraint – show you how to use UNIQUE constraint to enforce the
uniqueness of values in a column or a group of columns in a table.
CHECK constraint emulation – walk you through various ways to emulate the
CHECK constraint in MySQL.
Import CSV File Into MySQL Table – show you how to use LOAD DATA INFILE
statement to import CSV file into a MySQL table.
MySQL Export Table to CSV – learn various techniques of how to export MySQL
table to a CSV file format.
Summary: this tutorial shows you step by step how to install MySQL on Windows platform
using MySQL Installer. After the tutorial, you will have a MySQL database server and its
tools up and running in your system for learning and practicing MySQL.
If you want to install MySQL on Windows environment, using MySQL installer is the easiest
way. MySQL installer provides you with an easy-to-use wizard that helps you to install
MySQL with the following components:
MySQL Server
All Available Connectors
MySQL Workbench with Sample Data Models
MySQL Notifier
Tools for Excel and Microsoft Visual Studio
MySQL Sample Databases
MySQL Documentation
To install MySQL using the MySQL installer, double click on the MySQL installer file and
follow the steps below:
Install MySQL Step 1: Windows configures MySQL Installer
Install MySQL Step 2 – Welcome Screen: A welcome screen provides several options.
Choose the first option: Install MySQL Products
Install MySQL Step 3 – Download the latest MySQL products : MySQL installer checks and
downloads the latest MySQL products including MySQL server, MySQL Workbench,etc.
Install MySQL Step 8 – Configuration Overview. Click Next button to configure MySQL
Database Server
Install MySQL Step 8.1 – MySQL Server Configuration: choose Config Type and MySQL
port (3006 by default) and click Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration : choose a password for the root
account. Please note the password download and keep it securely if you are install MySQL
database server in a production server. If you want to add more MySQL user, you can do it in
this step.
Install MySQL Step 8.1 – MySQL Server Configuration: choose Windows service details
including Windows Service Name and account type, then click Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration – In Progress : MySQL Installer is
configuring MySQL database server. Wait until it is done and click Next button to continue.
Install MySQL Step 8.1 – MySQL Server Configuration – Done. Click the Next button to
continue.
Install MySQL Step 8.2 – Configuration Overview: MySQL Installer installs sample
databases and sample models.
Install MySQL Step 9 – Installation Completes: the installation completes. Click finish button
to close the installation wizard and launch the MySQL Workbench.
In this tutorial, you have learned how to install MySQL in your Windows system using
MySQL installer. Let’s download MySQL sample database and load it into MySQL server
for practicing and learning MySQL through our MySQL tutorials.
We use the classicmodels database as a MySQL sample database to help you work with
MySQL quickly and effectively. The classicmodels database is a retailer of scale models of
classic cars database. It contains typical business data such as customers, products, sales
orders, sales order line items, etc.
We use this sample database in our MySQL tutorials to demonstrate many MySQL features
from simple queries to complex stored procedures.
You can download the MySQL sample database in the following link:
The download file is in ZIP format so you need a zip program to unzip it. You can download
a free zip program at www.7-zip.org.
After uncompressing the sampledatabase.zip file, you can load the sample database into
MySQL database server by following how to load sample database into MySQL database
server tutorial and test it by using the following SQL statements:
1 USE classicmodels;
2 SELECT * FROM customers;
Basically, those statements switch the current database to classicmodels and query data from
the customers table. If you see the customers data returned, you have successfully imported the
sample database into the MySQL database server.
You can download the MySQL sample database ER-diagram in PDF format via the following
link. We recommend that you print the ER diagram out and stick it to your desk to get
familiar with the schema while learning MySQL.
Summary: in this tutorial, you will learn how to load the MySQL sample database into
MySQL database server using MySQL Workbench. After the tutorial, you will have
classicmodels sample database loaded into MySQL server for practicing and learning MySQL.
Step 1. Download the classicmodels database from the MySQL sample database section.
Step 2. Unzip the downloaded file into a temporary folder.You can use any folder you want.
To make it simple we will unzip it to the C:\temp folder as follows.
Step 3. Launch MySQL Workbench application from the Program Files > MySQL > MySQL
Workbench 5.2 . The newer version of MySQL Workbench is also relevant.
Step 4. To add a new database connection for querying, click New Connection as follows:
Step 5. Setup a new connection: you must enter all connection parameters on this Setup New
Connection window. The following information is required:
Connection name: the name of the connection. If you connect to the localhost , just type
local . In case you connect to a specific host, use the host name for the name of the
connection to make it clear.
Host name: in this case it is 127.0.0.1 i.e., localhost . You can enter either IP address or
the name of the database server.
Username: the user that you use connect to the MySQL database. In this case it it the
root user.
Password: the password of the user that you use to connect to the database.
Default Schema: is the database that you want to connect. You can leave it blank and
select later using the use database command.
You should click on Test Connection to make sure that the parameters you provided are
correct, and then click OK button to create a new connection. Once you complete, you will
see connections window as follows:
Step 6. Click the local database connection to connect to MySQL database server. Because
we didn’t provide the password in the previous step, MySQL asks us to enter the password
for the root account. We enter our password and click OK button.
If you enter both user and password correctly, you will see the following window:
Step 7. Open SQL Script by choosing File > Open SQL Script or press the Ctrl+Shift+O keyboard
shortcut.
Step 8. Choose SQL Script File by selecting the File C:\temp\mysqlsampledatabase.txt
Step 10. To execute SQL Script, you click execute button from the toolbar as following:
Step 11. Right click inside the Schemas panel and click Refresh All button to update the
panel. The classimodels database is loaded successfully into MySQL database server.
In this tutorial, we have shown you step by step how to load the MySQL sample database into
MySQL database server using MySQL Workbench.
Section 2. Querying data
Summary: in this tutorial, you will learn how to use MySQL SELECT statement to query
data from tables or views.
The SELECT statement allows you to get the data from tables or views. A table consists of
rows and columns like a spreadsheet. Often, you want to see a subset rows, a subset of
columns, or a combination of two. The result of the SELECT statement is called a result set
that is a list of rows, each consisting of the same number of columns.
See the following employees table in the sample database. It has eight columns: employee
number, last name, first name, extension, email, office code, reports to, job title and many
rows.
The SELECT statement controls which columns and rows that you want to see. For example, if
you are only interested in the first name, last name, and job title of all employees or you just
want to view the information of every employee whose job title is the sales rep, the SELECT
statement helps you to do this.
Let’s take look into the syntax of the SELECT statement:
The SELECT statement consists of several clauses as explained in the following list:
The SELECT and FROM clauses are required in the statement. Other parts are optional.
You will learn about each clause in more detail in the subsequent tutorials. In this tutorial, we
are going to focus on the basic form of the SELECT statement.
The SELECT statement allows you to query partial data of a table by specifying a list of
comma-separated columns in the SELECT clause. For instance, if you want to view only first
name, last name, and job title of the employees, you use the following query:
Even though the employees table has many columns, the SELECT statement just returns data of
three columns of all rows in the table as highlighted in the picture below:
If you want to get data for all columns in the employees table, you can list all column names in
the SELECT clause. Or you just use the asterisk (*) to indicate that you want to get data from
all columns of the table like the following query:
It returns all columns and rows in the employees table.
You should use the asterisk (*) for testing only. In practical, you should list the columns that
you want to get data explicitly because of the following reasons:
The asterisk (*) returns data from the columns that you may not use. It produces
unnecessary I/O disk and network traffic between the MySQL database server and
application.
If you explicit specify the columns, the result set is more predictable and easier to
manage. Imagine when you use the asterisk(*) and someone changes the table by
adding more columns, you will end up with a result set that is different from what you
expected.
Using asterisk (*) may expose sensitive information to unauthorized users.
In this tutorial, you’ve learned about the basic MySQL SELECT statement to query data from
a table in MySQL.
Using MySQL DISTINCT to Eliminate Duplicates
Summary: in this tutorial, you will learn how to use MySQL DISTINCT clause with the
SELECT statement to eliminate duplicate rows in a result set.
When querying data from a table, you may get duplicate rows. In order to remove these
duplicate rows, you use the DISTINCT clause in the SELECT statement.
Let’s take a look a simple example of using the DISTINCT clause to select the unique last
names of employees from the employees table.
First, we query the last names of employees from the employees table using the SELECT
statement as follows:
Some employees have the same last name Bondur,Firrelli etc.
To remove the duplicate last names, you add the DISTINCT clause to the SELECT statement as
follows:
The duplicate last names are eliminated in the result set when we used the DISTINCT clause.
For example, in the customers table, we have many rows whose state column has NULL values.
When we use the DISTINCT clause to query the customers’ states, we will see unique states
and a NULL value as the following query:
You can use the DISTINCT clause with more than one column. In this case, MySQL uses the
combination of all columns to determine the uniqueness of the row in the result set.
For example, to get the unique combination of city and state from the customers table, you use
the following query:
Without the DISTINCT clause, you will get the duplicate combination of state and city as
follows
DISTINCT clause vs. GROUP BY clause
If you use the GROUP BY clause in the SELECT statement without using aggregate functions,
the GROUP BY clause behaves like the DISTINCT clause.
The following statement uses the GROUP BY clause to select the unique states of customers
from the customers table.
You can achieve the similar result by using the DISTINCT clause:
Generally speaking, the DISTINCT clause is a special case of the GROUP BY clause. The
difference between DISTINCT clause and GROUP BY clause is that the GROUP BY clause sorts
the result set whereas the DISTINCT clause does not.
If you add the ORDER BY clause to the statement that uses the DISTINCT clause, the result
set is sorted and it is the same as the one returned by the statement that uses GROUP BY
clause.
You can use the DISTINCT clause with an aggregate function e.g., SUM, AVG, and COUNT,
to remove duplicate rows before MySQL applies the aggregate function to the result set.
For example, to count the unique states of customers in the U.S., you use the following query:
MySQL DISTINCT with LIMIT clause
In case you use the DISTINCT clause with the LIMIT clause, MySQL stops searching
immediately when it finds the number of unique rows specified in the LIMIT clause.
The following query selects the first 5 non-null unique states in the customers table.
In this tutorial, we have shown you various ways of using MySQL DISTINCT clause such as
eliminating duplicate rows and counting non-NULL values.
Section 3. Filtering data
Summary: you will learn how to use MySQL WHERE clause in the SELECT statement to
filter rows in the result set.
If you use the SELECT statement to query the data from tables without the WHERE clause,
you will get all rows in the tables that may be not necessary. The tables accumulate data from
business transactions all times. It does not make sense to get all rows from a table especially
for big tables like employees, sales orders, purchase orders, production orders, etc., because
we often want to analyze a set of data at a time e.g, sales of this quarter, sales of this year
compared to last year, etc.
The WHERE clause allows you to specify exact rows to select based on a particular filtering
expression or condition.
You will also learn how to use LIMIT clause to constrain the number of rows returned by the
SELECT statement.
We will continue with the employees table data in the sample database as shown in the picture
below.
Suppose, we just want to get sales rep employees from the employees table, we use the
following query:
Even though the WHERE clause appears at the end of the statement, MySQL evaluates the expression
in the WHERE clause first to select the matching rows. It chooses the rows that have job title as Sales
Rep
MySQL then selects the columns from the selection list in the SELECT clause. The
highlighted area contains the columns and rows in the final result set.
You can form a simple condition like the query above, or a very complex one that combines
multiple expressions with logical operators such as AND, OR, etc. For example, to find all
sales rep in the office code 1, you use the following query:
The following table lists the comparison operators that you can use to form filtering
expressions in the WHERE clause.
Operator Description
= Equal to. You can use it with almost any data types.
<> or != Not equal to.
Less than. You typically use it with numeric and date/time data
<
types.
> Greater than.
<= Less than or equal to
>= Greater than or equal to
The following query uses the not equal to operator to get all employees who are not the sales
rep:
What about employee with office code less than or equal 4 (<=4):
More on MySQL WHERE clause…
There are also some useful operators that you can use in the WHERE clause to form complex
conditions such as:
The WHERE clause is used not only with the SELECT statement but also other SQL statements
to filter rows such as DELETE and UPDATE.
In this tutorial, we’ve shown you how to use MySQL WHERE clause to filter rows based on
conditions.
Section 4. Sorting data
Summary: in this tutorial, you will learn how to sort a result set using MySQL ORDER BY
clause.
When you use the SELECT statement to query data from a table, the result set is not sorted in
any orders. To sort the result set, you use the ORDER BY clause. The ORDER BY clause allows
you to:
The ASC stands for ascending and the DESC stands for descending. By default, the ORDER
BY clause sorts the result set in ascending order if you don’t specify ASC or DESC explicitly.
If you want to sort the contacts by last name in descending order, you specify the DESC after
the contactLastname column in the ORDER BY clause as the following query:
If you want to sort the contacts by last name in descending order and first name in ascending
order, you specify both DESC and ASC in the corresponding column as follows:
In the query above, the ORDER BY clause sorts the result set by the last name in descending
order first and then sorts the sorted result set by the first name in ascending order to produce
the final result set.
The ORDER BY clause also allows you to sort the result set based on an expression.
See the following orderdetails table.
The following query selects the order line items from the orderdetails table. It calculates the subtotal
for each line item and sorts the result set based on the order number, order line number, and subtotal.
To make the query more readable, you can sort by the column alias as the following query:
We used subtotal as the column alias for the expression quantityOrdered * priceEach and sorted
the result set based on the subtotal alias.
The ORDER BY clause enables you to define your own custom sort order for the values in a
column using the FIELD() function.
For example, if you want to sort the orders based on the following status by the following
order:
In Process
On Hold
Cancelled
Resolved
Disputed
Shipped
You can use the FIELD function to map those values to a list of numeric values and use the
numbers for sorting; See the following query:
In this tutorial, we’ve shown you various techniques to sort a result set by using the MySQL
ORDER BY clause.