You are on page 1of 45

Database Query Language for Beginners (MySQL)

Table of Contents
Table of Contents ....................................................................................................... 1
BEGINNER’S MODULE (SQL BASIC) ............................................................................ 2
Unit 1: SQL Introduction ............................................................................................ 2
Unit 2: SQL Getting Started ........................................................................................ 3
Unit 3: SQL Syntax .................................................................................................... 4
Unit 4: SQL CREATE DATABASE Statement ................................................................... 5
Unit 5: SQL CREATE TABLE Statement ......................................................................... 5
Unit 6: SQL Constraints .............................................................................................. 7
Unit 7: SQL INSERT Statement ................................................................................... 9
Unit 8: SQL SELECT Statement ................................................................................. 10
Unit 9: SQL WHERE Clause ....................................................................................... 11
Unit 10: SQL AND & OR Operators .............................................................................. 13
Unit 11: SQL IN & BETWEEN Operators ....................................................................... 14
Unit 12: SQL ORDER BY Clause .................................................................................. 15
Unit 13: SQL TOP/LIMIT Clause .................................................................................. 17
Unit 14: SQL DISTINCT Clause (Retrieving Distinct Values) ........................................... 18
Unit 15: SQL UPDATE Statement ................................................................................ 19
Unit 16: SQL DELETE Statement ................................................................................ 20
Unit 17: SQL TRUNCATE TABLE Statement .................................................................. 21
Unit 18: SQL DROP Statement ................................................................................... 21
INTERMEDIARY MODULE (SQL JOINS) ..................................................................... 23
Unit 19: SQL Joining Tables ....................................................................................... 23
Unit 20: SQL INNER JOIN Operation ........................................................................... 23
Unit 21: SQL LEFT JOIN Operation .............................................................................. 24
Unit 22: SQL RIGHT JOIN Operation ........................................................................... 25
Unit 23: SQL FULL JOIN Statement ............................................................................. 26
Unit 24: SQL CROSS JOIN Operation .......................................................................... 27
ADVANCED MODULE (SQL ADVANCED) ..................................................................... 29
Unit 25: SQL UNION Operation .................................................................................. 29
Unit 26: SQL LIKE Operator ....................................................................................... 30
Unit 27: SQL ALTER TABLE Statement ........................................................................ 31
Unit 28: SQL Aliases ................................................................................................. 32
Unit 29: SQL GROUP BY Clause .................................................................................. 34
Unit 30: SQL HAVING Clause ..................................................................................... 35
Unit 31: SQL CREATE VIEW Statement ........................................................................ 35
Unit 32: SQL CREATE INDEX Statement ...................................................................... 37
Unit 33: SQL Dates and Times ................................................................................... 39
Unit 34: SQL Cloning Tables ...................................................................................... 40
Unit 35: SQL Temporary Tables .................................................................................. 41
Unit 36: SQL Subqueries ........................................................................................... 42
Unit 37: SQL Injection .............................................................................................. 43
Unit 38: SQL Functions ............................................................................................. 45

1|Page 45
BEGINNER’S MODULE (SQL BASIC)
Unit 1: SQL Introduction
SQL is a standard language designed for managing data in relational database management
system. SQL stands for Structured Query Language. SQL is a standard programming language
specifically designed for storing, retrieving, managing or manipulating the data inside a relational
database management system (RDBMS). SQL became an ISO standard in 1987. SQL is the most
widely-implemented database language and supported by the popular relational database
systems, like MySQL, SQL Server, and Oracle. However, some features of the SQL standard are
implemented differently in different database systems. SQL was originally developed at IBM in the
early 1970s. Initially it was called SEQUEL (Structured English Query Language) which was later
changed to SQL (pronounced as S-Q-L). Today almost all RDBMS (MySql, Oracle, Infomix, Sybase,
MS Access) use SQL as the standard database query language. SQL is used to perform all types of
data operations in RDBMS.
SQL is used in the accessing, updating, and manipulation of data in a database. Its design
allows for the management of data in an RDBMS, such as MYSQL. SQL language is also used
for controlling data access and for creation and modification of Database schemas (physical
structure). MySQL is a multithreaded, multi-user SQL database management system. It is the
world's second most popular and widely used open source database. It is interesting how
MySQL name was given to this query language. SQL is the short form of Structured Query
Language and currently owned by Oracle. Hence, MySQL is an Oracle-supported Relational
Database Management System (RDBMS) which is based on structured query language. MySQL
supports wide ranges of operating systems most famous of those include Windows, Linux &
UNIX. Although it is possible to develop a wide range of application with MySQL, it is only used
for web applications and online publishing. It is a fundamental part of an open source
enterprise known as LAMP.
SQL is used in the accessing, updating, and manipulation of data in a database while MySQL is
an RDBMS that allows keeping the data that exists in a database organized. SQL is a Structured
Query Language and MySQL is a RDBMS to store, retrieve, modify and administrate a database.
A database is a structured collection of data. It may be anything from a simple shopping list.
MySQL is a relational database management system based on SQL. The application is used for a
wide range of purposes, including data warehousing, e-commerce, and logging applications.
However, the most commonly use of MySQL is for the purpose of a web database.
There are lot more things you can do with SQL:
• You can create a database, tables and insert records in a database.
• You can query or request information from a database.
• You can update or modify records in a database.
• You can delete records from the database.
• You can set permissions or access control within the database for data security.
• You can create views to avoid typing frequently used complex queries.
The list does not end here as you can perform many other database-related tasks with SQL.
You will learn about all of them in detail in upcoming sections. It is important to note that
relational database systems also have their own additional proprietary extensions in addition to
the SQL standard that are available only on their system.
What is Relational Database?
A relational database is a database divided into logical units called tables, where tables are
related to one another within the database. Relational database allows data to be broken down
into logical, smaller, and manageable units for easier maintenance and better performance.
Tables are related to one another through common keys or fields in a relational database
system, that's why even though the desired data may exist in more than one table, you can
easily join multiple tables together to get combined data set using a single query. It is important
2|Page 45
to note that SQL became a standard of the American National Standards Institute (ANSI) in
1986 and International Organization for Standardization (ISO) in 1987. Although, most SQL
codes are not completely portable among different database systems without adjustments.

Difference between SQL, MySQL and SQL Server


SQL is a language which is used to communicate with a relational database. It provides a way
to manipulate and create databases. On the other hand, MySQL and Microsoft SQL Server both
are RDBMSs that use SQL as their standard relational database language. MySQL is available
for free as it is open source whereas SQL server is not open source software.

What is Lamp?
Lamp is a platform used for web development. Lamp uses Linux (as Operating System),
Apache (as web server), MySQL (as database) and PHP (as object-oriented scripting
language). Hence, abbreviated as LAMP.

Basic Terminologies in Structure Query Language


SQL is a standard database language for creating, manipulating and designing relational
database.
a. Query: A query is a request/question expressed in a formal way with intent to get some
result. For example, “SELECT’ is a query used for retrieval of data.
b. Relational Database: Relational database depends on relational data model in which
data is arranged in columns and rows as relation (tables), having unique key in each row.
For example, the table below shows a relation (table) of name Student which stores
Enroll_No, Student_Name, DOB, Gender and Age.
Enroll_No Student_Name DOB Gender Age
1 Falana 06/05/1998 M 19
2 Mabayoje 01/01/1998 M 19
3 Ajayi 11/11/1998 M 18
c. Tuple: Rows of a relation are referred as tuples.
d. Attribute: Columns/fields of a relation are referred as attributes.
e. Degree: The number of attributes in a relation determines the degree of a relation. A
relation with having ‘n’ attributes is said to be a relation of degree n. E.g. Degree of
Student is 5.
f. Cardinality: The number of tuples in a relation determines the cardinality of a relation.
E.g. Cardinality of Student is 3.

Unit 2: SQL Getting Started


As you already know SQL is used to communicate with the database, so before you start
experimenting with SQL, you need access to a database system first. However, to execute
some SQL statement you'll need access to a full-fledged database management system like
MySQL, SQL Server etc.
Setting Up Work Environment for SQL
If you have no DBMS (Database Management System) already installed on your system, you
have several options to choose from. You can install a free, open-source DBMS. MySQL is the
most popular and widely supported open-source database management system. It is very easy
to download and use and available for both Windows and Linux (or UNIX) operating system.
You can download it freely from here https://dev.mysql.com/downloads/mysql/. You can also
install SQL Server Express. It is a free version of Microsoft SQL Server which allows up to
10GB of database storage. You can download the express edition from here
https://www.microsoft.com/en-in/download/details.aspx?id=30438. Alternatively, if you're
planning to develop an application with PHP and MySQL, you can install WampServer or
XAMPP. WampServer is a Windows web development environment. It allows you to create web

3|Page 45
applications with Apache2, PHP and a MySQL database. It will also provide the MySQL
administrative tool PhpMyAdmin to easily manage your databases using a web browser. You
can download it from here http://www.wampserver.com/en/

Unit 3: SQL Syntax


The syntax of SQL is governed by the American National Standards Institute (ANSI) and the
International Organization for Standardization (ISO). There are different categories of
commands or statements used as queries to manipulate data in SQL. These are:
i. Data Defining Language (DDL): DDL provides command for defining relation schemas,
deleting schemas and modifying relation schema i.e. it works on the structure of a relation
schema for e.g. CREATE, ADD, DROP, ALTER, TRUNCATE, RENAME.
ii. Data Manipulation Language (DML): DML provides command to manipulate data in a
table for e.g. INSERT, UPDATE, DELETE.
iii. Data Query Language (DQL): It is used to extract the data from table. For example,
SELECT.
iv. Transaction Control Language (TCL): It is used to manage transactions in database. It
means they are used to manage changes made by DML statements. For example,
COMMIT, ROLLBACK and SAVEPOINT.
v. Data Control Language (DCL): Data control language are the commands to grant and
take back authority from any database user. For example, GRANT and REVOKE
SQL Statements
SQL statements are very simple and straightforward like plain English but with specific syntax.
An SQL statement is composed of a sequence of keywords, identifiers, etc. terminated by a
semicolon (;). Here is an example of a valid SQL statement.
Example
SELECT emp_name, hire_date, salary FROM employees WHERE salary > 5000;
For better readability you can also write the same statement, as follow:
SELECT emp_name, hire_date, salary
FROM employees
WHERE salary > 5000;
Use semicolon at the end of an SQL statement terminates the statement or submits the
statement to the database server. Some database management system has, however, no such
requirement, but it is considered as a best practice to use it. Note: Any number of line breaks
may occur within a SQL statement, provided it does not break off keywords, values,
expression, etc.

Case Sensitivity in SQL


Consider another SQL statement that retrieves the records from employees table:
Example
SELECT emp_name, hire_date, salary FROM employees;
The same statement can also be written, as follow:
select emp_name, hire_date, salary from employees;
SQL keywords are case-insensitive that means SELECT is same as select. But, the database
and table names may case-sensitive depending on the operating system. In general, UNIX or
Linux platforms are case-sensitive, whereas Windows platforms aren't. It is recommended to
write the SQL keywords in uppercase, to differentiate it from other text inside a SQL statement
for a better understanding.

4|Page 45
SQL Comments
A comment is simply a text that is ignored by the database engine. Comments can be used to
provide a quick hint about the SQL statement. SQL supports single-line as well as multi-line
comments. To write a single-line comment, start the line with two consecutive hyphens (--).
Example
-- Select all the employees
SELECT * FROM employees;
However, to write multi-line comments, start the comment with a slash followed by an asterisk
(/*) and end the comment with an asterisk followed by a slash (*/), like this:
Example
/* Select all the employees whose
salary is greater than 5000 */
SELECT * FROM employees
WHERE salary > 5000;

Unit 4: SQL CREATE DATABASE Statement


In this unit, you will learn how to create database in a relational database management system
like, MySQL, SQL Server, etc. using SQL.

