Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views60 pages

DBMS LAB Manual

Ktu S5 dbms lab manual cycle 1

Uploaded by

krithika58raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views60 pages

DBMS LAB Manual

Ktu S5 dbms lab manual cycle 1

Uploaded by

krithika58raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

CSL333 DATABASE MANAGEMENT SYSTEMS LAB

Ex. No Contents
CYCLE I
1. Creation of database schema using DDL commands
2. Creation of database schema using DDL commands
3. Database initialization - Data insert, Data import to a database (bulk import using UI
and SQL Commands)
4. Practice SQL commands for DML (insertion, updating, altering, deletion of data, and
viewing/querying records based on condition in databases)
5. Implementation of built-in functions in RDBMS
6. Implementation of various aggregate functions in SQL
7. Implementation of Order By, Group By & Having clause
8. Implementation of set operators nested queries, and join queries
9. Practice of SQL TCL commands like Rollback, Commit, Savepoint

INTRODUCTION TO SQL
History of SQL
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared Data Banks", in June 1970
in the Association of Computer Machinery (ACM) journal, Communications of the ACM. Codd's model is now
accepted as the definitive model for relational database management systems (RDBMS). The language,
Structured English Query Language ("SEQUEL") was developed by IBM Corporation, Inc., to use Codd's
model. SEQUEL later became SQL (still pronounced "sequel"). In 1979, Relational Software, Inc. (now Oracle
Corporation) introduced the first commercially available implementation of SQL. Today, SQL is accepted as
the standard RDBMS language.
Oracle was the first company to release a product that used the English-based Structured Query Language or
SQL. This language allows end users to manipulate information of table (primary database object). To use SQL
you need not to require any programming experience. SQL is a standard language common to all relational
databases. SQL is database language used for storing and retrieving data from the database. Most Relational
Database Management Systems provide extension to SQL to make it easier for application developer. A table is
a primary object of database used to store data. It stores data in form of rows and columns.
SQL*Plus is an Oracle tool (specific program) which accepts SQL commands and PL/SQL blocks and executes
them. SQL *Plus enables manipulations of SQL commands and PL/SQL blocks. It also performs additional
tasks such as calculations, store and print query results in the form of reports, list column definitions of any
table, access and copy data between SQL databases and send messages to and accept responses from the user.
SQL *Plus is a character based interactive tool, that runs in a GUI environment. It is loaded on the client
machine.
SQL supports the following categories of commands:
1. Data Definition Language (DDL)
DDL is the short name for Data Definition Language, which deals with database schemas and descriptions, of
how the data should reside in the database.
• CREATE: to create a database and its objects like (table, index, views, store procedure, function, and
triggers)
• ALTER: alters the structure of the existing database
• DROP: delete objects from the database
• TRUNCATE: remove all records from a table, including all spaces allocated for the records are removed
• COMMENT: add comments to the data dictionary
• RENAME: rename an object

2. Data Manipulation Language (DML)


DML focuses on manipulating the data stored in the database, enabling users to retrieve, add, update, and delete
data.
• SELECT: retrieve data from a database
• INSERT: insert data into a table
• UPDATE: updates existing data within a table
• DELETE: Delete all records from a database table
• MERGE: UPSERT operation (insert or update)
• CALL: call a PL/SQL or Java subprogram
• EXPLAIN PLAN: interpretation of the data access path
• LOCK TABLE: concurrency Control
3. Data Control Language (DCL)
DCL commands manage access permissions, ensuring data security by controlling who can perform certain
actions on the database.
• GRANT: Provides specific privileges to a user (e.g., SELECT, INSERT).
• REVOKE: Removes previously granted permissions from a user.
4. Transaction Control Language (TCL)
TCL commands oversee transactional data to maintain consistency, reliability, and atomicity.
• ROLLBACK: Undoes changes made during a transaction.
• COMMIT: Saves all changes made during a transaction.
• SAVEPOINT: Sets a point within a transaction to which one can later roll back.
5. Data Query Language (DQL)
DQL is a subset of DML, specifically focused on data retrieval.
• SELECT: The primary DQL command, used to query data from the database without altering its
structure or contents.
Some of The Most Important SQL Commands
• SELECT - extracts data from a database
• UPDATE - updates data in a database
• DELETE - deletes data from a database
• INSERT INTO - inserts new data into a database
• CREATE DATABASE - creates a new database
• ALTER DATABASE - modifies a database
• CREATE TABLE - creates a new table
• ALTER TABLE - modifies a table
• DROP TABLE - deletes a table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index

Experiment No: 1

Creation of database schema using DDL commands


Experiment No: 2

Creation of database schema using DDL commands


AIM
Creation of database schema using DDL commands (create tables, set constraints, enforce relationships, create
indices, delete and modify tables).

Consider the employee database given below:


emp (emp_id,emp_name, Street_No, city)
works (emp_id, company name, salary)
company (company name, city)
manages (emp_id, manager_id)
1. Add these four tables with sufficient constraints.
2. Alter table emp add a constraint that emp_name cannot be null

COMMANDS
A. Create table emp
a. Create table emp(emp_id char(8) primary key, emp_name varchar(18),street_no int,city varchar(18));
B. Create table company
a. Create table company(company_name varchar(18) primary key, city varchar(18));
C. Create table works
a. Create table works(emp_id char(8) references emp(emp_id),company_name varchar(18) references
company(company_name),salary float,primary key(emp_id,company_name));

D. Create table manages


Create table manages(emp_id char(8) references emp(emp_id),manager_id char(8) references
emp(emp_id),unique(emp_id,manager_id));
I. Alter table emp
a. alter table emp MODIFY emp_name varchar(18) NOT NULL;
SAMPLE OUTPUT:

mysql> create database employee;


Query OK, 1 row affected (0.05 sec)

mysql> use employee;


Database changed
mysql> Create table emp(emp_id char(8) primary key, emp_name varchar(18),street_no int,city varchar(18));
Query OK, 0 rows affected (0.13 sec)

mysql> desc emp;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| emp_id | char(8) | NO | PRI | NULL | |
| emp_name | varchar(18) | YES | | NULL | |
| street_no | int | YES | | NULL | |
| city | varchar(18) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.05 sec)

mysql> Create table company(company_name varchar(18) primary key, city varchar(18));


Query OK, 0 rows affected (0.06 sec)

mysql> desc company;


+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| company_name | varchar(18) | NO | PRI | NULL | |
| city | varchar(18) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> Create table works(emp_id char(8) references emp(emp_id),company_name varchar(18) references


company(company_name),salary float,primary key(emp_id,company_name));
Query OK, 0 rows affected (0.07 sec)

mysql> desc works;


+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| emp_id | char(8) | NO | PRI | NULL | |
| company_name | varchar(18) | NO | PRI | NULL | |
| salary | float | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> Create table manages(emp_id char(8) references emp(emp_id),manager_id char(8) references


emp(emp_id),unique(emp_id,manager_id));
Query OK, 0 rows affected (0.08 sec)

mysql> desc manages;


+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| emp_id | char(8) | YES | MUL | NULL | |
| manager_id | char(8) | YES | | NULL | |
+------------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table emp MODIFY emp_name varchar(18) NOT NULL;


Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc emp;


+-----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| emp_id | char(8) | NO | PRI | NULL | |
| emp_name | varchar(18) | NO | | NULL | |
| street_no | int | YES | | NULL | |
| city | varchar(18) | YES | | NULL | |
+-----------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

RESULT
Query has run successfully and result is obtained.
Experiment No: 3

Database initialization - Data insert, Data import to a database (bulk import using UI
and SQL Commands)

AIM
To insert data to tables used in employee database using insert commands and bulk import using UI and
sql commands.

COMMANDS
1. INSERT COMMANDS

insert into emp values(101,'Adarsh',101,'MG Road');


insert into emp values(102,'Bonny',101, 'MG Road');
insert into emp values(103,'Catherine', 102, 'Cochin');
insert into emp values(104,'Glenn', 104, 'Ernakulam');
insert into emp values(105,'George', 201,'MG Road');
insert into emp values(106,'Hayes', 101, 'MG Road');
insert into emp values(107,'Johnson',102,‘Cochin‘);
insert into emp values(108,'Jones', 101, 'Cochin');
insert into emp values(109,‗Karthik‘, 101, 'Ernakulam');
insert into emp values(110,'Lavanya', 101, 'Palace Road');
insert into emp values(111,'Niharika', 102, ‗Ernakulam‘);

