0% found this document useful (0 votes)
326 views

SQL - MySQL For Data Analytics and Business Intelligence

The document discusses the SQL DELETE statement as part of the Data Manipulation Language (DML) in SQL. DML statements allow users to manipulate the data within database tables. The DELETE statement is used to remove or delete rows from a table in a database. It allows the user to permanently remove rows that are no longer needed.

Uploaded by

Nidhi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
326 views

SQL - MySQL For Data Analytics and Business Intelligence

The document discusses the SQL DELETE statement as part of the Data Manipulation Language (DML) in SQL. DML statements allow users to manipulate the data within database tables. The DELETE statement is used to remove or delete rows from a table in a database. It allows the user to permanently remove rows that are no longer needed.

Uploaded by

Nidhi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1307

The SQL DELETE Statement

SQL – MySQL for Data Analytics and


Business Intelligence
SQL Theory
Data Definition Language (DDL)
Data Definition Language

SQL’s syntax
Data Definition Language

SQL’s syntax
comprises several types of statements that allow you to perform various
commands and operations
Data Definition Language

SQL’s syntax
comprises several types of statements that allow you to perform various
commands and operations

Data Definition Language (DDL)


Data Definition Language

SQL’s syntax
comprises several types of statements that allow you to perform various
commands and operations

Data Definition Language (DDL)


- a syntax
- a set of statements that allow the user to define or modify data
structures and objects, such as tables
Data Definition Language

SQL’s syntax
comprises several types of statements that allow you to perform various
commands and operations

Data Definition Language (DDL)


- a syntax
- a set of statements that allow the user to define or modify data
structures and objects, such as tables

the CREATE statement


Data Definition Language

SQL’s syntax
comprises several types of statements that allow you to perform various
commands and operations

Data Definition Language (DDL)


- a syntax
- a set of statements that allow the user to define or modify data
structures and objects, such as tables

the CREATE statement


used for creating entire databases and database objects as tables
Data Definition Language

the CREATE statement


used for creating entire databases and database objects as tables

CREATE object_type object_name;


Data Definition Language

the CREATE statement


used for creating entire databases and database objects as tables

CREATE object_type object_name;

CREATE TABLE object_name (column_name data_type);


Data Definition Language

CREATE TABLE object_name (column_name data_type);


Data Definition Language

CREATE TABLE object_name (column_name data_type);

CREATE TABLE sales (purchase_number INT);


Data Definition Language

CREATE TABLE object_name (column_name data_type);

CREATE TABLE sales (purchase_number INT);

sales
purchase_number
Data Definition Language

CREATE TABLE sales (purchase_number INT);

sales
purchase_number

the table name can coincide with the name assigned to the database
Data Definition Language

the ALTER statement


Data Definition Language

the ALTER statement


used when altering existing objects
Data Definition Language

the ALTER statement


used when altering existing objects

- ADD
- REMOVE
- RENAME
Data Definition Language

sales
purchase_number
Data Definition Language

ALTER TABLE sales


ADD COLUMN date_of_purchase DATE;

sales
purchase_number
Data Definition Language

ALTER TABLE sales


ADD COLUMN date_of_purchase DATE;

sales
purchase_number date_of_purchase
Data Definition Language

the DROP statement


Data Definition Language

the DROP statement


used for deleting a database object
Data Definition Language

DROP object_type object_name;

customers
customer_id first_name
Data Definition Language

used for deleting a database object

DROP object_type object_name;

DROP TABLE customers; customers


customer_id first_name
Data Definition Language

used for deleting a database object

DROP object_type object_name;

DROP TABLE customers; customers


customer_id first_name
Data Definition Language

the RENAME statement


Data Definition Language

the RENAME statement


allows you to rename an object
Data Definition Language

RENAME object_type object_name TO new_object_name;

customers
customer_id first_name
Data Definition Language

used for deleting a database object

RENAME object_type object_name TO new_object_name;

RENAME TABLE customers TO customer_data;

customers
customer_id first_name
Data Definition Language

used for deleting a database object

RENAME object_type object_name TO new_object_name;

RENAME TABLE customers TO customer_data;

customer_id first_name
Data Definition Language

used for deleting a database object

RENAME object_type object_name TO new_object_name;

RENAME TABLE customers TO customer_data;

customer_data
customer_id first_name
Data Definition Language

the TRUNCATE statement


Data Definition Language

the TRUNCATE statement


instead of deleting an entire table through DROP, we can also remove its
data and continue to have the table as an object in the database
Data Definition Language

TRUNCATE object_type object_name;

customers
customer_id first_name
Data Definition Language

used for deleting a database object

TRUNCATE object_type object_name;

TRUNCATE TABLE customers;


customers
customer_id first_name
Data Definition Language

used for deleting a database object

TRUNCATE object_type object_name;

TRUNCATE TABLE customers;


customers
customer_id first_name
Data Definition Language

Data Definition Language (DDL)


Data Definition Language

Data Definition Language (DDL)


- CREATE
- ALTER
- DROP
- RENAME
- TRUNCATE
Next:
Next:
Keywords
Next:
Keywords
Data Manipulation Language
SQL Keywords
Keywords

Keywords:
- ADD
Keywords

Keywords:
- ADD
- CREATE
- ALTER
- etc.
Keywords

Keywords:
- ADD
- CREATE
- ALTER
- etc.

KEYWORDS IN SQL CANNOT BE VARIABLE NAMES!


Keywords

Keywords:
- ADD
- CREATE
- ALTER
- etc.

KEYWORDS IN SQL CANNOT BE VARIABLE NAMES!


objects or databases cannot have names that coincide with SQL keywords
Keywords

CREATE, ALTER:
Keywords

CREATE, ALTER:

CREATE TABLE alter (purchase_number INT);

alter
purchase_number
Data Definition Language

ADD
Data Definition Language

ADD

ALTER TABLE sales


ADD COLUMN date_of_purchase DATE;

sales
purchase_number date_of_purchase
Data Definition Language

ADD, ALTER

ALTER TABLE sales


ADD COLUMN date_of_purchase DATE;

sales
purchase_number date_of_purchase
Keywords

Keywords = reserved words


Keywords

Keywords = reserved words


they cannot be used when naming objects
Data Manipulation Language (DML)
Data Manipulation Language

Data Manipulation Language (DML)


its statements allow us to manipulate the data in the tables of a
database

the SELECT statement


used to retrieve data from database objects, like tables
Data Manipulation Language

SELECT * FROM sales;

sales
purchase_number
Data Manipulation Language

SELECT * FROM sales;

sales
purchase_number
Data Manipulation Language

SELECT… FROM sales;

sales
purchase_number
Data Manipulation Language

SELECT… FROM sales;

sales
purchase_number
Data Manipulation Language

SELECT… FROM sales;

sales
purchase_number
Data Manipulation Language

Why are we going to need just a piece of the table?

- imagine a table with 2 million rows of data


- it can be helpful if you could extract only a portion of the table
that satisfies given criteria
- you should know how to use SELECT perfectly well
Data Manipulation Language

the INSERT statement


used to insert data into tables

INSERT INTO… VALUES…;


Data Manipulation Language

INSERT INTO sales (purchase_number, date_of_purchase) VALUES


(1, ‘2017-10-11’);

sales
purchase_number date_of_purchase
Data Manipulation Language

INSERT INTO sales (purchase_number, date_of_purchase) VALUES


(1, ‘2017-10-11’);

sales
purchase_number date_of_purchase
1 2017-10-11
Data Manipulation Language

INSERT INTO sales VALUES


(1, ‘2017-10-11’);

sales
purchase_number date_of_purchase
1 2017-10-11
Data Manipulation Language

INSERT INTO sales (purchase_number, date_of_purchase) VALUES


(1, ‘2017-10-11’);

INSERT INTO sales VALUES


(1, ‘2017-10-11’);
Data Manipulation Language

INSERT INTO sales (purchase_number, date_of_purchase) VALUES


(2, ‘2017-10-27’);

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

the UPDATE statement


allows you to renew existing data of your tables
Data Manipulation Language

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

UPDATE sales
SET date_of_purchase = ‘2017-12-12’
WHERE purchase_number = 1;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

UPDATE sales
SET date_of_purchase = ‘2017-12-12’
WHERE purchase_number = 1;

sales
purchase_number date_of_purchase
1 2017-12-12
2 2017-10-27
Data Manipulation Language

the DELETE statement


- functions similarly to the TRUNCATE statement

TRUNCATE vs. DELETE


TRUNCATE allows us to remove all the records contained in a table

vs.

with DELETE, you can specify precisely what you would like to be removed
Data Manipulation Language

DELETE FROM sales;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

DELETE FROM sales; TRUNCATE TABLE sales;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

DELETE FROM sales; TRUNCATE TABLE sales;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

DELETE FROM sales


WHERE
purchase_number = 1;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

DELETE FROM sales


WHERE
purchase_number = 1;

sales
purchase_number date_of_purchase
1 2017-10-11
2 2017-10-27
Data Manipulation Language

Data Manipulation Language (DML)


- SELECT… FROM…
- INSERT INTO… VALUES…
- UPDATE… SET… WHERE…
- DELETE FROM… WHERE…
Next:
Data Control Language (DCL)
Data Control Language (DCL)
Data Control Language

Data Control Language (DCL)


Data Control Language

Data Control Language (DCL)

the GRANT and REVOKE statements


Data Control Language

Data Control Language (DCL)

the GRANT and REVOKE statements


allow us to manage the rights users have in a database
Data Control Language
Data Control Language
Data Control Language

users
Data Control Language

The GRANT statement


Data Control Language

The GRANT statement


gives (or grants) certain permissions to users
Data Control Language

The GRANT statement


gives (or grants) certain permissions to users
Data Control Language

The GRANT statement


gives (or grants) certain permissions to users

GRANT type_of_permission ON database_name.table_name TO


‘username’@’localhost’
Data Control Language

The GRANT statement


gives (or grants) certain permissions to users

one can grant a specific type of permission, like complete or partial


access

GRANT type_of_permission ON database_name.table_name TO


‘username’@’localhost’
Data Control Language
these rights will be assigned to a person who has a username registered
at the local server (‘localhost’: IP 127.0.0.1)

GRANT type_of_permission ON database_name.table_name TO


‘username’@’localhost’
Data Control Language
these rights will be assigned to a person who has a username registered
at the local server (‘localhost’: IP 127.0.0.1)

big companies and corporations don’t use this type of server, and their
databases lay on external, more powerful servers

GRANT type_of_permission ON database_name.table_name TO


‘username’@’localhost’
Data Control Language

Database administrators
Data Control Language

Database administrators
people who have complete rights to a database
Data Control Language

Database administrators
people who have complete rights to a database
- they can grant access to users and can revoke it
Data Control Language

Database administrators
people who have complete rights to a database
- they can grant access to users and can revoke it

the REVOKE clause


Data Control Language

Database administrators
people who have complete rights to a database
- they can grant access to users and can revoke it

the REVOKE clause


used to revoke permissions and privileges of database users
Data Control Language

Database administrators
people who have complete rights to a database
- they can grant access to users and can revoke it

the REVOKE clause


used to revoke permissions and privileges of database users
- the exact opposite of GRANT
Data Control Language

the REVOKE clause


used to revoke permissions and privileges of database users
Data Control Language

the REVOKE clause


used to revoke permissions and privileges of database users

REVOKE type_of_permission ON database_name.table_name FROM


‘username’@’localhost’
Data Control Language

Next:
Data Control Language

Next:
Transaction Control Language (TCL)
Transaction Control Language (DCL)
Transaction Control Language

Transaction Control Language (DCL)


Transaction Control Language

Transaction Control Language (DCL)


- not every change you make to a database is saved automatically
Transaction Control Language

Transaction Control Language (DCL)


- not every change you make to a database is saved automatically

the COMMIT statement


Transaction Control Language

Transaction Control Language (DCL)


- not every change you make to a database is saved automatically

the COMMIT statement


- related to INSERT, DELETE, UPDATE
Transaction Control Language

Transaction Control Language (DCL)


- not every change you make to a database is saved automatically

the COMMIT statement


- related to INSERT, DELETE, UPDATE
- will save the changes you’ve made
Transaction Control Language

Transaction Control Language (DCL)


- not every change you make to a database is saved automatically

the COMMIT statement


- related to INSERT, DELETE, UPDATE
- will save the changes you’ve made
- will let other users have access to the modified version of the
database
Transaction Control Language

DB administrator
Transaction Control Language

DB administrator
- Change the last name of the 4th customer from ‘Winnfield’ to ‘Johnson’
Transaction Control Language

DB administrator
- Change the last name of the 4th customer from ‘Winnfield’ to ‘Johnson’
Transaction Control Language

DB administrator
- Change the last name of the 4th customer from ‘Winnfield’ to ‘Johnson’
Transaction Control Language

DB administrator
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4;
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4;
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4;
Transaction Control Language

DB administrator

Problem: users
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4;
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4
COMMIT;
Transaction Control Language

DB administrator

users
Transaction Control Language

the COMMIT statement


Transaction Control Language

the COMMIT statement


committed states can accrue
Transaction Control Language

the COMMIT statement


committed states can accrue

the ROLLBACK clause


Transaction Control Language

the COMMIT statement


committed states can accrue

the ROLLBACK clause


the clause that will let you make a step back
Transaction Control Language

the COMMIT statement


committed states can accrue

the ROLLBACK clause


the clause that will let you make a step back
- allows you to undo any changes you have made but don’t want to be
saved permanently
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4
COMMIT;
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4
COMMIT;

ROLLBACK;
Transaction Control Language

DB administrator

UPDATE customers
SET last_name = ‘Johnson’
WHERE customer_id = 4
COMMIT;

ROLLBACK;
Transaction Control Language

the COMMIT statement


Transaction Control Language

the COMMIT statement


- saves the transaction in the database
Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone
Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone

the ROLLBACK clause


Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone

the ROLLBACK clause


- allows you to take a step back
Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone

the ROLLBACK clause


- allows you to take a step back
- the last change(s) made will not count
Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone

the ROLLBACK clause


- allows you to take a step back
- the last change(s) made will not count
- reverts to the last non-committed state
SQL Syntax

DDL – Data Definition Language

DML – Data Manipulation Language

DCL – Data Control Language

TCL – Transaction Control Language


SQL Syntax

DDL – Data Definition Language


creation of data

DML – Data Manipulation Language


manipulation of data

DCL – Data Control Language


assignment and removal of permissions to use this data

TCL – Transaction Control Language


saving and restoring changes to a database
Next:
Next:
More about Database Theory
Basic Database Terminology
Relational Schemas: Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key
these tables have a tabular shape
Relational Schemas: Primary Key
these tables have a tabular form

a relational schema can be applied to represent them


Relational Schemas: Primary Key
Relational Schemas: Primary Key

sales per customer of our company


Relational Schemas: Primary Key
Relational Schemas: Primary Key

the dates of a few purchases may coincide


Relational Schemas: Primary Key

the ID of a customer may appear a few times


Relational Schemas: Primary Key

