0% found this document useful (0 votes)
11 views172 pages

8 Mysql

The document provides a comprehensive overview of MySQL, including commands for managing databases and tables, performing CRUD operations, and executing queries. It covers various SQL functionalities such as inserting records, using aggregate functions, and applying conditions with WHERE, LIKE, and IN clauses. Additionally, it explains the use of operators, sorting results with ORDER BY, handling NULL values, and the importance of the LIMIT clause.

Uploaded by

singhaayu2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views172 pages

8 Mysql

The document provides a comprehensive overview of MySQL, including commands for managing databases and tables, performing CRUD operations, and executing queries. It covers various SQL functionalities such as inserting records, using aggregate functions, and applying conditions with WHERE, LIKE, and IN clauses. Additionally, it explains the use of operators, sorting results with ORDER BY, handling NULL values, and the importance of the LIMIT clause.

Uploaded by

singhaayu2008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 172

MySQL

Avinash Pathak

[email protected]
Objectives
• To understand the MySQL implementation
• To get familiar with the MySQl environment
• To get updated on various features of the MySQL:
• Databases
• Tables
• CRUD/CRID
• Queries
• Indexes

[email protected]
MySQL
• Login command -> mysql –u root
• \h it will show list of commands that can be issued at the mysql
prompt

• show databases; to display current databases available


• exit; to quit mysql
• quit; to quit mysql

[email protected]
Databases
• show databases;
• will display list of current databases available

• create database temp;


• to create a new database, called as "temp"

[email protected]
Databases
• show databases;
• check whether the new database has been created or not

• Use temp;
• to use a database whose name is "temp“

• show tables;
• to display list of tables in the current database, "temp"

[email protected]
Databases
• drop database temp;
• to delete the "temp" database

• show databases;
• check whether the database has got deleted or not

• create database test1;


• create another new database, "test1"

[email protected]
Databases
• use test1;
• switch to the newly created database,"test1“

• show tables;
• display list of tables in the database "test1", currently it will be empty

[email protected]
Databases
• select database();
• to display the currently used database

• create database if not exists t1;


• to create database "t1", if it not exists

• drop database if exists t1;


• to drop or delete database "t1", if it exists

[email protected]
Databases
• select database();
• to display the currently used database

• show tables;
• to show list of all the tables in the current database

• show create database test1;


• to show the system create statement of the database "test"

[email protected]
Tables
• create table emp (empid int(4)unsigned not null
auto_increment,empname varchar(10) not null,
• primary key (empid));

• show tables;
• to show list of all the tables in the current database

• describe emp;
• to display the structure of the table "emp"
[email protected]
Databases
• show create table emp;
• to display the system create statement for table "emp“

• insert into emp values(null,'avinash');


• to insert one record of employee

• select * from emp;


• to display all the records of the table emp

[email protected]
Insert
• INSERT INTO statement is used to insert new records in a table.
• It is possible to write the INSERT INTO statement in two ways.
• INSERT INTO table_name (column1, column2, column3, ...)
• VALUES (value1, value2, value3, ...);

• INSERT INTO table_name


• VALUES (value1, value2, value3, ...);
• Above make sure the order of the values is in the same order as the
columns in the table.
[email protected]
Insert
• INSERT INTO Customers (CustomerName, ContactName, Address,
City, PostalCode, Country)
• VALUES ('tata', 'suresh', '21 wadgaon', 'pune', '411012', 'india')

• The CustomerID column is an auto-increment field and will be


generated automatically
• when a new record is inserted into the table.

[email protected]
Insert
• It is also possible to only insert data in specific columns.
• The following SQL statement will insert a new record, but only insert
data in
• the "CustomerName", "City", and "Country" columns (CustomerID will
be updated automatically):
• INSERT INTO Customers (CustomerName, City, Country)
• VALUES ('anil', 'pune', 'india');

[email protected]
Distinct
• Create a Table "Customers"
• The fields in the Customers table are:
• CustomerID, CustomerName, ContactName, Address, City ,
PostalCode, Country
• To display all columns/fields data

• SELECT * FROM Customers;

[email protected]
Distinct
• To select the "CustomerName" and "City" columns from the
"Customers" table:

• SELECT CustomerName, City FROM Customers;

• The SELECT DISTINCT statement is used to return only distinct


(different) values.
• SELECT Country FROM Customers;
• SELECT DISTINCT City FROM Customers;
[email protected]
Count()
• SELECT COUNT(City) FROM Customers;

• SELECT COUNT(DISTINCT City) FROM Custo


• mers;

[email protected]
Where
• WHERE clause is used to extract only those records that fulfill a
specified condition.

• WHERE clause is not only used in SELECT statement, it is also used in


UPDATE, DELETE
• SELECT * FROM Customers
• WHERE City='pune';
• SELECT * FROM Customers
• WHERE CustomerID=1;
[email protected]
Operators
• = Equal

• <> Not equal. Note: In some versions of SQL this operator may be written as !=

• > Greater than

• < Less than

• >= Greater than or equal

• <= Less than or equal


[email protected]
Operators
• BETWEEN Between an inclusive range

• LIKE Search for a pattern

• IN To specify multiple possible values for a column

• The WHERE clause can be combined with AND, OR, and NOT
operators.

[email protected]
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 is TRUE.

• The OR operator displays a record if any of the conditions separated by


OR is TRUE.