insert into company values('SBI', 'MG Road');


insert into company values('SBT', 'MG Road');
insert into company values('Federal’, ‘Broadway’);
insert into company values('Indian Bank', ‘Cochin‘);
insert into company values('SIB', 'Ernakulam');
insert into company values('HDFC', 'Palace Road');
insert into company values('Axis’, ‘Cochin‘);
insert into company values('City bank', 'Ernakulam');

insert into works values(101, 'SBI', 71000);


insert into works values(102, 'SBI', 90000);
insert into works values(103, 'SBT', 40000);
insert into works values(104, 'Federal', 37000);
insert into works values(105, 'SBT', 17000);
insert into works values(106, 'Indian Bank', 30000);
insert into works values(107, ‘SIB‘, 21000);
insert into works values(108, 'SIB', 18000);
insert into works values(109, 'Indian Bank', 28000);
insert into works values(110, 'SBT', 250000);
insert into works values(111, 'Federal',40000);

insert into manages values(101, '102');


insert into manages values(102, Null);
insert into manages values(103, '110');
insert into manages values(104, '111');
insert into manages values(105, '110');
insert into manages values(106, ‘109‘);
insert into manages values(107, Null);
insert into manages values(108, Null);
insert into manages values(109,Null);
insert into manages values(110, Null);
insert into manages values(111, null);
Export table values to a file
First see where is the path set for secure_file_priv, we can do Export and import in this location only
(else need to configure it) so use following command:
mysql>SHOW VARIABLES LIKE 'secure_file_priv';
mysql>SELECT * FROM WORKS
-> INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/out.txt'
-> FIELDS TERMINATED BY ','
-> ENCLOSED BY '"'
-> LINES TERMINATED BY '\n';

To show the contents of the file to which data is Exported use type in command prompt
type "C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\out.txt"
Load values from a Exported file to SQL Table
mysql>LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/out.txt'
-> IGNORE
-> INTO TABLE EMPLOYEE.WORKS
-> FIELDS TERMINATED BY ','
-> ENCLOSED BY '"'
-> LINES TERMINATED BY '\n';
SAMPLE OUTPUT:

mysql> use employee;


Database changed
mysql> insert into emp values(101,'Adarsh',101,'MG Road');
Query OK, 1 row affected (0.01 sec)

mysql> insert into emp values(102,'Bonny',101, 'MG Road');


Query OK, 1 row affected (0.01 sec)

mysql> insert into emp values(103,'Catherine', 102, 'Cochin');


Query OK, 1 row affected (0.01 sec)

mysql> insert into emp values(104,'Glenn', 104, 'Ernakulam');


Query OK, 1 row affected (0.01 sec)

mysql> select * from emp;


+--------+-----------+-----------+-----------+
| emp_id | emp_name | street_no | city |
+--------+-----------+-----------+-----------+
| 101 | Adarsh | 101 | MG Road |
| 102 | Bonny | 101 | MG Road |
| 103 | Catherine | 102 | Cochin |
| 104 | Glenn | 104 | Ernakulam |
+--------+-----------+-----------+-----------+
4 rows in set (0.00 sec)

mysql> insert into company values('SBT', 'MG Road' );


Query OK, 1 row affected (0.01 sec)

mysql> insert into company values('SBI', 'MG Road');


Query OK, 1 row affected (0.01 sec)

mysql> insert into company values('Indian Bank','Cochin');


Query OK, 1 row affected (0.01 sec)

mysql> select * from company;


+--------------+---------+
| company_name | city |
+--------------+---------+
| Indian Bank | Cochin |
| SBI | MG Road |
| SBT | MG Road |
+--------------+---------+
3 rows in set (0.00 sec)

mysql> insert into works values(101, 'SBI', 71000);


Query OK, 1 row affected (0.01 sec)

mysql> insert into works values(102, 'SBI', 90000);


Query OK, 1 row affected (0.01 sec)

mysql> insert into works values(103, 'SBT', 40000);


Query OK, 1 row affected (0.01 sec)

mysql> select * from works;


+--------+--------------+--------+
| emp_id | company_name | salary |
+--------+--------------+--------+
| 101 | SBI | 71000 |
| 102 | SBI | 90000 |
| 103 | SBT | 40000 |
+--------+--------------+--------+
3 rows in set (0.00 sec)

mysql> insert into manages values(101, 'E102');


Query OK, 1 row affected (0.01 sec)

mysql> insert into manages values(102, Null);


Query OK, 1 row affected (0.01 sec)

mysql> insert into manages values(103, 'E-110');


Query OK, 1 row affected (0.01 sec)

mysql> insert into manages values(104, 'E-111');


Query OK, 1 row affected (0.01 sec)
mysql> select * from manages;
+--------+------------+
| emp_id | manager_id |
+--------+------------+
| 101 | E102 |
| 102 | NULL |
| 103 | E-110 |
| 104 | E-111 |
+--------+------------+
4 rows in set (0.00 sec)

mysql> SHOW VARIABLES LIKE 'secure_file_priv';


+------------------+------------------------------------------------+
| Variable_name | Value |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set (0.02 sec)
mysql> SELECT * FROM WORKS
-> INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/out.txt'
-> FIELDS TERMINATED BY ','
-> ENCLOSED BY '"'
-> LINES TERMINATED BY '\n';
Query OK, 3 rows affected (0.01 sec)
Command Prompt:
C:\Users\SHIBI>type "C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\out.txt"
"101","SBI","71000"
"102","SBI","90000"
"103","SBT","40000"

mysql> LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/out.txt'


-> IGNORE
-> INTO TABLE EMPLOYEE.WORKS
-> FIELDS TERMINATED BY ','
-> ENCLOSED BY '"'
-> LINES TERMINATED BY '\n';
Query OK, 0 rows affected, 3 warnings (0.00 sec)
Records: 3 Deleted: 0 Skipped: 3 Warnings: 3

RESULT
Query has run successfully and result is obtained.
Experiment No: 4

Practice SQL commands for DML (insertion, updating, altering, deletion of data,
and viewing/querying records based on condition in databases)

AIM
Consider the employee database created in Find results for the following questions.
a. Find the names of all employees who work for SBI.
b. Find all employees in the database who live in the same cities as the companies for
which they work.
c. Find all employees and their managers in the database who live in the same cities and on the same
street number as do their managers.
d. Find all employees who earn more than the average salary of all employees of their
company.
e. Find the company that pay least total salary along with the salary paid.
f. Give all managers of SBI a 10 percent raise.
g. Find the company that has the most employees.
h. Find those companies whose employees earn a higher salary, on average than the
average salary at Indian Bank.
i. Query to find name and salary of all employees who earn more than each employee
of ‘Indian Bank.
Queries:
a) Find the names of all employees who work for SBI.
SELECT emp_name FROM works,emp WHERE company_name=‘SBI‘and
emp.emp_id=works.emp_id;
b) Find all employees in the database who live in the same cities as the companies for which they
work.
SELECT emp.emp_name FROM emp, works,company WHERE
emp.emp_id = works. emp_id AND works. company_name= company.company_name AND
emp.city = company.city;
c) Find all employees and their managers in the database who live in the same cities and on the
same street number as do their managers.
SELECT emp.emp_name,e2.emp_name “manager name”FROM emp,emp e2,
manages WHERE emp.emp_id = manages.emp_id AND e2.Emp_id= manages.manager_id AND
emp.street_no = e2.street_no AND emp.city = e2.city;
d) Find all employees who earn more than the average salary of all employees of their company.
SELECT emp_name,emp.emp_id,salary FROM works ,emp WHERE salary >(SELECT AVG
(salary) FROM works S WHERE works.company_name =S.company_name) and
emp.emp_id=works.emp_id;
e) Find the company that pay least total salary along with the salary paid.
SELECT company_name,sum(salary) “SALARY PAID” from Works GROUP
BY company_name HAVING sum(salary) <= all (SELECT sum(salary) FROM
Works GROUP BY company_name);
f) Give all managers of SBI a 10 percent raise.
UPDATE works SET salary = salary * 1.1 WHERE emp_id in (select manager_id from manages)
and company_name =‘SBI‘;
g) Find the company that has the most employees
SELECT company_name FROM works GROUP BY company_name HAVING COUNT(DISTINCT
emp_id) = (SELECT MAX(emp_count) FROM (SELECT COUNT(DISTINCT emp_id) AS emp_count
FROM works GROUP BY company_name) AS counts);
h) Find those companies whose employees earn a higher salary, on average than the average salary
at Indian Bank.
SELECT company_name FROM works GROUP BY company_name HAVING AVG(salary)>
(SELECT AVG(salary) FROM works WHERE company_name = ‘Indian Bank’ GROUP BY
company_name);
i) Query to find name and salary of all employees who earn more than each employee of ‘Indian
Bank’
SELECT emp_name,salary FROM works,emp WHERE salary > (SELECT MAX(salary) FROM
works WHERE company_name = ‘Indian Bank’ GROUP BY company_name) and
emp.emp_id=works.emp_id;

