E Textbook
E Textbook
0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations
2023
Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations
BACKGROUND
The e‐textbook titled “Database Basics and operations with MySQL” is intended for students registered in
the University of Health Sciences (UHS) in Vientiane, Laos.
The purpose of this e‐textbook is to present to the students the basic concepts of the modern databases
and the most basic characteristics and operations of the Structured Query Language – SQL.
OBJECTIVES
The objectives are as follows:
‐ To present the concepts of data management and the basic the modern databases
‐ To introduce the students to the different data types and the data definition concepts
‐ To present the basic SQL operations and queries
‐ To introduce the students to MySQL Server and its characteristics
‐ To show to the students the basic steps for database design and the related rules
Name Affiliation
Mr. Lattanavong Thammabavong University of Health Sciences, Vientiane, Laos
Mr. Seksith Vangkonevilay University of Health Sciences, Vientiane, Laos
Ms. Noy Lovanhuk University of Health Sciences, Vientiane, Laos
Assoc. Prof. Dr. Nina Bencheva University of Ruse “Angle Kanchev”, Ruse, Bulgaria
Prof. Dr. Georgi Hristov University of Ruse “Angle Kanchev”, Ruse, Bulgaria
Assoc. Prof. Dr. Plamen Zahariev University of Ruse “Angle Kanchev”, Ruse, Bulgaria
This E‐textbook is a part of the ASEAN FACTORI 4.0 project, supported by ERASMUS+ Program of the European Union.
ASEAN FACTORI 4.0: From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian
Nations, reference number: 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP.
Disclaimer: This publication reflects the views only of the authors, and the Commission cannot be held responsible for any use
which may be made of the information contained therein.
Project 609854‐EPP‐1‐2019‐1‐FR‐EPPKA2‐CBHE‐JP ‐ ASEAN FACTORI 4.0:
From Automation and Control Training to the Overall Roll‐out of Industry 4.0 across South East Asian Nations
TABLE OT CONTENTS
2.1. Data Types in MySQL Server. Numeric, String and Data Types.
2.2. Database Modeling. Data Definition using GUI Clients.
2.3. Basic SQL Queries. Data Definition using SQL.
2.4. Table Customization. Adding Rules, Constraints and Relationships.
2.5. Altering Tables. Changing Table Properties After Creation.
2.6. Deleting Data and Structures. Dropping and Truncating.
2.7. Summary
Chapter 8. Functions and Triggers – User‐defined Functions, Procedures, Triggers and Transactions
Total: 69.90
• Size
• Ease of updating
• Accuracy
• Security
• Redundancy
• Importance
• It parses requests from the user and takes the appropriate action
Database Engines
Database Basics and operations with MySQL
Database Engine Flow
• SQL Server uses the Client-Server Model
Data Data
TCP/IP
DATABASE
Source: http://db-engines.com/en/ranking
• Queries
Update clause Expression
• Clauses
UPDATE employees
• Expressions
SET salary = salary * 0.1
Statement WHERE job_title = "Cashier";
• Predicates
Predicate
• Statements
• Windows: dev.mysql.com/downloads/windows/installer/
• Ubuntu/Debian: dev.mysql.com/downloads/repo/apt/
• Instance
• Database/Schema Table Table
• Table Database(Schema)
Table Table
• Physical Storage
• Data files and Log files
• Data pages Data Logs
☰ ☰ ☰ ☰ ☰ ☰ ☰ ☰
Cell
• Each row is called a record or entity
• Columns (fields) define the type of data they contain
203 [email protected]
Primary Key Foreign Key
• Connection via Foreign Key in one table pointing to the Primary Key in another
Programmability
Customizing Database Behavior
Database Basics and operations with MySQL
Indices
• Indices make data lookup faster
• Clustered – bound to the primary key, physically sorts data
• Non-Clustered – can be any field, references the primary index
• Structured as an ordered tree
PK Index
Data ☰ ☰ ☰ ☰ ☰ ☰ ☰ Links ☰ ☰ ☰ ☰ ☰ ☰ ☰
CALL udp_get_employees_salary_above_35000
SELECT udf_get_age('1988-12-21');
• Enables us:
• To create a new database
• To create objects in the database (tables, stored procedures, relationships and
others)
• To change the properties of objects
• To enter records into the tables
• Click on row Create new index -> Primary from the context menu of
the desired row
Default value
ALTER TABLE people
ALTER COLUMN balance SET DEFAULT 0;
Column name
Join
Combine tables by
some column
Table 1 Table 2
Database Basics and operations with MySQL
SELECT – Examples
• Selecting all columns from the "departments" table
SELECT * FROM departments;
department_id name manager_id
1
List of columns Engineering Table name 12
2 Tool design 4
(* for3all) Sales 273
… … …
id Display name
first_name last_name
1 Guy Gilbert
2 Kevin Brown
… … …
• Usage:
v_table1_table2
Column 1 Column 2 Column 3
Table 2
Column 1 Column 2 Column 3
Existing source
• Or into an existing table List of columns
• Delete all rows from a table (TRUNCATE works faster than DELETE)
UPDATE `employees`
SET `salary` = `salary` * 1.10,
`job_title` = CONCAT('Senior',' ', `job_title`)
WHERE `department_id` = 3;
• Note: Don’t forget the WHERE clause!
Database Basics and operations with MySQL
Summary
• Other
SUBSTRING(String, Position)
String to replace
UPDATE books
SET title = REPLACE(title,"The","***")
WHERE SUBSTRING(title, 1, 3) = "The";
SELECT title from books
WHERE SUBSTRING(title, 1, 3) = "***";
LENGTH(String)
LEFT(String, Count)
RIGHT(String, Count)
LOCATE(Pattern, String,[Position])
• INSERT – insert substring at specific position
INSERT(String, Position, Length, Substring)
Number of characters
to delete
Database Basics and operations with MySQL
Arithmetical Operators and Numeric
Functions
Database Basics and operations with MySQL
Arithmetical Operators
• Supported common arithmetic operators
Name Description
DIV Integer division
/ Division operator
- Minus Operator
%, MOD Modulo operator
+ Addition operator
* Multiplication operator
- (arg) Change sign of argument
ABS(Value)
SQRT(Value)
POW(Value, Exponent)
SIGN(Value)
RAND()
RAND(Seed)
SELECT NOW();
• Finds any values that starts with "a" and ends with "o"
Regular expression
SELECT e.`department_id`,
MIN(e.`salary`) AS 'MinSalary'
FROM `employees` AS e
GROUP BY e.`department_id`;
Database Basics and operations with MySQL
COUNT
• COUNT - counts the values (not nulls) in one or more columns based
on grouping criteria
employee department_name salary
Adam Database Support 5,000 department_name SalaryCount
John Database Support 15,000 Database Support 2
Jane Application Support 10,000 Application Support 3
George Application Support 15,000 Software Support 1
Lila Application Support 5,000
Fred Software Support 15,000
• Unlike HAVING, the WHERE clause filters rows before the aggregation
Aggregated value
employe department_name salary Total
e Salary
Adam Database Support 5,000 department_name average_salary
20,000
John Database Support 15,000 Database Support 10,000
Jane Application Support 10,000 Software Support 15,000
George Application Support 15,000 10,000
Lila Application Support 5,000
Fred Software Support 15,000 15,000
SELECT
SUM(e.`salary) AS 'TotalSalary'
FROM `employees` AS e
GROUP BY e.`department_id`
HAVING SUM(e.`salary`) < 250000;
1 2 3
Identification of Defining table Defining primary
the entities columns keys
4 5 6
Modeling Defining
Filling test data
relationships constraints
• Exceptions
• Entities that have well known ID, e.g. countries (BG, DE, US) and currencies
(USD, EUR, BGN)
Mountains Peaks
mountain_id name peak_id mountain_id
1 Causasus 61 1
66 1
Relation
CONSTRAINT fk_peaks_mountains
FOREIGN KEY (mountain_id) Foreign Key
REFERENCES mountains(mountain_id);
Referent Table Primary Key
Mapping table
employees_projects
employee_id project_id
1 4
40 24
Database Basics and operations with MySQL
Setup
CREATE TABLE employees(
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50) Table Employees
);
Relation
CONSTRAINT fk_cars_drivers
FOREIGN KEY (driver_id) Foreign Key
REFERENCES drivers(driver_id)
Referent Table Primary Key
Join Condition
Database Basics and operations with MySQL
Problem: Peaks in Rila
• Report all peaks for "Rila" mountain.
• Report includes mountain's name, peak's name and also peak's elevation
• Peaks should be sorted by elevation descending
• Use database "Geography".
Sort
orders order_items
order_id order_name item_id order_id
1 … 4 1
22 … 24 22
87 1
Cascade delete
Edward 3 3 Sales
John NULL 4 Marketing
5 Purchasing
Edward 3 Sales
Database Basics and operations with MySQL
Cartesian Product
• This will produce Cartesian product:
SELECT last_name, name AS department_name
FROM employees, departments;
• The result:
last_name department_name
Gilbert Engineering
Brown Engineering
… …
Gilbert Sales
Brown Sales
• Formed when:
• A join condition is omitted
• A join condition is invalid
OUTER
(UNION) CROSS JOIN
JOIN
Database Basics and operations with MySQL
Tables
1 Alice 1 1 HTML5
2 Michael 1 2 CSS3
3 Caroline 2 3 JavaScript
4 David 5 4 PHP
5 Emma NULL 5 MySQL
students_name courses_name
Alice HTML5
Michael HTML5
SELECT students.name, courses.name
Caroline CSS3
FROM students
RIGHT JOIN courses NULL JavaScript
ON students.course_id = courses.id NULL PHP
David MySQL
Join Conditions
Database Basics and operations with MySQL
OUTER (FULL JOIN)
Relation
Database Basics and operations with MySQL
Join Overview: INNER JOIN
Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 18 Accounting
Jessica 15 22 Engineering
Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 15 Shipping And
Receiving
Jessica 15
18 Accounting
22 Engineering
NULL NULL
Sally 13 7 Executive
John 10 8 Sales
Michael 22 10 Marketing
Bob 11 12 HR
Robin 7 18 Accounting
Jessica 15 22 Engineering
Subqueries
Query Manipulation on Multiple Levels
id name course_id
SELECT * FROM students 1 Alice 1
WHERE course_id = 1; 2 Michael 1
Subquery
Table "employees"
Data ☰ ☰ ☰ ☰ ☰ ☰ ☰
Data ☰ ☰ ☰ ☰ ☰ ☰ ☰
CREATE INDEX
ix_users_first_name_last_name
ON users(first_name, last_name);
Columns
Table Name
• Returns the count of employees in the database who live in that town
Function Name
CREATE FUNCTION ufn_count_employees_by_town(town_name VARCHAR(20))
RETURNS DOUBLE
BEGIN
DECLARE e_count DOUBLE;
SET e_count := (SELECT COUNT(employee_id) FROM employees AS e
INNER JOIN addresses AS a ON a.address_id = e.address_id
INNER JOIN towns AS t ON t.town_id = a.town_id
WHERE t.name = town_name);
RETURN e_count; Function Logic
END
SELECT ufn_count_employees_by_town('Berlin'); 1
SELECT ufn_count_employees_by_town(NULL); 0
CALL usp_select_employees_by_seniority();
• DROP PROCEDURE
• Example of transaction
• A bank transfer from one account into another (withdrawal + deposit)
• If either the withdrawal or the deposit fails the whole operation is cancelled
Mario SURVIVE
STATE 1 STATE 2
Queries COMMIT
• ACID means:
• Atomicity
• Consistency
• Isolation
• Durability
Event Event
Events
• Add a trigger to employees table that logs deleted employees into the
deleted_employees table
• Use uni_ruse database
REFERENCES
1. Robin Dewson, Beginning SQL Server for Developers, 4th Edition, Apress Publishing, pp. 705,
ISBN: 1484202813, 2014;
2. Walter Shields, SQL QuickStart Guide: The Simplified Beginner's Guide to Managing,
Analyzing, and Manipulating Data With SQL (QuickStart Guides™ ‐ Technology), ClydeBank
Media LLC, pp. 242, ISBN: 1945051752, 2019;
3. Vinicius Grippa, Sergey Kuzmichev, Learning MySQL: Get a Handle on Your Data, 2nd Edition,
O'Reilly Media, pp. 629, ISBN: 1492085928, 2021;
4. Joel Murach, Murach's MySQL, 3rd Edition, Mike Murach & Associates Publishing, pp. 628,
ISBN: 1943872368, 2019;
6. Sveta Smirnova, Alkin Tezuysal, MySQL Cookbook: Solutions for Database Developers and
Administrators, 4th Edition, O'Reilly Media, pp. 971, ISBN: 1492093165, 2022;
7. Thomas Pettit, Scott Cosentino, The MySQL Workshop: A practical guide to working with data
and managing databases with MySQL, Packt Publishing, pp. 726, ISBN: 1839214902, 2022;
8. Adam Aspin, Querying MySQL: Make your MySQL database analytics accessible with SQL
operations, data extraction, and custom queries, BPB Publications, pp. 672, ISBN:
9355512678, 2022;