• The NOT operator displays a record if the condition(s) is NOT TRUE.


[email protected]
Operators
• SELECT * FROM Customers
• WHERE Country='indi' AND City='pune';

• SELECT * FROM Customers


• WHERE NOT City='pune';

[email protected]
Operators
• SELECT * FROM Customers
• WHERE Country='india' OR City='pune';

• SELECT * FROM Customers


• WHERE Country='india' AND (City='pune' OR City='mumbai');

• SELECT * FROM Customers


• WHERE NOT Country='india' AND NOT Country='nepal';

[email protected]
Order By
• 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.

[email protected]
Order By
• SELECT * FROM Customers
• ORDER BY Country;

• SQL statement selects all customers from the "Customers" table,


• sorted DESCENDING by the "Country" column:

• SELECT * FROM Customers


• ORDER BY Country DESC;

[email protected]
Order By
• SQL statement selects all customers from the "Customers" table,
• sorted by the "Country" and the "CustomerName" column:

• SELECT * FROM Customers


• ORDER BY Country, CustomerName;

[email protected]
Order By
• SQL statement selects all customers from the "Customers" table,
sorted ascending by the "Country" and descending by the
"CustomerName" column:

• SELECT * FROM Customers


• ORDER BY Country ASC, CustomerName DESC;

[email protected]
Null Values
• A field with a NULL value is a field with no value.

• If a field in a table is optional, it is possible to insert a new record or


update a record without adding a value to this field.

• Then, the field will be saved with a NULL value.

• Always use IS NULL to look for NULL values.

[email protected]
Null Values
• It is very important to understand that a NULL value is different from a zero
value
• or a field that contains spaces.

• A field with a NULL value is one that has been left blank during record creation!

• It is not possible to test for NULL values with comparison operators, such as =,
<, or <>.

• We will have to use the IS NULL and IS NOT NULL operators instead.

[email protected]
Null Values
SELECT LastName, FirstName, Address FROM Persons
WHERE Address IS NULL;

SELECT LastName, FirstName, Address FROM Persons


WHERE Address IS NOT NULL;

[email protected]
Update
• The UPDATE statement is used to modify the existing records in a
table.

• 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
[email protected]
Update
UPDATE Customers
SET ContactName='suresh';

UPDATE Customers
SET ContactName = 'suresh', City= 'pune'
WHERE CustomerID = 1;

[email protected]
Update
• It is the WHERE clause that determines how many records that will be
updated.

• The following SQL statement will update the contactname to "suresh" for
all records
• where country is "india":

• UPDATE Customers
• SET ContactName='suresh'
• WHERE Country='india';
[email protected]
Delete
• The DELETE statement is used to delete existing records in a table.

• Be careful when deleting records in a table! Notice the WHERE clause


in the DELETE statement.

• The WHERE clause specifies which record(s) that should be deleted

• If you omit the WHERE clause, all records in the table will be deleted

[email protected]
Delete
• DELETE FROM Customers
• WHERE CustomerName='suresh';
• It is possible to delete all rows in a table without deleting the table.

• This means that the table structure, attributes, and indexes will be intact:

• DELETE FROM table_name;

DELETE FROM Customers;


[email protected]
Limit
• MySQL supports the LIMIT clause to select a limited number of
records, while Oracle uses ROWNUM.

• SELECT column_name(s)
• FROM table_name WHERE condition LIMIT number;

• SELECT * FROM Customers


LIMIT 3;

[email protected]
Aggregate Functions
• For these examples create "Prodcuts" and "OrderDeatils" tables,
accordingly

• The MIN() function returns the smallest value of the selected column.

• SELECT MIN(Price) AS SmallestPrice


• FROM Products;

[email protected]
Aggregate Functions
• The MAX() function returns the largest value of the selected column.

• SELECT MAX(Price) AS LargestPrice


• FROM Products;

[email protected]
Aggregate Functions
• The COUNT() function returns the number of rows that matches a
specified criteria.

• SELECT COUNT(ProductID)
• FROM Products;

[email protected]
Aggregate Functions
• The SUM() function returns the total sum of a numeric column.

• SELECT SUM(Quantity)
• FROM OrderDetails;

[email protected]
Aggregate Functions
• The AVG() function returns the average value of a numeric column.

• SELECT AVG(Price)
• FROM Products;

[email protected]
Like
• The LIKE operator is used in a WHERE clause to search for a specified pattern
in a column.

• There are two wildcards used in conjunction with the LIKE operator:

•% - The percent sign represents zero, one, or multiple characters

•_ - The underscore represents a single character

• The percent sign and the underscore can also be used in combinations
[email protected]
Like
• You can also combine any number of conditions using AND or OR operators.

• WHERE CustomerName LIKE 'a%'


• Finds any values that starts with "a"

• WHERE CustomerName LIKE '%a'


• Finds any values that ends with "a"

• WHERE CustomerName LIKE '%or%'


• Finds any values that have "or" in any position
[email protected]
Like
• WHERE CustomerName LIKE '_r%'
• Finds any values that have "r" in the second position

• WHERE CustomerName LIKE 'a_%_%'


• Finds any values that starts with "a" and are at least 3 characters in
length

• WHERE ContactName LIKE 'a%o'


• Finds any values that starts with "a" and ends with "o"
[email protected]
Like
• SQL statement selects all customers with a CustomerName starting
with "a":