SAMPLE OUTPUT:

mysql> use employee;


Database changed
a) Find the names of all employees who work for SBI.
mysql> SELECT emp_name FROM works,emp WHERE company_name='SBI'and
emp.emp_id=works.emp_id;
+----------+
| emp_name |
+----------+
| Adarsh |
| Bonny |
+----------+
2 rows in set (0.05 sec)
b) Find all employees in the database who live in the same cities as the companies for
which they work.
mysql> SELECT emp.emp_name FROM emp, works,company WHERE
-> emp.emp_id = works. emp_id AND works. company_name= company.company_name AND emp.city =
company.city;
+----------+
| emp_name |
+----------+
| Adarsh |
| Bonny |
+----------+
2 rows in set (0.01 sec)
c) Find all employees and their managers in the database who live in the same cities and on the same street
number as do their managers.
mysql> SELECT emp.emp_name,e2.emp_name "manager name"FROM emp,emp e2,manages WHERE
emp.emp_id = manages.emp_id AND e2.Emp_id= manages.manager_id AND emp.street_no = e2.street_no
AND emp.city = e2.city;
Empty set (0.01 sec)
d) Find all employees who earn more than the average salary of all employees of their company.
mysql> SELECT emp_name,emp.emp_id,salary FROM works ,emp WHERE salary >(SELECT AVG (salary)
FROM works S WHERE works.company_name =S.company_name) and emp.emp_id=works.emp_id;
+----------+--------+--------+
| emp_name | emp_id | salary |
+----------+--------+--------+
| Bonny | 102 | 90000 |
+----------+--------+--------+
1 row in set (0.01 sec)
e) Find the company that pay least total salary along with the salary paid.
mysql> SELECT company_name,sum(salary) "SALARY PAID" from Works GROUP BY company_name
HAVING sum(salary) <= all (SELECT sum(salary) FROM Works GROUP BY company_name);
+--------------+-------------+
| company_name | SALARY PAID |
+--------------+-------------+
| SBT | 40000 |
+--------------+-------------+
1 row in set (0.01 sec)
f) Give all managers of SBI a 10 percent raise.
mysql> UPDATE works SET salary = salary * 1.1 WHERE emp_id in (select manager_id from manages) and
company_name ='SBI';
Query OK, 0 rows affected (0.01 sec)
Rows matched: 0 Changed: 0 Warnings: 0
g) Find the company that has the most employees
mysql> SELECT company_name FROM works GROUP BY company_name HAVING COUNT(DISTINCT
emp_id) = (SELECT MAX(emp_count) FROM (SELECT COUNT(DISTINCT emp_id) AS emp_count FROM
works GROUP BY company_name) AS counts);
+--------------+
| company_name |
+--------------+
| SBI |
+--------------+
1 row in set (0.00 sec)
h) Find those companies whose employees earn a higher salary, on average than the average salary at Indian
Bank.

mysql> SELECT company_name FROM works GROUP BY company_name HAVING AVG(salary)>


(SELECT AVG(salary) FROM works WHERE company_name = 'Indian Bank' GROUP BY company_name);
Empty set (0.00 sec)
i) Query to find name and salary of all employees who earn more than each employee of ‘Indian Bank’
mysql> SELECT emp_name,salary FROM works,emp WHERE salary > (SELECT MAX(salary) FROM
works WHERE company_name = 'Indian Bank' GROUP BY company_name) and emp.emp_id=works.emp_id;
Empty set (0.00 sec)

