A Short MySQL Tutorial with Examples: Tables, Queries and JOINs

A hands-on MySQL tutorial: create tables, add data, then query and update them with SELECT, JOIN, COUNT and UPDATE.

Following my previous article on databases and database planning, I have decided to add a quick practical tour of a MySQL database. MySQL and MariaDB are equivalent for the purpose of this article as they both use the exact same syntax. We will assume that you have access to a MySQL/MariaDB server and have sufficient rights to create and edit a database. The syntax convention is to use CAPITALS for MySQL commands and lowercase for data, labels, or database/table names. All commands are terminated with a semicolon (;).


Setting up our database

Log in to the database from a terminal session so that you may execute SQL commands or "queries" directly and do the following:

MySQL and MariaDB logos

Create our test database called "testdb" by typing "CREATE DATABASE testdb;" and then press ENTER.

CREATE DATABASE testdb;
Query OK, 1 row affected (0.05 sec)

Then nominate the database for use with "USE testdb;".

USE testdb;
Database changed

Now we need to create our tables to contain the data. We must specify the table name and each column name. The columns also need specifications such as the data type to be stored in the column as well as the length or possible length of the data. We will also add an AUTO_INCREMENT column and a UNIQUE KEY.

CREATE TABLE clients (idx MEDIUMINT NOT NULL AUTO_INCREMENT,
fname CHAR(30) NOT NULL,
lname CHAR(45) NOT NULL,
phone CHAR(25) NOT NULL,
PRIMARY KEY (idx),
UNIQUE (lname,fname)
);
Query OK, 0 rows affected (0.37 sec)

This will create an empty table that does not allow duplicate entries for the last-name, first-name combination. Next, we will create a table for personal details.

CREATE TABLE clientdetails (idxp MEDIUMINT NOT NULL,
home VARCHAR(75),
work VARCHAR(30),
occup VARCHAR(25),
id VARCHAR(20),
bank VARCHAR(30),
bankinfo VARCHAR(75),
incomecat INT(1)
);
Query OK, 0 rows affected (0.07 sec)

Now that we have completed the table to contain client information, we can add the second last table for our client vehicles.

CREATE TABLE clientvehicles (idxv MEDIUMINT NOT NULL,
make VARCHAR(30),
model VARCHAR(30),
year INT,
mileage INT,
reg VARCHAR(20),
servicedate DATE,
lastservice DATE,
lastmileage INT,
workdone VARCHAR(100),
notes VARCHAR(255)
);
Query OK, 0 rows affected (0.07 sec)

Our last table is for the income categories of our clients.

CREATE TABLE catdef (incomecat INT(2) NOT NULL,
bracket INT(10)
);
Query OK, 0 rows affected (0.06 sec)

We now have four tables. Once we have added all the data, they will look similar to this. Only the table names will be different:

Database tables

Now we get to the interesting part.


Adding data to your MySQL database

First, show your database tables to make sure all are there:

SHOW TABLES;
+------------------+
| Tables_in_testdb |
+------------------+
| catdef |
| clientdetails |
| clients |
| clientvehicles |
+------------------+
4 rows in set (0.00 sec)

Let us populate the table clients first.

INSERT INTO clients (fname,lname,phone)
VALUES
('Joe','Smith','5552846'),
('Susan','Harris','6549920'),
('Peter','Jones','7920122');
Query OK, 3 rows affected (0.10 sec)
Records: 3 Duplicates: 0 Warnings: 0

Now we can do a "SELECT" statement to display the data we have just entered.

SELECT * FROM clients;
+-----+-------+--------+---------+
| idx | fname | lname | phone |
+-----+-------+--------+---------+
| 1 | Joe | Smith | 5552846 |
| 2 | Susan | Harris | 6549920 |
| 3 | Peter | Jones | 7920122 |
+-----+-------+--------+---------+
3 rows in set (0.03 sec)

I will now provide the lines that you can copy and paste to create the rest of the data we need. Table 2 - Client Information:

INSERT INTO clientdetails
VALUES
('1','3 Halfmoon cresc, Mountainview','Woolworths','Manager','5801021234086','NationalBank','acc 321543123','3'),
('2','241 Honey Ave, Hibiscus Heights','Masons','Accountant','7510214321082','SecurityHold','acc 876576545','2'),
('3','84 Hamilton Cl, Cyprus Canyon','Shell','Salesman','8011229876087','MoneSafe','acc 102210123','2');

Table 3 - Client Vehicle Info

INSERT INTO clientvehicles
VALUES
('1','Jaguar','XF','2015','12598','CA 223344','2018-04-11','2017-01-15','6521','Oil & Filters','None'),
('2','Ford','Mondeo','2013','52344','CF 123212','2017-11-23','2015-12-03','34565','Oil, Filters & Plugs','Left rear tyre bald patch'),
('3','Mini','Cooper S','2010','87433','CY 982212','2018-01-15','2017-01-12','70211','Oil, Filters & Plugs','LF CV Joint Boot worn');

Table 4 - Income Categories

INSERT INTO catdef
VALUES
('1','10000'),
('2','20000'),
('3','30000'),
('4','40000');

Now that we have completed the data input, we can query each table to check. We have already queried the table "clients". We shall now query the other tables.

SELECT * FROM clientdetails;
+------+---------------------------------+------------+------------+---------------+--------------+---------------+-----------+
| idxp | home | work | occup | id | bank | bankinfo | incomecat |
+------+---------------------------------+------------+------------+---------------+--------------+---------------+-----------+
| 1 | 3 Halfmoon cresc, Mountainview | Woolworths | Manager | 5801021234086 | NationalBank | acc 321543123 | 3 |
| 2 | 241 Honey Ave, Hibiscus Heights | Masons | Accountant | 7510214321082 | SecurityHold | acc 876576545 | 2 |
| 3 | 84 Hamilton Cl, Cyprus Canyon | Shell | Salesman | 8011229876087 | MoneSafe | acc 102210123 | 2 |
+------+---------------------------------+------------+------------+---------------+--------------+---------------+-----------+
3 rows in set (0.00 sec)

SELECT * FROM clientvehicles;
+------+--------+----------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
| idxv | make | model | year | mileage | reg | servicedate | lastservice | lastmileage | workdone | notes |
+------+--------+----------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
| 1 | Jaguar | XF | 2015 | 12598 | CA 223344 | 2018-04-11 | 2017-01-15 | 6521 | Oil & Filters | None |
| 2 | Ford | Mondeo | 2013 | 52344 | CF 123212 | 2017-11-23 | 2015-12-03 | 34565 | Oil, Filters & Plugs | Left rear tyre bald patch |
| 3 | Mini | Cooper S | 2010 | 87433 | CY 982212 | 2018-01-15 | 2017-01-12 | 70211 | Oil, Filters & Plugs | LF CV Joint Boot worn |
+------+--------+----------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
3 rows in set (0.00 sec)

SELECT * FROM catdef;
+-----------+---------+
| incomecat | bracket |
+-----------+---------+
| 1 | 10000 |
| 2 | 20000 |
| 3 | 30000 |
| 4 | 40000 |
+-----------+---------+
4 rows in set (0.00 sec)

The SELECT query

With the data in place, we can start to query it. You have already used the simplest query, "SELECT * FROM clients;", which returns every row and column of a table. While MySQL commands are not case sensitive, database and table names are case sensitive on most Linux servers, so a table name typed in CAPITALS fails:

SELECT * FROM CLIENTS;
ERROR 1146 (42S02): Table 'testdb.CLIENTS' doesn't exist

Typed in lowercase, the same query returns the three clients shown above. This is one reason to keep database and table names simple: use lowercase letters, digits and underscores only. A name with any other character, such as a hyphen or a space, has to be quoted in backticks every time you use it.


Output modifier CONCAT

We can manipulate the output slightly. Let us join the first and last names with CONCAT. If we do not rename, or alias, the output, we get our CONCAT statement as a column header like this:

SELECT idx,CONCAT(fname," ",lname),phone FROM clients;
+-----+-------------------------+---------+
| idx | CONCAT(fname," ",lname) | phone |
+-----+-------------------------+---------+
| 1 | Joe Smith | 5552846 |
| 2 | Susan Harris | 6549920 |
| 3 | Peter Jones | 7920122 |
+-----+-------------------------+---------+
3 rows in set (0.05 sec)

Now the aliased output, where AS names the column "fullname". Note that we have to specify a space (" ") between the first and last name.

SELECT idx,CONCAT(fname," ",lname) AS fullname,phone FROM clients;
+-----+--------------+---------+
| idx | fullname | phone |
+-----+--------------+---------+
| 1 | Joe Smith | 5552846 |
| 2 | Susan Harris | 6549920 |
| 3 | Peter Jones | 7920122 |
+-----+--------------+---------+
3 rows in set (0.00 sec)

LIMIT output rows returned

We can also specify a LIMIT on the data returned, which is useful when you have a few thousand rows of data.

SELECT * FROM clientdetails LIMIT 1;
+------+--------------------------------+------------+---------+---------------+--------------+---------------+-----------+
| idxp | home | work | occup | id | bank | bankinfo | incomecat |
+------+--------------------------------+------------+---------+---------------+--------------+---------------+-----------+
| 1 | 3 Halfmoon cresc, Mountainview | Woolworths | Manager | 5801021234086 | NationalBank | acc 321543123 | 3 |
+------+--------------------------------+------------+---------+---------------+--------------+---------------+-----------+
1 row in set (0.00 sec)

Using LIMIT we can also ask for only the 3rd row of data. Remember that the first row is in position 0, thus the 3rd row will be position 2 and we only want 1 row returned. The LIMIT will thus be specified as LIMIT 2,1 (position 2, 1 row only).

SELECT * FROM clientdetails LIMIT 2,1;
+------+-------------------------------+-------+----------+---------------+----------+---------------+-----------+
| idxp | home | work | occup | id | bank | bankinfo | incomecat |
+------+-------------------------------+-------+----------+---------------+----------+---------------+-----------+
| 3 | 84 Hamilton Cl, Cyprus Canyon | Shell | Salesman | 8011229876087 | MoneSafe | acc 102210123 | 2 |
+------+-------------------------------+-------+----------+---------------+----------+---------------+-----------+
1 row in set (0.00 sec)

LIMIT 1 OFFSET 2 returns the same row and is easier to read. Without an ORDER BY clause the database picks the row order, so add one, such as ORDER BY idxp, when the position matters.


Using JOIN to look up related data

Now let us combine the output of two tables in a useful way. We will do this with JOIN, which overlays data from one table on the relevant data from another. Let us start by asking "Who owns the Ford Mondeo?". In the SQL query, this will first involve choosing the record containing make = Ford and model = Mondeo.

SELECT * FROM clientvehicles WHERE make LIKE 'ford' AND model LIKE 'mondeo';
+------+------+--------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
| idxv | make | model | year | mileage | reg | servicedate | lastservice | lastmileage | workdone | notes |
+------+------+--------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
| 2 | Ford | Mondeo | 2013 | 52344 | CF 123212 | 2017-11-23 | 2015-12-03 | 34565 | Oil, Filters & Plugs | Left rear tyre bald patch |
+------+------+--------+------+---------+-----------+-------------+-------------+-------------+----------------------+---------------------------+
1 row in set (0.00 sec)

MySQL's default collations ignore case when they compare text, so 'ford' finds "Ford" here, as it would with = in place of LIKE. What LIKE adds is the wildcard "%", which matches any run of characters. If the model was "Mondeo LX", we could have searched for "LIKE 'mondeo %'".

As we are not interested in the vehicle details, but need the owner, we now JOIN the clients table. Note that we alias each table to shorten the SQL statement: the clientvehicles table becomes V and the clients table becomes C. Each vehicle's idxv is the idx of the client who owns it, so we join on V.idxv=C.idx.

