MySQL Tutorial
MySQL Tutorial
1|Page
TABLE OF CONTENTS
1. Managing Database3 2. Understanding MySQL Table Types.7 3. MySQL Data Types8 4. Understanding MySQL Time Stamps.12 5. Working with Tables Part 1.14 6. Working with Tables Part 2....................................................................................................16 7. Changing Table Structure Using MySQL ALTER Table18 8. Managing Database Index...20 9. Using MySQL SELECT Statement to Query Data22 10. How to Use MySQL DISTINCT to Eliminate Duplicate Rows25 11. How to Use MySQL LIMIT to Constrain Number Of Returned Records.27 12. Selecting Data with SQL IN29 13. Retrieving Data In Range with SQL BETWEEN.31 14. How to Use MySQL Like Operator to Select data Based On Patterns Matching.33 15. Combining Result Sets By Using MySQL UNION.37 16. MySQL INNER JOIN.39 17. How to Use MySQL LEFT JOIN to Select Data From Multiple Tables42 18. MySQL GROUP BY44 19. MySQL HAVING.47 20. Inserting Data into Database Tables..50 21. Updating Data in Database Tables..52 22. Deleting Records from Tables by Using MySQL Delete.54 23. How to Use MySQL REPLACE to Insert or Update Data.56 24. MySQL Transaction.58 25. MySQL Prepared Statement.61
2|Page
Creating Database
Before doing anything else with data, you need to create a database. A database is a container of data. It stores contact, vendor or customer or any kind of data you can think of. In MySQL, a database is a collection of objects that are used to store and manipulate data such as tables, stored procedures...etc. To create a database in MySQL, you use CREATE DATABASE statement as follows: CREATE DATABASE [IF NOT EXISTS] database_name; Let's examine the CREATE DATABASE statement in a greater details: Followed by CREATE DATABASE statement is database name you want MySQL to create. It is recommended that database name should be meaningful and descriptive. IF NOT EXISTS is an optional part of the statement. The IF NOT EXISTS statement prevents you from error if there is a database with the same name exists in the database catalog. Of course you cannot have 2 databases with the same name in a same database catalog. For example, to create classicmodels database, you just need to execute the CREATE DATABASE statement above as follows: CREATE DATABASE classicmodels; After executing the statement, MySQL will returns you a message to notify the new database created successfully or not.
3|Page
Removing Database
Removing database means you delete the database physically. All the data and related objects inside the database are permanently deleted and cannot be undone. So it is very important to execute this query with cares. To delete a database you can use DROP DATABASE statement, which is a standard SQL statement as well. DROP DATABASE [IF EXISTS] database_name; You need to specify database name after the DROP DATABASE statement. Like CREATE DATABASE statement, IF EXIST is an optional part to prevent you from removing database which does not exist in database catalog. If you want to practice with DROP DATABASE statement, you can first create a new temporary database, make sure that it is created and remove it. The sequence of SQL query to execute is as follows: CREATE DATABASE IF NOT EXISTS temp_database; SHOW DATABASES; DROP DATABASE IF EXISTS temp_database; In this tutorial, you've learned how to create a new database, drop an existing database, select the database you want to work with and list all databases in database catalog.
4|Page
After unzip sampledatabase.zip file, you can load the sample database into MySQL database server.
Aug 7 15:03 hmp Aug 5 13:57 lost+found Aug 5 2008 sampledatabase.sql Aug 15 19:58 share
3. Execute the below command to import the database file. [root@testrhel home]# mysql -u root -p classicmodels<sampledatabase.sql Enter password:
5|Page
6|Page
The most important feature to make all the table types above distinction is transaction-safe or not. Only InnoDB and BDB tables are transaction safe and only MyISAM tables support full-text indexing and searching feature. MyISAM is also the default table type when you create table without declaring which storage engine to use. Here are some major features of each table types:
ISAM
ISAM had been deprecated and removed from version 5.x. All of it functionality entire replace by MyISAM. ISAM table has a hard size 4GB and is not portable.
MyISAM
MyISAM table type is default when you create table. MyISAM table work very fast but not transactionsafe. The size of MyISAM table depends on the operating system and the data file are portable from system to system. With MyISAM table type, you can have 64 keys per table and maximum key length of 1024 bytes.
InnoDB
Different from MyISAM table type, InnoDB table are transaction safe and supports row-level locking. Foreign keys are supported in InnoDB tables. The data file of InnoDB table can be stored in more than one file so the size of table depends on the disk space. Like the MyISAM table type, data file of InnoDB is portable from system to system. The disadvantage of InnoDB in comparison with MyISAM is it take more disk space.
BDB
BDB is similar to InnoDB in transaction safe. It supports page level locking but data file are not portable.
MERGE
Merge table type is added to treat multiple MyISAM tables as a single table so it remove the size limitation from MyISAM tables.
7|Page
HEAP
Heap table is stored in memory so it is the fastest one. Because of storage mechanism, the data will be lost when the power failure and sometime it can cause the server run out of memory. Heap tables do not support columns with AUTO_INCREMENT, BLOB and TEXT characteristics.
8|Page
9|Page
MEDIUMBLOB A medium-sized BLOB LONGBLOB TINYTEXT TEXT A large BLOB A very small non-binary string A small non-binary string
MEDIUMTEXT A medium-sized non-binary string LONGTEXT ENUM SET A large non-binary string An enumeration; each column value may be assigned one enumeration member A set; each column value may be assigned zero or more set members
10 | P a g e
11 | P a g e
The SQL commands can be explained as follows: First we created a table called test_TIMESTAMP. Next we set our time zone to UTC. Then we insert a TIMESTAMP value into the table test_timestamp. Finally we select it to see the value we inserted.
Now can set our time zone to a different time zone and see what value we get from database server:
12 | P a g e
SET time_zone =+03:00; SELECT t1 FROM test_timestamp; +---------------------+ | t1 | +---------------------+ | 2008-01-01 03:00:01 | +---------------------+ 1 row in set (0.00 sec) As you see, we get adjusted value to our new time zone.
CREATE TABLE tbl_name( created_on ); TIMESTAMP DEFAULT 0 changed_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP
So when you insert a new record, just omit two TIMESTAMP columns or set them to NULL. The both created_on and changed_on column will be inserted as the current TIMESTAMP. When you update, omit both TIMESTAMP columns, the changed_on column's value will be automatic updated if there is any change in other columns values. In this tutorial, you've learned how MySQLTIMESTAMP data stored in the MySQL database table and how to use its characteristics to design the created on and last changed on columns.
13 | P a g e
Creating Tables
To create table we use the CREATE TABLE statement. The typical form of SQL CREATE TABLE statement is as follows: CREATE TABLE [IF NOT EXISTS] table_name( column_list ) type=table_type MySQL supports IF NOT EXISTS after CREATE TABLE statement to prevent you from error of creating table which already exists on the database server. table_name is the name of table you would like to create. After that, you can define a set of columns which is usually in this form: column_name data_type(size) [NOT] NULL. You can specify the storage engine type you prefer to use for the table. MySQL supports various storage engines such as InnoDB, MyISAM... If you don't explicit declare storage engine type, MySQL will use MyISAM by default. In our classicmodels sample database, to create employees table, we can use the CREATE TABLE statement as follows: CREATE TABLE employees ( employeeNumber int(11) NOT NULL, lastName varchar(50) NOT NULL, firstName varchar(50) NOT NULL, extension varchar(10) NOT NULL, email varchar(100) NOT NULL, officeCode varchar(10) NOT NULL, reportsTo int(11) default NULL, jobTitle varchar(50) NOT NULL, PRIMARY KEY (employeeNumber) ); First, you specify table name employees after CREATE TABLE statement. Then you list the columns of the table with their attributes such as data type, size, NOT NULL. And finally you specify the primary key of the table, in this case the primary key is employeeNumber. If the table has more than one primary key, you can seperate them by a comma. For example, the payments table has two primary keys customerNumber and checkNumber. You can createpayments table by executing following query:
14 | P a g e
CREATE TABLE payments ( customerNumber int(11) NOT NULL, checkNumber varchar(50) NOT NULL, paymentDate datetime NOT NULL, amount double NOT NULL, PRIMARY KEY (customerNumber,checkNumber) ); It is important to note that by default MySQL uses MyISAM storage engine for the table it created.
15 | P a g e
Deleting Tables
To delete table from the database, you can use DROP TABLE statement: DROP [TEMPORARY] TABLE [IF EXISTS] table_name [, table_name,...]
16 | P a g e
TEMPORARY keyword is used for deleting temporary tables. MySQL allows you to drop multiple tables at once by listing them and separated each by a comma. IF EXISTS is used to prevent you from deleting table which does not exist in the database.
17 | P a g e
18 | P a g e
In this tutorial, you've learned how to use MySQL ALTER TABLE statement to change existing table structure and rename table.
19 | P a g e
Creating Indexes
Usually you create index when creating table. Any column in creating table statement declared as PRIMARY KEY, KEY, UNIQUE or INDEX will be indexed automatically by MySQL. In addition, you can add indexes to the tables which has data. The statement to create index in MySQL is as follows: CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name USING [BTREE | HASH | RTREE] ON table_name (column_name [(length)] [ASC | DESC],...) First you specify the index based on the table types or storage engine: UNIQUE means MySQL will create a constraint that all values in the index must be distinct. Duplicated NULL is allowed in all storage engine except BDB. FULLTEXT index is supported only by MyISAM storage engine and only accepted columns which have data type is CHAR,VARCHAR or TEXT. SPATIAL index supports spatial column and available in MyISAM storage engine. In addition, the column value must not be NULL. Then you name the index using index types such as BTREE, HASH or RTREE also based on storage engine. Here is the list:
20 | P a g e
Finally you declare which column on which table using the index. In our sample database, you can create index to officeCode column on employees table to make the join operation with office table faster. The SQL statement to create index is as follows: CREATE INDEX officeCode ON employees(officeCode)
Removing Indexes
Besides creating index, you can also remove index by using DROP INDEX statement. Interestingly, DROP INDEX statement is also mapped to ALTER TABLE statement. Here is the syntax: DROP INDEX index_name ON table_name For example, if you want to drop index officeCode which we have added to the employees table, just execute following query: DROP INDEX officeCode ON employees
In this tutorial, you've learned how to manage database index of database table in MySQL including creating and removing index.
21 | P a g e
The MySQL SELECT statement also allows you to to view partial data of a table by listing columns' name after the SELECT keyword. This is called projection. For example if you need to view only first name, last name and job title of employee in the employees table, you can use the following query: SELECT lastname,firstname,jobtitle FROM employees
22 | P a g e
WHERE Clause
WHERE clause of the MySQL SELECT statement enables you to select particular rows which match its conditions or search criteria. You use WHERE clause to filter the records based on a certain conditions. For example, you can find the president of company by using the following query: SELECT firstname,lastname,email FROM employees WHERE jobtitle="president"
DISTINCT
With DISTINCT keyword, you can eliminate the duplicate records from the SELECT statement. For example, to find how many job title of all employees in the employees table, you use DISTINCT keyword in SELECT statement as follows:
23 | P a g e
In this tutorial, you've learned about basic MySQL SELECT statement to retrieve data from one database table. You'll learn more about each technique in details in later tutorials.
24 | P a g e
25 | P a g e
SELECT DISTINCT lastname FROM employees ORDER BY lastname +-----------+ | lastname | +-----------+ | Bondur | | Bott | | Bow | | Castillo | | Firrelli | | Fixter | | Gerard | | Hernandez | | Jennings | | Jones | | Kato | | King | | Marsh | | Murphy | | Nishi | | Patterson | | Thompson | | Tseng | | Vanauf | +-----------+ 19 rows in set (0.00 sec) As you can see in the new result set, four duplicate records are eliminated from the list when we used DISTINCT. The DISTINCT keyword can be applied with more than one column. In this case, the combination of all columns are used to define the uniqueness of a record in the return result set. For example, to get all cities and states of customers in the customers table, we can use the following query: SELECT DISTINCT city, state FROM customers
26 | P a g e
+-----------+-----------+ | firstname | lastname | +-----------+-----------+ | Diane | Murphy | | Mary | Patterson | | Jeff | Firrelli | | William | Patterson | | Gerard | Bondur | +-----------+-----------+ 5 rows in set (0.00 sec)
27 | P a g e
Now if you want to get five employees from employee number 10 you can use MySQL LIMIT with offset as follows: SELECT firstname,lastname FROM employees LIMIT 10,5 +-----------+-----------+ | firstname | lastname | +-----------+-----------+ | Foon Yue | Tseng | | George | Vanauf | | Loui | Bondur | | Gerard | Hernandez | | Pamela | Castillo | +-----------+-----------+ 5 rows in set (0.00 sec)
28 | P a g e
29 | P a g e
SELECT officeCode, city, phone FROM offices WHERE country NOT IN ('USA','France') Here is the output of offices which does not in USA and France +------------+--------+------------------+ | officeCode | city | phone | +------------+--------+------------------+ | 5 | Tokyo | +81 33 224 5000 | | 6 | Sydney | +61 2 9264 2451 | | 7 | London | +44 20 7877 2041 | +------------+--------+------------------+ SQL IN is used most often in sub-query. For example, if you want to find out all orders in theorders table which have total cost greater than $60000, we can use SQL IN with sub-query. First to select all the orders which has total cost greater than $60000, you can retrieve it fromorderDetails table as follows: SELECT orderNumber FROM orderDetails GROUP BY orderNumber HAVING SUM(quantityOrdered * priceEach) > 60000 You get all the orders which have total cost greater than $60000 +-------------+----------------+---------+---------------------+ | orderNumber | customerNumber | status | shippedDate | +-------------+----------------+---------+---------------------+ | 10165 | 148 | Shipped | 2003-12-26 00:00:00 | | 10287 | 298 | Shipped | 2004-09-01 00:00:00 | | 10310 | 259 | Shipped | 2004-10-18 00:00:00 | +-------------+----------------+---------+---------------------+
30 | P a g e
Lets practice with several examples of using SQL BETWEEN to search values in a range. Suppose we want to find all products which buy price is in a range of 90$ and 100$, we can perform the following query to do so: SELECT productCode,ProductName,buyPrice FROM products WHERE buyPrice BETWEEN 90 AND 100 ORDER BY buyPrice DESC Here is the output +-------------+--------------------------------------+----------+ | productCode | ProductName | buyPrice | +-------------+--------------------------------------+----------+ | S10_1949 | 1952 Alpine Renault 1300 | 98.58 | | S24_3856 | 1956 Porsche 356A Coupe | 98.3 | | S12_1108 | 2001 Ferrari Enzo | 95.59 | | S12_1099 | 1968 Ford Mustang | 95.34 | | S18_1984 | 1995 Honda Civic | 93.89 | | S18_4027 | 1970 Triumph Spitfire | 91.92 | | S10_4698 | 2003 Harley-Davidson Eagle Drag Bike | 91.02 | +-------------+--------------------------------------+----------+
31 | P a g e
The output contains all products in the range of 90$ and 100$, and if there is a product with buy price 90$ or 100$, it will be included in the output too. In order to find all records which are not in a range we use NOT BETWEEN. To find all products that buy price outside the range of 20 and 100, we can operate following query: SELECT productCode,ProductName,buyPrice FROM products WHERE buyPrice NOT BETWEEN 20 AND 100 +-------------+-------------------------------------+----------+ | productCode | ProductName | buyPrice | +-------------+-------------------------------------+----------+ | S10_4962 | 1962 LanciaA Delta 16V | 103.42 | | S18_2238 | 1998 Chrysler Plymouth Prowler | 101.51 | | S24_2972 | 1982 Lamborghini Diablo | 16.24 | | S24_2840 | 1958 Chevy Corvette Limited Edition | 15.91 | +-------------+-------------------------------------+----------+ The query above is equivalent to the following query SELECT productCode,ProductName,buyPrice FROM products WHERE buyPrice < 20 OR buyPrice > 100 ORDER BY buyPrice DESC
In this tutorial, you've learned how to use SQL BETWEEN to select data from database tables in a range.
32 | P a g e
Chapter 14 How to Use MySQL LIKE to Select Data Based on Patterns Matching
Summary: MySQL provides LIKE operator in SQL standard. The MySQL LIKE operator is commonly used to select data based on patterns matching. Using MySQL LIKE in appropriate way is essential to increase application's performance. In this tutorial, you will learn how to use MySQL LIKE and when to avoid using it to increase the speed of retrieving data from database table. MySQL LIKE allows you to perform pattern matching in your characters column in a database table. MySQL LIKE is often used with SELECT statement in WHERE clause. MySQL provides you two wildcard characters for using with LIKE, the percentage % and underscore _. Percentage (%) wildcard allows you to match any string of zero or more characters Underscore (_) allows you to match any single character.
Lets practice with couples of examples which use MySQL Like with different wildcard characters. Suppose you want to search for employee in employees table who has first name starting with character a, you can do it as follows: SELECT employeeNumber, lastName, firstName FROM employees WHERE firstName LIKE 'a%' +----------------+----------+-----------+ | employeeNumber | lastName | firstName | +----------------+----------+-----------+ | 1611 | Fixter | Andy | +----------------+----------+-----------+ 1 row in set (0.00 sec) MySQL scans the whole employees table to find all employees which have first name starting with character a and followed by any number of characters. To search all employees which have last name ended with on string you can perform the query as follows: SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName LIKE '%on' +----------------+-----------+-----------+ | employeeNumber | lastName | firstName | +----------------+-----------+-----------+ | 1088 | Patterson | William | | 1216 | Patterson | Steve | +----------------+-----------+-----------+ 2 rows in set (0.00 sec)
33 | P a g e
If you know a searched string is embedded somewhere in a column, you can put the percentage wild card at the beginning and the end of it to find all possibilities. For example, if you want to find all employees which have last name containing on string you can execute following query: SELECT employeeNumber, lastName, firstName FROM employees WHERE lastname LIKE '%on%' +----------------+-----------+-----------+ | employeeNumber | lastName | firstName | +----------------+-----------+-----------+ | 1088 | Patterson | William | | 1102 | Bondur | Gerard | | 1216 | Patterson | Steve | | 1337 | Bondur | Loui | | 1504 | Jones | Barry | +----------------+-----------+-----------+ 5 rows in set (0.00 sec) To search all employees whose name are such as Tom, Tim You can use underscore wildcard SELECT employeeNumber, lastName, firstName FROM employees WHERE firstname LIKE ''T_m" +----------------+----------+-----------+ | employeeNumber | lastName | firstName | +----------------+----------+-----------+ | 1619 | King | Tom | +----------------+----------+-----------+ 1 row in set (0.00 sec)
The MySQL LIKE allows you to put the NOT keyword to find all strings which are unmatched with a specific pattern. Suppose you want to search for all employees whose last name are not starting with B, you can use the following query SELECT employeeNumber, lastName, firstName FROM employees WHERE lastName NOT LIKE 'B%'
+----------------+-----------+-----------+ | employeeNumber | lastName | firstName | +----------------+-----------+-----------+ | 1088 | Patterson | William | | 1188 | Firrelli | Julie | | 1216 | Patterson | Steve | | 1286 | Tseng | Foon Yue | | 1323 | Vanauf | George | | 1370 | Hernandez | Gerard | | 1401 | Castillo | Pamela | | 1504 | Jones | Barry | | 1611 | Fixter | Andy | | 1612 | Marsh | Peter | | 1619 | King | Tom | | 1621 | Nishi | Mami |
34 | P a g e
| 1625 | Kato | Yoshimi | | 1702 | Gerard | Martin | +----------------+-----------+-----------+ 14 rows in set (0.00 sec) Be noted that SQL LIKE is not case sensitive so b% and B% are the same. What if you want to search for records which have a field starting with a wildcard character? In this case, you can use ESCAPE to shows that the wildcard characters followed it has literal meaning not wildcard meaning. If ESCAPE does not specify explicitly, the escape character in MySQL by default is \. For example, if you want to find all products which as product code which has _20 embedded on it, you can perform following query. SELECT productCode, productName FROM products WHERE productCode LIKE '%\_20%' +-------------+-------------------------------------------+ | productCode | productName | +-------------+-------------------------------------------+ | S10_2016 | 1996 Moto Guzzi 1100i | | S24_2000 | 1960 BSA Gold Star DBD34 | | S24_2011 | 18th century schooner | | S24_2022 | 1938 Cadillac V-16 Presidential Limousine | | S700_2047 | HMS Bounty | +-------------+-------------------------------------------+ 5 rows in set (0.00 sec) MySQL LIKE gives you a convenient way to find records which have character columns match specified patterns. Because MySQL LIKE scans the whole table to find all the matching records therefore it does not allow database engine to use the index for fast searching. When the data in the table is big enough, the performance of MySQL LIKE will degrade. In some cases you can avoid this problem by using other techniques to achieve the same result as MySQL LIKE. For example, if you want to find all employees which have first name starting with a specified string you can use LEFT function in where clause like the following query: SET @str = 'b'; SELECT employeeNumber, lastName, firstName FROM employees WHERE LEFT(lastname,length(@str)) = @str; It returns the same result as the query below but it faster because we can leverage the index on the column lastname. SELECT employeeNumber, lastName, firstName FROM employees WHERE lastname LIKE 'b%'
And another technique to achieve all string which end with a specified string by using RIGHT function. Suppose we want to retrieve all employees which have last name ended with on string, we can use RIGHT function instead of MySQL LIKE as follows:
35 | P a g e
SET @str = 'on'; SELECT employeeNumber, lastName, firstName FROM employees WHERE RIGHT (lastname,length(@str)) = @str; +----------------+-----------+-----------+ | employeeNumber | lastName | firstName | +----------------+-----------+-----------+ | 1088 | Patterson | William | | 1216 | Patterson | Steve | +----------------+-----------+-----------+ 2 rows in set (0.00 sec)
It returns the same result as the following query SELECT employeeNumber, lastName, firstName FROM employees WHERE lastname LIKE '%on'
36 | P a g e
Like SQL standard, MySQL UNION allows you to combine two or more result sets from multiple tables together. The syntax of using MySQL UNION is as follows: SELECT statement UNION [DISTINCT | ALL] SELECT statement UNION [DISTINCT | ALL] In order to use UNION statement, there are some rules you need to follow: The number of columns in each SELECT statement has to be the same . The data type of the column in the column list of the SELECT statement must be the same or at least convertible. By default the MySQL UNION removes all duplicate rows from the result set even if you dont explicit using DISTINCT after the keyword UNION. If you use UNION ALL explicitly, the duplicate rows remain in the result set. You only use this in the cases that you want to keep duplicate rows or you are sure that there is no duplicate rows in the result set. Lets practice with couples of examples with MySQL UNION to get a better understanding. Suppose you want to combine customers and employees infomation into one result set, you use the following query: SELECT customerNumber id, contactLastname name FROM customers UNION SELECT employeeNumber id,firstname name FROM employees Here is the excerpt of the output: id name ------ --------------103 Schmitt 112 King 114 Ferguson 119 Labrune 121 Bergulfsen 124 Nelson 125 Piestrzeniewicz
37 | P a g e
When using ORDER BY to sort the result with UNION, you have to use it in the last SQL SELECT statement. It would be the best to parenthesize all the SELECT statements and place ORDER BY at the end. Suppose you want to sort the combination of employees and customers in the query above byname and ID in ascending order. (SELECT customerNumber id,contactLastname name FROM customers) UNION (SELECT employeeNumber id,firstname name FROM employees) ORDER BY name,id What will be displayed in the output if we dont use alias for each column in the SELECT statements? MySQL will use the column names of the first SELECT statement as the label of the output. (SELECT customerNumber, contactLastname FROM customers) UNION (SELECT employeeNumber, firstname FROM employees)
MySQL also provides you another option to sort the result set based on column position in the ORDER BY clause as the following query:contactLastname, customerNumber (SELECT customerNumber, contactLastname FROM customers) UNION (SELECT employeeNumber,firstname FROM employees) ORDER BY 2, 1
38 | P a g e
For example, if you join two tables A and B, the MySQL INNER JOIN clause compares each record of the table A with each record of table B to find all pair of records that satisfy the join-condition. When the joincondition are satisfied, column values for each matched pair of record of table A and table B are combined into a returned record. Note that the records on both tables have to match based on the joincondition. If no record on both table A and B matches, the query will return an empty result.
39 | P a g e
Another effective way to avoid column ambiguous is by using table alias. For example, you can give A as the table alias of the table tbl_A and refer to the column M as A.M so you dont have to type again and again the long table name in your SQL statement.
The products table is the master data table that stores all products. Whenever a product is sold, it is stored in the orderDetails table with other information. The link between products table and orderDetails table is productCode. Now, if you want to know what product was sold in which order, you can use the MySQL INNER JOIN clause as follows: SELECT A.productCode, A.productName, B.orderNumber FROM products A INNER JOIN orderDetails B on A.productCode = B.productCode;
40 | P a g e
There are more returned rows that are not listed on this screenshot
The MySQL INNER JOIN clause compares each row of table products and orderDetails table to find a pair of rows that has the same productCode. If a pair of rows that have the same, the product code, product name and order number are combined into a returned row. In this tutorial, you have learned how to use MySQL INNER JOIN to select data from multiple tables. You have also learned how to use table qualifier to avoid column ambiguous error in MySQL INNER JOIN clause.
41 | P a g e
SELECT c.customerNumber, customerName,orderNUmber, o.status FROM customers c LEFT JOIN orders o ON c.customerNumber = o.customerNumber;
42 | P a g e
There are more rows which are not listed on this screenshot.
The left table is the customers table so you see all customers are listed as the way MySQL LEFT JOIN clause works. However, there are rows that we have customer information but all order information are NULL. This means those customers do not have any order in our database. The MySQL LEFT JOIN clause is very useful when you want to find the records in the left table that are unmatched by the right table. You can accomplish this by add a WHERE clause to select only that have NULL values in a right table column. So to find all customers who does not have any order in our database we can use the MySQL LEFT JOIN clause as follows: SELECT c.customerNumber, customerName,orderNUmber, o.status FROM customers c LEFT JOIN orders o ON c.customerNumber = o.customerNumber WHERE orderNumber is NULL
There are more rows which are not listed on this screenshot.
As the result, the query only returns customers which do not have any order represented by NULL values.
In this tutorial, you have learned how to use MySQL LEFT JOIN clause to select data from multiple tables. You've also learned how to use MySQL LEFT JOIN to find unmatched records between two tables.
43 | P a g e
The MySQL GROUP BY clause is used with SQL SELECT statement to to group selected records into a set of summary records by the one or more column's value or expression. The MySQL GROUP BY clause is an optional part of the SQL SELECT statement. The MySQL GROUP BY clause must appear after the WHERE clause or FROM clause if WHERE clause is omitted of the SQL SELECT statement. The MySQL GROUP BY clause consists of GROUP BY keyword followed by a list of expressions separated by commas. The following illustrates the MySQL GROUP BY clause:
SELECT col1_,col_2,... col_n, aggregate_function(expression) FROM table WHERE where_conditions GROUP BY col_1, col_2, ... col_n ORDER BY column_list We will examine the GROUP BY clause in details. Lets take a look at the order table in our sample database.
44 | P a g e
+------------+ | status | +------------+ | Cancelled | | Disputed | | In Process | | On Hold | | Resolved | | Shipped | +------------+ 6 rows in set (0.00 sec)
It seems that the GROUP BY clause only scans for unique occurrences in the status column and return the result set. However if you look at the data of the orders table you will see that each row in result set above is summary of records that represent a group orders that have the same status on the status column.
+------------+----------+ | status | count(*) | +------------+----------+ | Cancelled | 6 | | Disputed | 3 | | In Process | 6 | | On Hold | 4 | | Resolved | 4 | | Shipped | 303 | +------------+----------+ 6 rows in set (0.00 sec) The query counts number of orders for each orders status.
45 | P a g e
SELECT status, count(*) FROM orders GROUP BY status DESC; +------------+----------+ | status | count(*) | +------------+----------+ | Shipped | 303 | | Resolved | 4 | | On Hold | 4 | | In Process | 6 | | Disputed | 3 | | Cancelled | 6 | +------------+----------+ 6 rows in set (0.00 sec)
As you see the status of orders now are in reverse alphabetical order. By default it is ascending order determined by ASC. In this tutorial, you have learned how to use MySQL GROUP BY to retrieve data records in-group. Youve also learned how to sort the result set in the MySQL GROUP BY clause supported only in MySQL.
46 | P a g e
SELECT ordernumber, sum(quantityOrdered) AS itemsCount, sum(priceeach) AS total FROM orderdetails GROUP BY ordernumber
47 | P a g e
Now you can ask what order has total value greater than $1000. In this case, you need to use the MySQL HAVING clause on aggregate to answer that question. SELECT ordernumber, sum(quantityOrdered) AS itemsCount, sum(priceeach) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000
We use column alias for the aggregate sum(priceeach) as total so in the HAVING clause we just have to specify that column alias total instead of typing the aggregate sum(priceeach) again.
48 | P a g e
You can use a complex condition in the MySQL HAVING clause such as OR, AND operators. For example if you want to know what order has total value greater than $1000 and has more than 600 items in it. You can use the following query to find out: SELECT ordernumber, sum(quantityOrdered) AS itemsCount, sum(priceeach) AS total FROM orderdetails GROUP BY ordernumber HAVING total > 1000 AND itemsCount > 600
The MySQL HAVING clause is useful only with the MySQL GROUP BY clause for building output of highlevel reports. For example, you can use the MySQL HAVING clause to answer questions like how many order has total values more than 1000 this month, this quarter and this year?...
In this tutorial, you have learned how to use the MySQL HAVING clause together with the MySQL GROUP BY to specify filter condition on a group or aggregate.
49 | P a g e
INSERT Statement
INSERT statement allows you to insert one or more rows to the table. In MySQL, the INSERT statement forms are listed as follows:
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] table_name [(column_name,...)] VALUES ((expression | DEFAULT),...),(...),... INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] table_name [(column_name,...)] INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] table_name SET column_name=(expression | DEFAULT), ... As you can see INTO in the INSERT statement is optional. In the first form, you insert a new data row into an existing table by specifying the column name and data for each. As an example to insert a new office to the offices table in the sample database you can do as follows: INSERT INTO classicmodels.offices (officeCode, city, phone, addressLine1, addressLine2, state, country, postalCode, territory ) VALUES ('8', 'Boston', '+1 215 837 0825', '1550 dummy street', 'dummy address', 'MA', 'USA', '02107', 'NA' )
50 | P a g e
In the second form, instead of providing explicit data, you select it from other table by using SELECT statement. This form allows you to copy some or some part of data from other table to the inserted table. As an example, we can create a temporary table and insert all offices which locate in US into that one by using this query: INSERT INTO temp_table SELECT * FROM offices WHERE country = 'US' The third form enables you to specify the column you want to insert the data. For example, we have the query like this: INSERT INTO productlines SET productLine = 'Luxury Cars' It means we only insert the data into productLine column in productLines table.
51 | P a g e
SQL UPDATE statement is used to update existing data in database tables. It can be used to change values of single row, group of rows or even all rows in a table. In MySQL, the SQL UPDATE statement form is as below:
UPDATE [LOW_ PRIORITY] [IGNORE] table_name [, table_name...] SET column_name1=expr1 [, column_name2=expr2 ...] [WHERE condition]
Let's examine the MySQL UPDATE statement in details: Followed by the UPDATE keyword is the name of a table you want to change the data. In MySQL, you can change the data of multiple tables at a time. If an UPDATE command violates any integrity constraint, MySQL does not perform the update and it will issue an error message. The SET clause determines the columns' name and the changed values. The changed values could be a constant value, expression or even a subquery. WHERE clause determines which rows of the tables will be updated. It is an optional part of SQL UPDATE statement. If WHERE clause is ignored, all rows in the tables will be updated. The WHERE clause is so important that you should not forget. Sometimes you want to change just one row of a table but you forget WHERE clause so you accidentally update the whole table. LOW_ PRIORITY keyword is used to delay the execution until no other client applications reading data from the table. This is used for controlling the update process in MySQL database server. IGNORE keyword is used to execute the update even errors occurred during the execution. The errors in the update process could be duplicate value on unique column, or new data does not match with the column data type. In the first situation data is not updated and in the second one MySQL tries to convert the data into closest valid values. Let's practice with a couple of examples in our sample database to understand more about SQL UPDATE statement. In employees table, if you want to update the email of Mary Patterson with employeeNumber 1 with the new email as mary-patterso@classicmodelcars.com, you can execute the following query: Make sure we are truly updating the data we select it first to see what the current data looks like.
52 | P a g e
SELECT firstname, lastname, email FROM employees WHERE employeeNumber = 1 +-----------+-----------+--------------------------------+ | lastname | firstname | email | +-----------+-----------+--------------------------------+ | Patterson | Mary | mpatterso@classicmodelcars.com | +-----------+-----------+--------------------------------+ 1 row in set (0.02 sec) Update her email to the new email mary-patterso@classicmodelcars.com UPDATE employees SET email = 'mary-patterso@classicmodelcars.com' WHERE employeeNumber = 1 Execute the select query above again; you will see the email change to the new value. +-----------+-----------+------------------------------------+ | lastname | firstname | email | +-----------+-----------+------------------------------------+ | Patterson | Mary | mary-patterso@classicmodelcars.com | +-----------+-----------+------------------------------------+ 1 row in set (0.00 sec) In this tutorial, you've learned how to use SQL UPDATE statement in MySQL to update data of database tables.
53 | P a g e
To remove all rows or records from a database table you use MySQL DELETE statement. The following illustrates MySQL DELETE statement: DELETE [LOW_PRIORITY] [QUICK] FROM table_name [WHERE conditions] [ORDER BY ...] [LIMIT rows] DELETE [LOW_PRIORITY] [QUICK] table_name[.*] [, table_name[.*] ...] FROM table-references [WHERE where_definition] DELETE [LOW_PRIORITY] [QUICK] FROM table_name[.*] [, table_name[.*] ...] USING table-references [WHERE where_definition]
Let's examine the MySQL DELETE statements in details as below: In the first form of MySQL DELETE statement, followed the DELETE FROM part is the table name where you want to delete records. The WHERE clause specifies condition to limit which rows you want to to remove. If a record meets WHERE condition, it will be removed from the database table permanently. If the WHERE clause is ignored in the MySQL DELETE statement, all rows of the table are deleted. The second form of MySQL DELETE statement, It deletes records from multiple tables which reference to other table. The third form of MySQL DELETE statement is quite similar to the second one except Using keyword is used instead of FROM keyword. Let's have a couple of examples of using MySQL DELETE statement in the sample database. It is recommended that you make a copy of employee table before practicing with the MySQL DELETE statement. Suppose you want to delete all employees in an office with officeNumber is 4, just execute the following query:
54 | P a g e
DELETE FROM employees WHERE officeCode = 4 To delete all employees from all offices, just remove the WHERE condition as follows: DELETE FROM employees It will remove all rows from employees table.
If you want to delete all employee who work for office with officecode 1 and also that office. You can use the second form of MySQL DELETE statement to delete data from multiple tables as follows: DELETE employees,offices FROM employees,offices WHERE employees.officeCode = offices.officeCode offices.officeCode = 1
AND
You can achieve the same above effect by using the third form of DELETE statement as below: DELETE FROM employees,offices USING employees,offices WHERE employees.officeCode = offices.officeCode offices.officeCode = 1
AND
In this tutorial, you've learned various forms of MySQL DELETE statement to delete records from one or multiple database tables.
55 | P a g e
MySQL REPLACE statement is a MySQL extension to SQL standard. MySQL REPLACE works like the INSERT statement with the following rules: If the record being inserting does not exist, MySQL REPLACE will insert a new record. If the record being inserting exists, MySQL REPLACE will delete the old record first and then insert a new record with new values. In order to use MySQL REPLACE you need to have at least both INSERT and DELETE privileges for the table. The first form of MySQL REPLACE statement is similar to the INSERT statement except the keyword INSERT is replaced by the REPLACE keyword as follows:
REPLACE INTO table_name(column_name1,column_name2,) VALUES(value1,value2,) For example if you want to insert a new office into offices table, you use the following query: REPLACE INTO offices(officecode,city) VALUES(8,'San Jose') Note that all values of missing columns in the REPLACE statement will be set to default value. Now if you want to update the inserted office with San Mateo city, we can do it as follows: REPLACE INTO offices(officecode,city) VALUES(8,'San Mateo') You see that two rows affected by the query above because the existing record is deleted and the new record is inserted. The second form of MySQL REPLACE like UPDATE statement as follows: REPLACE INTO table_name SET column_name1 = value1 AND column2 = value2 Note that there is no WHERE clause is specified in the REPLACE statement. For example, if you want to update office in San Mateo with officecode 8 you can do it as follows:
56 | P a g e
The third form of MySQL REPLACE is similar to SQL INSERT INTO SELECT statement as follows: REPLACE INTO table_name1(column_name1,column_name2,) SELECT column_name1, column_name2 FROM table_name2 WHERE where_condition Lets say if we want to copy the office with officecode 1, we can do it as follows: REPLACE INTO offices(officecode, city, phone, addressline1, addressline2, state, country, postalcode, territory) SELECT (SELECT MAX(officecode) + 1 FROM offices), city, phone, addressline1, addressline2, state, country, postalcode, territory FROM offices WHERE officecode = 1
There are several important points you need to know before using MySQL REPLACE statement: If you are developing an application that potentially supports not only MySQL database, try to avoid using MySQL REPLACE because other database management system may not support the REPLACE statement. You can use the combination of INSERT and DELETE statement instead. If you are using MySQL REPLACE in the table which has triggers associate with it and if the deletion of duplicate key happens, the triggers are fired in the following orders: Before insert Before delete After delete After insert
It is preferred using MySQL UPDATE statement to using MySQL REPLACE in case you just want to update data. Because MySQL UPDATE performs faster than MySQL REPLACE.
In this tutorial, you've learned different forms of MySQL REPLACE statement to insert or update data in database tables.
57 | P a g e
Now imagine what would happen to your data if one or more steps above fail because of database failure such as table lock security etc? If the step of adding order items into orderdetails table failed, you would have an empty sale order in your system without knowing it. Your data may not be integrity and the effort you have to spend to fix it is tremendous. How do you solve this problem? Thats why the transaction processing comes to the rescue. MySQL transaction enables you to execute sets of MySQL operations to ensure that the databases never contain the result of partial operations. In the set of operations, if one of them fails, the rollback occurs to restore the database. If no error occurred, the entire set of statements is committed to the database.
58 | P a g e
/ / / / / /
ALTER / DROP DATABASE ALTER / DROP / RENAME / TRUNCATE TABLE DROP INDEX DROP EVENT DROP FUNCTION DROP PROCEDURE
To write the changes into the database within a transaction you use the COMMIT statement. It is important to note that MySQL automatically commit the changes to the database by default. To force MySQL not to commit changes automatically, you need to use the following statement: SET autocommit = 0;
-- start a new transaction start transaction; -- get latest order number select @orderNumber := max(orderNUmber) from orders; -- set new order number set @orderNumber = @orderNumber + 1; -- insert a new order for customer 145 insert into orders( orderNumber, orderDate, requiredDate, shippedDate, status, customerNumber) values(@orderNumber,
59 | P a g e
now(), date_add(now(), INTERVAL 5 DAY), date_add(now(), INTERVAL 2 DAY), 'In Process', 145); -- insert 2 order line items insert into orderdetails( orderNumber, productCode, quantityOrdered, priceEach, orderLineNumber) values(@orderNumber,'S18_1749', 30, '136', 1), (@orderNumber,'S18_2248', 50, '55.09', 2); -- commit changes commit; -- get the new inserted order select * from orders a inner join orderdetails b on a.ordernumber = b.ordernumber where a.ordernumber = @ordernumber;
In this tutorial, youve learned how to use MySQL transaction statements including START TRANSACTION, COMMIT ad ROLLBACK to manage transactions in MySQL to ensure data integrity.
60 | P a g e
PREPARE stmt1 FROM 'SELECT productCode, productName FROM products WHERE productCode = ?'; SET @pc = 'S10_1678'; EXECUTE stmt1 USING @pc; DEALLOCATE PREPARE stmt1;
61 | P a g e
In the above example, first we used PREPARE statement to prepare a statement for execution. We used SQL SELECT statement to retrieve a product from products table for a given product code. We used product code as a place holder. Next we declared product code variable @pc and set it values to S10_1678. Then we use EXECUTE statement to execute the prepared statement product code variable @pc. Finally we used DEALLOCATE PREPARE to release the prepared statement. In this tutorial, youve learned how to use MySQL prepared statement to execute a query with placeholder to improve the speed of the query by taking advantage of client/server binary protocol and make your code more secured.
62 | P a g e