SlideShare a Scribd company logo
Asst. Lec.
Zahraa NajimAbdullah
July 2021
https://uokerbala.edu.iq/
Asst. Lec.
Huda Ragib Kadhim
Lecture One
Relational Database Management System
• A relational database can be defined informally as: A relational database is a database
where all data visible to the user is organized strictly as tables of data values, and where all
database operations work on these tables.
• From the definition it is known that the organizing principle in a relational database is the
table, a rectangular, two-dimensional arrangement of data values.
TABLES
• Each table has a unique table name that identifies its contents. Each
column in a table has a column name, which is at the top of the column.
• The columns of a table must all have different names. The data in each
column is of the same type.
• Each row of a table contains exactly one data value in each column.
The rows in a table do not have any particular order.
• A table can have any number of rows. A table of zero rows is
called an empty table, which means it contains no data.
Introduction to SQL Language
• SQL is an abbreviation for Structured Query Language (pronounced "ess- que-
el").SQL is used to communicate with a database meaning, it is a tool for
organizing, managing, and retrieving data stored in a database.
• According to ANSI (American National Standards Institute), it is the standard
language for relational database management systems (RDBMS).
• SQL statements are used to perform tasks such as update data on a database, or
retrieve data from a database.
• Some common relational database management systems that use SQL are:
Oracle, Sybase, Microsoft SQL Server, Access, Ingress, Mysql, etc.
• To allow access to the information in a database, SQL defines the
reserved words (operations, functions and commands) of the
language which indicates the actions to be performed on the
database.
• These words are described by Data Definition Language (DDL)
and Data Manipulation Language (DML).
• The DDL commands allow us to create and define new
databases, fields and indexes while the DML commands let us
build queries to sort, filter and extract data from the database
DDL Commands
• CREATE used to create new tables, fields and indexes.
• DROP is used to delete tables and indexes from the databases.
• ALTER is used to modify tables by adding fields or changing field
definitions.
DML Commands
• SELECT is used to query the database.
• INSERT is used to load data into the database.
• UPDATE is used to change the values of particular records and
fields.
• DELETE is used to remove records from a database.
Why choose MySQL?
• 1. Speed. Developers claims it's the fastest
(http//:www.mysql.com/benchmark.html)
• 2. Ease of Use Simple administrations and installations
• 3. Its free
• 4. Query Language Support Supports SQL
• 5. Capability
• 6. Connectivity and Security Accessed from whereever you are and supports
flixable access control
• 7. Portability: Run on Linux, Unix, Solaris , FreeBSD ,Windows , etc
• 8. Open source
Mysql Installation
•UseWamp server to install mysql server, we will
use the wamp server to get phpmyadmin also.
•You are done and ready to use the system!!
Issuing Queries (General Queries)
• Connect to database server either remotely or locally and type
the following commands:
mysql> SELECT NOW();
mysql> SELECT NOW ();
mysql> SELECT NOW(),VERSION();
mysql> SHOW DATABASES;
mysql> USE mysql;
mysql> SHOWTABLES;
mysql> DESCRIBE USER;
Database related SQL (create a database )
To create a database :
CREATE DATABASE db_name
To delete a database and all the tables inside:
DROP DATABASE db_name
To list all the databases in the server :
SHOW DATABASES
To set the default database for the current session :
USE db_name
Create aTable
This is an example of the CREATETABLE sql :
CREATETABLE HeadOfState (
ID INT NOT NULL,
LastName CHAR(30) NOT NULL,
FirstName CHAR(30) NOT NULL );
Note : We can examine the table structure using
SHOW CREATETABLE tbl_name
Which shows the CREATETABLE statement that creates the given table. Alternatively
we can use the below statement to display more user friendly table description:
DESCRIBE table_name
To list all the tables in the current database:
SHOWTABLES
To drop a table and all its data:
DROPTABLE table_name
To display all the data in a table:
SELECT * FROM table_name
CreatingTables Based on ExistingTables
MySQL provides two ways to create a table based on another table:
CREATETABLE ... SELECT creates a table and populates it from the result set
returned by an arbitrary SELECT statement. In this case, the "other table" is the set of
rows and columns retrieved by the SELECT.
CREATETABLE ... LIKE creates an empty table using the definition of another
existing table.
CREATETABLE ... SELECT can create a table that is empty or non-empty, depending
on what is returned by the SELECT part.
The result is a new table with a definition that includes all column attributes and
indexes of the original table. Suppose that table t looks like this:
CREATETABLE t
(i INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (i))
ENGINE = MyISAM;
The result of CREATE TABLE ... LIKE differs from the result of using CREATE
TABLE ... SELECT to create an empty table. Either of the following statements will
create an empty copy of the table t:
mysql> CREATE TABLE copy1 SELECT * FROM t WHERE 0;
mysql> CREATE TABLE copy2 LIKE t;
However, the resulting copies differ in the amount of information retained from the original table structure:
mysql> SHOW CREATETABLE copy1G;
*************************** 1. row ***************************
Table: copy1
Create Table: CREATETABLE ‘copy1 ‘ (
‘i ‘ int(11) NOT NULL default '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1
mysql> SHOW CREATETABLE copy2G;
*************************** 1. row ***************************
Table: copy2
Create Table: CREATETABLE ‘copy2 ‘ (
‘i ‘ int(11) NOT NULL auto_increment,
PRIMARY KEY (i ‘)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Adding and Dropping Columns
To add a new column to a table, use ALTERTABLE with an ADD clause that specifies
the column's definition. A column definition uses the same syntax for ALTERTABLE
as for CREATE TABLE. For example, to add a DATE column named Inauguration
you can issue this statement:
ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL;
That ALTERTABLE statement changes the table structure as follows:
mysql> DESCRIBE HeadOfState;
To indicate that MySQL should place the new column in a specific position within the
table, append either the keyword FIRST or the keyword-identifier combination
AFTER column_name to the column definition. For example, assume that you had
executed this ALTERTABLE statement instead of the previous one:
ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL FIRST;
The FIRST keyword tells ALTERTABLE to place the new column before all existing
columns (in the "first" position), resulting in the following table structure:
mysql> DESCRIBE HeadOfState;
Using AFTER column_name tells ALTERTABLE to place the new column
after a specific existing column. For example, to place the new Inauguration
column after the existing FirstName column, you would issue this statement:
ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL AFTER
FirstName;
That ALTERTABLE statement results in a table structure that looks like this:
mysql> DESCRIBE HeadOfState;
Column names within a table must be unique, so you cannot add a column
with the same name as one that already exists in the table. Also, column
names are not case sensitive, so if the table already contains a column named
ID, you cannot add a new column using any of these names: ID, id, Id, or iD.
They all are considered to be the same name.
To drop a column, use a DROP clause that names the column to be removed:
ALTERTABLE table_name DROP column_name;
Modifying Existing Columns
There are two ways to change the definition of an existing column within a table. One
of these also enables you to rename the column.
The first way to alter a column definition is to use a MODIFY clause. You must specify
the name of the column that you want to change, followed by its new definition.
Assume that you want to change the ID column's data type from INT to BIGINT, to
allow the table to accommodate larger identification numbers. You also want to make
the column UNSIGNED to disallow negative values. The following statement
accomplishes this task:
ALTERTABLE HeadOfState MODIFY ID BIGINT UNSIGNED NOT NULL;
DESCRIBE or (DESC) now shows the table structure to be as follows:
mysql> DESCRIBE HeadOfState;
The second way to alter a column definition is to use a CHANGE clause. CHANGE
enables you to modify both the column's definition and its name. To use this clause,
specify the CHANGE keyword, followed by the column's existing name, its new
name, and its new definition, in that order. Note that this means you must specify the
existing name twice if you want to change only the column definition (and not the
name). For example, to change the LastName column from CHAR(30) to CHAR(40)
without renaming the column, you'd do this:
ALTERTABLE HeadOfState CHANGE LastName LastName CHAR(40) NOT NULL;
To change the name as well (for example, to Surname), provide the new name
following the existing name:
ALTERTABLE HeadOfState CHANGE LastName Surname CHAR(40) NOT NULL;
Renaming aTable
Renaming a table changes neither a table's structure nor its contents. The following statement renames
table t1 to t2:
ALTERTABLE t1 RENAMETO t2;
Another way to rename a table is by using the RENAMETABLE statement:
RENAMETABLE t1TO t2;
RENAME TABLE has an advantage over ALTER TABLE in that it can perform multiple table renames in a
single operation. One use for this feature is to swap the names of two tables:
RENAMETABLE t1TO tmp, t2TO t1, tmpTO t2;
For TEMPORARY tables, RENAMETABLE does not work.You must use ALTERTABLE instead.
ALTERTABLE HeadOfState MODIFY ID BIGINT UNSIGNED NOT NULL;
MySQL DataTypes
Generally there are 3 categories of column type supported
by MySQL which are :
1. NumericType
2. String (Character )Type
3. Date andTimeType
Numeric ColumnType
MySQL understands integers, floating points and scientific
notations. Numbers can be preceded by a minus sign to indicate
negative value. Following is the column type available (commonly
used in MySQL).
INT,TINYINT, SMALLINT, INT, FLOAT, DOUBLE, DECIMAL,
Usage example:
TINYINT[(M)] [UNSIGNED] [ZEROFILL]
DOUBLE [(M,D)] [ZEROFILL]
String ColumnTypes
CHAR,VARCHAR,TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB,TINYTEXT,TEXT,
MEDIUMTEXT,LONGTEXT,ENUM,SET
example:
nameVARCHAR(20) NOT NULL,
In Numeric Column Type, the number inside the parenthesis indicates display number, but in over here it is not.
It explicitly defined the length of the character.
Only CHAR and VARCHAR s' length can be defined. Strings are actually a 'generic' type in a sense because it
can be used to hold any values.
VARCHAR and CHAR are the most common type. CHAR is fixed length type while the VARCHAR is variable
length type. BLOB is a binary large object which can hold anything you throw into it. The variation indicates
different maximum number of information can be stored. TEXT type is identical to BLOB, but different in the
sense that BLOB is case sensitive while TEXT is case insensitive. (This matters when sorting and comparing is
used).
ENUM and SET
• ENUM and SET are special type for which colomn values must be chosen
from a fixed set of strings.
• Difference is ENUM column values must have at least exactly one member
of the set while SET may contain any or all members of the set.
Date andTime ColumnType
• DATE,TIME, DATETIME,TIMESTAMP,YEAR
• Values of TIME type are elapsed time. A 12:30:00 means 12 hours, and 30
minutes and not 12.30 am which means that TIME can hold values like
50:13:00 but not 50:65:00
• If TIMESTAMP column is set to "NULL" then automatically it will be set to
current time and date.
• M inTIMEFORMAT indicates display formats
Attributes
A. Numeric ColumnType
1. AUTO_INCREMENT Indicates that the value is automatically increased by 1
from the previous value. For any column to be used as auto_increment must
be declared as NOT NULL and PRIMARY KEY / UNIQUE KEY
2. UNSIGNED Disallows negative numbers
B. String ColumnTypes
1. Binary Specified for CHAR or VARCHAR, which causes the column values to
be treated as binary strings.
2. NULL or NOT NULL
3. DEFAULT To specify a default value for CHAR or VARCHAR only.
Inserting into aTable
The INSERT statement is used to insert or add a new row of data into a table, below
we have the two forms of the insert statement:
INSERT INTO table_name (column_list) VALUES (value_list);
INSERT INTO table_name SET column_name = value [, column_name2
= value2] ... ;
For any column not assigned an explicit value by an INSERT statement, MySQL sets
it to its default value if it has one. For example, to have MySQL set the id column to
its default, you can simply omit it from the statement.The following example shows
statements using each INSERT syntax that assign no explicit id value:
Examples :
INSERT INTO people (name,age) VALUES('William',25);
INSERT INTO people SET name = 'William', age = 25;
LectureTwo
Retrieving Non specific Data
SELECT command is used to retrieve data from tables.The simplest retrieval is when
you ask for all the data in a table. Following command retrieve all data from table
named 'animal'
SELECT * FROM animals
This statement returns all the data in all the rows and columns of the table 'animals'.
The asterisk (*) is a wildcard character means "all attributes ".
Retrieving Specific Data
SELECT command can be used to query the database and retrieve selected data that
match the certain criteria. These is easily achieved by adding "WHERE" clause to the
SELECT statement above. Here is the format of a simple select statement:
SELECT "column1" [,"column2", etc] FROM tbl_name [where
"condition"];
Example:
SELECT * FROM animals WHERE gender='f' AND species='cat';
Expression in WHERE clause can use arithmetic operators, comparison operators and
logical operators as below
Arithmetic Operators+ :, - , * and /
Comparison Operators= : , > , >= , ) =! <> ) , >= and >
Logical Operator: AND, OR, NOT
Others: BETWEEN, Like
Specifying Which Rows to Retrieve
If you specify no criteria for selecting records from a table, a SELECT
statement retrieves every record in the table. This is often more information
than you need, particularly for large tables. To be more specific about which
rows are of interest, include a WHERE clause that describes the characteristics
of those rows.
• SELECT * FROM Country WHERE IndepYear > 1990;
• SELECT * FROM Country WHERE Population >= 1000000 AND
Population <= 2000000;
• SELECT * FROM Country WHERE Population BETWEEN 1000000 AND
2000000;
Using ORDER BY to Sort Query Results
By default, the rows in the result set produced by a SELECT statement are
returned by the server to the client in no particular order. If you require output
rows to be returned in a specific order, include an ORDER BY clause that
indicates how to sort the results. The examples in this section demonstrate
ORDER BY:
• SELECT id, last_name, first_name, birth FROM t ORDER BY birth;
• SELECT id, last_name, first_name, birth FROM t ORDER BY last_name,
first_name;
• SELECT id, last_name, first_name, birth FROM t ORDER BY id DESC;
Limiting a Selection Using LIMIT
MySQL supports a LIMIT clause in SELECT statements, which tells the server to
return only some of the rows selected by the statement. This is useful for retrieving
records based on their position within the set of selected rows. LIMIT may be given
with either one or two arguments:
LIMIT row_count
LIMIT skip_count, row_count
SELECT * FROM Country LIMIT 10;
SELECT * FROM Country LIMIT 20,10;
Deleting Records
To remove records from tables, use a DELETE statement or a trUNCATE TABLE statement. The
DELETE statement allows a WHERE clause that identifies which records to remove, whereas
TRUNCATETABLE always removes all records. DELETE therefore can be more precise in its effect.
To empty a table entirely by deleting all its records, you can use either of the following statements:
DELETE FROM table_name;
TRUNCATETABLE table_name;
To remove only specific records in a table, trUNCATE TABLE cannot be used. You must issue a
DELETE statement that includes a WHERE clause that identifies which records to remove:
DELETE FROM table_name WHERE ... ;
Updating Records
The UPDATE statement is used to update or change records that match
specified criteria. This is accomplished by carefully constructing a where
clause.
UPDATE table_name
SET column_name = value [, column_name = value] ...
WHERE ... ;
Using DISTINCT to Eliminate Duplicates
If a query returns a result that contains duplicate rows, you can remove
duplicates to produce a result set in which every row is unique. To do this,
include the keyword DISTINCT after SELECT and before the output column
list.
Suppose that a query returns a result set that contains duplicated rows:
mysql> SELECT last_name FROM t;
Adding DISTINCT removes the duplicates and returns only unique rows:
mysql> SELECT DISTINCT last_name FROM t;
Aggregating Results
A SELECT statement can produce a list of rows that match a given set of
conditions. The list provides the details about the selected rows, but if you
want to know about the overall characteristics of the rows, you'll be more
interested in getting a summary instead. When that's your goal, use aggregate
functions to calculate summary values, possibly combined with a GROUP BY
clause to arrange the selected rows into groups so that you can get summaries
for each group. Grouping can be based on the values in one or more columns
of the selected rows.
There are several types of aggregate functions.Those discussed
here are as follows:
• MIN() and MAX() find smallest and largest values.
• SUM() and AVG() summarize numeric values to produce sums
(totals) and averages.
• COUNT() counts rows, values, or the number of distinct values.
The MIN() and MAX() Aggregate Functions
MIN() and MAX() are comparison functions. They return smallest or largest numeric
values, lexically first or last string values, and earliest or latest temporal values. The
following queries determine the smallest and largest country populations and the
lexically first and last country names:
mysql> SELECT MIN(Population), MAX(Population) FROM Country;
mysql> SELECT MIN(Name), MAX(Name) FROM Country;
MIN() and MAX() ignore NULL values.
The SUM() and AVG() Aggregate Functions
The SUM() and AVG() functions calculate sums and averages. For example,
the Country table in the world database contains a Population column, so
you can calculate the total world population and the average population per
country like this:
mysql> SELECT SUM(Population), AVG(Population) FROM Country;
SUM() and AVG() ignore NULL values.
COUNT() Aggregate Function
The COUNT() function can be used in several ways to count either rows or values. To
illustrate, the examples here use the following table that has several rows containing
various combinations of NULL and non-NULL values:
SELECT COUNT(i), COUNT(j) FROM t;
COUNT(DISTINCT expression) counts the number of distinct (unique) non-NULL
values of the given expression. expression can be a column name to count the
number of distinct non-NULL values in the column:
SELECT COUNT(DISTINCT i), COUNT(DISTINCT j) FROM t;
SELECT COUNT(DISTINCT i, j) FROM t;
Grouping Results
If a query does not contain a GROUP BY clause to place rows of the result set into
groups, an aggregate function produces a result that is based on all the selected rows.
A GROUP BY clause may be added to generate a more fine-grained summary that
produces values for subgroups within a set of selected rows.
Adding a GROUP BY clause arranges rows using the values in the grouping column or
columns.The result is that COUNT(*) produces a count for each group.To find out
how many times each title occurs, do this:
• SELECT title, COUNT(*) FROM personnel GROUP BY title;
• SELECT dept_id, title, COUNT(*) FROM personnel GROUP BY dept_id, title;
GROUP BY and Sorting
In MySQL, a GROUP BY clause has the side effect of sorting rows. If you
already have a GROUP BY clause in your query that produces the desired sort
order, there's no need for an ORDER BY. Use of ORDER BY is necessary with
GROUP BY only to produce a different sort order than that resulting from the
GROUP BY. However, this isn't a portable behavior. For database engines
other than MySQL, GROUP BY might not sort rows. To write more portable
queries, add an ORDER BY even if MySQL does not require it.
Selecting Groups with HAVING
It could be when you use GROUP BY that you're interested only in groups that have
particular summary characteristics. To retrieve just those groups and eliminate the
rest, use a HAVING clause that identifies the required group characteristics. HAVING
acts in a manner somewhat similar to WHERE, but occurs at a different stage of query
processing:
1.WHERE, if present, identifies the initial set of records to select from a table.
2. GROUP BY arranges the selected records into groups.
3. Aggregate functions compute summary values for each group.
4. HAVING identifies which groups to retrieve for the final result set.
mysql> SELECT title, salary, COUNT(*), AVG(salary)
-> FROM personnel WHERE dept_id = 7
-> GROUP BY title
-> HAVING COUNT(*)> 1;
LectureThree
Joins
• When it's necessary to draw on information that is stored in multiple tables, use a join—
an operation that produces a result by combining (joining) information in one table with
information in another.
• A join between tables is an extension of a single-table SELECT statement, but involves
the following additional complexities:
• The FROM clause names all the tables needed to produce the query result, not just one
table.
• A join that matches records in one table with records in another must specify how to
match up the records. These conditions often are given in the WHERE clause, but the
particular syntax depends on the type of join.
1. SELECT Name, Language FROM CountryLanguage, Country WHERE CountryCode = Code;
2. SELECT Name, Language FROM Country INNER JOIN CountryLanguage ON Code =
CountryCode;
Outer Join
• An inner join produces results by selecting combinations of matching rows from the joined tables.
• However, it cannot find nonmatches; that is, instances where a row in one table has no match in
another table.
• An outer join finds matches (just like an inner join), but also identifies mismatches.
• Furthermore, with an appropriate WHERE clause, an outer join can filter
out matches to display only the mismatches.
• Two common forms of outer joins are left joins and right joins.
• These are written using the LEFT JOIN or RIGHT JOIN keywords rather than the comma operator
or the INNER JOIN keywords.
Outer Join
• A left join is a type of outer join, written using the LEFT JOIN keywords.
• A left join treats the left table (the first one named) as a reference table and produces output for
each row selected from it, whether or not the row is matched by rows in the right table.
• A LEFT JOIN is written using either ON or USING()after the table names in the FROM clause.
• The example here uses the ON syntax:
SELECT Name, Language FROM Country LEFT JOIN CountryLanguage ON Code = CountryCode;
• In this query, the left table is the one named first (Country) and the right table is the one named
second (CountryLanguage).
Outer Join
• A right join is another type of outer join, written using the RIGHT JOIN keywords.
• Every right join corresponds to an equivalent left join.
• The only difference is that the roles of the tables in a right join are reversed relative to the
roles in a left join.
• That is, the right table is the reference table, so a RIGHT JOIN produces a result for each row
in the right table, whether or not it has any match in the left table.
Updating and Deleting MultipleTables
• MySQL allows the use of join syntax in UPDATE and DELETE statements to enable updates or
deletes that involve multiple tables.
• Some of the principles involved in writing joins in SELECT statements also apply to multiple-table
UPDATE and DELETE statements. This section provides a brief overview of their syntax.
• A multiple-table UPDATE is an extension of a single-table statement:
• Following the UPDATE keyword, name the tables involved in the operation, separated by commas. (You must name all the
tables used in the query, even if you aren’t updating all of them.)
• In the WHERE clause, describe the conditions that determine how to match records in the tables.
• In the SET clause, assign values to the columns to be updated. These assignments can refer to columns from any of the
joined tables.
UPDATE t1, t2 SET t1.name = t2.name WHERE t1.id = t2.id;
Updating and Deleting MultipleTables
• Multiple-table DELETE statements can be written in two formats.
• The following example demonstrates one syntax, for a query that deletes rows from a table t1
where the id values match those in a table t2:
DELETE t1 FROM t1, t2 WHERE t1.id = t2.id;
• The second syntax is slightly different:
DELETE FROM t1 USING t1, t2 WHERE t1.id = t2.id;
• The ORDER BY and LIMIT clauses normally supported by UPDATE and DELETE aren’t
allowed when these statements are used for multiple-table operations.
SQL Expressions
• Expressions are a common element of SQL statements, and they occur in many contexts.
• For example, expressions often occur in the WHERE clause of SELECT, DELETE, or
UPDATE statements to identify which records to retrieve, delete, or update.
• But expressions may be used in many other places; for example, in the output column list of a
SELECT statement, or in ORDER BY or GROUP BY clauses.
• Expressions use different types of values like : Table columns, Literal values, or Functions.
String Expressions
• Literal strings in expressions are written as quoted values.
• By default, either single quotes or double quotes can be used, although single quotes are more standard.
• The data types for representing strings in tables include CHAR, VARCHAR, BINARY, VARBINARY, and the TEXT and
BLOB types.
• String concatenation is done with the CONCAT() function:
SELECT CONCAT('abc','def');
+-----------------------------------+
| CONCAT('abc','def’) |
+-----------------------------------+
| abcdef |
+-----------------------------------+
• UPPER() and LOWER() functions perform case conversion only if the argument is a non-binary
string.
SELECT UPPER('AbCd'), LOWER('AbCd');
+---------------+---------------+
| UPPER('AbCd') | LOWER('AbCd') |
+---------------+---------------+
| ABCD |abcd |
+---------------+---------------+
Using LIKE for Pattern Matching
• Operators such as = and =! are useful for finding values that are equal to or not equal to a
specific exact comparison value.
• When it's necessary to find values based on similarity instead, a pattern match is useful.
• To perform a pattern match, use value LIKE 'pattern', where value is the value you want to test
and 'pattern' is a pattern string that describes the general form of values that you want to
match.
• Patterns used with the LIKE pattern-matching operator can contain two special characters
(called "metacharacters" or "wildcards "( that stand for something other than themselves:
• The '%' character matches any sequence of zero or more characters.
• The '_' (underscore) character matches any single character.
• To match a pattern metacharacter literally, escape it by preceding it by a backslash.
Using LIKE for Pattern Matching
SELECT 'AA' LIKE 'A%', 'AA' LIKE 'A%', 'A%' LIKE 'A%';
+-----------------+-----------------+----------------+
| 'AA' LIKE 'A%’ | 'AA' LIKE 'A%' | 'A%' LIKE 'A%'|
+-----------------+-----------------+----------------+
| 1| 0| 1|
+-----------------+-----------------+----------------+
mysql> SELECT 'AA' LIKE 'A_', 'AA' LIKE 'A_', 'A_' LIKE 'A_';
+-----------------+-----------------+----------------+
| 'AA' LIKE 'A_’ | 'AA' LIKE 'A_’ | 'A_' LIKE 'A_'|
+-----------------+-----------------+----------------+
| 1| 0 | 1|
+-----------------+-----------------+----------------+
Foreign Key
• InnoDB supports foreign key constraints.
• The syntax for a foreign key constraint definition in the create table statement:
[CONSTRAINT [symbol]] FOREIGN KEY
(index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
Foreign Key Conditions
1. Both tables must be InnoDB tables and they must not be TEMPORARY tables.
2. Corresponding columns in the foreign key and the referenced key must have similar internal
data types inside InnoDB so that they can be compared without a type conversion. The sign
of integer types must be the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation must be the same.
3. InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can
be fast and not require a table scan. In the referencing table, there must be an index where
the foreign key columns are listed as the first columns in the same order. Such an index is
created on the referencing table automatically if it does not exist.
4. InnoDB permits a foreign key to reference any index column or group of columns. However, in
the referenced table, there must be an index where the referenced columns are listed as the
first columns in the same order.
5. If the CONSTRAINT symbol clause is given, the symbol value must be unique in the
database. If the clause is not given, InnoDB creates the name automatically.
Foreign Key
• nnoDB rejects any INSERT or UPDATE operation that attempts to create a foreign key value in
a child table if there is no a matching candidate key value in the parent table.
• The action InnoDB takes for any UPDATE or DELETE operation that attempts to update or
delete a candidate key value in the parent table that has some matching rows in the child table
is dependent on the referential action specified using ON UPDATE and ON DELETE
subclauses.
• InnoDB supports four options regarding the action to be taken. If ON DELETE or ON UPDATE
are not specified, the default action is RESTRICT.
1. CASCADE: Delete or update the row from the parent table and automatically delete or update the matching rows in
the child table.
2. SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child
table to NULL.
3. NO ACTION, RESTRICT: Attempt to delete or update a primary key value is not permitted to proceed if there is a
related foreign key value in the referenced table.
Foreign Key Example
• Here is a simple example that relates parent and child tables through a single-column
foreign key:
CREATE TABLE parent (id INT NOT NULL, PRIMARY KEY (id)) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT, INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE) ENGINE=INNODB;
MySQLTransactions
• A transaction is a sequential group of database manipulation operations, which is performed
as if it were one single work unit.
• In other words, a transaction will never be complete unless each individual operation within
the group is successful.
• If any operation within the transaction fails, the entire transaction will fail.
• Two keywords Commit and Rollback are mainly used for MySQL Transactions.
• When a successful transaction is completed, the COMMIT command should be issued so
that the changes to all involved tables will take effect.
• If a failure occurs, a ROLLBACK command should be issued to return every table
referenced in the transaction to its previous state.
MySQLTransactions Example
1. Begin transaction by issuing SQL command BEGIN WORK
2. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE
3. Check if there is no error and everything is according to your requirement.
4. If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
Views
• A view is a database object that is defined in terms of a SELECT statement that retrieves the
data you want the view to produce.
• A view can be used to select from regular tables (called "base tables “) or other views.
• In some cases, a view is updatable and can be used with statements such as UPDATE,
DELETE, or INSERT to modify an underlying base table.
• To define a view, use the CREATE VIEW statement, which has this syntax:
CREATE [OR REPLACE] [ALGORITHM = algorithm_type]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
Views
• view_name is the name to give the view.
• select_statement is a SELECT statement that indicates how to retrieve data when the view is
used. The statement can select from base tables or other views.
• The OR REPLACE clause causes any existing view with same name as the new one to be
dropped prior to creation of the new view.
• The ALGORITHM clause specifies the processing algorithm to use when the view is invoked.
• column_list provides names for the view columns to override the default names.
• When the WITH CHECK OPTION clause is included in a view definition, all data changes
made to the view are checked to ensure that the new or updated rows satisfy the view-
defining condition. If the condition is not satisfied, the change is not accepted, either in the
view or in the underlying base table.
Views
• The following CREATE VIEW statement defines a simple view named CityView that selects the ID
and Name columns from the City table. The SELECT statement shows an example of how to
retrieve from the view:
CREATE VIEW CityView AS SELECT ID, Name FROM City;
SELECT * FROM CityView;
+-----------------------------------+
| ID | Name |
+-----------------------------------+
| 1 | Kabul |
| 2 | Qandahar |
| 3 | Herat |
| 4 | Mazar-e-Sharif |
...
• Views and base tables share the same namespace, so CREATE VIEW results in an error if a base
table or view with the given name already exists.
MySQL Essential Training

More Related Content

What's hot

introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
farwa waqar
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
Ehsan Hamzei
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Languagepandey3045_bit
 
Database Overview
Database OverviewDatabase Overview
Database Overview
Livares Technologies Pvt Ltd
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
TechandMate
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
Sharad Dubey
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
Smriti Jain
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsAshwin Dinoriya
 
Sql commands
Sql commandsSql commands
Sql commands
Mohd Tousif
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
Ram Sagar Mourya
 
SQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate TableSQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate Table
1keydata
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
SQL
SQLSQL
Sql commands
Sql commandsSql commands
Sql commands
Pooja Dixit
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commandsBelle Wx
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
Eddyzulham Mahluzydde
 

What's hot (19)

introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Database Overview
Database OverviewDatabase Overview
Database Overview
 
SQL Server Learning Drive
SQL Server Learning Drive SQL Server Learning Drive
SQL Server Learning Drive
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
DDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and JoinsDDL,DML,SQL Functions and Joins
DDL,DML,SQL Functions and Joins
 
Sql commands
Sql commandsSql commands
Sql commands
 
A must Sql notes for beginners
A must Sql notes for beginnersA must Sql notes for beginners
A must Sql notes for beginners
 
SQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate TableSQL Tutorial - How To Create, Drop, and Truncate Table
SQL Tutorial - How To Create, Drop, and Truncate Table
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
SQL
SQLSQL
SQL
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
1 ddl
1 ddl1 ddl
1 ddl
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 

Similar to MySQL Essential Training

Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
paddu123
 
Module 3
Module 3Module 3
Module 3
cs19club
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
PavithSingh
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
SakkaravarthiS1
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
Sheethal Aji Mani
 
Sql tables
Sql tablesSql tables
Sql tables
arwa wshyar
 
Creating, altering and dropping tables
Creating, altering and dropping tablesCreating, altering and dropping tables
Creating, altering and dropping tablespunu_82
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
Abrar ali
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
jainendraKUMAR55
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
Sankhya_Analytics
 
ADBMS Unit-II c
ADBMS Unit-II cADBMS Unit-II c
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
Raj vardhan
 
Oraclesql
OraclesqlOraclesql
Oraclesql
Priya Goyal
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
PriyaPandey767008
 
Lab
LabLab

Similar to MySQL Essential Training (20)

Mysql cheatsheet
Mysql cheatsheetMysql cheatsheet
Mysql cheatsheet
 
Sql smart reference_by_prasad
Sql smart reference_by_prasadSql smart reference_by_prasad
Sql smart reference_by_prasad
 
Module 3
Module 3Module 3
Module 3
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
Sql tables
Sql tablesSql tables
Sql tables
 
Creating, altering and dropping tables
Creating, altering and dropping tablesCreating, altering and dropping tables
Creating, altering and dropping tables
 
Database COMPLETE
Database COMPLETEDatabase COMPLETE
Database COMPLETE
 
DBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptxDBMS and SQL(structured query language) .pptx
DBMS and SQL(structured query language) .pptx
 
Getting Started with MySQL I
Getting Started with MySQL IGetting Started with MySQL I
Getting Started with MySQL I
 
Sql
SqlSql
Sql
 
ADBMS Unit-II c
ADBMS Unit-II cADBMS Unit-II c
ADBMS Unit-II c
 
SQL Tutorial for BCA-2
SQL Tutorial for BCA-2SQL Tutorial for BCA-2
SQL Tutorial for BCA-2
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
Mysql
MysqlMysql
Mysql
 
Lab
LabLab
Lab
 
Les10 Creating And Managing Tables
Les10 Creating And Managing TablesLes10 Creating And Managing Tables
Les10 Creating And Managing Tables
 

Recently uploaded

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 

Recently uploaded (20)

Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 

MySQL Essential Training

  • 1. Asst. Lec. Zahraa NajimAbdullah July 2021 https://uokerbala.edu.iq/ Asst. Lec. Huda Ragib Kadhim
  • 3. Relational Database Management System • A relational database can be defined informally as: A relational database is a database where all data visible to the user is organized strictly as tables of data values, and where all database operations work on these tables. • From the definition it is known that the organizing principle in a relational database is the table, a rectangular, two-dimensional arrangement of data values.
  • 4. TABLES • Each table has a unique table name that identifies its contents. Each column in a table has a column name, which is at the top of the column. • The columns of a table must all have different names. The data in each column is of the same type. • Each row of a table contains exactly one data value in each column. The rows in a table do not have any particular order. • A table can have any number of rows. A table of zero rows is called an empty table, which means it contains no data.
  • 5. Introduction to SQL Language • SQL is an abbreviation for Structured Query Language (pronounced "ess- que- el").SQL is used to communicate with a database meaning, it is a tool for organizing, managing, and retrieving data stored in a database. • According to ANSI (American National Standards Institute), it is the standard language for relational database management systems (RDBMS). • SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. • Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingress, Mysql, etc.
  • 6. • To allow access to the information in a database, SQL defines the reserved words (operations, functions and commands) of the language which indicates the actions to be performed on the database. • These words are described by Data Definition Language (DDL) and Data Manipulation Language (DML). • The DDL commands allow us to create and define new databases, fields and indexes while the DML commands let us build queries to sort, filter and extract data from the database
  • 7. DDL Commands • CREATE used to create new tables, fields and indexes. • DROP is used to delete tables and indexes from the databases. • ALTER is used to modify tables by adding fields or changing field definitions. DML Commands • SELECT is used to query the database. • INSERT is used to load data into the database. • UPDATE is used to change the values of particular records and fields. • DELETE is used to remove records from a database.
  • 8. Why choose MySQL? • 1. Speed. Developers claims it's the fastest (http//:www.mysql.com/benchmark.html) • 2. Ease of Use Simple administrations and installations • 3. Its free • 4. Query Language Support Supports SQL • 5. Capability • 6. Connectivity and Security Accessed from whereever you are and supports flixable access control • 7. Portability: Run on Linux, Unix, Solaris , FreeBSD ,Windows , etc • 8. Open source
  • 9. Mysql Installation •UseWamp server to install mysql server, we will use the wamp server to get phpmyadmin also. •You are done and ready to use the system!!
  • 10. Issuing Queries (General Queries) • Connect to database server either remotely or locally and type the following commands: mysql> SELECT NOW(); mysql> SELECT NOW (); mysql> SELECT NOW(),VERSION(); mysql> SHOW DATABASES; mysql> USE mysql; mysql> SHOWTABLES; mysql> DESCRIBE USER;
  • 11. Database related SQL (create a database ) To create a database : CREATE DATABASE db_name To delete a database and all the tables inside: DROP DATABASE db_name To list all the databases in the server : SHOW DATABASES To set the default database for the current session : USE db_name
  • 12. Create aTable This is an example of the CREATETABLE sql : CREATETABLE HeadOfState ( ID INT NOT NULL, LastName CHAR(30) NOT NULL, FirstName CHAR(30) NOT NULL );
  • 13. Note : We can examine the table structure using SHOW CREATETABLE tbl_name Which shows the CREATETABLE statement that creates the given table. Alternatively we can use the below statement to display more user friendly table description: DESCRIBE table_name To list all the tables in the current database: SHOWTABLES To drop a table and all its data: DROPTABLE table_name To display all the data in a table: SELECT * FROM table_name
  • 14. CreatingTables Based on ExistingTables MySQL provides two ways to create a table based on another table: CREATETABLE ... SELECT creates a table and populates it from the result set returned by an arbitrary SELECT statement. In this case, the "other table" is the set of rows and columns retrieved by the SELECT. CREATETABLE ... LIKE creates an empty table using the definition of another existing table. CREATETABLE ... SELECT can create a table that is empty or non-empty, depending on what is returned by the SELECT part.
  • 15. The result is a new table with a definition that includes all column attributes and indexes of the original table. Suppose that table t looks like this: CREATETABLE t (i INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (i)) ENGINE = MyISAM; The result of CREATE TABLE ... LIKE differs from the result of using CREATE TABLE ... SELECT to create an empty table. Either of the following statements will create an empty copy of the table t: mysql> CREATE TABLE copy1 SELECT * FROM t WHERE 0; mysql> CREATE TABLE copy2 LIKE t;
  • 16. However, the resulting copies differ in the amount of information retained from the original table structure: mysql> SHOW CREATETABLE copy1G; *************************** 1. row *************************** Table: copy1 Create Table: CREATETABLE ‘copy1 ‘ ( ‘i ‘ int(11) NOT NULL default '0' ) ENGINE=MyISAM DEFAULT CHARSET=latin1 mysql> SHOW CREATETABLE copy2G; *************************** 1. row *************************** Table: copy2 Create Table: CREATETABLE ‘copy2 ‘ ( ‘i ‘ int(11) NOT NULL auto_increment, PRIMARY KEY (i ‘) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
  • 17. Adding and Dropping Columns To add a new column to a table, use ALTERTABLE with an ADD clause that specifies the column's definition. A column definition uses the same syntax for ALTERTABLE as for CREATE TABLE. For example, to add a DATE column named Inauguration you can issue this statement: ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL; That ALTERTABLE statement changes the table structure as follows: mysql> DESCRIBE HeadOfState;
  • 18. To indicate that MySQL should place the new column in a specific position within the table, append either the keyword FIRST or the keyword-identifier combination AFTER column_name to the column definition. For example, assume that you had executed this ALTERTABLE statement instead of the previous one: ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL FIRST; The FIRST keyword tells ALTERTABLE to place the new column before all existing columns (in the "first" position), resulting in the following table structure: mysql> DESCRIBE HeadOfState;
  • 19. Using AFTER column_name tells ALTERTABLE to place the new column after a specific existing column. For example, to place the new Inauguration column after the existing FirstName column, you would issue this statement: ALTERTABLE HeadOfState ADD Inauguration DATE NOT NULL AFTER FirstName; That ALTERTABLE statement results in a table structure that looks like this: mysql> DESCRIBE HeadOfState;
  • 20. Column names within a table must be unique, so you cannot add a column with the same name as one that already exists in the table. Also, column names are not case sensitive, so if the table already contains a column named ID, you cannot add a new column using any of these names: ID, id, Id, or iD. They all are considered to be the same name. To drop a column, use a DROP clause that names the column to be removed: ALTERTABLE table_name DROP column_name;
  • 21. Modifying Existing Columns There are two ways to change the definition of an existing column within a table. One of these also enables you to rename the column. The first way to alter a column definition is to use a MODIFY clause. You must specify the name of the column that you want to change, followed by its new definition. Assume that you want to change the ID column's data type from INT to BIGINT, to allow the table to accommodate larger identification numbers. You also want to make the column UNSIGNED to disallow negative values. The following statement accomplishes this task: ALTERTABLE HeadOfState MODIFY ID BIGINT UNSIGNED NOT NULL; DESCRIBE or (DESC) now shows the table structure to be as follows: mysql> DESCRIBE HeadOfState;
  • 22. The second way to alter a column definition is to use a CHANGE clause. CHANGE enables you to modify both the column's definition and its name. To use this clause, specify the CHANGE keyword, followed by the column's existing name, its new name, and its new definition, in that order. Note that this means you must specify the existing name twice if you want to change only the column definition (and not the name). For example, to change the LastName column from CHAR(30) to CHAR(40) without renaming the column, you'd do this: ALTERTABLE HeadOfState CHANGE LastName LastName CHAR(40) NOT NULL; To change the name as well (for example, to Surname), provide the new name following the existing name: ALTERTABLE HeadOfState CHANGE LastName Surname CHAR(40) NOT NULL;
  • 23. Renaming aTable Renaming a table changes neither a table's structure nor its contents. The following statement renames table t1 to t2: ALTERTABLE t1 RENAMETO t2; Another way to rename a table is by using the RENAMETABLE statement: RENAMETABLE t1TO t2; RENAME TABLE has an advantage over ALTER TABLE in that it can perform multiple table renames in a single operation. One use for this feature is to swap the names of two tables: RENAMETABLE t1TO tmp, t2TO t1, tmpTO t2; For TEMPORARY tables, RENAMETABLE does not work.You must use ALTERTABLE instead. ALTERTABLE HeadOfState MODIFY ID BIGINT UNSIGNED NOT NULL;
  • 24. MySQL DataTypes Generally there are 3 categories of column type supported by MySQL which are : 1. NumericType 2. String (Character )Type 3. Date andTimeType
  • 25. Numeric ColumnType MySQL understands integers, floating points and scientific notations. Numbers can be preceded by a minus sign to indicate negative value. Following is the column type available (commonly used in MySQL). INT,TINYINT, SMALLINT, INT, FLOAT, DOUBLE, DECIMAL, Usage example: TINYINT[(M)] [UNSIGNED] [ZEROFILL] DOUBLE [(M,D)] [ZEROFILL]
  • 26. String ColumnTypes CHAR,VARCHAR,TINYBLOB,BLOB,MEDIUMBLOB,LONGBLOB,TINYTEXT,TEXT, MEDIUMTEXT,LONGTEXT,ENUM,SET example: nameVARCHAR(20) NOT NULL, In Numeric Column Type, the number inside the parenthesis indicates display number, but in over here it is not. It explicitly defined the length of the character. Only CHAR and VARCHAR s' length can be defined. Strings are actually a 'generic' type in a sense because it can be used to hold any values. VARCHAR and CHAR are the most common type. CHAR is fixed length type while the VARCHAR is variable length type. BLOB is a binary large object which can hold anything you throw into it. The variation indicates different maximum number of information can be stored. TEXT type is identical to BLOB, but different in the sense that BLOB is case sensitive while TEXT is case insensitive. (This matters when sorting and comparing is used).
  • 27. ENUM and SET • ENUM and SET are special type for which colomn values must be chosen from a fixed set of strings. • Difference is ENUM column values must have at least exactly one member of the set while SET may contain any or all members of the set.
  • 28. Date andTime ColumnType • DATE,TIME, DATETIME,TIMESTAMP,YEAR • Values of TIME type are elapsed time. A 12:30:00 means 12 hours, and 30 minutes and not 12.30 am which means that TIME can hold values like 50:13:00 but not 50:65:00 • If TIMESTAMP column is set to "NULL" then automatically it will be set to current time and date. • M inTIMEFORMAT indicates display formats
  • 29. Attributes A. Numeric ColumnType 1. AUTO_INCREMENT Indicates that the value is automatically increased by 1 from the previous value. For any column to be used as auto_increment must be declared as NOT NULL and PRIMARY KEY / UNIQUE KEY 2. UNSIGNED Disallows negative numbers B. String ColumnTypes 1. Binary Specified for CHAR or VARCHAR, which causes the column values to be treated as binary strings. 2. NULL or NOT NULL 3. DEFAULT To specify a default value for CHAR or VARCHAR only.
  • 30. Inserting into aTable The INSERT statement is used to insert or add a new row of data into a table, below we have the two forms of the insert statement: INSERT INTO table_name (column_list) VALUES (value_list); INSERT INTO table_name SET column_name = value [, column_name2 = value2] ... ; For any column not assigned an explicit value by an INSERT statement, MySQL sets it to its default value if it has one. For example, to have MySQL set the id column to its default, you can simply omit it from the statement.The following example shows statements using each INSERT syntax that assign no explicit id value: Examples : INSERT INTO people (name,age) VALUES('William',25); INSERT INTO people SET name = 'William', age = 25;
  • 32. Retrieving Non specific Data SELECT command is used to retrieve data from tables.The simplest retrieval is when you ask for all the data in a table. Following command retrieve all data from table named 'animal' SELECT * FROM animals This statement returns all the data in all the rows and columns of the table 'animals'. The asterisk (*) is a wildcard character means "all attributes ".
  • 33. Retrieving Specific Data SELECT command can be used to query the database and retrieve selected data that match the certain criteria. These is easily achieved by adding "WHERE" clause to the SELECT statement above. Here is the format of a simple select statement: SELECT "column1" [,"column2", etc] FROM tbl_name [where "condition"]; Example: SELECT * FROM animals WHERE gender='f' AND species='cat'; Expression in WHERE clause can use arithmetic operators, comparison operators and logical operators as below Arithmetic Operators+ :, - , * and / Comparison Operators= : , > , >= , ) =! <> ) , >= and > Logical Operator: AND, OR, NOT Others: BETWEEN, Like
  • 34. Specifying Which Rows to Retrieve If you specify no criteria for selecting records from a table, a SELECT statement retrieves every record in the table. This is often more information than you need, particularly for large tables. To be more specific about which rows are of interest, include a WHERE clause that describes the characteristics of those rows. • SELECT * FROM Country WHERE IndepYear > 1990; • SELECT * FROM Country WHERE Population >= 1000000 AND Population <= 2000000; • SELECT * FROM Country WHERE Population BETWEEN 1000000 AND 2000000;
  • 35. Using ORDER BY to Sort Query Results By default, the rows in the result set produced by a SELECT statement are returned by the server to the client in no particular order. If you require output rows to be returned in a specific order, include an ORDER BY clause that indicates how to sort the results. The examples in this section demonstrate ORDER BY: • SELECT id, last_name, first_name, birth FROM t ORDER BY birth; • SELECT id, last_name, first_name, birth FROM t ORDER BY last_name, first_name; • SELECT id, last_name, first_name, birth FROM t ORDER BY id DESC;
  • 36. Limiting a Selection Using LIMIT MySQL supports a LIMIT clause in SELECT statements, which tells the server to return only some of the rows selected by the statement. This is useful for retrieving records based on their position within the set of selected rows. LIMIT may be given with either one or two arguments: LIMIT row_count LIMIT skip_count, row_count SELECT * FROM Country LIMIT 10; SELECT * FROM Country LIMIT 20,10;
  • 37. Deleting Records To remove records from tables, use a DELETE statement or a trUNCATE TABLE statement. The DELETE statement allows a WHERE clause that identifies which records to remove, whereas TRUNCATETABLE always removes all records. DELETE therefore can be more precise in its effect. To empty a table entirely by deleting all its records, you can use either of the following statements: DELETE FROM table_name; TRUNCATETABLE table_name; To remove only specific records in a table, trUNCATE TABLE cannot be used. You must issue a DELETE statement that includes a WHERE clause that identifies which records to remove: DELETE FROM table_name WHERE ... ;
  • 38. Updating Records The UPDATE statement is used to update or change records that match specified criteria. This is accomplished by carefully constructing a where clause. UPDATE table_name SET column_name = value [, column_name = value] ... WHERE ... ;
  • 39. Using DISTINCT to Eliminate Duplicates If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list. Suppose that a query returns a result set that contains duplicated rows: mysql> SELECT last_name FROM t; Adding DISTINCT removes the duplicates and returns only unique rows: mysql> SELECT DISTINCT last_name FROM t;
  • 40. Aggregating Results A SELECT statement can produce a list of rows that match a given set of conditions. The list provides the details about the selected rows, but if you want to know about the overall characteristics of the rows, you'll be more interested in getting a summary instead. When that's your goal, use aggregate functions to calculate summary values, possibly combined with a GROUP BY clause to arrange the selected rows into groups so that you can get summaries for each group. Grouping can be based on the values in one or more columns of the selected rows.
  • 41. There are several types of aggregate functions.Those discussed here are as follows: • MIN() and MAX() find smallest and largest values. • SUM() and AVG() summarize numeric values to produce sums (totals) and averages. • COUNT() counts rows, values, or the number of distinct values.
  • 42. The MIN() and MAX() Aggregate Functions MIN() and MAX() are comparison functions. They return smallest or largest numeric values, lexically first or last string values, and earliest or latest temporal values. The following queries determine the smallest and largest country populations and the lexically first and last country names: mysql> SELECT MIN(Population), MAX(Population) FROM Country; mysql> SELECT MIN(Name), MAX(Name) FROM Country; MIN() and MAX() ignore NULL values.
  • 43. The SUM() and AVG() Aggregate Functions The SUM() and AVG() functions calculate sums and averages. For example, the Country table in the world database contains a Population column, so you can calculate the total world population and the average population per country like this: mysql> SELECT SUM(Population), AVG(Population) FROM Country; SUM() and AVG() ignore NULL values.
  • 44. COUNT() Aggregate Function The COUNT() function can be used in several ways to count either rows or values. To illustrate, the examples here use the following table that has several rows containing various combinations of NULL and non-NULL values: SELECT COUNT(i), COUNT(j) FROM t; COUNT(DISTINCT expression) counts the number of distinct (unique) non-NULL values of the given expression. expression can be a column name to count the number of distinct non-NULL values in the column: SELECT COUNT(DISTINCT i), COUNT(DISTINCT j) FROM t; SELECT COUNT(DISTINCT i, j) FROM t;
  • 45. Grouping Results If a query does not contain a GROUP BY clause to place rows of the result set into groups, an aggregate function produces a result that is based on all the selected rows. A GROUP BY clause may be added to generate a more fine-grained summary that produces values for subgroups within a set of selected rows. Adding a GROUP BY clause arranges rows using the values in the grouping column or columns.The result is that COUNT(*) produces a count for each group.To find out how many times each title occurs, do this: • SELECT title, COUNT(*) FROM personnel GROUP BY title; • SELECT dept_id, title, COUNT(*) FROM personnel GROUP BY dept_id, title;
  • 46. GROUP BY and Sorting In MySQL, a GROUP BY clause has the side effect of sorting rows. If you already have a GROUP BY clause in your query that produces the desired sort order, there's no need for an ORDER BY. Use of ORDER BY is necessary with GROUP BY only to produce a different sort order than that resulting from the GROUP BY. However, this isn't a portable behavior. For database engines other than MySQL, GROUP BY might not sort rows. To write more portable queries, add an ORDER BY even if MySQL does not require it.
  • 47. Selecting Groups with HAVING It could be when you use GROUP BY that you're interested only in groups that have particular summary characteristics. To retrieve just those groups and eliminate the rest, use a HAVING clause that identifies the required group characteristics. HAVING acts in a manner somewhat similar to WHERE, but occurs at a different stage of query processing: 1.WHERE, if present, identifies the initial set of records to select from a table. 2. GROUP BY arranges the selected records into groups. 3. Aggregate functions compute summary values for each group. 4. HAVING identifies which groups to retrieve for the final result set. mysql> SELECT title, salary, COUNT(*), AVG(salary) -> FROM personnel WHERE dept_id = 7 -> GROUP BY title -> HAVING COUNT(*)> 1;
  • 49. Joins • When it's necessary to draw on information that is stored in multiple tables, use a join— an operation that produces a result by combining (joining) information in one table with information in another. • A join between tables is an extension of a single-table SELECT statement, but involves the following additional complexities: • The FROM clause names all the tables needed to produce the query result, not just one table. • A join that matches records in one table with records in another must specify how to match up the records. These conditions often are given in the WHERE clause, but the particular syntax depends on the type of join. 1. SELECT Name, Language FROM CountryLanguage, Country WHERE CountryCode = Code; 2. SELECT Name, Language FROM Country INNER JOIN CountryLanguage ON Code = CountryCode;
  • 50. Outer Join • An inner join produces results by selecting combinations of matching rows from the joined tables. • However, it cannot find nonmatches; that is, instances where a row in one table has no match in another table. • An outer join finds matches (just like an inner join), but also identifies mismatches. • Furthermore, with an appropriate WHERE clause, an outer join can filter out matches to display only the mismatches. • Two common forms of outer joins are left joins and right joins. • These are written using the LEFT JOIN or RIGHT JOIN keywords rather than the comma operator or the INNER JOIN keywords.
  • 51. Outer Join • A left join is a type of outer join, written using the LEFT JOIN keywords. • A left join treats the left table (the first one named) as a reference table and produces output for each row selected from it, whether or not the row is matched by rows in the right table. • A LEFT JOIN is written using either ON or USING()after the table names in the FROM clause. • The example here uses the ON syntax: SELECT Name, Language FROM Country LEFT JOIN CountryLanguage ON Code = CountryCode; • In this query, the left table is the one named first (Country) and the right table is the one named second (CountryLanguage).
  • 52. Outer Join • A right join is another type of outer join, written using the RIGHT JOIN keywords. • Every right join corresponds to an equivalent left join. • The only difference is that the roles of the tables in a right join are reversed relative to the roles in a left join. • That is, the right table is the reference table, so a RIGHT JOIN produces a result for each row in the right table, whether or not it has any match in the left table.
  • 53. Updating and Deleting MultipleTables • MySQL allows the use of join syntax in UPDATE and DELETE statements to enable updates or deletes that involve multiple tables. • Some of the principles involved in writing joins in SELECT statements also apply to multiple-table UPDATE and DELETE statements. This section provides a brief overview of their syntax. • A multiple-table UPDATE is an extension of a single-table statement: • Following the UPDATE keyword, name the tables involved in the operation, separated by commas. (You must name all the tables used in the query, even if you aren’t updating all of them.) • In the WHERE clause, describe the conditions that determine how to match records in the tables. • In the SET clause, assign values to the columns to be updated. These assignments can refer to columns from any of the joined tables. UPDATE t1, t2 SET t1.name = t2.name WHERE t1.id = t2.id;
  • 54. Updating and Deleting MultipleTables • Multiple-table DELETE statements can be written in two formats. • The following example demonstrates one syntax, for a query that deletes rows from a table t1 where the id values match those in a table t2: DELETE t1 FROM t1, t2 WHERE t1.id = t2.id; • The second syntax is slightly different: DELETE FROM t1 USING t1, t2 WHERE t1.id = t2.id; • The ORDER BY and LIMIT clauses normally supported by UPDATE and DELETE aren’t allowed when these statements are used for multiple-table operations.
  • 55. SQL Expressions • Expressions are a common element of SQL statements, and they occur in many contexts. • For example, expressions often occur in the WHERE clause of SELECT, DELETE, or UPDATE statements to identify which records to retrieve, delete, or update. • But expressions may be used in many other places; for example, in the output column list of a SELECT statement, or in ORDER BY or GROUP BY clauses. • Expressions use different types of values like : Table columns, Literal values, or Functions.
  • 56. String Expressions • Literal strings in expressions are written as quoted values. • By default, either single quotes or double quotes can be used, although single quotes are more standard. • The data types for representing strings in tables include CHAR, VARCHAR, BINARY, VARBINARY, and the TEXT and BLOB types. • String concatenation is done with the CONCAT() function: SELECT CONCAT('abc','def'); +-----------------------------------+ | CONCAT('abc','def’) | +-----------------------------------+ | abcdef | +-----------------------------------+ • UPPER() and LOWER() functions perform case conversion only if the argument is a non-binary string. SELECT UPPER('AbCd'), LOWER('AbCd'); +---------------+---------------+ | UPPER('AbCd') | LOWER('AbCd') | +---------------+---------------+ | ABCD |abcd | +---------------+---------------+
  • 57. Using LIKE for Pattern Matching • Operators such as = and =! are useful for finding values that are equal to or not equal to a specific exact comparison value. • When it's necessary to find values based on similarity instead, a pattern match is useful. • To perform a pattern match, use value LIKE 'pattern', where value is the value you want to test and 'pattern' is a pattern string that describes the general form of values that you want to match. • Patterns used with the LIKE pattern-matching operator can contain two special characters (called "metacharacters" or "wildcards "( that stand for something other than themselves: • The '%' character matches any sequence of zero or more characters. • The '_' (underscore) character matches any single character. • To match a pattern metacharacter literally, escape it by preceding it by a backslash.
  • 58. Using LIKE for Pattern Matching SELECT 'AA' LIKE 'A%', 'AA' LIKE 'A%', 'A%' LIKE 'A%'; +-----------------+-----------------+----------------+ | 'AA' LIKE 'A%’ | 'AA' LIKE 'A%' | 'A%' LIKE 'A%'| +-----------------+-----------------+----------------+ | 1| 0| 1| +-----------------+-----------------+----------------+ mysql> SELECT 'AA' LIKE 'A_', 'AA' LIKE 'A_', 'A_' LIKE 'A_'; +-----------------+-----------------+----------------+ | 'AA' LIKE 'A_’ | 'AA' LIKE 'A_’ | 'A_' LIKE 'A_'| +-----------------+-----------------+----------------+ | 1| 0 | 1| +-----------------+-----------------+----------------+
  • 59. Foreign Key • InnoDB supports foreign key constraints. • The syntax for a foreign key constraint definition in the create table statement: [CONSTRAINT [symbol]] FOREIGN KEY (index_col_name, ...) REFERENCES tbl_name (index_col_name,...) [ON DELETE reference_option] [ON UPDATE reference_option] reference_option: RESTRICT | CASCADE | SET NULL | NO ACTION
  • 60. Foreign Key Conditions 1. Both tables must be InnoDB tables and they must not be TEMPORARY tables. 2. Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same. 3. InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. 4. InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order. 5. If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.
  • 61. Foreign Key • nnoDB rejects any INSERT or UPDATE operation that attempts to create a foreign key value in a child table if there is no a matching candidate key value in the parent table. • The action InnoDB takes for any UPDATE or DELETE operation that attempts to update or delete a candidate key value in the parent table that has some matching rows in the child table is dependent on the referential action specified using ON UPDATE and ON DELETE subclauses. • InnoDB supports four options regarding the action to be taken. If ON DELETE or ON UPDATE are not specified, the default action is RESTRICT. 1. CASCADE: Delete or update the row from the parent table and automatically delete or update the matching rows in the child table. 2. SET NULL: Delete or update the row from the parent table and set the foreign key column or columns in the child table to NULL. 3. NO ACTION, RESTRICT: Attempt to delete or update a primary key value is not permitted to proceed if there is a related foreign key value in the referenced table.
  • 62. Foreign Key Example • Here is a simple example that relates parent and child tables through a single-column foreign key: CREATE TABLE parent (id INT NOT NULL, PRIMARY KEY (id)) ENGINE=INNODB; CREATE TABLE child (id INT, parent_id INT, INDEX par_ind (parent_id), FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE) ENGINE=INNODB;
  • 63. MySQLTransactions • A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. • In other words, a transaction will never be complete unless each individual operation within the group is successful. • If any operation within the transaction fails, the entire transaction will fail. • Two keywords Commit and Rollback are mainly used for MySQL Transactions. • When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect. • If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state.
  • 64. MySQLTransactions Example 1. Begin transaction by issuing SQL command BEGIN WORK 2. Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE 3. Check if there is no error and everything is according to your requirement. 4. If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
  • 65. Views • A view is a database object that is defined in terms of a SELECT statement that retrieves the data you want the view to produce. • A view can be used to select from regular tables (called "base tables “) or other views. • In some cases, a view is updatable and can be used with statements such as UPDATE, DELETE, or INSERT to modify an underlying base table. • To define a view, use the CREATE VIEW statement, which has this syntax: CREATE [OR REPLACE] [ALGORITHM = algorithm_type] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION]
  • 66. Views • view_name is the name to give the view. • select_statement is a SELECT statement that indicates how to retrieve data when the view is used. The statement can select from base tables or other views. • The OR REPLACE clause causes any existing view with same name as the new one to be dropped prior to creation of the new view. • The ALGORITHM clause specifies the processing algorithm to use when the view is invoked. • column_list provides names for the view columns to override the default names. • When the WITH CHECK OPTION clause is included in a view definition, all data changes made to the view are checked to ensure that the new or updated rows satisfy the view- defining condition. If the condition is not satisfied, the change is not accepted, either in the view or in the underlying base table.
  • 67. Views • The following CREATE VIEW statement defines a simple view named CityView that selects the ID and Name columns from the City table. The SELECT statement shows an example of how to retrieve from the view: CREATE VIEW CityView AS SELECT ID, Name FROM City; SELECT * FROM CityView; +-----------------------------------+ | ID | Name | +-----------------------------------+ | 1 | Kabul | | 2 | Qandahar | | 3 | Herat | | 4 | Mazar-e-Sharif | ... • Views and base tables share the same namespace, so CREATE VIEW results in an error if a base table or view with the given name already exists.