0% found this document useful (0 votes)
4 views178 pages

Outline

The document outlines key concepts in database systems, focusing on SQL join operations, including inner, left, right, and full outer joins. It provides syntax examples and descriptions of how these joins work to combine data from multiple tables based on related columns. Additionally, it briefly mentions MySQL string and numeric functions used for data manipulation.

Uploaded by

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

Outline

The document outlines key concepts in database systems, focusing on SQL join operations, including inner, left, right, and full outer joins. It provides syntax examples and descriptions of how these joins work to combine data from multiple tables based on related columns. Additionally, it briefly mentions MySQL string and numeric functions used for data manipulation.

Uploaded by

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

Outline

 Join Expressions
 Views
 Transactions
 Integrity Constraints
 SQL Data Types and Schemas
 Index Definition in SQL
 Authorization

Database System Concepts - 7th Edition 4.1 ©Silberschatz, Korth and Sudarshan
Joined Relations

 Join operations take two relations and return as a result another


relation.
 A join operation is a Cartesian product which requires that tuples in the
two relations match (under some condition). It also specifies the
attributes that are present in the result of the join
 The join operations are typically used as subquery expressions in the
from clause
 Three types of joins:
 Natural join
 Inner join
 Outer join

Database System Concepts - 7th Edition 4.2 ©Silberschatz, Korth and Sudarshan
JOINS

OrderID CustomerID OrderDate


10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
CustomerI
Let's look atCustomerName ContactName
a selection from the "Orders" table: Country
D
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Ana Trujillo Mexico
Emparedados y
helados

3 Antonio Moreno Antonio Moreno Mexico


Taquería

Database System Concepts - 7th Edition 4.3 ©Silberschatz, Korth and Sudarshan
Inner join

 SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996


10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996

10278 Berglunds snabbköp 8/12/1996

Database System Concepts - 7th Edition 4.4 ©Silberschatz, Korth and Sudarshan
joins
Different Types of SQL JOINs
Here are the different types of the JOINs in SQL:
•(INNER) JOIN: Returns records that have matching values in both tables
•LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the
right table
•RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from
the left table
•FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

Database System Concepts - 7th Edition 4.5 ©Silberschatz, Korth and Sudarshan
Inner join
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in
both tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

Database System Concepts - 7th Edition 4.6 ©Silberschatz, Korth and Sudarshan
Inner join

Customer Customer ContactN Address City PostalCo Country


ID Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e
2 Ana Ana Avda. de México 05021 Mexico
Trujillo Trujillo la D.F.
Empared Constituc
ados y ión 2222
helados

3 Antonio Antonio Matadero México 05023 Mexico


Moreno Moreno s 2312 D.F.
Taquería
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID =
Customers.CustomerID;

Database System Concepts - 7th Edition 4.7 ©Silberschatz, Korth and Sudarshan
joins
Number of Records: 196

OrderID CustomerName

10248 Wilman Kala

10249 Tradição Hipermercados

10250 Hanari Carnes

10251 Victuailles en stock

10252 Suprêmes délices

10253 Hanari Carnes

10254 Chop-suey Chinese

10255 Richter Supermarkt

Database System Concepts - 7th Edition 4.8 ©Silberschatz, Korth and Sudarshan
Left join

SQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2).
The result is 0 records from the right side, if there is no match.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN

Database System Concepts - 7th Edition 4.9 ©Silberschatz, Korth and Sudarshan
joins

Customer Customer ContactN Address City PostalCo Country


ID Name ame de
1 Alfreds Maria Obere Str. Berlin 12209 Germany
Futterkist Anders 57
e
2 Ana Ana Avda. de México 05021 Mexico
Trujillo Trujillo la D.F.
Empared Constituci
ados y ón 2222
helados
3 Antonio Antonio Matadero México 05023 Mexico
Moreno Moreno s 2312 D.F.
Taquería

Database System Concepts - 7th Edition 4.10 ©Silberschatz, Korth and Sudarshan
joins
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID =
Orders.CustomerID
ORDER BY Customers.CustomerName;
Try it Yourse

lf »Note: The LEFT JOIN keyword returns all records from the left table (Customers), even if there are no
matches in the right table (Orders).

Database System Concepts - 7th Edition 4.11 ©Silberschatz, Korth and Sudarshan
Number of Records: 213
CustomerName OrderID
Alfreds Futterkiste null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10355
Around the Horn 10383
B's Beverages 10289
Berglunds snabbköp 10278
Berglunds snabbköp 10280
Berglunds snabbköp 10384
Blauer See Delikatessen null

Database System Concepts - 7th Edition 4.12 ©Silberschatz, Korth and Sudarshan
Right join

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

Note: In some databases RIGHT JOIN is called RIGHT OUTER


JOIN.

The RIGHT JOIN keyword returns all records from the right table (table2),
and the matching records from the left table (table1).
The result is 0 records from the left side, if there is no match.

Database System Concepts - 7th Edition 4.13 ©Silberschatz, Korth and Sudarshan
joins

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

EmployeeID LastName FirstName BirthDate Photo


1 Davolio Nancy 12/8/1968 EmpID1.pic
2 Fuller Andrew 2/19/1952 EmpID2.pic
3 Leverling Janet 8/30/1963 EmpID3.pic
SELECT Orders.OrderID, Employees.LastName,
Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID
ORDER BY Orders.OrderID;
Try it Yourself
Database System Concepts - 7th Edition 4.14 ©Silberschatz, Korth and Sudarshan
Number of Records: 197

OrderID LastName FirstName

West Adam

10248 Buchanan Steven

10249 Suyama Michael

10250 Peacock Margaret

10251 Leverling Janet

10252 Peacock Margaret

10253 Leverling Janet

10254 Buchanan Steven

