Outline
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
Database System Concepts - 7th Edition 4.2 ©Silberschatz, Korth and Sudarshan
JOINS
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
Database System Concepts - 7th Edition 4.3 ©Silberschatz, Korth and Sudarshan
Inner join
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;
Database System Concepts - 7th Edition 4.6 ©Silberschatz, Korth and Sudarshan
Inner join
Database System Concepts - 7th Edition 4.7 ©Silberschatz, Korth and Sudarshan
joins
Number of Records: 196
OrderID CustomerName
Database System Concepts - 7th Edition 4.8 ©Silberschatz, Korth and Sudarshan
Left join
Database System Concepts - 7th Edition 4.9 ©Silberschatz, Korth and Sudarshan
joins
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;
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
West Adam
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
Database System Concepts - 7th Edition 4.17 ©Silberschatz, Korth and Sudarshan
joins
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
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
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
Database System Concepts - 7th Edition 4.21 ©Silberschatz, Korth and Sudarshan
PI Returns the value of PI
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
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
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
TO_DAYS Returns the number of days between a date and date "0000-00-00"
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
CURRENT_USER Returns the user name and host name for the MySQL account that the server used
to authenticate the current client
IFNULL Return a specified value if the expression is NULL, otherwise return the expression
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
Database System Concepts - 7th Edition 4.27 ©Silberschatz, Korth and Sudarshan
SELECT CHAR_LENGTH("SQL Tutorial") AS LengthOfString;
LengthOfString
12
LengthOfString
12
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
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
Database System Concepts - 7th Edition 4.33 ©Silberschatz, Korth and Sudarshan
Custome Customer ContactN Address City PostalCo Country
rID Name ame de
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;
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;
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;
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.
Database System Concepts - 7th Edition 4.45 ©Silberschatz, Korth and Sudarshan
DML
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>;
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
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;
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.
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.
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:
Database System Concepts - 7th Edition 4.56 ©Silberschatz, Korth and Sudarshan
constraints
Database System Concepts - 7th Edition 4.58 ©Silberschatz, Korth and Sudarshan
constraints
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:
Database System Concepts - 7th Edition 4.60 ©Silberschatz, Korth and Sudarshan
constraints
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:
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;
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()
);
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
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.
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
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
Database System Concepts - 7th Edition 4.69 ©Silberschatz, Korth and Sudarshan
views
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
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
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;
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;
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
Database System Concepts - 7th Edition 4.82 ©Silberschatz, Korth and Sudarshan
SQL UNION Example
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
Database System Concepts - 7th Edition 4.85 ©Silberschatz, Korth and Sudarshan
union
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.
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
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.
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.
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;
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.
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:
Database System Concepts - 7th Edition 4.109 ©Silberschatz, Korth and Sudarshan
triggers
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;
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;
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’);
Database System Concepts - 7th Edition 4.120 ©Silberschatz, Korth and Sudarshan
INSERT INTO Student1 SELECT * FROM Student2;
INSERT INTO Student1 SELECT * FROM Student2;
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 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.
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);
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.
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
Database System Concepts - 7th Edition 4.130 ©Silberschatz, Korth and Sudarshan
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
Database System Concepts - 7th Edition 4.136 ©Silberschatz, Korth and Sudarshan
Right Outer Join
Database System Concepts - 7th Edition 4.137 ©Silberschatz, Korth and Sudarshan
Full Outer Join
Database System Concepts - 7th Edition 4.138 ©Silberschatz, Korth and Sudarshan
Joined Types and Conditions
Database System Concepts - 7th Edition 4.139 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples
Database System Concepts - 7th Edition 4.140 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples
Database System Concepts - 7th Edition 4.141 ©Silberschatz, Korth and Sudarshan
Joined Relations – Examples
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
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
select name
from faculty
where dept_name = 'Biology'
Create a view of department salary totals
Database System Concepts - 7th Edition 4.145 ©Silberschatz, Korth and Sudarshan
Views Defined Using Other Views
Database System Concepts - 7th Edition 4.146 ©Silberschatz, Korth and Sudarshan
Views Defined Using Other Views
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:
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
Database System Concepts - 7th Edition 4.150 ©Silberschatz, Korth and Sudarshan
Update of a View
Database System Concepts - 7th Edition 4.151 ©Silberschatz, Korth and Sudarshan
Some Updates Cannot be Translated Uniquely
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
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
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
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
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.)
Database System Concepts - 7th Edition 4.162 ©Silberschatz, Korth and Sudarshan
Cascading Actions in Referential Integrity
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
Database System Concepts - 7th Edition 4.166 ©Silberschatz, Korth and Sudarshan
Built-in Data Types in SQL
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
Database System Concepts - 7th Edition 4.169 ©Silberschatz, Korth and Sudarshan
Domains
create domain construct in SQL-92 creates user-defined domain
types
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.
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
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
Database System Concepts - 7th Edition 4.177 ©Silberschatz, Korth and Sudarshan
Roles
Database System Concepts - 7th Edition 4.178 ©Silberschatz, Korth and Sudarshan
Roles Example
Database System Concepts - 7th Edition 4.179 ©Silberschatz, Korth and Sudarshan
Authorization on Views
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