Mysql
Mysql
Muzzamil Arain 1
Database
A database is a structured collection of data. It's organized to allow for efficient storage, retrieval, and management
of information.
Types of Databases
• Relational Databases
Store data in tables with relationships between them, offering a structured approach.
• NoSQL Databases
Offer more flexibility in data structures, suitable for unstructured and semi-structured data.
• Other Types
Other types include graph databases, object-oriented databases, and document databases.
Muzzamil Arain 2
What is SQL?
• SQL stands for Structured Query Language
• SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International
Muzzamil Arain 3
What is MySQL?
• MySQL is a relational database management system
• MySQL is open-source
• MySQL is free
• MySQL is cross-platform
Muzzamil Arain 4
What is RDBMS?
RDBMS stands for Relational Database Management System.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server, Oracle, and Microsoft
Access.
Muzzamil Arain 5
CustomerID CustomerName ContactNo City Country
Muzzamil Arain 6
The MySQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
Example
CREATE DATABASE testDB;
Tip: Make sure you have admin privilege before creating any database. Once a database is created, you can check
it in the list of databases with the following SQL command: SHOW DATABASES;
Muzzamil Arain 7
The MySQL CREATE TABLE Statement
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
Muzzamil Arain 8
MySQL Data Types
Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each column when creating a table. The
data type is a guideline for SQL to understand what type of data is expected inside of each column, and it also
In MySQL there are three main data types: string, numeric, and date and time.
Muzzamil Arain 9
MySQL Data Types
String Data Types
DataType Description
CHAR(size) A FIXED length string (can contain letters, numbers, and special characters). The size
parameter specifies the column length in characters - can be from 0 to 255. Default is 1
VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters). The size
parameter specifies the maximum column length in characters - can be from 0 to 65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length
in bytes. Default is 1
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
Muzzamil Arain 10
MySQL Data Types
Numeric Data Types
DataType Description
BIT(size) A bit-value type. The number of bits per value is specified in size. The size parameter can hold a
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The
MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to
16777215. The size parameter specifies the maximum display width (which is 255)
INT/INTEGER(size A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0
) to 4294967295. The size parameter specifies the maximum display width (which is 255)
FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE
for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to
DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size. The number of
DECIMAL/DEC(si An exact fixed-point number. The total number of digits is specified in size. The number of digits
ze, d) after the decimal point is specified in the d parameter. The maximum number for size is 65. The
maximum number for d is 30. The default value for size is 10. The default value for d is 0.
Muzzamil Arain 11
MySQL Data Types
Date and Time Data Types
DataType Description
DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from
'1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column
definition to get automatic initialization and updating to the current date and time
TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch
('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating
to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON
TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
Muzzamil Arain 12
The MySQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL
query. However, make sure the order of the values is in the same order as the columns in the table. Here, the
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
Muzzamil Arain 13
The MySQL SELECT Statement
The SELECT statement is used to select data from a database.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If you want to select all the
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.
FROM table_name;
Muzzamil Arain 14
The MySQL DROP DATABASE Statement
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax
DROP DATABASE databasename;
Note: Be careful before dropping a database. Deleting a database will result in loss of complete information stored
in the database!
Example
DROP DATABASE testDB;
Muzzamil Arain 15
The following example creates a table called "Persons" that contains five columns: PersonID, LastName,
Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Muzzamil Arain 16
The MySQL DROP TABLE Statement
The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete information stored in the
table!
Example
DROP TABLE Shippers;
Syntax
TRUNCATE TABLE table_name;
Muzzamil Arain 17
The MySQL WHERE Clause
The WHERE clause is used to filter records.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Muzzamil Arain 18
The MySQL AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
• The AND operator displays a record if all the conditions separated by AND are TRUE.
AND Syntax
SELECT column1, column2, ...
FROM table_name
Muzzamil Arain 19
The MySQL AND, OR and NOT Operators
OR Syntax
SELECT column1, column2, ...
FROM table_name
NOT Syntax
SELECT column1, column2, ...
FROM table_name
Muzzamil Arain 20
The MySQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order,
use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
"CustomerName" column. This means that it orders by Country, but if some rows have the same Country, it orders
them by CustomerName:
Example
SELECT * FROM Customers
Muzzamil Arain 21
The MySQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE
clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will
be updated!
The following SQL statement will update the PostalCode to 00000 for all records where country is "Mexico":
Example
UPDATE Customers
Muzzamil Arain 22
The MySQL DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE
clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be
deleted!
Muzzamil Arain 23
The MySQL LIMIT Clause
The LIMIT clause is used to specify the number of records to return.
The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can
impact performance.
LIMIT Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Muzzamil Arain 24
MySQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
Muzzamil Arain 25
MySQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
Muzzamil Arain 26
The MySQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
Muzzamil Arain 27
The MySQL IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
IN Syntax
SELECT column_name(s)
FROM table_name
or:
SELECT column_name(s)
FROM table_name
Muzzamil Arain 28
Symbol Description Example
MySQL Wildcard Characters
% Represents zero bl% finds bl, black,
A wildcard character is used to substitute one or more
characters
Wildcard Characters in
MySQL»»»
Muzzamil Arain 29
The MySQL LIKE Operator
Like Operator Description
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"
WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length
Muzzamil Arain 30
MySQL Wildcard Characters
The MySQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
Tip: You can also combine any number of conditions using AND or OR operators.
Muzzamil Arain 31
MySQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
Example
ALTER TABLE Customers
Muzzamil Arain 32
ALTER TABLE - DROP COLUMN
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting a
column):
Muzzamil Arain 33
MySQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit 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.
Constraints can be column level or table level. Column level constraints apply to a column, and table level
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CREATE INDEX - Used to create and retrieve data from the database very quickly
Muzzamil Arain 34
MySQL Constraints
Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is
created with the ALTER TABLE statement.
Syntax
CREATE TABLE table_name (
....
);
Muzzamil Arain 35
MySQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record, or update a
Example
CREATE TABLE Persons (
Age int
);
Muzzamil Arain 36
MySQL NOT NULL Constraint
NOT NULL on ALTER TABLE
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already created, use the
following SQL:
Example
ALTER TABLE Persons
Muzzamil Arain 37
MySQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of
columns.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
Muzzamil Arain 38
MySQL UNIQUE Constraint
UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "ID" column when the table is already created, use the following SQL:
Muzzamil Arain 39
MySQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns
(fields).
FirstName varchar(255),
Age int,
);
Muzzamil Arain 40
MySQL PRIMARY KEY Constraint
PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL:
Muzzamil Arain 41
MySQL FOREIGN KEY Constraint
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is called the referenced or
parent table.
PersonID int,
);
Muzzamil Arain 42
MySQL FOREIGN KEY Constraint
FOREIGN KEY on ALTER TABLE
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created, use the
following SQL:
Muzzamil Arain 43
MySQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert,
As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is
Note: The date data type are set for a column when you create a new table in your database!
Muzzamil Arain 44
MySQL Aliases
Aliases are used to give a table, or a column in a table, a temporary name.
FROM table_name;
Muzzamil Arain 45