Database System Concepts - 7th Edition 4.15 ©Silberschatz, Korth and Sudarshan
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in
left (table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Database System Concepts - 7th Edition 4.16 ©Silberschatz, Korth and Sudarshan
joins
Customer Customer ContactN Address City PostalCo Country
ID Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e
2 Ana Ana Avda. de México 05021 Mexico
Trujillo Trujillo la D.F.
Empared Constituc
ados y ión 2222
helados
3 Antonio Antonio Matadero México 05023 Mexico
Moreno Moreno s 2312 D.F.
Taquería

OrderID CustomerID EmployeeID OrderDate ShipperID


10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2

Database System Concepts - 7th Edition 4.17 ©Silberschatz, Korth and Sudarshan
joins

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
A selection from the result set may look like this:
Note: The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, 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“.

CustomerName OrderID
Null 10309
Null 10310
Alfreds Futterkiste Null
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería Null
Database System Concepts - 7th Edition 4.18 ©Silberschatz, Korth and Sudarshan
MySQL String Functions
Function Description
ASCII Returns the ASCII value for the specific character
CHAR_LENGTH Returns the length of a string (in characters)
CHARACTER_LENGT Returns the length of a string (in characters)
H
CONCAT Adds two or more expressions together
CONCAT_WS Adds two or more expressions together with a separator
FIELD Returns the index position of a value in a list of values
FIND_IN_SET Returns the position of a string within a list of strings
FORMAT Formats a number to a format like "#,###,###.##", rounded to a specified
number of decimal places
INSERT Inserts a string within a string at the specified position and for a certain
number of characters
INSTR Returns the position of the first occurrence of a string in another string

LCASE Converts a string to lower-case


LEFT Extracts a number of characters from a string (starting from left)

LENGTH Returns the length of a string (in bytes)


LOCATE Returns the position of the first occurrence of a substring in a string

LOWER Converts a string to lower-case

Database System Concepts - 7th Edition 4.19 ©Silberschatz, Korth and Sudarshan
LPAD Left-pads a string with another string, to a certain length
LTRIM Removes leading spaces from a string
MID Extracts a substring from a string (starting at any position)
POSITION Returns the position of the first occurrence of a substring in a string
REPEAT Repeats a string as many times as specified
REPLACE Replaces all occurrences of a substring within a string, with a new substring

REVERSE Reverses a string and returns the result


RIGHT Extracts a number of characters from a string (starting from right)
RPAD Right-pads a string with another string, to a certain length
RTRIM Removes trailing spaces from a string
SPACE Returns a string of the specified number of space characters
STRCMP Compares two strings
SUBSTR Extracts a substring from a string (starting at any position)
SUBSTRING Extracts a substring from a string (starting at any position)
SUBSTRING_INDE Returns a substring of a string before a specified number of delimiter occurs
X
TRIM Removes leading and trailing spaces from a string
UCASE Converts a string to upper-case
UPPER Converts a string to upper-case

Database System Concepts - 7th Edition 4.20 ©Silberschatz, Korth and Sudarshan
MySQL Numeric Functions
Function Description
ABS Returns the absolute value of a number
ACOS Returns the arc cosine of a number
ASIN Returns the arc sine of a number
ATAN Returns the arc tangent of one or two numbers
ATAN2 Returns the arc tangent of two numbers
AVG Returns the average value of an expression
CEIL Returns the smallest integer value that is >= to a number
CEILING Returns the smallest integer value that is >= to a number
COS Returns the cosine of a number
COT Returns the cotangent of a number
COUNT Returns the number of records returned by a select query
DEGREES Converts a value in radians to degrees
DIV Used for integer division
EXP Returns e raised to the power of a specified number
FLOOR Returns the largest integer value that is <= to a number
GREATEST Returns the greatest value of the list of arguments
LEAST Returns the smallest value of the list of arguments
LN Returns the natural logarithm of a number
LOG Returns the natural logarithm of a number, or the logarithm of a number to a specified base

LOG10 Returns the natural logarithm of a number to base 10


LOG2 Returns the natural logarithm of a number to base 2
MAX Returns the maximum value in a set of values
MIN Returns the minimum value in a set of values
MOD Returns the remainder of a number divided by another number

Database System Concepts - 7th Edition 4.21 ©Silberschatz, Korth and Sudarshan
PI Returns the value of PI

POW Returns the value of a number raised to the


power of another number

POWER Returns the value of a number raised to the


power of another number

RADIANS Converts a degree value into radians

RAND Returns a random number

ROUND Rounds a number to a specified number of


decimal places

SIGN Returns the sign of a number

SIN Returns the sine of a number

SQRT Returns the square root of a number

SUM Calculates the sum of a set of values

TAN Returns the tangent of a number

TRUNCATE Truncates a number to the specified


number of decimal places

Database System Concepts - 7th Edition 4.22 ©Silberschatz, Korth and Sudarshan
MySQL Date Functions
ADDDATE Adds a time/date interval to a date and then returns the
date
ADDTIME Adds a time interval to a time/datetime and then returns
the time/datetime
CURDATE Returns the current date
CURRENT_DATE Returns the current date
CURRENT_TIME Returns the current time
CURRENT_TIMESTAMP Returns the current date and time
CURTIME Returns the current time
DATE Extracts the date part from a datetime expression

DATEDIFF Returns the number of days between two date values

DATE_ADD Adds a time/date interval to a date and then returns the


date
DATE_FORMAT Formats a date
DATE_SUB Subtracts a time/date interval from a date and then
returns the date
DAY Returns the day of the month for a given date

DAYNAME Returns the weekday name for a given date

DAYOFMONTH Returns the day of the month for a given date

Database System Concepts - 7th Edition 4.23 ©Silberschatz, Korth and Sudarshan
DAYOFWEEK Returns the weekday index for a given date
DAYOFYEAR Returns the day of the year for a given date
EXTRACT Extracts a part from a given date
FROM_DAYS Returns a date from a numeric datevalue
HOUR Returns the hour part for a given date
LAST_DAY Extracts the last day of the month for a given date
LOCALTIME Returns the current date and time
LOCALTIMESTAMP Returns the current date and time
MAKEDATE Creates and returns a date based on a year and a number
of days value
MAKETIME Creates and returns a time based on an hour, minute, and
second value
MICROSECOND Returns the microsecond part of a time/datetime
MINUTE Returns the minute part of a time/datetime
MONTH Returns the month part for a given date
MONTHNAME Returns the name of the month for a given date
NOW Returns the current date and time
PERIOD_ADD Adds a specified number of months to a period
PERIOD_DIFF Returns the difference between two periods
QUARTER Returns the quarter of the year for a given date value
SECOND Returns the seconds part of a time/datetime
Database System Concepts - 7th Edition 4.24 ©Silberschatz, Korth and Sudarshan
SECOND Returns the seconds part of a time/datetime

SEC_TO_TIME Returns a time value based on the specified seconds

STR_TO_DATE Returns a date based on a string and a format

SUBDATE Subtracts a time/date interval from a date and then returns the date

SUBTIME Subtracts a time interval from a datetime and then returns the
time/datetime

SYSDATE Returns the current date and time


TIME Extracts the time part from a given time/datetime

TIME_FORMAT Formats a time by a specified format


TIME_TO_SEC Converts a time value into seconds
TIMEDIFF Returns the difference between two time/datetime expressions

TIMESTAMP Returns a datetime value based on a date or datetime value

TO_DAYS Returns the number of days between a date and date "0000-00-00"

WEEK Returns the week number for a given date

WEEKDAY Returns the weekday number for a given date

WEEKOFYEAR Returns the week number for a given date

YEAR Returns the year part for a given date


YEARWEEK Returns the year and week number for a given date

Database System Concepts - 7th Edition 4.25 ©Silberschatz, Korth and Sudarshan
MySQL Advanced Functions
Function Description
BIN Returns a binary representation of a number
BINARY Converts a value to a binary string
CASE Goes through conditions and return a value when the first condition is met

CAST Converts a value (of any type) into a specified datatype


COALESCE Returns the first non-null value in a list
CONNECTION_ID Returns the unique connection ID for the current connection

CONV Converts a number from one numeric base system to another

CONVERT Converts a value into the specified datatype or character set

CURRENT_USER Returns the user name and host name for the MySQL account that the server used
to authenticate the current client

DATABASE Returns the name of the current database


IF Returns a value if a condition is TRUE, or another value if a condition is FALSE

IFNULL Return a specified value if the expression is NULL, otherwise return the expression

ISNULL Returns 1 or 0 depending on whether an expression is NULL

Database System Concepts - 7th Edition 4.26 ©Silberschatz, Korth and Sudarshan
LAST_INSERT_ID Returns the AUTO_INCREMENT id of
the last row that has been inserted or
updated in a table
NULLIF Compares two expressions and
returns NULL if they are equal.
Otherwise, the first expression is
returned

SESSION_USER Returns the current MySQL user name


and host name
SYSTEM_USER Returns the current MySQL user name
and host name
USER Returns the current MySQL user name
and host name
VERSION Returns the current version of the
MySQL database

Database System Concepts - 7th Edition 4.27 ©Silberschatz, Korth and Sudarshan
 SELECT CHAR_LENGTH("SQL Tutorial") AS LengthOfString;
LengthOfString
12

SELECT CHARACTER_LENGTH("SQL Tutorial") AS LengthOfString;

LengthOfString
12

SELECT CONCAT("SQL ", "Tutorial ", "is ", "fun!") AS ConcatenatedString;


ConcatenatedString
SQL Tutorial is fun!

SELECT STRCMP("SQL Tutorial", "SQL Tutorial");


STRCMP("SQL Tutorial", "SQL Tutorial")
0
SELECT SUBSTRING("SQL Tutorial", 5, 3) AS ExtractString;
ExtractString
Tut
Database System Concepts - 7th Edition 4.28 ©Silberschatz, Korth and Sudarshan
MySQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows,
like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG())
to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Database System Concepts - 7th Edition 4.29 ©Silberschatz, Korth and Sudarshan
CustomerID CustomerNa ContactNam Address City PostalCode Country
me e

1 Alfreds Maria Obere Str. Berlin 12209 Germany


Futterkiste Anders 57

2 Ana Trujillo Ana Trujillo Avda. de la México D.F. 05021 Mexico


Emparedado Constitución
s y helados 2222

3 Antonio Antonio Mataderos México D.F. 05023 Mexico


Moreno Moreno 2312
Taquería

4 Around the Thomas 120 Hanover London WA1 1DP UK


Horn Hardy Sq.

5 Berglunds Christina Berguvsväg Luleå S-958 22 Sweden


snabbköp Berglund en 8

Database System Concepts - 7th Edition 4.30 ©Silberschatz, Korth and Sudarshan
 SQL statement lists the number of customers in each country:
 SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
 SQL statement lists the number of customers in each country, sorted high
to low:
 SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

Database System Concepts - 7th Edition 4.31 ©Silberschatz, Korth and Sudarshan
COUNT(CustomerID) Country
3 Argentina
2 Austria
2 Belgium
9 Brazil
3 Canada
2 Denmark
2 Finland
11 France

COUNT(CustomerID) Country
13 USA
11 France
11 Germany
9 Brazil
7 UK
5 Spain
Database System Concepts - 7th Edition 4.32 ©Silberschatz, Korth and Sudarshan
MySQL HAVING Clause

The MySQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Database System Concepts - 7th Edition 4.33 ©Silberschatz, Korth and Sudarshan
Custome Customer ContactN Address City PostalCo Country
rID Name ame de

1 Alfreds Maria Obere Str. Berlin 12209 Germany


Futterkist Anders 57
e

2 Ana Ana Avda. de México 05021 Mexico


Trujillo Trujillo la D.F.
Empared Constituci
ados y ón 2222
helados

3 Antonio Antonio Matadero México 05023 Mexico


Moreno Moreno s 2312 D.F.
Taquería

4 Around Thomas 120 London WA1 1DP UK


the Horn Hardy Hanover
Sq.

5 Berglunds Christina Berguvsv Luleå S-958 22 Sweden


snabbköp Berglund ägen 8

Database System Concepts - 7th Edition 4.34 ©Silberschatz, Korth and Sudarshan
 MySQL HAVING clause
 The following SQL statement lists the number of customers in each
country. Only include countries with more than 5 customers:
 SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

 The following SQL statement lists the number of customers in each


country, sorted high to low (Only include countries with more than 5
customers):

 SELECT COUNT(CustomerID), Country


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

Database System Concepts - 7th Edition 4.35 ©Silberschatz, Korth and Sudarshan
COUNT(CustomerID) Country
9 Brazil
11 France
11 Germany
7 UK
13 USA

COUNT(CustomerID) Country
13 USA
11 Germany
11 France
9 Brazil
7 UK

Database System Concepts - 7th Edition 4.36 ©Silberschatz, Korth and Sudarshan
SQL - Sub Queries
 A Subquery or Inner query or a Nested query is a query within another
SQL query and embedded within clauses, most commonly in the WHERE
clause. It is used to return data from a table, and this data will be used in
the main query as a condition to further restrict the data to be retrieved.
 Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, <, >, >=, <=, IN,
BETWEEN, etc.
 There are a few rules that subqueries must follow −
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its
selected columns.
 An ORDER BY command cannot be used in a subquery, although the main
query can use an ORDER BY. The GROUP BY command can be used to
perform the same function as the ORDER BY in a subquery.
 Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.

Database System Concepts - 7th Edition 4.37 ©Silberschatz, Korth and Sudarshan
COMMIT
 Transaction Control Language(TCL) commands are used to manage
transactions in the database.

COMMIT command
COMMIT command is used to permanently save any transaction into the
database.
When we use any DML command like INSERT, UPDATE or DELETE, the
changes made by these commands are not permanent,
until the current session is closed, the changes made by these commands can be
rolled back.
To avoid that, we use the COMMIT command to mark the changes as
permanent.
Commit command syntax is COMMIT;

Database System Concepts - 7th Edition 4.38 ©Silberschatz, Korth and Sudarshan
ROLLBACK

ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT
command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database,
and realise that those changes were not required, then we can use
the ROLLBACK command to
rollback those changes, if they were not commited using the COMMIT command.

ROLLBACK TO savepoint_name;

SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you
can rollback to that point whenever required.