• SELECT * FROM Customers


• WHERE CustomerName LIKE 'a%';

[email protected]
Like
• SQL statement selects all customers with a CustomerName ending
with "a":

• SELECT * FROM Customers


• WHERE CustomerName LIKE '%a';

[email protected]
Like
• SQL statement selects all customers with a CustomerName that have
"or" in any position:

• SELECT * FROM Customers


• WHERE CustomerName LIKE '%or%';

[email protected]
Like
• SQL statement selects all customers with a CustomerName that have
"r" in the second position:

• SELECT * FROM Customers


• WHERE CustomerName LIKE '_r%';

[email protected]
Like
• SQL statement selects all customers with a CustomerName that starts
with "a" and are at least 3
• characters in length:

• SELECT * FROM Customers


• WHERE CustomerName LIKE 'a_%_%';

[email protected]
Like
• SQL statement selects all customers with a CustomerName that starts
with "a" and ends with "o":

• SELECT * FROM Customers


• WHERE ContactName LIKE 'a%o';

[email protected]
Like
• SQL statement selects all customers with a CustomerName that NOT
starts with "a":

• SELECT * FROM Customers


• WHERE CustomerName NOT LIKE 'a%';

[email protected]
In
• For the examples you need to create a "Suppliers" table also

• The IN operator allows you to specify multiple values in a WHERE


clause.

• The IN operator is a shorthand for multiple OR conditions.

[email protected]
In
• SELECT column_name(s)
• FROM table_name
• WHERE column_name IN (value1, value2, ...);

• SELECT column_name(s)
• FROM table_name
• WHERE column_name IN (SELECT STATEMENT);

[email protected]
In
• SQL statement selects all customers that are located in "Germany",
"France" and "UK":

• SELECT * FROM Customers


• WHERE Country IN ('Germany', 'France', 'UK');

[email protected]
In
• SQL statement selects all customers that are NOT located in
"Germany", "France" or "UK":

• SELECT * FROM Customers


• WHERE Country NOT IN ('Germany', 'France', 'UK');

[email protected]
In
• SQL statement selects all customers that are from the same countries
as the suppliers:

• SELECT * FROM Customers


• WHERE Country IN (SELECT Country FROM Suppliers);

[email protected]
Between
• 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.

[email protected]
Between
• SQL statement selects all products with a price BETWEEN 10 and 20:

• SELECT * FROM Products


• WHERE Price BETWEEN 10 and 20 ;

[email protected]
Between
• To display the products outside the range of the previous example,
use NOT BETWEEN:

• SELECT * FROM Products


• WHERE Price NOT BETWEEN 10 AND 20;

[email protected]
Between
• SQL statement selects all products with a price BETWEEN 10 and 20.
In addition;
• do not show products with a CategoryID of 1,2, or 3:

• SELECT * FROM Products


• WHERE (Price BETWEEN 10 AND 20)
• AND NOT CategoryID IN (1,2,3);

[email protected]
Between
• SQL statement selects all products with a ProductName BETWEEN
'brittiana' and 'marie':

• SELECT * FROM Products


• WHERE ProductName BETWEEN 'brittiana' AND 'marie'
• ORDER BY ProductName;

[email protected]
Between
• SQL statement selects all products with a ProductName NOT
BETWEEN 'brittiana' and 'marie':

• SELECT * FROM Products


• WHERE ProductName NOT BETWEEN 'brittiana' AND 'marie'
• ORDER BY ProductName;

[email protected]
Between
• SQL statement selects all orders with an OrderDate BETWEEN '04-
July-2016' and '09-July-2016':

• SELECT * FROM Orders


• WHERE OrderDate BETWEEN #07/04/2016# AND
#07/09/2016#; ..........not supported mysql

[email protected]
Aliases
• SQL aliases are used to give a table, or a column in a table, a
temporary name.
• Aliases are often used to make column names more readable.
• Aliases can be useful when:-
• There are more than one table involved in a query
• Functions are used in the query
• Column names are big or not very readable
• Two or more columns are combined together

[email protected]
Aliases
• An alias only exists for the duration of the query.

• SELECT column_name AS alias_name


• FROM table_name;

• SELECT column_name(s)
• FROM table_name AS alias_name;

[email protected]
Aliases
• SQL statement creates two aliases, one for the CustomerID column
and one for the CustomerName column:

• SELECT CustomerID as ID, CustomerName AS Customer


• FROM Customers;

[email protected]
Aliases
• SQL statement creates an alias named "Address" that combine 3
columns

• (Address, City and Country):

[email protected]
Aliases

• SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,',


',Country) AS Address FROM Customers;

[email protected]
Aliases
• We use the "Customers" and "Orders" tables, and give them the table
aliases of "c" and "o" respectively

• Here we use aliases to make the SQL shorter:

• Orders Table -> OrderID, OrderDate, CustomerID,OrderValue

[email protected]
Aliases
• SELECT o.OrderID, o.OrderDate, c.CustomerName
• FROM Customers AS c, Orders AS o
• WHERE c.CustomerName="reliance"
AND
c.CustomerID=o.CustomerID;

[email protected]
Aliases
• SQL statement is the same as above, but without aliases:

• SELECT Orders.OrderID, Orders.OrderDate,