there is a possibility to see the same item code a few times


Relational Schemas: Primary Key
Relational Schemas: Primary Key

all the numbers in this column will be different


Relational Schemas: Primary Key

primary key
a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key
Relational Schemas: Primary Key

Primary Key
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
Relational Schemas: Primary Key

Primary Key
may be composed of a set of columns
Relational Schemas: Primary Key

Primary Key
may be composed of a set of columns
e.g. “purchase_number” + “date_of_purchase”
Relational Schemas: Primary Key

Primary Key
may be composed of a set of columns
e.g. “purchase_number” + “date_of_purchase”
Relational Schemas: Primary Key

Primary Key
one-column primary key = all purchases will be recorded under a
different number
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
- primary keys are the unique identifiers of a table
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
- primary keys are the unique identifiers of a table
- cannot contain null values!
Relational Schemas: Primary Key

Primary Key
Relational Schemas: Primary Key

Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key
Relational Schemas: Primary Key

Table name: Sales


Primary key: purchase_number
Other fields: date_of_purchase, customer_id, item_code
Relational Schemas: Primary Key

=
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
- primary keys are the unique identifiers of a table
- cannot contain null values!
Relational Schemas: Primary Key

Primary Key

a column (or a set of columns) whose value exists and is unique for
every record in a table is called a primary key

- each table can have one and only one primary key
- in one table, you cannot have 3 or 4 primary keys
- primary keys are the unique identifiers of a table
- cannot contain null values!
- not all tables you work with will have a primary key
Relational Schemas: Primary Key

relational schema
Relational Schemas: Primary Key

database schema
Relational Schemas: Primary Key

database schema
(relational schemas)
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key

always look for the foreign keys, as


they show us where the relations are
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key

no repeating and missing values


Relational Schemas: Foreign Key

no repeating and missing values


(unique values only)
Relational Schemas: Foreign Key

no repeating and missing values


(unique values only)

repeating and missing values


Relational Schemas: Foreign Key
Relational Schemas: Foreign Key

ERROR
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key

no repeating and missing values


Relational Schemas: Foreign Key

no repeating and missing values

repeating and missing values


Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key
Relational Schemas: Foreign Key

foreign key
identifies the relationships between tables, not the tables themselves
Relational Schemas: Foreign Key
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values

?
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values

You can have two or more


companies with the same name
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values

You cannot have two US numbers that are completely identical


Relational Schemas: Unique Key & Null Values

?
Relational Schemas: Unique Key & Null Values

unique key
used whenever you would like to specify that you don’t want to see
duplicate data in a given field
Relational Schemas: Unique Key & Null Values

primary key unique key

NULL VALUES no yes


Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values

ERROR
Relational Schemas: Unique Key & Null Values

primary key unique key

NULL VALUES no yes

NUMBER OF KEYS 1 0, 1, 2…
Relational Schemas: Unique Key & Null Values

primary key unique key

NULL VALUES no yes

NUMBER OF KEYS 1 0, 1, 2…

APPLICATION TO
yes yes
MULTIPLE COLUMNS
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values
Relational Schemas: Unique Key & Null Values
Relationships
Relationships

Relationships
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa
Relationships
Relationships
Relationships

unique values
Relationships

unique values
Relationships

unique values

repeated values
Relationships

unique values

repeated values

one-to-many type of relationship


one value from the customer_id column under the “Customers” table can
be found many times in the customer_id column in the “Sales” table.
Relationships
Relationships
Relationships
Relationships

1 customer
Relationships

1 purchase 1 customer
Relationships

1 purchase 1 customer

or >1 purchase
Relationships

1 purchase 1 customer

or >1 purchase
Relationships

1 purchase 1 customer

or >1 purchase

minimum # of instances of the


“Customers” table that can be
associated with the “Sales” entity
Relationships

1 purchase 1 customer

or >1 purchase

1
minimum # of instances of the
“Customers” table that can be
associated with the “Sales” entity
Relationships

1 purchase 1 customer

or >1 purchase
Relationships

1 purchase 1 customer

or >1 purchase

maximum # of instances of the


“Customers” table that can be
associated with the “Sales” entity
Relationships

1 purchase 1 customer

or >1 purchase

maximum # of instances of the


“Customers” table that can be
many associated with the “Sales” entity
Relationships
Relationships
Relationships

1 purchase
Relationships

1 purchase 1 customer
Relationships

1 purchase minimum = 1 customer


Relationships

1 purchase minimum = 1 customer = maximum


Relationships

1 purchase minimum = 1 customer = maximum


Relationships

1 purchase minimum = 1 customer = maximum


Relationships
Relationships
Relationships

Customers to Sales: one-to-many


Relationships

Customers to Sales: one-to-many


Relationships

Customers to Sales: one-to-many

Sales to Customers: many-to-one


Relationships
Relationships

cardinality constraints
Relationships

M N
cardinality constraints
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa

types of relationships
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa

types of relationships
- one-to-many (many-to-one)
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa

types of relationships
- one-to-many (many-to-one)
- one-to-one
Relationships

Relationships
relationships tell you how much of the data from a foreign key field can
be seen in the primary key column of the table the data is related to
and vice versa

types of relationships
- one-to-many (many-to-one)
- one-to-one
- many-to-many
Relationships

Relational schemas
Relationships

Relational schemas
- represent the concept database administrators must implement
Relationships

Relational schemas
- represent the concept database administrators must implement
- depict how a database is organized
Relationships

Relational schemas
- represent the concept database administrators must implement
- depict how a database is organized
= blueprints, or a plan for a database
Relationships

Relational schemas
- represent the concept database administrators must implement
- depict how a database is organized
= blueprints, or a plan for a database

- will help you immensely while writing your queries!


Installing MySQL
and Getting Acquainted with the Interface
The Client-Server Model
The Client-Server Model

This is a visualization that explains which MySQL features we must


install and why.
The Client-Server Model

write code
(SQL query)

Client Program:
MySQL Server MySQL Workbench

2 provided by

obtain results
The Client-Server Model

The program we will be working with in this course is called MySQL


Workbench. It is the Oracle visual tool for database design, modelling,
creation, manipulation, maintenance, and administration. Professionals
refer to this type of software as “Integrated Development Environment”
or IDE. So, Workbench will be our IDE.

And, if you wonder what Oracle is, Client Program:


this is the software company that owns
the MySQL version of SQL. MySQL Workbench

provided by
The Client-Server Model

You could also wonder why we would need a server. Sticking to the basic
theory of operation of computer networks, MySQL Workbench acts as a
client program – a client of a MySQL Server.

Client Program:
MySQL Server MySQL Workbench

provided by
The Client-Server Model

The server is, practically, nothing more than a machine that provides
data and services to the same or other computers.

MySQL Server

The data could be provided locally or online. Regardless whether the


server is installed locally on your computer or is being accessed
remotely over the internet from another computer, you will need a Server
to use MySQL. In our case, we installed the server locally.
The Client-Server Model

Client Program:
MySQL Server MySQL Workbench

provided by
Briefly, the server will perform all calculations and operations you execute in
Workbench. You will be writing queries through the Workbench interface, in the
form of raw code, which MySQL server understands and processes.
The Client-Server Model

write code
(SQL query)

Client Program:
MySQL Server MySQL Workbench

provided by
Briefly, the server will perform all calculations and operations you execute in
Workbench. You will be writing queries through the Workbench interface, in the
form of raw code, which MySQL server understands and processes.
The Client-Server Model

Finally, when it finalizes its calculations, it will bring the respective


results back to you in the form of an output displayed on your screen.

Client Program:
MySQL Server MySQL Workbench

2 provided by
The Client-Server Model

Finally, when it finalizes its calculations, it will bring the respective


results back to you in the form of an output displayed on your screen.

Client Program:
MySQL Server MySQL Workbench

2 provided by

obtain results
The Client-Server Model

write code
(SQL query)

MySQL Server Client Program

2
obtain results
The Client-Server Model

write code
(SQL query)

Client Program:
MySQL Server MySQL Workbench

2 provided by

obtain results
First Steps in SQL
Creating a Database – Part I
Creating a Database – Part I

So far:
Creating a Database – Part I

So far:

- Theory of Relational Databases


Creating a Database – Part I

So far:

- Theory of Relational Databases


- SQL Theory
Creating a Database – Part I

So far:

- Theory of Relational Databases


- SQL Theory
- Download and Installation of MySQL Workbench (provided by )
Creating a Database – Part I

Sales
Creating a Database – Part I

Sales
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;


Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

CREATE DATABASE
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

CREATE DATABASE
creates a database as an abstract unit
Creating a Database – Part I
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

[IF NOT EXISTS]


Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

[IF NOT EXISTS]


verifies if a database with the same name exists already
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

[IF NOT EXISTS]


verifies if a database with the same name exists already
- the brackets around mean the statement is optional (you could either
type or omit the statement)
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

database_name
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

database_name
give a name that is short but at the same time as related to the content
of the data as possible
Creating a Database – Part I

Sales
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

database_name
give a name that is short but at the same time as related to the content
of the data as possible
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

database_name
give a name that is short but at the same time as related to the content
of the data as possible
- the SQL code is not case sensitive
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

database_name
give a name that is short but at the same time as related to the content
of the data as possible
- the SQL code is not case sensitive
- in this element the quotes are optional
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

; (the semicolon character)


Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

; (the semicolon character)


it functions as a statement terminator
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

; (the semicolon character)


it functions as a statement terminator
- when your code contains more than a single statement, ; is indispensable
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

; (the semicolon character)


it functions as a statement terminator
- when your code contains more than a single statement, ; is indispensable
- will help you avoid errors sometimes
Creating a Database – Part I

CREATE DATABASE [IF NOT EXISTS] database_name;

; (the semicolon character)


it functions as a statement terminator
- when your code contains more than a single statement, ; is indispensable
- will help you avoid errors sometimes
- will improve the readability of your code
Introduction to Data Types
Introduction to Data Types

We must always specify the type of data that will be


inserted in each column of the table

Different data types represent different types of information that can


be contained in a specific column
Introduction to Data Types

Surname of a
person:

string ‘James’
Introduction to Data Types

Surname of a
person:

string ‘James’

length

a measure used to indicate how many symbols a certain string has


Introduction to Data Types

Surname of a
person: length

string ‘James’ 5 symbols

‘Jackson’ 7 symbols

length

a measure used to indicate how many symbols a certain string has


Introduction to Data Types

Digits, symbols, or blank spaces can also be used in the


string format

they will only convey text information

e.g. addresses: ‘Hugh Street 45’


Introduction to Data Types

size

indicates the memory space used by a data type

- measured in bytes
- 1 byte ~ 1 symbol
Introduction to Data Types

Surname of a
person: length size

string ‘James’ 5 symbols 5 bytes


Introduction to Data Types

storage
the physical space in the computer drive’s memory, where the data is
being saved or stored
String Data Types
String Data Types

String – the text format in SQL

‘James’ – a variable of the string data type

= a variable of the alphanumeric data type


String Data Types

Example
string data type Storage

character CHAR fixed CHAR(5)


String Data Types

Example
string data type Storage length size
(symbols) (bytes)

character CHAR fixed CHAR(5)


‘James’ 5 5
‘Bob’ 3 5

CHAR(5)
5 represents the maximum number of symbols you are
allowed to use in writing a value in this format
String Data Types

Example
string data type Storage length size
(symbols) (bytes)

character CHAR fixed CHAR(5)


‘James’ 5 5
‘Bob’ 3 5

variable VARCHAR variable VARCHAR(5)


character
‘James’ 5 5
‘Bob’ 3 3
String Data Types

Maximum size
string data type
(bytes)

character CHAR 255

variable VARCHAR 65,535


character
String Data Types

Maximum size
string data type
(bytes)

character CHAR 255 50% faster

variable VARCHAR 65,535 a lot more responsive to


character the data value inserted
String Data Types

company CHAR(3)

Password:
the symbols cannot be more than password VARCHAR(10)
10 characters
String Data Types

string data type Example

character CHAR CHAR(5)

variable VARCHAR VARCHAR(5)


character

ENUM ENUM ENUM(‘M’,’F’)


(“enumerate”)
MySQL will show an error
if you attempt to insert
ERROR any value different from
“M” or “F”.
Integers
Integers
text ≠ numbers

numeric data types

integer fixed-point floating-point

integers
whole numbers with no decimal point

e.g. 5; 15; -200; 1,000

INTEGER INT
Integers

size minimum value maximum value


numeric data type (bytes) (signed/unsigned) (signed/unsigned)

-128 127
TINYINT 1
0 255
-32,768 32,767
SMALLINT 2
0 65,535
-8,388,608 8,388,607
MEDIUMINT 3
0 16,777,215
-2,147,483,648 2,147,483,647
INT 4
0 4,294,967,295
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
BIGINT 8
0 18,446,744,073,709,551,615
Integers
signed ≠ unsigned

if the encompassed range includes


both positive and negative values
Integers

size minimum value maximum value


numeric data type (bytes) (signed/unsigned) (signed/unsigned)

-128 127
TINYINT 1
0 255
-32,768 32,767
SMALLINT 2
0 65,535
-8,388,608 8,388,607
MEDIUMINT 3
0 16,777,215
-2,147,483,648 2,147,483,647
INT 4
0 4,294,967,295
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
BIGINT 8
0 18,446,744,073,709,551,615
Integers
signed ≠ unsigned

if the encompassed range includes


both positive and negative values
if integers are allowed to be only
positive
Integers

size minimum value maximum value


numeric data type (bytes) (signed/unsigned) (signed/unsigned)

-128 127
TINYINT 1
0 255
-32,768 32,767
SMALLINT 2
0 65,535
-8,388,608 8,388,607
MEDIUMINT 3
0 16,777,215
-2,147,483,648 2,147,483,647
INT 4
0 4,294,967,295
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
BIGINT 8
0 18,446,744,073,709,551,615
Integers

integer data types are ‘signed’ by default


Integers

size minimum value maximum value


numeric data type (bytes) (signed/unsigned) (signed/unsigned)

-128 127
TINYINT 1
0 256
-32,768 32,767
SMALLINT 2
0 65,535
-8,388,608 8,388,607
MEDIUMINT 3
0 16,777,215
-2,147,483,648 2,147,483,647
INT 4
0 4,294,967,295
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
BIGINT 8
0 18,446,744,073,709,551,615
Integers

integer data types are ‘signed’ by default

if you want to use a range containing only positive, ‘unsigned’ values,


you would have to specify this in your query
Integers

size minimum value maximum value


numeric data type (bytes) (signed/unsigned) (signed/unsigned)

-128 127
TINYINT 1
0 256
-32,768 32,767
SMALLINT 2
0 65,535
-8,388,608 8,388,607
MEDIUMINT 3
0 16,777,215
-2,147,483,648 2,147,483,647
INT 4
0 4,294,967,295
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
BIGINT 8
0 18,446,744,073,709,551,615
Integers

Why not just use BIGINT all the time?


Integers

Why not just use BIGINT all the time?