SAVEPOINT savepoint_name;

Database System Concepts - 7th Edition 4.39 ©Silberschatz, Korth and Sudarshan
TCL

id name
1 Abhi
2 Adam
4 Alex

Database System Concepts - 7th Edition 4.40 ©Silberschatz, Korth and Sudarshan
 INSERT INTO class VALUES(5, 'Rahul');
 COMMIT;
 UPDATE class SET name = 'Abhijit' WHERE id = '5';
 SAVEPOINT A;
 INSERT INTO class VALUES(6, 'Chris');
 SAVEPOINT B;
 INSERT INTO class VALUES(7, 'Bravo');
 SAVEPOINT C;
 SELECT * FROM class;

Database System Concepts - 7th Edition 4.41 ©Silberschatz, Korth and Sudarshan
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo

ROLLBACK TO B;

SELECT * FROM class;

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6
Database System Concepts - 7th Edition
Chris
4.42 ©Silberschatz, Korth and Sudarshan
 ROLLBACK TO A;

 SELECT * FROM class;

id name
1 Abhi
2 Adam
4 Alex
5 Abhijit

Database System Concepts - 7th Edition 4.43 ©Silberschatz, Korth and Sudarshan
DML,DDL,DCL,TCL COMMANDS
DML COMMANDS- INSERT, UPDATE, DELETE COMMANDS
TCL COMMANDS- COMMIT, ROLL BACK AND SAVEPOINT COMMANDS
DDL COMMANDS- CREATE,ALTER,TRUNCATE, ALTER, RENAME
DCL COMMANDS- SELECT, WHERE CLAUSE,LIKE CLAUSE, ORDER BY
CLAUSE, GROUP BY CLAUSE, HAVING CLAUSE
 Data Manipulation Language (DML) statements are used for managing
data in database. DML commands are not auto-committed. It means
changes made by DML command are not permanent to database, it can be
rolled back.

INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
INSERT INTO table_name VALUES(data1, data2, ...)

Database System Concepts - 7th Edition 4.44 ©Silberschatz, Korth and Sudarshan
DML
s_id name age
The above command will insert a new record into student table.

Consider a table student with the following fields.


INSERT INTO student VALUES(101, 'Adam', 15);

s_id name age


101 Adam 15
Insert value into only specific columns
We can use the INSERT command to insert values for only some specific
columns of a row. We can specify the column names along with the values
to be inserted like this,
INSERT INTO student(id, name) values(102, 'Alex');

Database System Concepts - 7th Edition 4.45 ©Silberschatz, Korth and Sudarshan
DML

UPDATE command is used to update any record of data in a table. Following is


its general syntax,
UPDATE table_name SET column_name = new_value WHERE
some_condition;

WHERE is used to add a condition to any SQL query .

 DELETE COMMAND IS USED TO DELETE RECORDS FROM THE


TABLE.
 DELETE FROM TABLE_NAME;

DELETE FROM student WHERE s_id=103;

Database System Concepts - 7th Edition 4.46 ©Silberschatz, Korth and Sudarshan
DDL
 Creating a Database
 To create a database in RDBMS, create command is used.
 CREATE DATABASE <DB_NAME>;

CREATE DATABASE Test;

CREATE TABLE <TABLE_NAME>


(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);
ALTER Command: Add a new Column
Using ALTER command we can add a column to any
existing table. Following is the syntax,

ALTER TABLE table_name ADD( column_name datatype);

Database System Concepts - 7th Edition 4.47 ©Silberschatz, Korth and Sudarshan
DDL
 ALTER TABLE student ADD(
 address VARCHAR(200)
 );
 MULTIPLE VALUES
 ALTER TABLE table_name ADD(
 column_name1 datatype1,
 column-name2 datatype2,
 column-name3 datatype3);
 ALTER TABLE student ADD(
 father_name VARCHAR(60),
 mother_name VARCHAR(60),
 dob DATE);
 DEFAULT VALUES
 ALTER TABLE table_name ADD(
 column-name1 datatype1 DEFAULT some_value
 );

Database System Concepts - 7th Edition 4.48 ©Silberschatz, Korth and Sudarshan
DDL

 ALTER TABLE student ADD(dob DATE DEFAULT '01-Jan-99);’


 MODIFYING EXISTING TABLE
ALTER TABLE table_name modify(column_name datatype);
ALTER TABLE student MODIFY(address varchar(300));
RENAME A COLUMN
ALTER TABLE table_name RENAME old_column_name TO
new_column_name;
 ALTER TABLE student RENAME address TO location;
 DROP A COLUMN
 ALTER TABLE table_name DROP( column_name);
 ALTER TABLE student DROP(address);

Database System Concepts - 7th Edition 4.49 ©Silberschatz, Korth and Sudarshan
DDL
TRUNCATE command
TRUNCATE command removes all the records
from a table. But this command will not destroy
the table's structure.
TRUNCATE TABLE table_name
TRUNCATE TABLE student;
DROP TABLE table_name
DROP TABLE student;

DROP DATABASE Test;


RENAME TABLE old_table_name to
new_table_name

RENAME TABLE student to students_info;

Database System Concepts - 7th Edition 4.50 ©Silberschatz, Korth and Sudarshan
CONSTRAINTS
 SQL constraints are used to specify rules for data in a table.
Create Constraints
Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER TABLE statement.

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

Database System Concepts - 7th Edition 4.51 ©Silberschatz, Korth and Sudarshan
MySQL Constraints
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table.
This ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
•NOT NULL - Ensures that a column cannot have a NULL value
•UNIQUE - Ensures that all values in a column are different
•PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
•FOREIGN KEY - Prevents actions that would destroy links between tables
•CHECK - Ensures that the values in a column satisfies a specific condition
•DEFAULT - Sets a default value for a column if no value is specified
•CREATE INDEX - Used to create and retrieve data from the database very quickly

Database System Concepts - 7th Edition 4.52 ©Silberschatz, Korth and Sudarshan
constraints
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record,
or update a record without adding a value to this field.

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
ALTER TABLE Persons
MODIFY Age int NOT NULL;

Database System Concepts - 7th Edition 4.53 ©Silberschatz, Korth and Sudarshan
constraints
MySQL UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are
different.
Both the UNIQUE and PRIMARY KEY constraints provide a
guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but
only one PRIMARY KEY constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons"
table is created:

Database System Concepts - 7th Edition 4.54 ©Silberschatz, Korth and Sudarshan
constraints
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE (ID)
);
 Multiple columns
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT UC_Person UNIQUE (ID,LastName)
);

Database System Concepts - 7th Edition 4.55 ©Silberschatz, Korth and Sudarshan
constraints
UNIQUE Constraint on ALTER
TABLE
To create
ALTER a UNIQUE
TABLE constraint on the "ID" column when the table is already
Persons
created, use the
ADD UNIQUE following SQL:
(ID);

To name a UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the following SQL
syntax:

ALTER TABLE Persons


ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);

DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL

ALTER TABLE Persons


DROP INDEX UC_Person;

Database System Concepts - 7th Edition 4.56 ©Silberschatz, Korth and Sudarshan
constraints

MySQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist
of single or multiple columns (fields).

PRIMARY KEY on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Database System Concepts - 7th Edition 4.57 ©Silberschatz, Korth and Sudarshan
constraints
PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is
already created, use the following SQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple
columns,
use the following SQL syntax:
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:

ALTER TABLE Persons


DROP PRIMARY KEY;

Database System Concepts - 7th Edition 4.58 ©Silberschatz, Korth and Sudarshan
constraints

MySQL FOREIGN KEY Constraint


The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.

FOREIGN KEY on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons
(PersonID)
);

Database System Concepts - 7th Edition 4.59 ©Silberschatz, Korth and Sudarshan
constraints
 CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
FOREIGN KEY on ALTER TABLE
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created,
use the following SQL:

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(Perso
nID);
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use
the following SQL syntax:

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

Database System Concepts - 7th Edition 4.60 ©Silberschatz, Korth and Sudarshan
constraints

DROP a FOREIGN KEY


Constraint
ALTER
To drop TABLE Orders
a FOREIGN KEY constraint, use the following SQL:
DROP FOREIGN KEY FK_PersonOrder;
MySQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in
other columns in the row.
SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created.
The CHECK constraint ensures that the age of a person must be 18, or older:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

Database System Concepts - 7th Edition 4.61 ©Silberschatz, Korth and Sudarshan
constraints
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following SQL syntax:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sands')
);
CHECK on ALTER TABLE
To create a CHECK constraint on the "Age" column when the table is already created, use the following SQL:

ALTER TABLE Persons


ADD CHECK (Age>=18);
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns,
use the following SQL syntax:

ALTER TABLE Persons


ADD CONSTRAINT CHK_PersonAge CHECK (Ag
e>=18 AND City='Sandnes');

Database System Concepts - 7th Edition 4.62 ©Silberschatz, Korth and Sudarshan
constraints
DROP a CHECK Constraint
To drop a CHECK constraint, use the following SQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;

MySQL DEFAULT Constraint


The DEFAULT constraint is used to set a default value for a column.
The default value will be added to all new records, if no other value is specified.

DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

Database System Concepts - 7th Edition 4.63 ©Silberschatz, Korth and Sudarshan
 CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT CURRENT_DATE()
);

DEFAULT on ALTER TABLE


To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';

DROP a DEFAULT Constraint


To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;

Database System Concepts - 7th Edition 4.64 ©Silberschatz, Korth and Sudarshan
constraints

 SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation
 Types of SQL Constraints
 NOT NULL Constraint.
 UNIQUE Constraint.
 DEFAULT Constraint.
 CHECK Constraint.
 PRIMARY KEY Constraint.
 FOREIGN KEY Constraint.
 between the constraint and the data action, the action is aborted.

Database System Concepts - 7th Edition 4.65 ©Silberschatz, Korth and Sudarshan
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.
 Views are virtual tables that can be a great way to optimize your database
experience. Not only are views good for defining a table without using
extra storage, but they also accelerate data analysis and can provide your
data extra security.

