Professional Documents
Culture Documents
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.
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.
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/
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;
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;
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.
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.
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).
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
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 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.
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
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.
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
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;
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
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.
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
Exercise/Assignment 2
Create a table named trainees with the following records:
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
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.
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:
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
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.
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.
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.
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.
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:
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.
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:
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.
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:
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.
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
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.
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
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:
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.
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.
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.
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.
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:
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;
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.
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.
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.
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.
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.
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.
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.
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
45 | P a g e 4 5