e.g. if you are sure that, in a certain column, you won’t need an

integer smaller than 0 or greater than 100, TINYINT would do the

job perfectly and you would not need more storage space per data point
Integers

Why not just use BIGINT all the time?

e.g. if you are sure that, in a certain column, you won’t need an

integer smaller than 0 or greater than 100, TINYINT would do the

job perfectly and you would not need more storage space per data point

a smaller integer type may increase the processing speed


Fixed- and Floating-Point Data Types
Fixed- and Floating-Point Data Types

number: precision

10.523 5

precision

refers to the number of digits in a number


Fixed- and Floating-Point Data Types

number: precision scale

10.523 5 3

scale

refers to the number of digits to the right of the decimal point in a


number
Fixed- and Floating-Point Data Types

number: precision scale

10.523 5 3

36.875 5 3

e.g. DECIMAL ( 5 , 3 )
Fixed- and Floating-Point Data Types
text ≠ numbers

numeric data types

integer fixed-point floating-point


Fixed- and Floating-Point Data Types

fixed-point data represent exact values

DECIMAL ( 5 , 3 ) 10.523

10.5 10.500

10.5236789 10.524
Fixed- and Floating-Point Data Types

fixed-point data represent exact values

when only one digit is specified within the parentheses, it will be


treated as the precision of the data type

DECIMAL ( 7 )
1234567
DECIMAL ( 7, 0 )
Fixed- and Floating-Point Data Types

fixed-point data represent exact values

DECIMAL has a synonymous data type. It is called NUMERIC.

DECIMAL = NUMERIC
Fixed- and Floating-Point Data Types
text ≠ numbers

numeric data types

integer fixed-point floating-point

INTEGER DECIMAL

NUMERIC
Fixed- and Floating-Point Data Types

DECIMAL = NUMERIC

e.g. salaries

NUMERIC ( p , s )

precision: p = 7

scale: s = 2

e.g. NUMERIC (7,2) $ 75,000.50


Fixed- and Floating-Point Data Types

floating-point data type


- used for approximate values only
- aims to balance between range and precision ( => “floating” )

FLOAT ( 5 , 3 ) 10.523

10.5236789 10.524

(10.524 is an approximate value)


Fixed- and Floating-Point Data Types

the main difference between the fixed- and the floating-point type
is in the way the value is represented in the memory of the computer

DECIMAL ( 5 , 3 )

10.5236789 10.524

FLOAT ( 5 , 3 )

10.5236789 10.524
Fixed- and Floating-Point Data Types
text ≠ numbers

numeric data types

integer fixed-point floating-point

INTEGER DECIMAL FLOAT

NUMERIC DOUBLE
Fixed- and Floating-Point Data Types

Floating-point size precision maximum number


data type (bytes) of digits

FLOAT 4 single 23

DOUBLE 8 double 53
Other Useful Data Types
Other Useful Data Types

DATE

used to represent a date in the format YYYY-MM-DD

1st of January 1000 - 31st of December 9999

e.g. 25th of July 2018: ‘2018-07-25’


Other Useful Data Types

DATE DATETIME

next to the date, we could save the time:


YYYY-MM-DD HH:MM:SS [.fraction]

0 – 23:59:59.999999

e.g. 25th of July 2018 9:30 a.m.: ‘2018-07-25 9:30:00’


Other Useful Data Types

DATETIME
represents the date shown on the calendar and the time shown on the
clock

vs.

TIMESTAMP
used for a well-defined, exact point in time
Other Useful Data Types

TIMESTAMP

used for a well-defined, exact point in time

1st of January 1970 UTC – 19th of January 2038, 03:14:07 UTC

- records the moment in time as the number of seconds passed after


the 1st of January 1970 00:00:00 UTC

e.g. 25th of July 2018: 1,535,155,200


Other Useful Data Types

TIMESTAMP
- representing a moment in time as a number allows you to easily
obtain the difference between two TIMESTAMP values

e.g. end time: ‘2018-07-25 10:30:00’ UTC TIMESTAMP


-
start time: ‘2018-07-25 09:00:00’ UTC TIMESTAMP

5,400 TIMESTAMP
Other Useful Data Types

TIMESTAMP is appropriate if you need to handle time zones

London = 1:00 a.m

Paris = 2:00 a.m

‘1970-01-01 01:00:00’ UTC


Other Useful Data Types

string, date, and time data types numeric data types

CHAR INTEGER

VARCHAR DECIMAL

DATE NUMERIC

DATETIME FLOAT

TIMESTAMP DOUBLE

data must be written only numeric values are


within quotes written without quotes
Other Useful Data Types

BLOB

Binary Large OBject

- refers to a file of binary data – data with 1s and 0s


- involves saving files in a record

*.doc *.xlsx *.xml *.jpg *.wav


Other Useful Data Types

*.jpg
Other Useful Data Types

string, date, and time data types numeric data types

CHAR INTEGER

VARCHAR DECIMAL

DATE NUMERIC

DATETIME FLOAT

TIMESTAMP DOUBLE
Creating a Table
Creating a Table

CREATE DATABASE [IF NOT EXISTS] sales;


Creating a Table

CREATE DATABASE [IF NOT EXISTS] sales;


CREATE TABLE table_name ( );
Creating a Table

CREATE DATABASE [IF NOT EXISTS] sales;


CREATE TABLE table_name ( );

compulsory requirement: add at least one column


Creating a Table

CREATE TABLE table_name


(
column_1 data_type constraints,
column_2 data_type constraints,

column_n data_type constraints
);
Creating a Table

Sales
Creating a Table

AUTO_INCREMENT
frees you from having to insert all purchase numbers manually through
the INSERT command at a later stage
Creating a Table

AUTO_INCREMENT
frees you from having to insert all purchase numbers manually through
the INSERT command at a later stage

- assigns 1 to the first record of the table and automatically


increments by 1 for every subsequent row
Creating a Table

AUTO_INCREMENT
sales
purchase_number
1
2
3
4


n
Creating a Table

AUTO_INCREMENT
sales
purchase_number
1
2
3
4


n
Creating a Table

Sales
Using Databases and Tables
Using Databases and Tables

queries
one of their main features is to manipulate data within a database
Using Databases and Tables

Sales
Using Databases and Tables

queries
one of their main features is to manipulate data within a database

e.g.

SELECT * FROM customers;


Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied
Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

SQL Objects:
- SQL table
Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

SQL Objects:
- SQL table
- views
- stored procedures
- functions
Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

1) set a default database


Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

1) set a default database

USE sales;
SELECT * FROM customers;
Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

1) set a default database

2) call a table from a certain database


Using Databases and Tables

Whenever you would like to refer to an SQL object in your


queries, you must specify the database to which it is
applied

1) set a default database

2) call a table from a certain database

database_object . sql_object
Using Databases and Tables

database_object . sql_object

. – “dot operator”
signals the existence of a connection between the two object types
Using Databases and Tables

database_object . sql_object

SELECT * FROM sales.customers;

. – “dot operator”
signals the existence of a connection between the two object types
Additional Notes on Using Tables
Additional Notes on Using Tables

query

a command you write in SQL with the idea of either retrieving


information from the database on which you are working, or,
alternatively, to insert, update, or delete data from it
Additional Notes on Using Tables

query

a command you write in SQL with the idea of either retrieving


information from the database on which you are working, or,
alternatively, to insert, update, or delete data from it

- it is a representation of a complete logical thought


Additional Notes on Using Tables

the DROP statement


used for deleting an SQL object
Additional Notes on Using Tables

the DROP statement


used for deleting an SQL object

DROP TABLE table_name;


Additional Notes on Using Tables

the DROP statement


used for deleting an SQL object

DROP TABLE table_name;

DROP TABLE sales;


MySQL Constraints
PRIMARY KEY Constraint
PRIMARY KEY Constraint

So far:
PRIMARY KEY Constraint

So far:

- Theory of Relational Databases


PRIMARY KEY Constraint

So far:

- Theory of Relational Databases


- SQL Theory
PRIMARY KEY Constraint

So far:

- Theory of Relational Databases


- SQL Theory
- Creating a Database
PRIMARY KEY Constraint

So far: In this section:

- Theory of Relational Databases


- SQL Theory
- Creating a Database
PRIMARY KEY Constraint

So far: In this section:

- Theory of Relational Databases - Constraints


- SQL Theory
- Creating a Database
PRIMARY KEY Constraint

So far: In this section:

- Theory of Relational Databases - Constraints


- SQL Theory In this lesson:
- Creating a Database
PRIMARY KEY Constraint

So far: In this section:

- Theory of Relational Databases - Constraints


- SQL Theory In this lesson:
- Creating a Database
- the PRIMARY KEY Constraint
PRIMARY KEY Constraint

constraints

specific rules, or limits, that we define in our tables


PRIMARY KEY Constraint

constraints

specific rules, or limits, that we define in our tables

- the role of constraints is to outline the existing


relationships between different tables in our database
PRIMARY KEY Constraint

constraints

specific rules, or limits, that we define in our tables

- the role of constraints is to outline the existing


relationships between different tables in our database

e.g. NOT NULL


PRIMARY KEY Constraint

Sales
FOREIGN KEY Constraint
FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

foreign key

points to a column of another table and, thus, links the two tables
FOREIGN KEY Constraint
FOREIGN KEY Constraint

child table
FOREIGN KEY Constraint

parent table

child table
FOREIGN KEY Constraint

parent table

child table
FOREIGN KEY Constraint

parent table = referenced table

child table = referencing table


FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

Sales
FOREIGN KEY Constraint

Sales

Remember, this is not an obligatory requirement – these two keys may


have two completely different names. What’s important is that the data
types and the information match! It’s just common practice to use, if
not the same, then similar names for both keys.
FOREIGN KEY Constraint

Sales

parent table = referenced table

child table = referencing table


FOREIGN KEY Constraint

a foreign key in SQL is defined through a foreign key


constraint
FOREIGN KEY Constraint

a foreign key in SQL is defined through a foreign key


constraint

the foreign key maintains the referential integrity within the database
FOREIGN KEY Constraint

ON DELETE CASCADE
if a specific value from the parent table’s primary key has been
deleted, all the records from the child table referring to this value
will be removed as well
FOREIGN KEY Constraint
FOREIGN KEY Constraint
FOREIGN KEY Constraint
FOREIGN KEY Constraint

ON DELETE CASCADE
UNIQUE Constraint
UNIQUE Constraint

unique key
used whenever you would like to specify that you don’t want to see
duplicate data in a given field
UNIQUE Constraint

unique key
used whenever you would like to specify that you don’t want to see
duplicate data in a given field

- ensures that all values in a column (or a set of columns)


are different
UNIQUE Constraint

unique keys are implemented in SQL through a constraint –


the UNIQUE Constraint
UNIQUE Constraint

unique keys are implemented in SQL through a constraint –


the UNIQUE Constraint

if you attempt to insert an already existing, duplicate value in the


unique column, SQL will display an error
UNIQUE Constraint

unique keys are implemented in SQL through a constraint –


the UNIQUE Constraint

if you attempt to insert an already existing, duplicate value in the


unique column, SQL will display an error

ERROR
UNIQUE Constraint

Sales
UNIQUE Constraint
UNIQUE Constraint

Indexes
UNIQUE Constraint

Indexes
unique keys in MySQL have the same role as indexes
UNIQUE Constraint

Indexes
unique keys in MySQL have the same role as indexes

the reverse isn’t true !!!


UNIQUE Constraint

Indexes
unique keys in MySQL have the same role as indexes

the reverse isn’t true !!!

index of a table

an organizational unit that helps retrieve data more easily


UNIQUE Constraint

Indexes
unique keys in MySQL have the same role as indexes

the reverse isn’t true !!!

index of a table

an organizational unit that helps retrieve data more easily

- it takes more time to update a table because indexes must be updated, too, and
that’s time consuming
UNIQUE Constraint
UNIQUE Constraint

ALTER TABLE table_name


DROP INDEX unique_key_field;
DEFAULT Constraint
DEFAULT Constraint

DEFAULT Constraint
DEFAULT Constraint

DEFAULT Constraint
helps us assign a particular default value to every row of a column
DEFAULT Constraint

DEFAULT Constraint
helps us assign a particular default value to every row of a column

- a value different from the default can be stored in a field where the
DEFAULT constraint has been applied, only if specifically indicated.
DEFAULT Constraint
DEFAULT Constraint

CREATE TABLE customers


(
customer_id INT,
first_name VARCHAR(255),
last_name VARCHAR(255),
email_address VARCHAR(255),
number_of_complaints INT DEFAULT 0,
PRIMARY KEY (customer_id)
);
DEFAULT Constraint
DEFAULT Constraint

2
DEFAULT Constraint

2 Peter Figaro M
Data Definition Language

Data Definition Language (DDL)


- CREATE
- ALTER
- DROP
NOT NULL Constraint
NOT NULL Constraint

primary key unique key

NULL VALUES no yes


NOT NULL Constraint

primary key unique key

NULL VALUES no yes

the “not null” restriction is applied through the NOT NULL Constraint
NOT NULL Constraint

primary key unique key

NULL VALUES no yes

the “not null” restriction is applied through the NOT NULL Constraint
- when you insert values in the table, you cannot leave the respective
field empty
NOT NULL Constraint

primary key unique key

NULL VALUES no yes

the “not null” restriction is applied through the NOT NULL Constraint
- when you insert values in the table, you cannot leave the respective
field empty
- if you leave it empty, MySQL will signal an error
ERROR
NOT NULL Constraint
NOT NULL Constraint

NOT NULL
NOT NULL Constraint

CREATE TABLE companies


(
company_id INT AUTO_INCREMENT,
headquarters_phone_number VARCHAR(255),
company_name VARCHAR(255),
PRIMARY KEY (company_id)
);
NOT NULL Constraint

CREATE TABLE companies


(
company_id INT AUTO_INCREMENT,
headquarters_phone_number VARCHAR(255),
company_name VARCHAR(255) NOT NULL,
PRIMARY KEY (company_id)
);
NOT NULL Constraint

Don’t confuse a NULL value with the value of 0 or with a


“NONE” response!

Think of a null value as a missing value.

0 NONE NULL

assigned by the assigned by the


user computer
NOT NULL Constraint

NULL
the value
of 0,
NOT NULL
NOT NULL Constraint

NULL
NOT NULL Constraint

NULL
NOT NULL Constraint

NULL
Next:
Coding Techniques and Best Practices
Data Manipulation
SQL Best Practices
Coding Techniques and Best Practices
Coding Techniques and Best Practices

complying with coding style is crucial


Coding Techniques and Best Practices

complying with coding style is crucial

- you will always work in a team


Coding Techniques and Best Practices

clean code

code that is focused and understandable, which means it must be


readable, logical, and changeable
Coding Techniques and Best Practices

good code is not the one computers understand; it is the one


humans can understand
Coding Techniques and Best Practices

good code is not the one computers understand; it is the one


humans can understand

code, in general, can be organized in several ways


Coding Techniques and Best Practices

good code is not the one computers understand; it is the one