Database System Concepts - 7th Edition 4.66 ©Silberschatz, Korth and Sudarshan
VIEWS
MySQL CREATE VIEW Statement
InSQL, 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 statements and functions to a view and present the data as if the data were
coming from one single table.
A view is created with the CREATE VIEW statement.

CREATE VIEW view_name AS


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

CREATE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';

SELECT * FROM [Brazil Customers];

Database System Concepts - 7th Edition 4.67 ©Silberschatz, Korth and Sudarshan
views
 SQL creates a view that selects every product in the "Products" table with
a price higher than the average price:
 CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
 query the view
 SELECT * FROM [Products Above Average Price];
 MySQL Updating a View

A view can be updated with the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW view_name AS


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

Database System Concepts - 7th Edition 4.68 ©Silberschatz, Korth and Sudarshan
views
 SQL adds the "City" column to the "Brazil Customers" view:
 CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
 MySQL Dropping a View

A view is deleted with the DROP VIEW statement.

 DROP VIEW view_name;


 DROP VIEW [Brazil Customers];

Database System Concepts - 7th Edition 4.69 ©Silberschatz, Korth and Sudarshan
views

 Types of Views in SQL


 There are two types of views in the SQL Server, namely System Defined
Views and User Defined Views.
 System Defined Views
 The System Defined Views are predefined views that already exist in the
SQL Server database, such as Tempdb, Master, and temp. Each of the
databases has its own properties and functions.
 User Defined Views
 These are the types of views that are defined by the users. There are two
types under User Defined views, Simple View and Complex View.
 Simple View and Complex View. Simple views can only contain a single
base table. Complex views can be constructed on more than one base
table. In particular, complex views can contain: join conditions, a group by
clause, order by clause.

Database System Concepts - 7th Edition 4.70 ©Silberschatz, Korth and Sudarshan
views
 Simple View
 These views can only contain a single base table or can be created only
from one table. Group functions such as MAX(), COUNT(), etc.,
 By using Simple View, DML operations can be performed. Insert, delete,
and update are directly possible, but Simple View does not contain group
by, rownum, distinct, columns defined by expressions. Simple view also
does not include NOT NULL columns from the base tables.
 Complex View
 These views can contain more than one base table or can be constructed
on more than one base table, and they contain a group by clause, join
conditions, an order by clause. Group functions can be used here, and it
contains groups of data.
 Insert, delete, and update cannot be applied directly on complex views. But
unlike Simple Views, Complex Views can contain group by, rownum,
distinct, columns defined by expressions. NOT NULL columns can be
included in complex views while they are not selected by the Simple View.

Database System Concepts - 7th Edition 4.71 ©Silberschatz, Korth and Sudarshan
privileges
To get started, you need to connect to your MySQL Server instance and log in as a
root user via MySQL command-line interface:
mysql -u root -p

To get started, you need to connect to your MySQL Server instance and log in as a
root user via MySQL command-line interface:
mysql -u root -p
To create a new MySQL user account via the MySQL shell, you need to
execute the CREATE USER statement

CREATE USER [IF NOT EXISTS] 'new_user_name'@'host_name' IDENTIFIED


BY 'user_password'
In the syntax above, replace new_user_name with the name of the new user
and host_name with the name of the host from which the user connects to the
MySQL Server.

Database System Concepts - 7th Edition 4.72 ©Silberschatz, Korth and Sudarshan
privileges
Optionally, set the host_name to ‘localhost’ if you want the user to be able to
connect to MySQL Server only from the localhost
, which means “this computer”.
If that’s not the case, you can use the remote machine IP address as hostname, for
instance:
CREATE USER 'new_user_name'@'10.8.0.5' IDENTIFIED BY 'user_password';
Finally, set a password for the new user after the IDENTIFIED BY
keywords.
Note that the IF NOT EXISTS option allows to ensure that the same user
has not been created before.
Once you are done with the new user creation, remember to grant
privileges to the user to let them access the MySQL database. Otherwise,
the user will not have any permissions to reach or manipulate the
database in any way.

Database System Concepts - 7th Edition 4.73 ©Silberschatz, Korth and Sudarshan
privileges
How to Grant Privileges and Add Permissions to User
To provide a user with access to the database and give permissions, you generally need to use
the following GRANT statement:
GRANT permission_type ON privilege_level TO 'new_user_name'@'host_name';

Database System Concepts - 7th Edition 4.74 ©Silberschatz, Korth and Sudarshan
privileges
 Create User Statement only creates a new user but does not grant any
privileges to the user account. Therefore to grant privileges to a user
account, the GRANT statement is used.
Syntax: GRANT privilegesnames ON object To User;
GRANT pTO user;

 Parameters Used:
 privileges_name: These are the access rights or privileges granted to the
user.
 object:It is the name of the database object to which permissions are
being granted. In the case of granting privileges on a table, this would be
the table name.
 user:It is the name of the user to whom the privileges would be granted.

Database System Concepts - 7th Edition 4.75 ©Silberschatz, Korth and Sudarshan
privileges

Grant Privileges on Database to User


To grant all privileges to a user account on all databases via MySQL command prompt,
you need to assign global privileges and use the *.* syntax after the ON keyword:
GRANT ALL PRIVILEGES ON *.* TO new_user_name@host_name;

you might want to grant limited permissions. For instance, you would like to
allow your new user access only a certain table within the database:
GRANT ALL PRIVILEGES ON database_name.table_name TO
user_name@host_name;
In this case, the user is granted table-level privileges, which apply to all
columns within the table. Hence, they gain permission to read,
edit, and modify the table as required.

Database System Concepts - 7th Edition 4.76 ©Silberschatz, Korth and Sudarshan
privileges
Show All MySQL User Account Privileges
To display the privileges granted to MySQL user accounts, you need to apply the
SHOW GRANTS command:
SHOW GRANTS FOR user_name@host_name;

How to Revoke All Privileges from User

REVOKE permission_type ON privilege_level FROM


'user_name'@'host_name';

REVOKE ALL PRIVILEGES ON database_name.* FROM


'user_name'@'host_name';
Remove User from MySQL
If you decide to remove a MySQL user account, execute the DROP
USER command through the command line:
DROP USER [IF EXISTS] 'user_name'@'host_name'
The command above will remove the user account together with all
of its privileges.

Database System Concepts - 7th Edition 4.77 ©Silberschatz, Korth and Sudarshan
Advantages of MySQL Views
MySQL views bring the following advantages.
1) Simplify complex query views
Views help simplify complex queries. If you have any frequently used complex query, you can create a
view based on it so that you can reference to the view by using a simple SELECT statement instead of
typing the query all over again.
2) Make the business logic consistent
Suppose you have to repeatedly write the same formula in every query. Or you have a query that has
complex business logic.
To make this logic consistent across queries, you can use a view to store the calculation and hide the
complexity.
3) Add extra security layers
A table may expose a lot of data including sensitive data such as personal and banking information.
By using views and privileges, you can limit which data users can access by exposing only the necessary
data to them.
For example, the table employees may contain SSN and address information, which should be accessible by
the HR department only.
To expose general information such as first name, last name, and gender to the General Administration
(GA) department,
you can create a view based on these columns and grant the users of the GA department to the view, not the
entire table employees .
4) Enable backward compatibility
In legacy systems, views can enable backward compatibility.
Suppose, you want to normalize a big table into many smaller ones. And you don’t want to impact the
current applications that reference the table.
In this case, you can create a view whose name is the same as the table based on the new tables so that all
applications can reference the view as if it were a table.
Note that a view and table cannot have the same name so you need to drop the table first before creating a
view whose name is the same as the deleted table.

Database System Concepts - 7th Edition 4.78 ©Silberschatz, Korth and Sudarshan
Set operator
 SET Operators in SQL
 SET operators are special type of operators which are used to combine the result of
two queries.
 Operators covered under SET operators are:
 UNION
 UNION ALL
 INTERSECT
 MINUS

Database System Concepts - 7th Edition 4.79 ©Silberschatz, Korth and Sudarshan
The MySQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.
•Every SELECT statement within UNION must have the same number of columns
•The columns must also have similar data types
•The columns in every SELECT statement must also be in the same order

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Database System Concepts - 7th Edition 4.80 ©Silberschatz, Korth and Sudarshan
Customer Customer ContactN Address City PostalCo Country
ID Name ame de
1 Alfreds Maria Obere Berlin 12209 Germany
Futterkist Anders Str. 57
e
2 Ana Ana Avda. de México 05021 Mexico
Trujillo Trujillo la D.F.
Empared Constituci
ados y ón 2222
helados
3 Antonio Antonio Matadero México 05023 Mexico
Moreno Moreno s 2312 D.F.
Taquería

Database System Concepts - 7th Edition 4.81 ©Silberschatz, Korth and Sudarshan
SupplierI Supplier ContactN Address City PostalCo Country
D Name ame de
1 Exotic Charlotte 49 Gilbert London EC1 4SD UK
Liquid Cooper St.
2 New Shelley P.O. Box New 70117 USA
Orleans Burke 78934 Orleans
Cajun
Delights

3 Grandma Regina 707 Ann 48104 USA


Kelly's Murphy Oxford Arbor
Homeste Rd.
ad

Database System Concepts - 7th Edition 4.82 ©Silberschatz, Korth and Sudarshan
SQL UNION Example

SQL SQL UNIONreturns


statement ALL Example
the cities (only distinct values) from both the "Customers" and
the The
"Suppliers" table:
following SQL statement returns the cities (duplicate values also) from
SELECT City
both the FROM Customers
"Customers" and the "Suppliers" table:
UNION
Example
SELECT City FROM Suppliers
SELECT City FROM Customers
ORDER BY City;
UNION ALL
Note: If someCity
SELECT customers or suppliers have the same city, each city will only be listed
FROM Suppliers
once, because
ORDER BYUNION
City; selects only distinct values. Use UNION ALL to also select
duplicate values!
SQL UNION ALL Example
SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:

 SELECT City FROM Customers


