SQLsecrets Revealed
SQLsecrets Revealed
What is Database?
Data is a raw fact and figure that is used everywhere in our real world. A
group of data makes a specific information or database. In our day-to-day
life if we visit a mall, we see that a shopkeeper is handling a product
database using a scanner. Another example, let us consider a bank, they are
handling customer database. Third example is in schools they are handling
student’s database. Henceforth the database can be handled either manually
in a register or through computer software such as MySQL.
What is relational database?
It is a collection of organized data stored in one or more tables. We can
easily see and understand how different data structures relate to each other.
Difference between MySQL and SQL
We can create, read, update, and delete the database using MySQL. But SQL
(structured query language) is a Compact-English-Statement used to access,
manipulate, and coordinate the database. In this eBook we are going to
discuss about interactive environment that is how to work on entered
database.
Types of Command used in MySQL
Following are the types of commands used in MySQL
• DDL (Data definition language)- These commands are used to
create, drop, alter and describe the Table.
• DML (Data manipulation language) -These commands are used to
manipulate data such sum, average and many more
• DCL (Data control language) – It provides security to the database
such as Grant and Revoke.
• DQL (Data query language) – It allows user to pass query to the
relational database.
• TCL (Transaction Control Language) – It allows user to save and
restore databases.
Note: We are about to discuss these commands in upcoming chapters.
In this section you will learn the installation of MySQL work bench.
Let’s get started by downloading MySQL from dev.mysql.com. Select
the operating system and download MySQL installer 8.0.19. Save it in
appropriate location for e.g. Desktop.
• Numeric
• String
• Date and Time
2.1.1 Numeric data type
It refers to the data that is in the form of numbers such as Integer, Float and
Boolean. The following table lists the MySQL Numeric data type.
Numeric data Type Range
BIT 0-1
TINYINT 0-255
SMALLINT -32,768 - 32,767
BIGINT -9,223,372,036,854,775,808 - 9,223,372,036,854,775,807
FLOAT -1.79E+308 - 1.79E+308
REAL -3.40E+38 - 3.40E+38
2.1.2 String data type
It allows us to store fixed or variable character values such as char, varchar, and text. The following
table lists the MySQL String data type.
String data Description
Type
CHAR Fixed length of 8000 characters
VARCHAR Variable- length of 8000 characters
TEXT Variable- length of 2GB data
2.1.3 Date and Time data type
It is used for storing values that can contain both date as well as time. The
following table lists the MySQL Date and Time data type.
Date and Time data Description
Type
DATE It stores date in the format (YYYY-MM-DD)
TIME It stores time in the format (HH:MI:SS)
DATETIME It stores date and time information (YYYY-MM-DD HH:MI:SS)
2.2 Operators in MySQL
The Logical operator performs Boolean operation which gives two results
either true or false. The following table lists the MySQL Logical operators.
Logical operators Description
AND True if both expressions are true
IN TRUE if the operand is equal to any one from
the list of expression
OR One expression must be true to get TRUE result
NOT Reverses the value
Like if the operand matches a pattern than true
BETWEEN if operand is within a range than true
2.2.3 Comparison operators
Set operators used to combine rows from two or more table. The following
table lists the MySQL Set operators.
Set operators Description
UNION Combines two or more result set without duplicating values
UNION ALL Combines two or more result set including duplicating values
INTERSECT It includes only the common values present in two or more result set
EXCEPT It includes only results from first result set that are not included in
second result set
CHAPTER 3: DATA DEFINITION
LANGUAGE (DDL)
In previous chapter we have seen the syntax of MySQL which includes
datatypes and operators used in MySQL, now we will learn about
integrity constraints used in MySQL than we will learn about DDL and
create a table using DDL commands.
3.1 Integrity constraints in MySQL
Integrity constraints are set of rules that a table’s data or column must
follow. We can use integrity Constraints with commands at the column or
table level. The table-level Integrity constraints will be applied to the entire
table, but the column level constraints are only applied to one column.
Table shows the list of Integrity constraints used in MySQL.
Description
Integrity constraints
It prevents a column from having a NULL value
NOT NULL
When no value is defined for a column, the DEFAULT Constraint
DEFAULT
provides a default value.
It ensures that any value in a column is unique.
UNIQUE
Uniquely identifies each row/record.
PRIMARY KEY
It recognizes a row/record in any database table uniquely.
FOREIGN KEY
3.2 Introduction to MySQL DDL
MySQL DDL statements are used to define and manipulate data base
structure. It allows us to create a table, modify and maintain databases
using commands.
Following are the commands of DDL.
2 employee_id INT,
3 first_name VARCHAR (50),
4 last_name VARCHAR (50),
5 hourly_pay DECIMAL (5,2),
6 hire_date DATE
7 );
I am going to show you how we can make some tables in MySQL. A
table in a relational database they consist of rows and columns kind of
like an Excel spreadsheet. In this topic we are going to create the table
and the column.
Just type CREATE TABLE than the name of table, I am going to create
a table named employees then add a set of parentheses semicolon at the
end within the set of parentheses we will list the columns for employees,
let’s have an employee_id, first_name, hourly_pay, hire_date. Now each
column we need to set the data type of what we are storing within each
column
Let’s set the data type for each and every column:
Employee_id INT – Data going to be whole integer
First_name VARCHAR (50) – series of max 50 characters
Last_name VARCHAR (50) – series of max 50 characters
Hourly_pay Decimal (5,2) – max 5 before decimal and 2 after decimal
point (99999.99)
Hire_data DATE – date format (dd-mm-yyyy)
If we need to alter the table, let’s add the new column phone_number,
type
ALTER TABLE employees
ADD phone_number VARCHAR (15);
Execute and get the result in MYSQL workbench.
Let’s add data type to email column, here we have to use MODIFY
command, type
ALTER TABLE employees
MODIFY COLUMN email VARCHAR (100)
Execute and get the result in MYSQL workbench.
Let’s insert a row of data using INSERT command. To insert a row into a
table we would type INSERT INTO the name of the
table followed by VALUES parentheses semicolon, between this set of
parentheses we will add all of the data for a row. We will follow this order
beginning with employee ID, first name, last name so on but we do have to
pay attention to the data types. Each piece of data will be separated with a
comma.
Let’s insert a row of data in Employees table
INSERT INTO employees
VALUES (1, “Eugene”, “Krabs”, 25.50, “2023-01-02”);
Now we can execute these statements and get the result as shown below.
Output
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
4.2.2 SELECT command
In this section, we are going to discuss how to select data in a table. To
select entire rows and columns in employees table, type
SELECT * FROM employees;
Sometimes you may not want all of the data. We can select specific
columns.
To retrieve full name of employees, type
SELECT first_name, last_name FROM employees;
Output
first_name last_name
Eugene Krabs
Squidward Tentacles
Spongebob Squarepants
Patrick Star
Sandy Cheeks
Output
employee_i first_name last_name hourly_pay hire_date
d125 Eugene Krabs 25.50 2023-01-
Squidward Tentacles 15.00 02 2023-
Sandy Cheeks 17.25 01-03
2023-01-
06
Output
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
4.2.3 UPDATE command
In this section, we are going discuss how to update data from a table. In our
table employee Id 6 missing some data.
Output
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 10.25 2023-01-
02
2 Squidward Tentacles 10.25 2023-01-
03
3 Spongebob Squarepants 10.25 2023-01-
04
4 Patrick Star 10.25 2023-01-
05
5 Sandy Cheeks 10.25 2023-01-
06
CHAPTER 5: DATA CONTROL
LANGUAGE (DCL)
5.1 Introduction to MySQL DCL
MySQL DCL used to implement security on database objects. GRANT
command gives the permission to access the database and REVOKE
command is used to remove previously granted access privileges from a
user.
The primary DCL commands in MySQL include:
GRANT: It allows users to perform specified tasks.
REVOKE: To remove user access rights.
5.2 DCL command execution
Let us control the root database by giving access permission. DCL gives us
facility to implement security on created database.
5.2.1 GRANT command
We have already created a root database (employees table), now Let’s
give access privileges to a new user(user1) using GRANT command.
To create new dummy user, let’s move on to the MySQL workbench.
We can click on one connection, we have already created a data base
(employees table), to create a new user click on server and go to Users
and Privileges
In “User and privileges” section we have all the users already created,
now I will add an account, enter login Name – user_1 and password –
12345, confirm the password and apply.
Note: New user (User_1) having permission to access, insert and delete
data from root database.
5.2.2 REVOKE command
Let’s remove the permission of inserting data in to a employees table,
login to the root database, press ctrl+V and type
USE hr_emp;
REVOKE INSERT
ON employees
FROM ‘User_1’;
Execute and get the result
User access rights for INSERT command is successfully removed.
Note: Now, the new user (User_1) is unable to insert data in root
database (employees table).
CHAPTER 6: TRANSACTION
CONTROL LANGUAGE (TCL)
6.1 Introduction to MySQL TCL
MySQL TCL is a subset of SQL commands used to manage
transactions in a database. It allows us to roll back the changes made in
database during transaction.
Note: WHERE clause use to filter the rows depending upon condition.
7.1.4 Syntax 4
2 product_id INT,
3 product_name VARCHAR (25) UNIQUE,
4 price DECIMAL (4,2)
5 );
Since we have used UNIQUE constraint so we cannot insert any product
names that are the same they all have to be unique.
In case if we forgot to add UNIQUE constraint during table creation
than we can use the following sequence of commands to add UNIQUE
constraint
1 ALTER TABLE products
2 ADD CONSTRAINT
3 UNIQUE (product_name);
Execute and get the result.
UNIQUE constraint is successfully added to column product_name.
If we insert the same product twice in product_name column than an
error message will be displayed. So, all the values in product_name
need to be different.
8.2 NOT NULL constraint
If we use NOT NULL constraint than the value within a specific column
should not be null. If we forgot to add value than error will occur. We
cannot enter a null value. We can set to be zero that’s acceptable. It’s a
useful constraint to verify input if there’s any column that you don’t want to
have any null values.
8.3 CHECK constraint
The CHECK constraint is used to limit what values can be placed in a
column, for example I live in a United States depending on which state
you live in there is a minimum hourly wage that employers must pay in
this example let’s set an hourly pay to our employees table, every
employee needs to be paid at least minimum wage in that region, we
can do that with the CHECK constraint.
Let’s create employees table with constraint CHECK
1 CREATE TABLE employees (
2 employee_id INT,
3 first_name VARCHAR (50),
4 last_name VARCHAR (50),
5 hourly_pay DECIMAL (5,2),
6 hire_date DATE
7 CONSTRAINT chk_hourly_pay CHECK (hourly_pay >= 10.00)
8 );
Here, check constraint check hourly pay will be violated if hourly_pay is
less than 10.00. so after executing the above sequence of statement a
user must be alert not to enter any value less than 10 in hourly_pay
column.
We can also remove the CHECK constraint, type
1 ALTER TABLE employees
2 DROP CHECK chk_hourly_pay;
Execute and get the result
8.4 DEFAULT constraint
When we are inserting a new row if we do not specify a value for a
column by default, we can add some value that we set here’s an
example. Let’s create products table and set the price default value to 0.
Type
1 CREATE TABLE products (
2 product_id INT,
3 product_name VARCHAR(25),
4 price DECIMAL(4,2) DEFAULT 0
5 );
Here, if we insert product id and product name in the table than the
price 0 will be automatically included due to DEFAULT constraint.
Output
customer_id first_name last_name
1 Fred Fish
2 Larry Lobster
3 Bubble Bass
Now, we are going to create a link between our customers table and our
transactions table via customer ID. Let’s create a transaction table with
FOREIGN KEY constraint, type
1 CREATE TABLE transactions (
2 transaction_id INT PRIMARY KEY AUTO_INCREMENT,
3 amount DECIMAL (5,2),
4 customer_id INT,
5 FOREIGN KEY (customer_id) REFERENCES
customers(customer_id)
6 );
Execute and get the result
transaction_id amount customer_id
Note: Here customer_id column is FOREIGN KEY.
1. Table of Transaction
transaction_id amount customer_i
1000 4.8 d2313
1001 9
1002 2.6
1003 8
3.3
2
4.9
9
2. Table of Customers
customer_id first_name last_name
1 Fred Fish
2 Larry Lobster
3 Bubble Bass
The Logical operator is a keyword use to combine more than one condition.
Let’s use our employees table to demonstrate logical operators.
SELECT * FROM employees;
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
6 Sheldon Plankton 10.25 2023-01-
07
9.2.1 AND operator
1 SELECT *
2 FROM employees
3 WHERE hire_date< “2023-01-6” AND hourly_pay<15;
It will return any results that match these two criteria.
employee_id first_name last_name hourly_pay hire_date
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
9.2.2 OR operator
1 SELECT *
2 FROM employees
3 WHERE hire_date< “2023-01-6” OR hourly_pay<15;
It will return any results that match one of these two criteria.
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
9.2.3 NOT operator
1 SELECT *
2 FROM employees
3 WHERE NOT hourly_pay = 12.50;
Here, NOT basically reverses anything you say.
employee_i
hourly_pay first_name last_name hire_date
d12
25.50 Eugene Krabs 2023-01-
15.00 Squidward Tentacles 02 2023-
01-03
9.2.4 Between operator
1 SELECT *
2 FROM employees
3 WHERE hire_date BETWEEN “2023-01-04” AND “2023-01-07”;
Execute and get the result according to criteria.
employee_id first_name last_name hourly_pay hire_date
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
6 Sheldon Plankton 10.25 2023-01-
07
9.2.5 IN operator
1 SELECT *
2 FROM employees
3 WHERE hourly_pay IN (17.25,10.25);
We can find any values that are within a set.
employee_i first_name last_name hourly_pay hire_date
d56 Sandy Cheeks 17.25 2023-01-
Sheldon Plankton 10.25 06 2023-
01-07
CHAPTER 10: SOME IMPORTANT
MYSQL COMMANDS
In this section, we are going to discuss about some important clauses used
in MySQL to handle databases or schema object.
10.1 Wild card character
Wild card is a special character used to handle the database. There are two
wild card character – precent and underscore.
Let’s use % in our employees table to retrieve first name begins with S, type
1 SELECT * FROM employees
2 WHERE first_name LIKE “s%”;
Let’s find the employee hired in January from employees table, type
1 SELECT * FROM employees
2 WHERE hire_date LIKE “____-01-__”;
Note: Year uses four underscore and month uses two underscore.
Output
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
6 Sheldon Plankton 10.25 2023-01-
07
10.2 Order by clause
The ORDER BY clause sorts the results of a query in either ascending
or descending order based on which column we list.
Let’s change the order of our employees table’s first name, type
1 SELECT * FROM employees
2 ORDER BY first_name DESC;
Execute and get the result
1 SELECT * FROM employees
2 ORDER BY first_name ASC;
Execute and get the result
10.3 Limit clause
The LIMIT clause use to limit the number of records. It is very useful if you
are working with a large database.
Let’s limit the number of employees that are displayed from employees
table, type
1 SELECT * FROM employees
2 LIMIT 2;
Note: Only first two employee’s details will be displayed.
Output
employee_i first_name last_name hourly_pay hire_date
d12 Eugene Krabs 25.50 2023-01-
Squidward Tentacles 15.00 02 2023-
01-03
10.4 Union operator
The UNION operator combines the results of two or more select statements.
Let’s combine the first_name and last_name of our two tables- Employees
table and Customers table.
Employees table
employee_id first_name last_name hourly_pay hire_date
1 Eugene Krabs 25.50 2023-01-
02
2 Squidward Tentacles 15.00 2023-01-
03
3 Spongebob Squarepants 12.50 2023-01-
04
4 Patrick Star 12.50 2023-01-
05
5 Sandy Cheeks 17.25 2023-01-
06
6 Sheldon Plankton 10.25 2023-01-
07
Customers table
customer_id first_name last_name
1 Fred Fish
2 Larry Lobster
3 Bubble Bass
Output
first_name last_name
Eugene Krabs
Squidward Tentacles
Spongebob Squarepants
Patrick Star
Sandy Cheeks
Sheldon Plankton
10.6 Indexes in MySQL
Indexes are used to find the values within a specific column more quickly.
MySQL normally searches sequentially through a column.
Customer’s table
customer_id first_name last_name
1 Fred Fish
2 Larry Lobster
3 Bubble Bass
Output
customer_id first_name last_name
3 Bubble Bass
10.7 Subqueries
THE END