humans can understand

code, in general, can be organized in several ways

good practice implies you will choose the version that will be easiest
to read and understand
Coding Techniques and Best Practices

good code is not the one computers understand; it is the one


humans can understand

code, in general, can be organized in several ways

good practice implies you will choose the version that will be easiest
to read and understand

assumption:
at your workplace, you will always type code cleanly –
as simple as possible, perfectly organized, maintaining a steady logical flow
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked


Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked


Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked

customer_purchase_unique_number
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked

customer_purchase_unique_number
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked

customer_purchase_unique_number
Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked


Coding Techniques and Best Practices
when assigning names to variables or SQL objects,
always chose shorter, meaningful names, conveying specific information

pronounceable, where one word per concept has been picked

- names will constitute more than 80% of your code


Coding Techniques and Best Practices

CREATE TABLE sales


(
purchase_number INT,
date_of_purchase DATE,
customer_id VARCHAR(255),
item_code VARCHAR(255),
PRIMARY KEY (purcase_number)
);
Coding Techniques and Best Practices
Coding Techniques and Best Practices

purchase_number
Coding Techniques and Best Practices

purchase_number

PurchaseNumber
Coding Techniques and Best Practices

purchase_number

PurchaseNumber

purchase number
Coding Techniques and Best Practices

purchase_number

PurchaseNumber

purchase number

ERROR
Coding Techniques and Best Practices

readability
Coding Techniques and Best Practices

readability

- horizontal and vertical organization of code


Coding Techniques and Best Practices

readability

- horizontal and vertical organization of code


- colour
Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently
Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently

- time is a factor
Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently

- time is a factor

- unification of coding style is a top-priority


Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently

- time is a factor

- unification of coding style is a top-priority

it is unprofessional to merge code written in the same language but in a


different style
Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently
Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently

2 use the relevant analogical tool provided in Workbench


Coding Techniques and Best Practices

use ad-hoc software that re-organizes code and colours


1
different words consistently

2 use the relevant analogical tool provided in Workbench

3 intervene manually and adjust your code as you like


Coding Techniques and Best Practices

comments

lines of text that Workbench will not run as code; they convey a
message to someone who reads our code
Coding Techniques and Best Practices

comments

lines of text that Workbench will not run as code; they convey a
message to someone who reads our code

/* … */ (for large comments)


Coding Techniques and Best Practices

comments

lines of text that Workbench will not run as code; they convey a
message to someone who reads our code

/* … */ (for large comments)


# or -- (for one-line comments)
Next:
Loading the ‘employees’ database
The SQL SELECT Statement
SELECT… FROM…
SELECT… FROM…

So far:
SELECT… FROM…

So far:

- Theory of Relational Databases


- SQL Theory
- Creating SQL Databases and Tables
- Creating SQL Constraints
SELECT… FROM…

So far: In this section:

- Theory of Relational Databases


- SQL Theory
- Creating SQL Databases and Tables
- Creating SQL Constraints
SELECT… FROM…

So far: In this section:

- Theory of Relational Databases - Data Manipulation


- SQL Theory
- Creating SQL Databases and Tables
- Creating SQL Constraints
SELECT… FROM…

the SELECT statement


SELECT… FROM…

the SELECT statement


allows you to extract a fraction of the entire data set
SELECT… FROM…

the SELECT statement


allows you to extract a fraction of the entire data set

- used to retrieve data from database objects, like tables


SELECT… FROM…

the SELECT statement


allows you to extract a fraction of the entire data set

- used to retrieve data from database objects, like tables


- used to “query data from a database”
SELECT… FROM…

SELECT column_1, column_2,… column_n


FROM table_name;
SELECT… FROM…

SELECT column_1, column_2,… column_n


FROM table_name;

- when extracting information, SELECT goes with FROM


SELECT… FROM…

SELECT column_1, column_2,… column_n


FROM table_name;
SELECT… FROM…

SELECT column_1, column_2,… column_n


FROM table_name;

SELECT first_name, last_name


FROM employees;
SELECT… FROM…

SELECT * FROM employees;

* - a wildcard character, means “all” and “everything”


WHERE
WHERE

SELECT * FROM employees;


WHERE

SELECT column_1, column_2,… column_n


FROM table_name;
WHERE

the WHERE clause


WHERE

the WHERE clause


it will allow us to set a condition upon which we will specify what part
of the data we want to retrieve from the database
WHERE

the WHERE clause


it will allow us to set a condition upon which we will specify what part
of the data we want to retrieve from the database

SELECT column_1, column_2,… column_n


FROM table_name;
WHERE

the WHERE clause


it will allow us to set a condition upon which we will specify what part
of the data we want to retrieve from the database

SELECT column_1, column_2,… column_n


FROM table_name
WHERE condition;
AND
AND

= equal operator
AND

= equal operator
in SQL, there are many other linking keywords and symbols, called
operators, that you can use with the WHERE clause
AND

= equal operator
in SQL, there are many other linking keywords and symbols, called
operators, that you can use with the WHERE clause

- AND
- OR
- IN - NOT IN
- LIKE - NOT LIKE
- BETWEEN… AND…
AND

= equal operator
in SQL, there are many other linking keywords and symbols, called
operators, that you can use with the WHERE clause

- AND - EXISTS - NOT EXISTS


- OR - IS NULL - IS NOT NULL
- IN - NOT IN - comparison operators
- LIKE - NOT LIKE - etc.
- BETWEEN… AND…
AND

AND
AND

AND
allows you to logically combine two statements in the condition code
block
AND

AND
allows you to logically combine two statements in the condition code
block

SELECT column_1, column_2,… column_n


FROM table_name
WHERE condition_1 AND condition_2;
AND

AND
allows you to logically combine two statements in the condition code
block

SELECT column_1, column_2,… column_n


FROM table_name
WHERE condition_1 AND condition_2;

- allows us to narrow the output we would like to extract from our data
OR
OR

AND
AND binds SQL to meet both conditions enlisted in the WHERE clause
simultaneously

SELECT column_1, column_2,… column_n


FROM table_name
WHERE condition_1 AND condition_2;
OR

AND
conditions set on different columns
OR

AND
conditions set on different columns

OR
conditions set on the same column
Operator Precedence
Operator Precedence

So far:
Operator Precedence

So far:

- AND
- OR
Operator Precedence

So far: In this lesson:

- AND
- OR
Operator Precedence

So far: In this lesson:

- AND - the logical order with which you must


comply when you use both operators in
- OR the same WHERE block
Operator Precedence

logical operator precedence


Operator Precedence

logical operator precedence


an SQL rule stating that in the execution of the query, the operator AND
is applied first, while the operator OR is applied second
Operator Precedence

logical operator precedence


an SQL rule stating that in the execution of the query, the operator AND
is applied first, while the operator OR is applied second

AND > OR
Operator Precedence

logical operator precedence


an SQL rule stating that in the execution of the query, the operator AND
is applied first, while the operator OR is applied second

AND > OR
regardless of the order in which you use these operators, SQL will
always start by reading the conditions around the AND operator
Wildcard Characters
Wildcard Characters

wildcard characters

% _ *

you would need a wildcard character whenever you wished to put


“anything” on its place
Wildcard Characters

% - a substitute for a sequence of characters

LIKE (‘Mar%’) Mark, Martin, Margaret

_ - helps you match a single character

LIKE (‘Mar_’) Mark, Marv, Marl


Wildcard Characters

* will deliver a list of all columns in a table

SELECT * FROM employees;

- it can be used to count all rows of a table


BETWEEN… AND…
BETWEEN… AND…

BETWEEN… AND…
helps us designate the interval to which a given value belongs
BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date BETWEEN '1990-01-01' AND '2000-01-01';
BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date BETWEEN '1990-01-01' AND '2000-01-01';

'1990-01-01' AND '2000-01-01' will be included in the retrieved list of


records
BETWEEN… AND…

NOT BETWEEN… AND…


BETWEEN… AND…

NOT BETWEEN… AND…


will refer to an interval composed of two parts:
BETWEEN… AND…

NOT BETWEEN… AND…


will refer to an interval composed of two parts:
- an interval below the first value indicated
BETWEEN… AND…

NOT BETWEEN… AND…


will refer to an interval composed of two parts:
- an interval below the first value indicated
- a second interval above the second value
BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date NOT BETWEEN '1990-01-01' AND '2000-01-01';
BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date NOT BETWEEN '1990-01-01' AND '2000-01-01';

- the hire_date is before '1990-01-01'


BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date NOT BETWEEN '1990-01-01' AND '2000-01-01';

- the hire_date is before '1990-01-01'


or
- the hire_date is after ‘2000-01-01'
BETWEEN… AND…

SELECT
*
FROM
employees
WHERE
hire_date NOT BETWEEN '1990-01-01' AND '2000-01-01';

'1990-01-01' AND '2000-01-01’ are not included in the intervals


BETWEEN… AND…

BETWEEN… AND…
BETWEEN… AND…

BETWEEN… AND…

- not used only for date values


BETWEEN… AND…

BETWEEN… AND…

- not used only for date values


- could also be applied to strings and numbers
IS NOT NULL / IS NULL
IS NOT NULL / IS NULL

IS NOT NULL
IS NOT NULL / IS NULL

IS NOT NULL
used to extract values that are not null
IS NOT NULL / IS NULL

IS NOT NULL
used to extract values that are not null

SELECT column_1, column_2,… column_n


FROM table_name
WHERE column_name IS NOT NULL;
IS NOT NULL / IS NULL

IS NULL
used to extract values that are null

SELECT column_1, column_2,… column_n


FROM table_name
WHERE column_name IS NULL;
Other Comparison Operators
Other Comparison Operators

So far:
Other Comparison Operators

So far:

- BETWEEN… AND…
- LIKE - NOT LIKE
- IS NOT NULL - IS NULL
Other Comparison Operators

So far: In this lecture:

- BETWEEN… AND…
- LIKE - NOT LIKE
- IS NOT NULL - IS NULL
Other Comparison Operators

So far: In this lecture:

- BETWEEN… AND… =, >, >=, =<, <, <>, !=


- LIKE - NOT LIKE
- IS NOT NULL - IS NULL
Other Comparison Operators

SQL

= equal to

> greater than

>= greater than or equal to

< less than

<= less than or equal to


Other Comparison Operators

SQL “Not Equal” operators

<>, != not equal,≠

different from
SELECT DISTINCT
SELECT DISTINCT

the SELECT statement


SELECT DISTINCT

the SELECT statement


can retrieve rows from a designated column, given some criteria
SELECT DISTINCT

SELECT DISTINCT
selects all distinct, different data values
SELECT DISTINCT

SELECT DISTINCT
selects all distinct, different data values

SELECT DISTINCT column_1, column_2,… column_n


FROM table_name;
Introduction to Aggregate Functions
Introduction to Aggregate Functions

aggregate functions

they are applied on multiple rows of a single column of a table and


return an output of a single value
Introduction to Aggregate Functions

COUNT()
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
returns the minimum value from the entire list
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
returns the minimum value from the entire list

MAX()
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
returns the minimum value from the entire list

MAX()
returns the maximum value from the entire list
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
returns the minimum value from the entire list

MAX()
returns the maximum value from the entire list

AVG()
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

SUM()
sums all the non-null values in a column

MIN()
returns the minimum value from the entire list

MAX()
returns the maximum value from the entire list

AVG()
calculates the average of all non-null values belonging to a certain
column of a table
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field
Introduction to Aggregate Functions

COUNT()
counts the number of non-null records in a field

- it is frequently used in combination with the reserved word “DISTINCT”


Introduction to Aggregate Functions

COUNT()

SELECT COUNT(column_name)
FROM table_name;
Introduction to Aggregate Functions

COUNT()

SELECT COUNT(column_name)
FROM table_name;

the parentheses after COUNT() must start right after the keyword, not
after a whitespace
Introduction to Aggregate Functions

COUNT(DISTINCT )

SELECT COUNT(DISTINCT column_name)


FROM table_name;
Introduction to Aggregate Functions

aggregate functions

they are applied on multiple rows of a single column of a table and


return an output of a single value

- they ignore NULL values unless told not to


GROUP BY
GROUP BY

When working in SQL, results can be grouped according to a specific


field or fields
GROUP BY

GROUP BY
When working in SQL, results can be grouped according to a specific
field or fields
GROUP BY

GROUP BY
When working in SQL, results can be grouped according to a specific
field or fields

- GROUP BY must be placed immediately after the WHERE conditions, if


any, and just before the ORDER BY clause
GROUP BY

GROUP BY
When working in SQL, results can be grouped according to a specific
field or fields

- GROUP BY must be placed immediately after the WHERE conditions, if


any, and just before the ORDER BY clause

- GROUP BY is one of the most powerful and useful tools in SQL


GROUP BY

GROUP BY

SELECT column_name(s)
FROM table_name
WHERE conditions
GROUP BY column_name(s)
ORDER BY column_name(s);
GROUP BY

GROUP BY
in most cases, when you need an aggregate function, you must add a
GROUP BY clause in your query, too

Always include the field you have grouped your results by in the
SELECT statement!
HAVING
HAVING

HAVING
HAVING

HAVING

- frequently implemented with GROUP BY


HAVING

HAVING
refines the output from records that do not satisfy a certain condition

- frequently implemented with GROUP BY


HAVING

SELECT column_name(s)
FROM table_name
WHERE conditions
GROUP BY column_name(s)
HAVING conditions
ORDER BY column_name(s);
HAVING

SELECT column_name(s)
FROM table_name
WHERE conditions
GROUP BY column_name(s)
HAVING conditions
ORDER BY column_name(s);

- HAVING is like WHERE but applied to the GROUP BY block


HAVING

WHERE vs. HAVING

after HAVING, you can have a condition with an aggregate function,


while WHERE cannot use aggregate functions within its conditions
WHERE vs HAVING
WHERE vs HAVING

WHERE
WHERE vs HAVING

WHERE
allows us to set conditions that refer to subsets of individual rows
WHERE vs HAVING

WHERE
allows us to set conditions that refer to subsets of individual rows

applied before re-organizing the output into groups


WHERE vs HAVING
WHERE vs HAVING

WHERE
WHERE vs HAVING

WHERE
re-organizing the
output into groups
(GROUP BY)
WHERE vs HAVING

WHERE
re-organizing the
output into groups
(GROUP BY)

the output can be further improved, or filtered


WHERE vs HAVING

WHERE
re-organizing the
output into groups
(GROUP BY)

HAVING
WHERE vs HAVING

WHERE
re-organizing the
output into groups
(GROUP BY)

HAVING
WHERE vs HAVING

WHERE
re-organizing the
output into groups
(GROUP BY)

HAVING

ORDER BY…
WHERE vs HAVING

HAVING
- you cannot have both an aggregated and a non-aggregated condition in
the HAVING clause
WHERE vs HAVING

Aggregate functions – GROUP BY and HAVING


WHERE vs HAVING

Aggregate functions – GROUP BY and HAVING

General conditions - WHERE


