Uploaded by Shubham Sharma

Practical file DBMS

advertisement
Apeejay Institute of Management &
Engineering Technical Campus, Jalandhar
Practical File
On
Data Base Management System
UGCA 1925
Submitted by:
Shubham Sharma
BCA (Sem 4)
Roll No: 204017
Uni Roll No: 2026276
Submitted to:
Mr. Daljeet Singh Matharu
Practical 1
Use of CREATE, ALTER, RENAME and DROP statement in the database tables
(relations)
a) The CREATE table statement is used to create a new table in a database.
Ex:
CREATE TABLE Student(
s_ID int,
s_Name varchar(30),
Class varchar(10),
City varchar(20) );
b) The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
Ex:
ALTER TABLE Student
ADD s_Mobile varchar(11);
c) The ALTER TABLE can also use to rename the name of table.
Ex:
ALTER TABLE Student
RENAME COLUMN s_ID TO Roll_No;
d) The DROP TABLE statement is used to drop an existing table in a database.
Ex:
DROP TABLE Student;
Practical 2:
Use of INSERT INTO, DELETE and UPDATE statement in the database tables
(relations).
a) The INSERT INTO statement is used to insert new records in a table.
Ex:
INSERT INTO Student
VALUES (2001,”xyz”,”BCA”,”Jalandhar’”,”1122334455”);
b) The UPDATE statement is used to modify the existing records in a table.
Ex:
UPDATE Student
SET s_name = “Shubham” WHERE Roll_no =2001;
c) The DELETE statement is used to delete existing records in a table.
Ex:
DELETE FROM Student WHERE s_Name=”Shubham”;
Practical 3:
Use of simple select statement and use of select query on two relations.
SQL SELECT Statement
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from. If
you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
Example:
SELECT * FROM Customers;
SELECT query on multiple relations:
Using SELECT to query data from a single table and multiple tables
Hrishikesh Gore—12/7/2019Developers
SUMMARY: This article covers the SELECT statement in PostgreSQL and how to use it to
query data from single and multiple tables:
1. Overview for SELECT statement
2. Retrieving methods from the database
1. From a single table
2. From multiple tables
3. Using standard joins
4. Using subquery
Overview for the SELECT statement
PostgreSQL is based on the Relational Database Management System (RDBMS). Data can
be stored in the following hierarchy :
Database Cluster
-> Database/s
-> Schema/s
-> Table/s
To retrieve data from any specific table, we have to use the SELECT statement.
The SELECT statement can be divided into three main parts:
Syntax:
SELECT <list_of_columns> FROM <list_of_table_names> WHERE <conditions> ;
<list_of_columns>: specifies the column names that need to be retrieved from that particular
table or tables.
<list_of_table_names>: the tables from which to retrieve the data.
<conditions>: optional parameters used for any further restrictions on the data.
Retrieving methods from database
From a single table
To retrieve all the information from single table you can use the following format :
Syntax :
SELECT * FROM <table_name>;
For example :
SELECT * FROM emp;
Output:
To retrieve specific information from a single table, we can simply define the specific
column names and apply conditions for the table :
We can use ‘AS’ for alias or used to assign temporarily a new name to a table column.
For example :
SELECT empno as employee_id, ename as employee_name, job as job_title
FROM emp
WHERE sal BETWEEN 1000 AND 5000;
Output :
From multiple tables
To retrieve information from more than one table, you need to join those tables
together. This can be done using JOIN methods, or you can use a second SELECT
statement inside your main SELECT query—a subquery.
Using Joins
Joins are used to retrieve rows from two or more tables, based on a related column between
those tables.
Syntax :
SELECT <list_of_column_names> FROM <table1> , <table2> … <tableN> WHERE
<conditions>;
For example :
SELECT e.empno as employee_id, e.ename as employee_name, d.dname as
department_name, d.loc as location
FROM emp e , dept d
WHERE e.deptno=d.deptno AND e.deptno IN (10,30);
Practical 4:
Use of aggregate functions.
SQL Aggregate Functions:SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.
It is also used to summarize the data.
Types of SQL Aggregation Function:1. COUNT FUNCTION
COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax:
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax:
SUM()
or
SUM( [ALL|DISTINCT] expression )
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax:
AVG()
or
AVG( [ALL|DISTINCT] expression )
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax:
MAX()
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax:
MIN()
or
MIN( [ALL|DISTINCT] expression )
Practical 5:
Use of substring comparison and use of order by statement.
SQL Server SUBSTRING() Function:
Definition and Usage:
The SUBSTRING() function extracts some characters from a string.
Syntax:
SUBSTRING(string, start, length)
Example:
Extract 5 characters from the "CustomerName" column, starting in position 1:
SELECT SUBSTRING(CustomerName, 1, 5) AS ExtractString
FROM Customers;
SQL ORDER BY Keyword
The SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
ORDER BY Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example:
SELECT * FROM Customers
ORDER BY Country;
Practical 6:
Consider the following schema for a Library Database:
BOOK (Book_id, Title, Publisher_Name, Pub_Year)
BOOK_AUTHORS (Book_id, Author_Name)
PUBLISHER (Name, Address, Phone)
BOOK_COPIES (Book_id, Branch_id, No-of_Copies)
BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)
LIBRARY_BRANCH (Branch_id, Branch_Name, Address)
Write SQL queries to
1. Retrieve details of all books in the library_id, title, name of publisher, authors,
number of copies in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books between Jan
2018 to Jun 2018
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with
a simple query.
5. Create a view of all books and its number of copies that are currently available in the
Library.
Solution:
Table Creation
CREATE TABLE PUBLISHER
(PNAME VARCHAR2 (20) PRIMARY KEY,
PHONE INTEGER,
ADDRESS VARCHAR2 (20));
CREATE TABLE BOOK
(BOOK_ID INTEGER PRIMARY KEY,
TITLE VARCHAR2(20),
PUB_YEAR VARCHAR2 (20),
PUBLISHER_PNAME REFERENCES PUBLISHER (PNAME) ON DELETE CASCADE);
CREATE TABLE BOOK_AUTHORS
(AUTHOR_NAME VARCHAR2 (20),
BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
PRIMARY KEY (BOOK_ID, AUTHOR_NAME));
CREATE TABLE LIBRARY_BRANCH (
BRANCH_ID INTEGER PRIMARY KEY, BRANCH_NAME VARCHAR (50),
ADDRESS VARCHAR2 (50));
CREATE TABLE BOOK_COPIES
(NO_OF_COPIES INTEGER,
BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
BRANCH_ID REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON DELETE
CASCADE,
PRIMARY KEY (BOOK_ID, BRANCH_ID));
CREATE TABLE CARD
(CARD_NO INTEGER PRIMARY KEY);
CREATE TABLE BOOK_LENDING
(DATE_OUT DATE,
DUE_DATE DATE,
BOOK_ID REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
BRANCH_ID REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON DELETE
CASCADE,
CARD_NO REFERENCES CARD (CARD_NO) ON DELETE CASCADE,
PRIMARY KEY (BOOK_ID, BRANCH_ID, CARD_NO));
Inserting Values:
INSERT INTO PUBLISHER VALUES ('EMCGRAW-HILL', 9989076587,
'EBANGALORE');
INSERT INTO PUBLISHER VALUES ('EPEARSON', 9889076565, 'ENEWDELHI');
INSERT INTO PUBLISHER VALUES ('ERANDOM HOUSE',
7455679345,'EHYDRABAD');
INSERT INTO PUBLISHER VALUES ('EHACHETTE LIVRE', 8970862340,'ECHENAI');
INSERT INTO PUBLISHER VALUES
('EGRUPOPLANETA',7756120238,'EBANGALORE');
INSERT INTO BOOK VALUES (1,'DBMS','JAN-2018','EMCGRAW-HILL');
INSERT INTO BOOK VALUES (2,'ADBMS','JUN-2016','EMCGRAW-HILL');
INSERT INTO BOOK VALUES (3,'CN','SEP-2016', 'EPEARSON');
INSERT INTO BOOK VALUES (5,'OS','MAY-2016', 'EPEARSON');
INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 1);
INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 2);
INSERT INTO BOOK_AUTHORS VALUES ('TANENBAUM', 3);
INSERT INTO BOOK_AUTHORS VALUES ('EDWARD ANGEL', 4);
INSERT INTO BOOK_AUTHORS VALUES ('GALVIN', 5);
INSERT INTO LIBRARY_BRANCH VALUES (10,'RR NAGAR','BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (11,'RNSIT','BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (12,'RAJAJI NAGAR', 'BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (13,'NITTE','MANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (14,'MANIPAL','UDUPI');
INSERT INTO BOOK_COPIES VALUES (10, 1, 10);
INSERT INTO BOOK_COPIES VALUES (5, 1,11);
INSERT INTO BOOK_COPIES VALUES (2, 2,12);
INSERT INTO BOOK_COPIES VALUES (5, 2,13);
INSERT INTO BOOK_COPIES VALUES (7, 3,14);
INSERT INTO BOOK_COPIES VALUES (1, 5,10);
INSERT INTO BOOK_COPIES VALUES (3, 4,11);
INSERT INTO CARD VALUES (100);
INSERT INTO CARD VALUES (101);
INSERT INTO CARD VALUES (102);
INSERT INTO CARD VALUES (103);
INSERT INTO CARD VALUES (104);
INSERT INTO BOOK_LENDING VALUES ('01-JAN-18','01-JUN-18', 1, 10, 101);
INSERT INTO BOOK_LENDING VALUES ('11-JAN-18','11-MAR-18', 3, 14, 101);
INSERT INTO BOOK_LENDING VALUES ('21-FEB-18','21-APR-18', 2, 13, 101);
INSERT INTO BOOK_LENDING VALUES ('15-MAR-18','15-JUL-18', 4, 11, 101);
INSERT INTO BOOK_LENDING VALUES ('12-APR-18','12-MAY-18', 1, 11, 104);
Queries:
1:
SELECT B.BOOK_ID, B.TITLE, B.PUBLISHER_PNAME, A.AUTHOR_NAME,
C.NO_OF_COPIES,L.BRANCH_ID
FROM BOOK B, BOOK_AUTHORS A, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=A.BOOK_ID AND B.BOOK_ID=C.BOOK_ID AND
L.BRANCH_ID=C.BRANCH_ID;
2.
SELECT CARD_NO FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN '01-JAN-2018' AND '01-JUL-2018';
GROUP BY CARD_NO HAVING COUNT (*)>3;
3.
DELETE FROM BOOK
WHERE BOOK_ID=3;
4.
CREATE VIEW V_PUBLICATION AS SELECT
PUB_YEAR
FROM BOOK;
5.
CREATE VIEW V_BOOKS AS
SELECT B.BOOK_ID, B.TITLE, C.NO_OF_COPIES
FROM BOOK B, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=C.BOOK_ID
AND C.BRANCH_ID=L.BRANCH_ID;
Practical 7
Consider the following schema for Order Database:
SALESMAN (Salesman_id, Name, City, Commission)
CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
ORDERS (Ord_No, Purchase_Amt, Ord_Date, Customer_id, Salesman_id)
Write SQL queries to
1. Count the customers with grades above Amritsar’s average.
2. Find the name and numbers of all salesmen who had more than one
customer.
3. List all salesmen and indicate those who have and don’t have customers
in their cities (Use UNION operation.)
4. Create a view that finds the salesman who has the customer with the
highest order of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000.
All his orders must also be deleted.
Solution:
Table Creation
CREATE TABLE SALESMAN
(SALESMAN_ID NUMBER (4),
SNAME VARCHAR2 (20),
CITY VARCHAR2 (20),
COMMISSION VARCHAR2 (20),
PRIMARY KEY (SALESMAN_ID));
CREATE TABLE CUSTOMER1
(CUSTOMER_ID NUMBER (4),
CUST_NAME VARCHAR2 (20),
CITY VARCHAR2 (20),
GRADE NUMBER (3),
PRIMARY KEY (CUSTOMER_ID),
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE SET
NULL);
CREATE TABLE ORDERS
(ORD_NO NUMBER (5),
PURCHASE_AMT NUMBER (10, 2),
ORD_DATE DATE,
PRIMARY KEY (ORD_NO),
CUSTOMER_ID REFERENCES CUSTOMER1 (CUSTOMER_ID) ON DELETE
CASCADE,
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE
CASCADE);
Inserting Values
INSERT INTO SALESMAN VALUES (1000, 'kajal','AMRITSAR','25 %');
INSERT INTO SALESMAN VALUES (2000,'akshay','BANGALORE','20 %');
INSERT INTO SALESMAN VALUES (3000, 'abhishek','MYSORE','15 %');
INSERT INTO SALESMAN VALUES (4000, 'rohan','DELHI','30 %');
INSERT INTO SALESMAN VALUES (5000,'ishan','HYDRABAD','15 %');
INSERT INTO CUSTOMER1 VALUES (10, 'soya','AMRITSAR', 100, 1000);
INSERT INTO CUSTOMER1 VALUES (11, 'kartik','MANGALORE', 300, 1000);
INSERT INTO CUSTOMER1 VALUES (12, 'kamal','CHENNAI', 400, 2000);
INSERT INTO CUSTOMER1 VALUES (13, 'palak','AMRITSAR', 200, 2000);
INSERT INTO CUSTOMER1 VALUES (14, 'vishal','BANGALORE', 400, 3000);
INSERT INTO ORDERS VALUES (50, 5000, '04-MAY-22', 10, 1000);
INSERT INTO ORDERS VALUES (51, 450, '20-JAN-22', 10, 2000);
INSERT INTO ORDERS VALUES (52,1000,'24-FEB-22',13,2000);
INSERT INTO ORDERS VALUES (53,3500,'13-APR-22',14,3000);
INSERT INTO ORDERS VALUES (54, 550, '09-MAR-22', 12, 2000);
Queries
1.
SELECT GRADE, COUNT (DISTINCT CUSTOMER_ID) FROM CUSTOMER1
GROUP BY GRADE HAVING GRADE > (SELECT AVG(GRADE)
FROM CUSTOMER1 WHERE CITY='AMRITSAR');
2.
SELECT SALESMAN_ID, SNAME FROM SALESMAN A
WHERE 1 < (SELECT COUNT (*) FROM CUSTOMER1
WHERE SALESMAN_ID=A.SALESMAN_ID);
3.
SELECT SALESMAN.SALESMAN_ID, SNAME, CUST_NAME, COMMISSION FROM
SALESMAN, CUSTOMER1
WHERE SALESMAN.CITY = CUSTOMER1.CITY UNION
SELECT SALESMAN_ID, SNAME, 'NO MATCH', COMMISSION FROM SALESMAN
WHERE NOT CITY = ANY (SELECT CITY FROM CUSTOMER1) ORDER BY 2 DESC;
4.
CREATE VIEW ELITSALESMAN AS
SELECT B.ORD_DATE, A.SALESMAN_ID, A.SNAME FROM SALESMAN A,
ORDERS B
WHERE A.SALESMAN_ID = B.SALESMAN_ID
AND B.PURCHASE_AMT=(SELECT MAX (PURCHASE_AMT)FROM ORDERS C
WHERE C.ORD_DATE = B.ORD_DATE);
5.
DELETE FROM SALESMAN
WHERE SALESMAN_ID=1000;
Practical 8
Write a PL/SQL code to add two numbers and display the result. Read the
numbers during run time and Write a program to create a trigger which will
convert the name of a student to uppercase before inserting or updating the
name column of student table.
Sum Of Two Numbers in PL/SQL:
In PL/SQL code groups of commands are arranged within a block. A block group related
declarations or statements.
In declare part, we declare variables and between begin and end part, we perform the
operations. Here, first, we take three variables x, y, and z and assign the value in x and y and
after addition of both the numbers, we assign the resultant value to z and print z.
Program:
declare
-- declare variable x, y
-- and z of datatype number
x number(5);
y number(5);
z number(7);
begin
-- Here we Assigning 10 into x
x:=10;
-- Assigning 20 into x
y:=20;
-- Assigning sum of x and y into z
z:=x+y;
Print the Result
dbms_output.put_line('Sum is '||z);
end;
/
-- Program End
Practical 9:
Write a PL/SQL block to count the number of rows affected by an update
statement using SQL%ROW COUNT.
Program:
SET SERVEROUTPUT ON
DECLARE
avg_1 NUMBER;
avg_2 NUMBER;
var_rows NUMBER;
BEGIN
SELECT AVG(salary) INTO avg_1 FROM employees where department_id=10;
SELECT AVG(salary) INTO avg_1 FROM employees where department_id=20;
if avg_1 > avg_2 THEN
UPDATE employees SET salary=(salary *20/100)+ salary
where department_id=20;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
end if;
end;
Practical 10:
Write a PL/SQL block to increase the salary of all doctors by 1000.
Program:
CREATE TABLE doc_emp AS
SELECT dEMP_id, first_name, last_name, department_id, salary
FROM employees;
DECLARE
CURSOR employee_cur IS
SELECT dEMP_id, salary
FROM emp_temp
WHERE department_id = 50
FOR UPDATE;
incr_sal NUMBER;
BEGIN
FOR employee_rec IN employee_cur LOOP
IF employee_rec.salary < 9000 THEN
incr_sal := 1000;
UPDATE emp_temp
SET salary = salary + salary * incr_sal
WHERE CURRENT OF employee_cur;
END LOOP;
END;
/
Download