Sei sulla pagina 1di 71

Chapter

Chapter
-
-
5
5
Structured Query Language
SQL
S. Nandagopalan, BIT S. Nandagopalan, BIT 2 2
Overview of SQL
Overview of SQL
It is a 4 GL It is a 4 GL
Oracle9i in specific Oracle9i in specific
DML DML
DDL DDL
Triggers and integrity constraints Triggers and integrity constraints
Embedded and Dynamic SQL Embedded and Dynamic SQL
Client Client- -Server Execution and remote database access Server Execution and remote database access
Transaction management Transaction management
Security Security
OODBMS features, Data mining, spatial data, and XML OODBMS features, Data mining, spatial data, and XML
data management data management
S. Nandagopalan, BIT S. Nandagopalan, BIT 3 3
Basic SQL Commands
8tatement
Description
3ELECT Data retrieal statement.
lN3ERT
uP0ATE
0ELETE
Data Manipulation Language
,DML,.
Add rows, change data, and delete
ew rows.
CREATE
ALTER
0R0P
RENAVE
Create new tables,iews, remoe
tables, iews, and change the
schema.
C0VVlT
R0LL8ACK
3AvEP0lNT
Modiied alues o database are
permanently written into disk,
rollback the changes made.
0RANT
REv0KE
Access control can be assigned or
changed.

