School of Data
Analytics & AI
Structure Query
Language
Introduction
SQL is short for Structured Query Language
ess-que-ell
sequel
SQL
A programming language that lets you store data, access and manipulate
them in databases.
It is a domain-specific language used in programming and designed for
managing data held in a relational database management system (RDBMS).
Database Management
✔ SEARCH
CONTACT LIST
✔ UPDATE
✔ DELETE
✔ ADD
Types of Databases
✔ Relational
✔ Non-relational
Relational Database
Database that organizes data/information into one or more tables.
Refer to database_concepts.pdf for more
DB concepts
MySQL Installation
• MySQL Community Server
• MySQL Workbench
Data Types
Please fill the information below
First Name
ALPHABETIC
Last Name
Phone Number NUMBERS
Email Address MIXED
SIGN UP
Data Types
TYPES
NUMERIC Numbers
STRINGS Letters/Characters
DATE Date & Time
Numeric Data Types
NUMERIC
INTEGER Whole Numbers
Whole Numbers &
DECIMAL
Fractions
INTEGE
2
R
They are whole numbers without decimals or any fractions.
An integer can be written without a fractional component
e.g., 1, 101, 7, -19, and it cannot be 1.5, 8/5
INTEGE
15
R
They are used to store exact numbers, for example number
of students in a class.
INTEGE
7
R
There are more subtypes, but they only differ in storage
capacity & ranges.
DECIMA
5.45
L
DECIMAL data type is often used for monetary data such as
prices, salary, account balances. They store whole numbers &
fractions/decimals.
DECIMA
17.2
L
Example, salary_amount DECIMAL(6,2), which means that the
column can store up to 6 digits with 2 decimals (i.e., fractional
part)
salary_amount = 9998.99
DECIMA
1.5
L
From the example, we have DECIMAL(P,S).
Where P is the Precision, and S is the scale.
String Data Types
STRING
• Fixed Length Characters
• Used to store data with
CHAR
fixed size
• Length value is 0 - 255
• Variable Length Characters
• Used for passwords,
VARCHAR
usernames
• Length value is 0 - 65535
CHAR [Link]
VALUE CHAR(4) VARCHAR(4)
a b a b a b
a b c d a b c d a b c d
a b c d e a b c d a b c d
Date Data Types
DATE
DATE Store dates
TIME Store/display time
DATETIME Timestamp
DATE
DATE type is used to store dates.
Format
‘YYYY-MM-DD’
E.g. – 2019-03-22
Year Day
Mont
h
TIME
TIME type is used to display time.
Format
‘HH:MM:SS’
E.g. – [Link]
Hour Seconds
Minute
s
DATETIME
DATETIME values contain both date and time.
Format
‘YYYY-MM-DD HH:MM:SS’
E.g. – 2019-03-22 [Link]
DDL Statements
SQL Statements
CREATE DATABASE - syntax
CREATE DATABASE database_name;
CREATE DATABASE university;
USE database_name - syntax
USE database_name;
USE university;
CREATE TABLE - syntax
CREATE TABLE table_name (
col1_name datatype,
col2_name datatype,
col3_name datatype
);
CREATE TABLE students (
student_id INTEGER,
name VARCHAR(55),
year INTEGER
);
DESCRIBE table_name - syntax
DESCRIBE table_name;
DESCRIBE students;
CREATE TABLE
Column students
student_id name year
Row
INSERT INTO
Column students
student_id name year
1 Izundu Dan-Ekeh 3
2 Miriam Abubakar 2
3 Dorcas Roberts 3
4 Emeka Frank 1 Row
INSERT INTO - syntax
INSERT INTO table_name (col1_name, col2_name, col3_name)
VALUES (val1, val2, val3);
INSERT INTO students (student_id, name, year)
VALUES (1, “Izundu Dan-Ekeh”, 3);
ALTER TABLE
ALTER
TABLE
ADD COLUMN
DROP COLUMN
MODIFY
COLUMN
ALTER TABLE ADD COLUMN - syntax
ALTER TABLE table_name
ADD COLUMN (col1_name datatype,
col2_name datatype,
col3_name datatype);
ALTER TABLE students
ADD COLUMN (age INTEGER,
grade INTEGER,
admitted_at DATE);
ALTER ADD COLUMN
students
student_id name year age grade admitted_at
1 Izundu Dan-Ekeh 3
2 Miriam Abubakar 2
3 Dorcas Roberts 3
4 Emeka Frank 1
ALTER DROP COLUMN
students
student_id name age grade admitted_at
1 Izundu Dan-Ekeh
2 Miriam Abubakar
3 Dorcas Roberts
4 Emeka Frank
ALTER TABLE DROP COLUMN - syntax
ALTER TABLE table_name
DROP COLUMN col1_name;
ALTER TABLE students
DROP COLUMN year;
ALTER TABLE ALTER COLUMN - syntax
ALTER TABLE table_name
ALTER COLUMN col1_name TYPE new_datatype;
ALTER TABLE students
ALTER COLUMN grade TYPE DECIMAL(2,1);
DROP TABLE - syntax
DROP TABLE table_name;
DROP TABLE students;
DQL Statements
SQL Statements
SELECT Statement
✔ Fetch data from a database table.
✔ Returns data in the form of a result table/set.
SELECT-FROM - syntax
SELECT *
FROM table_name;
SELECT col1, col2, col3, …, colN
FROM table_name;
students
student_id name age grade admitted_at
1 Seun Dada 27 3.8 2015-09-01
2 Miriam Abubakar 24 4.0 2017-09-01
3 Dorcas Roberts 24 3.7 2016-09-01
4 Ayomide Titilope 25 4.0 2015-09-01
5 Emeka Jude 24 3.8 2014-09-01
6 Caroline Obi 27 3.1 2013-09-01
7 Franklin Oladele 18 3.9 2019-09-01
8 Kola Ola 28 4.0 2013-09-01
9 Emmanuel Ovi 23 3.1 2016-09-01
10 Kareem Musa 24 3.3 2016-09-01
11 Mustapha Ahmed 24 3.9 2016-09-01
12 Femi Akin 24 2017-09-01
SELECT-FROM - syntax
SELECT *
FROM students;
SELECT name, grade
FROM students;
DISTINCT
✔ Removes duplicate values
✔ Returns unique values
DISTINCT
age
21 age
21 21
23 23
22 22
22
SELECT DISTINCT age
FROM table_name;
DISTINCT - syntax
SELECT DISTINCT age
FROM students;
LIMIT
✔ Used to restrict the number of rows returned from a query.
✔ Specify the maximum number of rows to be returned.
✔ Run query faster.
LIMIT - syntax
SELECT col SELECT *
FROM table_name FROM students
LIMIT number; LIMIT 5;
SELECT col1, col2
FROM table_name
LIMIT number;
ORDER BY
✔ Sort data ascending or descending according to one or more columns.
✔ Can order in ascending order
ASC
✔ Can order in descending order
DESC
ORDER BY - syntax
SELECT col1, col2 SELECT col1, col2
FROM table_name FROM table_name
ORDER BY col1 ASC; ORDER BY col1 DESC, col2 ASC;
SELECT col1, col2
FROM table_name
ORDER BY col1 DESC;
ORDER BY – Lab Question?
✔ Fetch all data from the students table and sort the result in descending
order according to the student_id column.
✔ Fetch all data from the students table, sort the result in ascending order
first according to the age column, and then in descending order
according to the student_id column.
ORDER BY - syntax
SELECT * SELECT *
FROM students FROM students
ORDER BY student_id DESC; ORDER BY age ASC,
student_id DESC;
WHERE
PRICE (₦)
300 1599999
SIZE COLOR
S Green
M Pink
L White
XL Blue
WHERE
✔ Fetch all data that fulfils a specified condition.
WHERE - syntax
SELECT col1, col2
FROM table_name
WHERE condition;
WHERE - conditions
Operator Description
= Equal
> Greater than
< Less than SELECT col1, col2
>= Greater than or equal FROM table_name
<= Less than or equal WHERE condition;
<> or != Not equal
BETWEEN Between a certain range
LIKE Search for a pattern
WHERE - conditions
Operator Description
SELECT col1, col2
= Equal
FROM table_name
> Greater than
< Less than
WHERE condition;
>= Greater than or equal
<= Less than or equal
<> or != Not equal
BETWEEN Between a certain range Numeric vs Non-Numeric Fields
LIKE Search for a pattern
• Single quotes around non-numeric e.g., name
= ‘Musa’
• No quotes around numeric values e.g., age =
21
WHERE – Lab Question?
✔ Fetch results for students aged greater than 24.
✔ Fetch results for students with grade of 3.1 and above.
✔ Fetch the record of Emmanuel Ovi.
WHERE - syntax
SELECT * SELECT *
FROM students FROM students
WHERE name = ‘Emmanuel Ovi’;
WHERE age > 24;
SELECT *
FROM students
WHERE grade >= 3.1;
LIKE
Querying a particular table may be sometimes difficult due to the kind of
data present.
For example, some text characters might be too long to remember exactly
what they look like.
LIKE
The LIKE clause in combination with wildcards makes it easier to carry
out these difficult queries.
LIKE
Wildcards are placeholders or stand-ins for characters.
Types of Wildcards
Percent (%) Any number of unknown
characters
Underscore (_) Just one unknown character
LIKE with %
Patterns using wildcard Result
website
%github% [Link]
[Link]
[Link] %google% [Link]
[Link] [Link]
[Link] %com [Link]
[Link]
[Link]
[Link] www%org [Link]
[Link]
%[Link]
[Link]
www% All the rows
LIKE with %
SELECT col1, col2
FROM table_name
WHERE col1 LIKE pattern;
SELECT website
FROM website_table
WHERE website LIKE ‘%github%’;
Returns – [Link]
LIKE – Lab Question?
✔ Return results for students with the names that contain “M”
✔ Return results for students with the last name “Musa”
✔ Return results for students with the names that start with “K”
LIKE with _
Patterns using wildcard Result
name Ovi
O_i
Musa Obi
Bayo Bayo
_ayo
Tayo Tayo
Ovi
Ov_ Ovi
Obi
Moyo Musa
M___
Moyo
LIKE with _
SELECT col1, col2
FROM table_name
WHERE col1 LIKE pattern;
SELECT name
FROM name_table
WHERE name LIKE ‘O_i’;
Returns – Obi and Ovi
LIKE – Lab Question?
✔ Return results for students with ages between 20-29, inclusive
✔ Some students have their name as either Obi or Ovi. Return the records
of these students.
LIKE - syntax
SELECT * SELECT *
FROM students FROM students
WHERE age LIKE ‘2_’; WHERE name LIKE ‘%O_i’;
Logical Operators
Introduction
Logical Operators
Logical operators can be used to combine 2 or more conditional statements.
LOGICAL OPERATORS
AND OR NOT
AND
The result is TRUE if all the conditional statements are
TRUE.
EXAMPLE
Condition 1 Condition 2
10 > 8 AND 10 > 8
TRU AND TRU
E E
} TRU
E
Truth Table with AND Operator
A truth table shows the TRUTH or FALSITY of a compound statement.
Statement 1 (P) Statement 2 (Q) P AND Q
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
AND
EXAMPLE
10 > 8 AND 5<8 TRU
E
TRU TRU
E E
4<8 AND 3>1 TRU
E
TRU TRU
E E
AND - syntax
SELECT col1, col2
FROM table_name
WHERE condition1 AND condition2;
AND – Lab Question?
✔ Fetch results for students that gained admission after 2015 and grade is
above 3.1.
✔ Fetch results for students with age above 20 and grade is below 3.9.
AND - syntax
SELECT *
FROM students
WHERE admitted_at > ‘2015-09-01’
AND grade > 3.1;
SELECT *
FROM students
WHERE age > 20 AND grade < 3.9;
OR
The result is TRUE if at least one of the conditional
statements are TRUE.
EXAMPLE
Condition 1 Condition 2
10 > 11 OR 5<8
FALS OR TRU
E E
} TRU
E
Truth Table with OR Operator
A truth table shows the TRUTH or FALSITY of a compound statement.
Statement 1 (P) Statement 2 (Q) P OR Q
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
OR
EXAMPLE
10 > 8 OR 5<8 TRU
E
TRU TRU
E E
8>4 OR 3 > 15 TRU
E
TRU FALS
E E
OR - syntax
SELECT col1, col2
FROM table_name
WHERE condition1 OR condition2;
OR – Lab Question?
✔ Fetch results for students with name that begins with letter ‘M’ or got a
grade above 3.1.
✔ Fetch results for students with age above 20 or got a grade that is above
3.1 or got admitted after 2017.
OR - syntax
SELECT * SELECT *
FROM students FROM students
WHERE name LIKE ‘M%’ WHERE age > 20
OR grade > 3.1; OR grade < 3.1
OR admitted_at > ‘2017-09-01’;
NOT
The result will be the reversal of the conditional statement.
EXAMPLE
Condition Result
10 > 11 10 < 11
NOT
FALS TRU
E E
Truth Table with NOT Operator
A truth table shows the TRUTH or FALSITY of a compound statement.
Statement 1 (P) NOT(P) Statement 2 (P OR Q) NOT(P OR Q)
TRUE FALSE TRUE FALSE
TRUE FALSE TRUE FALSE
FALSE TRUE TRUE FALSE
FALSE TRUE FALSE TRUE
NOT - syntax
SELECT col1, col2
FROM table_name
WHERE NOT condition1
AND/OR NOT condition2;
NOT – Lab Question?
✔ Fetch results for students with grade below 3.8.
✔ Fetch results for students with grade below 3.8 and age is below 25.
NOT - syntax
SELECT * SELECT *
FROM students FROM students
WHERE NOT grade >= 3.8
WHERE NOT grade >= 3.8;
AND NOT age >= 25;
OR
SELECT *
FROM students
WHERE NOT (grade >= 3.8 OR age >= 25);
IN
Question: Fetch results for students with age 23, 24, 27.
SELECT *
FROM students
WHERE age = 23
OR age = 24
OR age = 27;
IN
Rather than using all the OR operators, one can simplify the query with the
IN keyword.
The IN clause is used as a shorthand for multiple ORs.
SELECT *
FROM students
WHERE age IN (23, 24, 27);
IN - syntax
SELECT * SELECT *
FROM students FROM students
WHERE age = 23 WHERE age IN (23, 24, 27);
OR age = 24
OR age = 27;
IN – Lab Question?
✔ Fetch results for students with student_id 12, 3, 8, 4.
✔ Fetch results for students that gained admission in 2015 and 2017.
IN - syntax
SELECT * SELECT *
FROM students FROM students
WHERE student_id IN (12,3,8,4); WHERE admitted_at IN
(‘2015-09-01’, ‘2017-09-01’);
NOT IN
Adding NOT to the IN statement gives the result of anything that doesn’t
match the specified set of values.
SELECT *
FROM table_name
WHERE col_name NOT IN (val1, val2, ...);
NOT IN – Lab Question?
✔ Fetch results for students who are not 18.
✔ Fetch results for students that did not gain admission in 2015 and 2017.
NOT IN - syntax
SELECT * SELECT *
FROM students FROM students
WHERE age NOT IN (18); WHERE admitted_at NOT IN
(‘2015-09-01’, ‘2017-09-01’);
BETWEEN
Question: Fetch results for students with age that falls into the range
between and including 24 and 27.
SELECT *
FROM students
WHERE age >= 24
AND age <= 27;
BETWEEN
✔ Simplify previous query with the BETWEEN keyword.
✔ Obtain the same results with this keyword.
✔ It is equivalent to using <= and >=, but not the < and > symbol.
BETWEEN - syntax
SELECT col1, col2
FROM table_name
WHERE col_name BETWEEN val1 AND val2;
SELECT *
FROM students
WHERE age BETWEEN 24 AND 27;
BETWEEN – Lab Question?
✔ Fetch results for students with grade between 3.5 – 4.0, inclusive.
✔ Fetch results for students that gained admission between 2015 and 2017.
BETWEEN - syntax
SELECT *
FROM students
WHERE grade BETWEEN 3.5 AND 4.0;
SELECT *
FROM students
WHERE admitted_at BETWEEN ‘2015-09-01’ AND ‘2017-09-01’;
NOT BETWEEN
✔ This returns results that is not within the range of the specified values.
✔ NOT BETWEEN is equivalent to < “begin_value” OR >
“end_value”.
NOT BETWEEN - syntax
SELECT col1
FROM table_name
WHERE col_name NOT BETWEEN val1 AND val2;
SELECT *
FROM students
WHERE age NOT BETWEEN 24 AND 27;
NOT BETWEEN – Lab Question?
✔ Fetch results for students with grade that is not between 3.5 – 4.0.
✔ Fetch results for students that did not gain admission between 2015 and
2017.
NOT BETWEEN - syntax
SELECT *
FROM students
WHERE grade NOT BETWEEN 3.5 AND 4.0;
SELECT *
FROM students
WHERE admitted_at NOT BETWEEN ‘2015-09-01’ AND
‘2017-09-01’;
BETWEEN with IN and NOT
BETWEEN keyword operator can also be used together with IN and
NOT keywords.
SELECT *
FROM table_name
WHERE col_name BETWEEN val1 AND val2
AND/OR col_name IN (val1, val2, …);
BETWEEN with IN and NOT
BETWEEN keyword operator can also be used together with IN and
NOT keywords.
SELECT *
FROM table_name
WHERE col_name BETWEEN val1 AND val2
AND/OR col_name NOT IN (val1, val2, …);
BETWEEN with IN and NOT – Lab Question?
✔ Fetch results for students that got admitted between 2015-2017, and age
is 23, 24.
✔ Fetch results for students that got admitted between 2015-2017, and age
is not 23, 24.
BETWEEN with IN and NOT - syntax
SELECT *
FROM students
WHERE admitted_at BETWEEN ‘2015-09-01’ AND ‘2017-09-01’
AND age IN (23, 24);
SELECT *
FROM students
WHERE admitted_at BETWEEN ‘2015-09-01’ AND ‘2017-09-01’
AND age NOT IN (23, 24);
NULL
A field with NULL value is a field with no value.
It is a field that was left blank during record creation.
VALUE
id value
1 a
2 NULL
IS NULL
Nothing can be equal to NULL.
NULL is not the same as 0.
SELECT *
FROM values
WHERE col_name = NULL;
IS NULL
IS NULL operator is used to check for empty values/NULL values.
SELECT *
FROM values
WHERE col_name IS NULL;
IS NULL
value_table
id value
1 a
2 NULL
SELECT *
id value
FROM value_table 2 NULL
WHERE value IS NULL;
Update grade column for the next task
UPDATE students
SET grade = NULL
WHERE grade = 0.0;
By default, MySQL Workbench is in Safe Update mode which
means it rejects UPDATEs and DELETEs with no restrictions. So,
we must remove it from Safe Update mode to run the above
query.
IS NULL – Lab Question?
✔ Return results for students where age is NULL
✔ Return results for students where the grade is NULL
IS NULL - syntax
SELECT *
FROM students
WHERE age IS NULL;
SELECT *
FROM students
WHERE grade IS NULL;
IS NOT NULL
IS NOT NULL operator is used to check for non-empty values.
SELECT *
FROM table_name
WHERE col_name IS NOT NULL;
IS NOT NULL
value_table
id value
1 a
2 NULL
SELECT *
id value
FROM value_table 1 a
WHERE value IS NOT NULL;
IS NOT NULL – Lab Question?
✔ Return results for students where age is NOT NULL
✔ Return results for students where the grade is NOT NULL
IS NOT NULL - syntax
SELECT *
FROM students
WHERE age IS NOT NULL;
SELECT *
FROM students
WHERE grade IS NOT NULL;
CASE
When we want to run a query and the result to be returned depends on
certain conditions, we make use of the CASE statement.
You can think of it as an IF/ELSE statement, where the CASE statement
goes through conditions and returns a value when the first condition is met.
CASE
Once a condition is met and is true, it will stop reading and return the
result. If no conditions are true, it returns the value in the ELSE clause.
If there is no ELSE clause and no conditions are true, it returns NULL.
CASE
CASE SYNTAX
GENERA EXPRESSI
L ON
CASE – General syntax
SELECT *,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END AS col_name
FROM table_name;
CASE – General syntax
value_table
value
1
2
SELECT
CASE
WHEN value = 1 THEN ‘First’ value
WHEN value = 2 THEN ‘Second’
First
ELSE ‘Others’
END AS col_name Second
FROM value_table;
CASE (General syntax) – Lab Question?
✔ Fetch results for students by grouping the ages into different classes,
based on certain conditions below.
✔ For ages 26 and above – ‘Upper Age Class’
✔ For ages between, 23 and 25 – ‘Middle Age Class’
✔ For ages below 23 – ‘Lower Age Class’
CASE – General syntax
SELECT *,
CASE
WHEN age >= 26 THEN ‘Upper Age Class’
WHEN age BETWEEN 23 AND 25 THEN ‘Middle Age Class’
ELSE ‘Lower Age Class’
END
FROM students;
CASE – Expression syntax
The expression syntax first evaluates an expression then compares the
result with each value in the WHEN clauses.
CASE – Expression syntax
SELECT *,
CASE expression
WHEN val1 THEN result1
WHEN val2 THEN result2
WHEN valN THEN resultN
ELSE result
END
FROM table_name;
CASE – Expression syntax
value_table
value
1
2
SELECT *,
CASE value
WHEN 1 THEN ‘First’ value CASE
WHEN 2 THEN ‘Second’
1 First
ELSE ‘Others’
END 2 Second
FROM value_table;
CASE (Expression syntax) – Lab Question?
✔ The session award ceremony is approaching, and the school needs to give
the student with the highest grade attainable (4.0), the “Best Student”
award. Create a column for this award and return result for the other
scores as “Normal”.
CASE – Expression syntax
SELECT *,
CASE grade
WHEN 4.0 THEN ‘Best Student’
ELSE ‘Normal’
END
FROM students;
THE END