DBMS Query
DBMS Query
DBMS Query
0 0
42
AIM:
The aim of this laboratory is to inculcate the abilities of applying the principles of the
database management systems. This course aims to prepare the students for projects where a proper
implementation of databases will be required.
OBJECTIVES:
To understand data definitions and data manipulation commands
To learn the use of nested and join queries
To understand functions, procedures and procedural extensions of data bases
To be familiar with the use of a front end tool
To understand design and implementation of typical database applications
LIST OF EXPERIEMENTS
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
TOTAL: 60 PERIODS
OUTCOMES:
LIST OF EXPERIMENTS:
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications
BEYOND SYLLABUS
MINI PROJECT
Aim : To create database and perform DML and TCL queries to retrieve information from
the database.
BACKGROUND THEORY:
1. Creation of Table: Creates a table with specified attributes and its data type along with
constraints.
Syntax:
Create table r (A1 D1 , A2 D2,………An Dn,
(integrity-constraint1),
….,
(integrity-constraintk));
where r – relation name(Table name),
Ai – Attribute name,
Di – Data type.
Data Types in SQL:
1. char(n) : Fixed-length character string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis. Can store up to 255 characters
2. varchar(n) : Variable-length string (can contain letters, numbers, and special
characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note:
If you put a greater value than 255 it will be converted to a TEXT type
3. int : Integer -2147483648 to 2147483647 normal. 0 to 4294967295. The maximum
number of digits may be specified in parenthesis
4. smallint : Small Integer -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
5. numeric(p,d) : The number consists of p digits(plus a sign), d of the p digits are to
the right of the decimal point.
6. float(n,d) : Floating-point number. The maximum number of digits may be
specified in the size parameter. The maximum number of digits to the right of the decimal point
is specified in the d parameter
7. double (size,d): A large number with a floating decimal point. The maximum
number of digits may be specified in the size parameter. The maximum number of digits to the
right of the decimal point is specified in the d parameter.
8. date : The date containing a date, month and year. Used to store date value as
DD-MON-YY, data size is 9 byte
Format: YYYY-MM-DD
Note: The supported range is from '1000-01-01' to '9999-12-31'
9. time : The time in hours, minutes and seconds.
Format: HH:MM:SS
10. timestamp : The combination of date and time.
Format: YYYY-MM-DD HH:MM:SS
Syntax-
(i) Select A1,A2.. ,An from r1
(ii) Select * from r1;
(iii) Select A1,A2.. ,An from r1,r2,..,rn;
(iv) Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
(i) Select CustID,Custname from customer ;
(ii) Select CustID,Custname from customer where Custname=’Arun’);
DDL Commands:
Create
Alter
Rename
Drop
Altering the Table Schema: Add or delete or change the attribute and data type.
It also can add or drop the integrity constraints.
Syntax:
1. Alter table r add (Ai Di);
2. Alter table r drop(Ai);
3. Alter table r modify(Ai Di);
4. Alter table r add primary key(Ai);
5. Alter table r enable primary key;
6. Alter table r disable primary key;
Eg:
Alter table customer add ( phoneno int(12));
Alter table customer drop( custcity);
Alter table customer modify( custname varchar2(20));
Alter table depositor add primary key(acctno);
Alter table depositor disable primary key;
Alter table depositor enable primary key;
Dropping the Table: Deletes all information and structure about that table(relation)
Syntax:
Drop table r;
Eg:
Drop table customer;
Data Manipulation Language (DML) – to express database queries and updates.
1. Procedural DMLs – requires a user to specify what data are needed and how to get
those data.
2. Declarative DMLs ( nonprocedural language) - requires a user to specify what data are
needed without specifying how to get those data.
DML Component of SQL language is nonprocedural language.
(ii) Syntax-
Insert into r values(‘&A1’,’&A2’,….,’&An’); // where Ai – Attribute
Example-
Insert into customer values (‘&CustID’, ’&Custname’, ’&Custstreet’,
’&Custcity’);
2. Retrieval of Information by Select Command
(i) Syntax-
Select A1,A2.. ,An from r1,r2,..,rn where condition;
Example-
Select CustID,Custname from customer where Custname=’Arun’);
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. The following SQL
enforces the "P_Id" column and the "LastName" column to not accept NULL values:
UNIQUE Constraints
Eg
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the
following SQL:
CHECK Constraints
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include integers
greater than 0.
DEFAULT Constraints
To create a DEFAULT constraint on the "City" column when the table is already created
without city column, use the following SQL:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Each table should have a primary key, and each table can have only one primary key.
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is
created:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
);
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s)
must already have been declared to not contain NULL values (when the table was first created).
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy link
between tables.
The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign
key column, because it has to be one of the values contained in the table it points to
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Let's illustrate the foreign key with an example. Look at the following two tables:
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons"
table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following SQL:
Adding & Deleting the Constraints to the Table using constraint Names:
This example demonstrates how to specify constraints with constraint name during table
creation
create table salary_table (
fiscal_year varchar2(4) constraint nn_sal_year not null,
salary number constraint chk_sal_sal check (salary > 0 ),
fullname varchar2(64) constraint unq_sal_fullname unique,
emp_id varchar2(12) constraint fk_sal_emp_id references emp1(eno));
To disable a constraint, use the alter table command. To enable a disabled constraint, again
use the alter table command. The following examples disables and then re-enables the salary
check condition
The following example demonstrates how to drop the constraints using constraint name,
alter table salary_table drop constraint unq_sal_fullname;
alter table salary_table drop constraint chk_sal_sal;
alter table salary_table drop constraint nn_sal_year;
alter table salary_table drop constraint fk_sal_emp_id;
In short, using this command we can name the different states of our data in any table and then
rollback to that state using the ROLLBACK command whenever required.
EXAMPLE :
DELETE COMMAND
SQL> delete from person where lastname='Kumar';
2 rows deleted.
SQL> select * from person;
PID LASTNAME FIRSTNAME ADDRESS AGE
------ ---------- ---------- ------------ --------
1 Prettina Anne BAngalore 14
2 Benitto Anish Trichy 24
3 Raj Anita Chennai 27
4 Hinn Benny Britain 55
5 Prakash Bhaskar Assam 40
SQL> rollback;
Rollback complete.
Lab Exercise
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30)
branch_city varchar2(30)
assets number(8,2)
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11)
branch_name varchar2(30)
balance number(8)
C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11)
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)
D) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)
account_no varchar2(11)
E) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4)
branch_name varchar2(30)
amount number(8,2)
F) NAME: borrower
FIELDS DATATYPE
customer_id varchar2(11)
loan_no varcahr2(4)
a. Add a new column ‘account opening date’ in the account table, which is of type Date.
b. Increase the width of the column customer_street in table customer to 20.
4. Add primary keys to all the tables for the specified attributes
A) NAME: branch
FIELDS DATATYPE
branch_name varchar2(30) primary key
branch_city varchar2(30)
assets number(8,2)
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30)
balance number(8)
C) NAME: customer
FIELD DATATYPE
customer_id varchar2(11) primary key
customer_name varchar2(20)
customer_street varchar2(15)
customer_city varchar2(15)
D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30)
amount number(8,2)
5. Add foreign keys to the following tables for the specified attributes with mentioned
reference table
B) NAME: account
FIELDS DATATYPE
account_no varchar2(11) primary key
branch_name varchar2(30) references branch(branch_name)
balance number(8)
C) NAME: depositor
FIELD DATATYPE
customer_id varchar2(11)references customer (customer_id)
account_no varchar2(11)references account (account_no)
D) NAME: loan
FIELDS DATATYPE
loan_no varchar2(4) primary key
branch_name varchar2(30) references branch(branch_name) (Create constraint
with constraint name)
amount number(8,2)
1. branch :
2. account :
3. loan :
5. customer
CUSTOMER_ID CUSTOMER_NAME CUSTOMER_STREET CUSTOMER_CITY
c_01 smith north rye
c_02 turner putnam stamford
c_03 johnson alma palo alto
c_04 curry north rye
c_05 jones main harrisdon
c_06 adoms spring pittsfield
c_07 lindsay park pittsfield
c_08 hayes main harrison
c_09 williams nassau Princeton
6. borrower
CUSTOMER_ID LOAN_NO
c_01 1_11
c_01 1_23
c_03 1_93
c_05 1_17
c_03 1_16
c_05 1_14
Simple Queries
1. Create Employee table and insert the values like given below
Emplo First_ Last_ Email Phone_Nu Hire_d Salar Comm Man Depar
yee_id Name Name mber ate y ission_ ager_ tment
pct id _id
101 selva kumar selva@xyz. 9350454613 05- 20000 .20 104 201
com JAN-
1990
102 muthu Kumar muthu@xyz 7250548158 08- 30000 .10 104 201
.com FEB-
1991
103 selva laksh Selva1@xyz 8795458162 40000 104 201
mi .com
104 anu Sree anu@xyz.co 8495188645 22- 60000 .10 104 202
m MAR-
1989
105 bharath Rajan bharathi@x 6548521486 25- 20000 105 202
i yz.com MAR-
1989
106 muthu Selvi 9874525842 26- 80000 .10 105 202
APR-
1994
107 devi Priya devi@xyz.c 8547962140 70000 .20 105 203
om
108 selva Kumar 7589632410 31- 30000 .10 108 203
i SEP-
1990
109 Tamil Arasi tamil@xyz. 8546231189 29- 50000 .50 108 204
com OCT-
1997
110 maha laxmi maha@xyz. 8745962311 70000 .10 108 204
com
2. Create a query to display the last name, hire date, and employee number for each
employee, with employee number appearing first.
SOLUTION:
10 rows selected.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where Salary>20000;
EMPLO FIRS LAST EMAI PHONE_ HIR SALA COMMI MAN DEPA
YEE_ID T_NA _NA L NUMBE E_D RY SSION_ AGE RTM
ME ME R ATE PCT R_ID ENT_
ID
---------------------------------------------------------------------------------------------------------------------
---------------------
104 anu Sree anu@ 8495188 22- 60000 .1 104 202
xyz.co 645 MAR
m -89
108 selva Kuma NULL 7589632 30- 30000 .1 108 203
ri 410 SEP-
90
102 muthu Kuma muthu 7250548 08- 30000 .1 104 201
r @xyz. 158 FEB-
com 91
103 selva laksh Selva1 8795458 40000 104 201
mi @xyz. 162
com
106 muthu Selvi NULL 9874525 26- 80000 .1 105 202
842 APR-
94
107 devi Priya devi@ 8547962 70000 .2 105 203
xyz.co 140
m
109 Tamil Arasi tamil 8542631 29- 50000 .5 108 204
@xyz. 189 OCT-
com 97
110 maha laxmi maha 8754962 70000 .1 108 204
@xyz. 311
com
8 rows selected.
4. Create a query to display the last name and salary of employees whose salary is not in
the range of 2000 and 80000. (hints: not between )
SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary not between 20000
and 60000;
LAST_NAME SALARY
------------------------- ----------
Selvi 80000
Priya 70000
laxmi 70000
5. Display the employee last name, job ID, and start date of employees hired between 01-
MAR-1989 and May 1,1995. (hints: between)
SOLUTION:
SQL> select Last_Name,Employee_id,Hire_date from EMPLOYEES_TABLE where Hire_date
between '01-MAR-1989' and '01-MAY-1995';
LAST_NAME EMPLOYEE_ID HIRE_DATE
------------------------- ----------- -----------------
Sree 104 22-MAR-89
Rajan 105 25-MAR-89
Kumari 108 30-SEP-90
Kumar 101 05-JAN-90
Kumar 102 08-FEB-91
Selvi 106 26-APR-94
6 rows selected.
8. Display the last name and salary of all employees who earn between 60000 and 80000
and are in departments 201 and 204 .
SOLUTION:
SQL> select Last_Name,Salary from EMPLOYEES_TABLE where Salary between 60000 and
80000 and Department_id in (201,204);
LAST_NAME SALARY
------------------------- ----------
laxmi 70000
9. Display the last name and hire date of every employee who was hired in 1994.
(hints: like)
SOLUTION:
SQL> select Last_Name,Hire_date from EMPLOYEES_TABLE where Hire_date like '%94';
LAST_NAME HIRE_DATE
------------------------- ---------
Selvi 26-APR-94
10. Display employee details who does not have mail-id.
SOLUTION:
SQL> select * from EMPLOYEES_TABLE where email=’NULL’;
No rows selected
SubQueries
A subquery is a SQL query nested inside a larger query.
Syntax :
The subquery (inner query) executes once before the main query (outer query) executes.
The main query (outer query) use the subquery result.
student marks
Now we want to write a query to identify all students who get better marks than that of
the student who's StudentID is 'V002', but we do not know the marks of 'V002'.
- To solve the problem, we require two queries. One query returns the marks (stored in
Total_marks field) of 'V002' and a second query identifies the students who get better
marks than the result of the first query.
First query:
SELECT *
FROM `marks`
WHERE studentid = 'V002';
Copy
Query result:
Above two queries identified students who get the better number than the student who's
StudentID is 'V002' (Abhay).
You can combine the above two queries by placing one query inside the other. The
subquery (also called the 'inner query') is the query inside the parentheses. See the
following code and query result :
SQL Code:
SELECT a.studentid, a.name, b.total_marks
FROM student a, marks b
WHERE a.studentid = b.studentid AND b.total_marks >
(SELECT total_marks
FROM marks
WHERE studentid = 'V002');
Copy
Query result:
Subqueries: Guidelines
There are some guidelines to consider when using subqueries :
Type of Subqueries
SQL Code:
INSERT INTO neworder
SELECT * FROM orders
WHERE advance_amount in(2000,5000);
Output:
2 rows inserted
SQL Code:
UPDATE neworder
SET ord_date='15-JAN-10'
WHERE ord_amount-advance_amount<
(SELECT MIN(ord_amount) FROM orders);
Output:
7 rows updated
SQL Code:
DELETE FROM neworder
WHERE advance_amount<
(SELECT MAX(advance_amount) FROM orders);
Output:
34 rows deleted.
Correlated Subqueries
SQL Correlated Subqueries are used to select data from a table referenced in the outer
query. The subquery is known as a correlated because the subquery is related to the outer
query. In this type of queries, a table alias (also called a correlation name) must be used
to specify which table reference is to be used.
The alias is the pet name of a table which is brought about by putting directly after the
table name in the FROM clause. This is suitable when anybody wants to obtain
information from two separate tables.
the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,the following SQL statement can be used:
SQL Code:
SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code=(
SELECT b.agent_code
FROM agents b WHERE b.agent_name='Alex');
Output:
We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS the
following query display the employee_id, manager_id, first_name and last_name of those
employees who manage other employees.
SQL Code:
SELECT employee_id, manager_id, first_name, last_name
FROM employees a
WHERE EXISTS
(SELECT employee_id
FROM employees b
Output:
FROM employees a
(SELECT employee_id
FROM employees b
Output:
SOLUTION:
SQL> select * from emp_training;
10 rows selected.
2. Copy records from the EMPLOYEES table whose salary is less than 60000 in to
Emp_training2 relation.
SOLUTION:
SQL> create table Emp_training2 as(select Employee_id,First_Name,Email,Phone_Number
from EMPLOYEES_TABLE where salary<60000);
Table created.
SQL> select * from emptraning2;
EMPID FNAME EMAILID PHNO
---------- -------------------- ---------------------------------------
105 bharathi bharathi@xyz.com 9442952654
108 selva NULL 9086543489
101 SELVA selva@xyz.com 9346790056
102 muthu muthu@xyz.com 9876545787
109 tamil tamil@xyz.com 9887654456
5 rows selected.
JOIN
SQL joins are used to fetch data from two or more tables, based on conditions between
tables.
There are various type of joins. Like
Equi-Joins
Self-Join
Outer-Join
Cross-Join
Exercise:
1. Fetch records from two tables emp, dept where deptno of employee is equal to dept
no of dept.
SELECT * FROM EMP E,DEPT D WHERE E.DEPTNO=D.DEPTNO;
2. Suppose there are two tables category and product.Both table contains category_id.
We want to fetch the records where both tables contain same category_id .
SELECT * FROM CATEGORIES C ,PRODUCTS P where P.CATEGORYID = C.CATEGORYID;
Another way to write it,like
SELECT * FROM CATEGORIES C INNER JOIN PRODUCTS P ON P.CATEGORYID =
C.CATEGORYID;
3. There are two table emp and dept. We want to fetch records of emp where deptno
between 10 and 20.
SELECT * FROM EMP E, DEPT D WHERE D.DEPTNO BETWEEN 10 AND 20;
4. In Emp table there are two columns empno and mgr. Fetch the records where
empno and mgr are same.
SELECT * FROM EMP E1, EMP E2 WHERE E1.EMPNO=E2.MGR;
5. In Employee_details table retrieve the record whose city are same.
SELECT * FROM EMPLOYEE_DETAILS E1,EMPLOYEE_DETAILS E2 WHERE
E1.CITY=E2.CITY;
6. Select an employee's department where they have not been assigned to a
department.
SELECT * FROM EMP LEFT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO(+);
7. List dept no., Dept name for all the departments in which there are no employees in
the department.
SELECT * FROM EMP RIGHT OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO;
8. Retrieve each employee who is in a department and each department that has an
employee and also each employee who is not part of a department and each department
which doesn't have an employee.
SELECT * FROM EMP FULL OUTER JOIN DEPT ON EMP.DEPTNO=DEPT.DEPTNO;
(OR)
SELECT * FROM EMP,DEPT EMP.DEPTNO(+)=DEPT.DEPTNO(+);
a. Modify the balance attribute alone such that it decreases the amount by 10% for the
account table
b. Delete all the account tuples in the ‘Redwood’ branch.
c. Delete all loans with loan amounts between 15000 to 20000.
d. Find the names of all branches in the loan relation.
e. Display all the Customer names whose come from either pittsfield or stamford.
f. Find all loan numbers for loans made at the ‘Perryridge’ branch with loan amount greater
than 1200.
g. Find loan numbers of those loans with loan amount between 10000 and 20000.
h. Display the customer name in alphabetical order
i. Display all the customer names ordered by customer city
j. Give a count of how many account holds are in each branch.