Final DBMS Print
Final DBMS Print
AIM
To make a study about the various database concepts and their structure.
DATABASE CONCEPTS
RELATIONAL MODEL – TABLE – OPERATIONS ON TABLES – INDEX – TABLESPACE –
CLUSTERS – SYNONYM – VIEW – SCHEMA – DATA DICTIONARY – PRIVILEGE – ROLE –
TRANSACTIONS
Relational Model
In relational database the data and relations between them are organized in tables. A table is
a collection of records and each record in a table contains the same fields.
SQL?
SQL do?
2. DATA TYPES
Column types: These have no multiple column types but are valid only for single column.
The code for a single column is shown below:
Three Types
DDL
DML
DCL
1. CREATE Statement
The CREATE TABLE statement is used to create a table
Create table table_name
(
column_name1 data_type [constraints],
column_name1 data_type [constraints],
column_name1 data_type [constraints],
……..
);
2. Alter Table
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table
a. To Add a column
3. Drop Table
➢ Language for accessing and manipulating the data organized by the appropriate data model
o DML also known as query language
The query and update commands form the DML part of SQL:
The Data Control Language (DCL) component of the SQL language is used to create privileges to
allow users access to, and manipulation of, the database. There are two main commands:
GRANT command
5. INDEX
A database index is a data structure that improves the speed of data retrieval operations on a
database table at the cost of slower writes and increased storage space. Indexes can be created
using one or more columns of a database table.
• SQL UNION operator -The union operator combines the tuples of two relations and
removes all duplicate tuples from the result.
• INTERSECT operator -The intersection operator produces the set of tuples that two
relations share in common
• EXCEPT or MINUS operator The difference operator acts on two relations and produces
the set of tuples from the first relation that do not exist in the second relation.
6. TABLESPACE
A tablespace is a storage location where the actual data underlying database objects can be kept.
It is the physical portion of the database used to allocate storage for all DBMS managed segments.
7. VIEWS
A view is just a relation, but we store a definition, rather than a set of tuples.
Creating a Role
To create a role, we must have CREATE ROLE system privileges. The syntax for creating a role is:
CREATEROLE role_name
[ NOT IDENTIFIED | IDENTIFIED {BY password | USING [schema.] package | EXTERNALLY |
GLOBALLY } ;
o The role_name phrase is the name of the new role that we are creating. This is how
we will refer to the grouping of privileges.
o The NOT IDENTIFIED phrase means that the role is immediately enabled. No
password is required to enable the role.
o The IDENTIFIED phrase means that a user must be authorized by a specified method
before the role is enabled.
o The BY password phrase means that a user must supply a password to enable the
role.
o The USING package phrase means that you are creating an application role - a role
that is enabled only by applications using an authorized package.
o The GLOBALLY phrase means that a user must be authorized by the enterprise
directory service to enable the role.
8.1 Grant Privileges (on Tables) to Roles
We can grant roles various privileges to tables..
Privilege Description
Select Ability to query the table with a select statement.
Insert Ability to add new rows to the table with the insert statement.
Update Ability to update rows in the table with the update statement.
Delete Ability to delete rows from the table with the delete statement.
References Ability to create a constraint that refers to the table.
Alter Ability to change the table definition with the alter table statement.
Ability to create an index on the table with the create index
Index
statement.
The syntax for granting privileges on a table is:
grant privileges on object to role_name
Revoke Privileges (on Tables) to Roles: Once we have granted privileges, we may need to
revoke some or all of these privileges. The syntax for revoking privileges on a table is:
revoke privileges on object from role_name;
• The role_name phrase is the name of the role that you wish to enable.
• The IDENTIFIED BY password phrase is the password for the role to enable it. If the role
does not have a password, this phrase can be omitted.
• The ALL phrase means that all roles should be enabled for this current session, except
those listed in the EXCEPT phrase.
• The NONE phrase disables all roles for the current session. (including all default roles)
ALTER USER user_name DEFAULT ROLE ( role_name | ALL [EXCEPT role1, role2, ... ] |
NONE );
• The user_name phrase is the name of the user whose role we are setting as
DEFAULT.
• The role_name phrase is the name of the role that we wish to set as DEFAULT.
• The ALL phrase means that all roles should be enabled as DEFAULT, except those
listed in the EXCEPT phrase.
9. TRANSACTIONS
A transaction is a logical unit of work that contains one or more SQL statements.
A transaction begins with the first executable SQL statement. A transaction ends when it is
committed or rolled back, either explicitly with a COMMIT or ROLLBACK statement or implicitly
when a DDL statement is issued.
A transaction ends when any of the following occurs:
• A user issues a COMMIT or ROLLBACK statement without a SAVEPOINT clause.
• A user process terminates abnormally. The current transaction is rolled back.
After one transaction ends, the next executable SQL statement automatically starts the following
transaction.
9.1 COMMIT TRANSACTIONS
COMMIT in SQL is a transaction control language that is used to permanently save the
changes done in the transaction in tables/databases. The database cannot regain its
previous state after its execution of commit.
9.2 ROLLBACK OF TRANSACTIONS
Rolling back means undoing any changes to data that have been performed by SQL statements
within an uncommitted transaction. We can also roll back the trailing portion of an uncommitted
transaction to a marker called a savepoint.
All types of rollbacks use the same procedures:
• Statement-level rollback
• Rollback to a savepoint
• Rollback of a transaction due to user request
• Rollback of a transaction due to abnormal process termination
• Rollback of all outstanding transactions when an instance terminates abnormally
• Rollback of incomplete transactions during recovery
Table created.
SQL> INSERT INTO emp (empno, empname, DOB, salary, designation) VALUES(101,'Greg',
'20-JUL-1994',25000,'Clerk');
1 row created.
//To display the empname and salary from the table emp
EMPNAME SALARY
----------------------------------------------
Greg 25000
John 50000
//To display the empname and salary where salary is greater than 5000
EMPNAME SALARY
----------------------------------------
Greg 25000
John 50000
MODIFY VALUES:
DELETE VALUES:
Syntax:
Create table <table_name> (column_name datatype (size)
constrains);
Description
The create command when applied with above specification creates the field of
different data type.
2. ALTER COMMAND:-
Syntax:
a) alter table <table_name> add (column_name datatype
(size));
Description
The alter command when used with add allows us to add an additional column to an
already existing table.
Syntax:
b) alter table < table_name> modify(column_name
datatype(size));
Description
The alter command when used with modify redefines the column with the given values
but cannot change the column names.
Syntax:
c) alter table <table_name> drop(column_name);
Description
The alter command when used with drop deletes the specified column in the table.
3. DROP COMMAND:-
Syntax:
Drop table <table_name>;
Description
A table can be dropped (deleted) by using a drop table command.
4. CREATE VIEW COMMAND:-
Syntax:
Create view <view_name> as select <column_name> from
<table_name> where <condition>;
Description
A view is named, derived, virtual table. A view takes the output of a query and treats it
as a table; a view can be thought of as a “stored query” or a “virtual table”. The tables upon
which a view is based are called base tables.
Syntax:
Drop view <view_name>;
Description
A view can be dropped (deleted) by using a drop view command.
6. TRUNCATE COMMAND:-
Syntax:
Truncate table <table_name>;
Description
The details in the table are deleted but the table structure remains.
7. RENAME COMMAND:-
Syntax:
Rename <oldtable_name> to <newtable_nmae>;
Description
The old table name is replaced with the new table name.
CREATE A TABLE:
Table created.
A. ADD
//To alter the table emp by adding new attribute department
B. MODIFY
// To alter the table emp by modifying the size of the attribute department
C. DROP
// To alter the table emp by deleting the attribute department
SQL> ALTER TABLE emp DROP (department);
Table altered.
SQL> DESC emp;
D. RENAME
// To alter the table name by using rename keyword
DROP TABLE:
//To delete the table from the database
SQL> DROP TABLE emp1;
Table dropped.
SQL> DESC emp1;
ERROR:
ORA-04043: object emp1 does not exist
# IMPLEMENTATION OF DDL WITH CONSTRAINT
DDL WITH CONSTRAINTS:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
Table created.
Table created.
// Describe the table student
SQL> DESC exam;
Name Null? Type
----------------------------------------- -------- ----------------------------
EXAMID NOT NULL NUMBER
STUDENTID NUMBER
DEPARTMENT NOT NULL CHAR(5)
MARK1 NUMBER
MARK2 NUMBER
MARK3 NUMBER
MARK4 NUMBER
MARK5 NUMBER
TOTAL NUMBER
AVERAGE NUMBER
GRADE CHAR(1)
ALTER THE TABLE:
A. ADD
// To alter the table student by adding new attribute address
B. MODIFY
// To alter the table student by modifying the size of the attribute address
C. DROP
// To alter the table student by deleting the attribute address
D. RENAME
// To alter the table name by using rename keyword
DROP TABLE:
// To delete the table from the database
Syntax :
Insert into <table_name> values (val1,val2,…);
Description:
The ‘insert into’ command insert the values in the specified table. In the insert into SQL
sentence the column and values have a one to one relationship (i.e.) the first value described into
the first column, the second value described being inserted into the second column and so on.
DELETE:-
Syntax:
Delete from <table_name> where <condition>;
Description:
The delete in SQL is used to remove rows from table.
To remove,
1. All the rows from a table.
2. A select set of rows from a table.
UPDATE:-
Syntax:
Update <table_name> set fieldname=<expression> where
<condition>;
Description:
The update command is used to change or modify data values in a table.
To update,
1. All the rows from a table.
SELECT:-
Syntax:
a) select <attribute lists> from <table_name> [where
clause];
Description:
Select command is used to retrieve data from one or more tables or columns. The attributes
list is a list of attributes name whose values are displayed by query. A missing where clauses
indicate no condition on tuples selection. The condition is a Boolean expression that identifies the
tuples to be retrieved by the query.
Syntax:
b) select distinct <column_name> from
<table_name>;
Description:
Display the distinct values from a table by eliminating the duplicate values. It performs
grouping of the specified fields when queried with distinct statement.
7 rows selected.
UPDATE COMMAND
1 row updated.
DELETE COMMAND
1 row deleted.
6 rows selected.
# IMPLEMENTATION OF DML COMMANDS (with constraints)
INSERTING VALUES:
//insert values into student table:
SQL>INSERT INTO student VALUES (101,'RUPESH','IT', 5,'5-JUN-2005',
'[email protected]','MEC');
1 row created.
SQL> INSERT INTO student VALUES (102,'BALA','CSE',7,'7-OCT-1995','[email protected]','IIT');
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4, m5)VALUES (2222,101,'IT',98,87,83,99,87);
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4,m5)VALUES(3333,104,'IT',99,82,84,89,100);
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4,m5)VALUES (4444,108,'IT',92,85,83,91,87);
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4,m5)VALUES(5555,106,'CSE',82,85,87,91,85);
1 row created.
1 row deleted.
1 row created.
SNAME||STUDENTID
------------------------------
DEEPI101
SHAN102
REVA104
ANANTVI106
SASI108
// To display the records from the table student who belongs to MEC college.
// To display the student name and department from the table student who belongs to 5th
sem.
SQL> SELECT sname, department FROM student WHERE sem=5;
SNAME DEPAR
---------------------------------------
DEEPI IT
REVA IT
ANANT CSE
SASI IT
# IMPLEMENTATION OF DQL COMMANDS- SELECTION
PROGRAM TO LEARN DQL COMMANDS
CREATING TABLE:
SQL> CREATE TABLE student
(
studID NUMBER PRIMARY KEY,
sname VARCHAR2(15) NOT NULL,
department CHAR(5),
sem NUMBER,
dob DATE,
email_id VARCHAR2(20) UNIQUE,
college VARCHAR2(10) DEFAULT 'MVIT'
);
Table created.
//To display the student id, student name and department of the student whose the semester in
between 5 and 6
SQL> SELECT studid,sname,department FROM student WHERE sem BETWEEN 5 AND 6;
STUDID SNAME DEPAR
---------------------------------------------------------
101 DEEPI IT
104 REVA IT
106 ANANT CSE
108 SASI IT
IN:
// To display the student id, student name and department of the student whose in CSE and IT
department
SQL> SELECT studid, sname, department FROM student WHERE department IN ('CSE','IT');
NOT IN:
// To display the student id, student name and department of the student whose not in CSE
department
SQL> SELECT studid,sname,department FROM student WHERE department NOT IN 'CSE';
SQL> SELECT studid, sname FROM student WHERE sname LIKE '%I';
STUDID SNAME
-------------------------------------------
101 DEEPI
108 SASI
// To display the student id and student name of the student whose name has letters 'E' from the
table student
SQL> SELECT studid, sname FROM student WHERE sname LIKE '%E%';
STUDID SNAME
-------------------------------------------
101 DEEPI
104 REVA
RELATIONAL OPERATOR:
// To display the student id, student name of the student whose the stud id greater than 105
SQL> SELECT studid, sname FROM student WHERE studid > 105;
STUDID SNAME
-----------------------------------------
106 ANANT
108 SASI
LOGICAL OPERATOR:
// To display the student id, student name of the student whose the student id greater than 105
and cse department
SQL> SELECT studid, sname FROM student WHERE studid > 105 AND department='CSE';
STUDID SNAME
------------------------------------------------
106 ANANT
# IMPLEMENTATIN OF DCL COMMANDS
The DCL commands are:
❖ Grant
❖ Revoke
GRANT:-
Syntax:
Grant <privileges> on <table_name> to user;
Description:
Grant gives specifies SQL statement access or individual data objects to a user or a group of
users.
GRANT COMMAND
------------------------------
SQL> grant insert,select,update,delete on emp to system;
Grant succeeded.
REVOKE:-
Syntax:
Revoke <privileges> on <table_name> from user;
Description:
Revoke removes specific SQL statement access previously granted on individual database
objects from a user or group of users.
REVOKE COMMAND
--------------------------------
SQL> revoke select,insert on emp from system;
Revoke succeeded.
PROGRAM TO LEARN DCL
CREATE TABLE
SQL> create table emp
(
eno number primary key,
ename varchar2(10),
deptno number,
deptname varchar2(10)
);
Table created.
Grant succeeded.
Revoke succeeded.
# IMPLEMENTATION OF TCL COMMANDS
COMMIT:-
Syntax:
commit;
Description
COMMIT command is used to save the work done.
SAVE POINT:-
Syntax:
Save point pointname;
Description
SAVE POINT command is used to identify a point in a transaction in which it can be restored using
Roll back command.
ROLLBACK:-
Syntax:
rollback;
Description
ROLLBACK command is used to restore database to original since last commit.
6 rows selected.
//COMMIT
SQL> COMMIT;
Commit complete.
//ROLLBACK
SQL> ROLLBACK;
Rollback complete.
6 rows selected.
//Creating Savepoint
NUMERIC FUNCTIONS
❖ ABS
❖ POWER
❖ ROUND
❖ TRUNC
❖ SQRT
❖ FLOOR
❖ CEIL
ABS:-
Syntax:
Select abs(field1) from <tablename>;
Description
Returns the absolute value of ‘n’.
POWER:-
Syntax:
Select power(field1,field2) from <tablename>;
Description
Returns m raised to the nth power ,n must be an integer else an error is returned.
ROUND:-
Syntax:
Select round(field1,[field2]) from <tablename>;
Description
Returns n,rounded to the places to the right of the decimal point.
SQRT:-
Syntax:
Select sqrt(field1) from <tablename>;
Description
Returns the square root of n.
TRUNC:-
Syntax:
Select trunc(field1,[field2]) from <tablename>;
Description
Returns a number truncated to a certain number of decimal places. If this parameter is omitted, the
TRUNC function will truncate the number to 0 decimal places.
FLOOR:-
Syntax:
Select floor(field1) from <tablename>;
Description
Returns the largest integer value that is equal to or less than a number.
CEIL:-
Syntax:
Select ceil(field1) from <tablename>;
Description
Returns the smallest integer value that is greater than or equal to a number.
STRING FUNCTIONS
❖ LOWER
❖ UPPER
❖ ASCII
LOWER:-
Syntax:
Select Lower(field1) from <tablename>;
Description
Returns char with all letters in lowercase.
UPPER:-
Syntax:
Select Upper(field1) from <tablename>;
Description
Returns char with all letters forced to uppercase.
ASCII:-
Syntax:
Select ASCII(char) from <tablename>;
Description
Returns the number code that represents the specified character.
COMMAND EXECUTION
NUMERIC FUNCTIONS:
ABS(-99)
---------------
99
ABS(45.95)
--------------
45.95
SQL> select power(3,2) from dual;
POWER(3,2)
------------------
9
SQL> select SQRT(625) from dual;
SQRT(625)
----------------
25
SQL> select SQRT(144) from dual;
SQRT(144)
----------------
12
SQL> select CEIL(22.22) from dual;
CEIL(22.22)
-----------------
23
SQL> select FLOOR(45.49) from dual;
FLOOR(45.49)
--------------------
45
SQL> select ROUND(66.66) from dual;
ROUND(66.66)
---------------------
67
SQL> select TRUNC(55.99) from dual;
TRUNC(55.99)
--------------------
55
SQL> select LN(2) from dual;
LN(2)
--------------
.693147181
SQL> select LN(55) from dual;
LN(55)
---------------
4.00733319
SQL> select SIN(60) from dual;
SIN(60)
---------------
-.30481062
SQL> select SIN(0) from dual;
SIN(0)
--------------
0
SQL> select cos(0) from dual;
COS(0)
--------------
1
SQL> select TAN(30) from dual;
TAN(30)
---------------
-6.4053312
STRING FUNCTIONS
D
-
X
SQL> select ascii('A') from dual;
ASCII('A')
--------------
65
SQL> select ascii('ab') from dual;
ASCII('AB')
-----------------
97
SQL> select ascii('R') from dual;
ASCII('R')
---------------
82
SQL> select lower('SAGAR') from dual;
LOWER
------------
sagar
SQL> select upper('sagar') from dual;
UPPER
-----------
SAGAR
SQL> spool off
not spooling currently
# AGGREGATE FUNCTIONS
1. MAX:-
Syntax:
Select max(field1) from <table_name>;
Description
MAX command is used to find the maximum among the entities in a particular attribute.
2. MIN:-
Syntax:
Select min(field1) from <table_name>;
Description
MIN command is used to find the minimum among the entities in a particular attribute.
3. COUNT:-
Syntax:
Select count(field1) from <table_name>;
Description
COUNT command is used to count the entire entities in a particular attribute.
4. SUM:-
Syntax:
Select sum(field1) from <table_name>;
Description
SUM command is used to add all the entities with in the attribute.
5. AVG:-
Syntax:
Select avg(field1) from <table_name>;
Description
AVG command is used to find average of entity in particular attribute.
PROGRAM TO LEARN AGGREGATE FUNCTION:
CREATING TABLE:
// To create the Table student:
SQL> CREATE TABLE student
(
sID NUMBER PRIMARY KEY,
sname VARCHAR2(15) NOT NULL,
department CHAR(5),
sem NUMBER,
dob DATE,
email_id VARCHAR2(20) UNIQUE,
college VARCHAR2(10) DEFAULT 'MVIT'
);
Table created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4, m5)VALUES (2222,101,'IT',98,87,83,99,87);
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4,m5)VALUES(3333,104,'IT',99,82,84,89,100);
1 row created.
SQL> INSERT INTO exam(eid, sid, dept, m1, m2, m3, m4,m5)VALUES(4444,108,'IT',92,85,83,91,87);
1 row created.
ORDER BY:
//To display the department, sem and student name from the table student based on department in
ascending order.
//To display the department, sem and student name from the table student based on
department in descending order.
SQL> SELECT department, sem, sname FROM student ORDER BY department DESC, sem DESC,
sname DESC;
DEPAR SEM SNAME
-------------------------------------------------
IT 5 DEEPI
IT 5 SASI
IT 5 REVA
CSE 7 SHAN
CSE 5 ANANT
GROUP BY:
DEPAR SUM_DEPARTMENT
------------------------------------------------
IT 1346
CSE 430
AGGREGATE FUNCTIONS:
// 1. COUNT - displays total number of rows:
SQL> SELECT COUNT (eid) AS STUDENTS_REGISTERED FROM exam;
STUDENTS_REGISTERED
--------------------------------------
4
// 2. MAX - displays the maximum value:
SQL> SELECT MAX(avg) AS RANK_1 FROM exam;
RANK_1
-------------
90.8
// 3. MIN - displays the minimum value
SQL> SELECT MIN(avg) AS LAST_RANK FROM exam;
LAST_RANK
-------------------
86
// 4. SUM - displays the total value:
SQL> SELECT department, SUM(tot) AS SUM_DEPARTMENT FROM exam5 GROUP BY
department;
DEPAR SUM_DEPARTMENT
----------------------------------------
IT 1346
CSE 430
444
# SET OPERATIONS
UNION:-
Syntax:
Select <fieldname1> from <table_name1> union Select
<fieldname2> from <table_name2>;
Description
UNION command is used to compile all distinct rows and display all entities in both rows.
UNIONALL:-
Syntax:
Select <fieldname1> from <table_name1> unionall Select
<fieldname2> from <table_name2>;
Description
UNIONALL command is used to return all entities in both rows.
INTERSECT:-
Syntax:
Select <fieldname1> from <table_name1> intersect Select
<fieldname2> from <table_name2>;
Description
Description
MINUS command is used to display only the rows that don’t match in both queries.
CREATING TABLE
//Create Table employee
SQL> CREATE TABLE employee
(
Employee_Name VARCHAR2(10),
Employee_no NUMBER PRIMARY KEY,
Dept_no NUMBER,
Dept_name VARCHAR2(10)
);
Table created.
UNION:
//To display employee_no using union - displays all values without duplicates from
employee and employee1
SQL> SELECT employee_no FROM employee UNION SELECT employee_no FROM employee1;
EMPLOYEE_NO
--------------------------------
234
476
877
985
990
UNION ALL:
//To display employee_no using union all - displays all values with duplicates from employee
and employee1
SQL> SELECT employee_no FROM employee UNION ALL SELECT employee_no FROM employee1;
EMPLOYEE_NO
---------------------
234
877
990
234
476
985
6 rows selected.
INTERSECT:
//To display employee_no using intersect - displays common values in both the tables without
duplicates from employee and employee1
SQL> SELECT employee_no FROM employee INTERSECT SELECT employee_no FROM employee1;
EMPLOYEE_NO
----------------------
234
MINUS:
//To display employee_no using minus - displays the values that minus the employee_no of
employee from employee1
SQL> SELECT employee_no FROM employee MINUS SELECT employee_no FROM employee1;
EMPLOYEE_NO
-----------------------
877
990
# JOINS
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
SELECT *
FROM table_name1
[JOIN KEYWORD] table_name2
WHERE table_name1.column = table_name2.column
1. INNER JOIN
Returns all the attributes from both tables including repeated attributes based on condition
2. OUTER JOIN
A. Left Outer Join
Return all rows FROM the left table, even if there are no match in the right table
B. Right Outer Join
Return all rows FROM the right table, even if there are no match in the left table
C. Full Outer Join
Returns all the rows FROM both the tables.
3. SELF JOIN
Returns rows by comparing the values of the same table.
4. EQUI JOIN
Returns the rows FROM two tables that satisfies the equal to condition
5. NON EQUI JOIN
Returns the rows FROM two tables that satisfies the non equal to condition
PROGRAM TO LEARN JOINS
CREATE A TABLE:
//To create a table cseitstudent
SQL> CREATE TABLE cseitstudent
(
studID NUMBER PRIMARY KEY,
sname VARCHAR(15),
dept CHAR(5),
sem NUMBER
);
Table created.
//To create a table placement
SQL> CREATE TABLE placement
(
PID NUMBER PRIMARY KEY,
StudID NUMBER,
dept CHAR(5),
Company VARCHAR2(30),
salary NUMBER
);
Table created.
INNER JOIN
SQL> SELECT * FROM cseitstudent INNER JOIN Placement ON
cseitstudent.studID=placement.StudID;
STUDID SNAME
---------------------------------------
105 Arnav
103 Navya
104 Anant
105 Arnav
104 Anant
105 Arnav
6 rows selected.
# NESTED SUB QUERIES
CREATING TABLE:
SQL> CREATE TABLE employee1
(
empno NUMBER,
empname VARCHAR2(15),
salary NUMBER,
designation VARCHAR2(10)
);
Table created.
INSERTING VALUES INTO TABLE EMPLOYEE1:
SQL> INSERT INTO employee1 VALUES(100,'DEEPI',20000,'Clerk');
1 row created.
EXAMPLE QUERIES:
SQL> SELECT * FROM employee1 WHERE salary < (SELECT salary FROM employee1 WHERE
empname='DEEPI');
EMPNO EMPNAME SALARY DESIGNATIO
---------------------------------------------------------------------------------
101 SHAN 10000 Typist
102 SHOLK 15000 Cashier
CREATE TABLE:
//To create a table cseitstudent
SQL> CREATE TABLE cseitstudent
(
studentID NUMBER PRIMARY KEY,
sname VARCHAR(15),
department CHAR(5),
sem NUMBER
);
Table created.
//To create a table placement
SQL> CREATE TABLE placement
(
PlacementID NUMBER PRIMARY KEY,
StudentID NUMBER,
department CHAR(5),
Company VARCHAR2(30),
salary NUMBER
);
Table created.
INSERTING VALUES IN TABLE:
// Inserting values into cseitstudent table
EXAMPLE QUERIES:
STUDENTID SNAME
-------------------------------------------------
102 Rajesh
103 Sasi
104 Sidhu
105 Astha
SQL> SELECT studentID, sname FROM cseitstudent WHERE studentID NOT IN
(SELECT studentID FROM placement);
STUDENTID SNAME
---------------------------------------------
101 Ranvir
SNAME DEPAR
------------------------------
Rajesh IT
Sasi CSE
Sidhu IT
SNAME DEPAR
-----------------------------
Ranvir IT
Astha CSE
SQL> SELECT studentID, company, salary FROM placement WHERE Salary > SOME
(SELECT salary FROM placement WHERE company='Infosys');
SQL> SELECT studentID, company, salary FROM placement WHERE salary < ALL(23000,28000);
SQL> SELECT * FROM employee1 WHERE EXISTS (SELECT * FROM employee1 WHERE
salary>5000 );
SQL> SELECT * FROM placement WHERE EXISTS (SELECT * FROM placement WHERE
salary>20000);
NOT EXISTS
SQL> SELECT * FROM employee1 WHERE NOT EXISTS (SELECT * FROM employee1 WHERE
salary>5000 );
no rows selected
# STORED PROCEDURES
Queries
SQL> create table stud(rno number(2),
mark1 number(3),
mark2 number(3),
total number(3),
primary key(rno));
Table created.
Procedure created.
9 rows selected.
Procedure created.
Procedure created.
Drop Procedure:
Procedure dropped.
# TRIGGER :
A Trigger is a special type of stored procedure that automatically runs when an event occurs in the
database server.DML trigger run when a uses tries to modify data through a data manipulation
language (DML) event.
DML events are INSERT, UPDATE or DELETE statements on a table or view.
*Create table
*Inserting Records
Table creation
Table Created
Table Created.
Inserting Records
SQL>Insert into books values (&BookNo, ’&BookName’, ’&AuthName’, ’&Publisher’,
&year); Enter BookNo : 100
Enter Bookquantity : 5
Enter BookCost_per_item : 10
Old 1: insert into Books130values (&BookNo,&Bookquantity, &cost_per_item) New 1:
insert into Book130values (100, 5, 10)
1 row created
SQL>/
Enter BookNo: 101
Enter Bookquantity: 4
Enter BookCost_per_item: 20
Old 1: insert into Books130 values (&BookNo, &Bookquantity, &cost_per_item) New 1:
insert into Book130 values(101,4,20)
SQL>/
101 4 25 19TD1145
1 row selected
# VIEW
A view is a virtual table based on the result-set of an SQL statement.A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.You can add SQL functions, WHERE, and JOIN statements
to a view and present the data as if the data were coming from one single table.
Creating a View
Syntax:
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name
WHERE condition
Updating a View
Syntax:
CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM
table_name
WHERE condition
Dropping a View
Syntax:
DROP VIEW view_name
//To display the records in placement table (After inserted a new record in base
tables)
// To display the records in studetails view (After deleted a new record in view)
// To display the records in studetails view (After updated a new record in view)
SELECT * FROM studetails;
STUDENTID SNAME DEPARTMENT SEM COMPANY SALARY
-----------------------------------------------------------------------------------------------------------------
104 nirmal IT 3 infosys 25000
105 eshwar CSE 5 Wipro 22000
102 reenu IT 3 infosys 27500
103 sheela CSE 3 infosys 25000
// To display the records in placement table (After deleted a new record in view)
SELECT * FROM placement;
PLACEMENTID STUDENTID DEPARTMENT COMPANY SALARY
----------------------------------------------------------------------------------------------------
1 04 IT infosys 25000
2 105 CSE Wipro 22000
3 204 MECH Hyundai 30000
4 102 IT infosys 27500
5 103 CSE infosys 25000
SQL> DROP VIEW studetails;
View dropped.
SQL> SELECT * FROM studetails;
ERROR at line 1:
ORA-00942: table or view does not exist
LIBRARY INFORMATION SYSTEM
AIM
To design a schema for Library Information and solve the following queries using
the schema.
SCHEMA DESCRIPTION
Book (Book_id, Title, Publisher)
Publisher (Name, Addrs, Phone)
Book_copies (Book_id, Branch_id, No_of_copies)
Book_loan (Book_id, Branch_id, Card_no,Date_out, Due_date)
Lib_branch (Branch_id, Branch_name, Addrs)
Borrower (Card_no, Name, Addrs, Phone)
name title Book_id
Published Written
by by
copies
Book_copies
Book_id No_of_copie
in s
Branch_id
Loan
Lib_branch
Branch_id addrs
one
Book_loan
Brch_name
Book_id Duedate
Card_no
borrower
Card_no addrs
name phone
CREATING TABLES
Table created.
Table created.
SQL> desc lib_branch;
Table created.
Table created.
Table created.
Table created.
SQL> desc book_loan;
1 row created.
QUERIES
1. To find out how many copies of the book with given title “cn” are owned by the
library branch whose name is “senthil books”.
SQL> Select no_of_copies from books, book_copies, lib_branch where(books. book_id
=book_copies. book_id and book_copies. branch_id=lib_branch. branch_id and
lib_branch. branch_name = 'senthil books' and books. title='cn');
NO_OF_COPIES
------------------------
122
2. How many copies of the book titled “dbms” are owned by each library branch.
SQL> Select lib_branch.branch_name, book_copies.no_of_copies from books,
book_copies,
lib_branch where (books. book_id = book_copies. book_id and book_copies.
branch_id
=lib_branch. branch_id and books. title ='dbms');
BRANCH_NAME NO_OF_COPIES
----------------------------------------------------------
vinayaga book house 155
3. To retrieve the name of all borrowers who have not borrowed any book from
any branch.
SQL> Select name from borrower b where not exists (select card_no from book_loan
where book_loan.card_no=b.card_no);
no rows selected
4. To find out for each book that is loanded out from “Kamaraj nagar” branch
whose due date is today.
SQL> select books.title from books,book_loan,lib_branch where due_date='17-feb-10'
and book_loan.branch_id=lib_branch.branch_id and book_loan.book_id=books.book_id
and lib_branch.branch_name='vinayaga
book house';
TITLE
---------------
Cn
5. To compute for each library branch retrieve the branch name, the total no of
books loaned out from that branch.
BRANCH_NAME NO_OF_BOOKS
-------------------------------------------------------
pondy books 2
senthil books 1
vinayaga book house 1
6. To retrieve the names, address and no of books borrowed for all borrowers
who have more than 1 book in their credit
SQL> select b.name, b.addrs ,a. no_of_books from(select card_no,
count(book_id) no_of_books from book_loan group by card_no) a, borrower b where
(a. card_no =b. card_no and a. no_of_books >1);
RESULT
Thus the schema diagram for LIBRARY INFORMATION SYSTEM was studied
and the queries are executed successfully.
LOGISTIC MANAGEMENT SYSTEM
AIM
To design a schema for Logistic management and solve the following queries
using the schema.
SCHEMA DESCRIPTION
Quotation(cusname , Goodsid, quan, destination, zipcode)
Shipper(shipperid, Shippername, shipperaddress, shippermobile, Goodsid)
Customer(customerid, customername, customeraddress, Goodsname, zipcode,
Goodsid)
Trade(portid, Goodsid, ploading, pdispatch, TFM, originzip, deszip)
Stock(stockid, cname, quantity)
Container(stockid, containerid, contname, contsize, quant)
TABLE CREATION
//Creating table quotation
MODIFICATION OF DATABASE
JOINS
//To compare each cusname from quotation and goodsid from customer using goodsid
with right outer join.
// To compare each cusname from quotation and goodsid from customer using goodsid
with left outer join
AGGREGATE FUNCTION
COUNT – To find the number tuples in the attribute TFM from the table trade
AVG – To calculate the average value of attribute quantity from the table quotation
MAX – To compute the Maximum value of attribute goodsid from the table Trade
MIN - To compute the Minimum value of attribute goodsid from the table Trade
//SUM – To compute the Total amount of the attribute quantity from the table quotation
NESTED SUBQUERIES
//Select the customer details from customer who belongs to destination of the customer
‘jeevith’
//To display the container details who belong to quant of the containerid =21002
//To display the goodsid, cusname from the table quotation where goodsid not present
in the table customer.
TRIGGER
RESULT
Thus the schema diagram for LOGISTIC MANAGEMENT SYSTEM was studied and the
queries are executed successfully.
Employee details using JDBC data base
AIM
To develop a Employee details for the any organization.
SCHEMA DESCRIPTION
STEP 1: Start
STEP 2: Create the Emp1 table with its essential attributes( Emp1(Eno, Ename,salary))
STEP 3: Insert attribute values into the emp1 table using jdbc connectivity
STEP 4: Update the attribute values into the emp1 table using jdbc connectivity
STEP 5: Delete the attribute values into the emp1 table using jdbc connectivity
STEP 6: Get the information of employee using select queries from the emp1 table
using jdbc connectivity
STEP 5: Stop
Insert.java
package javaapplication2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.util.Scanner;
class Insert{
public static void main(String args[]){
try{
Scanner s=new Scanner(System.in);
System.out.println("Insert the Values in Table");
System.out.println("Enter the Employee No:");
int eno=s.nextInt();
System.out.println("Enter the Employee Name:");
String name=s.next();
System.out.println("Enter the salary:");
int salary=s.nextInt();
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
Update.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.util.Scanner;
public class update {