Creating a Database
Before doing anything with the data, we must need to create a database first. We are
assuming that you already MySQL available for your use. The SQL CREATE DATABASE
statement is used to create a database. The basic syntax for creating a database is:
CREATE DATABASE database_name;

The following MySQL statement creates a database named demo:


CREATE DATABASE demo;
Creating a database does not select it for use. So, before moving further we must select the
target database with the USE statement. For example, the USE demo; command sets the
demo database as target database for all future commands. If you try to create a database
that is already exists you'll get an error message. To avoid this in MySQL you can use an
optional clause IF NOT EXISTS as follow:
CREATE DATABASE IF NOT EXISTS demo;

Selecting the Database


Type the following command and press enter. Now, our demo database is selected as default
database for all future operations.
USE demo;

SHOW DATABASES on the command


If you want to see a list of existing databases on the MySQL server, you can execute the
statement SHOW DATABASES on the command line.

Unit 5: SQL CREATE TABLE Statement


Here, we will how to create a table (or tuple) on the database server. Now, it's time to create
some tables inside our database that will actually hold the data. A database table simply
organizes the information into rows (or records) and columns (or fields). To create a table,
first select the database name. The SQL CREATE TABLE statement is used to create a table.
The basic syntax for creating a table is:

CREATE TABLE table_name (


5|Page 45
column1_name data_type constraints,
column2_name data_type constraints,
....
);
To understand this syntax easily, let's create a table in our demo database. Type the following
statement on MySQL command-line tool and press enter:
Example
-- Syntax for creating table in an existing Database
CREATE TABLE persons (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL UNIQUE
);
The above statement creates a table named persons with four columns id, name, birth_date
and phone. Notice that each column name is followed by a data type declaration. This
declaration specifies what type of data the column will store, whether integer, string, date, etc.
Some data types can be declared with a length parameter that indicates how many characters
can be stored in the column. For example, VARCHAR(50) can hold up to 50 characters.
Note: The data type of the columns may vary depending on the database system. For
example, MySQL and SQL Server supports INT data type for integer values, whereas the
Oracle database supports NUMBER data type.
The following table summarizes the most commonly used data types supported by MySQL.
Data Type Description
INT Stores numeric values in the range of -2147483648 to 2147483647
DECIMAL Stores decimal values with exact precision.
CHAR Stores fixed-length strings with a maximum size of 255 characters.
VARCHAR Stores variable-length strings with a maximum size of 65,535 characters.
TEXT Stores strings with a maximum size of 65,535 characters.
DATE Stores date values in the YYYY-MM-DD format.
DATETIME Stores combined date/time values in the YYYY-MM-DD HH:MM:SS format.
TIMESTAMP Stores timestamp values. TIMESTAMP values are stored as the number of
seconds since the Unix epoch ('1970-01-01 00:00:01' UTC).
Thereare a few additional constraints (also called modifiers) that are set for the table columns
in the
preceding statement. Constraints define rules regarding the values allowed in columns.
• The NOT NULL constraint ensures that the field cannot accept a NULL value.
• The PRIMARY KEY constraint marks the corresponding field as the table's primary key.
• The AUTO_INCREMENT attribute is a MySQL extension to standard SQL, which tells
MySQL to automatically assign a value to this field if it is left unspecified, by
incrementing the previous value by 1. Only available for numeric fields.
• The UNIQUE constraint ensures that each row for a column must have a unique value.
Note: The Microsoft SQL Server uses the IDENTITY property to perform an auto-increment
feature. The default value is IDENTITY(1,1) which means the seed or starting value is 1, and
the incremental value is also 1.

Create Table If Not Exists


If you try to create a table that is already exists inside the database you'll get an error
message. To avoid this in MySQL you can use an optional clause IF NOT EXISTS as follow:
Example:

6|Page 45
CREATE TABLE IF NOT EXISTS persons (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL UNIQUE
);
If you want to see the list of tables inside the currently selected database, you can execute
SHOW TABLES; statement on the MySQL command line.

Unit 6: SQL Constraints


What is Constraint?
A constraint is simply a restriction placed on one or more columns of a table to limit the type
of values that can be stored in that column. Constraints provide a standard mechanism to
maintain the accuracy and integrity of the data inside a database table. There are several
different types of constraints in SQL, including NOT NULL, PRIMARY KEY, UNIQUE, DEFAULT,
FOREIGN KEY and CHECK
1. NOT NULL Constraint
The NOT NULL constraint specifies that the column does not accept NULL values. This means if
NOT NULL constraint is applied on a column, then you cannot insert a new row in the table
without adding a non-NULL value for that column. The following SQL statement creates a table
named persons with four columns, out of which three columns, id, name and phone do not
accept NULL values.
Example
CREATE TABLE persons2 (
id INT NOT NULL,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
);
Note: A null value or NULL is different from zero (0), blank, or a zero-length character string
such as ''. NULL means that no entry has been made.
2. PRIMARY KEY Constraint
The PRIMARY KEY constraint identifies the column or set of columns that have values that
uniquely identify a row in a table. No two rows in a table can have the same primary key
value. Also, you cannot enter NULL value in a primary key column. The following SQL
statement creates a table named persons3 and specifies the id column as the primary key.
That means this field does not allow NULL or duplicate values. Primary key is used to index the
data inside the table.
Example
CREATE TABLE persons3 (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL
);
The primary key typically consists of one column in a table. However, more than one column
can comprise the primary key, e.g. either the employee's email address or assigned
identification number is the logical primary key for an employee table.

3. UNIQUE Constraint
The UNIQUE constraint restricts one or more columns to contain unique values within a table.
7|Page 45
Although both a UNIQUE constraint and a PRIMARY KEY constraint enforce uniqueness, use a
UNIQUE constraint instead of a PRIMARY KEY constraint when you want to enforce the
uniqueness of a column, or combination of columns, that is not the primary key. The following
SQL statement creates a table named persons4 and specifies the phone column as unique.
That means this field does not allow duplicate values.
Example
CREATE TABLE persons4 (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL UNIQUE
);
Multiple UNIQUE constraints can be defined on a table, whereas only one PRIMARY KEY
constraint can be defined on a table. Also, unlike PRIMARY KEY constraints, the UNIQUE
constraints allow NULL values.
4. DEFAULT Constraint
The DEFAULT constraint specifies the default value for the columns. A column default is some
value that will be inserted in the column by the database engine when an INSERT statement
doesn't explicitly assign a particular value. The following SQL statement creates a default for
the country column in the persons5 table:
Example
CREATE TABLE persons5 (
id INT NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL,
birth_date DATE,
phone VARCHAR(15) NOT NULL UNIQUE,
country VARCHAR(30) NOT NULL DEFAULT 'Nigeria'
);
If you define a table column as NOT NULL, but assign the column a default value, then in the
INSERT statement you don't need to explicitly assign a value for that column in order to insert
a new row in the table.
5. FOREIGN KEY Constraint
A foreign key (FK) is a column or combination of columns that is used to establish and enforce
a relationship between the data in two tables. Here is a sample diagram showing the
relationship between the employees and departments table. If you look at it carefully, you
will notice that the dept_id column of the employees table matches the primary key column
of the departments table. Therefore, the dept_id column of the employees table is the
foreign key to the departments table.

8|Page 45
In MySQL you can create a foreign key by defining a FOREIGN KEY constraint when you create
a table as follow. The following statement establishes a foreign key on the dept_id column of
the employees table that references the dept_id column of the departments table.
Example
CREATE TABLE employees (
emp_id INT NOT NULL PRIMARY KEY,
emp_name VARCHAR(55) NOT NULL,
hire_date DATE NOT NULL,
salary INT,
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

6. CHECK Constraint
The CHECK constraint is used to restrict the values that can be placed in a column. For
example, the range of values for a salary column can be limited by creating a CHECK
constraint that allows values only from 3,000 to 10,000. This prevents salaries from being
entered beyond the regular salary range. Here's an example:
Example
CREATE TABLE employees2 (
emp_id INT NOT NULL PRIMARY KEY,
emp_name VARCHAR(55) NOT NULL,
hire_date DATE NOT NULL,
salary INT NOT NULL CHECK (salary >= 3000 AND salary <= 10000),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id)
);

MySQL does not support SQL check constraint. The CHECK clause is parsed however but
ignored by all storage engines of the MySQL.

Unit 7: SQL INSERT Statement


Inserting Data or Records (Rows) in Table
In the preceding unit, we've created a table named persons in our demo database. Now it's
time to insert some data or records inside our newly created database table. The INSERT INTO
statement is used to insert new rows in a database table.
The basic syntax for inserting record into a table is:
INSERT INTO table_name (column1,column2,...)
VALUES (value1,value2,...);
Here the column1, column2,..., etc. represents the name of the table columns while the
value1, value2,..., and so on represents the corresponding values for these columns.

To insert multiple records simultaneously, the syntax is:


INSERT INTO table_name (column1, column2,…)
VALUES (value11,value12,...),
(value21,value22,...),
….
(valuen1,valuen2,...);
Let's insert some records into the persons table.

9|Page 45
Step 1: View Table Structure
Before adding record, it is a good idea to obtain the information about the table structure.
Executing the following command will display the information about the columns in the persons
table i.e. column name, data type, constraints etc.
DESCRIBE persons;
You can see the column information or structure of any table in MySQL and Oracle database
using the command DESCRIBE table_name;, whereas EXEC sp_columns table_name; in SQL
Server (replace the table_name with actual table name).

Step 2: Adding Records to a Table


The following statement inserts a new row in persons table.
Example
INSERT INTO persons (name, birth_date, phone)
VALUES ('Peju Ademola', '1990-07-15', '08056669090');

You will notice that we didn't insert any value for id field. If you remember from the create
table chapter, the id field was marked with AUTO_INCREMENT flag which tells MySQL to
automatically assign a value to this field if it is left unspecified. Note that non-numeric values
like strings and dates must always be surrounded by quotes while numeric values should never
be enclosed within quotes. Also, if your string itself contains quotes you should escape it with
backslash like 'Let's go'.
Similarly, insert another row into the persons table, as follow:
Example
INSERT INTO persons (name, birth_date, phone)
VALUES ('Bola Aina', '1995-05-01', '08151031259');

To insert one more row into the persons table, in a similar manner:
Example
INSERT INTO persons (name, birth_date, phone)
VALUES ('Bola Aina', '1995-05-01', '08151031259'),
('Felicia Arogundade', '1996-10-17', '09069545450');
Now, if you select the records from persons table, the output will now look like this:
id name birth_date phone
1 Peju Ademola 1990-07-15 08056669090
2 Bola Aina 1995-05-01 08151031259
3 Felicia Arogundade 1996-10-17 09069545450

Unit 8: SQL SELECT Statement


In the previous unit, we've learned how to insert data in a database table. Now it's time to
select the data from existing tables using the SQL query. The SELECT statement is used to
select or retrieve the data from one or more tables. You can use this statement to retrieve all
the rows from a table in one go, as well as to retrieve only those rows that satisfy a certain
condition or a combination of conditions.
The basic syntax for selecting the data from a table is:
SELECT column1_name, column2_name, columnN_name FROM table_name;

Here, column1_name, column2_name, ... are the names of the columns or fields of a database
table whose values you want to fetch. However, if you want to fetch the values of all the
columns available in a table, you can just use the following syntax:
SELECT * FROM table_name;
Exercise/Assignment 1
Create a table named employees in our database that contains the following records:
emp_id emp_name hire_date salary dept_id
10 | P a g e 4 5
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL
Select All from Table
The following statement will return all the rows from the employees table.
Example
SELECT * FROM employees;

After execution, the output is:


emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL
As you can see, it returns all the rows and columns from the employees table. The asterisk (*)
is a wildcard character that means everything. For example, the asterisk character in the
SELECT statement of the example above is a shorthand substitute for all the columns of the
employees table.

Select Columns from Table


If you don't require all the data, you can select specific columns, like this:
Example
SELECT emp_id, emp_name, hire_date, salary
FROM employees;

