Vous êtes sur la page 1sur 38

Database Management Systems Unit 8

Sikkim Manipal University Page No.: 128


Unit 8 History of SQL
Structure
8.1 Introduction
Objectives
Self Assessment Question(s) (SAQs)
8.2 Data Retrieval Statement (SELECT)
Self Assessment Question(s) (SAQs)
8.3 Multi table Queries
8.3.1 Nested Queries or Sub queries
8.3.2 Multiple Row Nested Queries:
8.3.3 The Exists Clause
Self Assessment Question(s) (SAQs)
8.4 Data Manipulation Language
Self Assessment Question(s) (SAQs)
8.5 The Create Table Statement
Self Assessment Question(s) (SAQs)
8.6 Summary
8.7 Terminal Questions (TQs)
8.8 Multiple Choice Questions (MCQs)
8.9 Answers to SAQs, TQs, and MCQs
8.9.1 Answers to Self Assessment Questions (SAQs)
8.9.2 Answers to Terminal Questions (TQs)
8.9.3 Answers to Multiple Choice Questions (MCQs)
8.1 Introduction
The history of SQL began in an IBM laboratory in San J ose, California,
where SQL was developed in the late 1970's. SQL stands for structured
Query Language. It is a non-procedural language, meaning that SQL
describes what data to retrieve, delete or insert, rather than how to perform
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 129
the operation. It is the standard command set used to communicate with
the RDBMS.
A SQL query is not-necessarily a question to the database. It can be
command to do one of the following.
Create or delete a table.
Insert, modify or delete rows.
Search several rows for specifying information and return the result in
order.
Modify security information.
THE SQL STATEMENT CAN BE GROUPED INTO FOLLOWING
CATEGORIES.
1. DDL(Data Definition Language)
2. DML(Data Manipulation Language)
3. DCL(Data Control Language)
4. TCL(Transaction Control Language)
DDL: Data Definition Language
The DDL statement provides commands for defining relation schema i,e for
creating tables, indexes, sequences etc. and commands for dropping,
altering, renaming objects.
DML: (Data Manipulation Language)
The DML statements are used to alter the database tables in someway.
The UPDATE, INSERT and DELETE statements alter existing rows in a
database tables, insert new records into a database table, or remove one or
more records from the database table.
DCL: (Data Control Language)
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 130
The Data Control Language Statements are used to Grant permission to the
user and Revoke permission from the user, Lock certain Permission for the
user.
SQL DBA>Revoke Import from Akash;
SQL DBA>Grant all on emp to public;
SQL DBA>Grant select, Update on EMP to L.Suresh;
SQlDBA>Grant ALL on EMP to Akashwith Grant option;
Revoke: Revoke takes out privilege from one or more tables or views.
SQL DBA>rEOKE UPDATE, DELETE FROM l.sURES;
SQL DBA>Revoke all on emp from Akash
TCL: (Transaction Control Language)
It is used to control transactions.
Eg: Commit
Rollbakc: Discard/Cancel the changes upto the previous commit point.
SQL* COMMANDS:
This subsection discusses the often used commands in sql environment.
For example, if your SQL commands are saved in a file (typically in note
pad) you can execute this file using an "at" @command, similarly there are a
number of such commands:
@<filename> Runs the command file stored in <filename>
/ Runs the SQL command or PL/SQL block
currently stored in the SQL buffer
EXEC[UTE] Runs a single PL/SQL statement.
R[UN] Runs the SQL command or PL/SQL block
currently stored in the SQL buffer.
R<filename> Runs the file specified in <filename>
EXIT or QUIT Exits from SQL.
LIST Lists the content of the buffer
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 131
A[PPEND] <text> Adds text at the end of the line
CLEAR BUFFER Deletes all the lines in the buffer
GER<filename> Loads host OS file into SQL BUFFER
(does not execute it)
SAV[E]<filename> Saves contents of buffers to OS file.
DEFIN_EDITOR='notepad' Define notepad as the editor.
ED[IT] Invokes the editor defined through
DEFINE_EDITOR>
DATA TYPES IN ORACLE 8i SQL:
The fig. shows the complete listing of the data types allowed in oracle.
DATA TYPE DESCRIPTION
CHAR (sizs) Fixed length character. Max =2000
VARCHAR2(size) Variable length character. Max=4000
DATE Date, valid range is from jan1,4712 B.C to.
DEC 31,4712 A.D.
BLOB Binary large object Max =4GB
CLOB Character large object Max=4G.B.
BFILE Pointer to binary OS file
LONG Character data of variable size, Max=2G.B.
LONG RAW Raw binary data. Rest is same as long
NUMBER (size) Numbers. Max. size =40 digits
NUMBER(size,d) Numbers, range=1.0E-130 tto 9.9E125
DECIMAL Same as NUMBER. Size /d can't be specified
FLOAT Same as NUMBER
INTEGER Same as NUMBER Size /d can't be specified
SMALLINT Same as NUMBER
EXAMPLE TABLES:
To study the SQL commands of various types we need some tables. Let us
consider two tables shown in the fig., which will be used throughout our
discussion.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 132
EMPLOYEE
SSN NAME BDATE SALARY MgrSSN Dno
1111 Deepak 5-jan-62 22000 4444 1
2222 Yadav 27-feb-84 30000 4444 3
3333 Venkat 22-jan-65 18000 2222 2
4444 Prasad 2-feb-68 32000 Null 3
5555 Reena 4-aug-79 8000 4444 3
DEPARTMENT
DNO DNAME LOC
1 Admin Chennai
2 Research Bangalore
3 Accounts Bangalore
Objectives
To Know About
o Data Retrieval Statement (SELECT)
o Multi table Queries
o Nested Queries or Sub queries:
o Multiple Row Nested Queries:
o The Exists Clause
o Data Manipulation Language
Self Assessment Question(s) (SAQs) (For Section 8.1)
1. What is SQL?
2. Write down the categories into which a SQL statement can be grouped?
3. Explain the concept of DCL.
8.2 Data Retrieval Statement (SELECT)
The select statement is used to extract information from one or more tables
in the database. To demonstrate SELECT we must have some tables
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 133
created within a specific user session. Let us assume Scott as the default
user and create two tables Employee and Department using CREATE
STATEMENT
CREATE TABLE Department(
Dno number(d) not null
Dname varchar2(10) not null
Loc varchar2(15)
Primary key (Dno));
Create table employee (
SSN number (4) not null
Name varchar3=2(20) not null
Bdate date,
Salary number(10,2)
MgrSSN umber(4)
DNo number(2) not null
Primary key(SSN)
Foreign key [MgrSSN] reference employee(SSN)
Foreign key (DNo) reference department (DNo))
The syntax of SELECT STATEMENT is given below:
Syntax:
Select* | {[DISTINCT] column | expression \)
From table(s);
The basic select statement must include the following;
A SELECT clause
A FROM clause
Selecting all columns
Example 1
Select * From employee
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 134
The * indicates that it should retrieve all the columns from employee
table. The out put of this query shown below:
Out put-1
Dno SSN NAME BDATE SALARY MgrSSN
1 1111 Deepak 5-jan-62 20000 4444
3 2222 Yadav 27-feb-60 30000 4444
2 3333 Venkat 22-jan-65 18000 2222
3 4444 Prasad 2-feb-84 32000 Null
3 5555 Reena 4-aug-65 8000 4444
Example 2
SELECT * FROM employee
ORDER BY SSN;
Output-2
SSN NAME BDATE SALARY MgrSSN Dno
1111 Deepak 27-feb-84 30000 4444 3
2222 Yadav 15-jan-65 8000 4444 1
3333 Venkat 22-jan-85 20000 2222 2
4444 Prasad 27-feb-84 32000 Null 3
5555 Reena 15-jan-65 8000 4444 1
SELECTING SPECIFIC COLUMNS:
We wish to retrieve only name and salary of the employees.
Example-3
SELECT name, salary FROM employee:
OUT PUT-3
NAME SALARY
Prasad 32000
Reena 8000
Deepak 22000
Venkat 30000
Yadav 18000
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 135
Using arithmetic operators:
SELECT name, salary, salary * 12
FROM employee;
Out put-4
NAME SALARY SALARY *12
Prasad 32000 384000
Reena 8000 96000
Deepak 22000 264000
Yadav 18000 360000
Venkat 30000 216000
USING ALIASES(Alternate name given to columns):
SELECT \(Name, Salary, Salary *12 "YRLY SALARY"
FROM Employee
OUT PUT
NAME SALARY SALARY *12
Prasad 32000 384000
Reena 8000 96000
Deepak 22000 264000
Yadav 18000 360000
Venkat 30000 216000
Eliminating duplicate rows:
To eliminate duplicate rows simply use the keyword DISTINCT.
SELECT DISTINCT MGRSSN FROM Employee
OUTPUT
MGRSSN
2222
4444
DISPLAYING TABLE STRUCTURE:
To display schema of table use the command DESCRIEBE or DESC.
DESC Employee;
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 136
OUTPUT
NAME NULL? TYPE
Ssn NOT NULL NUMBER [4]
NAME NOT NULL VARCHAR2 [20]
BDATE DATE
SALARY NUMBER [10,20]
MGRSSN NUMBER [4]
DNO NOT NULL NUMBER [2]
SELECT statement with WHERE clause
The conditions are specified in the where clause. It instructs sql to search
the data in a table and returns only those rows that meet search criteria.
SELECT * FROMemp
WHERE name ='yadav'
Out put-1
SSN NAME BDATE SALARY MGRSSN DNO
2222 yadav 10-dec-60 30000 4444 3
SELECT Name, Salary FROM Employee
WHERE Salary >20000;
OUT PUT
NAME SALARY
Prasad 32000
Deepak 22000
Yadav 18000
RELATIONAL OPERATOR S AND COMPARISON CONDITIONS:
= Equal to
> Greater than
>= Greater than or equal
< Less than
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 137
<= Less than or equal
<> Not equal
BETWEEN<a>ABD<b> Range between <a>and <b>inclusive
1N<set> True when the member is in the <set>
LIKE<pattern> Matches a specified pattern
IS NULL Is a null value
BETWEEN AND OR OPERATOR:
To illustrate the betweenand or operators.
SQL supports range searches. For eg If we want to see all the employees
with salary between 22000 and 32000
SELECT * from employee
WHERE salary between 22000 and 32000
Example
NAME SALARY
Prasad 32000
Yadav 30000
Deepak 22000
IS NULL OR IS NOT NULL:
The null tests for the null values in the table
Example:
SELECT Name FROM Employee
WHERE Mgrssn IS NULL;
OUT PUT:
NAME
Prasad
SORTING (ORDER BY CLAUSE):
It gives a result in a particular order. Select all the employee lists sorted by
name, salary in descending order.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 138
Select* from emp order by basic;
Select job, ename from emp order by joindate desc;
Desc at the end of the order by clause orders the list in descending order
instead of the default[ascending] order.
Example:
SELECT* FROM EMPLOYEE
ORDER BY name DESC.
OUT PUT:
NAME
Reena
Pooja
Deepak
Aruna
LIKE CONDITION:
Where clause with a pattern searches for sub string comparisons.
Sql also supports pattern searching through the like operator. We
describe patterns using two special characters.
Percent [%]. The % character matches any sub string.
Underscore ( _ ) The underscore matches any character.
Example:
SELECT emp_name from emp
WHERE emp_name like 'Ra%'
Example: 1
NAME
Raj
Rama
Ramana
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 139
Select emp_name from emp where name starts with 'R' and has j has
third caracter.
SELECT *from Emp
WHERE EMP_NAME LIKE 'r_J %';
WHERE clause using IN operator
SQL supports the concept of searching for items within a list; it compares
the values within a parentheses.
1. Select employee, who are working for department 10&20.
SELECT * from emp
WHERE deptno in (10,20)
2. Selects the employees who are working in a same project as that raja
works onl
SELECT eno from ep
WHERE (pno) IN (select pno from works_on where empno=E20);
AGGREGATE FUNCTIONS AND GROUPING:
Group by clause is used to group the rows based on certain common
criteria; for e.g. we can group the rows in an employee table by the
department. For example, the employees working for department number 1
may form a group, and all employees working for department number 2 form
another group. Group by clause is usually used in conjunction with
aggregate functions like SUM, MAX, Min etc.. Group by clause runs the
aggregate function described in the SELECT statement. It gives summary
information.
Example: For each department, retrieve the department number, the
number of employees in the department and their average salary.
SELECT Dno, count(*) "No.of Employees"
FROM employee
GROUP BY DNO;
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 140
OUT PUT
DNO No. of Employees
30 2
40 5
52 3
53 4
Select total salary for each department.
SELECT deptno sum(salary) from emp
GROU BY depno;
OUT PUT:
DNO SUM(SALARY)
1 22000
2 18000
3 7000
For each project, retrieve the project number, project name and the
number of employees who work on total project.
o SELECT Pnumber, Pname, count(*)
FROM project, works on
WHERE Pnumber=PNO
GROUP BY P number, Pname;
Retrieve total number of employees in the research department.
o SELECT COUNT(*) FROM employee, department
WHERE Dno=Dnumber and
Dname='Research'
Find the sum of salaries, the maximum and minimum salary of all the
employees.
o SELECT Sum(salary), max(salary),
Min(salary) FROM emp;
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 141
Sum(salary) Mad(salary) Min(salary)
50000 32000 8000
Find the sum of the salaries of all employees of the 'Research'
department, as well as the maximum salary, minimum salary in this
department.
o SELECT SUM(salary), max(salary), min(salary)
FROM emp, department
Where DNO=Dnumber and
Dname='Researhc';
HAVING CLAUSE:
The having clause filtrs the rows returned by the group by clause.
Eg: 1>Select job, count(*)from emp group by job having count(*)>20;
2>Select Deptno,max(basic), min(basic)from emp groupby
Detno having salary>30000
find the average salary of only department 1.
SELECT DnO,avg(salary)
FROM Employee
GROUP BY Dno
HAVING Dno =1;
For each department, retrieve the department number, Dname and
number of employees working in that department, so that department
should contain more than three employees.
o SELECT Dno, Dname, count(*)
FROM Emp, Dept.
WHERE Emp.Dno=dept.Dno
GROUP BY Dno
HAVING count(*)3;
Here where_clause limits the tuples to which functions are applied, the
having clause is used to select individual groups of tuples.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 142
For each department that has more than three employees, retrieve the
department number and the number of its employees, who are earning
more than 10,000.
o Example::
SELECT Dno, AVG(salary)
FROM Employee
WHERE Bdate LIKE '%jan%'
GROUP BYDno
HAVING max(salary) >10000;
OUT PUT:
DNO AVG(SALARY)
1 22000
2 18000
3 20000
Self Assessment Question(s) (SAQs) (For section 8.2)
1. How do you retrieve data from the database?
2. Explain the different types of relational operators used in retrieval of
data.
3. Explain the concept of Sorting.
4. How do you perform searching in SQL?
5. Write a note on aggregate functions and grouping in SQL.
8.3 Multi table Queries
So far the queries that we have discussed were containing only one table in
the from clause. There are many occasions in the database applications
where we need to retrieve data from more than one table. This section
addresses these kind of queries.
SIMPLE EQUI-JOINS:
When two tables are joinedtogether we must follow these guidelines:
Table names in the FROM clause are separated bycommas.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 143
Use appropriate joining condition. This means that the foreign key of
table 1 will be made equal to the primary key of table 2. This column
acts as the joining attribute. For example, dno of employee table and
dno of department will be involved in the joining condition of WHERE
clause.
EXAMPLE-1: This example demonstrates the equijoin and the purpose
is to display the employee names and the department names for which
they work.
SELECT NAME, DNAME
FROM Employee, Department
WHERE employe.Dno =department.Dno;
OUTPUT:
NAME DNAME
Prasad Accounts
Reena Accounts
Deepak Admin
Venkat Accounts
Pooja Research
EXAMPLE 2:
Let us now try to display only employees working for Accounts
department.
SELECT Name, salary, Dname
FROM Employee, department
WHERE (Emplyee.DNO =Department.DNO)
AND (Dname ='Accounts');
OUT PUT:
NAME SALARY DNAME
Prasad 32000 Accounts
Reena 8000 Accounts
Venkat 30000 Accounts
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 144
SELF JOIN and TABLE ALIASES:
The self-join is one where you involve the same table in the join. This is
illustrated in the following example. This technique is used fully to solve
many queries.
To find the employee who earns more than venkat
SELECT e1.name, e1.salary
FROM Employee e1, Employee e2
WHERE (e1.salary >e2.salary) AND (e2.name ='venkat')
OUT PUT:
NAME SALARY
Prasad 32000
OUTER JOINS:
Outer joins are used to display rows that do not meet the join condition. For
left outer join use a plus sign(+) to left condition and for right outer join use
the plus sign to the right condition. The syntax for left and right outer joins
are given below:
Left outer join
SELECT table1.col, table2.col
FROM table1 t1, table2 t2
WHERE t1.col(+) =t2.col;
Notice that the plus sign cannot be placed on both sides of the condition.
EXAMPLE 1: This example demonstrates the right outer join by retaining
the right side table(department) tuples and giving null values for the
tuples that do not match the left side table (employee).
SELECT Name, Dname
FROM Employee E, Department D
WHERE E.Name(+) =D.Dname;
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 145
OUTPUT::
NAME DNAME
Accounts
Admin
EXAMPLE 2: This is same as ex.1, but the only difference is that it is a
left outer join. So all the left table (employee) rows are kept, and if no
match occurs with the right side table (department) a null is shown.
SELECT Name, Dnaem
FROM Employee E, Department D
WHERE E.Name =D.Dname(+);
OUT PUT:
NAME DNAME
Deepak
Venkat
Pooja
Prasad
Reena
8.3.1 Nested Queries or Sub queries
A where clause generally contains a condition; but it can also contain an sql
query. The query within a WHERE clause is called the inner query or sub
query, and the query that encloses the inner one is called as outer query or
main query. It is also possible to place the inner query with in a FROM or
HAVING clause. Using nested queries it is possible to build powerful sql
programs.
Execution of nested queries:
The general syntax of a nested query is given below.
SELECT <column (s)>
FROM table outer query
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 146
WHERE <condn>operator
(SELECT <column>
FROM table); inner query
The operator mentioned in the outer query can be any one of >, =, or IN.
Normally the outer query uses the result of the inner query to display the
values of columns mentioned in the outer query.
Single-Row Nested Queries
The simplest single-row nested query is by using =sign.
EXAMPLE: Assume that we wish to display the names and the
employees working for accounts department.
SELECT Name
FROM Employee
WHERE Dno =
(SELECT DNo
FROM Department
WHERE Dname ='accounts');
OUTPUT:
NAME
Prasad
Reena
Venkat
GROUP BY clause in SUB QUERIES:
Display all the employees drawing more than or equal to the average salary
of department number 3.
SELECT Name, Salary
FROM Employee
WHERE Slary >=
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 147
(SELECT AVG(salary)
FROMEmployee
GROUP BY Dno
HAVING dnO =3);
OUT PUT
NAME SALARY
Prasad 32000
Venkat 30000
8.3.2 Multiple Row Nested Queries
The operators IN, ANY, and ALL are used in the multiple row sub queries.
The sub query in this case returns more than one row.
OPERATORS DESCRIPTION
IN Equal to any member in the list
ANY Compare value to each value returned by the
sub query
ALL Compare value to all the values returned by
the sub query.
EXAMPLE: Display the name of the highest paid employee,
SELECT Name, salary
FROM Employee
WHERE Salary IN
(SELECT MAX(Salary)
FROMEmployee)
Remember that the multiple row sub queries expect one or more results. In
this example the inner query gives a single value and the next example
shows a set of values. The following table gives an idea of how to use ANY
and ALL.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 148
OPERATOR MEANING EXAMPLE
<ANY Less than the
maximum
e<ANY(5.3.8) e is less than any single item in
the life (5,3,8). Even 7 qualifies, because 7<8
>ANY More than the
minimum
e>ANY (5,3,8): e is less than any single item
in the list (5,3,8). Even 4 qualities, because
4>3.
<ANY Same as IN e =any (5,3,8). ALL value in the list quality,
<ALL Less than the
maximum
e <ALL (5,3,8); anything below 3 qualifies.
>ALL More than the
maximum
e >ALL (5,3,8) : anything greater than 8
qualifies
!=ALL Not equal to
any thing
E !=(5,3,8): any thing other than 5, 3 and 8
qualifies.
EXAMPLE 1:
SELECT Name, salary
FROM Employee
WHERE Salary<ANY
(SELECT Salary
FROMEmployee
WHERE DNo =3);
OUTPUT:
NAME SALARY
Reena 8000
Deepak 22000
Venkat 30000
Pooja 18000
EXAMPLE 2:
SELECT Name, salary
FROM Employee
WHERE Salary>ANY
(SELECT Salary
FROMEmployee
WHERE DNO =3);
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 149
OUTPUT:
NAME SALARY
Prasad 32000
Deepak 22000
Venkat 30000
Pooja 18000
In this example, all the rows qualify except the row with salary 8000,
because all employees draw more than the minimum salary in the result
of the sub query. If your condition is >=then you get all the rows.
EXAMPLE
SELECT Name, salary
FROM Employee
WHERE Salary<ANY
(SELECT Salary
FROMEmployee
WHERE DNO =3);
If any body draws a salary lower than the minimum value in the set, their
names will be displayed. Here, nobody draws lower than 8000 and
hence there is no output.
OUTPUT:
No rows selected.
EXAMPLE2:
SELECT Name, salary
FROM Employee
WHERE Salary >ALL
(SELECT Salary
FROMEmployee
WHERE DNO =3);
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 150
Similar to the previous examples - nobody draws more than the
maximum inthe set and so no output again.
OUTPUT:
No rows selected.
EXAMPLE:
SELECT Name, salary
FROM Employee
WHERE Salary =ALL
(SELECT Salary
FROMEmployee
WHERE DNO =3);
Obviously this example should output salaries of employees other than
the set givenby the subquery.
OUTPUT:
NAME SALARY
Deepak 22000
Pooja 18000
8.3.3 The Exists Clause
The exits clause returns true in a WHERE clause, if the subquery that
follows returns at least one row.
EXAMPLE:
Assume that we want to display the names of employees who work for the
Accounts department; it can be written as:
SELECT Name
FROM Employee E
WHERE EXISTS
(SELECT*FROM Department D
SHERE E.DNO =D.DNO AND DNAME ='Accounts')
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 151
OUTPUT:
NAME
Prasad
Reena
Venkat
Self Assessment Question(s) (SAQs) (For section 8.3)
1. Write down the guidelines used to query more than one table.
2. What do you mean by nested query?
3. Define sub query and give one example
4. Explain the concept of multiple row nested queries.
5. What does Exists clause return?
8.4 Data Manipulation Language
A data manipulating language [DML] consists of SQL statements that are
used to insert, delete and update the records in a table.
INSERT STATEMENT:
To add a new row into the table you can follow the syntax:
INSERT INTO table [(column-1I, column-2I)]
Values (value- I I, value-2..I);
Using this syntax you can insert only one row at a time. To insert more than
one row, you can execute the insert statement repeatedly. The simplest
example for INSERT statement is shown below.
EMPLOYEE
INSERT INTOEmployee
VALUES (1111, 'deepak', '5-jan-82', 0000, 4444,);
To enter more records we can use / (slash symbol)
'/' is used to execute the commands stored in the buffer
insert into emp(empno,eaddr,basic)
values(&empno,'&eaddr',&ba);
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 152
DELETE OMMAND
It is a DML statement to delete record(s)
Syntax: DELETE FROM table
[WHERE cond]; / / If the WHERE condition is not present in
the query, all the rows in the table are deleted.
Example: delete from emp where name ='Yadav';
UPDATE COMMAND
It is used to change existing values in a table.
Syntax: UPDATE table
SET col I =val I, col2 =val2
[WHERE cond];
update emp set deptno =100; / / If the WHERE condition is not present in
the query, all the rows in the table are upaed.
Update emp set ename='Sourav' where empno =100;
Transaction Control Language It is used to control transaction
Eg: Commit
Save changes permanently in the database.
Roll back: Discard/Cncel the changes upto the previous commit point.
Save point:
Is used to commit / Rollback particular point.
Ex: Commit
Insert
Update..
Savepoint aa
Delete
#
#
#
Rollback to aa.
Commit to a
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 153
Creating And Altering Database objects (DDL):
The basic notion of this section is to introduce the ways to create and
manipulate the following database objects.
Table: A tabular structure that stores data.
View: A tabular structure similar to a table but it is a
collection of one or more tables.
Sequence Automatically generates a sequence of numbers
Index: Provides an efficient access structure.
Self Assessment Question(s) (SAQs) (For section 8.4)
1. How do you perform insertion, deletion and update operations in SQL?
8.5 The Create Table Statement
Now we shall discuss in detail ways to create and alter tables with
constraints.
syntax: CREATE TABLE tablename
(column_1 datatype,column_2 datatype.);
You specify the name of the table (should be unique) and one or
more attributes and their data types.
EXAMPLE
CREATE TABLE Employee (
SSN number (4) not null
NAME varchar (2) (20) not null
BDATE data,
Mgrssn number,
Primary key(SSN)
Foreign key(mgrssn ) reference emplyee(SSN));
Alter Table Statement
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 154
After creating a table, one or more columns can be added to this table,
similarly, columns can be dropped [oracle 9i only) and in either case the
existing table columns will not be affected, for example, assume that we
wish to add a column phone to employee table
EXAMPLE
ALTER TABLE Employee
ADD phone number(7) not null;
Using the same alter command you can modify the data type of a
column.
For example, the phone column can be modified from number to
varchar2.
ALTER TABLE Employee
MODIFY phone varchar2(10);
Oracle 81 does not support dropping a column, but oracle 9i does it.
ALTER TABLE employee
DROP COLUMN MODIFY phone;
Dropping a table even when it has data is possible
SYNTAX: DROP [TABLE] table;
For Example, to drop the employee table, use the following statement.
DROP employee
To rename the table use the RENAME statement as shown below
RENAME Employee to workers.
VIEWS (Virtual Table)
View is a derived table, which doesn't have storage of its own. Views are
created by picking certain columns from the base table. The advantage of
using views are:
It restricts direct data access form tables I,e it provides security
Reduces joining of tables each and every time.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 155
Syntax: Create viw<view name> as select <column/s> from<table/s>
where<condition>
Example: Create view V1 as Se;ect ssm.ma,e.sa;aru frp, e,[;
Desc V1;
You can create views by referring to more than 1 table.
NOTE:
1. If there are NOT NULL columns which are missing in view, you cannot
insert the records.
2. If a view is created by referring to more than 1 table we cannot do DML
operation except select.
3. View updation (Ins.Del.Update) is possible only if it is created by a single
table.
Insert into V1 values (11,'LSURESH',50000)
Update v1 set ename='Akash' where empno=101;
Create view v2 as select empno, ename,dept.deptno.deptname from
emp.dept;
Indexing:
>Indexing provides a faster access (for to columns that are indexed)
>Indexes can also be used to ensure that no duplicate values are
entered into a column.
Eg: Primary key of a table
SYNTAX:
CREATE INDEX index_name
ON table (column1,column2);
Example:
Create index ind 1 on emp(empno);
1. Query 1
Retrieve the name and address of all employee who work for the
research department.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 156
1. SELECT FNAME,LNAME,ADDRESS
FROM EMPLOYEE,DEPARTMENT
WHERE DNAME ='research' AND D number=DNO
Query Q1 is similar to a SELECT PROJ ECT J OIN sequence of
relational algebra operations.
Such queries are often called select-project-join queries. In the WHERE
clause of Q1, the conditional DNAME ='Research' is the selection condition
and corresponds to a SELECT operation inRelational algebra.
Other Important Examples:
Company database example
This example uses the following tables and underlines columns that are the
primary keys
Employee(
SSN char (9), Name varchar2 (10), Bdate Date, Address varchar 2 (30),
Sex chart (1), Salary Number (10, 2) SuperSSN char(9), Dno Number (2))
Department(
Dnumber Number(2), Dname Varchar2(10), MgrSSj char(9), Mgrstartdate
Date)
Project(
Pnumber Number(2), Pname vrchar2(10). Plocation varchar2(15). Dnum
Number(2))
Depedent(
ESSN CHAR(9), Dependent name Varchar2(15), sex char, Bdate Date,
Relationship varchar2(10))
Dept_locations(
Dnumber Number(2), Dlocationvarchar2(15))
Works_on(
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 157
ESSN char(9), Pno Number(2), Hours Number(3,1))
Query 1:
Retrieve the name and address of all employees who work for the research
department.
Q1: SELECT FNAME,LNAME,ADDRESS
FROM EMPLOYEE,DEPARTMENT
WHERE DNAME ='research' AND Dnumber=DNO
QUERY 2:
Retrieve the birthdate and address of the employee whose name is 'J ohn B.
Smith'.
Q2: SELECT BDATE,ADDRESS
FROM EMPLOYEE
WHERE FNAME ='J ohn ' AND D minit='B' and
LNAME='Smith'
This query involves only the 'EMPLOYEE' relation listed in the FROM
clause.
QUERY 3:
For every project located in 'stafford', list the project number, the controlling
department number, and the department manager's last name, address and
birth date.
Q3: SELECT PNUMBER,DNUM,LNAME,ADDRESS,BDATE
FROM PROJ ECT,DEPARTMENT,EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND
PLOCATION='Stafford'
The join condition DNUM=DNUMBER relates a project to its controlling
department, where as, the join condition MGRSSN=SSN relates the
controlling department to the Employee, who manages that department.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 158
QUERY 4:
Retrive the name of each employee who has a dependant with the same
first name as the employee.
Q4: SELECT E.FNAME,E.LNAME
FROM EMPLOYEE
WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT
WHERE ESSN=E.SSN AND
E.FNAME=DEPENDENT_NAME)
QUERY 5: SELECT FNAME,LNAME
FROM EMPLOYEE
WHERE ( (SELECT PNO
FROM WORKS_ON
WHERE SSN=ESSN)
CONTAINS
(SELECT PNUMBER
FROM PROJ ECT
WHERE DNUM=5) )
QUERY 6:
List the names of managers who have at least one dependant.
SELECT FNAM.LNAME
FROM EMPLOYEE
WHERE EDISTS (SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
AND
EXISTS (SELECT *
FROM DEPENDENT
WHERE SSN=MGRSSN
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 159
One way to write this query is shown in Q7, where we specify two nested
correlates.
Queries: the first selects all dependent tuples related to anEMPLOYEE, and
the second selects all department tuples managed by the EMPLOYEE.
QUERY 7:
For each employee, retrieve the employee's first and last name of his or her
immediate supervisor.
Q7: SELECT E.NAME,E.LNAME,S.FNAME,S.LNAME
FROM EMPLOYEE E.EMPLOYEE S
WHERE E.SUPERSSN=S.SSN
In this case, we are allowed to declare alternative relation names E and S,
called aliases, for the EMPLOYEE relation.
QUERY 8:
Make a list of all project numbers for projects that involve an employee
whose last name is 'Smith', either as the worker or as the manager of the
department that controls the project.
Q8: SELECT PNUMBER
FROM PROJ ECT.DEPARTMENT.EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN AND
LNAME='smith'.)
UNION
(SELECT PNUMBER
FROM WHERE PNUMBER=PNO AND ESSN=SSN
AND LNAME='smith'
The first SELECT query retrieves the project that involves a Smith as
manager of department that controls the project, and the second retrieves
the projects that involve a 'Smith' as a worker on the project.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 160
QUERY 9:
Retrieve the social security numbers of all employees who work on project
numbers 1,2,3.
Q9: SELECT DISTINCT ESSN
FROM WORKS ON
WHERE PNO IN (1,2,3)
QUERY 10:
Retrieve the social security numbers of all employees who work on project
numbers 1,2,3.
Q.10: SELECT DISTINCT ESSN
FROM WORKS ON
WHERE PNO IN (1,2,3)
QUERY 11:
Find the sum of all salaries of all employees, the maximum salary, the
minimum salary, and the average salary.
QLL: SELECT SUM(SALARY), MAX(SALARY), MIN(SALARY)
AVG (SALARY)
FROM EMPLOYEE
QUERY 12:
Count the number of distinct salary values in the database.
Q.12: SELECT COUNT(ISTINCT SALARY)
FROM EMPLOYEE
Notice that, if we write COUNT(SALARY) instead of COUNT(DISTINCT
SALARY) IN Q 19, we get the same result as COUNT(*)because duplicates
will not be eliminated.
Self Assessment Question(s) (SAQs) (For section 8.5)
Write the syntax we use to create a table in SQL.
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 161
8.6 Summary
This unit explained concepts such as
o Data Retrieval Statement (SELECT)
o Multi table Queries
o Nested Queries Or Sub queries:
o Multiple Row Nested Queries:
o The Exists Clause
o Data Manipulation Language
8.7 Terminal Questions (TQs)
Q. 1 What is SQL? Explain.
Q. 2 Discuss data retrieval using SQL.
Q. 3 Discuss the concept of Multi-table queries.
8.8 Multiple Choice Questions (MCQs)
1. To find the names of all branches in the relation
loan =(loan no., branch_name, amount ) we use the following SQL
statement
a) select branch name from loan ;
b) Select * from loan;
c) select all branch name;
d) select branch name from loan where amount >0;
2. If account=(account_no, branch_name, balance) is a relation, then to get
average balance for each branch we use
a) Group by clause b) average clause
c) having clause d) select clause
3. Consider a relation account=(account_no, branch_name, balance). If 5%
interest is to be paid only to accounts with balances $1000 or more, the SQL
statement is:
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 162
a) Update table account set balance =balance * 5% where balance
>1000;
b) Update set balance =balance * 1.05 where balance >=1000;
c) Update account set balance =balance * 1.5 where balance >=1000;
d) Update balance * 1.05 for account;
4. A command used to modifying the structure of tables is..
a) Drop b) Change
c) Modify d) Alter
8.9 Answers to SAQs, TQs, and MCQs
8.9.1 Answers to Self Assessment Questions (SAQs)
For Section 8.1
1. SQL stands for structured Query Language. It is a non-procedural
language, meaning that SQL describes what data to retrieve, delete or
insert rather than how to perform the operation. It is the standard
command set used to communicate with the RDBMS. (Refer section 8.1)
2. THE SQL STATEMENT CAN BE GROUPED INTO THE FOLLOWING
CATEGORIES.
5. DDL(Data Definition Language)
6. DML(Data Manipulation Language)
7. DCL(Data Control Language)
8. TCL(Transaction Control Language) (Refer section 8.1)
3. DCL: (Data Control Language)
The Data Control Language Statements are used to Grant permission to
the user, Revoke permission from the user and Lock certain Permission
for the user. (Refer section 8.1)
For Section 8.2
1. The select statement is used to extract information from one or more
tables in the database. (Refer section 8.2)
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 163
2.
RELATIONAL OPERATOR S AND COMPARISON CONDITIONS:
= Equal to
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
<> Not equal
BETWEEN<a>ABD<b> Range between <a>and <b>inclusive
1N<set> True when the member is in the <set>
LIKE<pattern> Matches a specified pattern
IS NULL Is a null value
(Refer section 8.2)
3. SORTING (ORDER BY CLAUSE):
It gives a result in a particular order. Select all the employees lists
sorted by name, salary in descending order.
Select* from emp order by basic;
Select job, ename from emp order by joindate desc;
Desc at the ed of the order by clause orders the list in descending order
instead of the default [ascending] order. (Refer section 8.2)
4. SQL supports range searches. For e.g. If we want to see all the
employees with salary between 22000 and 32000
SELECT * from employee
WHERE salary between 22000 and 32000
(Refer section 8.2)
5. AGGREGATE FUNCTIONS AND GROUPING:
Group by clause is used to group the rows based on certain common
criteria, for e.g. we can group the rows in an employee table by the
department. (Refer section8.2)
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 164
For Section 8.3
1. When two tables are joinedtogether we must follow these guidelines:
Table names in the FROM clause are separated bycommas.
Use appropriate joining condition. This means that the foreign key of
table 1 will be made equal to the primary key of table 2. This column
acts as the joining attribute. For example, dno of employee table
and dno of department will be involved in the joining condition of the
WHERE clause. (Refer section 8.3)
2. A where clause generally contains a condition; but it can also contain an
SQL query. The query is within a WHERE clause is called the inner
query or sub query, and the query that encloses the inner one is called
the outer query or main query. It is also possible to place the inner
query with in a FROM or HAVING clause. Using nested queries it is
possible to build powerful SQL programs. (Refer section 8.3.1)
3. The query is within a WHERE clause is called the inner query or sub
query and the query that encloses the inner one is called the outer query
or main query. (Refer section 8.3.1)
4. The operators IN, ANY, and ALL are used in the multiple row sub
queries. The sub query in this case returns more than one row. (Refer
section8.3.2)
5. The exits clause returns true in a WHERE clause if the subquery that
follows returns at least one row. (Refer section 8.3.3)
For Section 8.4
1. To add a new row into the table you can follow the syntax:
INSERT INTO table [(column-1I, column-2I)]
Values (value- I I, value-2..I);
Using this syntax you can insert only one row at a time.
(Refer section 8.4)
For Section 8.5
1. syntax: CREATE TABLE tablename
(column_1 datatype,column_2 datatype.);
Database Management Systems Unit 8
Sikkim Manipal University Page No.: 165
You specify the name of the table (should be unique) and one or more
attributes and their data types. (Refer section 8.5)
8.9.2 Answers to Terminal Questions (TQs)
1. SQL stands for structured Query Language, it is a non-procedural
language, meaning that SQL describes what data to retrieve, delete or
insert rather than how to perform the operation. (Refer section 8.1)
2. The select statement is used to extract information from one or more
tables in the database. (Refer section 8.2)
3. There are many occasions in the database applications where we need
to retrieve data from more than one table. (Refer section 8.3)
8.9.3 Answers to Multiple Choice Questions (MCQs)
1. A
2. A
3. C
4. D