8 Mysql
8 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
[email protected]
Databases
• show databases;
• will display list of current databases available
[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
[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
[email protected]
Databases
• select database();
• to display the currently used database
• show tables;
• to show list of all the tables in the current database
[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“
[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, ...);
[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
[email protected]
Distinct
• To select the "CustomerName" and "City" columns from the
"Customers" table:
[email protected]
Where
• WHERE clause is used to extract only those records that fulfill a
specified condition.
• <> Not equal. Note: In some versions of SQL this operator may be written as !=
• 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:
[email protected]
Operators
• SELECT * FROM Customers
• WHERE Country='india' OR City='pune';
[email protected]
Order By
• The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
[email protected]
Order By
• SELECT * FROM Customers
• ORDER BY Country;
[email protected]
Order By
• SQL statement selects all customers from the "Customers" table,
• sorted by the "Country" and the "CustomerName" column:
[email protected]
Order By
• SQL statement selects all customers from the "Customers" table,
sorted ascending by the "Country" and descending by the
"CustomerName" column:
[email protected]
Null Values
• A field with a NULL value is a field with no value.
[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;
[email protected]
Update
• The UPDATE statement is used to modify the existing records in a
table.
• 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.
• 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:
• SELECT column_name(s)
• FROM table_name WHERE condition LIMIT number;
[email protected]
Aggregate Functions
• For these examples create "Prodcuts" and "OrderDeatils" tables,
accordingly
• The MIN() function returns the smallest value of the selected column.
[email protected]
Aggregate Functions
• The MAX() function returns the largest value of the selected column.
[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 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.
[email protected]
Like
• SQL statement selects all customers with a CustomerName ending
with "a":
[email protected]
Like
• SQL statement selects all customers with a CustomerName that have
"or" in any position:
[email protected]
Like
• SQL statement selects all customers with a CustomerName that have
"r" in the second position:
[email protected]
Like
• SQL statement selects all customers with a CustomerName that starts
with "a" and are at least 3
• characters in length:
[email protected]
Like
• SQL statement selects all customers with a CustomerName that starts
with "a" and ends with "o":
[email protected]
Like
• SQL statement selects all customers with a CustomerName that NOT
starts with "a":
[email protected]
In
• For the examples you need to create a "Suppliers" table also
[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":
[email protected]
In
• SQL statement selects all customers that are NOT located in
"Germany", "France" or "UK":
[email protected]
In
• SQL statement selects all customers that are from the same countries
as the suppliers:
[email protected]
Between
• The BETWEEN operator selects values within a given range.
[email protected]
Between
• SQL statement selects all products with a price BETWEEN 10 and 20:
[email protected]
Between
• To display the products outside the range of the previous example,
use NOT BETWEEN:
[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:
[email protected]
Between
• SQL statement selects all products with a ProductName BETWEEN
'brittiana' and 'marie':
[email protected]
Between
• SQL statement selects all products with a ProductName NOT
BETWEEN 'brittiana' and 'marie':
[email protected]
Between
• SQL statement selects all orders with an OrderDate BETWEEN '04-
July-2016' and '09-July-2016':
[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(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:
[email protected]
Aliases
• SQL statement creates an alias named "Address" that combine 3
columns
[email protected]
Aliases
[email protected]
Aliases
• We use the "Customers" and "Orders" tables, and give them the table
aliases of "c" and "o" respectively
[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:
[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.
[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;
• 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;
• 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:
• 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:
[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 in each SELECT statement must also be in the same order
[email protected]
Union
[email protected]
Union
• UNION ALL Syntax
[email protected]
Union
• The following SQL statement selects all the different German cities (only
distinct values) from "Customers" and "Suppliers":
[email protected]
Group By
• SQL GROUP BY Statement
• 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:
[email protected]
Group By
• SQL statement lists the number of customers in each country, sorted
high to low:
[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:
[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):
[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):
[email protected]
Insert
• SQL statement copies "Suppliers" into "Customers" (fill all columns):
[email protected]
Insert
• SQL statement copies only the German suppliers into "Customers":
[email protected]
Auto-increment
• 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.
[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):
[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.
• 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.
[email protected]
Views
• You can update a view by using the following syntax:
[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:
[email protected]
Views
• SQL Dropping a View
• 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.
[email protected]
Index
• The SQL statement below creates an index named "idx_lastname" on
the "LastName" column in the "Persons" table:
[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:
[email protected]
Index
• DROP INDEX Statement
• MySQL:
[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.)
[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:
[email protected]
String Functions
• 1. ASCII Returns the number code that represents the specific
character
[email protected]
String Functions
• 6. FIELD Returns the position of a value in a list of values
[email protected]
String Functions
• 31. UCASE Converts a string to upper-case
[email protected]
Numerical Functions
• 1. ABS Returns the absolute value of a number
[email protected]
Numerical Functions
• 16. EXP Returns e raised to the power of number
[email protected]
Numerical Functions
• 18. LN Returns the natural logarithm of a number
[email protected]
Numerical Functions
• 21. LOG2 Returns the base-2 logarithm of a number
[email protected]
Numerical Functions
• 25. PI Returns the value of PI displayed with 6 decimal
places
[email protected]
Numerical Functions
• 29. RAND Returns a random number or a random number
within a range
[email protected]
Date Functions
• 1. ADDDATE Returns a date after which a certain
time/date interval has been added
[email protected]
Date Functions
• 9. DATEDIFF Returns a date after which a certain
time/date interval has been added
[email protected]
Date Functions
• 17. DAYOFYEAR Returns day of the year for a date value
[email protected]
Date Functions
• 21. LAST_DAY Returns the last day of the month for a given date
• 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
[email protected]
Date Functions
• 30. NOW Returns the current date and time
• 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
• 49. YEARWEEK Returns the year and week for a date value
[email protected]
Thank You