After executing the above statement, you'll get the output something like this:
emp_id emp_name hire_date salary
1 Enitan Alao 2001-05-01 5000
2 Sola Muraina 2002-07-15 6500
3 Sina Ajayi 2005-10-18 8000
4 Joy Enitan 2007-01-03 7200
5 Bolu Martin 2008-06-24 5600
As you can see this time, there is no dept_id column in the result set. In the next chapter we'll
learn how to select the records from a table based on a condition.

Unit 9: SQL WHERE Clause


Selecting Record Based on Condition
In the previous chapter we've learnt how to fetch all the records from a table or table columns.
But, in real world scenario we generally need to select, update or delete only those records
which fulfil certain condition like users who belongs to a certain age group, or country, etc.
The WHERE clause is used with the SELECT, UPDATE, and DELETE. However, you'll see the use
of this clause with other statements in upcoming units. The WHERE clause is used with the
SELECT statement to extract only those records that fulfill specified conditions. The basic
syntax can be given with:
SELECT column_list FROM table_name WHERE condition;
Here, column_list are the names of columns/fields like name, age, country etc. of a database
table whose values you want to fetch. However, if you want to fetch the values of all the
columns available in a table, you can use the following syntax:
SELECT * FROM table_name WHERE condition;

11 | P a g e 4 5
Now, let's check out some examples that demonstrate how it actually works. We have a table
called employees in our database with the following records:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL

Filter Records with WHERE Clause


The following SQL statement will returns all the employees from the employees table, whose
salary is greater than 7000. The WHERE clause simply filters out the unwanted data.
Example
SELECT * FROM employees
WHERE salary > 7000;
After execution, the output is:
emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
As you can see that the output contains only those employees whose salary is greater than
7000. Similarly, you can fetch records from specific columns, like this:
Example
SELECT emp_id, emp_name, hire_date, salary
FROM employees
WHERE salary > 7000;
After executing the above statement, the output is:
emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
The following statement will fetch the records of an employee whose employee id is 2.
Example
SELECT * FROM employees
WHERE emp_id = 2;
This statement will produce the following output:
emp_id emp_name hire_date salary dept_id
2 Sola Muraina 2002-07-15 6500 1
This time we got only one row in the output, because emp_id is unique for every employee.

Operators Allowed in WHERE Clause


SQL supports a number of different operators that can be used in WHERE clause, the most
important ones are summarized in the following table.
Operator Description Example
= Equal WHERE id = 2
> Greater than WHERE age > 30
< Less than WHERE age < 18
>= Greater than or equal WHERE rating >= 4
<= Less than or equal WHERE price <= 100
LIKE Simple pattern matching WHERE name LIKE 'Dav'
IN Check whether a specified value matches WHERE country IN ('USA', 'UK')
any value in a list or subquery
BETWEEN Check whether a specified value is within WHERE rating BETWEEN 3 AND 5
a range of values

12 | P a g e 4 5
Unit 10: SQL AND & OR Operators
In this tutorial you will learn how to use the AND & OR operators with the WHERE clause to
filter records based on more than one condition.

Selecting Record Based on Condition


In the previous chapter we've learned how to fetch records from a table using a single
condition with the WHERE clause. But sometimes you need to filter records based on multiple
conditions like selecting users whose ages are greater than 30 and country is United States,
selecting products whose price is lower than 100 dollar and ratings is greater than 4, etc.
The AND Operator
The AND operator is a logical operator that combines two conditions and returns TRUE only if
both condition evaluate to TRUE . The AND operator is often used in the WHERE clause of the
SELECT, UPDATE, DELETE statement to form conditions to filter the result set.

SELECT column1_name, column2_name, columnN_name


FROM table_name
WHERE condition1 AND condition2;

Let's check out some examples that demonstrate how it actually works. We have a table called
employees in our database with the following records:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL

Using WHERE Clause with AND Operator


The following SQL statement will return only those employees from the employees table whose
salary is greater than 7000 and the dept_id is equal to 5.
Example
SELECT * FROM employees
WHERE salary > 7000 AND dept_id = 5;
After execution, the output is:
emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5

The OR Operator
Similarly, the OR operator is also a logical operator that combines two conditions, but it
returns TRUE when either of the conditions is TRUE.
The following SQL statement will return all the employees from the employees table whose
salary is either greater than 7000 or the dept_id is equal to 5.
Example
SELECT * FROM employees
WHERE salary > 7000 OR dept_id = 5;

This time, the output is:


emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
Combining AND & OR Operator
You can also combine AND and OR to create complex conditional expressions.
The following SQL statement will return all the employees whose salary is greater than 5000
and the dept_id is either equal to 1 or 5.
Example
SELECT * FROM employees
WHERE salary > 5000 AND (dept_id = 1 OR dept_id = 5);

13 | P a g e 4 5
After executing the above query, the output is:
emp_id emp_name hire_date salary dept_id
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5

Unit 11: SQL IN & BETWEEN Operators


Working with Range and Membership Conditions
In the previous unit, we have learned how to combine multiple conditions using the AND and
OR operators. However, sometimes this is not sufficient and very productive. For example, if
you have to check the values that lie within a range or set of values. And here the IN and
BETWEEN operators comes in picture that lets you define an exclusive range or a set of values
rather than combining the separate conditions.

The IN Operator
The IN operator is logical operator that is used to check whether a particular value exists
within a set of values or not. To do this, the syntax is:
SELECT column_list FROM table_name
WHERE column_name IN (value1, value1,...);

Here, column_list are the names of columns/fields like name, age, country etc. of a database
table whose values you want to fetch. Well, let's check out some examples. Consider the
employees table in our database that has following records:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL
The following SQL statement will return only those employees whose dept_id is either 1 or 3.
Example
SELECT * FROM employees
WHERE dept_id IN (1, 3);
After executing the query, the result is:
emp_id emp_name hire_date salary dept_id
2 Sola Muraina 2002-07-15 6500 1
4 Joy Enitan 2007-01-03 7200 3
Similarly, you can use the NOT IN operator, which is exact opposite of the IN. The following
SQL statement will return all the employees except those whose dept_id is not 1 or 3.
Example
SELECT * FROM employees
WHERE dept_id NOT IN (1, 3);
After executing the query this time, the result is:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
3 Sina Ajayi 2005-10-18 8000 5
The BETWEEN Operator
Sometimes, you want to select a row if the value in a column falls within a certain range. This
type of condition is common when working with numeric data. To perform the query based on
such condition you can utilize the BETWEEN operator. It is a logical operator that allows you to
specify a range to test, as follow:

14 | P a g e 4 5
SELECT column1_name, column2_name, columnN_name
FROM table_name
WHERE column_name BETWEEN min_value AND max_value;
Let's build and perform the queries based upon range conditions on our employees table.

Define Numeric Ranges


The following SQL statement will return only those employees from the employees table,
whose salary falls within the range of 7000 and 9000.
Example
SELECT * FROM employees
WHERE salary BETWEEN 7000 AND 9000;
After execution, the output is:
emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3

Define Date Ranges using CAST() Function


When using the BETWEEN operator with date or time values, use the CAST() function to
explicitly convert the values to the desired data type for best results. For example, if you use a
string such as '2016-12-31' in a comparison to a DATE, cast the string to a DATE. The syntax is:
SELECT * FROM table_name WHERE column_name
BETWEEN CAST('yyyy-mm-dd' AS DATE) AND CAST('yyyy-mm-dd' AS DATE);
Example: The following SQL statement selects all the employees who hired between 1st
January 2006 (i.e. '2006-01-01') and 31st December 2016 (i.e. '2016-12-31'):

SELECT * FROM employees WHERE hire_date


BETWEEN CAST('2006-01-01' AS DATE) AND CAST('2016-12-31' AS DATE);

After executing the query, the result is:


emp_id emp_name hire_date salary dept_id
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL

Define String Ranges


While ranges of dates and numbers are most common, you can also build conditions that
search for ranges of strings. The following SQL statement selects all the employees whose
name beginning with any of the letter between 'O' and 'Z':
Example
SELECT * FROM employees
WHERE emp_name BETWEEN 'O' AND 'Z';
After execution, the output is:
emp_id emp_name hire_date salary dept_id
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5

Unit 12: SQL ORDER BY Clause


This clause orders (or sorts) the result set returned by a SELECT query in SQL. Generally when
you use the SELECT statement to fetch data from a table, the rows in result set are not in any
particular order. If you want your result set in a particular order, you can specify the
ORDER BY clause at the end of the statement which tells the server how to sort the data
returned by the query. The default sorting order is ascending. The ORDER BY clause is used to
sort the data returned by a query in ascending or descending order. The syntax is:
SELECT column_list FROM table_name ORDER BY column_name ASC/DESC;

15 | P a g e 4 5
Here, column_list are the names of columns/fields like name, age, country etc. of a database
table whose values you want to fetch, whereas the column_name is name of the column you
want to sort. Let's check out some examples that demonstrate how it actually works. Consider
the employees table in our database that has following records:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL

Sorting Single Column


The following SQL statement will return all the employees from the employees table and orders
the result set by the emp_name column in ascending order.
Example:
SELECT * FROM employees
ORDER BY emp_name ASC;
You can skip the ASC option and simply use the following syntax. It returns the same result set
as previous statement, because the default sorting order is ascending:
Example
SELECT * FROM employees
ORDER BY emp_name;

After executing the above command, the output is:

emp_id emp_name hire_date salary dept_id


1 Enitan Alao 2001-05-01 5000 4
5 Bolu Martin 2008-06-24 5600 NULL
4 Joy Enitan 2007-01-03 7200 3
3 Sina Ajayi 2005-10-18 8000 5
2 Sola Muraina 2002-07-15 6500 1
Similarly, you can use the DESC option to perform a sorting in descending order. The following
statement will orders the result set by the numeric salary column in descending order.
Example
SELECT * FROM employees
ORDER BY salary DESC;

This time, the result is:


emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
2 Sola Muraina 2002-07-15 6500 1
5 Bolu Martin 2008-06-24 5600 NULL
1 Enitan Alao 2001-05-01 5000 4

Sorting Multiple Columns


You can also specify multiple columns while sorting. However, the change in result set will not
visible until you've some duplicate values in your table. Well, let's find out. To understand the
multi-column sorting in a better way, let us create a table named trainees in our database.

Exercise/Assignment 2
Create a table named trainees with the following records:

id first_name last_name birth_date gender


16 | P a g e 4 5
1 Peter Amiola 1998-03-04 M
2 Henry Alaran 2001-08-30 M
3 Pelumi Paseda 2004-09-19 M
4 Alice Obakoya 1999-07-02 F
5 John Adeyemi 2002-01-15 M
Looking at the table carefully, that we've some duplicate values. However, the full name of the
trainee "Pelumi Amiola" and "Pelumi Paseda" are different but their first names are same. Now,
execute the following command which orders the result set by the first_name column.
Example
SELECT * FROM trainees
ORDER BY first_name;
After execution, the output is:
id first_name last_name birth_date gender
4 Alice Obakoya 1999-07-02 F
2 Henry Alaran 2001-08-30 M
5 John Adeyemi 2002-01-15 M
1 Peter Amiola 1998-03-04 M
3 Pelumi Paseda 2004-09-19 M
Execute this statement which orders the result set by last_name and first_name columns.
Example
SELECT * FROM trainees
ORDER BY last_name, first_name;
The result is:
id first_name last_name birth_date gender
5 John Adeyemi 2002-01-15 M
2 Henry Alaran 2001-08-30 M
1 Peter Amiola 1998-03-04 M
4 Alice Obakoya 1999-07-02 F
3 Pelumi Paseda 2004-09-19 M
Note that when multiple sort columns are specified, the result set is initially sorted by the first
column and then that ordered list is sorted by the second column etc.

Unit 13: SQL TOP/LIMIT Clause