Customers.CustomerName
• FROM Customers, Orders
• WHERE Customers.CustomerName="reliance" AND
Customers.CustomerID=Orders.CustomerID

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
JOINS Types
• (INNER) JOIN:
• Returns records that have matching values in both tables
• LEFT (OUTER) JOIN:
• Return all records from the left table, and the matched records from
the right table
• RIGHT (OUTER) JOIN:
• Return all records from the right table, and the matched records from
the left table
• FULL (OUTER) JOIN:
• Return all records when there is a match in either left or right table
[email protected]
INNER JOIN
• The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns.

• SQL statement selects all orders with customer information:-

• SELECT Orders.OrderID, Customers.CustomerName


• FROM Orders INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID;

[email protected]
LEFT JOIN
• The LEFT JOIN keyword returns all records from the left table (table1), and
the matched
• records from the right table (table2).
• The result is NULL from the right side, if there is no match.

• SELECT column_name(s)
• FROM table1
• LEFT JOIN table2 ON table1.column_name = table2.column_name;

• In some databases LEFT JOIN is called LEFT OUTER JOIN.


[email protected]
LEFT JOIN
• SQL statement will select all customers, and any orders they might have:

• SELECT Customers.CustomerName, Orders.OrderID


• FROM Customers
• LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
• ORDER BY Customers.CustomerName;

• The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
[email protected]
RIGHT JOIN
• The RIGHT JOIN keyword returns all records from the right table (table2), and
the matched
• records from the left table (table1).
• The result is NULL from the left side, when there is no match.

• SELECT column_name(s)
• FROM table1
• RIGHT JOIN table2 ON table1.column_name = table2.column_name;

• In some databases RIGHT JOIN is called RIGHT OUTER JOIN.


[email protected]
RIGHT JOIN
• SQL statement will return all employees, and any orders they might have have
placed:

• SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


• FROM Orders
• RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
• ORDER BY Orders.OrderID;

• The RIGHT JOIN keyword returns all records from the right table (Employees),
• even if there are no matches in the left table (Orders).
[email protected]
FULL OUTER JOIN
• The FULL OUTER JOIN keyword return all records when there is a
match in either left (table1)
• or right (table2) table records.
• Note: FULL OUTER JOIN can potentially return very large result-sets!

• SELECT column_name(s)
• FROM table1
• FULL OUTER JOIN table2 ON table1.column_name =
table2.column_name;
[email protected]
FULL OUTER JOIN
• SQL statement selects all customers, and all orders:

• SELECT Customers.CustomerName, Orders.OrderID


• FROM Customers
• FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
• ORDER BY Customers.CustomerName;

• If there are rows in "Customers" that do not have matches in "Orders", or if there
are rows
• in "Orders" that do not have matches in "Customers", those rows will be listed as
well.
[email protected]
Self JOIN
• A self JOIN is a regular join, but the table is joined with itself.

• SELECT column_name(s)
• FROM table1 T1, table1 T2
• WHERE condition;

[email protected]
Self JOIN
• SQL statement matches customers that are from the same city:

• SELECT A.CustomerName AS CustomerName1,


B.CustomerName AS CustomerName2, A.City FROM Customers
A, Customers B
• WHERE A.CustomerID <> B.CustomerID
• AND A.City = B.City
• ORDER BY A.City;

[email protected]
Union
• UNION operator is used to combine the result-set of two or more
SELECT statements.

• Each SELECT statement within UNION must have the same number of
columns

• The columns must also have similar data types

• The columns in each SELECT statement must also be in the same order
[email protected]
Union

• SELECT column_name(s) FROM table1


• UNION
• SELECT column_name(s) FROM table2;

[email protected]
Union
• UNION ALL Syntax

• The UNION operator selects only distinct values by default.

• To allow duplicate values, use UNION ALL:

• SELECT column_name(s) FROM table1


• UNION ALL
• SELECT column_name(s) FROM table2;
[email protected]
Union
• The column names in the result-set are usually equal to the column
names in the first SELECT statement in the UNION.
• SQL statement selects all the different cities (only distinct values) from
"Customers" and "Suppliers":

• 1. SELECT City FROM Customers


• UNION
• SELECT City FROM Suppliers
• ORDER BY City;
[email protected]
Union
• If some customers or suppliers have the same city, each city will only be listed once,
• because UNION selects only distinct values.
• Use UNION ALL to also select duplicate values
• The following SQL statement selects all cities (duplicate values also) from
"Customers" and "Suppliers":

• SELECT City FROM Customers


• UNION ALL
• SELECT City FROM Suppliers
• ORDER BY City;

[email protected]
Union

• The following SQL statement selects all the different German cities (only
distinct values) from "Customers" and "Suppliers":

• SELECT City, Country FROM Customers


• WHERE Country='Germany'
• UNION
• SELECT City, Country FROM Suppliers
• WHERE Country='Germany'
• ORDER BY City;
[email protected]
Union
• The following SQL statement lists all customers and suppliers:

• SELECT 'Customer' As Type, ContactName, City, Country


• FROM Customers
• UNION
• SELECT 'Supplier', ContactName, City, Country
• FROM Suppliers;

[email protected]
Group By
• SQL GROUP BY Statement

• The GROUP BY statement is often used with aggregate functions (COUNT,


MAX, MIN, SUM, AVG) to group the result-set by one or more columns.

• SELECT column_name(s)
• FROM table_name
• WHERE condition
• GROUP BY column_name(s)
• ORDER BY column_name(s);
[email protected]
Group By
• SQL statement lists the number of customers in each country:

• SELECT COUNT(CustomerID), Country


• FROM Customers
• GROUP BY Country;

[email protected]
Group By
• SQL statement lists the number of customers in each country, sorted
high to low:

• SELECT COUNT(CustomerID), Country


• FROM Customers
• GROUP BY Country
• ORDER BY COUNT(CustomerID) DESC;

[email protected]
Having
• HAVING clause was added to SQL because the WHERE keyword could
not be used with aggregate functions.

• SELECT column_name(s)
• FROM table_name
• WHERE condition
• GROUP BY column_name(s)
• HAVING condition
• ORDER BY column_name(s);
[email protected]
Having
• SQL statement lists the number of customers in each country. Only
include countries with more than 5 customers:

• SELECT COUNT(CustomerID), Country


• FROM Customers
• GROUP BY Country
• HAVING COUNT(CustomerID) > 5;

[email protected]
Having
• SQL statement lists the number of customers in each country, sorted
high to low (Only include countries with more than 5 customers):

• SELECT COUNT(CustomerID), Country


• FROM Customers
• GROUP BY Country
• HAVING COUNT(CustomerID) > 5
• ORDER BY COUNT(CustomerID) DESC;

[email protected]
Exists

• The EXISTS operator is used to test for the existence of any record in a
subquery.

• The EXISTS operator returns true if the subquery returns one or more records.

• SELECT column_name(s)
• FROM table_name
• WHERE EXISTS
• (SELECT column_name FROM table_name WHERE condition);
[email protected]
Exists
• SQL statement returns TRUE and lists the suppliers with a product
price less than 20:

• SELECT SupplierName
• FROM Suppliers
• WHERE EXISTS (SELECT ProductName FROM Products WHERE
SupplierId = Suppliers.supplierId AND Price < 20);

[email protected]
Exists
• SQL statement returns TRUE and lists the suppliers with a product
price equal to 22:

• SELECT SupplierName
• FROM Suppliers
• WHERE EXISTS (SELECT ProductName FROM Products WHERE
SupplierId = Suppliers.supplierId AND Price = 22);

[email protected]
Any All
• The ANY and ALL operators are used with a WHERE or HAVING clause.

• The ANY operator returns true if any of the subquery values meet the
condition.

• The ALL operator returns true if all of the subquery values meet the
condition.

[email protected]
Any All
• ANY Syntax

• SELECT column_name(s)
• FROM table_name
• WHERE column_name operator ANY
• (SELECT column_name FROM table_name WHERE condition);

[email protected]
Any All

• SELECT column_name(s)
• FROM table_name
• WHERE column_name operator ALL
• (SELECT column_name FROM table_name WHERE condition);

[email protected]
Any All
• The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).

• The ANY operator returns TRUE if any of the subquery values meet
the condition.

[email protected]
Any All
• The following SQL statement returns TRUE and lists the productnames
if it finds ANY records
• in the OrderDetails table that quantity = 10:

• SELECT ProductName
• FROM Products
• WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails
WHERE Quantity = 10);

[email protected]
Any All
• SQL statement returns TRUE and lists the productnames if it finds ANY
records in the OrderDetails
• table that quantity > 99:

• SELECT ProductName
• FROM Products
• WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails
WHERE Quantity > 99

[email protected]
Any All
• The ALL operator returns TRUE if all of the subquery values meet the
condition.

• The following SQL statement returns TRUE and lists the productnames if
ALL the records in the OrderDetails table has quantity = 10.

• SELECT ProductName
• FROM Products
• WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails
WHERE Quantity = 10);
[email protected]
Insert
• SQL statement copies "Suppliers" into "Customers" (the columns that
are not filled with data, will contain NULL):

• INSERT INTO Customers (CustomerName, City, Country)


• SELECT SupplierName, City, Country FROM Suppliers;

[email protected]
Insert
• SQL statement copies "Suppliers" into "Customers" (fill all columns):

• INSERT INTO Customers (CustomerName, ContactName,


Address, City, PostalCode, Country)
• SELECT SupplierName, ContactName, Address, City, PostalCode,
Country FROM Suppliers;

[email protected]
Insert
• SQL statement copies only the German suppliers into "Customers":

• SELECT SupplierName, City, Country FROM Suppliers


• WHERE Country='Germany';

[email protected]
Auto-increment

• Auto-increment allows a unique number to be generated


automatically when a new record is inserted into a table.

• Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.

[email protected]
Auto-increment
• CREATE TABLE Persons
• (
• ID int NOT NULL
AUTO_INCREMENT,
• LastName varchar(255) NOT NULL,
• FirstName varchar(255),
• Age int,
• PRIMARY KEY (ID)
• );
[email protected]
Auto-increment
• MySQL uses the AUTO_INCREMENT keyword to perform an auto-
increment feature.

• By default, the starting value for AUTO_INCREMENT is 1, and it will


increment by 1 for each new record.

[email protected]
Auto-increment
• To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statement:
• ALTER TABLE Persons AUTO_INCREMENT=100;

• To insert a new record into the "Persons" table, we will NOT have to
specify a value for the "ID" column (a unique value will be added
automatically):

• INSERT INTO Persons (FirstName,LastName)


• VALUES ('Lars','Monsen');
[email protected]
Auto-increment
• The SQL statement above would insert a new record into the
"Persons" table.

