DBMS Lab Manual
DBMS Lab Manual
Department of AI
Lab Manual
(2024-25)
List of Experiment
AIM: Draw E-R diagram and convert entities and relationships to relation table for a given scenario.
Two assignments shall be carried out i.e. consider two different scenarios (eg. bank, college,
Employee, Hotel etc)
Theory:
ER diagrams are visual tools that are helpful to represent the ER model. Peter Chen proposed
ER Diagram in 1971 to create a uniform convention that can be used for relational databases
and networks. He aimed to use an ER model as a conceptual modeling approach.
An entity-relationship diagram (ERD) shows the relationships of entity sets stored in a
database. An entity in this context is an object, a component of data. An entity set is a
collection of similar entities. These entities can have attributes that define their properties. By
defining the entities, and their attributes, and showing the relationships between them, an ER
diagram illustrates the logical structure of databases.
Facts about ER diagram are as follows:
Entity Relationship Diagram Symbols & Notations mainly contains three basic symbols which are
rectangle, oval and diamond to represent relationships between elements, entities and attributes. There are
some sub-elements which are based on main elements in ERD Diagram. ER Diagram is a visual
representation of data that describes how data is related to each other using different ERD Symbols and
Notations.
Chen Notation
a. ORDER (OrderNum (key), OrderDate, SalesPerson)
ORDERITEMS (OrderNum (key)(fk) , ItemNum (key), PartNum, Quantity, Cost)
b. In the above example, in the ORDERITEMS Relation: OrderNum
is the Foreign Key and OrderNum plus ItemNum is the Composite
Key.
Chen Notation
ER-Diagram:
Conclusion: In this experiment, we have studied history, facts about ER Diagram, necessity of ER diagram
along with Entity Relationships diagram notations and their use to draw the design of a database system.
********
Experiment No. - 2
AIM: To perform following SQL activity:
a) Creating a database
b) Creating Tables (With and Without Constraints)
c) Inserting Record in table
Theory:
CONSTRAINTS:
Integrity Constraints are a mechanism to prevent invalid data entry into the table to maintain data
consistency. The whole purpose of constraints is to maintain the data integrity during the various
transactions like update/delete/insert on a table.
Types of constraints:
● NOT NULL
● UNIQUE
● DEFAULT
● CHECK
● Key Constraints – PRIMARY KEY, FOREIGN KEY
NOT NULL:
NOT NULL constraint makes sure that a column does not hold NULL value. When we don't provide
value for a particular column while inserting a record into a table, it takes NULL value by default. By
specifying the NULL constraint, we can be sure that a particular column(s) cannot have NULL values.
UNIQUE:
UNIQUE Constraint enforces a column or set of columns to have unique values. If a column has a unique
constraint, it means that a particular column cannot have duplicate values in a table.
DEFAULT:
The DEFAULT constraint provides a default value to a column when there is no value provided while
inserting a record into a table.
CHECK:
This constraint is used for specifying a range of values for a particular column of a table. When this
constraint is being set on a column, it ensures that the specified column must have the value falling in the
specified range.
The primary key uniquely identifies each record in a table. It must have unique values and cannot contain
nulls. In the below example the ROLL_NO field is marked as the primary key, which means the
ROLL_NO field cannot have duplicate and null values.
FOREIGN KEY:
Foreign keys are the columns of a table that points to the primary key of another table. They act as a
cross-reference between tables.
a) Creating a database:
Mysql> create databse a1;
Output:
Database created
b) To view all databases
Mysql> show databases;
Output:
a1
System_init
Example:
Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint un
unique, DeptNo number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not null);
DOMAIN INTEGRITY
Example: Create table student (regno number (6), mark number (3) constraint b check (mark >=0
and mark <=100)); Alter table student add constraint b2 check (length(regno<=4));
ENTITY INTEGRITY
Queries:
Q1. Create a table called EMP with the following structure.
Name Type
EMPNO NUMBER(6)
ENAME
VARCHAR2(20) JOB
VARCHAR2(10)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Allow NULL for all columns except ename and job.
1. Understand create table syntax.
2. Use the create table syntax to create the said tables.
3. Create primary key constraints for each table as understood from logical
table structure.
SQL> create table emp(empno number(6),ename varchar2(20)not null,job varchar2(10) not null,
deptno number(3), sal number(7,2));
Table created.
Q3: Modify the column width of the job field of the emp table.
Solution:
1. Use the altered table syntax.
2. Modify the column width and its data type.
Ans: SQL> alter table emp modify(job varchar2(12));
Table altered.
DEPT
NUMBER(2) DNAME
VARCHAR2(10) LOC
VARCHAR2(10)
Deptno the primary key
Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table
structure. Ans:
SQL> create table dept(deptno number(2) primary key,dname
varchar2(10),loc varchar2(10));
Table created.
Q5: create the emp1 table with ename and empno, add constraints to check the empno value
while entering (i.e) empno > 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [columns name type]
3. Use the alter table syntax for adding
constraints. Ans:
SQL> create table emp1(ename varchar2(10),empno number(6) constraint
check(empno>100));
Table created.
Q7: Truncate the emp table and drop the dept table
Solution:
OUTPUT:
SQL> create table emp1(emp_no number(6),ename varchar2(20) not null,job varchar2(10)
not null,dept_no number(3),sal number(7,2));
Table created.
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(10)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(10)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EXPERIENCE NUMBER(5)
SQL> desc
emp1;
Name Null? Type
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EXPERIENCE NUMBER(5)
1 row created.
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
SQL> create table dept(deptno number(5) constraint dept_deptno_pk primary key, dname
varchar2(20),loc varchar2(20));
Table created.
SQL> desc
dept;
Name Null? Type
Table created.
SQL> desc
emp;
Name Null? Type
EMPNO NUMBER(5)
ENAME NOT NULL VARCHAR2(25)
JOB VARCHAR2(15)
MGR NUMBER(5)
JOINDATE DATE
SALARY NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(7)
SQL> insert into dept values(12,'computer','pune');
1 row created.
SQL> select * from dept;
DEPTNO DNAME LOC
12 computer pune
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(10)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EXPERIENCE NUMBER(5)
SQL> create table dept1(dept_no number(12) primary key,d_name varchar2(10),loc
varchar2(10));
Table created.
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
EXPERIENCE NUMBER(5)
EMP_NO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(12)
DEPT_NO NUMBER(3)
SAL NUMBER(7,2)
SQL> desc
emp1;
ERROR:
ORA-04043: object emp1 does not exist
EMPNO NUMBER(5)
ENAME NOT NULL VARCHAR2(25)
JOB VARCHAR2(15)
MGR NUMBER(5)
JOINDATE DATE
SALARY NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(7)
SQL> insert into dept values(12,'computer','pune');
1 row created.
SQL> select * from dept;
12 computer pune
Conclusion: In this experiment, we have studied the concept of constraint and executed all constraints such as
NULL, NOT NULL, PRIMARY KEY, UNIQUE, CHECK, DEFAULT, and REFERENCES. Also created
tables with and without constraint and inserted records into it.
********
Experiment No-3
Aim: To Perform the following: Viewing all databases, Viewing all Tables in a Database,
Updating/Deleting Records in a Table
Theory:
View:
● A database view is a virtual table or logical table which is defined as a SQL SELECT
query with joins. Because a database view is similar to a database table, which consists of
rows and columns, so you can query data against it. Most database management systems,
including MySQL, allows you to update data in the underlying tables through the
database view with some prerequisites.
● A database view is dynamic because it is not related to the physical schema. The database
system stores database views as a SQL SELECT statement with joins. When the data of
the tables changes, the view reflects that changes as well.
● A database view allows you to simplify complex queries: a database view is defined by
an SQL statement that associates with many underlying tables. You can use a database
view to hide the complexity of underlying tables to the end-users and external
applications. Through a database view, you only have to use simple SQL statements
instead of complex ones with many joins.
● A database view helps limit data access to specific users: You may not want a subset of
sensitive data that can be queryable by all users. You can use database views to expose
only non-sensitive data to a specific group of users.
● A database view provides an extra security layer. Security is a vital part of any
relational database management system. Database views provide extra security for a
database management system. A database view allows you to create only a read-only
view to expose read-only data to specific users. Users can only retrieve data in the
read-only view but cannot update it.
● A database view enables computed columns. A database table should not have
calculated columns however a database view should.
● Database view enables backward compatibility. Suppose you have a central database,
which many applications are using it. One day you decided to redesign the database to
adapt to the new business requirements. You remove some tables and create several
new tables, and you don’t want the changes to affect other
applications. In this scenario, you can create database views with the same schema as
the legacy tables that you have removed.
Besides the advantages above, there are several disadvantages of using database views:
● Performance: querying data from a database view can be slow especially if the view is
created based on other views.
● Tables dependency: you create a view based on underlying tables of the database.
Whenever you change the structure of those tables that view associates with, you have
to change the view as well.
DML COMMANDS: DML commands are the most frequently used SQL commands and are
used to query and manipulate the existing database objects. Some of the commands are Insert,
Select, Update, and Delete.
Insert Command 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.
Select Commands 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 columns from the
table.
Update Command It is used to alter the column values in a table. A single column may be
updated or more than one column could be updated.
Delete command after inserting a 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.
Show databases;
Show tables
Q2: Insert more than a record into emp table using a single insert command.
Ans: SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename: Mathi
row created.
1 row created.
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are
working as ASP
Ans: SQL> select * from emp;
SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 1 12000
SQL> update emp set sal=15000 where job='ASP'; 2 rows updated. SQL>
1 Mathi AP 1 10000
Q4: Create a pseudo table employee with the same structure as the table emp and insert rows into
the table using select clauses.
Table created.
- EMPNO NUMBER(6)
VARCHAR2(13) DEPTNO
NUMBER(3)
SAL NUMBER(7,2)
Q5: select employee name, job from the emp table Ans:
SQL> select ename, job from emp;
ENAME JOB
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
Suresh lect
6 rows were selected.
Q6: Delete only those who are working as lecturers
Ans: SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
6 Suresh lect 1 8000
6 rows were selected.
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000
Q7: List the records in the emp table order by salary in ascending order. Ans:
SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
1 Mathi AP 1 10000
5 Akalya AP 1 10000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
4 Karthik Prof 2 30000
Q8: List the records in the emp table order by salary in descending order.
Ans: SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
- 1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax.
2. Select should include a distinct clause for the
deptno. Ans: SQL> select distinct deptno from emp;
DEPTNO
1
2
Conclusion: In this experiment, we have studied the concept of Data Manipulation Language
and implemented Insert, Select, Update, Delete. Also implemented queries to View all databases,
all Tables in a Database.
Experiment No. - 4
Aim: To Perform the following SQL query on database:
Altering a Table, Dropping/Truncating/Renaming Tables, Backing up / Restoring a Database
Theory:
Structured Query Language(SQL) as we all know is the database language by the use of which we can
perform certain operations on the existing database and also we can use this language to create a
database. SQL uses certain commands like Create, Drop, Insert, etc.
Data Definition Language actually consists of the SQL commands that can be used to define the database
schema. It simply deals with descriptions of the database schema and is used to create and modify the
structure of database objects in the database. DDL is a set of SQL commands used to create, modify, and
delete database structures but not data. These commands are normally not used by a general user, who should
be accessing the database via an application.
Syntax:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
Syntax:
To delete a column in a table, use the following syntax (notice that some database systems don't allow deleting
a column):
Syntax:
ALTER TABLE table_name
DROP COLUMN column_name;
DCL (Data Control Language):
DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions, and
other controls of the database system.
The following SQL statement creates a full back up of the existing database "testDB" to the D disk:
Example:
Output:
1. The Create Table Command: - Defines each column of the table uniquely. Each
column has a minimum of three attributes, a name, data type, and size.
Syntax:
Create table <table name> (<col1> <datatype>(<size>),<col2>
char(10));
Syntax:
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>)); Ex:
alter table emp modify(ename varchar2(15));
5. Renaming the tables
Syntax:
Rename <oldtable> to <new table>;
Syntax:
Truncate table <tablename>;
Ex:trunc table emp1;
7. Destroying tables.
Syntax:
Conclusion: In this experiment we studied Data Definition Language all structure related queries such as
create, alter with add and modify option, rename, drop, truncate and backup database.
Experiment No. – 5
Aim: For a given set of relation schemes, create tables and perform the following Simple Queries:
Simple Queries with Aggregate functions, Queries with Aggregate functions (group by and having clause),
Queries involving- Date Functions, String Functions, Math Functions.
Theory:
Aggregate functions perform a calculation on a set of values and return a single value. There are
different types of aggregate functions such as min, max, sum, avg, count, etc.
Why use aggregate functions: From a business perspective, different organization levels have
different information requirements. Top levels managers are usually interested in knowing whole
figures and not necessary the individual details.
Aggregate functions allow us to easily produce summarized data from our database.
CHARACTER/STRING FUNCTION:
WELCOM
---
HA
---
hai
SQL> select initcap(‘hello world') from dual;
INITCAP('Hello world’)
Hello World
SQL> select ltrim(' hai') from dual;
LTR
---
hai
SQL> select rtrim('hai ')from dual;
RTR
---
hai
RTRIM('hai)
hai
GHRCEM Pune
LENGTH('SRM')
12
SQL> select replace('SRM university', 'SRM','Anna')from dual;
Anna university
SQL> select substr('SRM', 7,6)from dual;
SUBSTR
lingam
RPAD('
hai***
LPAD
***hai
REPLACE
Danie
TRANSL
cool
SET OPERATORS
Set operations:
Union/ Intersect/ Except operations – These operations operate on relations, which must be
compatible i.e. they must have the same no. of attributes with the same domain types.
Syntax:
(select query1) Union/ Intersect/Except (select query2)
Here set operations are applied to tuples in the results of multiple select queries. All
these operations eliminate duplicate tuples from the result.
103 Schmitt
112 King
114 Ferguson
119 Labrune
121 Bergulfsen
124 Nelson
125 Piestrzeniewicz
128 Keitel
129 Murphy
131 Lee
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
| book |
| first |
| info |
| jn |
| job |
| last |
| MySQL |
| performance_schema |
| se |
| sec |
| sece |
| second |
| suraj |
| third |
| universalbank |
| viju |
+ +
18 rows in set (0.13 sec)
+ +
| Largestdiscount |
+ +
| 100 |
+ +
1 row in set (0.00 sec)
Conclusion: In this experiment, we have studied aggregate functions and Transection Control Language
and implemented Count, Sum, Max, Min, Avg, Commit, Rollback, and Savepoint commands. Simple
Queries with Aggregate functions, Queries with Aggregate functions (group by and having clause),
Queries involving- Date Functions, String Functions, Math Functions.
Experiment No. - 6
Aim: To perform SQL query that demonstrate Join Queries- Inner Join, Outer Join, Left join, Right Join
Theory:
SQL JOIN: A JOIN clause is used to combine rows from two or more tables, based on a related column
between them. Following are different types of join.
1. Equi-join/Inner join
2. Non-equi-join
3. Self-join
4. Outer join
Equi-join:
A join that is based on equalities is called equi-join. '=' operator is used in equi- join
comparison. It retrieves rows from tables having a common column. It is also called simple join.
Non-equi-join:
A join that specifies the relationship between columns belonging to different tables by
making use of the relational operators (<, >, <=, >=, !=) other than the '=' operator is called as
non-equi-join
Self-join:
Joining a table to itself is known as self-join i.e. it joins one row in a table to another. It can
compare each row of the table to itself and also with other rows of the same table.
Outer join:
An outer join returns all the rows returned by simple join or equi join as well as those rows from
one table that do not match any row from the other table.
The symbol (+) represents outer join.
Implementation:
1. Equi join:
select e.empno, e.ename, e.dept, d.deptno, d.loc, d.dname from emp e, dept d
where e.dept=d.deptno;
Output:
Output:
ENAME SALARY GRAD
E
Amit Kumar 2000 3
Nilesh Joshi 2800 3
Avinash Pawar 5000 4
Pushkar Deshpande 6500 4
3. Self Join:
select worker.ename “employee”, manager.ename “manager” from emp worker, emp manager
where worker.mgr=manager.empno;
Output:
Employee Manager Avinash
Pawar Amit Kumar Pushkar
Deshpande Amit Kumar Niraj
Sharma Amit
Kumar
Sumit Patil nitin kulkarni
Amit kumar nitin kulkarni
DEPARTMENT
DEPARTMENT;
M
DNO DNAME MGRSSN GR
ST
AR
TD
10-AUG-
1 RESEARCH 111111 12
10-AUG-
2 ACCOUNTS 222222 10
15-APR-
3 AI 333333 12
18-MAY-
4 NETWORKS 111111 14
5 BIGDATA 666666 21-JAN-10
10 rows selected.
DLOCATION
DNO DLOC
1 MYSORE
1 TUMKUR
2
BENGALUR
U
> GUB
BI
> DELH
I
> BENGALURU
PROJECT;
222 GUBBI 3
TEXTSPEECH
333 IPSECURITY DELHI 4
444 BENGALUR 5
TRAFICANAL U
555 CLOUDSEC DELHI 1
WORKS_ON
666666 - 333 4
666666 111 2
111111 222 3
555555 222 2
333333 111 4
444444 111 6
222222 111 2
UNION
(SELECT DISTINCT P.PNO
FROM PROJECT P, WORKS_ON W,
EMPLOYEE E WHERE P.PNO=W.PNO
AND
W.SSN=E.SSN
AND
NAME='SCOTT');
PNO
111
333
444
> Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise.
1. rows selected.
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department.
SELECT SUM(SALARY), MAX(SALARY),
MIN(SALARY), AVG(SALARY) FROM EMPLOYEE E, DEPARTMENT
D
WHERE DNAME='ACCOUNTS'
AND D.DNO=E.DNO;
+ + + + + + +
3 rows in set (0.00 sec)
//INNER JOIN
+ + + +
| orderID | cust_name | city |
+ + + +
| 103 | puja | pune |
| 136 | divya | mumbai |
| 101 | jay | mumbai |
+ + + +
3 rows in set (0.00 sec)
// LEFT JOIN
+ + +
5 rows in set (0.00 sec)
# RIGHT JOIN
+ + + +
6 rows in set (0.00 sec)
| 3 | divya | mumbai |
| 1 | jay | mumbai |
+ + +
+ 6 rows in set (0.00 sec)
//EQUI JOIN
//NON-EQUI JOIN
| 171 | priya | |
| 172 | priya pune |
|
pune
+ + + +
18 rows in set (0.00 sec)
Conclusion: In this experiment, we have studied SQL queries for suitable database applications using SQL
DML Statements and implemented all types of Join.
Experiment No-7
Theory:
In SQL a Subquery can be simply defined as a query within another query. In other words we can say that a
Subquery is a query that is embedded in WHERE clause of another SQL query. Important rules for
Subqueries:
● You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING clause, FROM clause.
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements along with expression
operator. It could be equality operator or comparison operator such as =, >, =, <= and Like operator.
● A subquery is a query within another query. The outer query is called as main query and inner query is
called as subquery.
● The subquery generally executes first when the subquery doesn’t have any co-relation with the main
query, when there is a co-relation the parser takes the decision on the fly on which query to execute
on precedence and uses the output of the subquery accordingly.
● Subquery must be enclosed in parentheses.
● Subqueries are on the right side of the comparison operator.
● ORDER BY command cannot be used in a Subquery. GROUPBY command can be used to perform same
function as ORDER BY command.
● Use single-row operators with singlerow Subqueries. Use multiple-row operators with multiple-row
Subqueries.
Syntax: There is not any general syntax for Subqueries. However, Subqueries are seen to be used most
frequently with SELECT statement as shown below:
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );
Sample Table: Database
NAME ROLL_NO LOCATION PHONE_NUMBER
Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi105 Kanchipuram 8989856868
Student
NAME ROLL_NOSECTION
Ravi 104 A
Sumath
i 105 B
Raj 102 A
Sample Queries:
● To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE table whose
section is A
Select NAME, LOCATION, PHONE_NUMBER from DATABASE
WHERE ROLL_NO IN
(SELECT ROLL_NO from STUDENT where SECTION=’A’);
● Explanation : First subquery executes “ SELECT ROLL_NO from STUDENT where SECTION=’A’ ”
returns ROLL_NO from STUDENT table whose SECTION is ‘A’.Then outer-query executes it and return
the NAME, LOCATION, PHONE_NUMBER from the DATABASE table of the student whose
ROLL_NO is returned from inner subquery. Output:
NAM
E ROLL_NO LOCATION PHONE_NUMBER
● Output:
1 row delete successfully.
● Display Student2 table:
NAM
E ROLL_NOLOCATION PHONE_NUMBER
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878
● To update name of the students to geeks in Student2 table whose location is same as Raju, Ravi in
Student1 table
UPDATE Student2
SET NAME=’geeks’
WHERE LOCATION IN ( SELECT LOCATION
FROM Student1
WHERE NAME IN (‘Raju’,’Ravi’));
● Output:
1 row updated successfully.
● Display Student2 table:
NAM
E ROLL_NOLOCATION PHONE_NUMBER
Sai 112 mumbai 6565656565
geeks 113 coimbatore 7878787878
Experiment No-8
QL query for extracting data from more than one table using SQL concept
Theory:
-- create database
create database stud;
use stud;
-- extracting data of the student who has core subject from his field
select student.rollno, student.sname, department.deptid, department.dept, coresubject.subjectcode,
coresubject.subjectname from student join department on student.dept = department.dept join
coresubject on department.dept = coresubject.dept
Conclusion: In this experiment we implemented SQL query for extracting data from more than
one table using SQL concept
Experiment No. 9
AIM: To perform SQL query to understand the concepts: Transaction, ROLL BACK, COMMIT & CHECK
POINTS.
Theory:
TCL (Transaction Control Language) :
Transaction Control Language 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 commands –
COMMIT: Commit command is used to permanently save any transaction
into the database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction so
that you can rollback to that point whenever necessary.
Queries:
Their schemas are as follows , Departments ( dept _no , dept_ name , dept_location ); Employees
( emp_id , emp_name , emp_salary );
Q1: Develop a query to grant all privileges of employees table into departments table
Ans: SQL> Grant all on employees to departments;
Grant succeeded.
Q2: Develop a query to grant some privileges of employees table into departments table
Ans: SQL> Grant select, update, insert on departments to departments with grant option;
Grant succeeded.
Q3: Develop a query to revoke all privileges of employees table from departments table Ans:
SQL> Revoke all on employees from departments; Revoke succeeded.
Q4: Develop a query to revoke some privileges of employees table from departments table Ans:
SQL> Revoke select, update, insert on departments from departments;
Revoke succeeded.
1 Mathi AP 1 10000
1 Mathi AP 1 10000
5 Akalya AP 1 10000
1 Mathi AP 1 10000
Example:
For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than Rs.
6,00,000.
SELECT DNO,
COUNT(SSN) FROM THE
EMPLOYEE
FROM THE
EMPLOYEE GROUP
BY DNO
HAVING COUNT(SSN)>5)
GROUP BY DNO ;
DNO COUNT(SSN)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
| book |
| first |
| info |
| jn |
| job |
| last |
| MySQL |
| performance_schema |
| se |
| sec |
| sece |
| second |
| suraj |
| third |
| universalbank |
| viju |
+ +
18 rows in set (0.13 sec)
+ +
| Largestdiscount |
+ +
| 100 |
+ +
1 row in set (0.00 sec)
Conclusion: In this experiment performed Transaction Control Language such as commit, rollback,
savepoint.
Content Beyond Syllabus
● Create Operations
● Read Operations
● Update Operations
● Delete Operations
Create Operations
Create or insert operations and add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
In MongoDB, insert operations target a single collection. All write operations in MongoDB are
atomic on the level of a single document.
Read Operations
Read operations retrieves documents from a collection; i.e. queries a collection for documents.
MongoDB provides the following methods to read documents from a collection:
● db.collection.find()
You can specify query filters or criteria that identify the documents to return.
Update Operations
Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:
In MongoDB, update operations target a single collection. All write operations in MongoDB are
atomic on the level of a single document.
You can specify criteria, or filters, that identify the documents to update. These filters use the
same syntax as reading operations.
Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following
methods to delete documents of a collection:
In MongoDB, delete operations target a single collection. All write operations in MongoDB are
atomic on the level of a single document.
You can specify criteria, or filters, that identify the documents to remove. These filters use the
same syntax as reading operations.
1.1. The Use Command: MongoDB uses DATABASE_NAME is used to create a database.
The command will create a new database; if it doesn't exist otherwise it will return the
existing database.
Syntax: Use DATABASE_NAME;
Example: If you want to create a database with the name <mydb>, then use the database
the statement would be as follows:
>use mydb
switched to db mydb
Your created database (mydb) is not present in list. To display database you need to
insert at least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is tested. If you didn't create any database then collections will be
stored in the test database.
This will delete the selected database. If you have not selected any database, then it will
delete the default 'test' database
Example:
First, check the list of available databases by using the command show dbs
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
If you want to delete new database <mydb>, then dropDatabase() command would be
as follows:
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
3. Basic Operations with the Shell: We can use the four basic operations, create, read, update,
and delete (CRUD) to manipulate and view data in the shell.
3.1. Create: The insert function adds a document to a collection. For example, suppose we
want to store a blog post. First, we’ll create a local variable called post which is a
JavaScript object representing our document. It will have the keys "title", "content", and
"date". (the date that it was published):
3.2. Read: Find and findOne can be used to query a collection. If we just want to see one
document from a collection, we can use findOne.
> db.blog.findOne()
{
"_id" : ObjectId("5037ee4a1084eb3ffeef7228"),
"title" : "My Blog Post",
"content" : "Here's my blog post.",
"date" : ISODate("2012-08-24T21:12:09.982Z")
}
Find and findOne can also be passed criteria in the form of a query document. This will
restrict the documents matched by the query. The shell will automatically display up to 20
documents matching a find, but more can be fetched. See Chapter 4 for more information on
querying.
3.3. Update: If we would like to modify our post, we can use an update. The update takes (at
least) two parameters: the first is the criteria to find which document to update, and the
second is the new document. Suppose we decide to enable comments on the blog post we
created earlier. We’ll need to add an array of comments as the value for a new key in our
document.
The first step is to modify the variable post and add a "comments" key:
> post.commen
ts = [] [ ]
Then we perform the update, replacing the post titled “My Blog Post” with our new
version of the document:
> db.blog.update({title : "My Blog Post"}, post)
Now the document has a "comments" key. If we call find again, we can see the new key:
> db.blog.find()
{
"_id" : ObjectId("5037ee4a1084eb3ffeef7228"),
"title" : "My Blog Post",
"content" : "Here's my blog post.",
"date" : ISODate("2012-08-24T21:12:09.982Z"),
"comments" : [ ]
}
3.4. Delete: Remove permanently deletes documents from the database. Called with no
parameters, it removes all documents from a collection. It can also take a document
specifying criteria for removal. For example, this would remove the post we just created:
> db.TE.insert({Roll:1,Name:"ABC",Address:"Pune",Pe
r:76}) WriteResult({ "nInserted" : 1 })
> db.TE.insert({Roll:2,Name:"PQR",Address:"Pune",Pe
r:75}) WriteResult({ "nInserted" : 1 })
> db.TE.insert({Roll:3,Name:"LMN",Address:"Hadapsar",Pe
r:70}) WriteResult({ "nInserted" : 1 })
> db.TE.find({})
{ "_id" : ObjectId("541963be2741c7552caef0a9"), "Roll" : 1, "Name" : "ABC", "Address" :
"Pune", "Per" : 76 }
{ "_id" : ObjectId("541963cb2741c7552caef0aa"), "Roll" : 2, "Name" : "PQR", "Address" :
"Pune", "Per" : 75 }
{ "_id" : ObjectId("541963dc2741c7552caef0ab"), "Roll" : 3, "Name" : "LMN", "Address"
: "Hadapsar", "Per" : 70 }
> db.TE.find({})
{ "_id" : ObjectId("541963be2741c7552caef0a9"), "Roll" : 1, "Name" : "ABC", "Address" :
"Pune", "Per" : 76 }
{ "_id" : ObjectId("541963cb2741c7552caef0aa"), "Roll" : 2, "Name" : "PQR", "Address" :
"Pune", "Per" : 75 }
{ "_id" : ObjectId("541963dc2741c7552caef0ab"), "Roll" : 3, "Name" : "LMN", "Address"
: "Hadapsar", "Per" : 70 }
> db.TE.update({Roll:2},{$set:{Name:"Wagholi"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1
})
> db.TE.find({})
{ "_id" : ObjectId("541963be2741c7552caef0a9"), "Roll" : 1, "Name" : "ABC", "Address" :
"Pune", "Per" : 76 }
{ "_id" : ObjectId("541963cb2741c7552caef0aa"), "Roll" : 2, "Name" : "Wagholi", "Address" :
"Pune", "Per" : 75 }
{ "_id" : ObjectId("541963dc2741c7552caef0ab"), "Roll" : 3, "Name" : "LMN", "Address"
: "Hadapsar", "Per" : 70 }
> db.TE.remove({Roll:3})
WriteResult({ "nRemoved" : 1 })
> db.TE.find({})
{ "_id" : ObjectId("541963be2741c7552caef0a9"), "Roll" : 1, "Name" : "ABC", "Address"
: "Pune", "Per" : 76 }
{ "_id" : ObjectId("541963cb2741c7552caef0aa"), "Roll" : 2, "Name" : "Wagholi", "Address" :
"Pune", "Per" : 75 }
> db.TE.
drop() true
> db.TE.find({})
> show
collections
system.indexes
Output:
> db.dropDatabase("COEM")
2014-09-17T16:17:18.278+0530 dropDatabase doesn't take arguments at
src/mongo/shell/db.js:141
> db.dropDatabase()
{ "dropped" : "COEM", "ok" : 1 }
Conclusion: In this experiment, we have studied NoSQL and implemented CRUD operations for MongoDB
********
Content Beyond Syllabus Experiment
11. Cassendra Query Execution
Aim: Cassandra case study
A NoSQL database (sometimes called as Not Only SQL) is a database that provides a
mechanism to store and retrieve data other than the tabular relations used in relational databases.
These databases are schema-free, support easy replication, have simple API, are eventually
consistent, and can handle huge amounts of data.
Features of Cassandra
Cassandra has become so popular because of its outstanding technical features. Given below are
some of the features of Cassandra:
● Elastic scalability − Cassandra is highly scalable; it allows to add of more hardware to
accommodate more customers and more data as per requirement.
● Always on architecture − Cassandra has no single point of failure and it is continuously
available for business-critical applications that cannot afford a failure.
● Fast linear-scale performance − Cassandra is linearly scalable, i.e., it increases your throughput
as you increase the number of nodes in the cluster. Therefore it maintains a quick response
time.
● Flexible data storage − Cassandra accommodates all possible data formats including
structured, semi-structured, and unstructured. It can dynamically accommodate changes to
your data structures according to your need.
● Easy data distribution − Cassandra provides the flexibility to distribute data where you need it
by replicating data across multiple data centers.
● Transaction support − Cassandra supports properties like Atomicity, Consistency, Isolation,
and Durability (ACID).
● Fast writes − Cassandra was designed to run on cheap commodity hardware. It performs
blazingly fast writes and can store hundreds of terabytes of data, without sacrificing the read
efficiency.
C:\apache-cassandra-3.11.6\bin>cqlsh Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.6 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
(6 rows)
cqlsh> CREATE KEYSPACE test
. WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 3 }
. AND DURABLE_WRITES = false;
SyntaxException: line 2:0 mismatched input '.' expecting K_WITH (CREATE KEYSPACE
test[.]. )
cqlsh> SELECT * FROM system_schema.keyspaces;
(3 rows)
cqlsh:tutorialspoint> UPDATE emp SET emp_city='Delhi',emp_sal=50000
... WHERE emp_id=2;
emp;
(3 rows)
cqlsh:tutorialspoint> select * from emp;
(3 rows)
cqlsh:tutorialspoint> SELECT emp_name, emp_sal from emp;
emp_name | emp_sal
+
ram | 50000
robin | 50000
rahman | 45000
(3 rows)
(2 rows)
Conclusion: In this experiment, we have studied Cassandra and implemented Cassandra queries creating keyspace,
insert, select, and delete operations.