WHERE vs HAVING

SELECT column_name(s)
FROM table_name
WHERE conditions
GROUP BY column_name(s)
HAVING conditions
ORDER BY column_name(s);
LIMIT
LIMIT

SELECT column_name(s)
FROM table_name
WHERE conditions
GROUP BY column_name(s)
HAVING conditions
ORDER BY column_name(s)
LIMIT number ;
The SQL INSERT Statement
The INSERT Statement
The INSERT Statement

Sales
The INSERT Statement

The INSERT Statement

INSERT INTO table_name (column_1, column_2, …, column_n)


VALUES (value_1, value_2, …, value_n);
Inserting Data INTO a New Table
Inserting Data INTO a New Table

INSERT INTO SELECT

INSERT INTO table_2 (column_1, column_2, …, column_n)


SELECT column_1, column_2, …, column_n
FROM table_1
WHERE condition;
The SQL UPDATE Statement
TCL’s COMMIT and ROLLBACK
Transaction Control Language

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone

the ROLLBACK clause


- allows you to take a step back
- the last change(s) made will not count
- reverts to the last non-committed state
TCL’s COMMIT and ROLLBACK

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone
TCL’s COMMIT and ROLLBACK

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone
used to save the state of the data in the database at the moment of its
execution
TCL’s COMMIT and ROLLBACK

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone
used to save the state of the data in the database at the moment of its
execution

the ROLLBACK clause


- allows you to take a step back
- the last change(s) made will not count
- reverts to the last non-committed state
TCL’s COMMIT and ROLLBACK

the COMMIT statement


- saves the transaction in the database
- changes cannot be undone
used to save the state of the data in the database at the moment of its
execution

the ROLLBACK clause


- allows you to take a step back
- the last change(s) made will not count
- reverts to the last non-committed state
it will refer to the state corresponding to the last time you executed
COMMIT
TCL’s COMMIT and ROLLBACK
TCL’s COMMIT and ROLLBACK

COMMIT;

1
TCL’s COMMIT and ROLLBACK

COMMIT; COMMIT;

1 2
TCL’s COMMIT and ROLLBACK

COMMIT; COMMIT;

1 2 …
TCL’s COMMIT and ROLLBACK

COMMIT; COMMIT; COMMIT;

1 2 … 10
TCL’s COMMIT and ROLLBACK

COMMIT; COMMIT; COMMIT; ROLLBACK;

1 2 … 10 1
TCL’s COMMIT and ROLLBACK

- ROLLBACK will have an effect on the last execution you have performed

COMMIT; COMMIT; COMMIT; ROLLBACK;

1 2 … 10 1
TCL’s COMMIT and ROLLBACK

- ROLLBACK will have an effect on the last execution you have performed

COMMIT; COMMIT; COMMIT; ROLLBACK; ROLLBACK;

1 2 … 10 1 2
TCL’s COMMIT and ROLLBACK

- ROLLBACK will have an effect on the last execution you have performed

COMMIT; COMMIT; COMMIT; ROLLBACK; ROLLBACK;

1 2 … 10 1 2 …
TCL’s COMMIT and ROLLBACK

- ROLLBACK will have an effect on the last execution you have performed

COMMIT; COMMIT; COMMIT; ROLLBACK; ROLLBACK; ROLLBACK;

1 2 … 10 1 2 … 20
TCL’s COMMIT and ROLLBACK

- ROLLBACK will have an effect on the last execution you have performed

- you cannot restore data to a state corresponding to an earlier COMMIT

COMMIT; COMMIT; COMMIT; ROLLBACK; ROLLBACK; ROLLBACK;

1 2 … 10 1 2 … 20
The UPDATE Statement
The UPDATE Statement

the UPDATE Statement


The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table
The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table

UPDATE table_name
SET column_1 = value_1, column_2 = value_2 …
WHERE conditions;
The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table

UPDATE table_name
SET column_1 = value_1, column_2 = value_2 …
WHERE conditions;

- we do not have to update each value of the record of interest


The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table

UPDATE table_name
SET column_1 = value_1, column_2 = value_2 …
WHERE conditions;

- we do not have to update each value of the record of interest


- we can still say we have updated the specific record
The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table

UPDATE table_name
SET column_1 = value_1, column_2 = value_2 …
WHERE conditions;
The UPDATE Statement

the UPDATE Statement


used to update the values of existing records in a table

UPDATE table_name
SET column_1 = value_1, column_2 = value_2 …
WHERE conditions;

- if you don’t provide a WHERE condition, all rows of the table will be
updated
The SQL DELETE Statement
The DELETE Statement
The DELETE Statement

the DELETE statement


removes records from a database

DELETE FROM table_name


WHERE conditions;
FOREIGN KEY Constraint

ON DELETE CASCADE
if a specific value from the parent table’s primary key has been
deleted, all the records from the child table referring to this value
will be removed as well
DROP vs TRUNCATE vs DELETE
DROP vs TRUNCATE vs DELETE

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

DROP

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

DROP

column_1
1 indexes
2
3
4
+ + constraints


10
DROP vs TRUNCATE vs DELETE

DROP

column_1
1 indexes
2
3
4
+ + constraints


10
DROP vs TRUNCATE vs DELETE

DROP
- you won’t be able to roll back to its initial state, or to the last
COMMIT statement

use DROP TABLE only when you are sure you aren’t going to use the table
in question anymore
DROP vs TRUNCATE vs DELETE

TRUNCATE

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE ~ DELETE without WHERE

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE ~ DELETE without WHERE

column_1
1
2
3
4
+

10
DROP vs TRUNCATE vs DELETE

TRUNCATE ~ DELETE without WHERE

column_1
1
2
3
4
+

10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1
1
2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1
2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 11
2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 11
2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 11 1
2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 11 1
2 12
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 11 1
2 12 2
3 TRUNCATE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE
when truncating, auto-increment values will be reset

column_1 column_1
1 1
2 2
3 TRUNCATE 3
4 4

… …
10 10
DROP vs TRUNCATE vs DELETE

DELETE
DROP vs TRUNCATE vs DELETE

DELETE
removes records row by row
DROP vs TRUNCATE vs DELETE

DELETE
removes records row by row

DELETE FROM table_name


WHERE conditions;
DROP vs TRUNCATE vs DELETE

DELETE
removes records row by row

DELETE FROM table_name


WHERE conditions;

TRUNCATE ~ DELETE without WHERE


DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- the SQL optimizer will implement different programmatic approaches
when we are using TRUNCATE or DELETE
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- the SQL optimizer will implement different programmatic approaches
when we are using TRUNCATE or DELETE
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- the SQL optimizer will implement different programmatic approaches
when we are using TRUNCATE or DELETE

TRUNCATE delivers the output much quicker than DELETE


DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- the SQL optimizer will implement different programmatic approaches
when we are using TRUNCATE or DELETE

TRUNCATE delivers the output much quicker than DELETE


row by row row by row
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- the SQL optimizer will implement different programmatic approaches
when we are using TRUNCATE or DELETE

TRUNCATE delivers the output much quicker than DELETE


row by row row by row
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- auto-increment values are not reset with DELETE
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- auto-increment values are not reset with DELETE

column_1
1
2
3
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- auto-increment values are not reset with DELETE

column_1
1
2
3 DELETE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- auto-increment values are not reset with DELETE

column_1 column_1
1
2
3 DELETE
4


10
DROP vs TRUNCATE vs DELETE

TRUNCATE vs DELETE without WHERE


- auto-increment values are not reset with DELETE

column_1 column_1
1 11
2 12
3 DELETE 13
4 14

… …
10 20
Next:
Next:
SQL Functions
MySQL Aggregate Functions
COUNT()
COUNT()

So far:
COUNT()

So far:

- Theory of Relational Databases


- SQL Theory
- Coding Techniques and Best Practices
- SELECT, INSERT, UPDATE, DELETE
COUNT()

So far: Next:

- Theory of Relational Databases


- SQL Theory
- Coding Techniques and Best Practices
- SELECT, INSERT, UPDATE, DELETE
COUNT()

So far: Next:

- Theory of Relational Databases - Aggregate Functions


- SQL Theory
- Coding Techniques and Best Practices
- SELECT, INSERT, UPDATE, DELETE
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value

INPUT
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value

INPUT
the information contained
in multiple rows
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value

INPUT
the information contained
in multiple rows
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value

INPUT OUTPUT
the information contained
in multiple rows
COUNT()

aggregate functions
they gather data from many rows of a table, then aggregate it into a
single value

INPUT OUTPUT
the information contained the single value they
in multiple rows provide
COUNT()

COUNT()
COUNT()

COUNT()

SUM()
COUNT()

COUNT()

SUM()

MIN()
COUNT()

COUNT()

SUM()

MIN()

MAX()
COUNT()

COUNT()

SUM()

MIN()

MAX()

AVG()
COUNT()

COUNT()

SUM()

MIN()

MAX()

AVG()
COUNT()

COUNT()

SUM()

MIN() aggregate functions

MAX()

AVG()
COUNT()

COUNT()

SUM()

MIN() aggregate functions = summarizing functions

MAX()

AVG()
COUNT()

Why do these functions exist?


COUNT()

Why do these functions exist?

- they are a response to the information requirements of a company’s


different organizational levels
COUNT()

Why do these functions exist?

- they are a response to the information requirements of a company’s


different organizational levels

- top management executives are typically interested in summarized


figures and rarely in detailed data
COUNT()

COUNT()
applicable to both numeric and non-numeric data
COUNT()

COUNT(DISTINCT )
helps us find the number of times unique values are encountered in a
given column
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied

only if you have indicated a specific column name within the


parentheses
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied

only if you have indicated a specific column name within the


parentheses

Alternatively:
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied

only if you have indicated a specific column name within the


parentheses

Alternatively:
COUNT(*)
COUNT()

aggregate functions typically ignore null values throughout


the field to which they are applied

only if you have indicated a specific column name within the


parentheses

Alternatively:
COUNT(*)
* returns the number of all rows of the table, NULL values included
COUNT()

COUNT()
COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function
COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function

- you shouldn’t leave white space before opening the parentheses


COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function

- you shouldn’t leave white space before opening the parentheses

COUNT()
COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function

- you shouldn’t leave white space before opening the parentheses

COUNT() COUNT ()
COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function

- you shouldn’t leave white space before opening the parentheses

COUNT() COUNT _()


COUNT()

COUNT()

the parentheses and the argument must be attached to the name of the
aggregate function

- you shouldn’t leave white space before opening the parentheses

COUNT() COUNT _()


SUM()
SUM()

COUNT(*)
SUM()

COUNT(*)
* returns all rows of the table, NULL values included
SUM()

COUNT(*)
* returns all rows of the table, NULL values included

SUM(*)
SUM()

COUNT(*)
* returns all rows of the table, NULL values included

SUM(*)
SUM()

COUNT(*)
* returns all rows of the table, NULL values included

SUM(*)

* goes well with only the COUNT() function


SUM()

COUNT()
SUM()

COUNT() - applicable to both numeric and non-numeric data


SUM()

COUNT() - applicable to both numeric and non-numeric data

SUM()

MIN()

MAX()

AVG()
SUM()

COUNT() - applicable to both numeric and non-numeric data

SUM()

MIN()

MAX()

AVG()
SUM()

COUNT() - applicable to both numeric and non-numeric data

SUM()

MIN()
- work only with numeric data
MAX()

AVG()
MIN() and MAX()
MIN() and MAX()

MAX()
returns the maximum value of a column
MIN() and MAX()

MAX()
returns the maximum value of a column

MIN()
returns the minimum value of a column
AVG()
AVG()

AVG()
extracts the average value of all non-null values in a field
AVG()

COUNT()

SUM()

MIN()

MAX()

AVG()
AVG()

COUNT()

SUM() - aggregate functions can be applied to any group of


data values within a certain column

MIN()

MAX()

AVG()
AVG()

COUNT()

SUM() - aggregate functions can be applied to any group of


data values within a certain column

MIN()

MAX()

AVG()
AVG()

COUNT()

SUM() - aggregate functions can be applied to any group of


data values within a certain column

MIN()

MAX()

AVG()
AVG()

COUNT()

SUM() - aggregate functions can be applied to any group of


data values within a certain column

MIN()
frequently used together with a GROUP BY clause

MAX()

AVG()
ROUND()
ROUND()