Let us learn how to retrieve fixed number of records from the table. In some situations, you
may not be interested in all of the rows returned by a query. For example, if you just want to
retrieve the top 10 employees who recently joined the organization, get top 3 students by
score or something like that. To handle such situations, you can use SQL's TOP clause in the
SELECT statement. The LIMIT clause is used to achieve this task. The syntax is:
SELECT column_list FROM table_name LIMIT number;
The following statement returns top three highest-paid employees from the employees table.
Example
-- Syntax for MySQL Database
SELECT * FROM employees
ORDER BY salary DESC LIMIT 3;
After execution, the output is:
emp_id emp_name hire_date salary dept_id
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
2 Sola Muraina 2002-07-15 6500 1

17 | P a g e 4 5
Note: In a SELECT statement, always use an ORDER BY clause with the LIMIT clause.
Otherwise, you may not get the desired result.
Setting Row Offset in LIMIT Clause
The LIMIT clause accepts an optional second parameter. When two parameters are specified,
the first parameter specifies the offset of the first row to return i.e. the starting point, whereas
the second parameter specifies the maximum number of rows to return. The offset of the
initial row is 0 (not 1). To find out the third-highest paid employee, you can do the following:
Example
-- Syntax for MySQL Database
SELECT * FROM employees
ORDER BY salary DESC LIMIT 2, 1;
After executing the above command, only one record is in result set:
emp_id emp_name hire_date salary dept_id
2 Sola Muraina 2002-07-15 6500 1

Unit 14: SQL DISTINCT Clause (Retrieving Distinct Values)


Let us learn how to remove duplicate values from a result set. When fetching data from a
database table, the result set may contain duplicate rows or values. If you want to remove
these duplicate values you can specify the keyword DISTINCT directly after the SELECT
keyword, as demonstrated below. The DISTINCT clause is used to remove duplicate rows from
the result set. The syntax is:
SELECT DISTINCT column_list FROM table_name;
Here, column_list is a comma separated list of column or field names of a database table (e.g.
name, age, country, etc.) whose values you want to fetch.
Note: The DISTINCT clause behaves similar to the UNIQUE constraint except in the way it
treats nulls. Two NULL values are considered unique while at the same time they are not
considered distinct from each other.
Exercise/Assignment 3: Create customers table in our database with the following records:

cust_id cust_name city postal_code


1 Maria Adekola Abeokuta 12209
2 Frank Wilson Lagos 28023
3 Demilade Precious Awka 75016
4 Bolu Martin Enugu 10100
5 Thomas Haruna Ekiti 97219
6 Bunmi Akinyera Lagos 28001
Execute the following statement which returns all the rows from the city column of this table.
Example
SELECT city FROM customers;
After execution, the output is:
city
Abeokuta
Lagos
Awka
Enugu
Ekiti
Lagos
If you see the output carefully, you'll find the city "Lagos" appears two times in our result set,
which is not good. Well, let's fix this problem.
Removing Duplicate Data
The following statement uses DISTINCT to generate a list of all city in the customers table.

18 | P a g e 4 5
Example
SELECT DISTINCT city FROM customers;
After executing the above command, you'll get the output something like this:
city
Abeokuta
Lagos
Awka
Enugu
Ekiti
As you see now, there is no duplicate value in the result set. Note that if you use the SELECT
DISTINCT statement for a column that has multiple NULL values, Then SQL keeps one NULL
value and removes others from the result set, because DISTINCT treats all the NULL values as
the same value.

Unit 15: SQL UPDATE Statement


Here, you will learn how to update records in a database table using SQL.
Updating Table Data
In the previous units, we've learnt how to insert data and also select data from a database
table based on various conditions. Now, let us perform one more important task which is
updating the existing records in a database table. That is, changing some values to new ones.
The UPDATE statement is used to update existing data in a table using the syntax:
UPDATE table_name
SET column1_name = value1, column2_name = value2,...
WHERE condition;
Here, column1_name, column2_name,... are the names of the columns or fields of a database
table whose values you want to update. You can also combine multiple conditions using the
AND or OR operators as explained in the earlier unit. Warning: The WHERE clause in the
UPDATE statement specifies which record or records should be updated. If you omit the
WHERE clause, all the records will be updated.
Example: Consider the employees table in our database that has following records:
emp_id emp_name hire_date salary dept_id
1 Enitan Alao 2001-05-01 5000 1
2 Sola Muraina 2002-07-15 6500 5
3 Sina Ajayi 2005-10-18 8000 3
4 Joy Enitan 2007-01-03 7200 4
5 Bolu Martin 2008-06-24 5600 NULL

Updating a Single Column


The following SQL statement will update the emp_name field of the employees table and set a
new value where the employee id i.e. emp_id is equal to 3.
Example
UPDATE employees SET emp_name = 'Sarah Adeyemi'
WHERE emp_id = 3;
After execution, the result is:

emp_id emp_name hire_date salary dept_id


1 Enitan Alao 2001-05-01 5000 1
2 Sola Muraina 2002-07-15 6500 5
3 Sarah Ayeni 2005-10-18 8000 3
4 Joy Enitan 2007-01-03 7200 4
5 Bolu Martin 2008-06-24 5600 NULL

19 | P a g e 4 5
Updating Multiple Columns
Similarly, you can update multiple columns using a list of comma-separated column name and
value pair. The following example will update the salary and dept_id field of an existing
employee in the employees table whose emp_id is 5.
Example
UPDATE employees
SET salary = 6000, dept_id = 2
WHERE emp_id = 5;
After execution, the resulting table will look something like this:

emp_id emp_name hire_date salary dept_id


1 Enitan Alao 2001-05-01 5000 1
2 Sola Muraina 2002-07-15 6500 5
3 Sarah Ayeni 2005-10-18 8000 3
4 Joy Enitan 2007-01-03 7200 4
5 Bolu Martin 2008-06-24 6000 2

Unit 16: SQL DELETE Statement


Here, you will learn how to delete records from a database table using SQL.

Deleting Data from Tables


Just as you insert records into a table with the INSERT statement, you can delete records from
a table as well with the DELETE statement. The syntax is:
The DELETE statement is used to remove one or more rows from a table.
DELETE FROM table_name WHERE condition;

Warning: The WHERE clause in the DELETE statement specifies which record or records
should be deleted. It is however optional, but if you omit or forget the WHERE clause, all the
records will be deleted permanently from the table. Let us delete some records from the
persons table that we have created in create table unit. Suppose that our persons table
currently has the following records:
id name birth_date phone
1 Peju Ademola 1990-07-15 08056669090
2 Bola Aina 1995-05-01 08151031259
3 Felicia Arogundade 1996-10-17 09069545450
4 George Balogun 1993-03-05 08097034214
5 Lukman Alao 1999-08-25 08022556721

Delete Records Based on Conditions


The following statement will delete the rows from persons table where id is greater than 3.
Example
DELETE FROM persons WHERE id > 3;
After executing the query, the persons table will look something like this:
id name birth_date phone
1 Peju Ademola 1990-07-15 08056669090
2 Bola Aina 1995-05-01 08151031259
3 Felicia Arogundade 1996-10-17 09069545450
Note: Refer to SQL WHERE clause to know how to form complex query based on multiple
conditions while deleting the records from the tables.

Delete All Data


Similarly, as mentioned above if you do not specify the WHERE clause in the DELETE
statement all the rows from the table will be deleted. However, the target table itself won't be
deleted that means the table structure, attributes, and indexes will remain intact.
The following statement will remove all the records from the persons table:
20 | P a g e 4 5
Example
DELETE FROM persons;
Now, if you try to select the records from the persons table, you'll get an empty result set.

Unit 17: SQL TRUNCATE TABLE Statement


Removing Table Data
The TRUNCATE TABLE statement removes all the rows from a table more quickly than a
DELETE. Logically, TRUNCATE TABLE is similar to the DELETE statement with no WHERE
clause. The TRUNCATE TABLE statement removes all the rows from a table, but the table
structure and its columns, constraints, indexes, and so on remain intact. To remove the table
definition in addition to its data, you can use the DROP TABLE statement. The syntax is:
TRUNCATE TABLE table_name;
Let's perform the truncate operation on a database table.
Consider we've an employees table in our database with the following records:

emp_id emp_name hire_date salary dept_id


1 Enitan Alao 2001-05-01 5000 4
2 Sola Muraina 2002-07-15 6500 1
3 Sina Ajayi 2005-10-18 8000 5
4 Joy Enitan 2007-01-03 7200 3
5 Bolu Martin 2008-06-24 5600 NULL
The following command removes all the rows from the employees table:
Example
TRUNCATE TABLE employees;

Now, after executing the above SQL statement, if you try to select the records from the
employees table, you will get an empty result set.

TRUNCATE TABLE vs DELETE


Although DELETE and TRUNCATE TABLE seem to have the same effect, but they do work
differently. Here are some major differences between these two statements:
• TRUNCATE TABLE statement drop and re-create the table in such a way that any
auto-increment value is reset to its start value which is generally 1.
• DELETE lets you filter which rows to be deleted based upon an optional WHERE clause,
whereas TRUNCATE TABLE doesn't support WHERE clause it just removes all the rows.
• TRUNCATE TABLE is faster and uses fewer system resources than DELETE, because
DELETE scans the table to generate a count of rows that were affected then delete the
rows one by one and records an entry in the database log for each deleted row, while
TRUNCATE TABLE just delete all the rows without providing any additional information.
Use TRUNCATE TABLE if you just want to delete all the rows and re-create the whole table. Use
DELETE either if you want to delete limited number of rows based on specific condition or you
don't want to reset the auto-increment value.

Unit 18: SQL DROP Statement


Removing a Table from Database
You can use the DROP TABLE statement to easily delete the database tables that you no longer
need. The DROP TABLE statement permanently erases all data from the table, as well as the
metadata that defines the table in the data dictionary. The DROP TABLE removes one or more
tables. The syntax is:
DROP TABLE table1_name, table2_name, ...;
Here, table1_name, table2_name, ... are the names of the tables that you want to delete.

21 | P a g e 4 5
Warning: Dropping a database or table is irreversible. So, be careful while using the DROP
statement, because database system generally do not display any alert like "Are you sure?". It
will immediately delete the database or table and all of its data.
Let us try to remove a database table using the DROP TABLE statement. If you remember
during create table unit, we have created a table persons in our demo database. The following
statement will remove this table permanently from the database.
Example
DROP TABLE persons;
After executing the above command, if you try to perform any operation on the persons table,
like selecting the records from it, you'll get an error message.

Removing Database
Similarly, you can delete a database using the DROP DATABASE statement. The following
command will permanently remove the demo database from the database server.
Example
DROP DATABASE demo;
Now if you try to select the demo database using the USE demo; statement, you'll get an error
message saying "Unknown database" or "Database does not exist".

22 | P a g e 4 5
INTERMEDIARY MODULE (SQL JOINS)
Unit 19: SQL Joining Tables
All the queries you have seen so far have been concentrated on a single table. But in real life
situation you often need to query two or more tables at time and bring a combined result set.
This is technically referred to as a join, since it involves joining different tables, based on a
common field between them (the foreign key) to create new views of the data. To understand
this easily, let's look at the following employees and departments tables. Here, the dept_id
column of the employees table is the foreign key to the departments table. Therefore, these
two tables can be joined to get the combined data.

Note: In order to join tables, data of the columns which are used for joining tables should
match, not necessarily the column names.

Types of Joins
When you join tables, the type of join that you create in your query affects the rows that
appear in the result set. You can create the following types of joins:
1. Inner join
This is a join that returns only those rows that have a match in both joined tables. For
example, you can join the employees and departments tables to create a result set that shows
the department name for each employee. In an inner join, employees for which there is no
department information are not included in the result set, nor are departments with no
employees.
2. Outer join
Outer joins are an extension to inner joins. An outer join returns the rows even if they don't
have related rows in the joined table. There are three types of outer joins: left outer join (or
left join), right outer join (or right join), and full outer join (or full join).
3. Cross join
Cross joins are joins without a join condition. Each row of one table is combined with each row
of another table. This type of result set is called a Cartesian product or cross product. For
example, a cross join between the employees and departments tables yields a result set with
one row for each possible employees/departments combination.