S. Nandagopalan, BIT S. Nandagopalan, BIT 4 4
Basic data types in Oracle
0ala lype
Description
ClAR (s|ze) lixed length character. Max ~ 2000.
vARClAR2(s|ze Variable length character string. Max ~
4000.
0ATE Date. Vaild range is rom Jan 1, 412 B.C.
to Dec 31, 412 A.D.
8L08 Binary large object. Max ~ 4GB.
CL08 Character large object. Max ~ 4GB.
8FlLE Pointer to binary OS ile.
L0N0 Character data o ariable size. Max ~ 2GB.
L0N0 RAw
Raw binary data. Rest is same as L0N0.
NuV8ER(s|ze) Numbers. Max. size ~ 40 digits.
NuV8ER(s|ze,d) Numbers. Range ~ 1.0L-130 to 9.9L125.
0EClVAL
Same as NuV8ER. s|ze,d can't be speciied.
FL0AT
Same as NuV8ER.
lNTE0ER
Same as NuV8ER. s|ze,d can't be speciied.
3VALLlNT
Same as NuV8ER.

S. Nandagopalan, BIT S. Nandagopalan, BIT 5 5
Employee
Employee
33N Nare 80ale 3a|ary Vgr33N 0No
1111 0eepa| 5-Jar-2 22000 1111 1
2222 Nardagopa| 10-0ec-0 30000 1111 3
3333 Pooja 22-Jar-5 18000 2222 2
1111 Prasad 11-Jar-5Z 32000 Nu|| 3
5555 Reera 15-Jar-85 8000 1111 3



Example tables


0No 0Nare Loc
1 Adr|r Crerra|
2 Researcr 8arga|ore
3 Accourls 8arga|ore

Department
Department
S. Nandagopalan, BIT S. Nandagopalan, BIT 6 6
DDL
DDL
CREATE TABLE Department( CREATE TABLE Department(
DNo DNo number(3) not null, number(3) not null,
DName DName varchar2(10) not null, varchar2(10) not null,
Loc varchar2(15), Loc varchar2(15),
primary key ( primary key (DNo DNo)); ));
CREATE TABLE Employee( CREATE TABLE Employee(
SSN number(4) not null, SSN number(4) not null,
Name varchar2(20) not null, Name varchar2(20) not null,
BDate BDate date, date,
Salary number(10,2), Salary number(10,2),
MgrSSN MgrSSN number(4), number(4),
DNo DNo number(2) not null, number(2) not null,
primary key (SSN), primary key (SSN),
foreign key ( foreign key (MgrSSN MgrSSN) references ) references Employee(SSN Employee(SSN), ),
foreign key ( foreign key (DNo DNo) references ) references Department(DNo Department(DNo)); ));
S. Nandagopalan, BIT S. Nandagopalan, BIT 7 7
Data Retrieval Statement
Data Retrieval Statement
(SELECT)
(SELECT)
Syntax
Syntax
SELECT *|{[DISTINCT] column | expression} SELECT *|{[DISTINCT] column | expression}
FROM FROM table(s table(s); );
The basic SELECT statement must include
The basic SELECT statement must include
the following:
the following:
-
-
A SELECT clause.
A SELECT clause.
-
-
A FROM clause.
A FROM clause.
S. Nandagopalan, BIT S. Nandagopalan, BIT 8 8
Example
Example
-
-
1
1
SELECT * FROM
SELECT * FROM
Employee;
Employee;
The * indicates that it should retrieve all the
The * indicates that it should retrieve all the
columns from Employee table. The output of this
columns from Employee table. The output of this
query is shown below:
query is shown below:
Output
Output
-
-
1
1
SSN NAME BDATE SALARY MGRSSN DNO
---- -------------------- --------- --------- --------- ---------
4444 Prasad 11-JAN-57 32000 3
5555 Reena 15-JAN-85 8000 4444 3
1111 Deepak 05-JAN-62 22000 4444 1
2222 Nandagopal 10-DEC-60 30000 4444 3
3333 Pooja 22-JAN-65 18000 2222 2
S. Nandagopalan, BIT S. Nandagopalan, BIT 9 9
Example
Example
-
-
2
2
SELECT * FROM Employee
ORDER BY SSN;
Output
Output
-
-
2
2
SSN NAME BDATE SALARY MGRSSN DNO SSN NAME BDATE SALARY MGRSSN DNO
----- ----- -------------------- -------------------- --------- --------- --------- --------- --------- --------- --------------------------------- ---------------------------------
1111 Deepak 05 1111 Deepak 05- -JAN JAN- -62 22000 4444 62 22000 4444 1 1
2222 2222 Nandagopal Nandagopal 10 10- -DEC DEC- -60 30000 4444 60 30000 4444 3 3
3333 3333 Pooja Pooja 22 22- -JAN JAN- -65 18000 2222 65 18000 2222 2 2
4444 Prasad 11 4444 Prasad 11- -JAN JAN- -57 32000 57 32000 3 3
5555 5555 Reena Reena 15 15- -JAN JAN- -85 8000 4444 85 8000 4444 3 3
S. Nandagopalan, BIT S. Nandagopalan, BIT 10 10
Using arithmetic operators Using arithmetic operators
SELECT Name, Salary, Salary * 12 SELECT Name, Salary, Salary * 12
FROM FROM Employee; Employee;
Using aliases Using aliases
An alias when used for a column:
Renames a column heading
It is useful in arithmetic calculations.
AS keyword can optionally be used between column
name and alias name.
Example Example- -3 3
SELECT Name, Salary, Salary * 12 AS YRLY_SALARY
FROM Employee;
OR
SELECT Name, Salary, Salary * 12 "YRLY_SALARY"
FROM Employee;
S. Nandagopalan, BIT S. Nandagopalan, BIT 11 11
Example Example- -4 4
DESCRIBE Employee; DESCRIBE Employee;
OR OR
DESC Employee; DESC Employee;
Output Output- -4 4
Name Null? Type
------------------------------- -------- ----
SSN NOT NULL NUMBER(4)
NAME NOT NULL VARCHAR2(20)
BDATE DATE
SALARY NUMBER(10,2)
MGRSSN NUMBER(4)
DNO NOT NULL NUMBER(2)
S. Nandagopalan, BIT S. Nandagopalan, BIT 12 12
Select Statement with Where
Select Statement with Where
Example
Example
-
-
5
5
SELECT
SELECT
Name, Salary
Name, Salary
FROM
FROM
Employee
Employee
WHERE
WHERE
Salary > 25000;
Salary > 25000;
Example
Example
-
-
6
6
SELECT
SELECT
DName
DName
, Loc
, Loc
FROM
FROM
Department
Department
WHERE
WHERE
Loc = 'Bangalore';
Loc = 'Bangalore';
Example
Example
-
-
7
7
SELECT
SELECT
Name,
Name,
BDate
BDate
FROM
FROM
Employee
Employee
WHERE
WHERE
BDate
BDate
= '11
= '11
-
-
Jan
Jan
-
-
57';
57';
S. Nandagopalan, BIT S. Nandagopalan, BIT 13 13
Example Example- -8 8
SELECT SELECT Name, Name, BDate BDate
FROM FROM Employee Employee
WHERE WHERE Salary BETWEEN 25000 AND 30000; Salary BETWEEN 25000 AND 30000;
Example Example- -9 9
SELECT SELECT SSN, Name SSN, Name
FROM FROM Employee Employee
WHERE WHERE DNo DNo IN (1, 2); IN (1, 2);
Example Example- -10 10
SELECT SELECT Name Name
FROM FROM Employee Employee
WHERE WHERE Name LIKE 'P%'; Name LIKE 'P%';
Example Example- -11 11
SELECT SELECT Name, Name, DNo DNo
FROM FROM Employee Employee
WHERE WHERE BDate BDate LIKE '__ LIKE '__- -JAN JAN- -__'; __';
S. Nandagopalan, BIT S. Nandagopalan, BIT 14 14
Example Example- -12 12
SELECT SELECT Name Name
FROM FROM Employee Employee
WHERE WHERE MgrSSN MgrSSN IS NULL; IS NULL;
Example Example- -13 13
SELECT SELECT Name, Salary, Name, Salary, DNo DNo
FROM FROM Employee Employee
WHERE WHERE Salary > 30000 AND Salary > 30000 AND DNo DNo = 3; = 3;
Example Example- -14 14
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Name LIKE 'P%' OR Salary <= 20000; Name LIKE 'P%' OR Salary <= 20000;
Example Example- -15 15
SELECT SELECT Name, Salary, Name, Salary, DNo DNo
FROM FROM Employee Employee
ORDER BY ORDER BY DNo DNo DESC, Name; DESC, Name;
S. Nandagopalan, BIT S. Nandagopalan, BIT 15 15
SQL Functions
SQL Functions
ROUND(column ROUND(column | | expr expr, n) , n) Rounds to n decimal places. If n is negative, Rounds to n decimal places. If n is negative,
numbers to the left are rounded. numbers to the left are rounded.
TRUNC(column TRUNC(column | | expr expr, n) , n) Truncates to n decimal places. Truncates to n decimal places.
MOD(m MOD(m, n) , n) Returns the remainder of Returns the remainder of m/n m/n. .
ABS(n ABS(n) ) Absolute value of n. Absolute value of n.
CEIL(n CEIL(n) ) Smallest integer larger than n. Smallest integer larger than n.
FLOOR(n FLOOR(n) ) Largest integer smaller than n. Largest integer smaller than n.
EXP(n EXP(n) ) en en
POWER(n POWER(n, m) , m) nm nm
SQRT(n SQRT(n) ) Square root of n. Square root of n.
SIGN(n SIGN(n) ) 1 if n is positive, 1 if n is positive, - -1 if negative, 0 if zero. 1 if negative, 0 if zero.
LN(n LN(n) ) Natural log of n ( Natural log of n (lg lg n) n)
LOG(n LOG(n) ) log10 n log10 n
SIN(n SIN(n) ) Sine of n. Sine of n.
COS(n COS(n) ) Cosine of n. Cosine of n.
TAN(n TAN(n) ) Tangent of n. Tangent of n.
ASIN(n ASIN(n) ) Arc sine of n (in radians). Arc sine of n (in radians).
ACOS(n ACOS(n) ) Arc cosine of n (in radians). Arc cosine of n (in radians).
ATAN(n ATAN(n) ) Arc tangent of n (in radians). Arc tangent of n (in radians).
SINH(n SINH(n) ) Hyperbolic sine value of n. Hyperbolic sine value of n.
COSH(n COSH(n) ) Hyperbolic cosine value of n. Hyperbolic cosine value of n.
TANH(n TANH(n) ) Hyperbolic tan value of n. Hyperbolic tan value of n.
NVL(n NVL(n, m) , m) Null Value Null Value Substitute m for n if n = null. Substitute m for n if n = null.
VSIZE(n VSIZE(n) ) Storage size of n. Storage size of n.
S. Nandagopalan, BIT S. Nandagopalan, BIT 16 16
Working with Dates
Working with Dates
Century
Century
19
19
Year
Year
99
99
Month
Month
07
07
Day
Day
23
23
Hour
Hour
4
4
Minute
Minute
10
10
Second
Second
53
53
SELECT SYSDATE
SELECT SYSDATE
FROM
FROM
DUAL;
DUAL;
S. Nandagopalan, BIT S. Nandagopalan, BIT 17 17
Example Example- -16 (MONTHS_BETWEEN) 16 (MONTHS_BETWEEN)
SELECT MONTHS_BETWEEN(SYSDATE, '09 SELECT MONTHS_BETWEEN(SYSDATE, '09- -JAN JAN- -1983') 1983')
"Experience" "Experience"
FROM DUAL; FROM DUAL;
Output Output- -16 16
Experience Experience
--------------- ---------------
247.73471 247.73471
Example Example- -17 (GREATEST & LEAST) 17 (GREATEST & LEAST)
The function GREATEST finds the earliest date and LEAST finds The function GREATEST finds the earliest date and LEAST finds
the oldest date in the list. the oldest date in the list.
SELECT GREATEST('10 SELECT GREATEST('10- -JAN JAN- -93', '10 93', '10- -JAN JAN- -98'), 98'),
LEAST('10 LEAST('10- -JAN JAN- -93', '10 93', '10- -JAN JAN- -98') 98')
FROM DUAL; FROM DUAL;
Output Output- -17 17
GREATEST( LEAST('10 GREATEST( LEAST('10
--------- --------- --------- ---------
10 10- -JAN JAN- -98 10 98 10- -JAN JAN- -93 93
S. Nandagopalan, BIT S. Nandagopalan, BIT 18 18
Conversion Functions
Conversion Functions
VARCHAR2 or CHAR is converted to NUMBER
VARCHAR2 or CHAR is converted to NUMBER
VARCHAR2 or CHAR is converted to DATE
VARCHAR2 or CHAR is converted to DATE
NUMBER is converted to VARCHAR2
NUMBER is converted to VARCHAR2
DATE is converted to VARCHAR2
DATE is converted to VARCHAR2
S. Nandagopalan, BIT S. Nandagopalan, BIT 19 19
Use of TO_CHAR
Use of TO_CHAR
TO_CHAR function converts a date format to a character TO_CHAR function converts a date format to a character
string string
Example Example- -18 18
SELECT SELECT Name, Name, Bdate Bdate, , TO_CHAR(BDate TO_CHAR(BDate, ,
'DD/MM/YY') AS "Formatted" 'DD/MM/YY') AS "Formatted"
FROM FROM Employee Employee
WHERE WHERE SSN = 2222; SSN = 2222;
Example Example- -19 19
SELECT SELECT Name, Name, Bdate Bdate, , TO_CHAR(BDate TO_CHAR(BDate, 'Month, , 'Month, ddth ddth, YYYY') , YYYY')
AS "Formatted" AS "Formatted"
FROM FROM Employee Employee
WHERE WHERE Name = ' Name = 'Pooja Pooja'; ';
Output Output- -19 19
NAME BDATE Formatted NAME BDATE Formatted
-------------------- -------------------- --------- --------- --------------------- ---------------------
Pooja Pooja 22 22- -JAN JAN- -65 January , 22nd, 1965 65 January , 22nd, 1965
S. Nandagopalan, BIT S. Nandagopalan, BIT 20 20
Example
Example
-
-
20
20
SELECT
SELECT Name, Name, Bdate Bdate, , TO_CHAR(BDate TO_CHAR(BDate, ' , 'fmMonth fmMonth, , fmddth fmddth, YYYY') AS , YYYY') AS
"Formatted" "Formatted"
FROM
FROM
Employee;
Employee;
Output
Output
Prasad 11
Prasad 11
-
-
JAN
JAN
-
-
57 January, 11th, 1957
57 January, 11th, 1957
Example
Example
-
-
21
21
SELECT
SELECT Name, Name, Bdate Bdate, , TO_CHAR(BDate TO_CHAR(BDate, ' , 'fmMonth fmMonth, , fmddth fmddth, YYYY , YYYY
"at" HH:MI P.M.')AS "Formatted" "at" HH:MI P.M.')AS "Formatted"
FROM
FROM
Employee
Employee
WHERE SSN = 2222;
WHERE SSN = 2222;
Output
Output
Nandagopal Nandagopal 10 10- -DEC DEC- -60 December, 10th, 1960 at 12:00 A.M. 60 December, 10th, 1960 at 12:00 A.M.
Note: Note: fm fm suppresses unnecessary blanks suppresses unnecessary blanks
Use HH12 for 12 hrs clock and HH24 for 24 hrs clock Use HH12 for 12 hrs clock and HH24 for 24 hrs clock
S. Nandagopalan, BIT S. Nandagopalan, BIT 21 21
Use of TO_DATE
Use of TO_DATE
TO_DATE function is to convert any character literal string into TO_DATE function is to convert any character literal string into a a
valid date format. valid date format.
Example Example- -22 22
SELECT SELECT TO_DATE('1 TO_DATE('1- -Sep Sep- -2003', 'DD/MM/YYYY') 2003', 'DD/MM/YYYY')
FROM FROM DUAL; DUAL;
Output Output- -22 22
TO_DATE(' TO_DATE('
--------- ---------
01 01- -SEP SEP- -03 03
Example Example- -23 23
SELECT SELECT TO_DATE('08/30/2003', 'DD/MM/YYYY') TO_DATE('08/30/2003', 'DD/MM/YYYY')
FROM FROM DUAL; DUAL;
Output Output- -23 23
ERROR at line 1: ERROR at line 1:
ORA ORA- -01843: not a valid month 01843: not a valid month
S. Nandagopalan, BIT S. Nandagopalan, BIT 22 22
Character Functions
Character Functions
Program Output
SELECT LOWER('Bangalore')
FROM DUAL;
bangalore


SELECT UPPER('Bangalore')
FROM DUAL;
BANGALORE


SELECT INITCAP('bangalore
institute of technology')
FROM DUAL;
Bangalore Institute Of
Technology


SELECT CONCAT('Database ',
'Management')
FROM DUAL;
Database Management


SELECT SUBSTR('Database', 5, 4)
FROM DUAL;
base
SELECT LENGTH('Database')
FROM DUAL;
8


SELECT INSTR('Database', 'b')
FROM DUAL;
5

SELECT INSTR('Database', 'x')
FROM DUAL;
0


SELECT LPAD(Salary, 8, '*')
FROM Employee
WHERE SSN = 1111;
***22000



SELECT RPAD(Salary, 8, '*')
FROM Employee
WHERE SSN = 1111;
22000***


SELECT LTRIM(' Database', ' ') Database
S. Nandagopalan, BIT S. Nandagopalan, BIT 23 23
Aggregate Functions
Aggregate Functions
COUNT
COUNT
AVG
AVG
MAX
MAX
MIN
MIN
STDDEV
STDDEV
SUM
SUM
VARIANCE
VARIANCE
S. Nandagopalan, BIT S. Nandagopalan, BIT 24 24
Example
Example
-
-
24
24
SELECT COUNT(*) AS "No. of Employees"
SELECT COUNT(*) AS "No. of Employees"
FROM
FROM
Employee;
Employee;
Example
Example
-
-
25
25
SELECT
SELECT
SUM(Salary
SUM(Salary
) AS Total
) AS Total
FROM
FROM
Employee;
Employee;
Example
Example
-
-
26
26
SELECT
SELECT
Name
Name
,
,
MAX(Salary
MAX(Salary
),
),
MIN(Salary
MIN(Salary
)
)
FROM
FROM
Employee;
Employee;
S. Nandagopalan, BIT S. Nandagopalan, BIT 25 25
GROUP BY Clause
GROUP BY Clause
The rules to be followed while using GROUP BY
The rules to be followed while using GROUP BY
clause are given below:
clause are given below:
You can't have non-group function or column in
SLLLC1 clause.
Group functions ignore nulls.
By default the result of GROUP BY clause sort the
data in ascending order.
Example:
SELECT SELECT DNo DNo, , SUM(Salary SUM(Salary), COUNT(*), ), COUNT(*), AVG(Salary AVG(Salary) )
FROM FROM Employee Employee
GROUP BY GROUP BY DNo DNo; ;
S. Nandagopalan, BIT S. Nandagopalan, BIT 26 26
Example
Example
-
-
27
27
SELECT
SELECT
DNo
DNo
,
,
SUM(Salary
SUM(Salary
), COUNT(*),
), COUNT(*),
AVG(Salary
AVG(Salary
)
)
FROM
FROM
Employee
Employee
GROUP BY
GROUP BY
DNo
DNo
,
,
MgrSSN
MgrSSN
;
;
HAVING clause
HAVING clause
SELECT
SELECT
DNo
DNo
,
,
AVG(Salary
AVG(Salary
)
)
FROM
FROM
Employee
Employee
GROUP BY
GROUP BY
DNo
DNo
HAVING
HAVING
DNo
DNo
= 3;
= 3;
S. Nandagopalan, BIT S. Nandagopalan, BIT 27 27
The order of evaluation when all the clauses are
The order of evaluation when all the clauses are
specified is given below:
specified is given below:
1.
1.
First all rows matching the WHERE conditions
First all rows matching the WHERE conditions
are retrieved.
are retrieved.
2.
2.
These rows are grouped using the
These rows are grouped using the
column(s
column(s
) in
) in
GROUP BY clause.
GROUP BY clause.
3.
3.
Finally, groups matching the HAVING clause
Finally, groups matching the HAVING clause
condition are retained.
condition are retained.
SELECT
SELECT
DNo
DNo
,
,
AVG(Salary
AVG(Salary
)
)
FROM
FROM
Employee
Employee
WHERE
WHERE
BDate
BDate
LIKE '__
LIKE '__
-
-
JAN
JAN
-
-
__'
__'
GROUP BY
GROUP BY
DNo
DNo
HAVING
HAVING
MAX(Salary
MAX(Salary
) > 10000;
) > 10000;
S. Nandagopalan, BIT S. Nandagopalan, BIT 28 28
MULTITABLE QUERIES
MULTITABLE QUERIES
Simple
Simple
Equi
Equi
-
-
Joins : guidelines
Joins : guidelines
Table names in the FROM clause is separated with Table names in the FROM clause is separated with
commas. commas.
Use appropriate joining condition. This means that the Use appropriate joining condition. This means that the
foreign key of table1 will be made equal to the foreign key of table1 will be made equal to the
primary key of table2. primary key of table2.
When the attributes or columns have the same When the attributes or columns have the same
names, tag them with table names using dot notation. names, tag them with table names using dot notation.
Without proper joining condition or attributes the SQL Without proper joining condition or attributes the SQL
will display the Cartesian product of the tables in the will display the Cartesian product of the tables in the
FROM clause. FROM clause.
S. Nandagopalan, BIT S. Nandagopalan, BIT 29 29
Example
Example
-
-
28: Display the employee names and
28: Display the employee names and
the department names for which they work
the department names for which they work
.
.
SELECT
SELECT
Name,
Name,
DName
DName
FROM
FROM
Employee, Department
Employee, Department
WHERE
WHERE
Employee.DNo
Employee.DNo
=
=
Department.DNo
Department.DNo; ;
Example
Example
-
-
29 : Display only employees working
29 : Display only employees working
for Accounts department.
for Accounts department.
SELECT
SELECT
Name, Salary,
Name, Salary,
DName
DName
FROM
FROM
Employee, Department
Employee, Department
WHERE
WHERE
(
(
Employee.DNo
Employee.DNo
=
=
Department.DNo
Department.DNo
)
)
AND (
AND (
DName
DName
= 'Accounts');
= 'Accounts');
S. Nandagopalan, BIT S. Nandagopalan, BIT 30 30
Self
Self
-
-
Join and Table Aliases
Join and Table Aliases
Example
Example
-
-
30 : Find the employee who earns
30 : Find the employee who earns
more than
more than

Nandagopal
Nandagopal

.
.
SELECT
SELECT
e1.Name, e1.Salary
e1.Name, e1.Salary
FROM
FROM
Employee e1, Employee e2
Employee e1, Employee e2
WHERE
WHERE
(e1.Salary > e2.Salary) AND
(e1.Salary > e2.Salary) AND
(e2.Name = '
(e2.Name = '
Nandagopal
Nandagopal
');
');
S. Nandagopalan, BIT S. Nandagopalan, BIT 31 31
Left
Left
-
-
Outer Join
Outer Join
Example Example- -31 : 31 :
SELECT SELECT Name, Name, DName DName
FROM FROM Employee E, Department D Employee E, Department D
WHERE WHERE E.Name E.Name = = D.DName D.DName(+); (+);
Output Output- -31 31
NAME DNAME NAME DNAME
-------------------- -------------------- ---------- ----------
Deepak Deepak
Nandagopal Nandagopal
Pooja Pooja
Prasad Prasad
Reena Reena
S. Nandagopalan, BIT S. Nandagopalan, BIT 32 32
Right
Right
-
-
Outer Join
Outer Join
Example
Example
-
-
32
32
SELECT
SELECT
Name,
Name,
DName
DName
FROM
FROM
Employee E, Department D
Employee E, Department D
WHERE
WHERE
E.Name
E.Name
(+) =
(+) =
D.DName
D.DName
;
;
Output
Output
-
-
32
32
NAME DNAME
NAME DNAME
--------------------
--------------------
----------
----------
Accounts
Accounts
Admin
Admin
Research
Research
S. Nandagopalan, BIT S. Nandagopalan, BIT 33 33
NESTED QUERIES or SUB QUERIES
NESTED QUERIES or SUB QUERIES
SELECT < SELECT <column(s column(s)> )>
FROM table FROM table
WHERE < WHERE <condn condn operator> operator>
(SELECT (SELECT <column> <column>
FROM FROM table); table);
Outer query uses the result of the inner query. Outer query uses the result of the inner query.
If the inner query returns only one row it is called as If the inner query returns only one row it is called as
single row sub queries single row sub queries. .
Alternatively if the inner query returns a set of rows Alternatively if the inner query returns a set of rows
(more than one row) it is classified as (more than one row) it is classified as multiple multiple- -row sub row sub
queries queries. .
The comparison condition may be a single row operator The comparison condition may be a single row operator
like >, =, >=, <, <=, <>) or multiple row operators like IN, like >, =, >=, <, <=, <>) or multiple row operators like IN,
ANY, ALL. ANY, ALL.
S. Nandagopalan, BIT S. Nandagopalan, BIT 34 34
Single
Single
-
-
Row Nested Queries
Row Nested Queries
Display the names of the employees working for Accounts Display the names of the employees working for Accounts
department. department.
SELECT SELECT Name Name
FROM FROM Employee Employee
WHERE WHERE DNo DNo = =
(SELECT (SELECT DNO DNO
FROM FROM Department Department
WHERE WHERE DName DName = 'Accounts'); = 'Accounts');
Display names of employees whose salary is greater than the Display names of employees whose salary is greater than the
employee SSN=1111. employee SSN=1111.
SELECT SELECT Name Name
FROM FROM Employee Employee
WHERE WHERE Salary > Salary >
(SELECT (SELECT Salary Salary
FROM FROM Employee Employee
WHERE WHERE Name = 1111); Name = 1111);
S. Nandagopalan, BIT S. Nandagopalan, BIT 35 35
Example
Example
-
-
33
33
Display all the employees drawing more
Display all the employees drawing more
than or equal to the average salary of
than or equal to the average salary of
department number 3.
department number 3.
SELECT
SELECT
Name, Salary
Name, Salary
FROM
FROM
Employee
Employee
WHERE
WHERE
Salary >=
Salary >=
(SELECT
(SELECT
AVG(Salary
AVG(Salary
)
)
FROM
FROM
Employee
Employee
GROUP BY
GROUP BY
DNO
DNO
HAVING
HAVING
DNo
DNo
= 3);
= 3);
S. Nandagopalan, BIT S. Nandagopalan, BIT 36 36
Multiple
Multiple
-
-
Row Nested Queries
Row Nested Queries
IN
IN
:
:
Equal to
Equal to
any
any
member in the list.
member in the list.
ANY
ANY
: Compare value to
: Compare value to
each
each
value
value
returned by the
returned by the
subquery
subquery
.
.
ALL
ALL
: Compare value to
: Compare value to
all
all
the
the
values
values
returned by the
returned by the
subquery
subquery
.
.
S. Nandagopalan, BIT S. Nandagopalan, BIT 37 37
Display the name of the highest paid
Display the name of the highest paid
employee.
employee.
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary Salary = =
(SELECT (SELECT MAX(Salary MAX(Salary) )
FROM FROM Employee); Employee);
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary Salary IN IN
(SELECT (SELECT MAX(Salary MAX(Salary) )
FROM FROM Employee); Employee);
Both '=' and 'IN' works, because the inner query produces a sing Both '=' and 'IN' works, because the inner query produces a single le
tuple tuple. .
S. Nandagopalan, BIT S. Nandagopalan, BIT 38 38
Find the Name and Salary of people who draw
Find the Name and Salary of people who draw
in the range
in the range
Rs
Rs
. 20,000 to
. 20,000 to
Rs
Rs
. 40,000
. 40,000
.
.
Select Name, Salary from Employee
Select Name, Salary from Employee
where Salary
where Salary
=
=
(Select Salary from Employee
(Select Salary from Employee
where Salary between 20000 and 40000);
where Salary between 20000 and 40000);
Error: ORA Error: ORA- -01427: single 01427: single- -row row subquery subquery returns more than one row returns more than one row
Correct Query: Correct Query:
Select Name, Salary from Employee
Select Name, Salary from Employee
where Salary
where Salary
IN
IN
(Select Salary from Employee
(Select Salary from Employee
where Salary between 20000 and 40000);
where Salary between 20000 and 40000);
S. Nandagopalan, BIT S. Nandagopalan, BIT 39 39
ANY and ALL
ANY and ALL
0perator Hean|ng Examp|e
<ANY
Less than the
maximum.
e ANY ,5,3,8,: e is less than any
single item in the list ,5,3,8,. Len
qualiies, because 8.
>ANY
More than
the minimum.
e ANY ,5,3,8,: e is less than any
single item in the list ,5,3,8,. Len
4 qualiies, because 4 3.
=ANY
Same as IN.
e ~ ANY,5,3,8,. All alues in the
list qualiy.
<ALL
Less than the
maximum.
e ALL ,5,3,8,: Anything below 3
qualiies.
>ALL
More than
the minimum.
e ALL ,5,3,8,: Anything greater
than 8 qualiies.
l=ALL
Not equal to
anything.
e !~ ,5,3,8,: Anything other than
5,3, and 8 qualiies.

S. Nandagopalan, BIT S. Nandagopalan, BIT 40 40
Example Example- -34: 34:
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary < ANY Salary < ANY
(SELECT (SELECT Salary Salary
FROM FROM Employee Employee
WHERE WHERE DNo DNo = 3); = 3);
Example Example- -35: 35:
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary > ANY Salary > ANY
(SELECT (SELECT Salary Salary
FROM FROM Employee Employee
WHERE WHERE DNo DNo = 3); = 3);
S. Nandagopalan, BIT S. Nandagopalan, BIT 41 41
Example Example- -35: 35:
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary < ALL Salary < ALL
(SELECT (SELECT Salary Salary
FROM FROM Employee Employee
WHERE WHERE DNo DNo = 3); = 3);
Example Example- -36: 36:
SELECT SELECT Name, Salary Name, Salary
FROM FROM Employee Employee
WHERE WHERE Salary > ALL Salary > ALL
(SELECT (SELECT Salary Salary
FROM FROM Employee Employee
WHERE WHERE DNo DNo = 3); = 3);
>ALL means greater than the greatest and <ALL means >ALL means greater than the greatest and <ALL means
less than the lowest value. less than the lowest value.
S. Nandagopalan, BIT S. Nandagopalan, BIT 42 42
CREATING and ALTERING
CREATING and ALTERING
DATABASE OBJECTS
DATABASE OBJECTS
Table
Table
: A tabular structure that stores data.
: A tabular structure that stores data.
View
View
: A tabular structure similar to a table
: A tabular structure similar to a table
but it is a collection of one or more tables.
but it is a collection of one or more tables.
Sequence
Sequence
: Automatically generates a
: Automatically generates a
sequence of numbers.
sequence of numbers.
Index
Index
: Provides an efficient access
: Provides an efficient access
structure.
structure.
S. Nandagopalan, BIT S. Nandagopalan, BIT 43 43
CREATE TABLE Employee(
CREATE TABLE Employee(
SSN
SSN
Number(4)
Number(4)
not null,
not null,
Name
Name
Varchar2(20)
Varchar2(20)
not null,
not null,
BDate
BDate
Date,
Date,
Salary
Salary
Number(10,2),
Number(10,2),
MgrSSN
MgrSSN
Number(4),
Number(4),
DNo
DNo
Number(2)
Number(2)
not null, Primary Key (SSN),
not null, Primary Key (SSN),
Foreign Key (
Foreign Key (
MgrSSN
MgrSSN
) references
) references
Employee(SSN
Employee(SSN
),
),
Foreign Key (
Foreign Key (
DNo
DNo
) references
) references
Department(DNo
Department(DNo
));
));
S. Nandagopalan, BIT S. Nandagopalan, BIT 44 44
Names of the tables/views Names of the tables/views
SELECT SELECT * *
FROM FROM TAB; TAB;
Schema details of a table Schema details of a table
DESC Employee; DESC Employee;
Name Null? Type Name Null? Type
------------------------------- ------------------------------- -------- -------- ---- ----
SSN NOT NULL NUMBER(4) SSN NOT NULL NUMBER(4)
NAME NOT NULL VARCHAR2(20) NAME NOT NULL VARCHAR2(20)
BDATE DATE BDATE DATE
SALARY NUMBER(10,2) SALARY NUMBER(10,2)
MGRSSN NUMBER(4) MGRSSN NUMBER(4)
DNO NOT NULL NUMBER(2) DNO NOT NULL NUMBER(2)
S. Nandagopalan, BIT S. Nandagopalan, BIT 45 45
ON DELETE constraint
ON DELETE constraint
CREATE TABLE Department(
CREATE TABLE Department(
DNo
DNo
Number(3) not null,
Number(3) not null,
DName
DName
Varchar2(10) not null,
Varchar2(10) not null,
Loc
Loc
Varchar2(15),
Varchar2(15),
Primary Key (
Primary Key (
DNo
DNo
),
),
Manager Number(4) references
Manager Number(4) references
Employee(SSN Employee(SSN) ON DELETE CASCADE); ) ON DELETE CASCADE);
Creating tables with a
Creating tables with a
Subquery
Subquery
CREATE TABLE
CREATE TABLE
Emp
Emp
AS
AS
SELECT SSN, Name, Salary
SELECT SSN, Name, Salary
FROM
FROM
Employee;
Employee;
S. Nandagopalan, BIT S. Nandagopalan, BIT 46 46
ALTER TABLE Statement
ALTER TABLE Statement
ALTER TABLE Employee
ALTER TABLE Employee
ADD Phone Number(7) not null;
ADD Phone Number(7) not null;
(Note: to add not null constraint, the column must be empty) (Note: to add not null constraint, the column must be empty)
ALTER TABLE Employee
ALTER TABLE Employee
MODIFY Phone Varchar2(10);
MODIFY Phone Varchar2(10);
(Note: to modify data type, the column must be empty) (Note: to modify data type, the column must be empty)
ALTER TABLE Employee
ALTER TABLE Employee
DROP COLUMN Phone;
DROP COLUMN Phone;
S. Nandagopalan, BIT S. Nandagopalan, BIT 47 47
Disabling and Enabling Constraints
Disabling and Enabling Constraints
CREATE TABLE Employee(
CREATE TABLE Employee(

Salary Number(10,2) CONSTRAINT


Salary Number(10,2) CONSTRAINT
Ch_Sal
Ch_Sal
CHECK (Salary > 0));
CHECK (Salary > 0));
ALTER TABLE Employee
ALTER TABLE Employee
DISABLE CONSTRAINT
DISABLE CONSTRAINT
Ch_Sal
Ch_Sal
;
;
ALTER TABLE Employee
ALTER TABLE Employee
ENABLE CONSTRAINT
ENABLE CONSTRAINT
Ch_Sal
Ch_Sal
;
;
S. Nandagopalan, BIT S. Nandagopalan, BIT 48 48
CREATE VIEW Statement
CREATE VIEW Statement
The advantages of using views are:
The advantages of using views are:
It restricts data access.
It restricts data access.
Reduces joining of more tables often.
Reduces joining of more tables often.
Many users can access a particular view with
Many users can access a particular view with
proper privileges.
proper privileges.
Example
Example
CREATE VIEW CREATE VIEW Emp_Dept Emp_Dept
AS SELECT AS SELECT SSN, Name, SSN, Name, DName DName, Salary , Salary
FROM FROM Employee E, Department D Employee E, Department D
WHERE WHERE E.DNo E.DNo = = D.DNo D.DNo; ;
View created. View created.
S. Nandagopalan, BIT S. Nandagopalan, BIT 49 49
Restrictions on Views
Restrictions on Views
There are few restrictions on views:
There are few restrictions on views:
You can not insert new rows nor update the view
You can not insert new rows nor update the view
table.
table.
(Error Message: ORA (Error Message: ORA- -01776: cannot modify more than one base 01776: cannot modify more than one base
table through a join view) table through a join view)
You can not alter the constraints or data types of
You can not alter the constraints or data types of
the columns.
the columns.
If any changes are made to the base
If any changes are made to the base
table(s
table(s
),
),
view table will get updated automatically.
view table will get updated automatically.
S. Nandagopalan, BIT S. Nandagopalan, BIT 50 50
CREATE SEQUENCE Statement
CREATE SEQUENCE Statement
How to use a Sequence? How to use a Sequence?
Step Step- -1: 1:
CREATE SEQUENCE CREATE SEQUENCE Dept_Seq Dept_Seq START WITH 10; START WITH 10;
Step Step- -2: 2:
INSERT INTO Department INSERT INTO Department
values(Dept_Seq.NEXTVAL values(Dept_Seq.NEXTVAL, 'Sales', ' , 'Sales', 'Belgaum Belgaum'); ');
Dropping a sequence Dropping a sequence
DROP SEQUENCE DROP SEQUENCE Dept_Seq Dept_Seq; ;
Creating an index for Employee table on Name Creating an index for Employee table on Name
CREATE INDEX IDXSSN ON Employee (Name); CREATE INDEX IDXSSN ON Employee (Name);
Dropping an index Dropping an index
DROP INDEX IDXSSN; DROP INDEX IDXSSN;
S. Nandagopalan, BIT S. Nandagopalan, BIT 51 51
Rights
Rights
SQL Server 2000 SQL Server 2000
GRANT { ALL | statement [ ,...n ] } GRANT { ALL | statement [ ,...n ] }
TO TO security_account security_account [ ,...n ] [ ,...n ]
Object permissions: Object permissions:
GRANT GRANT
{ ALL [ PRIVILEGES ] | permission [ ,...n ] } { ALL [ PRIVILEGES ] | permission [ ,...n ] }
{ {
[ ( column [ ,...n ] ) ] ON { table | view } [ ( column [ ,...n ] ) ] ON { table | view }
| ON { table | view } [ ( column [ ,...n ] ) ] | ON { table | view } [ ( column [ ,...n ] ) ]
| ON { | ON { stored_procedure stored_procedure | | extended_procedure extended_procedure } }
| ON { | ON { user_defined_function user_defined_function } }
} }
TO TO security_account security_account [ ,...n ] [ ,...n ]
[ WITH GRANT OPTION ] [ WITH GRANT OPTION ]
[ AS { group | role } ] [ AS { group | role } ]
S. Nandagopalan, BIT S. Nandagopalan, BIT 52 52
Rights (
Rights (
Contd
Contd

)
)
Oracle 9i: Oracle 9i:
GRANT { GRANT {objectprivileges objectprivileges | ALL} | ALL}
[( [(columnname columnname), { ), {objectprivileges(columnname objectprivileges(columnname)] )]
ON ON objectname objectname
TO TO {username | {username | rolename rolename | PUBLIC} | PUBLIC}
[WITH GRANT OPTION] [WITH GRANT OPTION]
where, where, objectprivileges objectprivileges: INSERT or UPDATE : INSERT or UPDATE
objectname objectname : table/view/sequence : table/view/sequence
Example: GRANT UPDATE ( Example: GRANT UPDATE (ssn ssn) ON employee TO bit; ) ON employee TO bit;
S. Nandagopalan, BIT S. Nandagopalan, BIT 53 53
Creating Users
Creating Users
1) 1)
CONNECT SYSTEM/MANAGER;
CONNECT SYSTEM/MANAGER;
2) 2)
CREATE USER Guest
CREATE USER Guest
IDENTIFIED BY bit;
IDENTIFIED BY bit;
3) 3)
GRANT CONNECT, RESOURCE TO Guest;
GRANT CONNECT, RESOURCE TO Guest;
4) 4)
REVOKE Select ON Employee FROM Guest;
REVOKE Select ON Employee FROM Guest;
Commit, Rollback, etc.
Commit, Rollback, etc.
S. Nandagopalan, BIT S. Nandagopalan, BIT 54 54
Examples
Examples
Objective
Objective

1
1
Create a user account called Create a user account called sng sng with password apple. with password apple.
create user create user sng sng identified by apple; identified by apple;
Format for Grant command Format for Grant command
grant {system privilege} to user [with admin options] grant {system privilege} to user [with admin options]
system privilege: select/delete/insert/update and instead of system privilege: select/delete/insert/update and instead of
user you can specify public as well. user you can specify public as well.
Format for Revoke command: Format for Revoke command:
revoke {system privilege} from user [with admin options] revoke {system privilege} from user [with admin options]
Revoking does not delete a user from Oracle or remove Revoking does not delete a user from Oracle or remove
any tables created by him. It simply prohibits him from any tables created by him. It simply prohibits him from
accessing the database. accessing the database.
S. Nandagopalan, BIT S. Nandagopalan, BIT 55 55
Examples (
Examples (
contd
contd

)
)
Objective
Objective

2
2
Create another user
Create another user
deepak
deepak
identified by rock.
identified by rock.
create user
create user
deepak
deepak
identified by rock;
identified by rock;
At this point of time you must provide grant
At this point of time you must provide grant
permission for connect and resource. Therefore
permission for connect and resource. Therefore
execute the following commands:
execute the following commands:
grant connect, resource to
grant connect, resource to
sng
sng
;
;
grant connect, resource to
grant connect, resource to
deepak
deepak
;
;
connect
connect
sng
sng
/apple;
/apple;
S. Nandagopalan, BIT S. Nandagopalan, BIT 56 56
Examples (
Examples (
contd
contd

)
)
Objective Objective 3 3
This objective shows how to grant permission to This objective shows how to grant permission to
all. all. This can be done by using the keyword public. For This can be done by using the keyword public. For
example, example,
grant select on EMPLOYEE to public; grant select on EMPLOYEE to public;
This statement grants access to Employee table to This statement grants access to Employee table to
all and the following command removes this all and the following command removes this
privilege from all. privilege from all.
revoke select on EMPLOYEE from public; revoke select on EMPLOYEE from public;
Provide select permission to Provide select permission to deepak deepak for the table for the table
EMPLOYEE,assuming EMPLOYEE,assuming that this table is owned by that this table is owned by sng sng. .
grant select on EMPLOYEE to grant select on EMPLOYEE to deepak deepak; ;
S. Nandagopalan, BIT S. Nandagopalan, BIT 57 57
Objective Objective 5 5
Display the contents of EMPLOYEE table. Display the contents of EMPLOYEE table.
connect connect deepak deepak/rock; // /rock; // deepak deepak gets connected gets connected
select * from select * from sng.EMPLOYEE sng.EMPLOYEE; ;
Unless a synonym is used, the table name must be preceded by the Unless a synonym is used, the table name must be preceded by the
username of the owner of the table. Otherwise you will get an er username of the owner of the table. Otherwise you will get an error. ror.
The user The user deepak deepak can create a can create a view view to access the EMPLOYEE table. to access the EMPLOYEE table.
create view EMPLOYEE as create view EMPLOYEE as
select * from select * from sng.EMPLOYEE sng.EMPLOYEE; ;
Creating a synonym. Creating a synonym.
create synonym EMPLOYEE for create synonym EMPLOYEE for sng.EMPLOYEE sng.EMPLOYEE; ;
If the table/view is not owned by a particular user, then he can If the table/view is not owned by a particular user, then he can not pass not pass
the granting of that table/view to other users. the granting of that table/view to other users.
ERROR: ERROR: grant select on grant select on sng.EMPLOYEE sng.EMPLOYEE to to reena reena; ;
Here, Here, reena reena is some other user is some other user. .
S. Nandagopalan, BIT S. Nandagopalan, BIT 58 58
DML Statements
DML Statements
INSERT Statement INSERT Statement
INSERT INTO Employee INSERT INTO Employee
VALUES (1111, ' VALUES (1111, 'Deeapk Deeapk', ' ', '5 5- -Jan Jan- -62 62', 22000, 4444, 1); ', 22000, 4444, 1);
Inserting through Keyboard Inserting through Keyboard
INSERT INTO Employee INSERT INTO Employee
VALUES (&SSN, &Name, & VALUES (&SSN, &Name, &BDate BDate, &Salary, , &Salary, & &MgrSSN MgrSSN, & , &DNo DNo); );
Inserting dates Inserting dates
INSERT INTO Employee INSERT INTO Employee
VALUES (6666, 'John', TO_DATE('5 VALUES (6666, 'John', TO_DATE('5- -Jan Jan- -2003 3:40', 2003 3:40',
'DD 'DD- -MM MM- -YYYY HH24:SS'), 22000, 4444, 1); YYYY HH24:SS'), 22000, 4444, 1);
S. Nandagopalan, BIT S. Nandagopalan, BIT 59 59
Inserting rows from an existing table Inserting rows from an existing table
INSERT INTO INSERT INTO EMP2 EMP2
SELECT SELECT * *
FROM FROM Employee; Employee;
DELETE Statement DELETE Statement
DELETE Employee DELETE Employee
WHERE WHERE SSN = 1111; SSN = 1111;
UPDATE Statement UPDATE Statement
UPDATE UPDATE Employee Employee
SET SET DNo DNo = 1 = 1
WHERE WHERE Name = ' Name = 'Nandagopal Nandagopal'; ';
To hike the salary of all employees by 10%. To hike the salary of all employees by 10%.
UPDATE UPDATE Employee Employee
SET SET Salary = Salary = Salary Salary * 1.05; * 1.05;
S. Nandagopalan, BIT S. Nandagopalan, BIT 60 60
ADDITIONAL EXAMPLES
ADDITIONAL EXAMPLES
Company Database Example Company Database Example
Employee Employee( (SSN SSN Char(9), Name Varchar2(20), Char(9), Name Varchar2(20), Bdate Bdate Date, Address Date, Address
Varchar2(30), Sex Char(1),Salary Number(10,2), Varchar2(30), Sex Char(1),Salary Number(10,2),
SuperSSN SuperSSN Char(9), Char(9), DNo DNo Number(2)); Number(2));
Department Department( (Dnumber Dnumber Number(2), Number(2), DName DName Varchar2(10), Varchar2(10),
MgrSSN MgrSSN Char(9), Char(9), MgrStartDate MgrStartDate Date); Date);
Project Project( (PNumber PNumber Number(2), Number(2), PName PName Varchar(10), Varchar(10), Plocation Plocation
Varchar2(15), Varchar2(15), Dnum Dnum Number(2)); Number(2));
Dependent Dependent( (ESSN ESSN Char(9), Char(9), Dependent_Name Dependent_Name Varchar2(15), Varchar2(15),
Sex Char, Sex Char, Bdate Bdate Date, Relationship Varchar2(10)); Date, Relationship Varchar2(10));
Dept_Locations Dept_Locations( (DNumber DNumber Number(2), Number(2), Dlocation Dlocation Varchar2(15)); Varchar2(15));
Works_On Works_On( (ESSN ESSN Char(9), Char(9), PNo PNo Number(2), Hours Number(3,1)); Number(2), Hours Number(3,1));
S. Nandagopalan, BIT S. Nandagopalan, BIT 61 61
Example Example- -1: 1: Find all employees who were born during 1980. Find all employees who were born during 1980.
SELECT SELECT Name Name
FROM FROM EMPLOYEE EMPLOYEE
WHERE WHERE BDate BDate LIKE '__ LIKE '__- -___ ___- -80'; 80';
Example Example- -2: 2: Calculate the wages earned by each employee, Calculate the wages earned by each employee,
assuming the remuneration for each hour is assuming the remuneration for each hour is Rs Rs. 250.00. . 250.00.
SELECT SELECT Essn Essn, , Sum(Hours),Sum(Hours Sum(Hours),Sum(Hours) * 250 ) * 250
FROM FROM Works_On Works_On
GROUP BY GROUP BY Essn Essn; ;
Example Example- -3: 3: Retrieve the department number, number of employees Retrieve the department number, number of employees
in each department and their average salary. in each department and their average salary.
SELECT SELECT DNo DNo, Count(*), , Count(*), Avg(Salary Avg(Salary) )
FROM FROM Employee, Department Employee, Department
WHERE WHERE DNo DNo = = DNumber DNumber
GROUP BY GROUP BY DNo DNo; ;
S. Nandagopalan, BIT S. Nandagopalan, BIT 62 62
Example Example- -4: 4: For each project, retrieve the project number, the project For each project, retrieve the project number, the project
name, and the number of employees who work on that project. name, and the number of employees who work on that project.
SELECT SELECT PNumber PNumber, , PName PName, Count(*) , Count(*)
FROM FROM Project, Project, Works_On Works_On
WHERE WHERE PNumber PNumber = = PNo PNo
GROUP BY GROUP BY PNumber PNumber, , PName PName; ;
Example Example- -5: 5: For each project on which more than 3 employees work, For each project on which more than 3 employees work,
retrieve the project number, the project name, and the number of retrieve the project number, the project name, and the number of
employees who work on that project employees who work on that project. .
SELECT SELECT PNumber PNumber, , PName PName, Count(*) , Count(*)
FROM FROM Project, Project, Works_On Works_On
WHERE WHERE PNumber PNumber = = PNo PNo
GROUP BY GROUP BY PNumber PNumber, , PName PName
HAVING HAVING Count(*) > 3; Count(*) > 3;
Example Example- -6: 6: Print the number of employees whose salaries exceed more Print the number of employees whose salaries exceed more
than than Rs Rs. 25,000/ . 25,000/- - in each department. Display the department name also. in each department. Display the department name also.
SELECT SELECT DName DName, Count(*) , Count(*)
FROM FROM Department, Employee Department, Employee
WHERE WHERE DNumber DNumber = = DNo DNo AND Salary > 25000 AND Salary > 25000
GROUP BY GROUP BY DName DName; ;
S. Nandagopalan, BIT S. Nandagopalan, BIT 63 63
STUDENT Database Example
STUDENT Database Example
Student
Student
(
(
Student_id
Student_id
char(10),
char(10),
SName
SName
varchar2(10), Major varchar2(5), GPA
varchar2(10), Major varchar2(5), GPA
number(3,1))
number(3,1))
Faculty
Faculty
(
(
Faculty_id
Faculty_id
char(4),
char(4),
FName
FName
char(4), Dept
char(4), Dept
varchar2(5),
varchar2(5),
Desig
Desig
varchar2(5), Salary
varchar2(5), Salary
number(10,2))
number(10,2))
Course
Course
(
(
Course_id
Course_id
char(5),
char(5),
CName
CName
varchar2(10),
varchar2(10),
Faculty_id
Faculty_id
char(4))
char(4))
Enrol
Enrol
(
(
Course_id
Course_id
char(5),
char(5),
Student_id
Student_id
char(10),
char(10),
Grade char(1))
Grade char(1))
S. Nandagopalan, BIT S. Nandagopalan, BIT 64 64
Example Example- -1: 1: List the names of all students enrolled for the course List the names of all students enrolled for the course
'IS6T1'. 'IS6T1'.
SELECT SELECT SName SName
FROM FROM Student Student
WHERE WHERE Student_id Student_id In( In(
SELECT SELECT Student_id Student_id
FROM FROM Enrol Enrol
WHERE WHERE Course_id Course_id = 'IS6T1'); = 'IS6T1');
Example Example- -2: 2: List the names of students enrolled for the course 'IS6T1' List the names of students enrolled for the course 'IS6T1'
and have received 'A' grade. and have received 'A' grade.
SELECT SELECT SName SName
FROM FROM Student Student
WHERE WHERE Student_id Student_id In( In(
SELECT SELECT Student_id Student_id
FROM FROM Enrol Enrol
WHERE WHERE Course_id Course_id = 'IS6T1' AND Grade = 'A'); = 'IS6T1' AND Grade = 'A');
Example Example- -3: 3: List all the departments having an average salary of List all the departments having an average salary of
above above Rs Rs. 10000. . 10000.
SELECT SELECT Dept Dept
FROM FROM Faculty Faculty
GROUP BY GROUP BY Dept Dept
HAVING HAVING AVG(Salary AVG(Salary) > 10000; ) > 10000;
S. Nandagopalan, BIT S. Nandagopalan, BIT 65 65
Example
Example
-
-
5:
5:
List the names of all faculty
List the names of all faculty
members beginning with 'P' and ending
members beginning with 'P' and ending
with letter 'A'.
with letter 'A'.
SELECT
SELECT
FName
FName
FROM
FROM
Faculty
Faculty
WHERE
WHERE SUBSTR(FName,1,1) LIKE 'P' SUBSTR(FName,1,1) LIKE 'P'
AND SUBSTR(FName, AND SUBSTR(FName,- -2,1) LIKE 'A'; 2,1) LIKE 'A';
S. Nandagopalan, BIT S. Nandagopalan, BIT 66 66
More Examples
More Examples
Book Dealer Database
Book Dealer Database
AUTHOR AUTHOR ( (Authorid Authorid : : Int Int, Name : String, City : String, , Name : String, City : String,
Country : String) Country : String)
PUBLISHER PUBLISHER ( (Publisherid Publisherid : : Int Int, Name : String, City : String, , Name : String, City : String,
Country : String) Country : String)
CATALOG CATALOG ( (Bookid Bookid : : Int Int, Title : String, , Title : String, Authorid Authorid : : Int Int, ,
Publisherid Publisherid : : Int Int, , Categoryid Categoryid : : Int Int, ear : , ear : Int Int, Price : , Price : Int Int) )
CATEGORY CATEGORY ( (Categorid Categorid : : Int Int, Description : String) , Description : String)
ORDER_DETAILS ORDER_DETAILS ( (OrderNo OrderNo : : Int Int, , Bookid Bookid : : Int Int, Quantity : , Quantity : Int Int) )
S. Nandagopalan, BIT S. Nandagopalan, BIT 67 67
Queries
Queries
Give the details of the authors who have 2 or more Give the details of the authors who have 2 or more
books in the catalog and the price of the books is books in the catalog and the price of the books is
greater than the average price of the books in the greater than the average price of the books in the
catalog and the year of publication is after 2000. catalog and the year of publication is after 2000.
Query Query
select select C.Authorid C.Authorid, , A.AName A.AName
from Catalog C, Author A from Catalog C, Author A
where where A.Authorid A.Authorid = = C.Authorid C.Authorid and and C.Year C.Year > 2000 and > 2000 and C.Price C.Price > >
(Select (Select Avg(Price Avg(Price) from Catalog) ) from Catalog)
group by group by C.Authorid C.Authorid, , A.AName A.AName
having having count(C.Authorid count(C.Authorid) >= 2; ) >= 2;
S. Nandagopalan, BIT S. Nandagopalan, BIT 68 68
Find the number of the book which has
Find the number of the book which has
maximum sales.
maximum sales.
Create View Create View SalesDetails SalesDetails as ( as (
Select Select OD.Bookid OD.Bookid as Book#, as Book#, C.Price C.Price as Cost, as Cost,
Sum(OD.Quantity Sum(OD.Quantity) as Qty, ) as Qty, Sum(OD.Quantity Sum(OD.Quantity * *
C.Price C.Price) as Sales ) as Sales
from from Order_Details Order_Details OD, Catalog C, Author A OD, Catalog C, Author A
where where OD.Bookid OD.Bookid = = C.Bookid C.Bookid and and C.Authorid C.Authorid = =
A.Authorid A.Authorid
group by group by OD.Bookid OD.Bookid, , C.Price C.Price); );
select select A.Authorid A.Authorid, , A.AName,S.book A.AName,S.book#, #, S.Sales S.Sales
from Author A, catalog C, from Author A, catalog C, Salesdetails Salesdetails S S
where where A.Authorid A.Authorid = = C.Authorid C.Authorid and and S.Book S.Book# = # = C.Bookid C.Bookid
and sales = and sales =
(select (select Max(Sales Max(Sales) from ) from salesdetails salesdetails); );
S. Nandagopalan, BIT S. Nandagopalan, BIT 69 69
Student Enrollment Database
Student Enrollment Database
STUDENT
STUDENT
(
(
RegNo
RegNo
: String, Name : String,
: String, Name : String,
Major : String,
Major : String,
BDate
BDate
: date)
: date)
COURSE
COURSE
(
(
Course#
Course#
:
:
Int
Int
,
,
CName
CName
: String, Dept :
: String, Dept :
String)
String)
ENROLL
ENROLL
(
(
RegNo
RegNo
: String,
: String,
Course#
Course#
:
:
Int
Int
,
,
Sem
Sem
:
:
Int
Int
, Marks :
, Marks :
Int
Int
)
)
BOOK_ADOPTION
BOOK_ADOPTION
(
(
Course#
Course#
:
:
Int
Int
,
,
Sem
Sem
:
:
Int
Int
,
,
ISBN :
ISBN :
Int
Int
)
)
TEXT
TEXT
(ISBN :
(ISBN :
Int
Int
,
,
BookTitle
BookTitle
: String, Publisher :
: String, Publisher :
String, Author : String)
String, Author : String)
S. Nandagopalan, BIT S. Nandagopalan, BIT 70 70
Produce a list of text books (include Course#,
Produce a list of text books (include Course#,
ISBN,
ISBN,
BookTitle
BookTitle
) in the alphabetical order for
) in the alphabetical order for
courses offered by the 'CS' department that
courses offered by the 'CS' department that
use more than two books
use more than two books
Select
Select
C.Course
C.Course
#, T.ISBN,
#, T.ISBN,
T.BookTitle
T.BookTitle
from Course
from Course
C,Book_Adoption
C,Book_Adoption
BA, Text T
BA, Text T
where
where
C.Course
C.Course
# =
# =
BA.Course
BA.Course
# and BA.ISBN
# and BA.ISBN
= T.ISBN and
= T.ISBN and
C.Dept
C.Dept
= 'CSE'
= 'CSE'
group by
group by
C.Course
C.Course
#, T.ISBN,
#, T.ISBN,
T.BookTitle
T.BookTitle
;
;
S. Nandagopalan, BIT S. Nandagopalan, BIT 71 71
1nv o{
1nv o{
(nvc
(nvc

Potrebbero piacerti anche