UNION ALL
SELECT City FROM Suppliers
ORDER BY City;

Database System Concepts - 7th Edition 4.83 ©Silberschatz, Korth and Sudarshan
City
Aachen
Albuquerque
Anchorage
Ann Arbor
Annecy
Århus
Barcelona
Barquisimeto
City
Aachen
Albuquerque
Anchorage
Ann Arbor
Annecy
Århus

Database System Concepts - 7th Edition 4.84 ©Silberschatz, Korth and Sudarshan
union

 SQL UNION With WHERE


 SQL statement returns the German cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
 SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
City Country
Aachen Germany
Berlin Germany
Brandenburg Germany
Cunewalde Germany
Cuxhaven Germany

Database System Concepts - 7th Edition 4.85 ©Silberschatz, Korth and Sudarshan
union

 SQL UNION ALL With WHERE


SQL statement returns the German cities (duplicate values also) from both the
"Customers" and the "Suppliers" table
 SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
City Country
Aachen Germany
Berlin Germany
Berlin Germany
Brandenburg Germany
Cunewalde Germany
Cuxhaven Germany
Frankfurt Germany

Database System Concepts - 7th Edition 4.86 ©Silberschatz, Korth and Sudarshan
intersect

INTERSECT
Intersect operation is used to combine two SELECT statements, but it only
retuns the records
which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same.

Write a query to perform intersect operation between the table


t_employees and the table t2_employees.
Query:
SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employee
s;

Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and
perform INTERSECT operation with the records fetched by the second
SELECT query from the t2_employees table.

Database System Concepts - 7th Edition 4.87 ©Silberschatz, Korth and Sudarshan
minus
 MINUS
 It displays the rows which are present in the first query but absent in the
second query with no duplicates.
 Example 1:
 Write a query to perform a minus operation between the table t_employees
and the table t2_employees.
 Query:
SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;
 Here, in a single query, we have written two SELECT queries. The first
SELECT query will fetch the records from the t_employees table and
perform MINUS operation with the records fetched by the second SELECT
query from the t2_employees table.

Database System Concepts - 7th Edition 4.88 ©Silberschatz, Korth and Sudarshan
Triggers

 A MySQL trigger is a database object that is associated with a table. It will be


activated when a defined action is executed for the table. The trigger can be
executed when you run one of the following MySQL statements on the table:
INSERT, UPDATE and DELETE and it can be invoked before or after the
event.
 In MySQL, a trigger is a stored program invoked automatically in response to
an event such as insert, update or delete that occurs in the associated table.
For example, you can define a trigger that is invoked automatically before a
new row is inserted into a table.
 The SQL standard defines two types of triggers: row-level triggers and
statement-level triggers.
 A row-level trigger is activated for each row that is inserted, updated, or
deleted. For example, if a table has 100 rows inserted, updated, or deleted,
the trigger is automatically invoked 100 times for the 100 rows affected.
 A statement-level trigger is executed once for each transaction regardless of
how many rows are inserted, updated, or deleted.

Database System Concepts - 7th Edition 4.89 ©Silberschatz, Korth and Sudarshan
TRIGGERS

Advantages of triggers
• Triggers provide another way to check the integrity of data.
• Triggers handle errors from the database layer.
• Triggers give an alternative way to run scheduled tasks. By using
triggers, you don’t have to wait for the scheduled events to run
because the triggers are invoked automatically before or after a
change is made to the data in a table.
• Triggers can be useful for auditing the data changes in tables.

Database System Concepts - 7th Edition 4.90 ©Silberschatz, Korth and Sudarshan
TRIGGERS
Disadvantages of triggers
•Triggers can only provide extended validations, not all validations. For simple
validations,
•you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY constraints.
•Triggers can be difficult to troubleshoot because they execute automatically in the
database,
•which may not be visible to the client applications.
•Triggers may increase the overhead of the MySQL server.

CREATE TRIGGER trigger_name {BEFORE | AFTER} {INSERT | UPDATE|


DELETE } ON table_name FOR EACH ROW trigger_body;

Database System Concepts - 7th Edition 4.91 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 A trigger in MySQL is a set of SQL statements that reside in a system
catalog. It is a special type of stored procedure that is invoked
automatically in response to an event. Each trigger is associated with a
table, which is activated on any DML statement such as INSERT,
UPDATE, or DELETE.
 A trigger is called a special procedure because it cannot be called directly
like a stored procedure. The main difference between the trigger and
procedure is that a trigger is called automatically when a data modification
event is made against a table. In contrast, a stored procedure must be
called explicitly.
 Generally, triggers are of two types according to the SQL standard: row-
level triggers and statement-level triggers.
 Row-Level Trigger: It is a trigger, which is activated for each row by a
triggering statement such as insert, update, or delete. For example, if a
table has inserted, updated, or deleted multiple rows, the row trigger is
fired automatically for each row affected by the insert, update or delete
statement.
 Statement-Level Trigger: It is a trigger, which is fired once for each event
that occurs on a table regardless of how many rows are inserted, updated,
or deleted.

Database System Concepts - 7th Edition 4.92 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 Why we need/use triggers in MySQL?
We need/use triggers in MySQL due to the following features:
Triggers help us to enforce business rules.
Triggers help us to validate data even before they are inserted or updated.
Triggers help us to keep a log of records like maintaining audit trails in tables.
SQL triggers provide an alternative way to check the integrity of data.
Triggers provide an alternative way to run the scheduled task.
Triggers increases the performance of SQL queries because it does not need to compile each time the query
is executed.
Triggers reduce the client-side code that saves time and effort.
Triggers help us to scale our application across different platforms.
Triggers are easy to maintain.
Limitations of Using Triggers in MySQL
MySQL triggers do not allow to use of all validations; they only provide extended validations. For
example, we can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY constraints for simple
validations.
Triggers are invoked and executed invisibly from the client application. Therefore, it isn't easy to
troubleshoot what happens in the database layer.
Triggers may increase the overhead of the database server.

Database System Concepts - 7th Edition 4.93 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 Types of Triggers in MySQL?
 We can define the maximum six types of actions or events in the form of
triggers:
 Before Insert: It is activated before the insertion of data into the table.
 After Insert: It is activated after the insertion of data into the table.
 Before Update: It is activated before the update of data in the table.
 After Update: It is activated after the update of the data in the table.
 Before Delete: It is activated before the data is removed from the table.
 After Delete: It is activated after the deletion of data from the table.
 When we use a statement that does not use INSERT, UPDATE or
DELETE query to change the data in a table, the triggers associated with
the trigger will not be invoked.

Database System Concepts - 7th Edition 4.94 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 The following naming convention should be used to name the trigger
in MySQL;
 (BEFORE | AFTER) table_name (INSERT | UPDATE | DELETE)
 Thus,
 Trigger Activation Time: BEFORE | AFTER
 Trigger Event: INSERT | UPDATE | DELETE
 How to create triggers in MySQL?
 We can use the CREATE TRIGGER statement for creating a new trigger in
MySQL. Below is the syntax of creating a trigger in MySQL:
 CREATE TRIGGER trigger_name
 (AFTER | BEFORE) (INSERT | UPDATE | DELETE)
 ON table_name FOR EACH ROW
 BEGIN
 --variable declarations
 --trigger code
 END;

Database System Concepts - 7th Edition 4.95 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 MySQL Create Trigger
 how to create the first trigger in MySQL. We can create a new trigger in
MySQL by using the CREATE TRIGGER statement. It is to ensure that we
have trigger privileges while using the CREATE TRIGGER command. The
following is the basic syntax to create a trigger:
 CREATE TRIGGER trigger_name trigger_time trigger_event
 ON table_name FOR EACH ROW
 BEGIN
 --variable declarations
 --trigger code
 END;

Database System Concepts - 7th Edition 4.96 ©Silberschatz, Korth and Sudarshan
triggers
 How to show triggers in MySQL workbench?
 It is a visual GUI tool used to create databases, tables, indexes, views,
and stored procedures quickly and efficiently. To show a trigger using
this tool, we first need to launch the MySQL Workbench and log in
using the username and password that we have created earlier. We will
get the screen as follows:

Database System Concepts - 7th Edition 4.97 ©Silberschatz, Korth and Sudarshan
triggers
 Clicking on the Triggers sub-menu, we can see all triggers associated
with the selected table.

DROP TRIGGER employeedb.before_update_salarie


s;

Database System Concepts - 7th Edition 4.98 ©Silberschatz, Korth and Sudarshan
triggers
 Go to the Navigation tab and click on the Schema menu that contains
all the databases available in the MySQL server.
 Select the database (for example, mysqltestdb), double click on it, and
show the sub-menu containing Tables, Views, Functions, and Stored
Procedures.

Click on the Tables sub-menu and select the table on which you have
created a trigger.

Database System Concepts - 7th Edition 4.99 ©Silberschatz, Korth and Sudarshan
triggers
 If we execute the above statement again with an IF EXISTS clause, it will
return the warning message instead of producing an error.
mysql> DROP TRIGGER IF EXISTS employeedb.before_update_salarie
s;

How to Drop trigger in MySQL workbench?


To create an AFTER UPDATE trigger in workbench, we first launch the
MySQL Workbench and log in using the username and password.

Database System Concepts - 7th Edition 4.100 ©Silberschatz, Korth and Sudarshan
triggers
 Go to the Navigation tab and click on the Schema menu. It will display all
databases available in the MySQL database server.

Select the database (for example, mystudentdb). Then, double click on


the selected schema. It displays the sub-menu containing Tables, Views,
Functions, and Stored Procedures. See the below screen.

Database System Concepts - 7th Edition 4.101 ©Silberschatz, Korth and Sudarshan
triggers
 Expand the Tables sub-menu and select a table on which a trigger is
associated. Again expand the selected Table -> Triggers; we will get the
below image:

Database System Concepts - 7th Edition 4.102 ©Silberschatz, Korth and Sudarshan
triggers

 Now, right-click on the selected table and choose the Alter Table option
that gives the screen as below:

Database System Concepts - 7th Edition 4.103 ©Silberschatz, Korth and Sudarshan
triggers
 Now, click on the Trigger tab shown in the previous section's red
rectangular box. You will notice that there is a (+) and (-) icon button to
add or delete a trigger:

Database System Concepts - 7th Edition 4.104 ©Silberschatz, Korth and Sudarshan
triggers
 Now, clicking on the (-) button will permanently remove the trigger associated
with the table.

Database System Concepts - 7th Edition 4.105 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 Parameter Explanation
 The create trigger syntax contains the following parameters:
 trigger_name: It is the name of the trigger that we want to create. It must
be written after the CREATE TRIGGER statement. It is to make sure that
the trigger name should be unique within the schema.
 trigger_time: It is the trigger action time, which should be either
BEFORE or AFTER. It is the required parameter while defining a trigger.
It indicates that the trigger will be invoked before or after each row
modification occurs on the table.
 trigger_event: It is the type of operation name that activates the trigger.
It can be either INSERT, UPDATE, or DELETE operation. The trigger can
invoke only one event at one time. If we want to define a trigger which is
invoked by multiple events, it is required to define multiple triggers, and
one for each event.
 table_name: It is the name of the table to which the trigger is associated.
It must be written after the ON keyword. If we did not specify the table
name, a trigger would not exist.

Database System Concepts - 7th Edition 4.106 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 BEGIN END Block: Finally, we will specify the statement for execution
when the trigger is activated. If we want to execute multiple statements, we
will use the BEGIN END block that contains a set of queries to define the
logic for the trigger.
 The trigger body can access the column's values, which are affected by
the DML statement. The NEW and OLD modifiers are used to distinguish
the column values BEFORE and AFTER the execution of the DML
statement. We can use the column name with NEW and OLD modifiers
as OLD.col_name and NEW.col_name. The OLD.column_name indicates
the column of an existing row before the updation or deletion occurs.
NEW.col_name indicates the column of a new row that will be inserted or
an existing row after it is updated.

Database System Concepts - 7th Edition 4.107 ©Silberschatz, Korth and Sudarshan
TRIGGERS
 MySQL Trigger Example
 Let us start creating a trigger in MySQL that makes modifications in the employee table.
First, we will create a new table named employee by executing the below statement:
 CREATE TABLE employee(
 name varchar(45) NOT NULL,
 occupation varchar(35) NOT NULL,
 working_date date,
 working_hours varchar(10)
 );
 Next, execute the below statement to fill the records into the employee table:
 INSERT INTO employee VALUES
 ('Robin', 'Scientist', '2020-10-04', 12),
 ('Warner', 'Engineer', '2020-10-04', 10),
 ('Peter', 'Actor', '2020-10-04', 13),
 ('Marco', 'Doctor', '2020-10-04', 14),
 ('Brayden', 'Teacher', '2020-10-04', 12),
 ('Antonio', 'Business', '2020-10-04', 11);

Database System Concepts - 7th Edition 4.108 ©Silberschatz, Korth and Sudarshan
triggers
 Next, execute the SELECT statement to verify the inserted record:

we will create a BEFORE INSERT trigger. This trigger is invoked


automatically insert the working_hours = 0 if someone tries to
insert working_hours < 0.

Database System Concepts - 7th Edition 4.109 ©Silberschatz, Korth and Sudarshan
triggers

Next, we will create a BEFORE INSERT trigger. This trigger is invoked


automatically insert the working_hours = 0 if someone tries to
insert working_hours < 0.
1. mysql> DELIMITER //
2. mysql> Create Trigger before_insert_empworkinghours
3. BEFORE INSERT ON employee FOR EACH ROW
4.BEGIN
5. IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
6.END IF;
7.END //

Database System Concepts - 7th Edition 4.110 ©Silberschatz, Korth and Sudarshan
 we can use the following statements to invoke this trigger:
 mysql> INSERT INTO employee VALUES
 ('Markus', 'Former', '2020-10-08', 14);

 mysql> INSERT INTO employee VALUES
 ('Alexander', 'Actor', '2020-10-012', -13);
 After execution of the above statement, we will get the output as follows:

Database System Concepts - 7th Edition 4.111 ©Silberschatz, Korth and Sudarshan
Database System Concepts - 7th Edition 4.112 ©Silberschatz, Korth and Sudarshan
 MySQL Show/List Triggers
 The show or list trigger is much needed when we have many databases
that contain various tables. Sometimes we have the same trigger names in
many databases; this query plays an important role in that case. We can
get the trigger information in the database server using the below
statement. This statement returns all triggers in all databases:
 mysql> SHOW TRIGGERS;

Database System Concepts - 7th Edition 4.113 ©Silberschatz, Korth and Sudarshan
 The following steps are necessary to get the list of all triggers:
 Step 1: Open the MySQL Command prompt and logged into the database
server using the password that you have created during
MySQL's installation. After a successful connection, we can execute all
the SQL statements.
 Step 2: Next, choose the specific database by using the command below:
 mysql> USE database_name;
 Step 3: Finally, execute the SHOW TRIGGERS command.
 Let us understand it with the example given below. Suppose we have a
database name "mysqltestdb" that contains many tables. Then execute
the below statement to list the triggers:
 mysql> USE mysqltestdb;
 mysql>SHOW TRIGGERS;

Database System Concepts - 7th Edition 4.114 ©Silberschatz, Korth and Sudarshan
mysql> SHOW TABLES IN database_name;

mysql> SHOW TABLES FROM databa


se_name;

Database System Concepts - 7th Edition 4.115 ©Silberschatz, Korth and Sudarshan
 MySQL Command Line Client
 We can drop an existing trigger from the database by using the DROP
TRIGGER statement with the below syntax:
 DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name;

If we execute the above statement again with an IF EXISTS clause, it


will return the warning message instead of producing an error. See
the output:
mysql> DROP TRIGGER IF EXISTS employeedb.before_update_salarie
s;

Database System Concepts - 7th Edition 4.116 ©Silberschatz, Korth and Sudarshan
We can execute the SHOW WARNING statement that generates
a NOTE for a non-existent trigger when using IF EXISTS.

Database System Concepts - 7th Edition 4.117 ©Silberschatz, Korth and Sudarshan
 mysql> DELIMITER //
 mysql> Create Trigger before_insert_empworkinghours
 BEFORE INSERT ON employee FOR EACH ROW
 BEGIN
 IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
 END IF;
 END //
 If the trigger is created successfully, we will get the output as follows:

Database System Concepts - 7th Edition 4.118 ©Silberschatz, Korth and Sudarshan
Subqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR
(SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE])

PHONE_NUMB
NAME ROLL_NO LOCATION
ER
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipuram 8989856868
NAME ROLL_NO SECTION
Ravi 104 A
Sumathi 105 B
Raj 102 A

Database System Concepts - 7th Edition 4.119 ©Silberschatz, Korth and Sudarshan
Sub query
•To display NAME, LOCATION, PHONE_NUMBER of the students from
DATABASE table whose section is A
Select NAME, LOCATION, PHONE_NUMBER from DATABASE WHERE
ROLL_NO IN (SELECT ROLL_NO from STUDENT where SECTION=’A’);

NAME ROLL_NO LOCATION PHONE_NUMBER

Ravi 104 Salem 8989898989

Raj 102 Coimbatore 8877665544

Database System Concepts - 7th Edition 4.120 ©Silberschatz, Korth and Sudarshan
INSERT INTO Student1 SELECT * FROM Student2;
INSERT INTO Student1 SELECT * FROM Student2;

NAME ROLL_NO LOCATION PHONE_NUMBER

Ram 101 chennai 9988773344

Raju 102 coimbatore 9090909090

Ravi
NAME 103
ROLL_NO salem
LOCATION 8989898989
PHONE_NUMBER
Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878