Unit 20: SQL INNER JOIN Operation


In this unit, you will learn how to fetch data from two tables using SQL inner join.

Using Inner Joins


The INNER JOIN is the most common type of join. It returns only
those rows that have a match in both joined tables. The following
Venn diagram illustrates how inner join works.

To understand this easily, let's look at the following employees and departments tables above.

23 | P a g e 4 5
Now, let us say you need to retrieve the id, name, hire date, and the department name of only
those employees who are assigned to a particular department. In real-life scenario, there may be
some employees who are not yet assigned to a department, like the fifth employee "Bolu Martin"
in our employees table. But the issue here is on how to retrieve the data from both the tables in
the same SQL query. To address this issue, if you see the employees table, you will notice that it
has a column named dept_id which holds the ID of the department to which each employee is
assigned. In technical terms, the employees table's dept_id column is the foreign key to the
departments table, and therefore, we will use this column as a link between these two tables.
Example: Let us retrieves the employee's id, name, hiring date and their department by
joining the employees and departments tables together using the common dept_id column. It
excludes those employees who are not assigned to any department. The command is:
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 INNER JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY emp_id;
Tip: When joining tables, prefix each column name with the name of the table it belongs to (e.g.
employees.dept_id, departments.dept_id, or t1.dept_id, t2.dept_id if you're using the table
aliases) in order to avoid confusion and ambiguous column error in case columns in different tables
have the same name. Note: To save time, in place of typing the long table names you can use
table aliases in the query. For example, you can give the employees table an alias name t1 and
refer its column emp_name using t1.emp_name instead of employees.emp_name
After executing the above command, the result is:
emp_id emp_name hire_date dept_name
1 Enitan Alao 2001-05-01 Human Resources
2 Sola Muraina 2002-07-15 Administration
3 Sina Ajayi 2005-10-18 Sales
4 Joy Enitan 2007-01-03 Finance
The above result set contains only those employees for which the dept_id value is present and
that value also exists in the dept_id column of the departments table.

Unit 21: SQL LEFT JOIN Operation


A LEFT JOIN statement returns all rows from the left table along with the rows from the right
table for which the join condition is met. Left join is a type of outer join that's why it is also
referred as left outer join. Other variations of outer join are right join and full join. The
following Venn diagram illustrates how left join works.

Note: An outer join is a join that includes rows in a result set even though there may not be a
match between rows in the two tables being joined. To understand this clearly, let us consider
the employees and departments tables above.
Now, let's say you want to retrieve the id, name and hire date of all the employees along with
the name of their department, irrespective of whether they are assigned to any department or
not. To get such type of result set, we need to apply a left join. The following statement
retrieves employee's id, name, hiring date and their department name by joining the
employees and departments tables together using the common dept_id field. It also includes
those employees who are not assigned to a department.
Example:
24 | P a g e 4 5
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY emp_id;
Tip: In a join query, the left table is the one that appears leftmost in the JOIN clause, and the
right table is the one that appears rightmost.
After executing the above command, the result is:
emp_id emp_name hire_date dept_name
1 Enitan Alao 2001-05-01 Human Resources
2 Sola Muraina 2002-07-15 Administration
3 Sina Ajayi 2005-10-18 Sales
4 Joy Enitan 2007-01-03 Finance
5 Bolu Martin 2008-06-24 NULL

As you can clearly see the left join includes all the rows from the employees table in the result
set, whether or not there is a match on the dept_id column in the departments table.
Note: If there is a row in the left table but no match in the right table, then the associated
result row contains NULL values for all columns coming from the right table.

Unit 22: SQL RIGHT JOIN Operation


The RIGHT JOIN is the exact opposite of the LEFT JOIN. It returns all rows from the right table
along with the rows from the left table for which the join condition is met.
Right join is a type of outer join that's why it is also referred as right outer join. Other
variations of outer join are left join and full join. The following Venn diagram illustrates how
right join works.

Note: An outer join is a join that includes rows in a result set even though there may not be a
match between rows in the two tables being joined. To understand this clearly, let's look at the
employees and departments tables above.
Now, let's say you want to retrieve the names of all departments as well as the details of
employees who're working in that department. But, in real situation there may be some
department in which currently no employee is working. Well, let's find out.
The following statement retrieves all the available departments as well as the id, name, hiring
date of the employees who belongs to that department by joining the employees and
departments tables together using the common dept_id field.
Example:
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 RIGHT JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY dept_name;
Tip: In a join query, the left table is the one that appears leftmost in the JOIN clause, and the
right table is the one that appears rightmost.
After executing the above command, you will get this output:

emp_id emp_name hire_date dept_name

25 | P a g e 4 5
2 Sola Muraina 2002-07-15 Administration
NULL NULL NULL Customer Service
4 Joy Enitan 2007-01-03 Finance
1 Enitan Alao 2001-05-01 Administration
3 Sina Ajayi 2005-10-18 Human Resources

The right join includes all the rows from the departments table in the result set, whether or not
there is a match on the dept_id column in the employees table, as you can clearly see the
department "Customer Service" is included even if there is no employee in this department.
Note: If there is a row in the right table but no match in the left table, then the associated
result row contains NULL values for all columns coming from the left table.

Unit 23: SQL FULL JOIN Statement


A FULL JOIN returns all the rows from the joined tables, whether they are matched or not i.e.
you can say a full join combines the functions of a LEFT JOIN and a RIGHT JOIN. Full join is a
type of outer join that's why it is also referred as full outer join.
The following Venn diagram illustrates how full join works.

Note: An outer join is a join that includes rows in a result set even though there may not be a
match between rows in the two tables being joined.

To understand this clearly, let's look at the employees and departments tables above.
Now, let's say you just want to retrieve the names of all the employees and the names of
available departments, regardless of whether they have corresponding rows in the other table,
in that case you can use a full join as demonstrated below. The following statement retrieves
all the departments as well as the details of all the employees by joining the employees and
departments tables together using the common dept_id field.
Example:
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 FULL JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY emp_name;
Some databases, such as Oracle, MySQL do not support full joins. In that case, you can use
the UNION ALL operator to combine the LEFT JOIN and RIGHT JOIN as follows:
Example:
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id
UNION ALL
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 RIGHT JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY emp_name;
After executing the above command, you'll get the output something like this:

emp_id emp_name hire_date dept_name

26 | P a g e 4 5
NULL NULL NULL Customer Service
1 Enitan Alao 2001-05-01 Human Resources
1 Enitan Alao 2001-05-01 Human Resources
5 Bolu Martin 2008-06-24 NULL
4 Joy Enitan 2007-01-03 Finance
4 Joy Enitan 2007-01-03 Finance
1 Enitan Alao 2001-05-01 Administration
3 Sina Ajayi 2005-10-18 Sales
3 Sina Ajayi 2005-10-18 Sales
2 Sola Muraina 2002-07-15 Administration
2 Sola Muraina 2002-07-15 Administration
As you can see, the result includes all the rows from both the departments and employees
table. Note that in a join query, the left table is the one that appears leftmost in the JOIN
clause, and the right table is the one that appears rightmost. Also, when performing outer
joins, wherever the DBMS (Database Management System) can't match any row, it places
NULL in the columns to indicate data do not exist.

Unit 24: SQL CROSS JOIN Operation


If you don't specify a join condition when joining two tables, database system combines each
row from the first table with each row from the second table. This type of join is called a cross
join or a Cartesian product. The following Venn diagram illustrates how cross join works.

To understand this easily, let's look at the following employees and departments tables. The
number of rows in a cross join is the product of the number of rows in each table. Here's a
simple example of a cross join operation.
Example:
SELECT t1.emp_id, t1.emp_name, t1.hire_date, t2.dept_name
FROM employees AS t1 CROSS JOIN departments AS t2;
Tip: A cross join creates a Cartesian product or multiplication of all rows in one table with all
rows in another. So, for example, if one table has 5 rows and another has 10 rows, a cross-
join query produces 50 rows, the product of 5 and 10.
After executing the above command, you get the result set something like this:

emp_id emp_name hire_date dept_name

27 | P a g e 4 5
1 Enitan Alao 2001-05-01 Administration
2 Sola Muraina 2002-07-15 Administration
3 Sina Ajayi 2005-10-18 Administration
4 Joy Enitan 2007-01-03 Administration
5 Bolu Martin 2008-06-24 Administration
1 Enitan Alao 2001-05-01 Customer Service
2 Sola Muraina 2002-07-15 Customer Service
3 Sina Ajayi 2005-10-18 Customer Service
4 Joy Enitan 2007-01-03 Customer Service
5 Bolu Martin 2008-06-24 Customer Service
1 Enitan Alao 2001-05-01 Finance
2 Sola Muraina 2002-07-15 Finance
3 Sina Ajayi 2005-10-18 Finance
4 Joy Enitan 2007-01-03 Finance
5 Bolu Martin 2008-06-24 Finance
1 Enitan Alao 2001-05-01 Human Resources
2 Sola Muraina 2002-07-15 Human Resources
3 Sina Ajayi 2005-10-18 Human Resources
4 Joy Enitan 2007-01-03 Human Resources
5 Bolu Martin 2008-06-24 Human Resources
1 Enitan Alao 2001-05-01 Sales
2 Sola Muraina 2002-07-15 Sales
3 Sina Ajayi 2005-10-18 Sales
4 Joy Enitan 2007-01-03 Sales
5 Bolu Martin 2008-06-24 Sales
As you can see a cross join is not as useful as the other joins that we've covered in the
previous chapters. Since the query didn't specify a join condition, each row from the
employees table is combined with each row from the departments table. Therefore, unless you
are sure that you want a Cartesian product, don't use a cross join.

28 | P a g e 4 5
ADVANCED MODULE (SQL ADVANCED)
Unit 25: SQL UNION Operation
In this unit, you will learn how to combine the results of two or more SQL queries.

The UNION Operator


The UNION operator is used to combine the results of two or more SELECT queries into a
single result set. The union operation is different from using joins that combine columns from
two tables. The union operation creates a new table by placing all rows from two source tables
into a single result table, placing the rows on top of one another.
These are basic rules for combining the result sets of two SELECT queries by using UNION:
• The number and the order of the columns must be the same in all queries.
• The data types of the corresponding columns must be compatible.
When these criteria are met, the tables are union-compatible:
The basic syntax of UNION is:
SELECT column_list FROM table1_name
UNION SELECT column_list FROM table2_name;
To understand the union operation in a better way, let's assume that some hypothetical fields,
like first_name and last_name exists in our employees2 and customers2 tables. Please note
that these fields do not actually exist in our demo database tables.

Let's perform a union operation to combine the results of two queries.


