'DBMS LAB (1-9) ' With You
'DBMS LAB (1-9) ' With You
'DBMS LAB (1-9) ' With You
AIM:
To write a program for SQL Data Definition Language Commands on sample exercise
PROCEDURE:
• CREATE – is used to create the database or its objects (like table, index, function, views, store
procedure and triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including all spaces allocated for the
records are removed.
• COMMENT –is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.
1 - i) CREATE TABLE
Rules:
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. Different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
Syntax:
ii) DESC
SQL>desc tablename;
Syntax:
CREATE TABLE new_table_name AS SELECT column1, column2,... FROM existing_table_name WHERE ....;
2- DROP TABLE
Syntax:
SQL>DROP TABLE <TABLENAME>;
3- ALTER COMMAND
i) - ADD COMMAND
Syntax:
SQL>alter table tablename add/modify (attribute datatype(size));
4- TRUNCATE TABLE
If there is no further use of records stored in a table and the structure has to be retained then the
records alone can be deleted.
Syntax:
SQL>TRUNCATE TABLE <TABLE NAME>;
5- COMMENT
• Single line comments: Comments starting and ending in a single line are considered as single
line comments.
Line starting with ‘–‘ is a comment and will not be executed.
Syntax:
• Multi line comments: Comments starting in one line and ending in different line are
considered as multi line comments. Line starting with ‘/*’ is considered as starting point of
comment and are terminated when ‘*/’ is encountered.
Syntax:
• In line comments: In line comments are an extension of multi line comments, comments can
be stated in between the statements and are enclosed in between ‘/*’ and ‘*/’.
Syntax:
6- RENAME
If you want to change the name of the table in the SQL database because they want to give a
more relevant name to the table. Any database user can easily change the name by using the RENAME
TABLE and ALTER TABLE statement in Structured Query Language.
Syntax:
SQL>RENAME old_table _name To new_table_name ;
Program:
SQL> connect
Enter user-name: system
Enter password: admin
Connected.
Table created.
Table altered.
Table altered.
Table altered.
Table altered.
Table dropped.
ID NAME DEPT
---------- ---------- ----------
1 aaa cse
2 aaa cse
3 aaa ece
4 aaa cse
5 aaa cse
Table truncated.
no rows selected
Table dropped.
Result:
Hence, the above query has been implemented successfully.
EX.NO:2
DATE:
AIM:
To create a database using Data Manipulation Commands for inserting, deleting, updating and
retrieving tables and Transaction Control statements.
DESCRIPTION:
Data manipulation language (DML) statements access and manipulate data in existing
tables. DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are Insert, Select, Update,
Delete.
Examples of DML:
1) Insert Command: This is used to add one or more rows to a table. The values are
separated by commas and the data types char and date are enclosed in apostrophes.
The values must be entered in the same order as they are defined.
4) Delete command: After inserting row in a table we can also delete them if required.
The delete command consists of a from clause followed by an optional where clause.
Create table:
Insert more than a record into persons table using a single insert command.
SELECT COMMAND
It is used to retrieve information from the table. It is generally referred to as querying the
table. We can either display all columns in a table or only specify column from the table.
Syntax:
SQL> Select * from tablename; // This query selects all rows from the table.
Example:
Example:
SQL>Select DISTINCT lastname from persons;
To select specific rows from a table we include ‘where’ clause in the select command. It
can appear only after the ‘from’ clause.
Example:
Syntax:
Example:
SQL>create table persons1 as select * from persons;
Table created
Example: SQL>Select * from persons where pid between 100 and 500;
Syntax:
UPDATE table_nameSET column_name = value [, column_name = value]...
[ WHERE condition ];
Table updated.
DELETE COMMAND
1 row deleted.
RESULT:
Thus the database has been created and the data has been inserted, deleted, modified, altered,
updated and records are viewed based on conditions.
EX.NO:3
DATE:
AIM:
To create a database using Data Control Commands and Transaction Control Commands to
manage transactions in the database.
DESCRIPTION:
Transaction Control Language (TCL) commands are used to manage transactions in the
database. These are used to manage the changes made by DML-statements. It also allows
statements to be grouped together into logical transactions.
Examples of TCL:
(i) Commit
(ii) Rollback
(iii) Savepoint
Syntax: commit;
(ii)Rollback: Rollback Command restores database to original since the last Commit.
Syntax: ROLLBACK TO SAVEPOINT <savepoint_name>;
(iii) Savepoint:
SAVEPOINT command is used to temporarily save a transaction so that you can rollback
to that point whenever required.
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.
Syntax:SAVEPOINT <savepoint_name>;
Data Control Language
Data Control Language (DCL) is used to control privileges in Database. To perform any
operation in the database, such as for creating tables, sequences or views, a user needs privileges.
Privileges are of two types,
● System: This includes permissions for creating session, table, etc and all types of other
system privileges.
● Object: This includes permissions for any command or query to perform any operation on
the database tables.
● GRANT: Used to provide any user access privileges or other privileges for the database.
Thus the Data Control Language commands and Transaction Control Language commands were
executed successfully.
EX.NO:4 SQL FUNCTIONS
AIM
DESCRIPTION:
1. Aggregate Functions
2. Scalar Functions
Function Description
SUM() Used to return the sum of a group of values.
COUNT() Returns the number of rows either based on a condition, or without a condition.
AVG() Used to calculate the average value of a numeric column.
MIN() This function returns the minimum value of a column.
MAX() Returns a maximum value of a column.
FIRST() Used to return the first value of the column.
LAST() This function returns the last value of the column.
Function Description
LCASE() Used to convert string column values to lowercase
UCASE() This function is used to convert a string column values to Uppercase.
LEN() Returns the length of the text values in the column.
MID() Extracts substrings in SQL from column values having String data type.
ROUND() Rounds off a numeric value to the nearest integer.
NOW() This function is used to return the current system date and time.
FORMAT() Used to format how a field must be displayed.
EXAMPLE:
CHARACTER/STRING FUNCTION:
OUTPUT:
NUMERIC FUNCTION
OUTPUT:
MATH FUNCTION:
RESULT:
1. Vertabelo
2. Creatly
3. ERDPlus
4. Lucidchart
5. Visual Paradigm Online
6. Draw.io
7. Microsoft Visio
8. Gliffy
9. SqlDBM ER Diagram Online Tool
10. ER Draw Max
S.No. Problem Statement
(a) Construct an E-R diagram for a hospital with a set of patients and a set of medical
doctors. Associate with each patient a log of the various tests and examinations
conducted.
ER Diagram:
Consider a database used to record the marks that students get in different exams of different
course offerings.
a) Construct an E-R diagram that models exams as entities, and uses a ternary relationship, for
the above database.
6
b) Construct an alternative E-R diagram that uses only a binary relationship between students
and course-offerings. Make sure that only one relationship exists between a particular student
and course-offering pair, yet you can represent the marks that a student gets in different
exams of a course offering.
ER Diagram:
7
Consider a university database for the scheduling of classrooms for -final exams. This database
could be modeled as the single entity set exam, with attributes course-name, sectionnumber,
room-number, and time. Alternatively, one or more additional entity sets could be defined, along
with relationship sets to replace some of the attributes of the exam entity set, as
• course with attributes name, department, and c-number
• section with attributes s-number and enrollment, and dependent as a weak entity set on
course
• room with attributes r-number, capacity, and building
Show an E-R diagram illustrating the use of all three additional entity sets listed.
• Company organized into DEPARTMENT. Each department has unique name and a
particular employee who manages the department. Start date for the manager is recorded.
Department may have several locations.
• A department controls a number of PROJECT. Projects have a unique name, number and
9 a single location.
• Company’s EMPLOYEE name, ssno, address, salary, sex and birth date are recorded. An
employee is assigned to one department, but may work for several projects (not
necessarily controlled by her dept). Number of hours/week an employee works on each
project is recorded; The immediate supervisor for the employee.
• Employee’s DEPENDENT are tracked for health insurance purposes (dependent name,
birthdate, relationship to employee).
Design an E-R diagram for Customer Account.
10
EX.NO:6 NESTED QUERIES
AIM:
DESCRIPTION:
Nested query is one of the most useful functionalities of SQL. Nested queries are useful
when we want to write complex queries where one query uses the result from another query.
Nested queries will have multiple SELECT statements nested together. A SELECT statement
nested within another SELECT statement is called a subquery.
A nested query in SQL contains a query inside another query. The result of the inner query
will be used by the outer query. For instance, a nested query can have two SELECT statements,
one on the inner query and the other on the outer query.
In independent nested queries, the execution order is from the innermost query to the outer
query. An outer query won't be executed until its inner query completes its execution. The result
of the inner query is used by the outer query. Operators such as IN, NOT IN, ALL, and ANY are
used to write independent nested queries.
The IN operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.
The NOT IN operator checks if a column value in the outer query's result is not present in the
inner query's result. The final result will have rows that satisfy the NOT IN condition.
The ALL operator compares a value of the outer query's result with all the values of the inner
query's result and returns the row if it matches all the values.
The ANY operator compares a value of the outer query's result with all the inner query's result
values and returns the row if there is a match with any value.
2. Co-related Nested Queries
In co-related nested queries, the inner query uses the values from the outer query so that
the inner query is executed for every row processed by the outer query. The co-related nested
queries run slowly because the inner query is executed for every row of the outer query's result.
The SELECT query inside the brackets (()) is the inner query, and the SELECT query
outside the brackets is the outer query. The result of the inner query is used by the outer query.
EXAMPLE:
TABLE #1 - employeedata
SQL> CREATE TABLE employeedata(id NUMBER PRIMARY KEY, name VARCHAR2(25) NOT
NULL, salary NUMBER NOT NULL, role VARCHAR2(15) NOT NULL);
Table created.
SQL> INSERT INTO employeedata VALUES (1, 'Augustine Hammond', 10000, 'Developer');
1 row created.
SQL> INSERT INTO employeedata VALUES (2, 'Perice John', 10000, 'Manager');
1 row created.
SQL> INSERT INTO employeedata VALUES (3, 'Ragu Delafoy', 30000, 'Developer');
1 row created.
SQL> INSERT INTO employeedata VALUES (4, 'Teakwood Saffen', 40000, 'Manager');
1 row created.
SQL> INSERT INTO employeedata VALUES (5, 'Freddy Malcom', 50000, 'Developer');
1 row created.
OUTPUT:
TABLE #2 - awards
OUTPUT:
ID EMPLOYEE_ID AWARD_DAT
---------- ------------------ ----------------
1 1 01-APR-22
2 3 01-MAY-22
Independent Nested Queries
Example 1: IN
SQL> SELECT id, name FROM employeedata WHERE id IN (SELECT employee_id FROM
awards);
OUTPUT:
ID NAME
---------- -------------------------
1 Augustine Hammond
3 Ragu Delafoy
Example 2: NOT IN
SQL> SELECT id, name FROM employeedata WHERE id NOT IN (SELECT employee_id FROM
awards);
OUTPUT:
ID NAME
---------- -------------------------
2 Perice John
4 Teakwood Saffen
5 Freddy Malcom
Example 3: ALL
• Select all Developers who earn more than all the Managers
SQL> SELECT * FROM employeedata WHERE role = 'Developer' AND salary > ALL (SELECT
salary FROM employeedata WHERE role = 'Manager');
OUTPUT:
ID NAME SALARY ROLE
---------- ------------------------- ---------- ---------------
5 Freddy Malcom 50000 Developer
Example 4: ANY
OUTPUT:
• Select all employees whose salary is above the average salary of employees in
their role.
Example:
SQL> SELECT * FROM employeedata emp1 WHERE salary > (SELECT AVG(salary) FROM
employeedata emp2 WHERE emp1.role = emp2.role);
OUTPUT:
Explanation
The manager with id 4 earns more than the average salary of all managers (25000), and
the developer with id 5 earns more than the average salary of all developers (30000). The inner
query is executed for all rows fetched by the outer query. The role value (emp1.role) of every outer
query's row is used by the inner query (emp1.role = emp2.role).
• We can find the average salary of managers and developers using the below query:
SQL> SELECT role, AVG(salary) FROM employeedata GROUP BY role;
OUTPUT:
ROLE AVG(SALARY)
--------------- -----------
Developer 30000
Manager 25000
RESULT:
Thus the study the various SQL nested queries operations on the database is executed
successfully.
EX.NO:7 JOIN QUERIES
AIM
PROCEDURE:
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
1. (INNER) JOIN: Returns records that have matching values in both tables
Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
2. LEFT JOIN: Returns all records from the left table, and the matched records from the
right table
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right
table
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
EXAMPLE:
Table created.
ORDER_ID NUMBER(5)
ORDERNO NUMBER(5)
P_ID NUMBER(3)
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
DISPLAYING DATA FROM TABLE PRODUCTORDERS
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Table created.
1 row created.
1 row created.
1 row created.
OUTPUT
FIRSTNAME CITY
--------------- ----------
Kim AP
Kim AP
Jadon Chennai
Jadon Chennai
#2 LEFT JOIN
OUTPUT
Hemal Elango
OUTPUT
34764
OUTPUT
LASTNAME ADDRESS
---------- --------------------
Smith Ramapuram
Smith Ramapuram
Lanser Hyderabad
Lanser Hyderabad
6 rows selected.
RESULT:
Thus the various SQL Join queries operations on the database have been executed
successfully.
Ex.No:8
Date:
AIM:
PROCEDURE:
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
• The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
• In the union operation, all the number of datatype and columns must be same in
both the tables on which UNION operation is being applied.
• The union operation eliminates the duplicate rows from its resultset.
Syntax:
2. Union All
• Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.
Syntax:
SELECT column_name FROM table1 UNION ALL SELECT column_name FROM table2;
3. Intersect
• It is used to combine two SELECT statements. The Intersect operation returns
the common rows from both the SELECT statements.
• In the Intersect operation, the number of datatype and columns must be the
same.
• It has no duplicates and it arranges the data in ascending order by default.
Syntax:
4. Minus
• It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
• It has no duplicates and data arranged in ascending order by default.
Syntax:
Output:
SQL provides the concept of VIEW, which hides the complexity of the data and restricts
unnecessary access to the database.
It permits the users to access only a particular column rather than the whole data of the
table.
The View in the Structured Query Language is considered as the virtual table, which
depends on the result-set of the predefined SQL statement.
To create a View from multiple tables by including the tables in the SELECT statement.
A view in SQL can only be modified if the view follows the following conditions:
1. You can update that view which depends on only one table. SQL will not allow
updating the view which is created more than one table.
2. The fields of view should not contain NULL values.
3. The view does not contain any subquery and DISTINCT keyword in its definition.
4. The views cannot be updatable if the SELECT statement used to create a View contains
JOIN or HAVING or GROUP BY clause.
5. If any field of view contains any SQL aggregate function, you cannot modify the view.
Syntax to Update a View
Just like the insertion process of database tables, we can also insert the record in the
views. The following SQL INSERT statement is used to insert the new row or record in the
view:
Syntax:
Just like the deletion process of database tables, we can also delete the record from the
views. The following SQL DELETE statement is used to delete the existing row or record from
the view:
Syntax
DELETE FROM View_Name WHERE Condition;
Drop a View
To delete the existing view from the database if it is no longer needed the following
SQL DROP statement is used to delete the view:
Syntax:
DROP VIEW View_Name;
RESULT:
Thus the SQL queries for implementing the set operators and views are executed
successfully.
EX.NO: 9
PL/SQL CONDITIONAL AND ITERATIVE STATEMENTS
AIM
To study the various basic PL/SQL Conditional and Iterative Statements on the database.
DESCRIPTION:
The iterative statements are used to repeat the execution of certain statements multiple
times. This is achieved with the help of loops. Loops in PL/SQL provide a mechanism to perform
specific tasks multiple times without having to write them multiple times.
This article will discuss three main types of loops:
• Basic loop
• WHILE loop
• FOR loop
Basic loop
The basic loop will execute the statement provided a certain number of times until the exit
condition is met. It is necessary to have an EXIT statement so that the loop does not run
indefinitely. There is also an increment statement that can be used to increase/decrease the
changing variable in the loop.
Syntax:
LOOP
Statements;
[increment_statement]
EXIT condition;
END LOOP;
WHILE loop
The WHILE loop in PL/SQL is used to check the entry condition, and if the entry condition
is true, only then is the loop executed. The basic loop executes at least once, whereas the WHILE
loop will first check the condition provided in the boolean expression. If the condition is false, the
control does not enter the loop.
Syntax:
WHILE (boolean_expression) LOOP
statements ;
[increment_statement]
END LOOP;
FOR loop
The FOR loop in PL/SQL provides implicit variable declaration, implicit incrementation
of the variable by one, and implicit exit also. In the FOR loop, we do not have to declare the
variable as we did in the previous two types of loop. While writing the loop statement, the variable
is declared implicitly. The range consists of the starting value, from where the value of the iterating
variable begins, and the end value, which determines the last value which the variable can have.
In each loop, the variable is incremented by one.
Syntax:
FOR variable IN range LOOP
Statements;
END LOOP;
EXAMPLES:
SQL> declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
end;
/
INPUT:
OUTPUT:
sum of23and12is35
PL/SQL procedure successfully completed.
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF(CONDITION)THEN
<EXECUTABLE STATEMENT >;
END;
Coding for If Statement:
DECLARE
b number;
c number;
BEGIN
B:=10;
C:=20; if(C>B)
THEN
dbms_output.put_line('C is maximum');
end if;
end;
/
OUTPUT:
C is maximum
PL/SQL procedure successfully completed.
3. PL/ SQL GENERAL SYNTAX FOR IF AND ELSECONDITION:
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF (TEST CONDITION) THEN
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;
******************Less then or Greater Using IF ELSE **********************
SQL> declare
n number;
begin
dbms_output. put_line('enter a number');
n:=&number;
if n<5 then
dbms_output.put_line('entered number is less than 5');
else
dbms_output.put_line('entered number is greater than 5');
end if;
end;
/
INPUT
OUTPUT:
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
IF (TEST CONDITION) THEN
<STATEMENTS>;
ELSEIF (TEST CONDITION) THEN
<STATEMENTS>;
ELSE
<STATEMENTS>;
ENDIF;
END;
********** GREATEST OF THREE NUMBERS USING IF ELSEIF************
SQL> declare
a number;
b number;
c number;
d number;
begin
a:=&a;
b:=&b;
c:=&b;
if(a>b)and(a>c) then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
/
INPUT:
C is maximum
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
LOOP
<STATEMENT>;
END LOOP;
<EXECUTAVLE STATEMENT>;
END;
***********SUMMATION OF ODD NUMBERS USING FOR LOOP***********
SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum ='||sum1);
end;
/
INPUT:
Enter value for endvalue: 4
old 6: endvalue:=&endvalue;
new 6: endvalue:=4;
OUTPUT:
sum =4
PL/SQL procedure successfully completed.
6.PL/ SQL GENERAL SYNTAX FOR LOOPING STATEMENT:
SQL> DECLARE
<VARIABLE DECLARATION>;
BEGIN
WHILE <condition>
LOOP
<STATEMENT>;
END LOOP;
<EXECUTAVLE STATEMENT>;
END;
INPUT:
OUTPUT:
RESULT:
Thus the study the various basic PL/SQL Conditional and Iterative Statements (Basic
loop, WHILE loop, FOR loop) on the database is executed successfully.