RESULT
Query has run successfully and result is obtained.
Experiment No: 5
Implementation of built-in functions in RDBMS
AIM
RDBMS Built in Functions
There are two types of functions:
1. Single Row Functions: Single row or Scalar functions return a value for every row that is processed in a
query.
2. Group Functions: These functions group the rows of data based on the values returned by the query. This is
discussed in SQL GROUP Functions. The group functions are used to calculate aggregate values like total or
average, which return just one total or one average value after processing a group of rows.
There are four types of single row functions. They are:
1. Numeric Functions: These are functions that accept numeric input and return numeric values.
2. Character Functions: These are functions that accept character input and can return both character and number
values.
3. Date Functions: These are functions that take values that are of datatype DATE as input and return values of
datatype DATE, Except for the MONTHS_BETWEEN function, which returns a number.
4. Conversion Functions: These are functions that help us to convert a value in one form to another form. For
Example: a null value into an actual value, or a value from one datatype to another datatype like NVL(Null
Value Logic is used to replace null values with a specified value), TO_CHAR, TO_NUMBER, TO_DATE etc.
Mathematical Functions
SQL> select ABS(-100) from dual;
ABS(-100)
----------
100
SQL> select ABS(-6) from dual;
ABS(-6)
----------
6
SQL> select FLOOR(2345.78) FROM DUAL;
FLOOR(2345.78)
--------------
2345
SQL> SELECT GREATEST(23,67,90,123,78,50) FROM DUAL; GREATEST(23,67,90,123,78,50)
----------------------------
123
SQL> SELECT LEAST(34, 21,67,11,89,9) FROM DUAL;
LEAST(34,21,67,11,89,9)
9
SQL> SELECT LENGTH('RAJESHWARI') FROM DUAL;
LENGTH('RAJESHWARI')
--------------------
10
SQL> SELECT LENGTH(17245637) FROM DUAL;
LENGTH(17245637)
----------------
8
SQL> SELECT SQRT(16) FROM DUAL;
SQRT(16)
----------
4
SQL> SELECT SQRT(99) FROM DUAL;
SQRT(99)
9.94987437
SQL> SELECT POWER(2,4) FROM DUAL;
POWER(2,4)
----------
16
SQL> SELECT POWER(2,10) FROM DUAL;
POWER(2,10)
-----------
1024
SQL> SELECT power(2,10) FROM DUAL;
POWER(2,10)
-----------
1024
SQL> SELECT ROUND(5.86) FROM DUAL;
ROUND(5.86)
-----------
6
SQL> SELECT ROUND(1001.6) FROM DUAL;
ROUND(1001.6)
1002
SQL> SELECT ROUND(1001.3) FROM DUAL;
ROUND(1001.3)
-------------
1001
SQL> SELECT SIN(90) FROM DUAL;
SIN(90)
----------
.893996664
SQL> SELECT COS(45) FROM DUAL;
COS(45)
----------
.525321989
SQL> SELECT TAN(30) FROM DUAL;
TAN(30)
----------
-6.4053312
SQL> SELECT TAN(90) FROM DUAL;
TAN(90)
----------
-1.9952004
SQL> SELECT TAN(180) FROM DUAL;
TAN(180)
----------
1.33869021
SQL> SELECT SIGN(-128) FROM DUAL;
SIGN(-128)
----------
-1
SQL> SELECT SIGN(10) FROM DUAL;
SIGN(10)
----------
1
SQL> SELECT SIGN(0) FROM DUAL;
SIGN(0)
----------
0
SQL> SELECT LN(100) FROM DUAL;
LN(100)
----------
4.60517019
SQL> SELECT LN(10) FROM DUAL;
LN(10)
----------
2.30258509
SQL> SELECT LOG(10,100) FROM DUAL;
LOG(10,100)
-----------
2
SQL> SELECT LOG(100,10) FROM DUAL;
LOG(100,10)
-----------
.5
SQL> SELECT MOD(4,3) FROM DUAL;
MOD(4,3)
----------
1
SQL> SELECT MOD(4,2) FROM DUAL;
MOD(4,2)
----------
0
mysql> SELECT EXP(2) FROM DUAL;
+------------------+
| EXP(2) |
+------------------+
| 7.38905609893065 |
+------------------+
1 row in set (0.00 sec)
mysql> SELECT EXP(-2) FROM DUAL;
+--------------------+
| EXP(-2) |
+--------------------+
| 0.1353352832366127 |
+--------------------+
1 row in set (0.01 sec)
SQL> SELECT EXP(0) FROM DUAL;
EXP(0)
----------
1
Date Functions
SQL> SELECT CURRENT_DATE FROM DUAL;
CURRENT_D
---------
14-AUG-19
mysql> SELECT EXTRACT(YEAR FROM SYSDATE()) FROM DUAL;
+------------------------------+
| EXTRACT(YEAR FROM SYSDATE()) |
+------------------------------+
| 2025 |
+------------------------------+
1 row in set (0.01 sec)
SQL> SELECT EXTRACT(DAY FROM SYSDATE()) FROM DUAL;
EXTRACT(DAYFROMSYSDATE())
-----------------------
14
SQL> SELECT EXTRACT(MONTH FROM SYSDATE()) FROM DUAL;
EXTRACT(MONTHFROMSYSDATE())
-------------------------
8
SQL> SELECT SYSDATE() FROM DUAL;
SYSDATE
---------
AUG-19
String Functions
SQL> select ascii('t') from dual;
ASCII('T')
----------
116
SQL> select ascii('a') from dual;
ASCII('A')
----------
97
SQL> select ascii('A') from dual;
ASCII('A')
----------
65
SQL> select ascii('Z') from dual;
ASCII('Z')
----------
90
SQL> select ascii('z') from dual;
ASCII('Z')
----------
122
SQL> SELECT UPPER('bldea sb arts and kcp science college') from dual;
UPPER('BLDEASBARTSANDKCPSCIENCECOLLEG‘)
-------------------------------------
BLDEA SB ARTS AND KCP SCIENCE COLLEGE
SQL> select LOWER('welcome to dbms lab') from dual;
LOWER('WELCOMETODBMSLAB’)
-------------------
welcome to dbms lab
SQL> select LOWER('WELCOME TO DBMSLAB') from dual;
LOWER('WELCOMETO DBMSLAB')
------------------
welcome to dbmslab
SQL> SELECT REPLACE('HELLO','H','K') FROM DUAL;
+--------------------------+
| REPLACE('HELLO','H','K') |
+--------------------------+
| KELLO |
+--------------------------+
1 row in set (0.00 sec)
SQL> SELECT REPLACE('COMPUTER','C','K') FROM DUAL;
REPLACE( --------
KOMPUTER
SQL> SELECT REPLACE('HELLO','L','A') FROM DUAL;
REPLA
-----
HEAAO
SQL> SELECT TRIM('A' FROM 'ANACONDA') FROM DUAL;
TRIM('
--
NACOND
SQL> SELECT REGEXP_REPLACE('ANACONDA', '^A+', '');
+---------------------------------------+
| REGEXP_REPLACE('ANACONDA', '^A+', '') |
+---------------------------------------+
| NACONDA |
+---------------------------------------+
1 row in set (0.03 sec)
SQL> SELECT REGEXP_REPLACE('ANITA','^A+','') FROM DUAL;
+----------------------------------+
| REGEXP_REPLACE('ANITA','^A+','') |
+----------------------------------+
| NITA |
+----------------------------------+
1 row in set (0.00 sec)
SQL> SELECT REGEXP_REPLACE('ANACONDA', 'A+$', '');
+---------------------------------------+
| REGEXP_REPLACE('ANACONDA', 'A+$', '') |
+---------------------------------------+
| ANACOND |
+---------------------------------------+
1 row in set (0.00 sec)

RESULT
Query has run successfully and result is obtained.
Experiment No: 6
Implementation of various aggregate functions in SQL

AIM
Create the tables with the following fields
Faculty (FacultyCode, FacultyName)
Subject (SubjectCode,SubjectName,MaxMark,FacultyCode)
Student(StudentCode,StudentName,DOB,StudentsBranch(CS/EC/EE/ME),
AdmissionDate)
M_Mark (StudentCode, SubjectCode, Mark)
Do the following queries
a) Display the number of faculties.
b) Display the total mark for each student.
c) Display the subject, average mark for each subject.
d) Display the name of subjects for which at least one student got below 40%.
e) Display the name, subject and percentage of mark who got below 40 %.
f) Display the faculties and allotted subjects for each faculty
g) Display the name of faculties who take more than one subject.
h) Display name, subject, mark, % of mark in ascending order of mark.
Commands
Create Table Faculty (F_Code int Primary Key, F_Name Varchar(15));
INSERT INTO Faculty (F_Code, F_Name) VALUES (105, 'Jaya Kumar');
INSERT INTO Faculty (F_Code, F_Name) VALUES (104, 'Sangeethe');
INSERT INTO Faculty (F_Code, F_Name) VALUES (102, 'Bindu');
INSERT INTO Faculty (F_Code, F_Name) VALUES (101, 'Silgy');
INSERT INTO Faculty (F_Code, F_Name) VALUES (103, 'Vidhya');
SELECT * FROM Faculty;

create table Subject (subjectcode varchar(5) primary key not null,subjectname char(15),maxmark
int,faculty_code int,foreign key(faculty_code) references Faculty(f_code));
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('CS101', 'Database', 100,
105);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('503', 'DBMS', 100,
105);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('501', 'Maths', 150, 101);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('502', 'FSA', 100, 102);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('504', 'OS', 75, 103);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('505', 'DC', 200, 104);
INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('508', 'DBMS LAB',
1001, 103);

create table Student(studentcode varchar(5) primary key not null,studentname varchar(15),dob


date,studentbranch char(3),adate date,check(studentbranch in('cs','ec','ee','me')));
insert into Student values('1','Amitha','1987-01-12','cs','2000-06-1');
insert into Student values('1','Amitha','1987-01-12','cs','2000-06-1');
insert into student values(2,'vaidehi','88-12-25','me','2000-06-1');
insert into student values(3,'Varun','88-10-2','me','2000-06-2');
insert into student values(4,'Turner','88-09-5','ec','2000-06-1');
insert into student values(5,'Vani','88-07-20','ee','2000-06-1');

create table M_mark(studentcode varchar(5) references Student(studentcode),subjectcode varchar(5) references


Subject(subjectcode),mark int,primary key(studentcode,subjectcode));
insert into M_mark values(1,501,40);
insert into M_mark values(1,502,70);
insert into M_mark values(1,503,50);
insert into M_mark values(1,504,80);
insert into M_mark values(1,505,40);
insert into M_mark values(1,508,70);
insert into M_mark values(2,501,90);
insert into M_mark values(2,502,89);
insert into M_mark values(2,503,77);
insert into M_mark values(2,504,95);
insert into M_mark values(2,505,74);
insert into M_mark values(2,508,98);
insert into M_mark values(3,501,40);
insert into M_mark values(3,502,43);
insert into M_mark values(3,503,40);
insert into M_mark values(3,504,40);
insert into M_mark values(3,505,40);
insert into M_mark values(3,508,35);
insert into M_mark values(4,501,50);
insert into M_mark values(5,501,60);
insert into M_mark values(6,501,67);
insert into M_mark values(7,501,23);
insert into M_mark values(8,501,43);
insert into M_mark values(9,501,42);
insert into M_mark values(10,505,74);
insert into M_mark values(11,508,98);
insert into M_mark values(12,501,40);
insert into M_mark values(6,503,40);
insert into M_mark values(7,504,40);
insert into M_mark values(8,505,40);
insert into M_mark values(9,508,35);
insert into M_mark values(10,501,50);
insert into M_mark values(11,501,60);
insert into M_mark values(12,503,67);
insert into M_mark values(5,504,23);
insert into M_mark values(6,504,23);
insert into M_mark values(9,504,1);
insert into M_mark values(10,504,1);
insert into M_mark values(6,502,43);
insert into M_mark values(7,505,42);