Example: The following statement returns the first and last names of all the customers2 and
employees2:
SELECT first_name, last_name FROM employees2
UNION
SELECT first_name, last_name FROM customers2;
After executing the above statement, the result is:
first_name last_name
Nathaniel Nola
Anthony Mafoya
Sarah Ayeni
Ronke Ladega
Yinka Busari
Balqis Ayinla
Fatai Adeiye
Gbemisola Oduntan
Fope Buraimo
The UNION operation eliminates the duplicate rows from the combined result set, by default.
That's why the above query returns only 9 rows, because if you notice the name "Yinka Busari"
appears in both the employees2 and customers2 tables. However, if you want to keep the
duplicate rows you can use the ALL keyword, as follow:
Example
SELECT first_name, last_name FROM employees2
UNION ALL
SELECT first_name, last_name FROM customers2;
29 | P a g e 4 5
Unit 26: SQL LIKE Operator
In this unit, you will learn how to retrieve the data based on a partial match.
Pattern Matching
So far, you've seen the conditions that identify an exact string, e.g. WHERE name='Lois Lane'.
But in SQL you can perform partial or pattern matching too using the LIKE operator.
The LIKE operator provides a measure of pattern matching by allowing you to specify wildcards
for one or more characters. You can use the following two wildcard characters:
• The percent sign (%) — Matches any number of characters, even zero characters.
• The underscore (_) — Matches exactly one character
Here're some examples that show how to use the LIKE operator with wildcards.
Statement Meaning Values Returned
WHERE name LIKE 'Da%' Find names beginning with Da David, Dare
WHERE name LIKE '%th' Find names ending with th Elizabeth, Smith
WHERE name LIKE '%on%' Find names containing the on Davidson, Tony
WHERE name LIKE 'Sa_' Find names beginning with Sa and is followed by at Sam
most one character
WHERE name LIKE '_oy' Find names ending with oy and is preceded by at Joy, Roy
most one character
WHERE name LIKE '_am_' Find names containing an and begins and ends with Damilola,
at most one character Tamilore
WHERE name LIKE '%ar_' Find names containing ar, begins with any number Richard,
of characters, and ends with at most one character Karounwi
WHERE name LIKE '_ar%' Find names containing ar, begins with at most one Karounwi,
character, and ends with any number of characters Mariam

Let's put the statements we've discussed above into real use by searching some records.
Consider the employees2 table in our database following records:
emp_id emp_name hire_date salary dept_id
1 Nathaniel Nola 2001-05-01 5000 4
2 Anthony Mafoya 2002-07-15 6500 1
3 Sarah Ayeni 2005-10-18 8000 5
4 Ronke Ladega 2007-01-03 7200 3
5 Yinka Busari 2008-06-24 5600 NULL
6 simeon bamiro 2009-04-01 6000 1
Example: Let try to find out all from employees2 table whose name begins with S letter.
SELECT * FROM employees2
WHERE emp_name LIKE 'S%';
After executing the query, the output is:
emp_id emp_name hire_date salary dept_id
3 Sarah Ayeni 2005-10-18 8000 5
6 simeon bamiro 2009-04-01 6000 1

In MySQL nonbinary string (CHAR, VARCHAR, TEXT) comparisons are case-insensitive by