SELECT CONCAT(C.fname," ",C.lname) AS fullname FROM clients C JOIN clientvehicles V ON V.idxv=C.idx WHERE V.make LIKE 'ford' AND V.model LIKE 'mondeo';
+--------------+
| fullname |
+--------------+
| Susan Harris |
+--------------+
1 row in set (0.00 sec)

The double JOIN

Let us now find the income bracket of a client. There is no direct relation between the income bracket and the client, so one JOIN is not enough: we need a double JOIN, which is two JOINs in one query. We SELECT the clients, find their income category in the clientdetails table, and then use that category to find the income bracket in the catdef table. Visually, it can be represented as follows:

How the double JOIN links the clients, clientdetails and catdef tables

We will alias each table to enable a shorter, more readable query. The clients table will be C, the clientdetails table will be D and the catdef table will be CD. We thus SELECT the data to be shown and do a double JOIN to match the correct data. Here is the query and results:

SELECT C.fname,C.lname,CD.bracket FROM clients C JOIN clientdetails D ON C.idx=D.idxp JOIN catdef CD ON D.incomecat=CD.incomecat;
+-------+--------+---------+
| fname | lname | bracket |
+-------+--------+---------+
| Susan | Harris | 20000 |
| Peter | Jones | 20000 |
| Joe | Smith | 30000 |
+-------+--------+---------+
3 rows in set (0.01 sec)

Updating a table and inserting new data