• The "ID" column would be assigned a unique value.

• The "FirstName" column would be set to "Lars" and the "LastName"


column would be set to "Monsen".

[email protected]
Views
• In SQL, a view is a virtual table based on the result-set of an SQL statement.
• A view contains rows and columns, just like a real table.
• The fields in a view are fields from one or more real tables in the database.
• You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.

• CREATE VIEW Syntax


• CREATE VIEW view_name AS
• SELECT column1, column2, ...
• FROM table_name
• WHERE condition;
[email protected]
Views
• A view always shows up-to-date data!

• The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.

[email protected]
Views
• The view "Current Product List" lists all active products (products that
are not discontinued) from the "Products" table.

• The view is created with the following SQL:

• CREATE VIEW [Current Product List] AS


• SELECT ProductID, ProductName
• FROM Products
• WHERE Discontinued = No;
[email protected]
Views

• Then, we can query the view as follows:

SELECT * FROM [Current Product List];

[email protected]
Views
• You can update a view by using the following syntax:

• SQL CREATE OR REPLACE VIEW Syntax

• CREATE OR REPLACE VIEW view_name AS


• SELECT column1, column2, ...
• FROM table_name
• WHERE condition;

[email protected]
Views
• Now we want to add the "Category" column to the "Current Product
List" view.
• we will update the view with the following SQL:

• CREATE OR REPLACE VIEW [Current Product List] AS


• SELECT ProductID, ProductName, Category
• FROM Products
• WHERE Discontinued = No;

[email protected]
Views
• SQL Dropping a View

• You can delete a view with the DROP VIEW command.

• SQL DROP VIEW Syntax

• DROP VIEW view_name;

• DROP VIEW [Current Product List];


[email protected]
Index
• The CREATE INDEX statement is used to create indexes in tables.

• Indexes are used to retrieve data from the database very fast.

• The users cannot see the indexes, they are just used to speed up
searches/queries.

• Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update).
[email protected]
Index
• So, only create indexes on columns that will be frequently searched
against.

• CREATE INDEX Syntax

• Creates an index on a table. Duplicate values are allowed:

• CREATE INDEX index_name


• ON table_name (column1, column2, ...);
[email protected]
Index
• CREATE UNIQUE INDEX Syntax

• Creates a unique index on a table. Duplicate values are not allowed:

• CREATE UNIQUE INDEX index_name


• ON table_name (column1, column2, ...);

[email protected]
Index
• The SQL statement below creates an index named "idx_lastname" on
the "LastName" column in the "Persons" table:

• CREATE INDEX idx_lastname


• ON Persons (LastName);

[email protected]
Index
• If you want to create an index on a combination of columns, you can
list the column names within the parentheses, separated by commas:

• CREATE INDEX idx_pname


• ON Persons (LastName, FirstName);

[email protected]
Index
• DROP INDEX Statement

• The DROP INDEX statement is used to delete an index in a table.

• MySQL:

• ALTER TABLE table_name


• DROP INDEX index_name;

[email protected]
Text Data Types
• CHAR(size) :
• Holds a fixed length string (can contain letters, numbers, and special characters).
• The fixed size is specified in parenthesis.
• Can store up to 255 characters

• VARCHAR(size) :
• Holds a variable length string ,can contain letters, numbers, and special characters.
• The maximum size is specified in parenthesis.
• Can store up to 255 characters.
• If you put a greater value than 255 it will be converted to a TEXT type
[email protected]
Text Data Types
• TINYTEXT :
• Holds a string with a maximum length of 255 characters
• TEXT :
• Holds a string with a maximum length of 65,535 characters
• BLOB :
• For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
• MEDIUMTEXT :
• Holds a string with a maximum length of 16,777,215 characters

[email protected]
Text Data Types
• MEDIUMBLOB :
• For BLOBs (Binary Large Objects).
• Holds up to 16,777,215 bytes of data
• LONGTEXT :
• Holds a string with a maximum length of 4,294,967,295 characters
• LONGBLOB :
• For BLOBs (Binary Large Objects).
• Holds up to 4,294,967,295 bytes of data

[email protected]
Text Data Types
• ENUM(x,y,z,etc.)

• Let you enter a list of possible values.


• You can list up to 65535 values in an ENUM list.
• If a value is inserted that is not in the list, a blank value will be
inserted.
• The values are sorted in the order you enter them.
• You enter the possible values in this format: ENUM('X','Y','Z')

[email protected]
Text Data Types
• SET :

• Similar to ENUM except that SET may contain up to 64 list items and
can store more than one choice

[email protected]
Number Types
• TINYINT(size) :
• -128 to 127 normal.
• 0 to 255 UNSIGNED*.
• The maximum number of digits may be specified in parenthesis

• SMALLINT(size) :
• -32768 to 32767 normal.
• 0 to 65535 UNSIGNED*.
• The maximum number of digits may be specified in parenthesis
[email protected]
Number Types
• MEDIUMINT(size) :
• -8388608 to 8388607 normal.
• 0 to 16777215 UNSIGNED*.
• The maximum number of digits may be specified in parenthesis
• INT(size) :
• -2147483648 to 2147483647 normal.
• 0 to 4294967295 UNSIGNED*.
• The maximum number of digits may be specified in parenthesis