default, whereas binary strings (BINARY, VARBINARY, BLOB) comparisons are case-sensitive.
This means that if you search with WHERE name LIKE 'S%', you get all column values that
start with S or s (as you can see we've got both "Sarah" and "simeons"). However, if you want
to make this search case sensitive you can use the BINARY operator as follow:
Example
-- Syntax for MySQL Database
SELECT * FROM employees2
WHERE BINARY emp_name LIKE 'S%';
Now, this statement will return only those employees2 whose name starts with capital S letter:
emp_id emp_name hire_date salary dept_id
3 Sarah Ayeni 2005-10-18 8000 5

30 | P a g e 4 5
If you want a column always to be treated in case-sensitive fashion, declare it with a case
sensitive or binary collation to avoid any performance issue. Partial matches are useful when you
don't know the exact form of the string for which you're searching. You can also use partial
matching to retrieve multiple rows that contain similar strings in one of the table's columns.

Unit 27: SQL ALTER TABLE Statement


In this unit, let us learn how to alter or modify an existing table using SQL.
Modifying Existing Tables
It is quite possible that after creating a table, as you start using it, you may discover you've
forgot to mention any column or constraint or specified a wrong name for the column. In such
situation you can use the ALTER TABLE statement to alter or change an existing table by
adding, changing, or deleting a column in the table. Let us create a shippers table in our
database, whose structure is as follows:
Field Type Null Key Default Extra
shipper_id int NO PRI NULL auto_increment
shipper_name varchar(60) NO NULL
phone varchar(60) NO NULL
We will use this shippers table for all of our ALTER TABLE statements. Let us see how we can
expand the existing shippers table by adding one more column.
Adding a New Column
The basic syntax for adding a new column is:
ALTER TABLE table_name ADD column_name data_type constraints;
The following statement adds a new column mobile_no to the shippers table.
Example
ALTER TABLE shippers ADD mobile_no VARCHAR(20);
Now, after executing the above statement if you see the table structure using the command
DESCRIBE shippers; on MySQL command-line, it looks as follow:
Field Type Null Key Default Extra
shipper_id int NO PRI NULL auto_increment
shipper_name varchar(60) NO NULL
phone varchar(60) NO NULL
Mobile_no varchar(20) YES NULL
Note: If you want to add a NOT NULL column to an existing table, then you must specify an
explicit default value. This default value is used to populate the new column for every row that
already exists in your table. When adding a new column to the table, if neither NULL nor NOT
NULL is specified, the column is treated as though NULL had been specified.
MySQL add new columns at the end by default. However, if you want to add a new column
after a specific column you can use the AFTER clause, as follow:
ALTER TABLE shippers ADD mobile_no VARCHAR(20) AFTER shipper_name;
MySQL provide another clause FIRST that you can use to add a new column at first place
within a table. Just replace the clause AFTER with FIRST in the previous example to add the
column mobile_no at the beginning of the shippers table.

Changing Column Position


In MySQL, if you have already created a table but unhappy with the existing column position
within the table, you can change it any time using the following syntax:
ALTER TABLE table_name
MODIFY column_name column_definition AFTER column_name;

31 | P a g e 4 5
The following statement place the column mobile_no after shipper_name column in shippers
table.
ALTER TABLE shippers MODIFY mobile_no VARCHAR(20) AFTER shipper_name;

Adding Constraints
Our current shippers table has one major problem. If you insert records with duplicate phone
numbers, it wouldn't stop you from doing that which is not good. It should be unique. You can
fix this by adding a constraint UNIQUE to the phone column. The basic syntax for adding this
constraint to existing table columns can be given with:
ALTER TABLE table_name ADD UNIQUE (column_name,...);
The following statement adds a constraint UNIQUE to the phone column.
ALTER TABLE shippers ADD UNIQUE (phone);
After executing this statement, if you try to insert a duplicate phone number, you will get an
error. Similarly, if you've created a table without a PRIMARY KEY, you can add one with:
ALTER TABLE table_name ADD PRIMARY KEY (column_name,...);
The following statement adds a constraint PRIMARY KEY to the shipper_id column, if not
defined.
ALTER TABLE shippers ADD PRIMARY KEY (shipper_id);

Removing Columns
The basic syntax for removing a column from an existing table is:
ALTER TABLE table_name DROP COLUMN column_name;
The following statement removes our newly added column mobile_no from the shippers table.
ALTER TABLE shippers DROP COLUMN mobile_no;
Now, after executing the above statement if you see the table structure, it looks as follow:
Field Type Null Key Default Extra
shipper_id int NO PRI NULL auto_increment
shipper_name varchar(60) NO NULL
phone varchar(60) NO NULL

Changing Data Type of a Column


You can modify the data type of a column in MySQL using MODIFY clause. The syntax is:
ALTER TABLE table_name MODIFY column_name new_data_type;
The following statement changes the current data type of the phone column in our shippers
table from VARCHAR to CHAR and length from 20 to 15.
ALTER TABLE shippers MODIFY phone CHAR(15);
Similarly, you can use the MODIFY clause to switch between whether a column in the MySQL
table should allow null values or not by re-specifying the existing column definition and add the
NULL or NOT NULL constraint at the end. For example,
ALTER TABLE shippers MODIFY shipper_name CHAR(15) NOT NULL;
Renaming Tables
The basic syntax for renaming an existing table in MySQL is:
ALTER TABLE current_table_name RENAME new_column_name;
The following statement renames our shippers table shipper.
ALTER TABLE shippers RENAME shipper;
You can also achieve the same thing in MySQL using the RENAME TABLE statement, as follow:
RENAME TABLE shippers TO shipper;
Unit 28: SQL Aliases
32 | P a g e 4 5
In this unit, you will learn how to specify a short alias name for a table or a table column
within an SQL statement.
Defining Table Aliases
When multiple tables are being joined in a single query, you need to prefix each column name
with the name of the table it belongs to, like employees2.dept_id, departments.dept_id, etc. in
order to avoid the confusion and ambiguous column error in case columns in different tables
have the same name. But, if table names are long and appears several times in the query then
writing the query would become a difficult and annoying task. So to save time and avoid
writing the complete table names, you can give each table a short alias name and refer to its
columns using that alias name in the query.
To understand this clearly, let's look at the following employees2 and departments tables.

Here is a query that retrieves the employee's id, name and their department name by joining
the employees2 and departments tables together using the common dept_id field.
Example
SELECT employees2.emp_id, employees2.emp_name, departments.dept_name
FROM employees2 LEFT JOIN departments
ON employees2.dept_id = departments.dept_id ORDER BY emp_id;
Here is the compact version of the previous query that uses table aliases:
Example
SELECT t1.emp_id, t1.emp_name, t2.dept_name
FROM employees2 AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id ORDER BY emp_id;
If you execute any of these statements, you'll get the same output, as follow:
emp_id emp_name dept_name
1 Nathaniel Nola Human Resources
2 Anthony Mafoya Administration
3 Sarah Ayeni Sales
4 Ronke Ladega Finance
5 Yinka Busari NULL
As you can see how much typing effort we can save by using the table aliases.
Defining Aliases for Table Columns
In MySQL, when you use the SQL function to generate a customized output, the name of the
output column might not be human readable or very difficult to understand. In that case, you
can use the aliases to temporarily give a different name to the output column. Consider the
following query in which we've used an expression to reformat the dates in the hire_date
column for generating a custom output:
Example
-- Syntax for MySQL Database
SELECT emp_name, DATE_FORMAT(hire_date, '%M %e, %Y') FROM employees2;
If you execute the above statement, the output is:

emp_name DATE_FORMAT(hire_date, '%M %e, %Y')


Nathaniel Nola May 1, 2001

33 | P a g e 4 5
Anthony Mafoya July 15, 2002
Sarah Ayeni October 18, 2005
Ronke Ladega January 3, 2007
Yinka Busari June 24, 2008

As you can see, the label of the last column in our output is long and unwieldy. We can fix this
problem using the column aliases as follows:
Example
-- Syntax for MySQL Database
SELECT emp_name, DATE_FORMAT(hire_date, '%M %e, %Y') AS hire_date
FROM employees2;
If you execute the above statement, you will get more readable output below:

emp_name hire_date
Nathaniel Nola May 1, 2001
Anthony Mafoya July 15, 2002
Sarah Ayeni October 18, 2005
Ronke Ladega January 3, 2007
Yinka Busari June 24, 2008

Note: You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the
column. However, aliases in a WHERE clause is not allowed.

Unit 29: SQL GROUP BY Clause


In this unit, you will learn how to group rows based on column values.
Grouping Rows
The GROUP BY clause is used in conjunction with the SELECT statement and aggregate
functions to group rows together by common column values. To understand this easily, let's
look at the following employees2 and departments tables.

Now, let's say instead of finding just name of the employees2 and their departments, you want
to find out the total number of employees2 in every department. In case of small tables, you
can simply apply the left join and count the number of employees, but suppose if a table
contains thousands of employees, then it wouldn't be so easy. In this situation, you can use
the GROUP BY clause with the SELECT statement.
Example
SELECT t1.dept_name, count(t2.emp_id) AS total_employees2
FROM departments AS t1 LEFT JOIN employees2 AS t2
ON t1.dept_id = t2.dept_id
GROUP BY t1.dept_name;
If you execute the above statement, the output is:

dept_name total_employees2
Administration 1

34 | P a g e 4 5
Customer Service 0
Finance 1
Human Resources 1
Sales 1

Note: The GROUP BY clause must appear after the FROM and WHERE clauses, and before the
ORDER BY in a SQL SELECT statement.

Unit 30: SQL HAVING Clause


In this unit, let us learn how to filter the groups returned by a GROUP BY clause. That is, how
to specify a search condition for a group or an aggregate using the HAVING clause with the
GROUP BY clause.

Filtering the Groups Based on Condition


The HAVING clause is typically used with the GROUP BY clause to specify a filter condition for a
group or an aggregate. The HAVING clause can only be used with the SELECT statement. To
understand this easily, let's look at the following employees2 and departments tables.

Now, let's say instead of finding just name of the employees2 and their departments, you want
to find out the names of those departments in which there are no employees2. In case of small
tables you can simply apply the left join and check each department manually, but suppose if a
table contains thousands of employees2 then it wouldn't be so easy. In this situation you can
use the HAVING clause with the GROUP BY clause, like this:
Example
SELECT t1.dept_name, count(t2.emp_id) AS total_employees2
FROM departments AS t1 LEFT JOIN employees2 AS t2
ON t1.dept_id = t2.dept_id
GROUP BY t1.dept_name
HAVING total_employees2 = 0;
If you execute the above statement, the output is:
dept_name total_employees2
Customer Service 0

A HAVING clause is similar to a WHERE clause, but applies only to groups as a whole, whereas
the WHERE clause applies to individual rows. Note: A SELECT query can contain both a WHERE
and a HAVING clause, but in that case the WHERE clause must appear before the GROUP BY
clause, whereas the HAVING clause must appear after it but before the ORDER BY clause.

Unit 31: SQL CREATE VIEW Statement


In this unit, you will learn how to create, update, and delete a view in MySQL.
Creating Views to Simplify Table Access
A view is a virtual table whose definition is stored in the database. But, unlike tables, views do not
actually contain any data. Instead, it provides a way to store commonly used complex queries in
the database. However, you can use the view in a SQL SELECT statement to access the data just
as you would use a normal or base table. Views can also be used as a security mechanism by

35 | P a g e 4 5
allowing users to access data through the view, rather than giving them direct access to the entire
base tables. Views are created using the CREATE VIEW statement. The syntax is:
CREATE VIEW view_name AS select_statement;
To understand this clearly, let's look at the following employees2 and departments tables.

Suppose that you want retrieve the id and name of the employees2 along with their
department name then you need to perform the left join operation, as follow:
Example
SELECT t1.emp_id, t1.emp_name, t2.dept_name
FROM employees2 AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id;
Once you execute the above query, the output is:
emp_id emp_name dept_name
1 Nathaniel Nola Human Resources
2 Anthony Mafoya Administration
3 Sarah Ayeni Sales
4 Ronke Ladega Finance
5 Yinka Busari NULL

But, whenever you want to access this record, you need to type the whole query again. If you
perform such operations quite often, it becomes really inconvenient and annoying. In such
situation you can create a view to make the query results easier to access, as follow:
Example
CREATE VIEW emp_dept_view AS
SELECT t1.emp_id, t1.emp_name, t2.dept_name
FROM employees2 AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id;
Now you can access the same records using the view emp_dept_view, like this:
Example
SELECT * FROM emp_dept_view;
You can see how much time and effort you can save with the views. A view always shows up-
to-date data! The database engine executes the SQL query associated with the view and
recreates the data, every time a view is queried. Note that in MySQL you can also specify the
ORDER BY clause in a view definition. But, in SQL Sever a view definition cannot contain an
ORDER BY clause, unless there is also a TOP clause in the select list of the SELECT statement.

Replacing an Existing View


In MySQL, if you want to update or replace an existing view, you can either drop that view and
create a new one or just use the OR REPLACE clause in CREATE VIEW statement, as follow:
CREATE OR REPLACE VIEW view_name AS select_statement;
When the OR REPLACE clause is used in CREATE VIEW statement, it will create a new view if
the view does not exist, otherwise replaces an existing view.

36 | P a g e 4 5
The following SQL statement will replace or change the definition of the existing view
emp_dept_view by adding a new column salary to it.
Example
-- Syntax for MySQL Database
CREATE OR REPLACE VIEW emp_dept_view AS
SELECT t1.emp_id, t1.emp_name, t1.salary, t2.dept_name
FROM employees2 AS t1 LEFT JOIN departments AS t2
ON t1.dept_id = t2.dept_id;
Example
SELECT * FROM emp_dept_view ORDER BY emp_id;
The result is:

emp_id emp_name salary dept_name


1 Nathaniel Nola 5000 Human Resources
2 Anthony Mafoya 6500 Administration
3 Sarah Ayeni 8000 Sales
4 Ronke Ladega 7200 Finance
5 Yinka Busari 5600 NULL

Updating Data Through a View


Theoretically, you can also perform INSERT, UPDATE, and DELETE on views in addition to the
SELECT statement. However, not all views are updatable i.e. capable of modifying the data of
an underlying source table. There are some restrictions on the updatability.
Generally a view is not updatable if it contains any of the following:
• The DISTINCT, GROUP BY or HAVING clauses.
• Aggregate functions such as AVG(), COUNT(), SUM(), MIN(), MAX(), and so forth.
• The UNION, UNION ALL, CROSSJOIN, EXCEPT or INTERSECT operators.
• Subquery in the WHERE clause that refers to a table in the FROM clause.
If a view satisfies these conditions, you can modify the source table using that view.
The following statement will update the salary of the employee whose emp_id is equal to 1.
Example
UPDATE emp_dept_view SET salary = '6000'
WHERE emp_id = 1;
Note: For insert ability, the view must contain all columns in the base table that do not have a
default value. Similarly, for updatability each updatable column in the view must correspond to
an updatable column in a source table.

Dropping a View
Similarly, if you no longer need a view, you can use the DROP VIEW statement to drop it from
the database, as shown in the following syntax:
DROP VIEW view_name;
Example: The following command will drop the view emp_dept_view from the database.
DROP VIEW emp_dept_view;

Unit 32: SQL CREATE INDEX Statement


What is Index?
An index is a data structure associated with a table that provides fast access to rows in a table
based on the values in one or more columns (the index key). Indexes are created on tables to
improve the database performance.

37 | P a g e 4 5
Example: Assuming you have a customers2 table in your database and you want to find out
all the customers whose names begin with the letter A.
SELECT cust_id, cust_name, address FROM customers2
WHERE cust_name LIKE 'A%';
To find such customers2, server must scan each row one by one in the customers2 table and
inspect the contents of the name column. While it works fine for a table having few rows, but
imagine how long it might take to answer the query if the table contains millions of rows. In
such situation you can speed things up by applying indexes to the table.

Creating an Index
You can create indexes with the CREATE INDEX statement:
CREATE INDEX index_name ON table_name (column_name);
Example: Create an index on the name column in the customers table.
CREATE INDEX cust_name_idx ON customers2 (cust_name);
By default, the index will allow duplicate entries and sort the entries in ascending order. To
require unique index entries, add the keyword UNIQUE after CREATE, like this:
Example
CREATE UNIQUE INDEX cust_name_idx
ON customers2 (cust_name);
In MySQL, you can look at the available indexes on a specific table like this:
SHOW INDEXES FROM customers2 \G
Note: Terminate a SQL statement with \G instead of semicolon (;) to display the result
vertically rather than normal tabular format if they are too wide for the current window.

Creating Multi-column Indexes


You can also build the indexes that span multiple columns. For example, suppose you've a
table in your database named users having the columns first_name and last_name, and you
frequently access the user's records using these columns then you can build an index on both
the columns together to improve the performance.
Example:
CREATE INDEX user_name_idx ON users (first_name, last_name);
Note: You can consider a database index as index section of a book that helps you quickly find
or locate a specific topic within the book.

The Disadvantages of Indexes


Index should be created with care. Because, every time a row is added, updated or removed
from a table, all indexes on that table must be modified. Therefore, the more indexes you
have, the more work the server needs to do, which finally leads to slower performance.
Here are some basic guidelines that you can follow while creating index:
• Index columns that you frequently use to retrieve the data.
• Don't create indexes for columns that you never use as retrieval keys.
• Index columns that are used for joins to improve join performance.
• Avoid columns that contain too many NULL values.
Also, small tables do not require indexes, because in the case of small tables, it is usually
faster for the server to scan the table rather than look at the index first.
Note: Most database system like MySQL, SQL server, etc. automatically creates the indexes
for PRIMARY KEY and UNIQUE columns, when the table was created.

38 | P a g e 4 5
Drop Indexes
You can drop indexes that are no longer required with the following statement.
DROP INDEX index_name ON table_name;
Example: The following statement drops the index cust_name_idx from the customers2 table.
DROP INDEX cust_name_idx ON customers2;
Moreover, if you drop a table, then all associated indexes are also dropped.
Warning: You should investigate thoroughly before dropping an index. As a general rule of
thumb, never create or drop indexes blindly.

Unit 33: SQL Dates and Times


In this unit, you will learn how to work with dates and times in SQL.
Date and Time Manipulation
Along with strings and numbers, you often need to store date and/or time values in a
database, such as an user's birth date, employee's hiring date, date of the future events, the
date and time a particular row is created or modified in a table, and so on. This type of data is
referred as temporal data and every database engine has a default storage format and data
types for storing them. The following table shows the data types supported by the MySQL
database server for handling the dates and times.

Type Default format Allowable values


DATE YYYY-MM-DD 1000-01-01 to 9999-12-31
TIME HH:MM:SS or -838:59:59 to 838:59:59
HHH:MM:SS
DATETIME YYYY-MM-DD 1000-01-01 00:00:00 to 9999-12-31 23:59:59
HH:MM:SS
TIMESTAMP YYYY-MM-DD 1970-01-01 00:00:00 to 2037-12-31 23:59:59
HH:MM:SS
YEAR YYYY 1901 to 2155
DATE values have YYYY-MM-DD format, where YYYY represent the full year (4 digits), whereas
the MM and DD represents the month and day parts of the date respectively (2 digits with
leading zero). Likewise, the TIME values have normally HH:MM:SS format, where HH, MM, and
SS represents the hours, minutes, and seconds parts of the time respectively.
Example: The following statement demonstrates how to insert a date value in database table:
INSERT INTO employees2 (emp_name, hire_date, salary)
VALUES ('Adam Smith', '2015-06-24', 4500);
Note: In MySQL, the hours part of the TIME values may be larger, because MySQL treats them
as elapsed time. That means the TIME data type can be used not only to represent a time of
day (which must be less than 24 hours), but also a time interval between two events which
may be greater than 24 hours, or even negative.
Tracking Row Creating or Modification Times
While working with the database of a large application you often need to store record creation
time or last modification time in your database, for example, storing the date and time when a
user sign up, or when a user last updated his password, etc. In MySQL you can use the NOW()
function to insert the current timestamp, as follow:
Example
INSERT INTO users (name, birth_date, created_at)
VALUES ('Bilbo Baggins', '1998-04-16', NOW());
However, if you don't want to insert current date and time manually, you can simply use the
auto-initialization and auto-update properties of the TIMESTAMP and DATETIME data types. To

39 | P a g e 4 5
assign automatic properties, specify the DEFAULT CURRENT_TIMESTAMP and ON UPDATE
CURRENT_TIMESTAMP clauses in column definitions as follow:
Example
CREATE TABLE users (
id INT(4) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL UNIQUE,
birth_date DATE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
);
Note: Automatic initialization and updating for DATETIME data type is only available in MySQL
5.6.5 or later. If you're using an older version use the TIMESTAMP instead.

Extracting Parts of Dates or Times


There may be situations where you just want to obtain a part of date or time. In MySQL you
can use the functions specifically designed for extracting part of a temporal value, such as
YEAR(), MONTH(), DAYOFMONTH(), MONTHNAME(), DAYNAME(), HOUR(), MINUTE(),
SECOND(), etc. The following statement will extract the year part of the birth_date column
values, e.g. if the birth_date of any user is 1987-01-14 the YEAR(birth_date) will return 1987.
SELECT name, YEAR(birth_date) FROM users;
Similarly, you can use the function DAYOFMONTH() to get the day of the month, e.g. if the
birth_date of any user is 1986-10-06 the DAYOFMONTH(birth_date) will return 6.
SELECT name, DAYOFMONTH(birth_date) FROM users;

Formatting Date and Time


If you want more descriptive and readable date format in your result set, you can use the
DATE_FORMAT() and TIME_FORMAT() functions to reformat the existing date and time values.
Example: The following SQL statement will format the values of birth_date column of the
users table in more readable format, like the value 1987-01-14 to January 14, 1987.
SELECT name, DATE_FORMAT(birth_date, '%M %e, %Y') FROM users;

Unit 34: SQL Cloning Tables


In this unit, you will learn how to create a duplicate copy of an existing table.

Cloning or Copying a Table


There may be a situation when you just want to create an exact copy or clone of an existing
table to test or perform something without affecting the original table. The following unit
describes how to do this in few easy steps.
Step 1: Creating an Empty Table
First use the following statement to create an empty table based on the definition of original
table. It also includes the column attributes and indexes defined in the original table:
CREATE TABLE new_table LIKE original_table;
Step 2: Inserting Data into Table
Now, use the following statement to populate the empty table with data from original table:
INSERT INTO new_table SELECT * FROM original_table;
Let us make a clone of the table using the MySQL command-line tool using employees2 table
in our database that has the following records:

emp_id emp_name hire_date salary dept_id


40 | P a g e 4 5
1 Nathaniel Nola 2001-05-01 5000 4
2 Anthony Mafoya 2002-07-15 6500 1
3 Sarah Ayeni 2005-10-18 8000 5
4 Ronke Ladega 2007-01-03 7200 3
5 Yinka Busari 2008-06-24 5600 NULL
Executing the following statement will create an empty table employees2_clone based on the
definition of existing employees2 database table.
CREATE TABLE employees2_clone LIKE employees2;
Now, execute another statement which inserts all the records from employees2 table into
employees2_clone table. After executing this statement you'll get the employees2_clone table
which is an exact copy or duplicate of the employees2 table
INSERT INTO employees2_clone SELECT * FROM employees2;

Simple Cloning
However, if you just want to create a table from another table without taking into account any
column attributes and indexes you can use the simple one line statement:
CREATE TABLE new_table SELECT * FROM original_table;
The following command creates a simple copy of the employees2 table.
CREATE TABLE employees2_dummy SELECT * FROM employees2;
Use the CREATE TABLE ... SELECT syntax to quickly create a simple copy of any table that only
includes the structure and data of the source table.

Unit 35: SQL Temporary Tables


In this unit, you will learn how to create temporary tables using SQL.

Creating Temporary Tables


A temporary table is a table that is visible only to the current session, and is dropped
automatically when the session in which it was created is closed. Since temporary tables are
not stored in the database on a permanent basis, therefore, it would be useful in a situation
where you need a table only for a short time to perform or test something, after which you
want it to disappear automatically. The CREATE TEMPORARY TABLE statement is used to
create a temporary table. The syntax is:
CREATE TEMPORARY TABLE table_name (column definitions);
If you want to create a temporary table from scratch, you can use the TEMPORARY keyword
when creating a table, i.e. use CREATE TEMPORARY TABLE instead of CREATE TABLE
statement.

Creating a Temporary Copy of an Existing Table


Temporary tables can be useful in situations when you just want to test the SQL queries
without affecting the database. Let's create a temporary copy of an existing table in MySQL
database.
CREATE TEMPORARY TABLE persons SELECT * FROM persons;
The above statement creates a temporary table named persons of an existing base table
persons. Also, since it is a temporary copy of the persons table. Therefore, you can perform
any operation like INSERT, UPDATE or DELETE without worrying about affecting the original
persons base table by mistake. A temporary table can have the same name as a permanent
base table. If you specify the name of a temporary table same as the existing base table, then
the permanent base table is hidden until the temporary table is dropped.
Note: Since temporary tables are session-specific, so two different sessions can use the same
temporary table name without conflicting with each other.

41 | P a g e 4 5
Dropping Temporary Tables
Temporary tables are dropped automatically when the database connection or session in which
they are created is closed. However, if want to delete them without closing the current session,
you can use the DROP TEMPORARY TABLE statement as follows:
DROP TEMPORARY TABLE persons;
The above statement will delete the temporary table persons from the database. After that,
the original persons base table becomes visible.

Unit 36: SQL Subqueries


In this unit, you will learn how to embed a query within another query in SQL.
What Is a Subquery?
A subquery, also known as a nested query or sub select, is a SELECT query embedded within
the WHERE or HAVING clause of another SQL query. The data returned by the subquery is
used by the outer statement in the same way a literal value would be used. Subqueries
provide an easy and efficient way to handle the queries that depend on the results from
another query. They are almost identical to the normal SELECT statements, but there are few
restrictions. The most important ones are listed below:
• A subquery must always appear within parentheses.
• A subquery must return only one column. This means you cannot use SELECT * in a
subquery unless the table you are referring has only one column. You may use a
subquery that returns multiple columns, if the purpose is row comparison.
• You can only use subqueries that return more than one row with multiple value
operators, such as the IN or NOT IN operator.
• A subquery cannot be a UNION. Only a single SELECT statement is allowed.
Subqueries are most frequently used with the SELECT statement, however you can use them
within a INSERT, UPDATE, or DELETE statement as well, or inside another subquery.

Subqueries with the SELECT Statement


The following statement will return the details of only those customers2 whose order value in
the orders table is more than 5000 dollar. Also note that we've used the keyword DISTINCT in
our subquery to eliminate the duplicate cust_id values from the result set.
Example
SELECT * FROM customers2
WHERE cust_id IN (SELECT DISTINCT cust_id FROM orders
WHERE order_value > 5000);
A subquery can return a single value, a single row, a single column, or a table containing one
or more rows of one or more columns. Note that a subquery can be nested inside the WHERE
or HAVING clause of an outer SELECT, INSERT, UPDATE, or DELETE statement, or inside
another subquery.

Subqueries with the INSERT Statement


Subqueries can also be used with INSERT statements.
Example
INSERT INTO premium_customers2
SELECT * FROM customers2
WHERE cust_id IN (SELECT DISTINCT cust_id FROM orders
WHERE order_value > 5000);
The above statement will insert the records of premium customers2 into a table called
premium_customers2, by using the data returned from subquery. Here the premium
customers2 are the customers2 who had placed order worth more than 5000 dollar.

42 | P a g e 4 5
Subqueries with the UPDATE Statement
You can also use the subqueries in conjunction with the UPDATE statement to update the
single or multiple columns in a table.
Example:
UPDATE orders
SET order_value = order_value + 10
WHERE cust_id IN (SELECT cust_id FROM customers2
WHERE postal_code = 75016);
The above statement will update the order value in the orders table for those customers2 who
live in the area whose postal code is 75016, by increasing the current order value by 10 dollar.

Subqueries with the DELETE Statement


Similarly, you can use the subqueries in conjunction with the DELETE statement to delete the
single or multiple rows in a table.
Example:
DELETE FROM orders
WHERE order_id IN (SELECT order_id FROM order_details
WHERE product_id = 5);
The SQL statement in the example above will delete those orders from the orders table that
contains the product whose product_id is 5.

Unit 37: SQL Injection


In this unit, you will learn how to fix the common database vulnerabilities.

What is SQL Injection?


SQL injection is an attack wherein an attacker can inject or execute malicious SQL code via the
input data from the browser to the application server, such as web-form input. It can be used
to expose sensitive information like user's contact numbers, email addresses, credit card
information and so on. An attacker can even use it to bypass authentication process and get
access to the entire database. Let's see how it actually works.

How SQL Injection Works


Consider the following SQL statement which is a simple example of authenticating a user with
a username and password in a web application.
SELECT * FROM users WHERE username='username_val' AND
password='password_val';
Here, username_val and password_val represents the username and password entered by the
user respectively. If a user enters the values such as "john" as username and "123" as
password, then the resulting statement is:
SELECT * FROM users WHERE username='john' AND password='123';
But suppose, if user is an attacker and instead of entering a valid username and password in
the input fields, he entered the values something like: ' OR 'x'='x
In this case, the above SQL query will be constructed as:
SELECT * FROM users WHERE username='' OR 'x'='x' AND password='' OR 'x'='x';
This statement is a valid SQL statement and since WHERE 'x'='x' is always true, the query will
return all rows from the users table. You can see how easily an attacker can get access to all
the sensitive information of a database with just a little dirty trick. If the users table is quite
large and contains millions or rows, this single statement can also lead to denial-of-service
attack (DoS attack) by overloading the system resources and make your application
unavailable for legitimate users.

43 | P a g e 4 5
Warning: The consequences of ignoring SQL injection vulnerability can be even worse if your
script generates a DELETE or UPDATE query. An attacker can delete data from the table or
change all of its rows permanently.

Preventing SQL Injection


Always validate user input and make no assumptions. Never build SQL statements directly
from user input. If you're using PHP and MySQL you can use mysqli_real_escape_string()
function to create a legal SQL string that you can use in an SQL statement.
Here's a very basic example of user authentication using PHP and MySQL that demonstrates
how to prevent SQL injection while taking input from users.

Example
<?php
// Starting session
session_start();
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect to database.");
}
// Escape user inputs for security
$username_val = mysqli_real_escape_string($link, $_POST['username']);
$password_val = mysqli_real_escape_string($link, $_POST['password']);
if(isset($username_val, $password_val)){
// Attempt select query execution
$sql = "SELECT * FROM users WHERE username='" . $username_val . "' AND password='" .
$password_val . "'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) == 1){
// User is authenticated do your stuff here
$row = mysqli_fetch_array($result);
/* Holding values in session variable so that it can be
accessed later within the same session reference */
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['first_name'] = $row['first_name'];
header('Location: welcome.php');
} else{
echo "ERROR: Invalid username or password.";
}
} else{
echo "ERROR: Something went wrong. Please try again.";
}
}