a) Display the number of faculties.


select count(*) "No: of Faculties" from faculty;
b) Display the total mark for each student.
select studentname,sum(mark) "Total Mark" from M_mark,Student where Student.studentcode=
M_mark.studentcode group by studentname;
c) Display the subject, average mark for each subject.
select subjectname,round(avg(mark),2) "Average mark" from Subject,M_mark where Subject.subjectcode=
M_mark.subjectcode group by subjectname;
d) Display the name of subjects for which at least one student got below 40%.
select subject.subjectname,count(student.studentname)"NO: OF STUDENTS" from subject,m_mark,student
where student.studentcode= m_mark.studentcode and m_mark.mark<(40* maxmark)/100 and
subject.SubjectCode=m_mark.Subjectcode group by subject. Subjectname having
count(distinct(m_mark.subjectcode))>=1;
e) Display the name, subject and percentage of mark who got below 40 %.
select studentname,subjectname,mark,maxmark,round((m_mark.mark/maxmark)*100,2)"Percentage" from
subject, student, m_mark where mark<(40*maxmark/100) and subject.SubjectCode = m_mark. subjectcode and
student.studentcode =m_mark.studentcode;
f) Display the faculties and allotted subjects for each faculty.
select Faculty.f_name,Subject.subjectname from Faculty,Subject where Faculty.F_code=Subject.faculty_code;
g) Display the name of faculties who take more than one subject.
Select f_name name from Faculty where (select count(subjectcode) from Subject where
Subject.faculty_code=Faculty.f_code)>1 group by Faculty.f_name;
h) Display name, subject, mark, % of mark in ascending order of mark.
select studentname,subjectname,mark from Student,Subject,M_mark where
Student.studentcode=M_mark.studentcode and Subject.subjectcode=M_mark.subjectcode order by mark;
OUTPUT:
mysql> create database faculty;
Query OK, 1 row affected (0.11 sec)

mysql> use faculty;


Database changed
mysql> Create Table Faculty (F_Code int Primary Key, F_Name Varchar(15));
Query OK, 0 rows affected (0.30 sec)
mysql> desc Faculty;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| F_Code | int | NO | PRI | NULL | |
| F_Name | varchar(15) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
2 rows in set (0.10 sec)
mysql> INSERT INTO Faculty (F_Code, F_Name) VALUES (105, 'Jaya Kumar');
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Faculty (F_Code, F_Name) VALUES (104, 'Sangeethe');


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Faculty (F_Code, F_Name) VALUES (102, 'Bindu');


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Faculty (F_Code, F_Name) VALUES (101, 'Silgy');


ERROR 1062 (23000): Duplicate entry '101' for key 'faculty.PRIMARY'
mysql> INSERT INTO Faculty (F_Code, F_Name) VALUES (103, 'Vidhya');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM Faculty;