We will now answer two questions: how do we add a second vehicle for an existing client, and how do we UPDATE existing data? Let us first ADD a new vehicle entry for our client, Joe Smith (client #1). The car is new, so it has no last service yet and its lastservice is NULL.

INSERT INTO clientvehicles VALUES ('1','Porsche','Boxster S','2017','50','JOESMITH-CA','2018-04-26',NULL,'0','Handbrake Adjusted','New Vehicle');
Query OK, 1 row affected (0.02 sec)
SELECT * FROM clientvehicles;
+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| idxv | make | model | year | mileage | reg | servicedate | lastservice | lastmileage | workdone | notes |
+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| 1 | Jaguar | XF | 2015 | 12598 | CA 223344 | 2018-04-11 | 2017-01-15 | 6521 | Oil & Filters | None |
| 2 | Ford | Mondeo | 2013 | 52344 | CF 123212 | 2017-11-23 | 2015-12-03 | 34565 | Oil, Filters & Plugs | Left rear tyre bald patch |
| 3 | Mini | Cooper S | 2010 | 87433 | CY 982212 | 2018-01-15 | 2017-01-12 | 70211 | Oil, Filters & Plugs | LF CV Joint Boot worn |
| 1 | Porsche | Boxster S | 2017 | 50 | JOESMITH-CA | 2018-04-26 | NULL | 0 | Handbrake Adjusted | New Vehicle |
+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
4 rows in set (0.00 sec)

Now we have two vehicles with the same client id (idxv). Let us SELECT all vehicles for Joe Smith. At the same time, we use CONCAT to clean up the output.

SELECT CONCAT(V.make," ",V.model) AS car, CONCAT(C.fname," ",C.lname) AS owner FROM clientvehicles V JOIN clients C ON V.idxv=C.idx WHERE C.fname LIKE 'joe' AND C.lname LIKE 'smith';
+-------------------+-----------+
| car | owner |
+-------------------+-----------+
| Jaguar XF | Joe Smith |
| Porsche Boxster S | Joe Smith |
+-------------------+-----------+
2 rows in set (0.00 sec)

Next, we will let MySQL do some calculations for us. How many cars does Joe Smith have in our system? We use the COUNT() function to count the matching rows. Because the query also shows the owner's name, we group the rows by client with GROUP BY C.idx: without it, MySQL 5.7 and later reject the query under their default ONLY_FULL_GROUP_BY mode.

SELECT COUNT(V.idxv) AS number, CONCAT(C.fname," ",C.lname) AS owner FROM clientvehicles V JOIN clients C ON V.idxv=C.idx WHERE C.fname LIKE 'joe' AND C.lname LIKE 'smith' GROUP BY C.idx;
+--------+-----------+
| number | owner |
+--------+-----------+
| 2 | Joe Smith |
+--------+-----------+
1 row in set (0.00 sec)

Let us update the information on Joe Smith's Jaguar - he has a new registration, which is now "JOESJAG". We are going to add a UNIQUE id to the start of the table, as we cannot use the idxv field to uniquely identify the row anymore. MySQL numbers the existing rows for us when it adds the AUTO_INCREMENT column.

ALTER TABLE clientvehicles ADD COLUMN idx INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0
SELECT * FROM clientvehicles;
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| idx | idxv | make | model | year | mileage | reg | servicedate | lastservice | lastmileage | workdone | notes |
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| 1 | 1 | Jaguar | XF | 2015 | 12598 | CA 223344 | 2018-04-11 | 2017-01-15 | 6521 | Oil & Filters | None |
| 2 | 2 | Ford | Mondeo | 2013 | 52344 | CF 123212 | 2017-11-23 | 2015-12-03 | 34565 | Oil, Filters & Plugs | Left rear tyre bald patch |
| 3 | 3 | Mini | Cooper S | 2010 | 87433 | CY 982212 | 2018-01-15 | 2017-01-12 | 70211 | Oil, Filters & Plugs | LF CV Joint Boot worn |
| 4 | 1 | Porsche | Boxster S | 2017 | 50 | JOESMITH-CA | 2018-04-26 | NULL | 0 | Handbrake Adjusted | New Vehicle |
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
4 rows in set (0.00 sec)

Now that we have a UNIQUE reference, we can do the UPDATE. Here we SET the field reg to 'JOESJAG' WHERE the idx field equals 1.

UPDATE clientvehicles SET reg='JOESJAG' WHERE idx=1;
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
SELECT * FROM clientvehicles;
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| idx | idxv | make | model | year | mileage | reg | servicedate | lastservice | lastmileage | workdone | notes |
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
| 1 | 1 | Jaguar | XF | 2015 | 12598 | JOESJAG | 2018-04-11 | 2017-01-15 | 6521 | Oil & Filters | None |
| 2 | 2 | Ford | Mondeo | 2013 | 52344 | CF 123212 | 2017-11-23 | 2015-12-03 | 34565 | Oil, Filters & Plugs | Left rear tyre bald patch |
| 3 | 3 | Mini | Cooper S | 2010 | 87433 | CY 982212 | 2018-01-15 | 2017-01-12 | 70211 | Oil, Filters & Plugs | LF CV Joint Boot worn |
| 4 | 1 | Porsche | Boxster S | 2017 | 50 | JOESMITH-CA | 2018-04-26 | NULL | 0 | Handbrake Adjusted | New Vehicle |
+-----+------+---------+-----------+------+---------+-------------+-------------+-------------+-------------+----------------------+---------------------------+
4 rows in set (0.00 sec)

JOIN types explained

This is best shown with the "SQL Joins" diagram by Arbeck from Wikimedia Commons, licensed under CC BY 3.0.

SQL JOIN types shown as overlapping circles for table A and table B

Every JOIN in this tutorial is the INNER JOIN at the top of the diagram: MySQL reads JOIN on its own as INNER JOIN. MySQL has no FULL OUTER JOIN, which the two shapes at the bottom use. To get the same rows, combine the matching LEFT JOIN and RIGHT JOIN queries with UNION.

That completes this short MySQL tutorial. You have created a database and its tables, added data, and used SELECT, CONCAT, LIMIT, JOIN, COUNT(), ALTER TABLE and UPDATE to query and change it.

Happy Hosting!

Avatar for Michael O.

The Author

Michael O.

Michael is the founder, managing director, and CEO of HostAfrica. He studied at Friedrich Schiller University Jena and was inspired by Cape Town's beauty to bring his German expertise to Africa. Before HostAfrica, Michael was the Managing Director of Deutsche Börse Cloud Exchange AG, one of Germany's largest virtual server providers.

Deploy your application with confidence

Flexible application hosting built for developers and modern stacks.