// Close connection
mysqli_close($link);
?>
Please check out the tutorial on PHP MySQL prepared statements to learn the advanced
techniques of preventing SQL injection in your web applications.
Tip: Test the size and type or content of the data that is received by your application and
enforce appropriate limits to protect against system resources exploitation.

44 | P a g e 4 5
Unit 38: SQL Functions
SQL has many built-in functions that enable you to perform calculations on data.
SQL Aggregate Functions
SQL aggregate functions perform calculation on a set of values and return a single value. The
following table summarizes some useful aggregate functions:
Function Description
AVG() Returns the average of values
SUM() Returns the sum of values
COUNT() Returns the number of rows in a result set
MAX() Returns the maximum value
MIN() Returns the minimum value

SQL String Functions


SQL string functions perform operation on a string input value and return a string or numeric
value. The following table summarizes some useful string functions:
Function Description
CONCAT() Returns a string by concatenating two or more string values.
CONCAT_WS() Returns a string by concatenating two or more string values with a separator.
FORMAT() Returns a value formatted with the specified format.
LOWER() Converts a string to lowercase.
UPPER() Converts a string to uppercase.
TRIM() Remove leading and trailing spaces from a string.
REVERSE() Returns the reverse order of a string value.
SUBSTRING() Returns a substring from string.

MySQL Date Functions


Date functions are used to manipulate or perform operation on date values.
The following table summarizes some most important MySQL's built-in date functions:
Function Description
NOW() Returns the current date and time.
CURDATE() Returns the current date.
CURTIME() Returns the current time
DATE() Extract the date part of a date or datetime expression.
DAY() Returns the day of the month (0-31).
DAYNAME() Returns the name of the weekday.
MONTH() Returns the month from the date passed (1-12).
MONTHNAME() Returns the name of the month.
YEAR() Returns the year.
DATE_FORMAT() Displays date and time value in other formats.
EXTRACT() Extract part of a date.
DATE_ADD() Adds a specified time value (or interval) to a date value.
DATE_SUB() Subtracts a specified time value (or interval) from a date value.
DATEDIFF() Returns the number of days between two dates
NOTE: The date and time returned by these functions is the date and time of the computer on
which the instance of database server is running.

45 | P a g e 4 5

You might also like