+--------+------------+
| F_Code | F_Name |
+--------+------------+
| 101 | John Smith |
| 102 | Bindu |
| 103 | Vidhya |
| 104 | Sangeethe |
| 105 | Jaya Kumar |
+--------+------------+
5 rows in set (0.00 sec)
mysql> create table Subject (subjectcode varchar(5) primary key not null,subjectname char(15),maxmark
int,faculty_code int,foreign key(faculty_code) references Faculty(f_code));
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('CS101',
'Database', 100, 105);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('503', 'DBMS',
100, 105);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('501', 'Maths',
150, 101);
Query OK, 1 row affected (0.01 sec)
mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('502', 'FSA',
100, 102);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('504', 'OS', 75,
103);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('505', 'DC', 200,
104);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Subject (subjectcode, subjectname, maxmark, faculty_code) VALUES ('508', 'DBMS
LAB', 1001, 103);
Query OK, 1 row affected (0.01 sec)

mysql> select * from Subject;


+-------------+-------------+---------+--------------+
| subjectcode | subjectname | maxmark | faculty_code |
+-------------+-------------+---------+--------------+
| 501 | Maths | 150 | 101 |
| 502 | FSA | 100 | 102 |
| 503 | DBMS | 100 | 105 |
| 504 | OS | 75 | 103 |
| 505 | DC | 200 | 104 |
| 508 | DBMS LAB | 1001 | 103 |
| CS101 | Database | 100 | 105 |
+-------------+-------------+---------+--------------+
7 rows in set (0.00 sec)
mysql> create table Student(studentcode varchar(5) primary key not null,studentname varchar(15),dob
date,studentbranch char(3),adate date,check(studentbranch in('cs','ec','ee','me')));
Query OK, 0 rows affected (0.31 sec)
mysql> insert into Student values('1','Amitha','1987-01-12','cs','2000-06-1');
Query OK, 1 row affected (0.01 sec)
mysql> insert into student values(2,'vaidehi','88-12-25','me','2000-06-1');
Query OK, 1 row affected (0.02 sec)
mysql> insert into student values(3,'Varun','88-10-2','me','2000-06-2');
Query OK, 1 row affected (0.01 sec)
mysql> insert into student values(4,'Turner','88-09-5','ec','2000-06-1');
Query OK, 1 row affected (0.01 sec)
mysql> insert into student values(5,'Vani','88-07-20','ee','2000-06-1');
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;


+-------------+-------------+------------+---------------+------------+
| studentcode | studentname | dob | studentbranch | adate |
+-------------+-------------+------------+---------------+------------+
|1 | Amitha | 1987-01-12 | cs | 2000-06-01 |
|2 | vaidehi | 1988-12-25 | me | 2000-06-01 |
|3 | Varun | 1988-10-02 | me | 2000-06-02 |
|4 | Turner | 1988-09-05 | ec | 2000-06-01 |
|5 | Vani | 1988-07-20 | ee | 2000-06-01 |
+-------------+-------------+------------+---------------+------------+
5 rows in set (0.00 sec)

mysql> create table M_mark(studentcode varchar(5) references Student(studentcode),subjectcode varchar(5)


references Subject(subjectcode),mark int,primary key(studentcode,subjectcode));
Query OK, 0 rows affected (0.07 sec)
mysql> insert into M_mark values(1,501,40);
Query OK, 1 row affected (0.06 sec)

mysql> insert into M_mark values(1,502,70);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(1,503,50);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(1,504,80);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(1,505,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(1,508,70);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,501,90);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,502,89);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,503,77);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,504,95);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,505,74);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(2,508,98);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(3,501,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(3,502,43);


Query OK, 1 row affected (0.02 sec)

mysql> insert into M_mark values(3,503,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(3,504,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(3,505,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(3,508,35);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(4,501,50);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(5,501,60);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(6,501,67);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(7,501,23);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(8,501,43);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(9,501,42);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(10,505,74);


Query OK, 1 row affected (0.02 sec)

mysql> insert into M_mark values(11,508,98);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(12,501,40);


Query OK, 1 row affected (0.01 sec)
mysql> insert into M_mark values(6,503,40);
Query OK, 1 row affected (0.04 sec)

mysql> insert into M_mark values(7,504,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(8,505,40);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(9,508,35);


Query OK, 1 row affected (0.02 sec)

mysql> insert into M_mark values(10,501,50);


Query OK, 1 row affected (0.02 sec)
mysql> insert into M_mark values(11,501,60);
Query OK, 1 row affected (0.02 sec)

mysql> insert into M_mark values(12,503,67);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(5,504,23);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(6,504,23);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(9,504,1);


Query OK, 1 row affected (0.02 sec)

mysql> insert into M_mark values(10,504,1);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(6,502,43);


Query OK, 1 row affected (0.01 sec)

mysql> insert into M_mark values(7,505,42);


Query OK, 1 row affected (0.01 sec)

mysql> select * from M_mark;


+-------------+-------------+------+
| studentcode | subjectcode | mark |
+-------------+-------------+------+
|1 | 501 | 40 |
|1 | 502 | 70 |
|1 | 503 | 50 |
|1 | 504 | 80 |
|1 | 505 | 40 |
|1 | 508 | 70 |
| 10 | 501 | 50 |
| 10 | 504 | 1|
| 10 | 505 | 74 |
| 11 | 501 | 60 |
| 11 | 508 | 98 |
| 12 | 501 | 40 |
| 12 | 503 | 67 |
|2 | 501 | 90 |
|2 | 502 | 89 |
|2 | 503 | 77 |
|2 | 504 | 95 |
|2 | 505 | 74 |
|2 | 508 | 98 |
|3 | 501 | 40 |
|3 | 502 | 43 |
|3 | 503 | 40 |
|3 | 504 | 40 |
|3 | 505 | 40 |
|3 | 508 | 35 |
|4 | 501 | 50 |
|5 | 501 | 60 |
|5 | 502 | 43 |
|5 | 504 | 23 |
|6 | 501 | 67 |
|6 | 502 | 43 |
|6 | 503 | 40 |
|6 | 504 | 23 |
|7 | 501 | 23 |
|7 | 504 | 40 |
|7 | 505 | 42 |
|8 | 501 | 43 |
|8 | 505 | 40 |
|9 | 501 | 42 |
|9 | 504 | 1|
|9 | 508 | 35 |
+-------------+-------------+------+
41 rows in set (0.00 sec)

a) Display the number of faculties.


mysql> select count(*) "No: of Faculties" from faculty;
+------------------+
| No: of Faculties |
+------------------+
| 5|
+------------------+
1 row in set (0.00 sec)
b) Display the total mark for each student.
mysql> select studentname,sum(mark) "Total Mark" from M_mark,Student where Student.studentcode=
M_mark.studentcode group by studentname;
+-------------+------------+
| studentname | Total Mark |
+-------------+------------+
| Amitha | 350 |
| vaidehi | 523 |
| Varun | 238 |
| Turner | 50 |
| Vani | 126 |
+-------------+------------+
5 rows in set (0.02 sec)
c) Display the subject, average mark for each subject.
mysql> select subjectname,round(avg(mark),2) "Average mark" from Subject,M_mark where
Subject.subjectcode= M_mark.subjectcode group by subjectname;
+-------------+--------------+
| subjectname | Average mark |
+-------------+--------------+
| Maths | 50.42 |
| FSA | 57.60 |
| DBMS | 54.80 |
| OS | 37.88 |
| DC | 51.67 |
| DBMS LAB | 67.20 |
+-------------+--------------+
6 rows in set (0.02 sec)
d) Display the name of subjects for which at least one student got below 40%.
mysql> select subject.subjectname,count(student.studentname)"NO: OF STUDENTS" from
subject,m_mark,student where student.studentcode= m_mark.studentcode and m_mark.mark<(40*
maxmark)/100 and subject.SubjectCode=m_mark.Subjectcode group by subject. Subjectname having
count(distinct(m_mark.subjectcode))>=1;
+-------------+-----------------+
| subjectname | NO: OF STUDENTS |
+-------------+-----------------+
| DBMS LAB | 3|
| DC | 3|
| Maths | 3|
| OS | 1|
+-------------+-----------------+
4 rows in set (0.01 sec)
e) Display the name, subject and percentage of mark who got below 40 %.
mysql> select studentname,subjectname,mark,maxmark,round((m_mark.mark/maxmark)*100,2)"Percentage"
from subject, student, m_mark where mark<(40*maxmark/100) and subject.SubjectCode = m_mark.
subjectcode and student.studentcode =m_mark.studentcode;
+-------------+-------------+------+---------+------------+
| studentname | subjectname | mark | maxmark | Percentage |
+-------------+-------------+------+---------+------------+
| Amitha | Maths | 40 | 150 | 26.67 |
| Amitha | DC | 40 | 200 | 20.00 |
| Amitha | DBMS LAB | 70 | 1001 | 6.99 |
| vaidehi | DC | 74 | 200 | 37.00 |
| vaidehi | DBMS LAB | 98 | 1001 | 9.79 |
| Varun | Maths | 40 | 150 | 26.67 |
| Varun | DC | 40 | 200 | 20.00 |
| Varun | DBMS LAB | 35 | 1001 | 3.50 |
| Turner | Maths | 50 | 150 | 33.33 |
| Vani | OS | 23 | 75 | 30.67 |
+-------------+-------------+------+---------+------------+
10 rows in set (0.00 sec)
f) Display the faculties and allotted subjects for each faculty.
mysql> select Faculty.f_name,Subject.subjectname from Faculty,Subject where
Faculty.F_code=Subject.faculty_code;
+------------+-------------+
| f_name | subjectname |
+------------+-------------+
| John Smith | Maths |
| Bindu | FSA |
| Vidhya | OS |
| Vidhya | DBMS LAB |
| Sangeethe | DC |
| Jaya Kumar | DBMS |
| Jaya Kumar | Database |
+------------+-------------+
7 rows in set (0.00 sec)
g) Display the name of faculties who take more than one subject.
mysql> Select f_name name from Faculty where (select count(subjectcode) from Subject where
Subject.faculty_code=Faculty.f_code)>1 group by Faculty.f_name;
+------------+
| name |
+------------+
| Vidhya |
| Jaya Kumar |
+------------+
2 rows in set (0.00 sec)
h) Display name, subject, mark, % of mark in ascending order of mark.
mysql> select studentname,subjectname,mark from Student,Subject,M_mark where
Student.studentcode=M_mark.studentcode and Subject.subjectcode=M_mark.subjectcode order by mark;
+-------------+-------------+------+
| studentname | subjectname | mark |
+-------------+-------------+------+
| Vani | OS | 23 |
| Varun | DBMS LAB | 35 |
| Amitha | Maths | 40 |
| Amitha | DC | 40 |
| Varun | Maths | 40 |
| Varun | DBMS | 40 |
| Varun | OS | 40 |
| Varun | DC | 40 |
| Varun | FSA | 43 |
| Vani | FSA | 43 |
| Amitha | DBMS | 50 |
| Turner | Maths | 50 |
| Vani | Maths | 60 |
| Amitha | FSA | 70 |
| Amitha | DBMS LAB | 70 |
| vaidehi | DC | 74 |
| vaidehi | DBMS | 77 |
| Amitha | OS | 80 |
| vaidehi | FSA | 89 |
| vaidehi | Maths | 90 |
| vaidehi | OS | 95 |
| vaidehi | DBMS LAB | 98 |
+-------------+-------------+------+
22 rows in set (0.00 sec)

RESULT
Query has run successfully and result is obtained.
Experiment No: 7
Implementation of Order By, Group By & Having clause
AIM
Create a database sales with the table with the following fields
sales (sale_id, customer_name, product, quantity, price, sale_date)
1. List all sales, ordered by sale date from newest to oldest.
2. Show the total quantity of items bought by each customer.
3. How many times did each customer buy each product?
4. List customers who bought more than 2 items in total.
5. Show total spending by each customer (price × quantity). List only those who spent more than Rs.500,
sorted from highest to lowest.

Queries:

CREATE TABLE sales (sale_id INT PRIMARY KEY, customer_name VARCHAR(50),product


VARCHAR(50),quantity INT,price DECIMAL(10, 2),sale_date DATE);

INSERT INTO sales VALUES


(1, 'Alice', 'Laptop', 1, 1000.00, '2025-07-01'),
(2, 'Bob', 'Tablet', 2, 300.00, '2025-07-01'),
(3, 'Alice', 'Laptop', 1, 1000.00, '2025-07-02'),
(4, 'Charlie', 'Phone', 3, 200.00, '2025-07-03'),
(5, 'Bob', 'Laptop', 1, 1000.00, '2025-07-04'),
(6, 'Alice', 'Phone', 2, 200.00, '2025-07-04'),
(7, 'David', 'Tablet', 1, 300.00, '2025-07-05');

1. List all sales, ordered by sale date from newest to oldest.