ROUND(#,decimal_places)
ROUND()

ROUND(#,decimal_places)
numeric, or math, function you can use
ROUND()

ROUND(#,decimal_places)
numeric, or math, function you can use

- usually applied to the single values that aggregate functions return


COALESCE() - Preamble
COALESCE() - Preamble

Here we will study something a bit more sophisticated.

IF NULL() and COALESCE() are among the advanced SQL functions in the
toolkit of SQL professionals. They are used when null values are
dispersed in your data table and you would like to substitute the
null values with another value.

So, let’s adjust the “Departments” duplicate in a way that suits the
purposes of the next video, in which we will work with IF NULL() and
COALESCE().

First, let’s look at our table and see what we have there.
COALESCE() - Preamble

SELECT * FROM departments_dup;

Nine departments, with their department numbers and names provided. Ok!
COALESCE() - Preamble

Currently, as shown in the DDL statement of this table, the


“Department name” field is with a NOT NULL constraint, which
naturally means we must insert a value in each of its rows.
COALESCE() - Preamble

Now, with the ALTER TABLE statement and the CHANGE COLUMN command,
we will modify this constraint and allow null values to be
registered in the “department name” column.

ALTER TABLE departments_dup


CHANGE COLUMN dept_name dept_name VARCHAR(40) NULL;
COALESCE() - Preamble

Right after that, we will insert into the department number column
of this table a couple of data values – D-10 and D-11, the numbers
of the next two potential departments in the “Departments Duplicate”
table.

INSERT INTO departments_dup(dept_no) VALUES ('d010'), ('d011');


COALESCE() - Preamble

By running this SELECT query over here, you can see whether this
operation was carried out successfully.

SELECT
*
FROM
departments_dup
ORDER BY dept_no ASC;
COALESCE() - Preamble

We have the two new department numbers listed below, and in the
“Department name” column we can see two null values. The latter
happened because we allowed for null values to exist in this field,
“Department name”. Thus, Workbench will indicate that a value in a
cell is missing by attaching a “null” label to it. Great!
COALESCE() - Preamble

The next adjustment we’ll have to make is adding a third column


called “Department manager”. It will indicate the manager of the
respective department. For now, we will leave it empty, and will add
the NULL constraint. Finally, we will place it next to the
“Department name” column by typing “AFTER “Department name”.

ALTER TABLE employees.departments_dup


ADD COLUMN dept_manager VARCHAR(255) NULL AFTER dept_name;
COALESCE() - Preamble

Let’s check the state of the “Departments duplicate” table now.

SELECT
*
FROM
departments_dup
ORDER BY dept_no ASC;
COALESCE() - Preamble

Exactly as we wanted, right? The third column is completely empty


and we have null values in the last two records. These are the
“department name” and “manager” fields.
COALESCE() - Preamble

To save the “Departments duplicate” table in its current state,


execute a COMMIT statement.

COMMIT;

Here we’ll end the setup for the video about IF NULL() and
COALESCE().
Good luck!
IFNULL() and COALESCE()
IFNULL() and COALESCE()

IFNULL(expression_1, expression_2)
IFNULL() and COALESCE()

IFNULL(expression_1, expression_2)
returns the first of the two indicated values if the data value found in
the table is not null, and returns the second value if there is a null
value
IFNULL() and COALESCE()

IFNULL(expression_1, expression_2)
returns the first of the two indicated values if the data value found in
the table is not null, and returns the second value if there is a null
value
- prints the returned value in the column of the output
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


allows you to insert N arguments in the parentheses
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


allows you to insert N arguments in the parentheses

- think of COALESCE() as IFNULL() with more than two parameters


IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


allows you to insert N arguments in the parentheses

- think of COALESCE() as IFNULL() with more than two parameters


- COALESCE() will always return a single value of the ones we have
within parentheses, and this value will be the first non-null value of
this list, reading the values from left to right
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


- if COALESCE() has two arguments, it will work precisely like IFNULL()
IFNULL() and COALESCE()

IFNULL() and COALESCE() do not make any changes to the


data set. They merely create an output where certain data values
appear in place of NULL values.
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


- we can have a single argument in a given function
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


- we can have a single argument in a given function

- practitioners find this trick useful if some hypothetical result must


be provided in a supplementary column
IFNULL() and COALESCE()

COALESCE(expression_1, expression_2 …, expression_N)


- we can have a single argument in a given function

- practitioners find this trick useful if some hypothetical result must


be provided in a supplementary column
- COALESCE() can help you visualize a prototype of the table’s final
version
IFNULL() and COALESCE()

IFNULL() works with precisely two arguments


IFNULL() and COALESCE()

IFNULL() works with precisely two arguments

COALESCE() can have one, two, or more arguments


Next:
Next:
Joins
SQL Joins
Introduction to Joins
Introduction to Joins

joins
the SQL tool that allow us to construct a relationship between objects
Introduction to Joins
Introduction to Joins
Introduction to Joins

a join shows a result set, containing fields derived from two or more tables
Introduction to Joins

joins
- we must find a related column from the two tables that contains the
same type of data
Introduction to Joins
Introduction to Joins

joins
- we must find a related column from the two tables that contains the
same type of data
- we will be free to add columns from these two tables to our output
Introduction to Joins
Introduction to Joins

emp_no first_name last_name


Introduction to Joins

emp_no first_name last_name dept_no from_date


Introduction to Joins

emp_no first_name last_name dept_no from_date


Introduction to Joins

joins
- the columns you use to relate tables must represent the same object,
such as id
- the tables you are considering need not be logically adjacent
Introduction to Joins
Introduction to Joins

We will use two duplicate tables:

- ‘departments_dup’

- ‘dept_manager_dup’
Next:
INNER JOIN
INNER JOIN
INNER JOIN

INNER JOIN
INNER JOIN

INNER JOIN
INNER JOIN

INNER JOIN

Venn diagram
INNER JOIN

INNER JOIN

Venn diagram
a mathematical tool representing all possible logical relations
between a finite collection of sets
INNER JOIN

Venn diagram
a mathematical tool representing all possible logical relations
between a finite collection of sets
INNER JOIN

Venn diagram
a mathematical tool representing all possible logical relations
between a finite collection of sets
INNER JOIN

Which will be the related column here?


INNER JOIN

Related column: dept_no


INNER JOIN

the area that belongs to both circles, which is filled with red, represents all
records belonging to both the “Department Manager Duplicate” and the
“Departments Duplicate” tables
INNER JOIN

result set
the area that belongs to both circles, which is filled with red, represents all
records belonging to both the “Department Manager Duplicate” and the
“Departments Duplicate” tables
INNER JOIN

INNER JOIN
can help us extract this result set

result set
INNER JOIN

INNER JOIN
can help us extract this result set

result set
INNER JOIN

dept_no CHAR(4)
INNER JOIN

matching values = matching records


INNER JOIN

dept_no CHAR(4)

matching values = matching records


INNER JOIN
INNER JOIN

non-matching values = non-matching records


INNER JOIN

non-matching values = non-matching records


INNER JOIN

INNER JOIN

SELECT
table_1.column_name(s), table_2.column_name(s)
FROM
table_1
JOIN
table_2 ON table_1.column_name = table_2.column_name;
INNER JOIN

INNER JOIN

SELECT
t1.column_name, t1.column_name, …, t2.column_name, …
FROM
table_1 t1
JOIN
table_2 t2 ON t1.column_name = t2.column_name;
INNER JOIN
INNER JOIN
M D
INNER JOIN
inner joins extract only records in which the values in the related
columns match. Null values, or values appearing in just one of the two
tables and not appearing in the other, are not displayed
- only non-null matching values are in play
INNER JOIN

And what if such matching values did not exist?


INNER JOIN

And what if such matching values did not exist?


INNER JOIN

And what if such matching values did not exist?

Simply, the result set will be empty. There will be no link between the
two tables.
Duplicate Records
Duplicate Records

duplicate records, also known as duplicate rows, are


identical rows in an SQL table
Duplicate Records

duplicate records, also known as duplicate rows, are


identical rows in an SQL table

- for a pair of duplicate records, the values in each column coincide


Duplicate Records
duplicate rows are not always allowed in a database or a data table
Duplicate Records
duplicate rows are not always allowed in a database or a data table

- they are sometimes encountered, especially in new, raw, or uncontrolled data


Duplicate Records
duplicate rows are not always allowed in a database or a data table

- they are sometimes encountered, especially in new, raw, or uncontrolled data

here’s how to handle duplicates:

GROUP BY the field that differs most among records!


LEFT JOIN
LEFT JOIN

LEFT JOIN
LEFT JOIN

LEFT JOIN
LEFT JOIN
LEFT JOIN
LEFT JOIN

2 1

1) all matching values of the two tables +


2) all values from the left table that match no values from the right table
LEFT JOIN

all matching values of the two tables +


all values from the left table that match no values from the right table
LEFT JOIN

all matching values of the two tables +


all values from the left table that match no values from the right table
LEFT JOIN

all matching values of the two tables +


all values from the left table that match no values from the right table
LEFT JOIN

LEFT JOIN
when working with left joins, the order in which you join tables matters
LEFT JOIN
LEFT JOIN
LEFT JOIN
LEFT JOIN

INNER join
LEFT JOIN

INNER join
the result set is in the inner part of the Venn diagram
LEFT JOIN

LEFT join
LEFT JOIN

LEFT join
in the output obtained you have data from the
outer part of the Venn diagram too
LEFT JOIN

LEFT join = LEFT OUTER join


in the output obtained you have data from the
outer part of the Venn diagram too
LEFT JOIN

LEFT join = LEFT OUTER join


if you are using a left join, it will always be an
OUTER type of join
LEFT JOIN
left joins can deliver a list with all records from the left table that
do not match any rows from the right table
LEFT JOIN
left joins can deliver a list with all records from the left table that
do not match any rows from the right table
LEFT JOIN
left joins can deliver a list with all records from the left table that
do not match any rows from the right table
LEFT JOIN

SELECT
t1.column_name, t1.column_name, …, t2.column_name, …
FROM
table_1 t1
JOIN
table_2 t2 ON t1.column_name = t2.column_name
WHERE
column_name … IS NULL;
RIGHT JOIN
RIGHT JOIN

RIGHT JOIN
RIGHT JOIN

RIGHT JOIN

their functionality is identical to LEFT JOINs, with the only difference


being that the direction of the operation is inverted
RIGHT JOIN

RIGHT JOIN = RIGHT OUTER JOIN

their functionality is identical to LEFT JOINs, with the only difference


being that the direction of the operation is inverted
RIGHT JOIN
RIGHT JOIN
RIGHT JOIN
RIGHT JOIN
RIGHT JOIN
RIGHT JOIN

Whether we run a RIGHT JOIN or a LEFT JOIN with an inverted


tables order, we will obtain the same output, right?
RIGHT JOIN

Whether we run a RIGHT JOIN or a LEFT JOIN with an inverted


tables order, we will obtain the same output, right?

Yes, we will!
RIGHT JOIN
RIGHT JOIN
RIGHT JOIN

dept_no CHAR(4)
RIGHT JOIN

dept_no CHAR(4)

matching column = linking column


RIGHT JOIN

dept_no CHAR(4)

matching column = linking column


RIGHT JOIN

RIGHT JOIN
RIGHT JOIN

RIGHT JOIN
when applying a RIGHT JOIN, all the records from the right table will be
included in the result set
RIGHT JOIN

RIGHT JOIN
when applying a RIGHT JOIN, all the records from the right table will be
included in the result set
RIGHT JOIN

RIGHT JOIN
when applying a RIGHT JOIN, all the records from the right table will be
included in the result set

values from the left table will be included only if their linking column
contains a value coinciding, or matching, with a value from the
linking column of the right table
RIGHT JOIN

RIGHT JOIN
when applying a RIGHT JOIN, all the records from the right table will be
included in the result set

values from the left table will be included only if their linking column
contains a value coinciding, or matching, with a value from the
linking column of the right table
RIGHT JOIN
LEFT and RIGHT joins are perfect examples of one-to-many relationships
RIGHT JOIN
LEFT and RIGHT joins are perfect examples of one-to-many relationships
RIGHT JOIN
LEFT and RIGHT joins are perfect examples of one-to-many relationships

1 manager 1 department

or >1 managers
RIGHT JOIN
LEFT and RIGHT joins are perfect examples of one-to-many relationships
RIGHT JOIN
LEFT and RIGHT joins are perfect examples of one-to-many relationships

1 manager 1 department
The New and the Old Join Syntax
The New and the Old Join Syntax

- Relational Database Essentials


- MySQL Constraints
- SELECT, INSERT, UPDATE, DELETE
- MySQL Aggregate Functions
- INNER JOIN, LEFT JOIN, RIGHT JOIN
The New and the Old Join Syntax

Next:
- Relational Database Essentials
- MySQL Constraints
- SELECT, INSERT, UPDATE, DELETE
- MySQL Aggregate Functions
- INNER JOIN, LEFT JOIN, RIGHT JOIN
The New and the Old Join Syntax

Next:
- Relational Database Essentials - Subqueries, Self-joins
- MySQL Constraints - Stored Routines
- SELECT, INSERT, UPDATE, DELETE - Advanced SQL Tools
- MySQL Aggregate Functions
- INNER JOIN, LEFT JOIN, RIGHT JOIN
The New and the Old Join Syntax
The New and the Old Join Syntax
The New and the Old Join Syntax
The New and the Old Join Syntax
The New and the Old Join Syntax
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

connection points
The New and the Old Join Syntax

WHERE (the Old Join Syntax)

SELECT
t1.column_name, t1.column_name, …, t2.column_name, …
FROM
table_1 t1,
table_2 t2
WHERE
t1.column_name = t2.column_name;
The New and the Old Join Syntax

JOIN or WHERE?
The New and the Old Join Syntax

JOIN or WHERE?

- the retrieved output is identical


The New and the Old Join Syntax

JOIN or WHERE?

- the retrieved output is identical

- using WHERE is more time-consuming


The New and the Old Join Syntax

JOIN or WHERE?

- the retrieved output is identical

- using WHERE is more time-consuming

- the WHERE syntax is perceived as morally old and is rarely employed by


professionals
The New and the Old Join Syntax

JOIN or WHERE?

- the retrieved output is identical

- using WHERE is more time-consuming

- the WHERE syntax is perceived as morally old and is rarely employed by


professionals

- the JOIN syntax allows you to modify the connection between tables
easily
The New and the Old Join Syntax

JOIN (the New Join Syntax) vs WHERE (the Old Join Syntax)
JOIN and WHERE Used Together
JOIN and WHERE Used Together

JOIN + WHERE
JOIN and WHERE Used Together

JOIN + WHERE

JOIN:
- used for connecting the “employees” and “salaries” tables
JOIN and WHERE Used Together

JOIN + WHERE

JOIN:
- used for connecting the “employees” and “salaries” tables

WHERE:
- used to define the condition or conditions that will determine which will be
the connecting points between the two tables
JOIN and WHERE Used Together
FRAGILE
HANDLE WITH CARE
JOIN More Than Two Tables in SQL
JOIN More Than Two Tables in SQL
when creating a query that joins multiple tables, you must back it with
strong intuition and a crystal-clear idea of how you would like the
tables to be connected
JOIN More Than Two Tables in SQL

first_name last_name
JOIN More Than Two Tables in SQL

first_name last_name hire_date


JOIN More Than Two Tables in SQL

first_name last_name hire_date from_date


JOIN More Than Two Tables in SQL

first_name last_name hire_date from_date dept_name


JOIN More Than Two Tables in SQL

first_name last_name hire_date from_date dept_name


JOIN More Than Two Tables in SQL

first_name last_name hire_date from_date dept_name


Tips and Tricks for Joins
Tips and Tricks for Joins

dept_name
Tips and Tricks for Joins

dept_name average_salary
Tips and Tricks for Joins

dept_name average_salary
Tips and Tricks for Joins

dept_name average_salary
Tips and Tricks for Joins

JOINs
Tips and Tricks for Joins

JOINs
- one should look for key columns, which are common between the tables
involved in the analysis and are necessary to solve the task at hand
Tips and Tricks for Joins

JOINs
- one should look for key columns, which are common between the tables
involved in the analysis and are necessary to solve the task at hand
- these columns do not need to be foreign or private keys
Tips and Tricks for Joins

dept_name average_salary
UNION vs UNION ALL
UNION vs UNION ALL

UNION ALL
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

- you can think of it as a tool that allows you to unify tables


UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

SELECT
N columns
FROM
table_1
UNION ALL SELECT
N columns
FROM
table_2;
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

SELECT We have to select the same number of


N columns columns from each table.
FROM
table_1
UNION ALL SELECT
N columns
FROM
table_2;
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

SELECT We have to select the same number of


N columns columns from each table.
FROM These columns should have the same name,
table_1
UNION ALL SELECT
N columns
FROM
table_2;
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

SELECT We have to select the same number of


N columns columns from each table.
FROM These columns should have the same name,
table_1 should be in the same order,
UNION ALL SELECT
N columns
FROM
table_2;
UNION vs UNION ALL

UNION ALL
used to combine a few SELECT statements in a single output

SELECT We have to select the same number of


N columns columns from each table.
FROM These columns should have the same name,
table_1 should be in the same order, and should
UNION ALL SELECT contain related data types.
N columns
FROM
table_2;
Tips and Tricks for Joins
Tips and Tricks for Joins

_dup
UNION vs UNION ALL

UNION

SELECT
N columns
FROM
table_1
UNION SELECT
N columns
FROM
table_2;
UNION vs UNION ALL

when uniting two identically organized tables


UNION vs UNION ALL

when uniting two identically organized tables

- UNION displays only distinct values in the output


UNION vs UNION ALL

when uniting two identically organized tables

- UNION displays only distinct values in the output

- UNION ALL retrieves the duplicates as well


UNION vs UNION ALL

when uniting two identically organized tables

- UNION displays only distinct values in the output

- UNION ALL retrieves the duplicates as well


UNION vs UNION ALL

when uniting two identically organized tables

- UNION displays only distinct values in the output


- UNION uses more MySQL resources

- UNION ALL retrieves the duplicates as well


UNION vs UNION ALL

when uniting two identically organized tables

- UNION displays only distinct values in the output


- UNION uses more MySQL resources (computational power and storage space)

- UNION ALL retrieves the duplicates as well


UNION vs UNION ALL

Looking for better results?


UNION vs UNION ALL

Looking for better results?

- use UNION
UNION vs UNION ALL

Looking for better results?

- use UNION

Seeking to optimize performance?


UNION vs UNION ALL

Looking for better results?

- use UNION

Seeking to optimize performance?

- opt for UNION ALL


SQL Subqueries
SQL Subqueries with IN Nested Inside WHERE
SQL Subqueries with IN Nested Inside WHERE

subqueries
queries embedded in a query
SQL Subqueries with IN Nested Inside WHERE

subqueries
SQL Subqueries with IN Nested Inside WHERE

subqueries

queries embedded in a query


SQL Subqueries with IN Nested Inside WHERE

subqueries = inner queries

queries embedded in a query


SQL Subqueries with IN Nested Inside WHERE

subqueries = inner queries = nested queries

queries embedded in a query


SQL Subqueries with IN Nested Inside WHERE

subqueries = inner queries = nested queries

queries embedded in a query

- they are part of another query, called an outer query


SQL Subqueries with IN Nested Inside WHERE

subqueries = inner queries = nested queries = inner select

queries embedded in a query

- they are part of another query, called an outer query


SQL Subqueries with IN Nested Inside WHERE

subqueries = inner queries = nested queries = inner select

queries embedded in a query

- they are part of another query, called an outer query

= outer select
SQL Subqueries with IN Nested Inside WHERE

_dup
SQL Subqueries with IN Nested Inside WHERE

subqueries
SQL Subqueries with IN Nested Inside WHERE

subqueries
- a subquery should always be placed within parentheses
SQL Subqueries with IN Nested Inside WHERE
1) the SQL engine starts by running the inner query
SQL Subqueries with IN Nested Inside WHERE
1) the SQL engine starts by running the inner query