[email protected]
Number Types
• BIGINT(size) :
• -9223372036854775808 to 9223372036854775807 normal.
• 0 to 18446744073709551615 UNSIGNED*.
• The maximum number of digits may be specified in parenthesis

• FLOAT(size,d):
• A small number with a floating decimal point.
• The maximum number of digits may be specified in the size parameter.
• The maximum number of digits to the right of the decimal point is specified
• in the d parameter
[email protected]
Number Types
• DOUBLE(size,d) :
• A large number with a floating decimal point.
• The maximum number of digits may be specified in the size
parameter.
• The maximum number of digits to the right of the decimal point is
specified in the d parameter

[email protected]
Number Types
• DECIMAL(size,d) :
• A DOUBLE stored as a string , allowing for a fixed decimal point.
• The maximum number of digits may be specified in the size parameter.
• The maximum number of digits to the right of the decimal point is specified
in the d parameter
• *The integer types have an extra option called UNSIGNED.
• Normally, the integer goes from an negative to positive value.
• Adding the UNSIGNED attribute will move that range up so it starts at zero
• instead of a negative number.

[email protected]
Date Types
• DATE() :
• A date. Format: YYYY-MM-DD
• The supported range is from '1000-01-01' to '9999-12-31'
• DATETIME() :
• *A date and time combination. Format: YYYY-MM-DD HH:MI:SS
• The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
• 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:MI:SS
• The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
[email protected]
Date Types
• TIME() :
• A time. Format: HH:MI:SS
• The supported range is from '-838:59:59' to '838:59:59'
• YEAR() :
• A year in two-digit or four-digit format.
• Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format:
• 70 to 69, representing years from 1970 to 2069
• *Even if DATETIME and TIMESTAMP return the same format, they work very differently.
• In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date
and time.
• TIMESTAMP also accepts various formats, like YYYYMMDDHHMISS, YYMMDDHHMISS,
• YYYYMMDD, or YYMMDD.
[email protected]
Dates
• MySQL comes with the following data types for storing a date or a
date/time value in the database:

• DATE - format YYYY-MM-DD


• DATETIME - format: YYYY-MM-DD HH:MI:SS
• TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
• YEAR - format YYYY or YY
• SELECT * FROM Orders WHERE OrderDate='2008-11-11‘;

[email protected]
String Functions
• 1. ASCII Returns the number code that represents the specific
character

• 2. CHAR_LENGTH Returns the length of the specified string (in characters)

• 3. CHARACTER_LENGTH Returns the length of the specified string (in characters)

• 4. CONCAT Concatenates two or more expressions together

• 5. CONCAT_WS Concatenates two or more expressions together and


adds a separator between them

[email protected]
String Functions
• 6. FIELD Returns the position of a value in a list of values

• 7. FIND_IN_SET Returns the position of a string in a string list

• 8. FORMAT Formats a number as a format of "#,###.##", rounding it to


a certain number of decimal places

• 9. INSERT Inserts a substring into a string at a specified position for a


• certain number of characters

• 10. INSTR Returns the position of the first occurrence of a string in


another string
[email protected]
String Functions
• 11. LCASE Converts a string to lower-case

• 12. LEFT Extracts a substring from a string (starting from


left)

• 13. LENGTH Returns the length of the specified string (in


bytes)

• 14. LOCATE Returns the position of the first occurrence of a


substring in a string
• 15. LOWER Converts a string to lower-case
[email protected]
String Functions
• 18. LPAD Returns a string that is left-padded with a specified
string to certain length

• 17. LTRIMRemoves leading spaces from a string

• 18. MID Extracts a substring from a string (starting at any position)

• 19. POSITION Returns the position of the first occurrence of a substring in a


string

• 20. REPEAT Repeats a string a specified number of times


[email protected]
String Functions
• 21. REPLACE Replaces all occurrences of a specified string

• 22. REVERSE Returns a string with the characters in reverse order

• 23. RIGHT Extracts a substring from a string (starting from


right)

• 23. RPAD Returns a string that is right-padded with a


specified string to a certain length
[email protected]
String Functions
• 24. RTRIM Removes trailing spaces from a string

• 25. SPACE Returns a string with a specified number of


spaces

• 26. STRCMP Returns an integer value representing the


result of a string comparison

• 27. SUBSTR Extracts a substring from a string


[email protected]
String Functions
• SUBSTRING Extracts a substring from a string

• 29. SUBSTRING_INDEX Returns the substring of string before


number of occurrences of delimiter

• 30. TRIM Removes leading and trailing spaces from a string

[email protected]
String Functions
• 31. UCASE Converts a string to upper-case

• 32. UPPER Converts a string to upper-case

[email protected]
Numerical Functions
• 1. ABS Returns the absolute value of a number

• 2. ACOS Returns the arc cosine of a number

• 3. ASIN Returns the arc sine of a number

• 4. ATAN Returns the arc tangent of a number or returns the arc


tangent of n and m

• 5. ATAN2 Returns the arc tangent of n and m


[email protected]
Numerical Functions
• 6. AVG Returns the average value of an expression

• 7. CEIL Returns the smallest integer value that is greater


than or equal to a number

• 8. CEILING Returns the smallest integer value that is greater


than or equal to a number

• 9. COS Returns the cosine of a number


[email protected]
Numerical Functions
• 10. COT Returns the cotangent of a number

• 11. COUNT Returns the count of an expression

