RDBMS Fundamentals
Eng. Hebatallah Mostafa
What is Data Base ????
Data Base: an organized collection of
related data
we need to use the most less space to
store the data
- we need to retrieve the data in the fastest
time
The Relational Model
♦
One or more Tables represent data and the
relationships amongst different data
♦
A table is a collection of records in a Database
♦
A table has multiple columns
♦
Each column has a unique name, and contains sets of data
♦
Every set is called a row
♦
The value of the data is got by the intersection of a row and
a column
Database Design
Physical Design
Logical Design
Conceptual Design
Requirements collection
Conceptual Design
Data
Modeling
Entities &
relationships
ER
Diagrams
♦
Entities are objects of the real world relevant to the
information system
♦
The properties of an entity are its Attributes and this
determines the data that is to be stored
♦
Actual data can be described as the values of
attributes of entity
Entities and Relationships
Components of ER Diagram
1- Entities
3- Relationships
2- Attributes
Slide 3
-
9
Summary of the
notation for ER
diagrams
.
Slide 3
-
10
ER diagrams for the COMPANY schema, with structural
constraints specific using (min, max) notation
.
♦
ER modeling is a good aid for designing databases
♦
An ER model is a Graphical representation of
the system
♦
It is a high-level conceptual data model
♦
An ER model also supports a user’s perception of
data
Why ER Diagrams?
1
-
Entities
♦ Two types of entities
– Strong entity type
– Weak entity type
Strong
Entity
weak
Entity
♦ Entities are objects of the real world relevant to the
information system
• An Entity represents a discrete object.
• Entities can be thought of as nouns.
• Examples: a computer, an employee, a song
Strong
Entity
STRONG entity
is an entity that uniquely identified by its own attributes
alone
a Weak entity
A weak entity is an entity that can't be uniquely identified by
its own attributes alone; therefore, it must use a foreign key
in conjunction with its attributes to create a primary key.
The foreign key is typically a primary key of an entity it is
related to.
weak
Entity
2
-
Attributes
Attribute : is a property of the entity or of the relationship that
is interesting in a specific context
Student
name
Student ID
Student
Entities and relationships can both have attributes. Examples:
an employee entity might have a social security number attribute
the proved relationship may have a date attribute
.
Attributes are drawn as ovals connected to their owning entity
sets by a line
.
student
Studebt ID
Student name
Keys
- Super key : a superkey is a set of columns within a table whose values
can be used to uniquely identify
- Candidate Key: is a minimal set of columns necessary to identify a row
1- primary key :
it’s A unique key must uniquely identify all possible rows that exist in
a table and not only the currently existing rows.
Example of unique keys are Social Security numbers
Note : it does not allow null.
Kinds (simple-composite)
name
sn
Date of
birth
address
ID
2
-
Foreign keys
a foreign key is a reference to a key in another table
a foreign key (FK) is a referential constraint between two tables. The FK identifies
a column or a set of columns in one (referencing) table that refers to a column or set
of columns in another (referenced)
Emp_id
Emb_name
Dept_id
Man_id
Dept_id
Dept_
name
(
PK
)
(
FK
)
3
-
Relationships
Relationships represent a set of connections between objects
Student write Exam
Relationships can be thought of as verbs.
Examples: a performs relationship between an artist and a song,
a proved relationship between a mathematician and a theorem.
relationships are drawn as diamonds
Student
write
Exam
Types of Relationships (cardinality)
• One-to-One Relationship
• One-to-Many Relationship
• Many to Many Relationship
Degree of Relationship
1
-
Unary Relationship
Emp_id
Emb name
Dept_id
Man_id
Every Employee has a Manager and the
Manager is an Employee his self
2
-
Binary Relationship
Every employee work in a department and the department
has a specific entity
Emp_id
Emb_name
Dept_id
Man_id
Dept_id
Dept_ name
3
-
N-ary Relationship
computer
employee
project
1
-
Identify entities
2
-
Remove duplicate entities
3
-
List the attributes of each entity
4
-
Mark the primary keys
5
-
Define the relationships
6
-
Examine each entity type to see how it is
related to others
7
-
Describe the cardinality(1:1 or 1:m) of the
relationships
8
-
Remove redundant relationships
http://www.databaseanswers.org/data_models/index.htm
Constructing an ER Model
Normalization
What is Normalization?
The process of efficiently organizing data in a database.
There are two goals of the normalization process:
1. Storing the same data in more than one table.
2. Storing related data in a table.
Both of these are worthy goals as they reduce the
amount of space a database consumes and ensure that
data is logically stored.
Normalizing an example table
1- Unnormalized table
These steps demonstrate the process of normalizing
a fictitious student table.
Class3 Class2 Class1 Adv-Room Advisor Student#
159-02 143-01 101-07 412 Jones 1022
214-01 211-02 201-01 216 Smith 4123
(1NF) sets the very basic rules for an organized database:
Eliminate duplicative columns from the same table.
Create separate tables for each group of related data
and identify each row with a unique column or set of
columns (the primary key).
2- First Normal Form
No Repeating Groups
Tables should have only two dimensions. Since one student
has several classes, these classes should be listed in a
separate table.
Fields Class1, Class2, and Class3 in the above records are
indications of design trouble.
Spreadsheets often use the third dimension, but tables should
not.
Another way to look at this problem is with a one-to-many
relationship, do not put the one side and the many side in the
same table.
Instead, create another table in first normal form by
eliminating the repeating group (Class#), as shown below:
Class#
Adv-
Room
Adviso
r
Student
#
101-
07
412 Jones 1022
143-
01
412 Jones 1022
159-
02
412 Jones 1022
201-
01
216 Smith 4123
(2NF) further addresses the concept of removing duplicative
data:
3- Second Normal Form
Meet all the requirements of the first normal form.
Remove subsets of data that apply to multiple rows of a
table and place them in separate tables.
Create relationships between these new tables and their
predecessors through the use of foreign keys.
Students
Adv-Room
Adviso
r
Student#
412 Jones 1022
216 Smith 4123
Registration
Class# Student#
101-
07
1022
143-
01
1022
159-
02
1022
201-
01
4123
211-02 4123
214-
01
4123
The following two tables demonstrate second normal
form:
(3NF) goes one large step further:
Meet all the requirements of the second normal form.
Remove columns that are not dependent upon the
primary key.
4- Third Normal Form
Eliminate Data Not Dependent On Key
In the last example, Adv-Room (the advisor's office number)
is functionally dependent on the Advisor attribute. The
solution is to move that attribute from the Students table to
the Faculty table, as shown below:
Students Faculty
Adviso
r
Student
#
Jones 1022
Smith 4123
Dep
t
Roo
m Name
42 412 Jones
42 216 Smith
Assignment
• Draw the ER model of a car reservation company.!!!
SQL
Structured Query Language
About SQL
• Stands for Structured Query Language
• Developed at IBM Research for System R
• Includes features of relational algebra and tuple relational
calculus
• The standard for relational data access
• DBMS independent
Parts of SQL
DDL
♦ Data definition language
♦
CREATE
CREATE TABLE toys
(
buyerid INTEGER NOT NULL
,
item CHAR(40) NOT NULL
;)
♦
ALTER
ALTER TABLE toys ADD COLUMN sellerid integer
♦
DROP
DROP TABLE toys
DCL
♦ Data control language
♦
Controls and monitors data access
♦
Ensures data security
♦
Prevents illegal access to data
♦
Some of the SQL commands are
:
–
GRANT
–
REVOKE
.
DML
♦
Data Manipulation language
–
INSERT
INSERT INTO toys VALUES (21, 01,'barbie', 200.00)
INSERT INTO toys (buyerid, item,sellerid) VALUES (01,'barbie',21)
;
–
DELETE
DELETE FROM toys WHERE item = 'Barbie
'
–
UPDATE
UPDATE toys SET price = 500.00 WHERE item = 'Chair';
DQL
♦
Data Query language
♦
Simple SELECT
–
Retrieves data from tables
–
Can be a simple, or a conditional SELECT
SELECT * FROM table_name
;
SELECT colname1, colname2, …, colnamen FROM table_name
;
Conditional Selection
♦
Specifies the conditional SELECT statement
using the WHERE clause
SELECT * FROM TABLE_NAME WHERE OL_NAME = VALUE
;
The Relational Operators Operator Meaning
=
Equal to
<
Less than
=<
Less than or Equal to
>
Greater than
=>
Greater than or equal to
><
or != Not equal to
Aggregate Functions
♦
They are also called group functions
♦
They work on sets of rows and fetch results
♦
Important functions are SUM, AVG, MAX
,
MIN, and COUNT
Compound Conditions and Logical Operators
♦
The AND Operator
SELECT employeeidno FROM employeestatistics
WHERE salary > 40000 AND position = 'Staff
‘
♦
The OR Operator
SELECT employeeidno FROM employeestatistics
WHERE salary < 40000 OR benefits < 10000
♦
The IN Operator
SELECT employeeidno FROM employeestatistics
WHERE position IN ('Manager', 'Staff')
♦
the BETWEEN operator
SELECT employeeidno FROM employeestatistics WHERE salary
BETWEEN 30000 AND 50000
The NOT Operator
SELECT employeeidno FROM employeestatistics WHERE salary
NOT BETWEEN 30000 AND 50000
The LIKE Operator
SELECT employeeidno FROM employeeaddress WHERE
lastname LIKE 'S
‘%
The CONCATENATION Operator
SELECT firstname || ‘.’ || lastname FROM employeeaddress
first_name || ‘.’ || last_name
Alias Column Names
SELECT firstname || ‘.’ || lastname AS “Full Name“ FROM
employeeaddress
The ORDER BY Clause
♦
Formats the output based on one field in a
certain order, descending or ascending
SELECT * FROM employeestatistics ORDER BY salary ASC
SELECT * FROM employeestatistics ORDER BY salary DESC
The DISTINCT Clause
SELECT DISTINCT position FROM employeestatistics
The JOIN Condition
The "Persons" table:
The "Orders" table:
P_Id LastName FirstName Address City
1 Ahmed Abdalla Smouha 10 Alexandria
2 Mostafa Tarek Roshdy 23 Alexandria
3 Mohamed Karim Sporting 20 Alex
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Example
The JOIN Condition cont
.
1– Cartesian
SELECT Persons.LastName,
Persons.FirstName, Orders.OrderNo
FROM Persons, Orders
LastName FirstName OrderNo
Ahmed Abdalla 77895
Mostafa Tarek 44678
Mohamed Karim 22456
Ahmed Abdalla 44678
Mostafa Tarek 22456
Mohamed Karim 24562
Ahmed Abdalla 22456
Mostafa Tarek 24562
Mohamed Karim 34764
Ahmed Abdalla 24562
Mostafa Tarek 34764
Mohamed Karim 77895
Ahmed Abdalla 34764
Mostafa Tarek 77895
Mohamed Karim 44678
Now we want to list all the persons with any orders.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
The INNER JOIN keyword return rows when there is at least one
match in both tables. If there are rows in "Persons" that do not have
matches in "Orders", those rows will NOT be listed.
LastName FirstName OrderNo
Ahmed Abdalla 22456
Ahmed Abdalla 24562
Mohamed Karim 77895
Mohamed Karim 44678
2– INNER
The JOIN Condition cont
.
3– RIGHT OUTER
Now we want to list all the orders with containing persons - if any,
from the tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
The RIGHT JOIN keyword returns all the rows from the right table
(Orders), even if there are no matches in the left table (Persons).
LastName FirstName OrderNo
Ahmed Abdalla 22456
Ahmed Abdalla 24562
Mohamed Karim 77895
Mohamed Karim 44678
34764
The JOIN Condition cont
.
4– LEFT OUTER
Now we want to list all the persons and their orders - if any, from the
tables above.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
The LEFT JOIN keyword returns all the rows from the left table
(Persons), even if there are no matches in the right table (Orders).
LastName FirstName OrderNo
Ahmed Abdalla 22456
Ahmed Abdalla 24562
Mohamed Karim 77895
Mohamed Karim 44678
Mostafa Tarek
The JOIN Condition cont
.
5– FULL OUTER
Now we want to list all the persons and their orders, and all the orders
with their persons.
We use the following SELECT statement:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
The FULL JOIN keyword returns all the rows from the left table
(Persons), and all the rows from the right table (Orders). If there are
rows in "Persons" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Persons", those rows
will be listed as well.
LastName FirstName OrderNo
Ahmed Abdalla 22456
Ahmed Abdalla 24562
Mohamed Karim 77895
Mohamed Karim 44678
Mostafa Tarek
34764
The JOIN Condition cont
.
6– SELF
We use the following SELECT statement:
SELECT concat(e.firstname, e.lastname)
employee,
concat(m.firstname,m.lastname) manager
FROM employees e, employees m WHERE
m.employeeId = e.reportsTo
The result-set will look like this:
Employee Manager
Ahmed Abdalla Osama
Mohamed Karim Sherif
Mostafa Tarek Mona
The JOIN Condition cont
.
The GROUP BY Clause
SELECT buyerid, COUNT(item) AS items FROM toys
GROUP BY buyerid
The HAVING Clause
SELECT buyerid , COUNT(item) AS items FROM toys
GROUP BY buyerid HAVING COUNT(item) > 2
Writing Sub-queries
SELECT item FROM toys WHERE buyerid=(select ownerid
FROM toysowners WHERE firstname=’Bob’)
Correlated Sub-Queries
SELECT dept.name FROM dept WHERE EXISTS (SELECT
dept_id FROM emp WHERE emp.dept_id = dept.dept_id
Schema and Catalogs
Support for creating and maintaining schemas are provided
from SQL2. A schema is created by a CREATE SCHEMA
command. For example:
CREATE SCHEMA UNIV AUTHORIZATION dean;
Creates a schema “UNIV” owned by the user with userid “dean”.
A catalog is a named collection of schemas. Referential integrity
constraints can be defined across schemas only if they belong to
the same catalog.
Table Creation
A new relation can be created using the CREATE TABLE
command. The general syntax is as follows:
CREATE TABLE [schema.]table_name [{column descriptions}];
Example:
CREATE TABLE UNIV.DEPARTMENT;
Data Types and Domains (SQL2)
Primitive data types in SQL2 include:
Numeric (int, smallint, float, real, double precision)
Formatted numbers (decimal(i,j), numeric(i,j))
Character string of either fixed length (char(n)) or
of varying length (varchar(n))
Date, time and timestamp
Text
…
Constraints and Default Values
• The NOT NULL constraint on an attribute disallows NULL
as a valid value
• The DEFAULT construct specifies the default value of an
attribute
• The PRIMARY KEY construct specifies one or more
attributes as the primary key
• The UNIQUE construct specifies alternate (secondary) keys
• The FOREIGN KEY construct ensures referential integrity
Table Creation Example
CREATE TABLE EMPLOYEE (
PANNO VARCHAR(16) NOT NULL, UNIQUE,
EMPNO INT(6) NOT NULL,
NAME VARCHAR (40),
GENDER CHAR,
DOB DATE,
ADDRESS VARCHAR(100),
SALARY DECIMAL(8,2),
REPORTSTO INT(6),
PRIMARY KEY (EMPNO),
FOREIGN KEY (REPORTSTO) REFERENCES
EMPLOYEE (EMPNO));
Table Deletion
Tables can dropped (deleted) using the DROP TABLE command:
DROP TABLE NAME [DEPENDENT {CASCADE | RESTRICT}];
The above command drops the table specified by NAME. If the
CASCADE option is provided, then any foreign-key constraints
and views that reference the table will also be dropped.
If RESTRICT option is specified, then the table is dropped only if
it does not have any incoming references.
Schema Deletion
Schemata can dropped (deleted) using the DROP SCHEMA
command:
DROP SCHEMA NAME {CASCADE | RESTRICT};
The above command drops the schema specified by NAME. If the
CASCADE option is provided, then all tables in the schema will be
automatically dropped.
If RESTRICT option is specified, then the schema is dropped only if
it does not have any elements.
The SELECT Operation
The SELECT-FROM-WHERE form:
SELECT <attribute list>
FROM <table list>
WHERE <condition>;
Example:
SELECT EMPNO, NAME FROM EMPLOYEE
WHERE REPORTSTO = ‘007’;
The SELECT Operation
The SELECT-FROM-WHERE form can act on multiple tables
as well. Consider the table DEPARTMENT shown below:
CREATE TABLE DEPARTMENT (
DNO INT(6) NOT NULL,
NAME VARCHAR(20),
ADDRESS VARCHAR(60),
HEAD INT(6),
PRIMARY KEY (DNO),
FOREIGN KEY HEAD
REFERENCES EMPLOYEE(EMPNO));
The SELECT Operation
Consider the following query: What is the name of the person
who heads the “SUPPLIES” department?
Note the use of the table name in order to disambiguate
attributes having the same name. Table names need not be
used where there is no ambiguity.
SELECT EMPLOYEE.NAME
FROM EMPLOYEE, DEPARTMENT
WHERE EMPNO = HEAD
AND
DEPARTMENT.NAME = ‘SUPPLIES’;
The SELECT Operation
What happens when the same table has to be used multiple
times?
Consider the query: What is the name of the person to whom
Arvind Kulkarni reports to?
SELECT EMPLOYEE.NAME
FROM EMPLOYEE, EMPLOYEE
WHERE EMPLOYEE.NAME = ‘Arvind Kulkarni’
AND
EMPLOYEE.REPORTSTO =
EMPLOYEE.EMPNO;
Ambiguous
!
The SELECT Operation
The solution is to use “aliasing” of table names:
SELECT BOSS.NAME
FROM EMPLOYEE, EMPLOYEE AS BOSS
WHERE EMPLOYEE.NAME = ‘Arvind Kulkarni’
AND
EMPLOYEE.REPORTSTO = BOSS.EMPNO;
The SELECT Operation
When the WHERE clause is omitted, SELECT acts as the project
operator of relational algebra:
SELECT NAME, PANNO
FROM EMPLOYEE;
Returns all rows in EMPLOYEE, but only the NAME and PANNO
columns.
The SELECT Operation
When more than one table is specified and WHERE is omitted, the
result is equivalent to a project over the cross product of tables
SELECT EMPLOYEE.NAME, DEPARTMENT.NAME
FROM EMPLOYEE, DEPARTMENT;
Returns rows associating all EMPLOYEE names with all
DEPARTMENT names.
The SELECT Operation
All columns of a table can be retrieved using the ‘*’ construct:
SELECT *
FROM EMPLOYEE
WHERE NAME = ‘Bhadriah’;
Returns the entire row for all EMPLOYEE relations where
Name is “Bhadriah”.
SELECT * FROM EMPLOYEE, DEPARTMENT;
Returns the cross product of EMPLOYEE and DEPARTMENT.
The INSERT Command
Data tuples can be added to tables using the INSERT
command. Example:
INSERT INTO EMPLOYEE
VALUES (‘1002’, 002, ‘Bharath Kumar’, ‘M’,
‘9-5-1973’, ‘Rajajinagar Bangalore 10’,
300000, 007, 5);
Inserts an entire EMPLOYEE record with corresponding values.
The INSERT Command
Specific attributes can be populated by explicitly specifying
them by name:
INSERT INTO EMPLOYEE(NAME,ADDR,DNO)
VALUES (‘Arun K’, ‘Yeshwanthpur’, 5);
The other attributes will get either NULL values or their DEFAULT
values.
All attributes that are left out should hence not have NOT NULL
constraint or must have the DEFAULT constraint.
The INSERT Command
The result of a SELECT query can be provided as data for
an INSERT command:
Consider the following table:
CREATE TABLE EMD (
EMPLOYEE INT(6),
MANAGER INT(6),
DNO INTEGER);
The INSERT Command
The following INSERT dynamically creates data from a SELECT
query for insertion:
INSERT INTO EMD
SELECT E.EMPNO AS EMPLOYEE,
E.REPORTSTO AS MANAGER,
D.DNUMBER AS DNO
FROM EMPLOYEE AS E JOIN
DEPARTMENT AS D
ON E.DNO = D.DNUMBER;
The INSERT Command
• Inserts multiple instances of the same tuple if called multiple times
as long as there is no violation of UNIQUE constraints
• Insertion fails if referential integrity is violated
• Multiple tuples can be inserted within a single INSERT command by
enclosing each tuple within parentheses and separating tuples by a
comma
Deletion of Tuples
Tuples can be deleted from a table using the
DELETE-FROM-WHERE command:
DELETE FROM EMPLOYEE WHERE EMPNO=007;
(deletes one tuple)
DELETE FROM EMPLOYEE WHERE DNO IN
(SELECT DNUMBER FROM DEPARTMENT
WHERE HEAD=007);
(deletes possibly more than one tuples)
DELETE FROM EMPLOYEE;
(deletes all tuples)
Updating of Tuples
Tuples can be modified using the
UPDATE-SET-WHERE command:
UPDATE EMPLOYEE
SET SALARY = SALARY*1.1
WHEREREPORTSTO=007;
Give a 10% raise in salary for all employees working under 007.
Views (Virtual Tables)
• A table that physically exists in a database is called a base table
• A view or a virtual table is a table that is derived from other tables
• The other tables could either be base tables or other views
• Views need not be stored in the database as tables (but as queries)
• Update operations to a view are limited; but querying is not
Specification of Views
Views are specified using the CREATE VIEW command:
CREATE VIEW EMD(EMPL, MGR, DEPT)
AS
SELECT E.NAME, M.NAME, D.NAME
FROM EMPLOYEE AS E,
EMPLOYEE AS M,
DEPARTMENT AS D
WHERE E.REPORTSTO=M.EMPNO
AND
E.DNO=D.DNUMBER;
Views
• A view is always up to date
• Hence characterization of a view is not done during view definition
time, but during query
• Views can be deleted using the DROP VIEW command
• Efficient implementation of views a tricky problem.
Modifying Tables
Table definitions can be modified using the ALTER TABLE
command. Example:
ALTER TABLE COMPANY.EMPLOYEE
ADD JOB VARCHAR(20);
..adds a new column to the EMPLOYEE table with the name
job and domain VARCHAR of maximum size 20 characters.
Modifying Tables
Consider the following example:
ALTER TABLE COMPANY.EMPLOYEE
ADD JOB VARCHAR(20);
Unless a DEFAULT clause is specified, the value of the JOB
attribute for all the tuples will be NULL.
If no DEFAULT clause is specified, then the NOT NULL
constraint cannot be used.
Modifying Tables
To drop columns, either the CASCADE or RESTRICT options
should be used:
ALTER TABLE COMPANY.EMPLOYEE
DROP PANNO CASCADE;
If CASCADE option is used, then all constraints and views that
refer to the column (PANNO in this case) are also dropped
automatically.
If RESTRICT is used, then the column is dropped only if it does
not have any referencing constraints or views.
Modifying Tables
It is possible to alter a column definition by adding or dropping
DEFAULT clauses:
ALTER TABLE COMPANY.EMPLOYEE
ALTER REPORTSTO SET DEFAULT “007”;
or
ALTER TABLE COMPANY.EMPLOYEE
ALTER REPORTSTO DROP DEFAULT;
All NULL values for a column are updated whenever a new
DEFAULT is set.
Tables as Sets
By default SQL treats relations (tables) as bags or multi-sets
rather than sets.
A tuple may appear multiple times in a table. The DISTINCT
clause can be used to make the output into a set.
SELECT DISTINCT NAME
FROM EMPLOYEE;
Tables as Sets
Set theoretic operators UNION, INTERSECTION and EXCEPT
denote operations union, intersection and set difference.
They assume relations to be sets and not multi-sets. Note the use
of DISTINCT in the following example:
SELECT DISTINCT NAME
FROM EMPLOYEE
WHERE SALARY > 300000.00
UNION
SELECT DISTINCT NAME
FROM EMPLOYEE
WHERE SALARY < 24000.00;
Substring Comparison
Partial strings can be specified by embedding them around
% symbols and compared using the LIKE comparator:
SELECT *
FROM EMPLOYEE
WHERE NAME LIKE ‘%Arun%’;
% symbol matches any number of characters. A single character
can be matched by the underscore (_) symbol.
… WHERE NAME LIKE ‘_arun__’;
Arithmetic Operators
Standard numeric operators like addition (+), subtraction (-),
multiplication (*) and division (/) can be applied to attributes
having numeric domains.
The operators may also appear as part of the output table:
SELECT 1.1 * SALARY
FROM EMPLOYEE
WHERE SALARY > 300000;
Arithmetic Operators
The BETWEEN operator can be used to check for numeric values
within a given range:
SELECT *
FROM EMPLOYEE
WHERESALARY BETWEEN 300000 AND 400000;
Sorting Results
Output of a SELECT statement can be ordered (sorted) based
on one or more attributes by using the ORDER BY clause:
SELECT *
FROM EMPLOYEE
WHERE SALARY > 300000
ORDER BY NAME, EMPNO;
Nested Queries
Dynamically created tables from SELECT queries can be used
within other SELECT queries:
SELECT NAME
FROM DEPARTMENT
WHERE DNUMBER IN
(SELECT DNO
FROM EMPLOYEE
WHERESALARY > 300000);
Highlighted query called the “nested query” and the non-highlighted
query called “outer query”.
Nested Queries
Comparisons with an entire table of values can be performed using
the ALL clause:
SELECT NAME
FROM EMPLOYEE
WHERESALARY > ALL
(SELECT SALARY
FROM EMPLOYEE
WHERE SUPERVISOR=‘007’);
Returns the names of employees whose salaries are more than the
salaries of all those who report to ‘007’
Nested Queries
Attribute names and scope:
Any unqualified attribute name in a nested query applies to the
innermost block of the query:
SELECT E.NAME
FROM EMPLOYEE AS E
WHEREE.EMPNO IN
(SELECT REPORTSTO
FROM EMPLOYEE
WHERE E.NAME = NAME);
Return all employee names who have the same name as their boss.
Nested Queries
The (NOT) EXISTS clause is used to check whether the result of a
SELECT operation is empty or not:
SELECT D.HEAD
FROM DEPARTMENT AS D
WHERENOT EXISTS
(SELECT EMPNO
FROM EMPLOYEE
WHERE REPORTSTO=D.EMPNO);
Return the set of all heads of departments who do not have anyone
directly reporting to them.
Explicit Sets
Explicit sets of values for set theoretic operations can be specified
using parentheses:
SELECT NAME
FROM EMPLOYEE
WHERE REPORTSTO IN (‘007’, ‘008’, ‘009’);
Returns the names of all employees who report to ‘007’, ‘008’ or
‘009’.
Checking for NULL values
NULL values of attributes can be checked by using the
IS NULL or IS NOT NULL constructs.
SELECT NAME, SALARY
FROM EMPLOYEE AS E
WHEREEXISTS
(SELECT EMPNO
FROM EMPLOYEE
WHERE E.REPORTSTO = EMPNO
AND
REPORTSTO IS NULL);
Return the names and salaries of people who report directly to the
head of the company.
Renaming Attributes
The AS clause can be used to rename attributes in the same way
as it can rename relations.
SELECT NAME AS EMPLOYEE_NAME
FROM EMPLOYEE;
The renamed attribute will be displayed in the output result of the
SELECT query.
Aggregate Functions
Aggregate functions like COUNT, SUM, AVG, MAX and MIN
operate on all tuples from the result and return a value:
SELECT COUNT(SALARY), MIN(SALARY),
MAX(SALARY), SUM(SALARY),
AVG(SALARY)
FROM EMPLOYEE;
COUNT can be used on non-numeric attributes as well.
MAX and MIN can also be used on non-numeric attributes if they
have a total ordering defined (Ex: date, char, etc.)
Aggregate Functions
Since aggregate functions return a single value, they can be used
as part of a condition in a WHERE clause:
SELECT E.NAME
FROM EMPLOYEE AS E
WHERE (SELECT COUNT(*)
FROM DEPARTMENT AS D
WHERE D.HEAD=E.EMPNO) >= 2;
Return the names of all employees who head two or more departments.
Aggregate Functions
In many cases, aggregate functions have to be applied to
subgroups of tuples rather than all tuples. For this, the
GROUP BY clause is useful:
SELECT DNO, COUNT(*), AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNO;
For each department, count the number of employees and their
average salaries.
Aggregate Functions
GROUP BY is applied after computing results of a query.
Sometimes it is required to retrieve tuples based on some aggregate
property. For this, the HAVING clause is useful:
SELECT DNO, COUNT(*), AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*) > 20;
Return all departments having more than twenty employees, and
show the number of employees and their average salary.
Aggregate Functions
HAVING versus WHERE:
WHERE conditions apply to individual tuples independently.
HAVING conditions apply to groups of tuples.
SELECT Overall Form
SELECT <attribute and function list>
FROM <table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY <attribute list>];
Constructs within box braces are optional.
Thanks

SQL Database- Heba-14.pptx - database slide training

  • 1.
  • 2.
    What is DataBase ???? Data Base: an organized collection of related data we need to use the most less space to store the data - we need to retrieve the data in the fastest time
  • 3.
    The Relational Model ♦ Oneor more Tables represent data and the relationships amongst different data ♦ A table is a collection of records in a Database ♦ A table has multiple columns ♦ Each column has a unique name, and contains sets of data ♦ Every set is called a row ♦ The value of the data is got by the intersection of a row and a column
  • 5.
    Database Design Physical Design LogicalDesign Conceptual Design Requirements collection
  • 6.
  • 7.
    ♦ Entities are objectsof the real world relevant to the information system ♦ The properties of an entity are its Attributes and this determines the data that is to be stored ♦ Actual data can be described as the values of attributes of entity Entities and Relationships
  • 8.
    Components of ERDiagram 1- Entities 3- Relationships 2- Attributes
  • 9.
    Slide 3 - 9 Summary ofthe notation for ER diagrams .
  • 10.
    Slide 3 - 10 ER diagramsfor the COMPANY schema, with structural constraints specific using (min, max) notation .
  • 11.
    ♦ ER modeling isa good aid for designing databases ♦ An ER model is a Graphical representation of the system ♦ It is a high-level conceptual data model ♦ An ER model also supports a user’s perception of data Why ER Diagrams?
  • 12.
    1 - Entities ♦ Two typesof entities – Strong entity type – Weak entity type Strong Entity weak Entity ♦ Entities are objects of the real world relevant to the information system • An Entity represents a discrete object. • Entities can be thought of as nouns. • Examples: a computer, an employee, a song
  • 13.
    Strong Entity STRONG entity is anentity that uniquely identified by its own attributes alone
  • 14.
    a Weak entity Aweak entity is an entity that can't be uniquely identified by its own attributes alone; therefore, it must use a foreign key in conjunction with its attributes to create a primary key. The foreign key is typically a primary key of an entity it is related to. weak Entity
  • 15.
    2 - Attributes Attribute : isa property of the entity or of the relationship that is interesting in a specific context Student name Student ID Student Entities and relationships can both have attributes. Examples: an employee entity might have a social security number attribute the proved relationship may have a date attribute . Attributes are drawn as ovals connected to their owning entity sets by a line . student Studebt ID Student name
  • 16.
    Keys - Super key: a superkey is a set of columns within a table whose values can be used to uniquely identify - Candidate Key: is a minimal set of columns necessary to identify a row 1- primary key : it’s A unique key must uniquely identify all possible rows that exist in a table and not only the currently existing rows. Example of unique keys are Social Security numbers Note : it does not allow null. Kinds (simple-composite) name sn Date of birth address ID
  • 17.
    2 - Foreign keys a foreignkey is a reference to a key in another table a foreign key (FK) is a referential constraint between two tables. The FK identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) Emp_id Emb_name Dept_id Man_id Dept_id Dept_ name ( PK ) ( FK )
  • 18.
    3 - Relationships Relationships represent aset of connections between objects Student write Exam Relationships can be thought of as verbs. Examples: a performs relationship between an artist and a song, a proved relationship between a mathematician and a theorem. relationships are drawn as diamonds Student write Exam
  • 19.
    Types of Relationships(cardinality) • One-to-One Relationship • One-to-Many Relationship • Many to Many Relationship
  • 20.
    Degree of Relationship 1 - UnaryRelationship Emp_id Emb name Dept_id Man_id Every Employee has a Manager and the Manager is an Employee his self
  • 21.
    2 - Binary Relationship Every employeework in a department and the department has a specific entity Emp_id Emb_name Dept_id Man_id Dept_id Dept_ name
  • 22.
  • 23.
    1 - Identify entities 2 - Remove duplicateentities 3 - List the attributes of each entity 4 - Mark the primary keys 5 - Define the relationships 6 - Examine each entity type to see how it is related to others 7 - Describe the cardinality(1:1 or 1:m) of the relationships 8 - Remove redundant relationships http://www.databaseanswers.org/data_models/index.htm Constructing an ER Model
  • 24.
  • 25.
    What is Normalization? Theprocess of efficiently organizing data in a database. There are two goals of the normalization process: 1. Storing the same data in more than one table. 2. Storing related data in a table. Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
  • 26.
    Normalizing an exampletable 1- Unnormalized table These steps demonstrate the process of normalizing a fictitious student table. Class3 Class2 Class1 Adv-Room Advisor Student# 159-02 143-01 101-07 412 Jones 1022 214-01 211-02 201-01 216 Smith 4123
  • 27.
    (1NF) sets thevery basic rules for an organized database: Eliminate duplicative columns from the same table. Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). 2- First Normal Form No Repeating Groups Tables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble.
  • 28.
    Spreadsheets often usethe third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below: Class# Adv- Room Adviso r Student # 101- 07 412 Jones 1022 143- 01 412 Jones 1022 159- 02 412 Jones 1022 201- 01 216 Smith 4123
  • 29.
    (2NF) further addressesthe concept of removing duplicative data: 3- Second Normal Form Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in separate tables. Create relationships between these new tables and their predecessors through the use of foreign keys.
  • 30.
    Students Adv-Room Adviso r Student# 412 Jones 1022 216Smith 4123 Registration Class# Student# 101- 07 1022 143- 01 1022 159- 02 1022 201- 01 4123 211-02 4123 214- 01 4123 The following two tables demonstrate second normal form:
  • 31.
    (3NF) goes onelarge step further: Meet all the requirements of the second normal form. Remove columns that are not dependent upon the primary key. 4- Third Normal Form Eliminate Data Not Dependent On Key In the last example, Adv-Room (the advisor's office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below: Students Faculty Adviso r Student # Jones 1022 Smith 4123 Dep t Roo m Name 42 412 Jones 42 216 Smith
  • 32.
    Assignment • Draw theER model of a car reservation company.!!!
  • 33.
  • 34.
    About SQL • Standsfor Structured Query Language • Developed at IBM Research for System R • Includes features of relational algebra and tuple relational calculus • The standard for relational data access • DBMS independent
  • 35.
  • 36.
    DDL ♦ Data definitionlanguage ♦ CREATE CREATE TABLE toys ( buyerid INTEGER NOT NULL , item CHAR(40) NOT NULL ;) ♦ ALTER ALTER TABLE toys ADD COLUMN sellerid integer ♦ DROP DROP TABLE toys
  • 37.
    DCL ♦ Data controllanguage ♦ Controls and monitors data access ♦ Ensures data security ♦ Prevents illegal access to data ♦ Some of the SQL commands are : – GRANT – REVOKE .
  • 38.
    DML ♦ Data Manipulation language – INSERT INSERTINTO toys VALUES (21, 01,'barbie', 200.00) INSERT INTO toys (buyerid, item,sellerid) VALUES (01,'barbie',21) ; – DELETE DELETE FROM toys WHERE item = 'Barbie ' – UPDATE UPDATE toys SET price = 500.00 WHERE item = 'Chair';
  • 39.
    DQL ♦ Data Query language ♦ SimpleSELECT – Retrieves data from tables – Can be a simple, or a conditional SELECT SELECT * FROM table_name ; SELECT colname1, colname2, …, colnamen FROM table_name ;
  • 40.
    Conditional Selection ♦ Specifies theconditional SELECT statement using the WHERE clause SELECT * FROM TABLE_NAME WHERE OL_NAME = VALUE ;
  • 41.
    The Relational OperatorsOperator Meaning = Equal to < Less than =< Less than or Equal to > Greater than => Greater than or equal to >< or != Not equal to
  • 42.
    Aggregate Functions ♦ They arealso called group functions ♦ They work on sets of rows and fetch results ♦ Important functions are SUM, AVG, MAX , MIN, and COUNT
  • 43.
    Compound Conditions andLogical Operators ♦ The AND Operator SELECT employeeidno FROM employeestatistics WHERE salary > 40000 AND position = 'Staff ‘ ♦ The OR Operator SELECT employeeidno FROM employeestatistics WHERE salary < 40000 OR benefits < 10000 ♦ The IN Operator SELECT employeeidno FROM employeestatistics WHERE position IN ('Manager', 'Staff')
  • 44.
    ♦ the BETWEEN operator SELECTemployeeidno FROM employeestatistics WHERE salary BETWEEN 30000 AND 50000 The NOT Operator SELECT employeeidno FROM employeestatistics WHERE salary NOT BETWEEN 30000 AND 50000
  • 45.
    The LIKE Operator SELECTemployeeidno FROM employeeaddress WHERE lastname LIKE 'S ‘% The CONCATENATION Operator SELECT firstname || ‘.’ || lastname FROM employeeaddress first_name || ‘.’ || last_name Alias Column Names SELECT firstname || ‘.’ || lastname AS “Full Name“ FROM employeeaddress
  • 46.
    The ORDER BYClause ♦ Formats the output based on one field in a certain order, descending or ascending SELECT * FROM employeestatistics ORDER BY salary ASC SELECT * FROM employeestatistics ORDER BY salary DESC The DISTINCT Clause SELECT DISTINCT position FROM employeestatistics
  • 47.
    The JOIN Condition The"Persons" table: The "Orders" table: P_Id LastName FirstName Address City 1 Ahmed Abdalla Smouha 10 Alexandria 2 Mostafa Tarek Roshdy 23 Alexandria 3 Mohamed Karim Sporting 20 Alex O_Id OrderNo P_Id 1 77895 3 2 44678 3 3 22456 1 4 24562 1 5 34764 15 Example
  • 48.
    The JOIN Conditioncont . 1– Cartesian SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons, Orders LastName FirstName OrderNo Ahmed Abdalla 77895 Mostafa Tarek 44678 Mohamed Karim 22456 Ahmed Abdalla 44678 Mostafa Tarek 22456 Mohamed Karim 24562 Ahmed Abdalla 22456 Mostafa Tarek 24562 Mohamed Karim 34764 Ahmed Abdalla 24562 Mostafa Tarek 34764 Mohamed Karim 77895 Ahmed Abdalla 34764 Mostafa Tarek 77895 Mohamed Karim 44678
  • 49.
    Now we wantto list all the persons with any orders. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed. LastName FirstName OrderNo Ahmed Abdalla 22456 Ahmed Abdalla 24562 Mohamed Karim 77895 Mohamed Karim 44678 2– INNER The JOIN Condition cont .
  • 50.
    3– RIGHT OUTER Nowwe want to list all the orders with containing persons - if any, from the tables above. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Persons). LastName FirstName OrderNo Ahmed Abdalla 22456 Ahmed Abdalla 24562 Mohamed Karim 77895 Mohamed Karim 44678 34764 The JOIN Condition cont .
  • 51.
    4– LEFT OUTER Nowwe want to list all the persons and their orders - if any, from the tables above. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in the right table (Orders). LastName FirstName OrderNo Ahmed Abdalla 22456 Ahmed Abdalla 24562 Mohamed Karim 77895 Mohamed Karim 44678 Mostafa Tarek The JOIN Condition cont .
  • 52.
    5– FULL OUTER Nowwe want to list all the persons and their orders, and all the orders with their persons. We use the following SELECT statement: SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName The result-set will look like this: The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Persons", those rows will be listed as well. LastName FirstName OrderNo Ahmed Abdalla 22456 Ahmed Abdalla 24562 Mohamed Karim 77895 Mohamed Karim 44678 Mostafa Tarek 34764 The JOIN Condition cont .
  • 53.
    6– SELF We usethe following SELECT statement: SELECT concat(e.firstname, e.lastname) employee, concat(m.firstname,m.lastname) manager FROM employees e, employees m WHERE m.employeeId = e.reportsTo The result-set will look like this: Employee Manager Ahmed Abdalla Osama Mohamed Karim Sherif Mostafa Tarek Mona The JOIN Condition cont .
  • 54.
    The GROUP BYClause SELECT buyerid, COUNT(item) AS items FROM toys GROUP BY buyerid The HAVING Clause SELECT buyerid , COUNT(item) AS items FROM toys GROUP BY buyerid HAVING COUNT(item) > 2
  • 55.
    Writing Sub-queries SELECT itemFROM toys WHERE buyerid=(select ownerid FROM toysowners WHERE firstname=’Bob’) Correlated Sub-Queries SELECT dept.name FROM dept WHERE EXISTS (SELECT dept_id FROM emp WHERE emp.dept_id = dept.dept_id
  • 56.
    Schema and Catalogs Supportfor creating and maintaining schemas are provided from SQL2. A schema is created by a CREATE SCHEMA command. For example: CREATE SCHEMA UNIV AUTHORIZATION dean; Creates a schema “UNIV” owned by the user with userid “dean”. A catalog is a named collection of schemas. Referential integrity constraints can be defined across schemas only if they belong to the same catalog.
  • 57.
    Table Creation A newrelation can be created using the CREATE TABLE command. The general syntax is as follows: CREATE TABLE [schema.]table_name [{column descriptions}]; Example: CREATE TABLE UNIV.DEPARTMENT;
  • 58.
    Data Types andDomains (SQL2) Primitive data types in SQL2 include: Numeric (int, smallint, float, real, double precision) Formatted numbers (decimal(i,j), numeric(i,j)) Character string of either fixed length (char(n)) or of varying length (varchar(n)) Date, time and timestamp Text …
  • 59.
    Constraints and DefaultValues • The NOT NULL constraint on an attribute disallows NULL as a valid value • The DEFAULT construct specifies the default value of an attribute • The PRIMARY KEY construct specifies one or more attributes as the primary key • The UNIQUE construct specifies alternate (secondary) keys • The FOREIGN KEY construct ensures referential integrity
  • 60.
    Table Creation Example CREATETABLE EMPLOYEE ( PANNO VARCHAR(16) NOT NULL, UNIQUE, EMPNO INT(6) NOT NULL, NAME VARCHAR (40), GENDER CHAR, DOB DATE, ADDRESS VARCHAR(100), SALARY DECIMAL(8,2), REPORTSTO INT(6), PRIMARY KEY (EMPNO), FOREIGN KEY (REPORTSTO) REFERENCES EMPLOYEE (EMPNO));
  • 61.
    Table Deletion Tables candropped (deleted) using the DROP TABLE command: DROP TABLE NAME [DEPENDENT {CASCADE | RESTRICT}]; The above command drops the table specified by NAME. If the CASCADE option is provided, then any foreign-key constraints and views that reference the table will also be dropped. If RESTRICT option is specified, then the table is dropped only if it does not have any incoming references.
  • 62.
    Schema Deletion Schemata candropped (deleted) using the DROP SCHEMA command: DROP SCHEMA NAME {CASCADE | RESTRICT}; The above command drops the schema specified by NAME. If the CASCADE option is provided, then all tables in the schema will be automatically dropped. If RESTRICT option is specified, then the schema is dropped only if it does not have any elements.
  • 63.
    The SELECT Operation TheSELECT-FROM-WHERE form: SELECT <attribute list> FROM <table list> WHERE <condition>; Example: SELECT EMPNO, NAME FROM EMPLOYEE WHERE REPORTSTO = ‘007’;
  • 64.
    The SELECT Operation TheSELECT-FROM-WHERE form can act on multiple tables as well. Consider the table DEPARTMENT shown below: CREATE TABLE DEPARTMENT ( DNO INT(6) NOT NULL, NAME VARCHAR(20), ADDRESS VARCHAR(60), HEAD INT(6), PRIMARY KEY (DNO), FOREIGN KEY HEAD REFERENCES EMPLOYEE(EMPNO));
  • 65.
    The SELECT Operation Considerthe following query: What is the name of the person who heads the “SUPPLIES” department? Note the use of the table name in order to disambiguate attributes having the same name. Table names need not be used where there is no ambiguity. SELECT EMPLOYEE.NAME FROM EMPLOYEE, DEPARTMENT WHERE EMPNO = HEAD AND DEPARTMENT.NAME = ‘SUPPLIES’;
  • 66.
    The SELECT Operation Whathappens when the same table has to be used multiple times? Consider the query: What is the name of the person to whom Arvind Kulkarni reports to? SELECT EMPLOYEE.NAME FROM EMPLOYEE, EMPLOYEE WHERE EMPLOYEE.NAME = ‘Arvind Kulkarni’ AND EMPLOYEE.REPORTSTO = EMPLOYEE.EMPNO; Ambiguous !
  • 67.
    The SELECT Operation Thesolution is to use “aliasing” of table names: SELECT BOSS.NAME FROM EMPLOYEE, EMPLOYEE AS BOSS WHERE EMPLOYEE.NAME = ‘Arvind Kulkarni’ AND EMPLOYEE.REPORTSTO = BOSS.EMPNO;
  • 68.
    The SELECT Operation Whenthe WHERE clause is omitted, SELECT acts as the project operator of relational algebra: SELECT NAME, PANNO FROM EMPLOYEE; Returns all rows in EMPLOYEE, but only the NAME and PANNO columns.
  • 69.
    The SELECT Operation Whenmore than one table is specified and WHERE is omitted, the result is equivalent to a project over the cross product of tables SELECT EMPLOYEE.NAME, DEPARTMENT.NAME FROM EMPLOYEE, DEPARTMENT; Returns rows associating all EMPLOYEE names with all DEPARTMENT names.
  • 70.
    The SELECT Operation Allcolumns of a table can be retrieved using the ‘*’ construct: SELECT * FROM EMPLOYEE WHERE NAME = ‘Bhadriah’; Returns the entire row for all EMPLOYEE relations where Name is “Bhadriah”. SELECT * FROM EMPLOYEE, DEPARTMENT; Returns the cross product of EMPLOYEE and DEPARTMENT.
  • 71.
    The INSERT Command Datatuples can be added to tables using the INSERT command. Example: INSERT INTO EMPLOYEE VALUES (‘1002’, 002, ‘Bharath Kumar’, ‘M’, ‘9-5-1973’, ‘Rajajinagar Bangalore 10’, 300000, 007, 5); Inserts an entire EMPLOYEE record with corresponding values.
  • 72.
    The INSERT Command Specificattributes can be populated by explicitly specifying them by name: INSERT INTO EMPLOYEE(NAME,ADDR,DNO) VALUES (‘Arun K’, ‘Yeshwanthpur’, 5); The other attributes will get either NULL values or their DEFAULT values. All attributes that are left out should hence not have NOT NULL constraint or must have the DEFAULT constraint.
  • 73.
    The INSERT Command Theresult of a SELECT query can be provided as data for an INSERT command: Consider the following table: CREATE TABLE EMD ( EMPLOYEE INT(6), MANAGER INT(6), DNO INTEGER);
  • 74.
    The INSERT Command Thefollowing INSERT dynamically creates data from a SELECT query for insertion: INSERT INTO EMD SELECT E.EMPNO AS EMPLOYEE, E.REPORTSTO AS MANAGER, D.DNUMBER AS DNO FROM EMPLOYEE AS E JOIN DEPARTMENT AS D ON E.DNO = D.DNUMBER;
  • 75.
    The INSERT Command •Inserts multiple instances of the same tuple if called multiple times as long as there is no violation of UNIQUE constraints • Insertion fails if referential integrity is violated • Multiple tuples can be inserted within a single INSERT command by enclosing each tuple within parentheses and separating tuples by a comma
  • 76.
    Deletion of Tuples Tuplescan be deleted from a table using the DELETE-FROM-WHERE command: DELETE FROM EMPLOYEE WHERE EMPNO=007; (deletes one tuple) DELETE FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE HEAD=007); (deletes possibly more than one tuples) DELETE FROM EMPLOYEE; (deletes all tuples)
  • 77.
    Updating of Tuples Tuplescan be modified using the UPDATE-SET-WHERE command: UPDATE EMPLOYEE SET SALARY = SALARY*1.1 WHEREREPORTSTO=007; Give a 10% raise in salary for all employees working under 007.
  • 78.
    Views (Virtual Tables) •A table that physically exists in a database is called a base table • A view or a virtual table is a table that is derived from other tables • The other tables could either be base tables or other views • Views need not be stored in the database as tables (but as queries) • Update operations to a view are limited; but querying is not
  • 79.
    Specification of Views Viewsare specified using the CREATE VIEW command: CREATE VIEW EMD(EMPL, MGR, DEPT) AS SELECT E.NAME, M.NAME, D.NAME FROM EMPLOYEE AS E, EMPLOYEE AS M, DEPARTMENT AS D WHERE E.REPORTSTO=M.EMPNO AND E.DNO=D.DNUMBER;
  • 80.
    Views • A viewis always up to date • Hence characterization of a view is not done during view definition time, but during query • Views can be deleted using the DROP VIEW command • Efficient implementation of views a tricky problem.
  • 81.
    Modifying Tables Table definitionscan be modified using the ALTER TABLE command. Example: ALTER TABLE COMPANY.EMPLOYEE ADD JOB VARCHAR(20); ..adds a new column to the EMPLOYEE table with the name job and domain VARCHAR of maximum size 20 characters.
  • 82.
    Modifying Tables Consider thefollowing example: ALTER TABLE COMPANY.EMPLOYEE ADD JOB VARCHAR(20); Unless a DEFAULT clause is specified, the value of the JOB attribute for all the tuples will be NULL. If no DEFAULT clause is specified, then the NOT NULL constraint cannot be used.
  • 83.
    Modifying Tables To dropcolumns, either the CASCADE or RESTRICT options should be used: ALTER TABLE COMPANY.EMPLOYEE DROP PANNO CASCADE; If CASCADE option is used, then all constraints and views that refer to the column (PANNO in this case) are also dropped automatically. If RESTRICT is used, then the column is dropped only if it does not have any referencing constraints or views.
  • 84.
    Modifying Tables It ispossible to alter a column definition by adding or dropping DEFAULT clauses: ALTER TABLE COMPANY.EMPLOYEE ALTER REPORTSTO SET DEFAULT “007”; or ALTER TABLE COMPANY.EMPLOYEE ALTER REPORTSTO DROP DEFAULT; All NULL values for a column are updated whenever a new DEFAULT is set.
  • 85.
    Tables as Sets Bydefault SQL treats relations (tables) as bags or multi-sets rather than sets. A tuple may appear multiple times in a table. The DISTINCT clause can be used to make the output into a set. SELECT DISTINCT NAME FROM EMPLOYEE;
  • 86.
    Tables as Sets Settheoretic operators UNION, INTERSECTION and EXCEPT denote operations union, intersection and set difference. They assume relations to be sets and not multi-sets. Note the use of DISTINCT in the following example: SELECT DISTINCT NAME FROM EMPLOYEE WHERE SALARY > 300000.00 UNION SELECT DISTINCT NAME FROM EMPLOYEE WHERE SALARY < 24000.00;
  • 87.
    Substring Comparison Partial stringscan be specified by embedding them around % symbols and compared using the LIKE comparator: SELECT * FROM EMPLOYEE WHERE NAME LIKE ‘%Arun%’; % symbol matches any number of characters. A single character can be matched by the underscore (_) symbol. … WHERE NAME LIKE ‘_arun__’;
  • 88.
    Arithmetic Operators Standard numericoperators like addition (+), subtraction (-), multiplication (*) and division (/) can be applied to attributes having numeric domains. The operators may also appear as part of the output table: SELECT 1.1 * SALARY FROM EMPLOYEE WHERE SALARY > 300000;
  • 89.
    Arithmetic Operators The BETWEENoperator can be used to check for numeric values within a given range: SELECT * FROM EMPLOYEE WHERESALARY BETWEEN 300000 AND 400000;
  • 90.
    Sorting Results Output ofa SELECT statement can be ordered (sorted) based on one or more attributes by using the ORDER BY clause: SELECT * FROM EMPLOYEE WHERE SALARY > 300000 ORDER BY NAME, EMPNO;
  • 91.
    Nested Queries Dynamically createdtables from SELECT queries can be used within other SELECT queries: SELECT NAME FROM DEPARTMENT WHERE DNUMBER IN (SELECT DNO FROM EMPLOYEE WHERESALARY > 300000); Highlighted query called the “nested query” and the non-highlighted query called “outer query”.
  • 92.
    Nested Queries Comparisons withan entire table of values can be performed using the ALL clause: SELECT NAME FROM EMPLOYEE WHERESALARY > ALL (SELECT SALARY FROM EMPLOYEE WHERE SUPERVISOR=‘007’); Returns the names of employees whose salaries are more than the salaries of all those who report to ‘007’
  • 93.
    Nested Queries Attribute namesand scope: Any unqualified attribute name in a nested query applies to the innermost block of the query: SELECT E.NAME FROM EMPLOYEE AS E WHEREE.EMPNO IN (SELECT REPORTSTO FROM EMPLOYEE WHERE E.NAME = NAME); Return all employee names who have the same name as their boss.
  • 94.
    Nested Queries The (NOT)EXISTS clause is used to check whether the result of a SELECT operation is empty or not: SELECT D.HEAD FROM DEPARTMENT AS D WHERENOT EXISTS (SELECT EMPNO FROM EMPLOYEE WHERE REPORTSTO=D.EMPNO); Return the set of all heads of departments who do not have anyone directly reporting to them.
  • 95.
    Explicit Sets Explicit setsof values for set theoretic operations can be specified using parentheses: SELECT NAME FROM EMPLOYEE WHERE REPORTSTO IN (‘007’, ‘008’, ‘009’); Returns the names of all employees who report to ‘007’, ‘008’ or ‘009’.
  • 96.
    Checking for NULLvalues NULL values of attributes can be checked by using the IS NULL or IS NOT NULL constructs. SELECT NAME, SALARY FROM EMPLOYEE AS E WHEREEXISTS (SELECT EMPNO FROM EMPLOYEE WHERE E.REPORTSTO = EMPNO AND REPORTSTO IS NULL); Return the names and salaries of people who report directly to the head of the company.
  • 97.
    Renaming Attributes The ASclause can be used to rename attributes in the same way as it can rename relations. SELECT NAME AS EMPLOYEE_NAME FROM EMPLOYEE; The renamed attribute will be displayed in the output result of the SELECT query.
  • 98.
    Aggregate Functions Aggregate functionslike COUNT, SUM, AVG, MAX and MIN operate on all tuples from the result and return a value: SELECT COUNT(SALARY), MIN(SALARY), MAX(SALARY), SUM(SALARY), AVG(SALARY) FROM EMPLOYEE; COUNT can be used on non-numeric attributes as well. MAX and MIN can also be used on non-numeric attributes if they have a total ordering defined (Ex: date, char, etc.)
  • 99.
    Aggregate Functions Since aggregatefunctions return a single value, they can be used as part of a condition in a WHERE clause: SELECT E.NAME FROM EMPLOYEE AS E WHERE (SELECT COUNT(*) FROM DEPARTMENT AS D WHERE D.HEAD=E.EMPNO) >= 2; Return the names of all employees who head two or more departments.
  • 100.
    Aggregate Functions In manycases, aggregate functions have to be applied to subgroups of tuples rather than all tuples. For this, the GROUP BY clause is useful: SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO; For each department, count the number of employees and their average salaries.
  • 101.
    Aggregate Functions GROUP BYis applied after computing results of a query. Sometimes it is required to retrieve tuples based on some aggregate property. For this, the HAVING clause is useful: SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO HAVING COUNT(*) > 20; Return all departments having more than twenty employees, and show the number of employees and their average salary.
  • 102.
    Aggregate Functions HAVING versusWHERE: WHERE conditions apply to individual tuples independently. HAVING conditions apply to groups of tuples.
  • 103.
    SELECT Overall Form SELECT<attribute and function list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>]; Constructs within box braces are optional.
  • 104.