SELECT * FROM sales ORDER BY sale_date DESC;
2. Show the total quantity of items bought by each customer.
SELECT customer_name, SUM(quantity) AS total_items FROM sales GROUP BY customer_name;
3. How many times did each customer buy each product?
SELECT customer_name, product, COUNT(*) AS purchase_count FROM sales GROUP BY
customer_name, product;
4. List customers who bought more than 2 items in total.
SELECT customer_name, SUM(quantity) AS total_items FROM sales GROUP BY customer_name
HAVING SUM(quantity) > 2;
5. Show total spending by each customer (price × quantity). List only those who spent more than Rs.500,
sorted from highest to lowest.
SELECT customer_name, SUM(price * quantity) AS total_spent FROM sales GROUP BY customer_name
HAVING SUM(price * quantity) > 500 ORDER BY total_spent DESC;
OUTPUT:

mysql> create database sales;


Query OK, 1 row affected (0.11 sec)

mysql> use sales;


Database changed
mysql> CREATE TABLE sales (sale_id INT PRIMARY KEY, customer_name VARCHAR(50),product
VARCHAR(50),quantity INT,price DECIMAL(10, 2),sale_date DATE);
Query OK, 0 rows affected (0.25 sec)

mysql> desc sales;


+---------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------------+------+-----+---------+-------+
| sale_id | int | NO | PRI | NULL | |
| customer_name | varchar(50) | YES | | NULL | |
| product | varchar(50) | YES | | NULL | |
| quantity | int | YES | | NULL | |
| price | decimal(10,2) | YES | | NULL | |
| sale_date | date | YES | | NULL | |
+---------------+---------------+------+-----+---------+-------+
6 rows in set (0.07 sec)

mysql> INSERT INTO sales VALUES


-> (1, 'Alice', 'Laptop', 1, 1000.00, '2025-07-01'),
-> (2, 'Bob', 'Tablet', 2, 300.00, '2025-07-01'),
-> (3, 'Alice', 'Laptop', 1, 1000.00, '2025-07-02'),
-> (4, 'Charlie', 'Phone', 3, 200.00, '2025-07-03'),
-> (5, 'Bob', 'Laptop', 1, 1000.00, '2025-07-04'),
-> (6, 'Alice', 'Phone', 2, 200.00, '2025-07-04'),
-> (7, 'David', 'Tablet', 1, 300.00, '2025-07-05');
Query OK, 7 rows affected (0.03 sec)
Records: 7 Duplicates: 0 Warnings: 0

mysql> select * from sales;


+---------+---------------+---------+----------+---------+------------+
| sale_id | customer_name | product | quantity | price | sale_date |
+---------+---------------+---------+----------+---------+------------+
| 1 | Alice | Laptop | 1 | 1000.00 | 2025-07-01 |
| 2 | Bob | Tablet | 2 | 300.00 | 2025-07-01 |
| 3 | Alice | Laptop | 1 | 1000.00 | 2025-07-02 |
| 4 | Charlie | Phone | 3 | 200.00 | 2025-07-03 |
| 5 | Bob | Laptop | 1 | 1000.00 | 2025-07-04 |
| 6 | Alice | Phone | 2 | 200.00 | 2025-07-04 |
| 7 | David | Tablet | 1 | 300.00 | 2025-07-05 |
+---------+---------------+---------+----------+---------+------------+
7 rows in set (0.00 sec)

1. List all sales, ordered by sale date from newest to oldest.


mysql> SELECT * FROM sales ORDER BY sale_date DESC;
+---------+---------------+---------+----------+---------+------------+
| sale_id | customer_name | product | quantity | price | sale_date |
+---------+---------------+---------+----------+---------+------------+
| 7 | David | Tablet | 1 | 300.00 | 2025-07-05 |
| 5 | Bob | Laptop | 1 | 1000.00 | 2025-07-04 |
| 6 | Alice | Phone | 2 | 200.00 | 2025-07-04 |
| 4 | Charlie | Phone | 3 | 200.00 | 2025-07-03 |
| 3 | Alice | Laptop | 1 | 1000.00 | 2025-07-02 |
| 1 | Alice | Laptop | 1 | 1000.00 | 2025-07-01 |
| 2 | Bob | Tablet | 2 | 300.00 | 2025-07-01 |
+---------+---------------+---------+----------+---------+------------+
7 rows in set (0.00 sec)
2. Show the total quantity of items bought by each customer.
mysql> SELECT customer_name, SUM(quantity) AS total_items FROM sales GROUP BY
customer_name;
+---------------+-------------+
| customer_name | total_items |
+---------------+-------------+
| Alice | 4|
| Bob | 3|
| Charlie | 3|
| David | 1|
+---------------+-------------+
4 rows in set (0.01 sec)
3. How many times did each customer buy each product?
mysql> SELECT customer_name, product, COUNT(*) AS purchase_count FROM sales GROUP BY
customer_name, product;
+---------------+---------+----------------+
| customer_name | product | purchase_count |
+---------------+---------+----------------+
| Alice | Laptop | 2|
| Bob | Tablet | 1|
| Charlie | Phone | 1|
| Bob | Laptop | 1|
| Alice | Phone | 1|
| David | Tablet | 1|
+---------------+---------+----------------+
6 rows in set (0.00 sec)
4. List customers who bought more than 2 items in total.
mysql> SELECT customer_name, SUM(quantity) AS total_items FROM sales GROUP BY
customer_name
-> HAVING SUM(quantity) > 2;
+---------------+-------------+
| customer_name | total_items |
+---------------+-------------+
| Alice | 4|
| Bob | 3|
| Charlie | 3|
+---------------+-------------+
3 rows in set (0.00 sec)
5. Show total spending by each customer (price × quantity). List only those who spent more than Rs.500,
sorted from highest to lowest.

mysql> SELECT customer_name, SUM(price * quantity) AS total_spent FROM sales GROUP BY


customer_name
-> HAVING SUM(price * quantity) > 500 ORDER BY total_spent DESC;
+---------------+-------------+
| customer_name | total_spent |
+---------------+-------------+
| Alice | 2400.00 |
| Bob | 1600.00 |
| Charlie | 600.00 |
+---------------+-------------+
3 rows in set (0.00 sec)

RESULT
Query has been executed successfully and result is obtained.
Experiment No: 8
Implementation of set operators nested queries, and join queries

AIM

Create a database Student with the tables


Students(student_id,name,department)
Courses(course_id,course_name,department)
Enrollments(student_id,course_id,grade)

1. List the names of students and course names that belong to the CSE department.
2. List the students who are in the CSE department but not in the ECE department.
3. Find the names of students who have taken the course "DBMS".
4. Find the names of students who scored an 'A' grade in any course.
5. List all students with the names of the courses they are enrolled in.
Queries:
CREATE TABLE students (student_id INT PRIMARY KEY,name VARCHAR(50),department
VARCHAR(50));

INSERT INTO students (student_id, name, department) VALUES (1, 'Alice', 'CSE'),(2, 'Bob', 'ECE'),
(3, 'Charlie', 'CSE'),(4, 'David', 'MECH');

CREATE TABLE courses (course_id INT PRIMARY KEY, course_name VARCHAR(50),department


VARCHAR(50));

INSERT INTO courses (course_id, course_name, department) VALUES(101, 'DBMS', 'CSE'),


(102, 'Circuits', 'ECE'),(103, 'Thermodynamics', 'MECH');

CREATE TABLE enrollments (student_id INT,course_id INT,grade CHAR(1),PRIMARY KEY


(student_id, course_id),FOREIGN KEY (student_id) REFERENCES students(student_id),FOREIGN KEY
(course_id) REFERENCES courses(course_id));

INSERT INTO enrollments (student_id, course_id, grade) VALUES(1, 101, 'A'),(2, 102, 'B'),
(3, 101, 'B'),(4, 103, 'A');

1. List the names of students and course names that belong to the CSE department.
SELECT name AS name_or_course FROM students WHERE department = 'CSE' UNION
SELECT course_name FROM courses WHERE department = 'CSE';
2. List the students who are in the CSE department but not in the ECE department.
SELECT name FROM students WHERE department = 'CSE' EXCEPT SELECT name FROM students
WHERE department = 'ECE';
3. Find the names of students who have taken the course "DBMS".
SELECT name FROM students WHERE student_id IN (SELECT student_id FROM enrollments
WHERE course_id = (SELECT course_id FROM courses WHERE course_name = 'DBMS'));
4. Find the names of students who scored an 'A' grade in any course.
SELECT name FROM students WHERE student_id IN (SELECT student_id FROM enrollments
WHERE grade = 'A');
5. List all students with the names of the courses they are enrolled in.
SELECT s.name, c.course_name FROM students s JOIN enrollments e ON s.student_id = e.student_id
JOIN courses c ON e.course_id = c.course_id;