• 12. DEGREES Converts a radian value into degrees

• 13. DIV Used for integer division where n is divided by m


and an integer value is returned

[email protected]
Numerical Functions
• 16. EXP Returns e raised to the power of number

• 15. FLOOR Returns the largest integer value that is equal to or


less than a number

• 16. GREATEST Returns the greatest value in a list of expressions

• 17. LEAST Returns the smallest value in a list of expressions

[email protected]
Numerical Functions
• 18. LN Returns the natural logarithm of a number

• 19. LOG Returns the natural logarithm of a number or the


logarithm of a number to a specified base

• 20. LOG10 Returns the base-10 logarithm of a number

[email protected]
Numerical Functions
• 21. LOG2 Returns the base-2 logarithm of a number

• 22. MAX Returns the maximum value of an expression

• 23. MIN Returns the minimum value of an expression

• 24. MOD Returns the remainder of n divided by m

[email protected]
Numerical Functions
• 25. PI Returns the value of PI displayed with 6 decimal
places

• 26. POW Returns m raised to the nth power

• 27. POWER Returns m raised to the nth power

• 28. RADIANS Converts a value in degrees to radians

[email protected]
Numerical Functions
• 29. RAND Returns a random number or a random number
within a range

• 30. ROUND Returns a number rounded to a certain number of


decimal places

• 31. SIGN Returns a value indicating the sign of a number

• 32. SIN Returns the sine of a number


[email protected]
Numerical Functions
• 33. SQRT Returns the square root of a number

• 34. SUM Returns the summed value of an expression

• 35. TAN Returns the tangent of a number

• 36. TRUNCATE Returns a number truncated to a certain number


of decimal places

[email protected]
Date Functions
• 1. ADDDATE Returns a date after which a certain
time/date interval has been added

• 2. ADDTIME Returns a time/datetime value after which a


certain time interval has been added

• 3. CURDATE Returns the current date

• 4. CURRENT_DATE Returns the current date


[email protected]
Date Functions
• 5. CURRENT_TIME Returns the current time

• 6. CURRENT_TIMESTAMP Returns the current date and time

• 7. CURTIME Returns the current time

• 8. DATE Extracts the date value from a date or datetime


expression

[email protected]
Date Functions
• 9. DATEDIFF Returns a date after which a certain
time/date interval has been added

• 10. DATE_ADD Formats a date as specified by a format mask

• 11. DATE_FORMAT Returns a date after which a certain time/date


Interval has been subtracted

• 12. DATE_SUB Returns the difference in days between two


date value
[email protected]
Date Functions
• 13. DAY Returns the day portion of a date value

• 14. DAYNAME Returns the weekday name for a date

• 15. DAYOFMONTH Returns the day portion of a date value

• 16. DAYOFWEEK Returns the weekday index for a date value

[email protected]
Date Functions
• 17. DAYOFYEAR Returns day of the year for a date value

• 18. EXTRACT Extracts parts from a date

• 19. FROM_DAYS Takes a numeric representation of the day


and returns a date value

• 20. HOUR Returns the hour portion of a date value

[email protected]
Date Functions
• 21. LAST_DAY Returns the last day of the month for a given date

• 22. LOCALTIME Returns the current date and time

• 23. LOCALTIMESTAMP Returns the current date and time

• 24. MAKEDATE Returns the date for a certain year and day-of-year value

• 25. MAKETIME Returns the time for a certain hour, minute, second
combination
[email protected]
Date Functions
• 26. MICROSECOND Returns the microsecond portion of a date
value

• 27. MINUTE Returns the minute portion of a date value

• 28. MONTH Returns the month portion of a date value

• 29. MONTHNAME Returns the full month name for a date

[email protected]
Date Functions
• 30. NOW Returns the current date and time

• 31. PERIOD_ADD Takes a period (formatted as YYMM or


YYYYMM) and adds a specified number of months to
it

• 31. PERIOD_DIFF Returns the difference in months between


two periods (formatted as YYMM or YYYYMM)

• 32. QUARTER Returns the quarter portion of a date value


[email protected]
Date Functions
• 33. SECOND Converts numeric seconds into a time value

• 34. SEC_TO_TIME Returns the second portion of a date value

• 35. STR_TO_DATE Takes a string and returns a date specified by a format mask

• 36. SUBDATE Returns a date after which a certain time/date interval has
been subtracted

• 37. SUBTIME Returns a time/datetime value after which a certain time


interval has been subtracted
[email protected]
Date Functions
• 38. SYSDATE Returns the current date and time

• 39. TIME Extracts the time value from a


time/datetime expression

• 40. TIME_FORMAT Formats a time as specified by a format


mask

• 41. TIME_TO_SEC Converts a time value into numeric second


[email protected]
Date Functions
• 42. TIMEDIFF Returns the difference (expressed as a time value)
between two time/datetime values

• 43. TIMESTAMP Converts an expression to a datetime value and if


specified adds an optional time interval to the value

• 44. TO_DAYS Converts a date into numeric days

• 45. WEEK Returns the week portion of a date value


[email protected]
Date Functions
• 46. WEEKDAY Returns the weekday index for a date

• 47. WEEKOFYEAR Returns week of the year for a date value

• 48. YEAR Returns the year portion of a date value

• 49. YEARWEEK Returns the year and week for a date value

[email protected]
Thank You

[email protected]

You might also like