2) then it uses its returned output, which is intermediate, to execute


the outer query
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table
SQL Subqueries with IN Nested Inside WHERE

_dup
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table

- you can have a lot more than one subquery in your outer query
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table

- you can have a lot more than one subquery in your outer query
- it is possible to nest inner queries within other inner queries
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table

- you can have a lot more than one subquery in your outer query
- it is possible to nest inner queries within other inner queries

in that case, the SQL engine would execute the innermost query
first
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table

- you can have a lot more than one subquery in your outer query
- it is possible to nest inner queries within other inner queries

in that case, the SQL engine would execute the innermost query
first, and then each subsequent query
SQL Subqueries with IN Nested Inside WHERE

a subquery may return a single value (a scalar), a single row, a


single column, or an entire table

- you can have a lot more than one subquery in your outer query
- it is possible to nest inner queries within other inner queries

in that case, the SQL engine would execute the innermost query
first, and then each subsequent query, until it runs the outermost
query last
SQL Subqueries with EXISTS-NOT EXISTS
Nested Inside WHERE
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

if a row value of a subquery exists


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

if a row value of a subquery exists TRUE


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

the corresponding record of


if a row value of a subquery exists TRUE the outer query is extracted
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

the corresponding record of


if a row value of a subquery exists TRUE the outer query is extracted

if a row value of a subquery


doesn’t exist
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

the corresponding record of


if a row value of a subquery exists TRUE the outer query is extracted

if a row value of a subquery


doesn’t exist FALSE
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
EXISTS

checks whether certain row values are found within a subquery

- this check is conducted row by row

- it returns a Boolean value

the corresponding record of


if a row value of a subquery exists TRUE the outer query is extracted

if a row value of a subquery no row value from the outer


doesn’t exist FALSE query is extracted
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS IN
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS IN

tests row values


for existence
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS IN

tests row values searches among


for existence values
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS IN

tests row values searches among


for existence values

quicker in retrieving
large amounts of data
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE

EXISTS IN

tests row values searches among


for existence values

quicker in retrieving faster with


large amounts of data smaller datasets
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
ORDER BY (nested queries)
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
ORDER BY (nested queries)
it is more professional to apply ORDER BY in the outer query
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
ORDER BY (nested queries)
it is more professional to apply ORDER BY in the outer query

- it is more acceptable logically to sort the final version of your dataset


SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
some, though not all, nested queries can be rewritten using joins, which
are more efficient in general
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
some, though not all, nested queries can be rewritten using joins, which
are more efficient in general

this is true particularly for inner queries using the WHERE clause
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
- allow for better structuring of the outer query
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
- allow for better structuring of the outer query
- thus, each inner query can be thought of in isolation
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
- allow for better structuring of the outer query
- thus, each inner query can be thought of in isolation
- hence the name of SQL – Structured Query Language!
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
- allow for better structuring of the outer query
- thus, each inner query can be thought of in isolation
- hence the name of SQL – Structured Query Language!

- in some situations, the use of subqueries is much more intuitive


compared to the use of complex joins and unions
SQL Subqueries with EXISTS-NOT EXISTS Nested
Inside WHERE
subqueries:
- allow for better structuring of the outer query
- thus, each inner query can be thought of in isolation
- hence the name of SQL – Structured Query Language!

- in some situations, the use of subqueries is much more intuitive


compared to the use of complex joins and unions

- many users prefer subqueries simply because they offer enhanced code
readability
SQL Subqueries Nested in SELECT and FROM
SQL Subqueries Nested in SELECT and FROM

You have advanced with SQL a lot at this point!


SQL Subqueries Nested in SELECT and FROM

You have advanced with SQL a lot at this point!


SQL Subqueries Nested in SELECT and FROM

In this lecture:
SQL Subqueries Nested in SELECT and FROM

In this lecture:

challenging
task
SQL Subqueries Nested in SELECT and FROM

In this lecture:

challenging
task
SQL Subqueries Nested in SELECT and FROM

In this lecture:

challenging exercise
task
SQL Self Join
SQL Self Join
SQL Self Join

self join
SQL Self Join

self join
applied when a table must join itself
SQL Self Join

self join
applied when a table must join itself
- if you’d like to combine certain rows of a table with other rows of the
same table, you need a self-join
INNER JOIN

Related column: dept_no


INNER JOIN

in a self-join statement, you will have to comply with the same logical and
syntactic structure
SQL Self Join

in a self-join statement, you will have to comply with the same logical and
syntactic structure
SQL Self Join

in a self-join statement, you will have to comply with the same logical and
syntactic structure
SQL Self Join

- the 2 tables will be identical to the table you’ll be using in the self-join
SQL Self Join

- the 2 tables will be identical to the table you’ll be using in the self-join
SQL Self Join

=
- the 2 tables will be identical to the table you’ll be using in the self-join
SQL Self Join

=
- the 2 tables will be identical to the table you’ll be using in the self-join
- you can think of them as virtual projections of the underlying, base table
SQL Self Join

=
- the self-join will reference both implied tables and will treat them as two
separate tables in its operations
SQL Self Join

=
- the data used will come from a single source, which is the underlying table
that stores data physically
INNER JOIN
INNER JOIN

M D
SQL Self Join

=
- using aliases is obligatory
SQL Self Join

e1 = e2

- using aliases is obligatory


SQL Self Join

e1 = e2

- these references to the original table let you use different blocks of the
available data
SQL Self Join

e1 = e2

- you can either filter both in the join, or you can filter one of them in the
WHERE clause, and the other one – in the join
SQL Self Join

emp_manager

e1 = e2
SQL Views
Using SQL Views
Using SQL Views

view
a virtual table whose contents are obtained from an existing table or
tables, called base tables
Using SQL Views

view
a virtual table whose contents are obtained from an existing table or
tables, called base tables

- the retrieval happens through an SQL statement, incorporated into


the view
Using SQL Views
SQL View
Using SQL Views
SQL View
- think of a view object as a view into the base table
Using SQL Views
SQL View
- think of a view object as a view into the base table
- the view itself does not contain any real data; the data is physically
stored in the base table
Using SQL Views
SQL View
- think of a view object as a view into the base table
- the view itself does not contain any real data; the data is physically
stored in the base table
- the view simply shows the data contained in the base table
Using SQL Views
SQL View

CREATE VIEW view_name AS


SELECT
column_1, column_2,… column_n
FROM
table_name;
Using SQL Views
Using SQL Views
Using SQL Views
Using SQL Views
Using SQL Views
Using SQL Views
Using SQL Views

A view acts as a shortcut for writing the same SELECT statement every time a new
request has been made
Using SQL Views
SQL View
- saves a lot of coding time
Using SQL Views
SQL View
- saves a lot of coding time
- occupies no extra memory
Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table
Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table)

emp_no dept_no from_date to_date

10001 d005 1986-06-26 9999-01-01


Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table) ‘dept_emp’ (view)

emp_no dept_no from_date to_date emp_no dept_no from_date to_date

10001 d005 1986-06-26 9999-01-01 10001 d005 1986-06-26 9999-01-01


Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table)

emp_no dept_no from_date to_date

10001 d005 1986-06-26 9999-01-01


Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table)

emp_no dept_no from_date to_date

10001 d005 1986-06-26 2025-06-05


Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table) ‘dept_emp’ (view)

emp_no dept_no from_date to_date emp_no dept_no from_date to_date

10001 d005 1986-06-26 2025-06-05 10001 d005 1986-06-26 9999-01-01


Using SQL Views
SQL View
- acts as a dynamic table because it instantly reflects data and
structural changes in the base table

‘dept_emp’ (table) ‘dept_emp’ (view)

emp_no dept_no from_date to_date emp_no dept_no from_date to_date

10001 d005 1986-06-26 2025-06-05 10001 d005 1986-06-26 2025-06-05


Using SQL Views
SQL Views
Using SQL Views
SQL Views
Don’t forget they are not real, physical data sets, meaning we cannot
insert or update the information that has already been extracted.
Using SQL Views
SQL Views
Don’t forget they are not real, physical data sets, meaning we cannot
insert or update the information that has already been extracted.
- they should be seen as temporary virtual data tables retrieving
information from base tables
Stored Routines
Introduction to Stored Routines
Introduction to Stored Routines

routine (in a context other than computer science)

a usual, fixed action, or series of actions, repeated periodically


Introduction to Stored Routines

query output
Introduction to Stored Routines
Introduction to Stored Routines

stored routine
an SQL statement, or a set of SQL statements, that can be stored on the
database server

- whenever a user needs to run the query in question, they can


call, reference, or invoke the routine
Introduction to Stored Routines

algorithm
1) checks all monthly sales
generated throughout a
query calendar year
2) returns the lowest of these
values

stored routine
Introduction to Stored Routines

= 100
Introduction to Stored Routines

stored routine
Introduction to Stored Routines

stored routine
Introduction to Stored Routines

stored routine

= 100 - this routine can bring the desired result multiple times
Introduction to Stored Routines

stored routines

stored procedures functions


= procedures = user-defined
functions

≠ built-in functions
(aggregate functions,
datetime functions)
Introduction to Stored Routines

stored routines

stored procedures functions


The MySQL Syntax for Stored Procedures
The MySQL Syntax for Stored Procedures
semi-colons ;
- they function as a statement terminator
- technically, they can also be called delimiters

- by typing DELIMITER $$, you’ll be able to use the dollar symbols as


your delimiter

DELIMITER $$
The MySQL Syntax for Stored Procedures

Query #1 ;
Query #2 ;
call stored_procedure_1 ;
p_Query #1 ;

p_Query #2 ;

stored procedure
The MySQL Syntax for Stored Procedures

Query #1 ;
Query #2 ;
call stored_procedure_1 ;
p_Query #1 ;

p_Query #2 ;
Query #4 ;
Query #5 ;
… ; stored procedure
The MySQL Syntax for Stored Procedures

Query #1 ; $$ or //

Query #2 ;
DELIMITER $$
call stored_procedure_1 ;
p_Query #1 ;

p_Query #2 ;

stored procedure
The MySQL Syntax for Stored Procedures

Query #1 ;
Query #2 ;
DELIMITER $$
call stored_procedure_1 ;
p_Query #1 ;

p_Query #2 ;
Query #4 ;
Query #5 ;
… ; stored procedure
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name(param_1, param_2)

Parameters represent certain


values that the procedure will
use to complete the calculation
it is supposed to execute
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name() A procedure can be created
without parameters too!
Nevertheless, the parentheses
must always be attached to
its name
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
body of the procedure
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
+ BEGIN
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
query
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
;
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
;
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000$$
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000$$
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
DELIMITER ;
The MySQL Syntax for Stored Procedures

DELIMITER $$
CREATE PROCEDURE procedure_name()
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
From this moment on, $$ will not act as a
DELIMITER ; delimiter
Stored Procedures with an Input Parameter
Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure
Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter


Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter


Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter


Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter


Stored Procedures with an Input Parameter

DELIMITER $$
CREATE PROCEDURE procedure_name(in parameter)
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
DELIMITER ;
Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter


Stored Procedures with an Input Parameter
a stored routine can perform a calculation that transforms an input
value in an output value
stored procedures can take an input value and then use it in the query,
or queries, written in the body of the procedure

- this value is represented by the IN parameter

- after that calculation is ready, a result will be returned


Stored Procedures with an Output Parameter
Stored Procedures with an Output Parameter

DELIMITER $$
CREATE PROCEDURE procedure_name(in parameter, out parameter)
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
DELIMITER ;
Stored Procedures with an Output Parameter

DELIMITER $$
CREATE PROCEDURE procedure_name(in parameter, out parameter)
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
DELIMITER ;
Stored Procedures with an Output Parameter

DELIMITER $$
CREATE PROCEDURE procedure_name(in parameter, out parameter)
- BEGIN
SELECT * FROM employees
LIMIT 1000;
END$$
DELIMITER ;
Stored Procedures with an Output Parameter

DELIMITER $$
CREATE PROCEDURE procedure_name(in parameter, out parameter)
- BEGIN
SELECT * FROM employees
it will represent the variable
LIMIT 1000; containing the output value of
the operation executed by the
END$$
query of the stored procedure
DELIMITER ;
Stored Procedures with an Output Parameter
every time you create a procedure containing both an IN and an OUT
parameter, remember that you must use the SELECT-INTO structure in the
query of this object’s body!
Variables
Variables
when you are defining a program, such as a stored procedure for
instance, you can say you are using ‘parameters’
Variables
when you are defining a program, such as a stored procedure for
instance, you can say you are using ‘parameters’
- ‘parameters’ are a more abstract term
Variables
when you are defining a program, such as a stored procedure for
instance, you can say you are using ‘parameters’
- ‘parameters’ are a more abstract term