OUTPUT:
mysql> create database students;
Query OK, 1 row affected (0.03 sec)

mysql> use students;


Database changed
mysql> CREATE TABLE students (student_id INT PRIMARY KEY,name VARCHAR(50),department
VARCHAR(50));
Query OK, 0 rows affected (0.12 sec)

mysql> INSERT INTO students (student_id, name, department) VALUES (1, 'Alice', 'CSE'),(2, 'Bob',
'ECE'),
-> (3, 'Charlie', 'CSE'),(4, 'David', 'MECH');
Query OK, 4 rows affected (0.02 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql>
mysql> CREATE TABLE courses (course_id INT PRIMARY KEY, course_name
VARCHAR(50),department VARCHAR(50));
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO courses (course_id, course_name, department) VALUES(101, 'DBMS', 'CSE'),
-> (102, 'Circuits', 'ECE'),(103, 'Thermodynamics', 'MECH');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> CREATE TABLE enrollments (student_id INT,course_id INT,grade CHAR(1),PRIMARY KEY


(student_id, course_id),FOREIGN KEY (student_id) REFERENCES students(student_id),FOREIGN KEY
(course_id) REFERENCES courses(course_id));
Query OK, 0 rows affected (0.13 sec)

mysql> INSERT INTO enrollments (student_id, course_id, grade) VALUES(1, 101, 'A'),(2, 102, 'B'),
-> (3, 101, 'B'),(4, 103, 'A');
Query OK, 4 rows affected (0.02 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> select * from students;


+------------+---------+------------+
| student_id | name | department |
+------------+---------+------------+
| 1 | Alice | CSE |
| 2 | Bob | ECE |
| 3 | Charlie | CSE |
| 4 | David | MECH |
+------------+---------+------------+
4 rows in set (0.01 sec)

mysql> select * from courses;


+-----------+----------------+------------+
| course_id | course_name | department |
+-----------+----------------+------------+
| 101 | DBMS | CSE |
| 102 | Circuits | ECE |
| 103 | Thermodynamics | MECH |
+-----------+----------------+------------+
3 rows in set (0.01 sec)

mysql> select * from enrollments;


+------------+-----------+-------+
| student_id | course_id | grade |
+------------+-----------+-------+
| 1| 101 | A |
| 2| 102 | B |
| 3| 101 | B |
| 4| 103 | A |
+------------+-----------+-------+
4 rows in set (0.00 sec)

1. List the names of students and course names that belong to the CSE department.
mysql> SELECT name AS name_or_course FROM students WHERE department = 'CSE' UNION
-> SELECT course_name FROM courses WHERE department = 'CSE';
+----------------+
| name_or_course |
+----------------+
| Alice |
| Charlie |
| DBMS |
+----------------+
3 rows in set (0.01 sec)
2. List the students who are in the CSE department but not in the ECE department.
mysql> SELECT name FROM students WHERE department = 'CSE' EXCEPT SELECT name FROM
students WHERE department = 'ECE';
+---------+
| name |
+---------+
| Alice |
| Charlie |
+---------+
2 rows in set (0.00 sec)
3. Find the names of students who have taken the course "DBMS".
mysql> SELECT name FROM students WHERE student_id IN (SELECT student_id FROM
enrollments
-> WHERE course_id = (SELECT course_id FROM courses WHERE course_name = 'DBMS'));
+---------+
| name |
+---------+
| Alice |
| Charlie |
+---------+
2 rows in set (0.01 sec)
4. Find the names of students who scored an 'A' grade in any course.
mysql> SELECT name FROM students WHERE student_id IN (SELECT student_id FROM
enrollments WHERE grade = 'A');
+-------+
| name |
+-------+
| Alice |
| David |
+-------+
2 rows in set (0.01 sec)
5. List all students with the names of the courses they are enrolled in.
mysql> SELECT s.name, c.course_name FROM students s JOIN enrollments e ON s.student_id =
e.student_id
-> JOIN courses c ON e.course_id = c.course_id;
+---------+----------------+
| name | course_name |
+---------+----------------+
| Alice | DBMS |
| Charlie | DBMS |
| Bob | Circuits |
| David | Thermodynamics |
+---------+----------------+
4 rows in set (0.00 sec)

RESULT
Query has been executed successfully and result is obtained.
Experiment No: 9
Practice of SQL TCL commands like Rollback, Commit, Savepoint

AIM
TRANSATIONAL CONTROL LANGUAGE (T.C.L):
A transaction is a logical unit of work. All changes made to the database can be referred to as a
transaction. Transaction changes can be mode permanent to the database only if they are committed a transaction
begins with an executable SQL statement & ends explicitly with either roll back or commit statement.
COMMIT:
This command is used to end a transaction only with the help of the commit command transaction
changes can be made permanent to the database.
Syntax: SQL>COMMIT;
Example: SQL>COMMIT;
SAVE POINT:
Save points are like marks to divide a very lengthy transaction to smaller once. They are used to identify
a point in a transaction to which we can latter role back. Thus, save point is used in conjunction with roll back.
Syntax: SQL>SAVE POINT ID;
Example: SQL>SAVE POINT xyz;
ROLL BACK:
A roll back command is used to undo the current transactions. We can roll back the entire transaction so
that all changes made by SQL statements are undo (or) role back a transaction to a save point so that the SQL
statements after the save point are roll back.
Syntax:
ROLE BACK(current transaction can be roll back)
ROLE BACK to save point ID;
Example:
SQL>ROLE BACK;
SQL>ROLE BACK TO SAVE POINT xyz;

• COMMIT – Saves the changes.


• ROLLBACK – Undoes changes.
• SAVEPOINT – Sets a point in a transaction to which you can later roll back.

Commands:

CREATE TABLE employees1 (id INT PRIMARY KEY, name VARCHAR(100),salary INT);

START TRANSACTION;
→ Insert some rows
INSERT INTO employees VALUES (1, 'Alice', 50000);
INSERT INTO employees VALUES (2, 'Bob', 55000);

→ Create a savepoint
SAVEPOINT sp1;

→ Insert more data


INSERT INTO employees VALUES (3, 'Charlie', 60000);

→ Rollback to savepoint (this undoes Charlie's insert)


ROLLBACK TO sp1;

→ Commit remaining changes (Alice and Bob)


COMMIT;

OUTPUT:

mysql> CREATE TABLE employees1 (id INT PRIMARY KEY, name VARCHAR(100),salary INT);
Query OK, 0 rows affected (0.07 sec)

mysql>
mysql> desc employees1;
+--------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(100) | YES | | NULL | |
| salary | int | YES | | NULL | |
+--------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> START TRANSACTION;


Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO employees1 VALUES (2, 'Bob', 55000);


Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO employees1 VALUES (1, 'Alice', 50000);


Query OK, 1 row affected (0.00 sec)

mysql> select * from employees1;


+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Alice | 50000 |
| 2 | Bob | 55000 |
+----+-------+--------+
2 rows in set (0.00 sec)

mysql> SAVEPOINT sp1;


Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO employees1 VALUES (3, 'Charlie', 60000);
Query OK, 1 row affected (0.00 sec)

mysql> select * from employees1;


+----+---------+--------+
| id | name | salary |
+----+---------+--------+
| 1 | Alice | 50000 |
| 2 | Bob | 55000 |
| 3 | Charlie | 60000 |
+----+---------+--------+
3 rows in set (0.00 sec)

mysql> ROLLBACK TO sp1;


Query OK, 0 rows affected (0.00 sec)

mysql> select * from employees1;


+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Alice | 50000 |
| 2 | Bob | 55000 |
+----+-------+--------+
2 rows in set (0.00 sec)

mysql> COMMIT;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from employees1;
+----+-------+--------+
| id | name | salary |
+----+-------+--------+
| 1 | Alice | 50000 |
| 2 | Bob | 55000 |
+----+-------+--------+
2 rows in set (0.00 sec)
RESULT
Query has been executed successfully and result is obtained.

You might also like