Database System Concepts - 7th Edition 4.121 ©Silberschatz, Korth and Sudarshan
ate name of the students to geeks in Student2 table whose location is same as Raju,Ravi in Student1 table
Student2 SET NAME=’geeks’ WHERE LOCATION IN ( SELECT LOCATION FROM Student1 WHERE NAME IN (‘Raju’,’Ra

•To insert Student2 into Student1 table:


INSERT INTO Student1 SELECT * FROM Student2;

•To delete students from Student2 table whose rollno is same as that in Student1 table and having location as chennai
DELETE FROM Student2 WHERE ROLL_NO IN ( SELECT ROLL_NO FROM Student1 WHERE LOCATION = ’chennai’);
•To delete students from Student2 table whose rollno is same as that in Student1
table and
•having location as chennai
DELETE FROM Student2 WHERE ROLL_NO IN ( SELECT ROLL_NO FROM Student1
WHERE LOCATION = ’chennai’);
•To update name of the students to eng in Student2 table whose location is same as
•Raju,Ravi in Student1 table
UPDATE Student2 SET NAME=’eng’ WHERE LOCATION IN ( SELECT LOCATION FROM
Student1
WHERE NAME IN (‘Raju’,’Ravi’));

Database System Concepts - 7th Edition 4.122 ©Silberschatz, Korth and Sudarshan
Indexes
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.
Indexes are used to retrieve data from the database more quickly than otherwise.
The users cannot see the indexes,
they are just used to speed up searches/queries.

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
N

Database System Concepts - 7th Edition 4.123 ©Silberschatz, Korth and Sudarshan
ON Persons (LastName, FirstName);
ON Persons (LastName, FirstName);
ON Persons (LastName, FirstName);
indexes
ON Persons (LastName, FirstName);

 CREATE INDEX Example


 The SQL statement below creates an index named "idx_lastname" on the
"LastName" column in the "Persons" table:
 CREATE INDEX idx_lastname
ON Persons (LastName);
 If you want to create an index on a combination of columns, you can list
the column names within the parentheses, separated by co

 CREATE INDEX idx_pname


ON Persons (LastName, FirstName);

Database System Concepts - 7th Edition 4.124 ©Silberschatz, Korth and Sudarshan
DROP INDEX Statement
The DROP INDEX statement is used to delete an index in a table.

ALTER TABLE table_name


DROP INDEX index_name;

Database System Concepts - 7th Edition 4.125 ©Silberschatz, Korth and Sudarshan
Natural Join in SQL (Cont.)

 The from clause can have multiple relations combined using natural join:
select A1, A2, … An
from r1 natural join r2 natural join .. natural join rn
where P ;

Database System Concepts - 7th Edition 4.126 ©Silberschatz, Korth and Sudarshan
Student Relation

Database System Concepts - 7th Edition 4.127 ©Silberschatz, Korth and Sudarshan
Takes Relation

Database System Concepts - 7th Edition 4.128 ©Silberschatz, Korth and Sudarshan
student natural join takes

Database System Concepts - 7th Edition 4.129 ©Silberschatz, Korth and Sudarshan
Dangerous in Natural Join

 Beware of unrelated attributes with same name which get equated


incorrectly
 Example -- List the names of students instructors along with the titles of
courses that they have taken
 Correct version
select name, title
from student natural join takes, course
where takes.course_id = course.course_id;
 Incorrect version
select name, title
from student natural join takes natural join course;
 This query omits all (student name, course title) pairs where the
student takes a course in a department other than the student's
own department.
 The correct version (above), correctly outputs such pairs.

Database System Concepts - 7th Edition 4.130 ©Silberschatz, Korth and Sudarshan
Outer Join

 An extension of the join operation that avoids loss of information.


 Computes the join and then adds tuples form one relation that does not
match tuples in the other relation to the result of the join.
 Uses null values.
 Three forms of outer join:
 left outer join
 right outer join
 full outer join

Database System Concepts - 7th Edition 4.134 ©Silberschatz, Korth and Sudarshan
Outer Join Examples

 Relation course

 Relation prereq

 Observe that
course information is missing CS-347
prereq information is missing CS-315

Database System Concepts - 7th Edition 4.135 ©Silberschatz, Korth and Sudarshan
Left Outer Join

 course natural left outer join prereq

 In relational algebra: course ⟕ prereq

Database System Concepts - 7th Edition 4.136 ©Silberschatz, Korth and Sudarshan
Right Outer Join

 course natural right outer join prereq

 In relational algebra: course ⟖ prereq

Database System Concepts - 7th Edition 4.137 ©Silberschatz, Korth and Sudarshan
Full Outer Join

 course natural full outer join prereq

 In relational algebra: course ⟗ prereq

Database System Concepts - 7th Edition 4.138 ©Silberschatz, Korth and Sudarshan
Joined Types and Conditions

 Join operations take two relations and return as a result another


relation.
 These additional operations are typically used as subquery expressions
in the from clause
 Join condition – defines which tuples in the two relations match.
 Join type – defines how tuples in each relation that do not match any
tuple in the other relation (based on the join condition) are treated.

Database System Concepts - 7th Edition 4.139 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples

 course natural right outer join prereq

 course full outer join prereq using (course_id)

Database System Concepts - 7th Edition 4.140 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples

 course inner join prereq on


course.course_id = prereq.course_id

 What is the difference between the above, and a natural join?


 course left outer join prereq on
course.course_id = prereq.course_id

Database System Concepts - 7th Edition 4.141 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples

 course natural right outer join prereq

 course full outer join prereq using (course_id)

Database System Concepts - 7th Edition 4.142 ©Silberschatz, Korth and Sudarshan
Views

 In some cases, it is not desirable for all users to see the entire logical
model (that is, all the actual relations stored in the database.)
 Consider a person who needs to know an instructors name and
department, but not the salary. This person should see a relation
described, in SQL, by

select ID, name, dept_name


from instructor

 A view provides a mechanism to hide certain data from the view of


certain users.
 Any relation that is not of the conceptual model but is made visible to a
user as a “virtual relation” is called a view.

Database System Concepts - 7th Edition 4.143 ©Silberschatz, Korth and Sudarshan
View Definition
 A view is defined using the create view statement which has the form
create view v as < query expression >

where <query expression> is any legal SQL expression. The view name
is represented by v.
 Once a view is defined, the view name can be used to refer to the virtual
relation that the view generates.
 View definition is not the same as creating a new relation by evaluating
the query expression
 Rather, a view definition causes the saving of an expression; the
expression is substituted into queries using the view.

Database System Concepts - 7th Edition 4.144 ©Silberschatz, Korth and Sudarshan
View Definition and Use

 A view of instructors without their salary

create view faculty as


select ID, name, dept_name
from instructor
 Find all instructors in the Biology department

select name
from faculty
where dept_name = 'Biology'
 Create a view of department salary totals

create view departments_total_salary(dept_name, total_salary) as


select dept_name, sum (salary)
from instructor
group by dept_name;

Database System Concepts - 7th Edition 4.145 ©Silberschatz, Korth and Sudarshan
Views Defined Using Other Views

 One view may be used in the expression defining another view


 A view relation v1 is said to depend directly on a view relation v2 if v2 is
used in the expression defining v1
 A view relation v1 is said to depend on view relation v2 if either v1 depends
directly to v2 or there is a path of dependencies from v1 to v2
 A view relation v is said to be recursive if it depends on itself.

Database System Concepts - 7th Edition 4.146 ©Silberschatz, Korth and Sudarshan
Views Defined Using Other Views

 create view physics_fall_2017 as


select course.course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = 'Physics'
and section.semester = 'Fall'
and section.year = '2017’;

 create view physics_fall_2017_watson as


select course_id, room_number
from physics_fall_2017
where building= 'Watson';

Database System Concepts - 7th Edition 4.147 ©Silberschatz, Korth and Sudarshan
View Expansion
 Expand the view :
create view physics_fall_2017_watson as
select course_id, room_number
from physics_fall_2017
where building= 'Watson'
 To:

create view physics_fall_2017_watson as


select course_id, room_number
from (select course.course_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = 'Physics'
and section.semester = 'Fall'
and section.year = '2017')
where building= 'Watson';

Database System Concepts - 7th Edition 4.148 ©Silberschatz, Korth and Sudarshan
View Expansion (Cont.)
 A way to define the meaning of views defined in terms of other views.
 Let view v1 be defined by an expression e1 that may itself contain uses of
view relations.
 View expansion of an expression repeats the following replacement step:
repeat
Find any view relation vi in e1
Replace the view relation vi by the expression defining
vi
until no more view relations are present in e1
 As long as the view definitions are not recursive, this loop will terminate

Database System Concepts - 7th Edition 4.149 ©Silberschatz, Korth and Sudarshan
Materialized Views

 Certain database systems allow view relations to be physically stored.


 Physical copy created when the view is defined.
 Such views are called Materialized view:
 If relations used in the query are updated, the materialized view result
becomes out of date
 Need to maintain the view, by updating the view whenever the
underlying relations are updated.

Database System Concepts - 7th Edition 4.150 ©Silberschatz, Korth and Sudarshan
Update of a View

 Add a new tuple to faculty view which we defined earlier


insert into faculty
values ('30765', 'Green', 'Music');
 This insertion must be represented by the insertion into the instructor
relation
 Must have a value for salary.
 Two approaches
 Reject the insert
 Insert the tuple
('30765', 'Green', 'Music', null)
into the instructor relation

Database System Concepts - 7th Edition 4.151 ©Silberschatz, Korth and Sudarshan
Some Updates Cannot be Translated Uniquely

 create view instructor_info as


select ID, name, building
from instructor, department
where instructor.dept_name = department.dept_name;
 insert into instructor_info
values ('69987', 'White', 'Taylor');
 Issues
 Which department, if multiple departments in Taylor?
 What if no department is in Taylor?

Database System Concepts - 7th Edition 4.152 ©Silberschatz, Korth and Sudarshan
And Some Not at All
 create view history_instructors as
select *
from instructor
where dept_name= 'History';
 What happens if we insert
('25566', 'Brown', 'Biology', 100000)
into history_instructors?

Database System Concepts - 7th Edition 4.153 ©Silberschatz, Korth and Sudarshan
View Updates in SQL

 Most SQL implementations allow updates only on simple views


 The from clause has only one database relation.
 The select clause contains only attribute names of the relation, and
does not have any expressions, aggregates, or distinct
specification.
 Any attribute not listed in the select clause can be set to null
 The query does not have a group by or having clause.

Database System Concepts - 7th Edition 4.154 ©Silberschatz, Korth and Sudarshan
Transactions
 A transaction consists of a sequence of query and/or update
statements and is a “unit” of work
 The SQL standard specifies that a transaction begins implicitly when an
SQL statement is executed.
 The transaction must end with one of the following statements:
 Commit work. The updates performed by the transaction become
permanent in the database.
 Rollback work. All the updates performed by the SQL statements in
the transaction are undone.
 Atomic transaction
 either fully executed or rolled back as if it never occurred
 Isolation from concurrent transactions

Database System Concepts - 7th Edition 4.155 ©Silberschatz, Korth and Sudarshan
Integrity Constraints

 Integrity constraints guard against accidental damage to the database,


by ensuring that authorized changes to the database do not result in a
loss of data consistency.
 A checking account must have a balance greater than $10,000.00
 A salary of a bank employee must be at least $4.00 an hour
 A customer must have a (non-null) phone number

Database System Concepts - 7th Edition 4.156 ©Silberschatz, Korth and Sudarshan
Constraints on a Single Relation

 not null
 primary key
 unique
 check (P), where P is a predicate

Database System Concepts - 7th Edition 4.157 ©Silberschatz, Korth and Sudarshan
Not Null Constraints

 not null
 Declare name and budget to be not null
name varchar(20) not null
budget numeric(12,2) not null

Database System Concepts - 7th Edition 4.158 ©Silberschatz, Korth and Sudarshan
Unique Constraints

 unique ( A1, A2, …, Am)


 The unique specification states that the attributes A1, A2, …, Am
form a candidate key.
 Candidate keys are permitted to be null (in contrast to primary
keys).

Database System Concepts - 7th Edition 4.159 ©Silberschatz, Korth and Sudarshan
The check clause
 The check (P) clause specifies a predicate P that must be satisfied by
every tuple in a relation.
 Example: ensure that semester is one of fall, winter, spring or summer

create table section


(course_id varchar (8),
sec_id varchar (8),
semester varchar (6),
year numeric (4,0),
building varchar (15),
room_number varchar (7),
time slot id varchar (4),
primary key (course_id, sec_id, semester, year),
check (semester in ('Fall', 'Winter', 'Spring', 'Summer')))

Database System Concepts - 7th Edition 4.160 ©Silberschatz, Korth and Sudarshan
Referential Integrity

 Ensures that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation.
 Example: If “Biology” is a department name appearing in one of the
tuples in the instructor relation, then there exists a tuple in the
department relation for “Biology”.
 Let A be a set of attributes. Let R and S be two relations that contain
attributes A and where A is the primary key of S. A is said to be a
foreign key of R if for any values of A appearing in R these values also
appear in S.

Database System Concepts - 7th Edition 4.161 ©Silberschatz, Korth and Sudarshan
Referential Integrity (Cont.)

 Foreign keys can be specified as part of the SQL create table


statement
foreign key (dept_name) references department
 By default, a foreign key references the primary-key attributes of the
referenced table.
 SQL allows a list of attributes of the referenced relation to be specified
explicitly.
foreign key (dept_name) references department (dept_name)

Database System Concepts - 7th Edition 4.162 ©Silberschatz, Korth and Sudarshan
Cascading Actions in Referential Integrity

 When a referential-integrity constraint is violated, the normal procedure is to


reject the action that caused the violation.
 An alternative, in case of delete or update is to cascade
create table course (
(…
dept_name varchar(20),
foreign key (dept_name) references department
on delete cascade
on update cascade,
. . .)
 Instead of cascade we can use :
 set null,
 set default

Database System Concepts - 7th Edition 4.163 ©Silberschatz, Korth and Sudarshan
Integrity Constraint Violation During Transactions

 Consider:
create table person (
ID char(10),
name char(40),
mother char(10),
father char(10),
primary key ID,
foreign key father references person,
foreign key mother references person)
 How to insert a tuple without causing constraint violation?
 Insert father and mother of a person before inserting person
 OR, set father and mother to null initially, update after inserting all
persons (not possible if father and mother attributes declared to be not
null)
 OR defer constraint checking

Database System Concepts - 7th Edition 4.164 ©Silberschatz, Korth and Sudarshan
Complex Check Conditions
 The predicate in the check clause can be an arbitrary predicate that can
include a subquery.
check (time_slot_id in (select time_slot_id from time_slot))
The check condition states that the time_slot_id in each tuple in the
section relation is actually the identifier of a time slot in the time_slot
relation.
 The condition has to be checked not only when a tuple is inserted or
modified in section , but also when the relation time_slot changes

Database System Concepts - 7th Edition 4.165 ©Silberschatz, Korth and Sudarshan
Assertions

 An assertion is a predicate expressing a condition that we wish the


database always to satisfy.
 The following constraints, can be expressed using assertions:
 For each tuple in the student relation, the value of the attribute tot_cred
must equal the sum of credits of courses that the student has completed
successfully.
 An instructor cannot teach in two different classrooms in a semester in the
same time slot
 An assertion in SQL takes the form:
create assertion <assertion-name> check (<predicate>);

Database System Concepts - 7th Edition 4.166 ©Silberschatz, Korth and Sudarshan
Built-in Data Types in SQL

 date: Dates, containing a (4 digit) year, month and date


 Example: date '2005-7-27'
 time: Time of day, in hours, minutes and seconds.
 Example: time '09:00:30' time '09:00:30.75'
 timestamp: date plus time of day
 Example: timestamp '2005-7-27 09:00:30.75'
 interval: period of time
 Example: interval '1' day
 Subtracting a date/time/timestamp value from another gives an
interval value
 Interval values can be added to date/time/timestamp values

Database System Concepts - 7th Edition 4.167 ©Silberschatz, Korth and Sudarshan
Large-Object Types
 Large objects (photos, videos, CAD files, etc.) are stored as a large
object:
 blob: binary large object -- object is a large collection of uninterpreted
binary data (whose interpretation is left to an application outside of
the database system)
 clob: character large object -- object is a large collection of character
data
 When a query returns a large object, a pointer is returned rather than the
large object itself.

Database System Concepts - 7th Edition 4.168 ©Silberschatz, Korth and Sudarshan
User-Defined Types

 create type construct in SQL creates user-defined type

create type Dollars as numeric (12,2) final


 Example:
create table department
(dept_name varchar (20),
building varchar (15),
budget Dollars);

Database System Concepts - 7th Edition 4.169 ©Silberschatz, Korth and Sudarshan
Domains
 create domain construct in SQL-92 creates user-defined domain
types

create domain person_name char(20) not null

 Types and domains are similar. Domains can have constraints,


such as not null, specified on them.
 Example:
create domain degree_level varchar(10)
constraint degree_level_test
check (value in ('Bachelors', 'Masters', 'Doctorate'));

Database System Concepts - 7th Edition 4.170 ©Silberschatz, Korth and Sudarshan
Index Creation
 Many queries reference only a small proportion of the records in a table.
 It is inefficient for the system to read every record to find a record with
particular value
 An index on an attribute of a relation is a data structure that allows the
database system to find those tuples in the relation that have a specified
value for that attribute efficiently, without scanning through all the tuples of
the relation.
 We create an index with the create index command
create index <name> on <relation-name> (attribute);

Database System Concepts - 7th Edition 4.171 ©Silberschatz, Korth and Sudarshan
Index Creation Example
 create table student
(ID varchar (5),
name varchar (20) not null,
dept_name varchar (20),
tot_cred numeric (3,0) default 0,
primary key (ID))
 create index studentID_index on student(ID)
 The query:
select *
from student
where ID = '12345'
can be executed by using the index to find the required record, without
looking at all records of student

Database System Concepts - 7th Edition 4.172 ©Silberschatz, Korth and Sudarshan
Authorization
 We may assign a user several forms of authorizations on parts of the
database.

 Read - allows reading, but not modification of data.


 Insert - allows insertion of new data, but not modification of existing
data.
 Update - allows modification, but not deletion of data.
 Delete - allows deletion of data.
 Each of these types of authorizations is called a privilege. We may
authorize the user all, none, or a combination of these types of privileges
on specified parts of a database, such as a relation or a view.

Database System Concepts - 7th Edition 4.173 ©Silberschatz, Korth and Sudarshan
Authorization (Cont.)
 Forms of authorization to modify the database schema
 Index - allows creation and deletion of indices.
 Resources - allows creation of new relations.
 Alteration - allows addition or deletion of attributes in a relation.
 Drop - allows deletion of relations.

Database System Concepts - 7th Edition 4.174 ©Silberschatz, Korth and Sudarshan
Authorization Specification in SQL

 The grant statement is used to confer authorization


grant <privilege list> on <relation or view > to <user list>
 <user list> is:
 a user-id
 public, which allows all valid users the privilege granted
 A role (more on this later)
 Example:
 grant select on department to Amit, Satoshi
 Granting a privilege on a view does not imply granting any privileges on
the underlying relations.
 The grantor of the privilege must already hold the privilege on the
specified item (or be the database administrator).

Database System Concepts - 7th Edition 4.175 ©Silberschatz, Korth and Sudarshan
Privileges in SQL
 select: allows read access to relation, or the ability to query using the
view
 Example: grant users U1, U2, and U3 select authorization on the
instructor relation:
grant select on instructor to U1, U2, U3
 insert: the ability to insert tuples
 update: the ability to update using the SQL update statement
 delete: the ability to delete tuples.
 all privileges: used as a short form for all the allowable privileges

Database System Concepts - 7th Edition 4.176 ©Silberschatz, Korth and Sudarshan
Revoking Authorization in SQL

 The revoke statement is used to revoke authorization.


revoke <privilege list> on <relation or view> from <user list>
 Example:
revoke select on student from U1, U2, U3
 <privilege-list> may be all to revoke all privileges the revokee may hold.
 If <revokee-list> includes public, all users lose the privilege except those
granted it explicitly.
 If the same privilege was granted twice to the same user by different
grantees, the user may retain the privilege after the revocation.
 All privileges that depend on the privilege being revoked are also
revoked.

Database System Concepts - 7th Edition 4.177 ©Silberschatz, Korth and Sudarshan
Roles

 A role is a way to distinguish among various users as far as what these


users can access/update in the database.
 To create a role we use:
create a role <name>
 Example:
 create role instructor
 Once a role is created we can assign “users” to the role using:
 grant <role> to <users>

Database System Concepts - 7th Edition 4.178 ©Silberschatz, Korth and Sudarshan
Roles Example

 create role instructor;


 grant instructor to Amit;
 Privileges can be granted to roles:
 grant select on takes to instructor;
 Roles can be granted to users, as well as to other roles
 create role teaching_assistant
 grant teaching_assistant to instructor;
 Instructor inherits all privileges of teaching_assistant
 Chain of roles
 create role dean;
 grant instructor to dean;
 grant dean to Satoshi;

Database System Concepts - 7th Edition 4.179 ©Silberschatz, Korth and Sudarshan
Authorization on Views

 create view geo_instructor as


(select *
from instructor
where dept_name = 'Geology');
 grant select on geo_instructor to geo_staff
 Suppose that a geo_staff member issues
 select *
from geo_instructor;
 What if
 geo_staff does not have permissions on instructor?
 Creator of view did not have some permissions on instructor?

Database System Concepts - 7th Edition 4.180 ©Silberschatz, Korth and Sudarshan
Other Authorization Features
 references privilege to create foreign key
 grant reference (dept_name) on department to Mariano;
 Why is this required?
 transfer of privileges
 grant select on department to Amit with grant option;
 revoke select on department from Amit, Satoshi cascade;
 revoke select on department from Amit, Satoshi restrict;
 And more!

Database System Concepts - 7th Edition 4.181 ©Silberschatz, Korth and Sudarshan

You might also like