The webinar was conducted by Bhuvan Gandhi and Vishwas Ganatra on 22-23 August, 2020. It was powered by Encode - The coding club of PDPU.
Bhuvan Gandhi - https://github.com/bmg02/database-workshop-encode
Vishwas Ganatra - https://github.com/vishwasganatra/Encode-database-workshop
2. ABOUT US
Bhuvan Gandhi
Full stack web developer.
Experience: 2+ years
bm_gandhi
bmgandhi
vishwasganatra
vishwasganatra
0
bhuvan.gce18@sot.pdpu.ac.in vishwas.gce18@sot.pdpu.ac.in
Vishwas Ganatra
Full stack developer.
Experience: 3+ years
3. DAY 1 - LET’S BEGIN
1
Data types.
Commands.
Operators.
Constraints.
Keys.
Database
What is it?
Why we need it?
Types of DBs.
Schema architecture.
Functions of DBMS.
Popular DBs.
MySQL
What is it?
Power of MySQL.
MySQL GUI tools.
Terminologies.
Rules.
Let’s code
DDL syntaxes and examples.
DML syntaxes and examples.
DQL syntax and example.
Clause syntaxes and examples.
Understanding MySQL
We have covered only essential topics in this session to help you to build a foundation and to give you a kick-start by giving you the
enough knowledge about the subjects.
5. WHAT IS DB?
3
● Organized collection of structured information, or data, typically stored electronically
in a computer system.
● Controlled by Database Management System (DBMS).
● Data + DBMS = Database system.
● The stored data should be logically connected.
● The data is stored either in table format or in document format. (Detailed explanation is
given in the next slide)
● The data can be easily accessed, managed, modified, updated, controlled, and organized.
DBMS is an extension of human logic.
6. WHY WE NEED DB?
4
To overcome the limitations of traditional file system.
EfficiencySecurity
Automation
IntegrityScalability
Portability
8. TYPES OF DB
6
Root
Level 1 Level 2
Level 1.1 Level 2.1 Level 2.2
Organization based:
● Hierarchical
● Network
● NoSQL
● Object-oriented
● Relational
Data is stored in a tree structure. Each child record
in the tree will contain only one parent. On the
other hand, each parent record can have multiple
child records.
For searching a record, we need to traverse
through each level until the record is found.
9. TYPES OF DB
7
Company
Employees
Organization based:
● Hierarchical
● Network
● NoSQL
● Object-oriented
● Relational
Same as hierarchical. But here a child can have
more than one parent node.
It gives faster data access, search, and navigation
than hierarchical because it supports many-to-
many relationship. So, it provides better flexibility
and accessibility.
Managers
Customers Transactions
10. TYPES OF DB
8
Person
Organization based:
● Hierarchical
● Network
● NoSQL
● Object-oriented
● Relational
Stands for Not Only SQL. It doesn’t use SQL as
primary language for accessing data.
It does not have predefined schemas, which
makes it a perfect candidate for rapidly
developments.
Allows to make changes on the fly without
affecting applications.
Main categories: Column, Graph, Key-Value,
Document and Object.
{
“name”: “Bhuvan”,
“age”: 19,
...
}
11. TYPES OF DB
9
Organization based:
● Hierarchical
● Network
● NoSQL
● Object-oriented
● Relational
OODB = OOP + Relational database.
Focus is on Objects rather than actions.
Used to handle complex data models.
It has a caching mechanism. Caching is a data
retention method that makes it possible to
minimize disk access or network traffic flow.
+
12. TYPES OF DB
10
Organization based:
● Hierarchical
● Network
● NoSQL
● Object-oriented
● Relational
Categorized by a set of tables where data gets fit
into a pre-defined category.
The table consists of rows and columns where the
column has an entry for data for a specific category
and rows contains instance for that data defined
according to the category.
Widely used database because it is very simple to
use and easy to understand.
Persons
first_name last_name age
... ... ...
... ... ...
13. TYPES OF DB
11
Location based:
● Centralized
● Cloud
● Distributed
The data is stored centrally. Clients and servers are
using data through centralized database system.
Contains security and authentication mechanism
which allows only authorized users to access data.
So, we have to enforce the security at just one
location.
Suitable for small and medium size organizations.
Clients
Servers
Database
14. TYPES OF DB
12
Location based:
● Centralized
● Cloud
● Distributed
Data is stored in a virtual environment and
executes over the cloud computing platform.
Provides different services like Software as a
Service (SaaS), Platform as a Service (PaaS),
Infrastructure as a Service (IaaS) etc.
Widely used platforms are AWS, Google Cloud, MS
Azure etc.
Cloud is just someone else’s computer.
Clients
Databases
Cloud
15. TYPES OF DB
13
Location based:
● Centralized
● Cloud
● Distributed
Just opposite of centralized database. The data is not stored at
one place. It is distributed among different database systems of
an organization.
There are two types:
● Homogeneous: DBs which are executed on same OS and
running on same apps and hardware devices.
● Heterogeneous: DBs which are executed on different OS and
running on different apps and hardware devices.
Clients
Server
Databases
16. SCHEMA ARCHITECTURE
14
Internal schema
Conceptual schema Logical level
Internal level
Storage devices
End users
External level
Actual place where the data is stored i.e. HDD, SSD etc.
There could be one or more than one devices attached
with the system.
Also known as ANSI-SPARC architecture.
Views Each view schema describes the database part that a
particular user group is interested and hides the remaining
database from that user group.
Describes the structure of the whole database. Also
describes what data and the relationships between them.
Implementation of the data structure are hidden.
Also known as physical level. Describes how the data is
actually stored in the database and provides methods to
access data from the database.
Also responsible for allocating space to the data. Deals with
complex data structures at low-level.
17. FUNCTIONS OF DBMS
15
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
Data backup protects against data loss. If the
original data is lost, then using the backup it can
reconstructed.
Types:
Full backup, Differential backup and Transaction
Log.
Reasons behind data lost:
System crash, Transaction failure, Network failure,
Disk failure, Catastrophic event etc.
Devices:
Magnetic disks, HDDs etc.
If the data is lost, we recover data from the backup
devices.
Methods:
Log-based recovery and Recovery with Concurrent
Transactions.
18. FUNCTIONS OF DBMS
16
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
Manages the transactions simultaneously without
letting them interfere with each other.
Main objective is to allow many users perform
different operations at the same time.
It may lead to violation consistency and integrity if
there is no control on concurrency access.
Two protocols are used for concurrency control:
● Lock based protocols:
A mechanism to lock data item so that no one
can read or write when it is locked. There are
different types of lock for locking mechanism.
● Timestamp-based Protocols:
Every transaction has a timestamp associated
with it. The ordering is determined by the age of
the transaction.
19. FUNCTIONS OF DBMS
17
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
A data dictionary contains metadata – data about
the database. It consists of…
● Name of the tables in the database.
● Constraints of a table.
● Columns of the tables.
● Owner of the table.
● Last accessed information of the object.
● Last updated information of the object.
Types:
● Active Data Dictionary:
At any given point of time, if the structure or
specification of database is changed, then data
dictionary is automatically updated. It is the
responsibility of the DBMS.
● Passive Data Dictionary:
It is neither a part not managed by DBMS.
Changes in database structure need to be
applied in passive data dictionary manually or
with dedicated software.
20. FUNCTIONS OF DBMS
18
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
Responsible for creating and managing the complex
structures required for data storage.
The internal schema defines how the data should be
stored by the storage management. And the
storage manager interacts with the operating
system to access the physical storage.
It is also important for database performance tuning
which is related to the activities that make the
database perform more efficiently in terms of
storage and access speed.
21. FUNCTIONS OF DBMS
19
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
Data is stored collectively in file formats. A file is a
sequence of records stored in binary format.
A disk drive is formatted into several blocks that can
store records. File records are mapped onto those
disk blocks.
File organization types:
● Heap
● Sequential
● Hash
● Clustered
The organization of data inside a file plays a major
role in the process to locate the file pointer to a
desired record inside a file various based on whether
the records are arranged sequentially or clustered.
22. FUNCTIONS OF DBMS
20
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
It is a data structure technique to efficiently retrieve
records from the database files based on some
attributes on which the indexing has been done.
Types:
● Primary Index
● Secondary Index
● Clustering Index
● Dense Index
● Sparse index
● Multilevel index
23. FUNCTIONS OF DBMS
21
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Logical data independence
Transaction
It is defined as the ability to make changes in the
structure of the middle level of the DBMS without
affecting the highest-level schema or application
programs.
The modification in the logical level should not
result in any changes in the view levels or
application programs.
It is achieved by modifying the view level (external
level) to logical level mapping (VL - LL).
For example, changing the structure of relation
should not affect the external level.
24. FUNCTIONS OF DBMS
22
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Physical data independence
Transaction
Logical data independence
It is defined as the ability to make changes in the
structure of the lowest level of the DBMS without
affecting the higher-level schemas.
The modification in the Physical level should not
result in any changes in the Logical or View levels.
It is achieved by modifying the physical level to
logical level mapping (PL-LL mapping).
For example, changing the storage devices or
modifying the files at physical level should not affect
the data at the logical level.
25. FUNCTIONS OF DBMS
23
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recovery
Security
Transaction
Physical data independence
Logical data independence
It refers to the activities and measures to ensure the
confidentiality, integrity, and availability (CIA) of the
data.
Protecting the data in the database is a function of
authorization management. It defines procedures to
protect and guarantee database security and
integrity.
DBMS provides user access control mechanism to
set the user credentials and their privileges to
restrict unauthorized access on data.
DBMS also provides mechanism to allow only
specific data access to specific users.
To avoid misuse of data, developers can use
cryptography algorithms to encrypt data while
storing the sensitive data.
26. FUNCTIONS OF DBMS
24
Data dictionary management
Concurrency control
Data storage management
Indexing
File structure
Backup and recoveryTransaction
Security
Physical data independence
Logical data independence
A transaction can be defined as a group of tasks. A
single task is the minimum processing unit which
cannot be divided further.A transaction in a
database must maintain ACID properties.
● Atomicity:
It states that a transaction must be treated as an
atomic unit, that is, either all of its operations are
executed or none.
● Consistency:
It states that no transaction should have any
adverse effect on the data residing in the
database.
● Isolation:
When there are multiple transactions are
running on database, then no transaction
should interfere in any other transactions.
● Durability:
The database should be durable enough to hold
all its latest updates even if the system fails or
restarts.
27. POPULAR DBs
25
Relational database.
Free and open-source.
Lots of variety in user-interfaces.
Object-oriented database.
Paid and closed-source.
Suitable for large organizations.
Relational database.
Few versions are free. But all are
closed-source.
Relational database.
Free and-open source.
Better DB engine than MySQL.
Object-Relational database.
Free and open-source.
Supports JSON.
NoSQL database.
Community version is free. Not
fully open-source.
Uses JSON-like document
schema.
Trending nowadays.
29. WHAT IS MYSQL?
27
● SQL stands for Standard Query Language.
● It is the standardized language of the relational database.
● It is a database management system that allows you to manage relational databases.
● It is founded by David Axmark, Allan Larsson and Michael Widenius.
● “My” is the daughter’s name of the MySQL’s co-founder, Michael Widenius.
● It is open source and free to use. Though we can buy a commercial license version from
Oracle to get premium support services.
30. POWER OF MYSQL?
28
● is the world’s most used RDBMS. It is written in C and C++.
● it is tremendously flexible in providing robustness, scalability, and speed which are three
pillars of database performance.
● It works in client/server or embedded systems.
● Offers on-demand scalability.
● It provides high performance by ensuring optimum speed, full-text indexes and unique
memory caches.
● It works with almost every programming languages and operating systems.
● There are many organizations which are using MySQL for their backend support. Some of
them are given below.
Other
5.4 %
Oracle
1.8 %
Radis
8.4 %
PostgreSQL
17.4 %
MongoDB
24.6 %
MySQL
38.9 %
31. MYSQL GUI TOOLS
29
● As MySQL is among the most widely-used and popular database technologies, lots of tools
have been created to provide smooth experience in processes of designing, creating, and
administering databases.
● They come in free edition as well as in paid edition. As they all use the same database
technology, though they are different in terms of resource consumption, user-experience
etc. We can choose any one of them which fits in our requirements.
● Some of the popular tools are here.
● MySQL Workbench
● phpMyAdmin
● dbForge Studio
● SQLyog
● Relational
32. TERMINOLOGIES
30
Column
It is a set of data values of a particular type, one
value for each row of the database. Also known
as Attribute. Each row would provide a data
value for each column.
Consistency
It states that the data cannot be written that
would violate the database’s own rules for valid
data. If it violates, then that transaction must be
rolled back.
CRUD
Acronym for Create, Read, Update, Delete. It is a
common sequence of operations in database
applications.
Dependency
When one relation is dependent on another
relation. It shows that table stores some values
which are dependent on values of another table.
Instance
Defined as the data stored in database at a
particular moment of time. it changes frequently.
It is changed using different operations like
adding, updating or deleting.
Integrity
It refers that the data is correct. There are
integrity constraints which are used to maintain
the quality of information.
Metadata
Data about data. It helps to organize, find and
understand data. In RDBMS, it stores the
information related to table schema like data
types of columns, relationships, applied
constraints etc.
33. TERMINOLOGIES
31
Normalization
It is the process of minimizing redundancy from
a relation or set of relations. There are 6 stages:
1NF, 2NF, 3NF, BCNF, 4NF and 5NF.
Query
It is a request for data or information from a
database relation or combination of relations. A
database query can be either a select query or an
action.
Row
It is a data record within a table. Each row, which
represents a complete record of specific item
data, holds different data within the same
structure. Also known as tuple.
Redundancy
Defined as the repetition of same data in the DB.
It leads to violation of data consistency. It is not
possible to remove data redundancy completely
from DB but we can keep it as minimal as
possible.
Relationship
It defines how the data in one relation relates to
the data in another. There are different types of
relationships between relations of database.
Schema
It is the skeleton structure that represents the
logical view of the relation or database. It defines
how the data is organized and the relationships
among the data or relations. It also defines the
applied constraints on the data.
Table
It is a collection of data elements organised in
terms of rows and columns. Also known as
Relation.
34. RULES
32
● SQL statements are English-like statements. They starts with an action verb i.e. SELECT,
INSERT etc. And they are not case-sensitive.
● Each verb may be followed by number of clauses.
● A semicolon (;) is required at the end of an SQL statement.
● Character/String and date constants must be enclosed within quotes.
● Numeric constants must not enclosed with quotes. They can be either 101, 190.43 or 1.2E6
(Scientific notation).
● Double hyphen (--) for single line comment.
● /* ... */ for multi-line comment.
36. DATA TYPES
34
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Characteristics:
● Defines which kind of values it stores.
● The space that takes up and whether the values are a fixed-length or
variable length.
● The values of the data type can be indexed or not.
● How MySQL compares the values of a specific data type.
37. DATA TYPES
35
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Type Length (from - to)
BIT 0 - 1
TINYINT 0 - 255
SMALLINT -32,768 - 32,767
MEDIUMINT -8388608 - 8388607
INT -2,147,483,648 - 2,147,483,647
BIGINT -9,223,372,036, 854,775,808 - 9,223,372,036, 854,775,807
DECIMAL -10^38 +1 - 10^38 -1
FLOAT -1.79E + 308 - 1.79E + 308
REAL -3.40E + 38 - 3.40E + 38
38. DATA TYPES
36
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Type Description
CHAR Fixed length - Max. length of 8,000 characters (8 KB).
VARCHAR Var. length - Max. length of 8,000 characters (8 KB).
TINYTEXT Var. length - Max. length of 255 characters (255 B).
TEXT Var. length - Max. length of 65,535 characters (64 KB).
MEDIUMTEXT Var. length - Max. length of 16,777,215 characters (16 MB).
LONGTEXT Var. length - Max. length of 4,294,967,295 characters (4 GB).
39. DATA TYPES
37
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Type Description
DATE Stores date in the format YYYY-MM-DD.
TIME Stores time in the format HH:MI:SS.
DATETIME Stores date and time in the format YYYY-MM-DD HH:MI:SS.
TIMESTAMP Stores number of seconds passed since 1970-01-01 00:00:00 UTC.
YEAR Stores year in 2 or 4 digit format.
2-digit range: 70 to 69 (1970 to 2069).
4-digit range: 1901 to 2155.
40. DATA TYPES
38
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Type Description
TINYBLOB Var. length - Max. length of 255 characters (255 B).
BLOB Var. length - Max. length of 65,535 characters (64 KB).
MEDIUMBLOB Var. length - Max. length of 16,777,215 characters (16 MB).
LONGBLOB Var. length - Max. length of 4,294,967,295 characters (4 GB).
It is a Binary Large OBject that can hold a variable amount of data.
Mainly used for storing data files like images, videos etc.
41. DATA TYPES
39
Categories:
● Numeric
● Character and String
● Date and time
● Binary
● Miscellaneous
Type Description
BOOLEAN Var. length - Max. length of 255 characters (255 B).
ENUM Allows to store one value from the specified list. Max. 65,535 values
can be stored in the list. Value is targeted by it’s index number in list.
JSON Allows to store only JSON documents. Max. size is specified in system
variable called max_allowed_packet.
SET Same as ENUM. But it allows to store more than one value from the
specified list. Max. 64 distinct values are allowed to store in the list.
42. COMMANDS
40
DDL - Data Definition Language
Used to deal with the structure of the table. For example
creating/deleting table, updating table schema etc.
DDL commands are auto-committed. No need to pass
commit statement manually for saving permanently.
Commands: CREATE, ALTER, DROP etc.
DML - Data Manipulation Language
Used to deal with the data of the table. For example
inserting, deleting, updating etc.
DML commands are not auto-committed. We need to
pass commit manually.
Commands: INSERT, UPDATE, DELETE etc.
DQL - Data Query Language
Used to fetch data from the database.
Command: SELECT.
DCL - Data Control Language
Used to deal with DB authorization. It allows to
grant or revoke permissions from users on DB
entities.
Commands: GRANT and REVOKE.
TCL - Transmission Control Language
Can only be used with DML commands. It deals
with the transactions within the DB. It allows
manage the transactions of DB.
Commands: SAVEPOINT, ROLLBACK, COMMIT.
43. OPERATORS
41
Types:
● Arithmetic
● Comparison
● Logical
It is a symbol that tells the compiler or interpreter to perform
specific mathematical, relational or logical operation and produce
final result.
44. OPERATORS
42
Types:
● Arithmetic
● Comparison
● Logical
Operator Description
+ Used to add containing values of both operands.
- Used to subtract a right hand operand from left hand operand.
* Used to multiply both operands values.
/ Used to divides left hand operand by right hand operand.
% Divides left hand operand by right hand operand and returns reminder.
45. OPERATORS
43
Types:
● Arithmetic
● Comparison
● Logical
Operator Description
= Returns true if both operands value are equal.
!= <> Returns true if both operands value are not equal.
> Returns true if left operand value is greater than right operand value.
< Returns true if left operand value is smaller than right operand value.
>= Returns true if left operand value is greater than or equal to right
operand value.
<= Returns true if left operand value is smaller than or equal to right
operand value.
!> Return true if left operand value is not greater than the right operand
value.
!< Return true if right operand value is not smaller than the right operand
value.
46. OPERATORS
44
Types:
● Arithmetic
● Comparison
● Logical
Operator Description
ALL Used to compare a value to all values in another value set.
AND Used to combine multiple conditions in a query with WHERE clause.
ANY Used to compare a value to any applicable value in the list as per the
condition.
BETWEEN Used to search for between given range.
EXISTS Used to search the presence of a row that meets a certain criterion.
IN Used to compare a value in list of literal values that have beenspecified.
LIKE Used to compare a value to similar values using wildcard operators.
NOT It reverses the meaning of the logical operator with which it is used.
OR Used to combine multiple conditions in a query with WHERE clause.
IS NULL Used to compare a value with a NULL value.
UNIQUE It searches every row of a specified table for uniqueness.
47. CONSTRAINTS
45
It used to specify rules for the data in a table. It
limits the type of data that can go into a table.
This ensures the accuracy and reliability of the data
in the table. If there is any violation between the
constraint and the data action, the action is
aborted.
Operator Description
CHECK Controls the values in the associated column. It determines
whether the value is valid or not from a logical expression.
DEFAULT Each column must contain a value (including NULL). If no value is
supplied, then the column gets the value set as DEFAULT.
NOT NULL Allows to specify that a column can not contain any NULL value.
UNIQUE Does not allow to insert a duplicate value in a column. It maintains
the uniqueness of a column in the table.
48. KEYS
46
Keys play an important role in the relational
database. It is the part of constraints.
It is used to uniquely identify any record or row of
data from the table. It is also used to establish and
identify relationships between tables.
Super key is a superset of a candidate key.
Candidate key is a superset of a primary key.
Operator Description
SUPER KEY It is a set of one of more columns (attributes) to uniquely
identify rows in a table.
PRIMARY KEY Applied on columns to uniquely identify rows in that table.
COMPOSITE KEY It consists of more than one attribute to uniquely identify
rows in a table is called composite key.
CANDIDATE KEY A super key with no redundant attribute is known as
candidate key.
ALTERNATIVE KEY Out of all candidate keys, only one gets selected as PK,
remaining keys are known as alternate/secondary keys.
FOREIGN KEY It is applied on the column of a table which points to
primarykey of another table. It sets the cross-reference
between the tables.
49. LET’S CODE
47
DDL syntaxes and examples.
DML syntaxes and examples.
DQL syntax and example.
Clause syntaxes and examples.
50. DDL - DATA DEFINITION LANGUAGE
48
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
51. DDL - DATA DEFINITION LANGUAGE
49
CREATE
Used to create the database or its objects.
Syntax:
CREATE TABLE table_name (
column1 datatype(size),
[column2 datatype(size), ...]
);
Example:
CREATE TABLE employee (
id int(6),
name varchar(20),
dob date
);
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
52. DDL - DATA DEFINITION LANGUAGE
50
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
DROP
Used to delete objects from the database.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE employee;
53. DDL - DATA DEFINITION LANGUAGE
51
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
ALTER
Used to change the structure of the database.
Syntax:
ALTER TABLE table_name
ADD column_name datatype(size), ...;
ALTER TABLE table_name
MODIFY column_name datatype(size), ...;
ALTER TABLE table_name DROP column_name;
Example:
ALTER TABLE employee
ADD joined_on date;
54. DDL - DATA DEFINITION LANGUAGE
52
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
TRUNCATE
Used to remove all records from a table, including all spaces
allocated for the records are removed.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE employee;
55. DDL - DATA DEFINITION LANGUAGE
53
It consists of the SQL commands that can be used to define
the database schema.
It deals with descriptions of the database schema and is
used to create and modify the structure of database objects
in the database.
These commands are auto-committed. So, they can’t be
rolled back.
Commands:
● CREATE
● DROP
● ALTER
● TRUNCATE
● RENAME
RENAME
Used to rename an object existing in the database.
Syntax:
RENAME TABLE table_name TO new_table_name;
ALTER TABLE employee RENAME new_table_name;
Example:
RENAME TABLE employee TO emp_details;
56. DML - DATA MANIPULATION LANGUAGE
54
It deals with the manipulation of data present in the
database.
We need to commit manually to save it permanently. So,
they can be rolled back.
Commands:
● INSERT
● UPDATE
● DELETE
57. DML - DATA MANIPULATION LANGUAGE
55
It deals with the manipulation of data present in the
database.
We need to commit manually to save it permanently. So,
they can be rolled back.
Commands:
● INSERT
● UPDATE
● DELETE
INSERT
Used to insert data into a table.
Syntax:
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
INSERT INTO table_name
VALUES(value1, value2, value3, ...);
INSERT INTO table_name
VALUES(value1, value2, ...),
VALUES(value1, value 2, ...), ...;
Example:
INSERT INTO employee(id, name) VALUES(1, ‘Bob’);
58. DML - DATA MANIPULATION LANGUAGE
56
It deals with the manipulation of data present in the
database.
We need to commit manually to save it permanently. So,
they can be rolled back.
Commands:
● INSERT
● UPDATE
● DELETE
UPDATE
Used to update the existing data in a table.
Syntax:
UPDATE TABLE table_name
SET column_name = value
[WHERE condition...];
Example:
UPDATE TABLE employee
SET dob = ‘18-03-1998’
WHERE name = ‘Bob’;
59. DML - DATA MANIPULATION LANGUAGE
57
It deals with the manipulation of data present in the
database.
We need to commit manually to save it permanently. So,
they can be rolled back.
Commands:
● INSERT
● UPDATE
● DELETE
DELETE
Used to delete records from a database table.
Syntax:
DELETE FROM table_name
[WHERE condition...];
Example:
DELETE FROM employee
WHERE id = 1;
60. DQL - DATA QUERY LANGUAGE
58
Used to retrieve the data from one or multiple tables.
There is only one command: SELECT.
Syntax:
SELECT [DISTINCT] column1, column2, ... FROM table1, table2, ...
[WHERE conditions]
[GROUP BY columns HAVING conditions]
[ORDER BY column_name [DESC]]
[LIMIT j];
Example:
SELECT * FROM employee
WHERE dob < ‘2000-08-23’;
61. CLAUSES
59
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
62. CLAUSES
60
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
WHERE
Used to specify the selection criteria to retrieve only required
data from the tables.
Syntax:
SELECT column1, column2, ... FROM table_name
WHERE condition1 [ AND|OR condition2, ...];
Example:
SELECT name FROM employee
WHERE dob > ‘1995-08-23’ AND dob < ‘2000-08-23’;
63. CLAUSES
61
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
GROUP BY
Used to arrange identical data into groups.
Syntax:
SELECT column1, aggregation_func() FROM table_name
[WHERE conditions] GROUP BY column_name;
Example:
SELECT COUNT(*) FROM employee
GROUP BY name;
64. CLAUSES
62
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
HAVING
Used to specify a search condition for a group or an aggregate.
It mostly used with GROUP BY.
Syntax:
SELECT column1, column2, ... FROM table_name
[WHERE conditions]
GROUP BY column_name HAVING conditions;
Example:
SELECT COUNT(*) as total FROM employee
GROUP BY name HAVING total > 1;
65. CLAUSES
63
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
ORDER BY
Used to sorts the result-set in ascending or descending order.
Syntax:
SELECT column1, column2, ... FROM table_name
[WHERE conditions]
ORDER BY column1, column2, ... [ASC|DESC];
Example:
SELECT * FROM employee
ORDER BY name;
66. CLAUSES
64
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
DISTINCT
Used to retrieve only unique values of specified column.
Syntax:
SELECT DISTINCT column1, ... FROM table_name
[WHERE conditions] ...;
Example:
SELECT DISTINCT cities FROM employee;
67. CLAUSES
65
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
LIMIT
Used to constrain the number of rows to return. It takes two
args:
Offset: Specifies the offset of the first row to return.
Number of rows: Specifies the maximum number of rows to
return.
Syntax:
SELECT column1, ... FROM table_name
[WHERE conditions]
LIMIT [offset,] number_of_rows;
Example:
SELECT DISTINCT cities FROM employee
LIMIT 1, 5;
1
2
3
4
5
6
7
Offset
Numberofrows
68. CLAUSES
66
They are the special purpose keywords which are used for
filtering the data while retrieving the data.
Commands:
● WHERE
● GROUP BY
● HAVING
● ORDER BY
● DISTINCT
● LIMIT
● LIKE
LIKE
It is used in a WHERE clause to search for a specified pattern in
a column. There are mostly two operators:
% (Percent sign): Represents zero, one, or multiple characters.
_ (Underscore): Represents a single character.
Syntax:
SELECT column1, ... FROM table_name
[WHERE conditions]
LIKE pattern;
Examples:
Finds any value starts with a: LIKE ‘a%’
Finds any value ends with a: LIKE ‘%a’
Finds any value that have a: LIKE ‘%a%’
Finds any value that’s second character is a: LIKE ‘_a%’
Finds any value that has 5 characters: LIKE ‘_____’
Finds any value that starts with a and ends with z: LIKE ‘a%z’
69. END OF DAY 1
67
THANK YOU SO MUCH EVERYONE.
WE HOPE YOU HAVE LEARNED SOMETHING NEW.
SEE YOU ALL TOMORROW AT 11:00 AM.
FEEDBACK
http://bit.ly/db-feedback
70. DAY 2 - LET’S EXPLORE
68
Use of constraints.
Types of functions.
Subqueries.
Execution sequence.
Design an efficient DB.
Roadmap to master in DB.
71. USE OF CONSTRAINTS
69
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
72. USE OF CONSTRAINTS
70
DEFAULT
Syntax:
CREATE TABLE table_name (
column1 datatype(size) DEFAULT value,
...
);
Example:
ALTER TABLE employee
MODIFY email varchar(100) DEFAULT ‘NA’;
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
73. USE OF CONSTRAINTS
71
NOT NULL
Syntax:
CREATE TABLE table_name (
column1 datatype(size) NOT NULL,
...
);
Example:
ALTER TABLE employee
MODIFY email varchar(100) NOT NULL;
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
74. USE OF CONSTRAINTS
72
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
CHECK
Syntax:
Column level:
CREATE TABLE table_name (
column1 datatype(size) UNIQUE,
...
);
Table-level:
CREATE TABLE table_name (
column1 datatype(size),
... ,
UNIQUE (column1, column2, ...)
);
Example:
ALTER TABLE employee
MODIFY dob date UNIQUE;
75. USE OF CONSTRAINTS
73
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
PRIMARY KEY
Syntax:
Column level:
CREATE TABLE table_name (
column1 datatype(size) PRIMARY KEY,
...
);
Table-level:
CREATE TABLE table_name (
column1 datatype(size),
... ,
PRIMARY KEY (column1, column2, ...)
);
Example:
ALTER TABLE employee
MODIFY id int(6) PRIMARY KEY AUTO-INCREMENT;
76. USE OF CONSTRAINTS
74
Constraints are very useful for setting up the rules on which
type of data should be stored in DB. It used to maintain the
integrity of the data.
We can define the constraints while creating the table or
altering the table schema. Either on table-level or on
column-level.
Ways to enforce the constraints:
● DEFAULT
● NOT NULL
● UNIQUE
● PRIMARY KEY
● FOREIGN KEY
FOREIGN KEY
Syntax:
Column level:
CREATE TABLE table_name (
column1 datatype(size) REFERENCES table2(col_1),
...
);
Table-level:
CREATE TABLE table_name (
column1 datatype(size),
... ,
FOREIGN KEY (column1) REFERENCES table2(col_1);
);
Example:
ALTER TABLE projects
MODIFY emp_id int(6) REFERENCES employee(id);
77. TYPES OF FUNCTIONS
75
These are inbuilt functions. These functions allow
us to perform different types of manipulations on
the data. These functions can be broadly divided
into two types.
Aggregate: It perform calculations on a group of
values and then return a single value.
Scalar: returns a single value from the given input
value.
Types:
● Math
● String
● Date
78. TYPES OF FUNCTIONS
76
Math String Date
ABS
Returns the positive value of a number.
Syntax: ABS(number)
Example: SELECT ABS(-135.7) FROM dual;
Output: 135.7
AVG
Returns the average value of an expression.
Syntax: AVG(column1)
Example: SELECT AVG(salary) FROM employee;
EXP
Returns e (Euler’s number) raised to the power of
the specified number.
Syntax: EXP(number)
Example: SELECT EXP(2) FROM dual;
Output: 7.38905609893065
FLOOR / CEIL
Returns the largest/smallest integer value that is
smaller/larger than or equal to a number.
Syntax: FLOOR(number) / CEIL(number)
Example: SELECT FLOOR(12.5) FROM dual;
Output: 12
MIN / MAX
Returns the minimum/maximum value in a set
of values.
Syntax: MIN(column1) / MAX(column1)
Example: SELECT MIN(salary) FROM employee;
MOD
Returns the remainder of a number divided by
another number.
Syntax: MOD(x, y) / x MOD y / x % y
Example: SELECT MOD(18, 4) FROM dual;
Output: 2
POW
Returns the x raised to yth power. (xy).
Syntax: POW(x,y)
Example: SELECT POW(8, 3) FROM dual;
Output: 512
SQRT
Returns the square root of a number.
Syntax: SQRT(number)
Example: SELECT SQRT(64) FROM dual;
Output: 8
SUM
Returns the sum of a set of values (NULL values
are ignored).
Syntax: SUM(column1)
Example: SELECT SUM(salary) FROM employee;
79. TYPES OF FUNCTIONS
77
Date
CONCAT
Returns the string after adding one or more
expression together.
Syntax: CONCAT(exp1, exp2, exp3, ...)
Example: SELECT CONCAT(“My”, “Sql”) FROM
dual;
Output: MySql
CHAR_LENGTH
Returns the length of a string (counting chars).
Syntax: CHAR_LENGTH(str)
Example: SELECT CHAR_LENGTH(“€_SQL”) FROM
dual;
Output: 5
LENGTH
Returns the length of a string (counting bytes).
Syntax: LENGTH(str)
Example: SELECT LENGTH(“€_SQL”) FROM dual;
Output: 7
StringMath
REPLACE
Returns the string after replacing all occurrences
of a substring within a string, with a new
substring. It is case-sensitive.
Syntax: REPLACE(mainStr, fromStr, newStr)
Example: SELECT REPLACE(“ SQL”, “ ”, “My”)
FROM employee;
Output: MySQL
LOWER / UPPER
Returns the string in lower/upper case.
Syntax: LOWER(str) / UPPER(str)
Example: SELECT LOWER(“MySql”) FROM dual;
Output: mysql
REPEAT
Returns the string after repeating it as many as
specified.
Syntax: REPEAT(str, count)
Example: SELECT REPLACE(“SQL”, 3) FROM
employee;
Output: SQL
REVERSE
Returns the reverse of given string.
Syntax: REVERSE(str)
Example: SELECT REVERSE(“Hey”) FROM dual;
Output: yeH
80. TYPES OF FUNCTIONS
78
StringMath Date
CURRENT_DATE / CURRENT_TIME
Returns the current date/time in YYYY-MM-DD or
HH:MM:SS format.
Syntax: CURRENT_DATE() / CURRENT_TIME()
Example: SELECT CURRENT_DATE() FROM dual;
Output: 2020-08-23
CURRENT_TIMETSTAMP
Returns the current date-time in YYYY-MM-DD
HH:MM:SS format.
Syntax: CURRENT_TIMESTAMP()
Example: SELECT CURRENT_TIMESTAMP() FROM
dual;
Output: 2020-08-23 11:00:01
DATE / TIME
Returns date or time after extracting it from the
given date-time format..
Syntax: DATE(exp) / TIME(exp)
Example: SELECT DATE(“2020-08-23
11:00:01”) FROM dual;
Output: 2020-08-23
DATEDIFF / TIMEDIFF
Returns the difference between two date/time
values.
Syntax: DATEDIFF(date1, date2) /
TIMEDIFF(time1, time2)
Example: SELECT DATEDIFF("2020-08-22",
"2020-08-23") from dual;
Output: -1
DATE_FORMAT / TIME_FORMAT
Returns the date or time formatting in specified
format.
Syntax: DATE_FORMAT(date, format) /
TIME_FORMAT(time, format)
Example: SELECT TIME_FORMAT('16:40:28',
'%h:%i %p') FROM dual;
Output: 4:40 PM
UNIX_TIMESTAMP
Returns the UNIX epoch timestamp of current
date-time or specified date-time.
Syntax: UNIX_TIMESTAMP([date])
Example: SELECT UNIX_TIMESTAMP() FROM
dual;
Output: 1598160601
81. SUBQUERIES
79
It is a query within another SQL query and embedded
within the WHERE clause.
Also known as inner query and nested query.
It is used with the DML and DQL statements along with the
comparison and logical operators.
● SELECT
● INSERT
● UPDATE
● DELETE
Rules:
● Subqueries must be enclosed within parentheses.
● A subquery can have only one column in the SELECT
clause.
● ORDER BY cannot be applied to subquery, although main
query can use ORDER BY.
● Subqueries that return more than one row can only be
used with multiple value operators such as the IN
operator.
● The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.
82. SUBQUERIES
80
It is a query within another SQL query and embedded
within the WHERE clause.
Also known as inner query and nested query.
It is used with the DML and DQL statements along with the
comparison and logical operators.
● SELECT
● INSERT
● UPDATE
● DELETE
With SELECT statement
Subqueries are most frequently used with SELECT statements.
Syntax:
SELECT column1, column2, ... FROM table_names
WHERE column_name OPERATOR (
SELECT column_name FROM table_names
[WHERE conditions]
);
Example:
SELECT * FROM employee
WHERE dept_id IN (
SELECT dept_id FROM departments
WHERE dept_name = ‘HR’
);
83. SUBQUERIES
81
It is a query within another SQL query and embedded
within the WHERE clause.
Also known as inner query and nested query.
It is used with the DML and DQL statements along with the
comparison and logical operators.
● SELECT
● INSERT
● UPDATE
● DELETE
With INSERT statement
Here, we use subquery with INSERT and SELECT statement to
insert data by cloning it.
Syntax:
INSERT INTO table_name(column1, column2, ...)
SELECT column1, column2, ... FROM table_names
[WHERE conditions];
Example:
INSERT INTO hr_emp
SELECT * FROM employee
WHERE dept_id IN (
SELECT dept_id FROM departments
WHERE dept_name = ‘HR’
);
84. SUBQUERIES
82
It is a query within another SQL query and embedded
within the WHERE clause.
Also known as inner query and nested query.
It is used with the DML and DQL statements along with the
comparison and logical operators.
● SELECT
● INSERT
● UPDATE
● DELETE
With UPDATE statement
Here, we use subquery with UPDATE and SELECT statement to
compare data from another table to update only specific data.
Syntax:
UPDATE TABLE table_name SET column_name = new_value
WHERE condition OPERATOR (
SELECT column_name FROM table2
[WHERE condition]
)
Example:
UPDATE TABLE employee SET salary = ‘100000’
WHERE salary IN (
SELECT salary FROM employee
WHERE salary BETWEEN 90000 AND 99999
);
85. SUBQUERIES
83
It is a query within another SQL query and embedded
within the WHERE clause.
Also known as inner query and nested query.
It is used with the DML and DQL statements along with the
comparison and logical operators.
● SELECT
● INSERT
● UPDATE
● DELETE
With DELETE statement
Here, we use subquery with DELETE and SELECT statement to
compare data from another table to delete only specific data.
Syntax:
DELETE TABLE table_name
WHERE condition OPERATOR (
SELECT column_name FROM table2
[WHERE condition]
)
Example:
DELETE TABLE hr_emp
WHERE emp_id IN (
SELECT id AS emp_id FROM employee
WHERE status = ‘inactive’
);
86. EXECUTION SEQUENCE
84
Each query begins with finding the data that we need in a
database, and then filtering that data down into
something that can be processed and understood as
quickly as possible.
Each part of the query is executed sequentially.
A full SELECT query is look like this:
SELECT DISTINCT column1, AGG_FUNC(column)...
FROM table_name
JOIN another_table
ON table_name.column = table2.column
WHERE conditions
GROUP BY column
HAVING conditions
ORDER BY column ASC|DESC
LIMIT OFFSET, COUNT;
Operator Description
FROM | JOIN Choose and join tables to get base data.
WHERE Filters the base data.
GROUP BY Collapses base data into their distinct values.
HAVING Filters the grouped data.
SELECT Returns the final data.
ORDER BY Sorts the final data.
LIMIT Limits the final data to a row count.
Start
End
87. Add sample data in your DB. And check if you are
getting the result you want. Adjust the DB design
according to your requirements.
DESIGN AN EFFICIENT DB
85
Purpose of the database
Gather the information
Categorize into tables
Set up the relationships
Pass through normalization stages
Identify your keys
Refine your schema
Find out the purpose of using the DB.
Collect the information regarding what type of
data you want to store in the DB.
Divide the information into tables based on
logical relations.
Choose which type of key is suitable on which
column of the table. Do this for all the tables.
Set up the relationship between the tables of DB.
Pass your refined schema through each stage of
Normalization for getting the efficient design.
88. ROADMAP TO MASTER IN MYSQL
86
1 2
4
5
Concepts of Database. Fundamentals of MySQL.
Practice with simple and
complex queries.
3
Advanced concepts like views,
triggers, auto-schedulers etc.
Practice, practice and
practice.
The way to learn any language is to use it.
6
Keep learning, keep exploring.
Try to optimize your SQL queries.
89. Q & A
87
Feel free to ask us if you have any query.
FEEDBACK
http://bit.ly/db-feedback
RESOURCES
http://bit.ly/db-feedback
91. THANK YOU
89
We hope you have learned something new today.
Keep learning, keep growing.
FEEDBACK
http://bit.ly/db-feedback
RESOURCES
http://bit.ly/db-feedback
The coding club of PDPU