DELIMITER $$
CREATE PROCEDURE procedure_name (in , out )
Variables
when you are defining a program, such as a stored procedure for
instance, you can say you are using ‘parameters’
- ‘parameters’ are a more abstract term

DELIMITER $$
CREATE PROCEDURE procedure_name (in parameter , out )
Variables
when you are defining a program, such as a stored procedure for
instance, you can say you are using ‘parameters’
- ‘parameters’ are a more abstract term

DELIMITER $$
CREATE PROCEDURE procedure_name (in parameter , out parameter )
Variables
once the structure has been solidified, then it will be applied to the
database. The input value you insert is typically referred to as the
‘argument’, while the obtained output value is stored in a ‘variable’
Variables
once the structure has been solidified, then it will be applied to the
database. The input value you insert is typically referred to as the
‘argument’, while the obtained output value is stored in a ‘variable’

CREATE PROCEDURE …
Variables
once the structure has been solidified, then it will be applied to the
database. The input value you insert is typically referred to as the
‘argument’, while the obtained output value is stored in a ‘variable’

input:

CREATE PROCEDURE … argument


Variables
once the structure has been solidified, then it will be applied to the
database. The input value you insert is typically referred to as the
‘argument’, while the obtained output value is stored in a ‘variable’

input:

CREATE PROCEDURE … argument


Variables
once the structure has been solidified, then it will be applied to the
database. The input value you insert is typically referred to as the
‘argument’, while the obtained output value is stored in a ‘variable’

input: output:

CREATE PROCEDURE … argument variable


Variables

DELIMITER $$
CREATE PROCEDURE procedure_name (in parameter , out parameter )


input: output:

CREATE PROCEDURE … argument variable


Variables
IN-OUT parameters

CREATE PROCEDURE …
Variables
IN-OUT parameters

input:

CREATE PROCEDURE … IN parameter


Variables
IN-OUT parameters

input:

CREATE PROCEDURE … IN parameter


Variables
IN-OUT parameters

input:

CREATE PROCEDURE … OUT parameter


Variables
IN-OUT parameters

input = output

CREATE PROCEDURE … OUT parameter


User-Defined Functions in MySQL
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN
SELECT …
RETURN variable_name
END$$
DELIMITER ;
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN here you have no OUT parameters to
SELECT … define between the parentheses after
the object’s name
RETURN variable_name
END$$
DELIMITER ;
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN here you have no OUT parameters to
SELECT … define between the parentheses after
the object’s name
RETURN variable_name
all parameters are IN, and since this
END$$ is well known, you need not explicitly
indicate it with the word, ‘IN’
DELIMITER ;
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN
although there are no OUT
SELECT … parameters, there is a
RETURN variable_name ‘return value’

END$$
DELIMITER ;
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN
although there are no OUT
SELECT … parameters, there is a
RETURN variable_name ‘return value’
it is obtained after running the
END$$
query contained in the body of
DELIMITER ; the function
User-Defined Functions in MySQL

DELIMITER $$
CREATE FUNCTION function_name(parameter data_type) RETURNS data_type
DECLARE variable_name data_type
- BEGIN it can be of any data type
SELECT …
RETURN variable_name
END$$
DELIMITER ;
User-Defined Functions in MySQL
we cannot call a function!
User-Defined Functions in MySQL
we cannot call a function!
we can select it, indicating an input value within parentheses
User-Defined Functions in MySQL
we cannot call a function!
we can select it, indicating an input value within parentheses

SELECT function_name(input_value);
Stored Routines - Conclusion
Stored Routines - Conclusion

TECHNICAL DIFFERENCES
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

stored procedure
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

stored procedure
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

user-defined
stored procedure function
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

user-defined
stored procedure function

returns a value
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

user-defined
stored procedure function

does not return a returns a value


value
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

user-defined
stored procedure function

does not return a returns a value


value

CALL procedure;
Stored Routines - Conclusion

TECHNICAL DIFFERENCES

user-defined
stored procedure function

does not return a returns a value


value

CALL procedure; SELECT function;


Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT


parameters
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

- if you need to obtain more than one value as a result of a


calculation, you are better off using a procedure
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

- if you need to obtain more than one value as a result of a


calculation, you are better off using a procedure
- if you need to just one value to be returned, then you can use a
function
Stored Routines - Conclusion
how about involving an INSERT, an UPDATE, or a DELETE statement?
Stored Routines - Conclusion
how about involving an INSERT, an UPDATE, or a DELETE statement?

- in those cases, the operation performed will apply changes to the data in your
database
Stored Routines - Conclusion
how about involving an INSERT, an UPDATE, or a DELETE statement?

- in those cases, the operation performed will apply changes to the data in your
database
- there will be no value, or values, to be returned and displayed to the user
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

INSERT UPDATE

DELETE
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

INSERT UPDATE

DELETE
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

INSERT UPDATE INSERT UPDATE

DELETE DELETE
Stored Routines - Conclusion

CONCEPTUAL DIFFERENCES

user-defined
stored procedure function

can have multiple OUT can return a single


parameters value only

INSERT UPDATE INSERT UPDATE

DELETE DELETE
Stored Routines - Conclusion

user-defined
stored procedure function
Stored Routines - Conclusion

user-defined
stored procedure function

TECHNICAL DIFFERENCE
Stored Routines - Conclusion

user-defined
stored procedure function

TECHNICAL DIFFERENCE

CALL procedure; SELECT function;


Stored Routines - Conclusion

user-defined
stored procedure function

TECHNICAL DIFFERENCE

CALL procedure; SELECT function;

CONCEPTUAL DIFFERENCE
Stored Routines - Conclusion

user-defined
stored procedure function

TECHNICAL DIFFERENCE

CALL procedure; SELECT function;

CONCEPTUAL DIFFERENCE
- you can easily include
a function as one of the
columns inside a SELECT
statement
Stored Routines - Conclusion

user-defined
stored procedure function

TECHNICAL DIFFERENCE

CALL procedure; SELECT function;

CONCEPTUAL DIFFERENCE
- including a procedure - you can easily include
in a SELECT statement a function as one of the
is impossible columns inside a SELECT
statement
Stored Routines - Conclusion
once you become an advanced SQL user, and have gained a lot of practice,
you will appreciate the advantages and disadvantages of both types of
programs
Stored Routines - Conclusion
once you become an advanced SQL user, and have gained a lot of practice,
you will appreciate the advantages and disadvantages of both types of
programs
- you will encounter many cases where you should choose between procedures and
functions
Stored Routines - Conclusion
what we did in this section was to lay the foundation of the relevant
syntax, as well as performing exercises on the practical aspects of
these tools
Advanced SQL Topics
Types of MySQL Variables – Local Variables
Types of MySQL Variables – Local Variables

scope
the region of a computer program where a phenomenon, such as a
variable, is considered valid
Types of MySQL Variables – Local Variables

scope
the region of a computer program where a phenomenon, such as a
variable, is considered valid
Types of MySQL Variables – Local Variables

scope
the region of a computer program where a phenomenon, such as a
variable, is considered valid
Types of MySQL Variables – Local Variables

scope
the region of a computer program where a phenomenon, such as a
variable, is considered valid


Types of MySQL Variables – Local Variables

scope
the region of a computer program where a phenomenon, such as a
variable, is considered valid


Types of MySQL Variables – Local Variables

scope =
the region of a computer program where a phenomenon, such as a
variable, is considered valid


Types of MySQL Variables – Local Variables

scope = visibility
the region of a computer program where a phenomenon, such as a
variable, is considered valid


Types of MySQL Variables – Local Variables

MySQL Variables
Types of MySQL Variables – Local Variables

MySQL Variables
Types of MySQL Variables – Local Variables

MySQL Variables

local
Types of MySQL Variables – Local Variables

MySQL Variables

local
Types of MySQL Variables – Local Variables

MySQL Variables

local
session
Types of MySQL Variables – Local Variables

MySQL Variables

local
session
Types of MySQL Variables – Local Variables

MySQL Variables

local global
session
Types of MySQL Variables – Local Variables

MySQL Variables

local global
session
Types of MySQL Variables – Local Variables

MySQL Variables

local global
session

local variable
a variable that is visible only in the BEGIN – END block in which it was
created
Types of MySQL Variables – Local Variables
DECLARE is a keyword that can be used when creating local variables only

v_avg_salary is visible only in the BEGIN - END block


Session Variables
Session Variables

session
a series of information exchange interactions, or a dialogue, between a
computer and a user
Session Variables

session
a series of information exchange interactions, or a dialogue, between a
computer and a user

- e.g. a dialogue between the MySQL server and a client


application like MySQL Workbench
Session Variables
a session begins at a certain point in time and terminates at another,
later point
Session Variables
a session begins at a certain point in time and terminates at another,
later point
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1

set up a
connection
Step 1
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1

set up a
connection
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1

set up a
connection
Step 2
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1

set up a
connection
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2

set up a establish a
connection connection
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2

set up a establish a
connection connection
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3

set up a establish a the Workbench


connection connection interface will
open immediately
Step 3
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3


session

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3 Step 4


session

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3 Step 4


session

set up a establish a the Workbench end a


connection connection interface will connection
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3 Step 4


session

set up a establish a the Workbench end a


connection connection interface will connection
open immediately
Session Variables
a session begins at a certain point in time and terminates at another,
later point

Step 1 Step 2 Step 3 Step 4

set up a establish a the Workbench end a


connection connection interface will connection
open immediately
Session Variables
there are certain SQL objects that are valid for a specific session only
Session Variables
there are certain SQL objects that are valid for a specific session only

Step 1 Step 2 Step 3


session

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
there are certain SQL objects that are valid for a specific session only

Step 1 Step 2
session

set up a establish a the Workbench


connection connection interface will
open immediately
Session Variables
there are certain SQL objects that are valid for a specific session only

Step 1 Step 2
session

set up a establish a the Workbench end a


connection connection interface will connection
open immediately
Session Variables
there are certain SQL objects that are valid for a specific session only

Step 1 Step 2

set up a establish a the Workbench end a


connection connection interface will connection
open immediately
Session Variables

session variable

a variable that exists only for the session in which you are operating
Session Variables

session variable

a variable that exists only for the session in which you are operating

- it is defined on our server, and it lives there


Session Variables

session variable

a variable that exists only for the session in which you are operating

- it is defined on our server, and it lives there


- it is visible to the connection being used only
Session Variables
Session Variables

= 100
Session Variables

= 100 connections = 100


Session Variables

= 100 connections = 100 sessions = 100


Session Variables

“Var”

= 100 connections = 100 sessions = 100


Session Variables

“Var”

= 100 connections = 100 sessions = 100


Session Variables

SET @var_name = value;


Global Variables
Global Variables

global variables

global variables apply to all connections related to a specific server


Global Variables
Global Variables

“Var” “Var”
“Var” “Var”
“Var” “Var”
“Var”
“Var” “Var”
Global Variables

SET GLOBAL var_name = value;


Global Variables

SET GLOBAL var_name = value;

SET @@global.var_name = value;


Global Variables
you cannot set just any variable as global
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables

.max_connections()
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables

.max_connections()

.max_join_size()
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables

.max_connections() - indicates the maximum number of connections


to a server that can be established at a
certain point in time

.max_join_size()
Global Variables
you cannot set just any variable as global
- a specific group of pre-defined variables in MySQL is suitable for
this job. They are called system variables

.max_connections() - indicates the maximum number of connections


to a server that can be established at a
certain point in time

.max_join_size() - sets the maximum memory space allocated for


the joins created by a certain connection
User-Defined vs System Variables
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

user-defined
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

user-defined

system
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

user-defined variables that can be set by the user manually

system
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

user-defined variables that can be set by the user manually

system variables that are pre-defined on our system –


the MySQL server
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- local variables can be user-defined only


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- local variables can be user-defined only


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- only system variables can be set as global


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- only system variables can be set as global


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- both user-defined and system variables can be set as session variables


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- both user-defined and system variables can be set as session variables


User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined

system

- both user-defined and system variables can be set as session variables


there are limitations to this rule!
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined *

system *

- both user-defined and system variables can be set as session variables


there are limitations to this rule!
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined *

system *

- some of the system variables can be defined as global only; they


cannot be session variables
User-Defined vs System Variables
variables in MySQL can be characterized according to the way they have
been created

local session global

user-defined *

system *

- some of the system variables can be defined as global only; they


cannot be session variables (e.g. .max_connections() )
MySQL Indexes
MySQL Indexes
MySQL Indexes
MySQL Indexes
the index of a table functions like the index of a book
MySQL Indexes
the index of a table functions like the index of a book
- data is taken from a column of the table and is stored in a certain
order in a distinct place, called an index
MySQL Indexes
the index of a table functions like the index of a book
- data is taken from a column of the table and is stored in a certain
order in a distinct place, called an index

your datasets will typically contain 100,000+ or even 1,000,000+ records


MySQL Indexes
the index of a table functions like the index of a book
- data is taken from a column of the table and is stored in a certain
order in a distinct place, called an index

your datasets will typically contain 100,000+ or even 1,000,000+ records

- the larger a database is, the slower the process of finding the record
or records you need
MySQL Indexes
we can use an index that will increase the speed of searches related to
a table
MySQL Indexes
we can use an index that will increase the speed of searches related to
a table

CREATE INDEX index_name


ON table_name (column_1, column_2, …);
MySQL Indexes
we can use an index that will increase the speed of searches related to
a table

CREATE INDEX index_name


ON table_name (column_1, column_2, …);

the parentheses serve us to indicate the column


names on which our search will be based
MySQL Indexes
we can use an index that will increase the speed of searches related to
a table

CREATE INDEX index_name


ON table_name (column_1, column_2, …);

these must be fields from your data table you


will search frequently
MySQL Indexes
composite indexes
MySQL Indexes
composite indexes
- applied to multiple columns, not just a single one
MySQL Indexes
composite indexes
- applied to multiple columns, not just a single one

CREATE INDEX index_name


ON table_name (column_1, column_2, …);
MySQL Indexes
composite indexes
- applied to multiple columns, not just a single one

CREATE INDEX index_name


ON table_name (column_1, column_2, …);

- carefully pick the columns that would optimize your search!


MySQL Indexes
primary and unique keys are MySQL indexes
MySQL Indexes
primary and unique keys are MySQL indexes
- they represent columns on which a person would typically base their
search
MySQL Indexes
MySQL Indexes
SQL specialists are always aiming for a good balance between the
improvement of speed search and the resources used for its execution
MySQL Indexes
SQL specialists are always aiming for a good balance between the
improvement of speed search and the resources used for its execution

the costs of having an index might


small datasets be higher than the benefits
MySQL Indexes
SQL specialists are always aiming for a good balance between the
improvement of speed search and the resources used for its execution

the costs of having an index might


small datasets be higher than the benefits

a well-optimized index can make a


large datasets positive impact on the search
process

You might also like