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
âŚ
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
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
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
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
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
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
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
;
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.