DBMS Lab Workbook for CSE Students
DBMS Lab Workbook for CSE Students
(AUTONOMOUS)
II year II Sem (AR18)
Database Management Systems
Laboratory Work Book
(18CS22L3)
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
(2020-2021)
CERTIFICATE
This is to certify that Mr./ Miss
has satisfactorily completed number of programs in the Database
Management Systems Laboratory.
Faculty In-charge
HoD-CSE
List of Programs
S.No. Name of the Program Page no
1 E-R Model: Analyze the problem with the entities which identify data 8
persisted in the database which contains entities, attributes.
2 Concept design with E-R Model: Apply cardinalities for each 13
relationship; identify strong entities and weak entities for relationships
like generalization, aggregation, specialization.
3 Relation Model: Represent attributes as columns in tables and different 18
types of attributes like Composite, Multi-valued, and Derived. Apply
Normalization.
4 Installation of Mysql and Queries using DATA DEFINITION 24
LANGUAGE (DDL) Commands: Create, Alter, Drop, Truncate
5 Data Manipulation Language (DML) COMMANDS: SELECT, 36
INSERT, UPDATE, DELETE
6 Data Control Language (DCL): GRANT, REVOKE 41
Transaction Control Language (TCL) COMMANDS : COMMIT,
ROLL BACK SAVE POINT
7 In Built Functions: - DATE FUNCTION, NUMERICAL FUNCTIONS, 46
CHARACTER FUNCTIONS, CONVERSION FUNCTION
8 Querying Queries using ANY 60
9 Querying: Using aggregate functions COUNT, SUM using 65
GROUPBY and HAVING
a. Using aggregate functions AVERAGE
b. using GROUPBY and HAVING
10 Querying: NESTED QUERIES AND JOIN QUERIES: Nested Queries , 77
Correlated sub queries , Simple Join, a) Equi-join b) Non Equi-join , Self
join , Outer Join
11 Set Operators: Union 91
12 Views: Creating and dropping view 99
13 Triggers: Creation of INSERT TRIGGER, DELETE TRIGGER, 103
UPDATE TRIGGER
14 Procedures: Creation, Execution and Modification of stored Procedure 118
15 Additional Queries 125
PROGRAM OUTCOMES
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions : Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
12. Life-long learning : Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Course Objectives
Develop ability to
1. Learn and practice data modeling using entity-relationship and develop database design.
2. Understand the features of database management systems and Relational database.
3. Understand Structured Query Language (SQL) and learn SQL syntax.
4. Understand normalization process of a logical data model and correct any anomalies.
5. Understand needs of database processing and learn techniques for controlling the
consequences of concurrent data access.
Course Outcomes
After completion of the course, student would be able to
18CS22L3.1. Design and describe data models and schemas in DBMS.
18CS22L3.2. Use SQL- the standard language of relational databases, for database processing.
18CS22L3.3. Resolve redundant and functional dependencies, design a normalized database.
18CS22L3.4. Implement Transaction and Query processing techniques for data storage and retrieval.
18CS22L3.5. Choose appropriate file and page organizations, implement indexing methods including
B-tree, and hashing.
Prerequisites:
18CS1201 – ADVANCED DATA STRUCTURES
INDEX
S. Name of the Program Date of Date of Marks Signature Remarks
No Ex. Submission
WEEK 1 Date:
E-R Model
Analyze the problem with the entities which identify data persisted in the database which
contains entities and attributes.
Objectives:
Student will be able to learn the Entity-Relationship(ER) modeling to develop a conceptual
model of data.
Outcomes:
Student gains the ability to
• Know the business rules, notations and constructs.
• To Construct E-R diagrams including: Entities , Attributes , Relationships
E-R Model:
• Entity: Real-world objects distinguishable from other objects. An entity is described using
a set of attributes.
• An attribute is a characteristic. In a database management system (DBMS),
an attribute refers to a database component, such a table. It also may refer to
a database field. Attributes describe the instances in the row of a database.
• Entity Set: A collection of similar entities. E.g., all employees.
– All entities in an entity set have the same set of attributes.
– Each entity set has a key.
– Each attribute has a domain.
• Relationship: Association among two or more
entities. E.g., Anil works in Pharmacy department.
• Relationship Set: Collection of similar relationships.
– An n-ary relationship set R relates n entity sets E1 ... En; each relationship in R involves
entities e1 < E1, ..., en < En
– Same entity set could participate in different relationship sets, or in different “roles” in
same set.
Identify the Entities and their attributes for Library Management Systems:
Identify the Entities and their attributes for Hospital Management Systems:
.
Identify the Entities and their attributes for University Management Systems:
VIVA QUESTIONS
Work space:
WEEK 2 : Date:
Concept design with E-R Model. Apply cardinalities for each relationship. Identify strong
entities and weak entities for relationships like generalization, aggregation, specialization.
Objectives:
Student will be able to learn data structures in terms of entity types, relationship types and
attributes or classes, associations and attributes.
Outcomes:
Student gains the ability to describe the data requirements for a new information system in a
direct and easy to understand graphical notation.
The overall logical structure of a database can be expressed graphically by an E-R diagram,
which is built up from the following components.
• Rectangles, which represent entity sets
• Ellipse, which represent attributes
• Diamonds, which represent relationship sets
• Lines, which link attributes to entity sets and entity sets to relationship sets
• Double ellipses, which represent multi-valued attributes
• Double lines, which indicate total participation of an entity in a relationship
set For example in Fig 2.1. An employee Entity set with three attributes
Patients are treated in a single ward by the doctors assigned to them. Each patient will be
treated by a single doctor. Healthcare assistants also attend to the patients, a number of
these are associated with each ward. Patient undergoes various tests. Accounts
department manages patient treatment bill and staff payment. Some staff is paid part time
and doctors and care assistants work varying amounts of overtime at varying rates
VIVA QUESTIONS
Work space:
WEEK 3 Date:
Relation Model represents attributes as columns in tables and different types of attributes
like composite, Multi-valued and Derived.
Objectives:
Student will be able to learn the structural components of the relational data model.
Student will be able to learn to map ER models into relational models.
Outcomes:
Student gains the ability
• To describe the Model Structure.
• To define Properties of Relations.
• To define Domains.
• To implement Notation to Describe the Relational Schema
• To Represent an ER Model as a Relational Model.
1) Represent all the entities in tabular fashion. Represent attributes as columns in tables.
Library Management systems:
Entities
Book
authno isbn number title edition category price
Reader
UserId Email address Phone_no name
Publisher
PublisherId Year of publication name
Authentication System
LoginId password
Reports
UserId Reg_no Book_no Issue/Return date
Staff
staff_id name
Relationship Set
Reserve/Return
Reserve date Due date Return date
Relational Model:
Entities
Relationships
VIVA QUESTIONS
1 Andrew 6615927284 10
2 Sara 6583654865 20
3 Harry 4647567463 10
• <SUBJECT>
10 DBMS Korth
20 Algorithms Cormen
30 Algorithms Leiserson
• <ENROLL>
Student_Number Subject_Number
1 10
2 20
3 10
• {Student_Number}
• {Student_Phone}
• {Student_Number,Student_Name}
Geethanjali College of Engineering Page 22
Database Management Systems Lab Dept. of CSE.
• {Student_Number,Student_Phone}
• {Student_Number,Subject_Number}
• {Student_Phone,Student_Name}
• {Student_Phone,Subject_Number}
• {Student_Number,Student_Name,Student_Phone}
• {Student_Number,Student_Phone,Subject_Number}
• {Student_Number,Student_Name,Subject_Number}
• {Student_Phone,Student_Name,Subject_Number}
• {Subject_Number}
• {Subject_Number,Subject_Name}
• {Subject_Number,Subject_Instructor}
• {Subject_Number,Subject_Name,Subject_Instructor}
• {Subject_Name,Subject_Instructor}
• {Student_Number,Subject_Number}
WEEK 4 Date:
INSTALLATION OF MYSQL and Practicing DDL commands
Objectives:
Student will be able to learn DDL Statements to Create and Manage Tables.
Outcomes:
Student gains the ability to
• Categorize the main database objects
• Review the table structure
• List the data types that are available for columns
• Create a simple table
• Describe how constraints are created at the time of table creation
• Describe how schema objects work.
Installation of My SQL:
The latest and stable version of MySQL package is 5.7. It brings many security fixes and
performance enhancements. And we recommend to use it for your deployments.
So the first step is to get the MySQL community installer for the Windows platform. The latest
version of the MySQL community package is 5.7.17 which comprises the following
components.
1. MySQL Connectors – A set of programmable modules for C, C++, C# APIs, and ODBC. It
helps developing applications using MySQL database.
2. MySQL Workbench – A visual tool for DBA, Software Architects, and Web Developers. It
features data modeling, SQL builder, server/user management, and database backup.
3. MySQL Notifier – A service that resides in the system’s tray which lets you watch over the
status of any local or remote MySQL instance.
4. MySQL for Excel – An Excel Add-on to help users explore MySQL schemas, tables, views,
and stored procedures.
5. MySQL Server – It is the relational database management system (RDBMS) which uses
SQL for adding, accessing, and managing content in a database.
Other notable features which you’ll find in the MySQL package are as follows:
After downloading the MySQL community edition, double-click the installer file to begin the
installation process. It’ll launch the installer window.
Subsequently, follow the below steps. Take help from the snapshots attached. Make sure to
edit or select the option, as shown in the picture.
Step-1.
Step-2.
Check Requirements.
Step-3.
Begin Installation.
Geethanjali College of Engineering Page 26
Database Management Systems Lab Dept. of CSE.
Step-4.
Installation Status.
Step-5.
Step-6.
Edit Configuration.
Step-7.
Step-8.
You’ve completed the MySQL installation on your Windows system. Now, you can perform
the following tasks.
Geethanjali College of Engineering Page 29
Database Management Systems Lab Dept. of CSE.
You can access the MySQL CLI from the <All Programs> section inside the Windows start
menu. See the attached screenshot and open the 2nd CLI option as shown on the screen.
DDL COMMANDS:
1) CREATE
2) ALTER
3) DROP
4) TRUNCATE
5) RENAME
CREATE :-
--------:- It is used to create the database objects into the database.
Syntax:-
-------:-
create table table_name(col_name1 datatype(size),col_name2 datatype(size),col_name3
datatype(size));
ex:-
----:-
mysql> create table student(st_id int, st_name varchar(10),st_dob date, st_addr varchar(10));
Query OK, 0 rows affected (0.74 sec)
desc:-
-----:- It is for description and it is used to view the structure of the existing table.
Syntax:-
-------:- desc table_name;
ex:-
---:-
ALTER:-
-------:- It is used to modify the structure of the existing tables.
Syntax:-
------:-
alter table table_name add col_name datatype(size);
ex:-
----:-
mysql> alter table student add st_mobile_number int(10);
Query OK, 0 rows affected, 1 warning (0.59 sec)
Records: 0 Duplicates: 0 Warnings: 1
Syntax:-
--------:-
alter table table_name rename column old_col_name to new_col_name;
ex:-
---:-
mysql> alter table student rename column st_mobile_number to st_mobile;
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
ex:-
----:-
mysql> alter table student drop st_mobile;
Query OK, 0 rows affected (2.10 sec)
Records: 0 Duplicates: 0 Warnings: 0
DROP:-
-----:- It is used to remove the database objects in database.
Syntax:-
-------:-
drop table table_name;
ex:-
---:-
mysql> drop table medicine;
Query OK, 0 rows affected (0.70 sec)
TRUNCATE:-
-----------:-
It is used to remove the data permanently from the table.
Syntax:-
------:-
truncate table table_name;
ex:-
---:-
mysql> truncate table student;
Query OK, 0 rows affected (1.63 sec)
RENAME:-
-------:- It is used to change the table name from old table name to new table name.
Syntax:-
-------:-
rename table old_table_name to new_table_name;
ex:-
---:-
mysql> rename table student to student_1;
Query OK, 0 rows affected (0.72 sec)
VIVA QUESTIONS
1. Write the syntax for all DDL commands?
Create :-
Syntax:- create table table_name(col_name1 datatype(size),col_name2
datatype(size),col_name3 datatype(size));
Alter:-
Syntax:- alter table table_name add col_name datatype(size);
Drop:-
Syntax:- drop table table_name;
Truncate:-
Syntax:- truncate table table_name;
Rename:-
Syntax:-rename table old_table_name to new_table_name;
Work space:
WEEK 5 Date:
Practicing DML commands
Objectives:
Student will be able to learn commands that make changes in relational database and transaction
management.
Outcomes:
Student gains the knowledge to perform transactions like updating, deleting, inserting and
selecting data from a data base.
INSERT:-
---------:- It is used to insert the data into the tables.
Syntax:-
-------:-
insert into table_name(col_name1,col_name2,col_name3) values(val1,val2,val3);
Ex:-
----:-
UPDATE:-
-------:-
It is used to modify the data into existing table.
Syntax:-
--------:-
update table_name set col_name=value where <condition>;
Ex:-
---:-
DELETE:-
-------:-
It is used to remove the data temporarily from the table.
Syntax:-
--------:-
delete from table_name where <condition>;
Geethanjali College of Engineering Page 37
Database Management Systems Lab Dept. of CSE.
ex:-
---:-
mysql> select * from student;
+-------+---------+------------+---------+
| st_id | st_name | st_dob | st_addr |
+-------+---------+------------+---------+
| 1 | AAA | 2021-01-01 | HYD |
| 2 | BBB | 2021-02-01 | SEC |
| 3 | DDD | 2021-03-01 | HYT |
+-------+---------+------------+---------+
3 rows in set (0.00 sec)
DRL:-
----:- Data Retrieve Language:-
The DRL command is "select" statement.
SELECT:-
-------:- It is used to retrieve or access the data from the table.
Syntax:-
-------:-
select */col_list from table_name where <condition>;
ex:-
---:-
mysql> select * from emp;
+-------+--------+-----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
Geethanjali College of Engineering Page 38
Database Management Systems Lab Dept. of CSE.
VIVA QUESTIONS
3. What is the difference between NULL Values and NOT NULL Values?
NULL means that database columns can hold NULL values. NOT NULL means a column
does not accept NULL values.
Work space:
WEEK 6 : Date:
The DCL language is used for controlling the access to the table and hence securing the
database. DCL is used to provide certain privileges to a particular user. Privileges are rights to
be allocated. The privilege commands are namely, Grant and Revoke. The various privileges
that can be granted or revoked are, Select Insert Delete Update References Execute All.
GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user
can grant access to their database objects to other users.
REVOKE COMMAND: Using this command, the DBA can revoke the granted database
privileges from the user.
TCL COMMAND
COMMIT: command is used to save the Records.
Queries:
Tables Used: Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES”
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
Query:
Q2: Develop a query to grant some privileges of employees table into departments table
Query:
Q3: Develop a query to revoke all privileges of employees table from departments table
Query:
mysql> REVOKE ALL ON emp FROM 'root'@'localhost';
Query OK, 0 rows affected (0.10 sec)
Q4: Develop a query to revoke some privileges of employees table from departments table
Query:
Query:
VIVA QUESTIONS
Work space:
WEEK 7: Date:
In Built Functions: - DATE FUNCTION, NUMERICAL FUNCTIONS, CHARACTER
FUNCTIONS, CONVERSION FUNCTION
SQL Functions:-
----------------:-
Function:-
----------:- It accepts one or more arguments and it return single value.
The sql functions are,
* single row functions
* multiple row functions or aggregate group functions
* general functions
CHARACTER/STRING FUNCTIONS:
lower():-
----------:- It has one expression and it returns small characters.
ex:-
---:-
mysql> select lower('MYSQL CORPORATION');
+----------------------------+
| lower('MYSQL CORPORATION') |
+----------------------------+
| mysql corporation |
+----------------------------+
1 row in set (0.04 sec)
Geethanjali College of Engineering Page 46
Database Management Systems Lab Dept. of CSE.
upper():-
--------:- It has one expression and it returns capital characters.
ex:-
---:-
concat():-
----------:- It has two expressions and it is used to concatenate the two strings.
ex:-
----:-
length():-
---------:-It has one expression and it is used to count the individual characters and it returns
number.
ex:-
-----:-
substr():-
---------:-It returns substr from the main strings and it returns characters.
ex:-
------:-
ex:-
-----:-
instr():-
---------:-It is used to find the position of a substring.
ex:-
----:-
mysql> select instr('mysql is a powerful database','powerful');
+--------------------------------------------------+
| instr('mysql is a powerful database','powerful') |
+--------------------------------------------------+
| 12 |
+--------------------------------------------------+
1 row in set (0.06 sec)
+--------------------------------------------------+
| instr('mysql is a powerful database','database') |
+--------------------------------------------------+
| 21 |
+--------------------------------------------------+
1 row in set (0.00 sec)
Lpad():-
-------:-
It has three expressions and it returns characters.
Lpad() in mysql is used to pad or add a string to the left side of the original string.
ex:-
----:-
Rpad():-
---------:- It has three expressions and it returns characters.
Rpad() in mysql is used to pad or add a string to the right side of the original string.
ex:-
----:-
+---------+------------+
| 800.00 | 800.00XXXX |
| 1600.00 | 1600.00XXX |
| 1250.00 | 1250.00XXX |
| 2975.00 | 2975.00XXX |
| 1250.00 | 1250.00XXX |
| 2850.00 | 2850.00XXX |
| 2450.00 | 2450.00XXX |
| 3000.00 | 3000.00XXX |
| 5000.00 | 5000.00XXX |
| 1500.00 | 1500.00XXX |
| 1100.00 | 1100.00XXX |
| 950.00 | 950.00XXXX |
| 3000.00 | 3000.00XXX |
| 1300.00 | 1300.00XXX |
+---------+------------+
14 rows in set (0.00 sec)
trim():-
--------:- It returns a string that has unwanted characters removed.
ex:-
----:-
replace():-
----------:- It has three expressions and it replaces the string by string.
ex:-
-----:-
mysql> select replace('mysqlcorp','corp','xyz');
+-----------------------------------+
| replace('mysqlcorp','corp','xyz') |
+-----------------------------------+
| mysqlxyz |
+-----------------------------------+
1 row in set (0.00 sec)
| replace('mysqlcorp','mys','xyz') |
+----------------------------------+
| xyzqlcorp |
+----------------------------------+
1 row in set (0.00 sec)
NUMBER FUNCTIONS:-
-----------------:- The number functions are,
* power()
* abs()
* mod()
* sqrt()
* round()
* greatest()
* least()
* ceil()
* floor()
power():-
--------:-
power() in mysql is used to find the value of a number raised to the power of another number.
ex:-
---:-
mysql> select power(10,3);
+-------------+
| power(10,3) |
+-------------+
| 1000 |
+-------------+
1 row in set (0.01 sec)
abs():-
-------:-It means absolute function, it has one expression and it always return positive value.
ex:-
------:-
mysql> select abs(10);
+---------+
| abs(10) |
+---------+
| 10 |
+---------+
1 row in set (0.00 sec)
| abs(-10) |
+----------+
| 10 |
+----------+
1 row in set (0.00 sec)
mod():-
------:-It has two expressions and it returns remainder value.
ex:-
-----:-
mysql> select mod(10,2);
+-----------+
| mod(10,2) |
+-----------+
| 0|
+-----------+
1 row in set (0.00 sec)
sqrt():-
--------:- It has one expression and it returns sqrt value.
ex:-
-----:-
mysql> select sqrt(15);
+-------------------+
| sqrt(15) |
+-------------------+
| 3.872983346207417 |
+-------------------+
1 row in set (0.00 sec)
round():-
-----------:-It returns roundfig value.
ex:-
---:-
| round(sqrt(15)) |
+-----------------+
| 4|
+-----------------+
1 row in set (0.04 sec)
greatest():-
-----------:- it has multiple expressions and it returns greatest value.
ex:-
----:-
least():-
----------:- It has multiple expressions and it returns least value.
ex:-
-----:-
mysql> select least(10,20,30,-50,-70);
+-------------------------+
| least(10,20,30,-50,-70) |
+-------------------------+
| -70 |
+-------------------------+
1 row in set (0.00 sec)
ceil():-
--------:- the ceil() function returns the smallest integer value that is bigger than or equal to a
number.
ex:-
---:-
floor():-
----------:- the floor() function returns the largest integer value that is smaller than or equal to a
number.
ex:-
----:-
mysql> select floor(25);
+-----------+
| floor(25) |
+-----------+
| 25 |
+-----------+
1 row in set (0.00 sec)
adddate():-
--------------:-It adds dates.
ex:-
---:-
mysql> select adddate('2021-01-01',20);
+--------------------------+
| adddate('2021-01-01',20) |
+--------------------------+
| 2021-01-21 |
+--------------------------+
1 row in set (0.05 sec)
addtime():-
---------:-It adds time.
ex:-
------:-
mysql> select addtime('2021-01-01 01:01:01','01:01:01');
+-------------------------------------------+
| addtime('2021-01-01 01:01:01','01:01:01') |
+-------------------------------------------+
| 2021-01-01 02:02:02 |
+-------------------------------------------+
1 row in set (0.04 sec)
curdate():-
------------:- It returns current date.
ex:-
----:-
mysql> select curdate();
+------------+
| curdate() |
+------------+
| 2021-06-02 |
+------------+
1 row in set (0.00 sec)
curtime():-
---------:- It returns current time.
ex:-
----:-
sysdate() or now():-
--------------------:- Both functions are used to returns system dates with time.
ex:-
----:-
mysql> select sysdate();
+---------------------+
| sysdate() |
+---------------------+
| 2021-06-02 15:09:02 |
+---------------------+
1 row in set (0.00 sec)
dayname():-
-----------:- It returns the name of the weekday for date.
ex:-
-----:-
last_day():-
-------------:- It has one expression and it returns last day of the month.
ex:-
----:-
+------------------------+
1 row in set (0.01 sec)
monthname():-
--------------:- It returns the full name of the month for date.
ex:-
-----:-
hour():-
------:- It returns hour for time.
ex:-
------:-
minute():-
------------:- It returns minute for time.
ex:-
-----:-
second():-
---------:- It returns second for time.
ex:-
----:-
CONVERT FUNCTION:-
----------------------:- Here we are using convert() function.
The convert() function is used for converting a value from one datatype to a different datatype.
ex:-
----:-
mysql> select convert(150,char);
+-------------------+
| convert(150,char) |
+-------------------+
| 150 |
+-------------------+
1 row in set (0.00 sec)
+--------------------------+
1 row in set (0.00 sec)
VIVA QUESTIONS
1. Differentiate between Ceil() and floor ()?
Ceil() is a function that returns the smallest integer value that is bigger than or equal to a
number while Floor() is a function that returns the largest integer value that is smaller than or
equal to a number.
Pratik 1996-09-26
Objectives:
Student will able to learn to operate on multiple result sets to return a single result set.
Student will able to learn to perform nested Queries.
Outcomes:
Student gains the knowledge to implement queries using ANY, ALL, IN, NOT IN.
IN:-
----:-
The in operator allows you to specify multiple values in a WHERE clause.
ex:-
---:-
mysql> select * from emp where sal in(select max(sal) from emp group by deptno);
+-------+-------+-----------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+-------+-----------+------+------------+---------+------+--------+
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
NOT IN:-
-------:-
The not in operator allows you to specify multiple values in a WHERE clause.
mysql> select * from emp where sal not in(select max(sal) from emp group by deptno);
+-------+--------+----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+----------+------+------------+---------+---------+--------+
10 rows in set (0.00 sec)
ANY:-
----:-
ANY means that the condition will be true if the operation is true for any of the values in the
Geethanjali College of Engineering Page 61
Database Management Systems Lab Dept. of CSE.
range.
ex:-
---:-
mysql> select * from emp where sal>any(select min(sal) from emp group by deptno);
+-------+--------+-----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+-----------+------+------------+---------+---------+--------+
13 rows in set (0.00 sec)
mysql> select * from emp where sal<any(select min(sal) from emp group by deptno);
+-------+--------+----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
+-------+--------+----------+------+------------+---------+---------+--------+
5 rows in set (0.00 sec)
Geethanjali College of Engineering Page 62
Database Management Systems Lab Dept. of CSE.
ALL:-
----
ALL means that the condition will be true only if the operation is true for all values in the range.
ex:-
----:-
mysql> select * from emp where sal>all(select min(sal) from emp group by deptno);
+-------+--------+-----------+------+------------+---------+--------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+--------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
+-------+--------+-----------+------+------------+---------+--------+--------+
8 rows in set (0.00 sec)
mysql> select * from emp where sal<all(select min(sal) from emp group by deptno);
Empty set (0.00 sec)
VIVA QUESTIONS
• WHERE Clause
• ORDER BY clause
• HAVING Clause
• TOP Clause
• GROUP BY Clause
Work space:
WEEK 9 : Date:
Querying Using Aggregate functions:
Objectives:
Student will able to learn to perform mathematical operations that return a single value,
calculated from values in a column.
Outcomes:
Student gains the knowledge to perform aggregate operations on the database appropriately.
Aggregate operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now consider
a powerful class of constructs for computing aggregate values such as MIN and SUM.
1. Count: COUNT following by a column name returns the count of tuple in that column. If
DISTINCT keyword is used then it will return only the count of unique tuple in the column.
Otherwise, it will return count of all the tuples (including duplicates) count (*) indicates all the
tuples of the column.
Syntax: COUNT (Column name)
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in that column.
Syntax: SUM (Column name)
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that column values.
Syntax: AVG (n1,n2..)
Example: Select AVG(10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
5. MIN: MIN followed by column name returns the minimum value of that column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
+-------------+
| 2073.214286 |
+-------------+
1 row in set (0.00 sec)
+----------+--------+
3 rows in set (0.00 sec)
| 3 | 10 |
| 5 | 20 |
| 6 | 30 |
+------------+--------+
3 rows in set (0.00 sec)
Order by():-
---------:- It is one of the clause and it is used to sorting the data either asc order or desc order.
This order by clause we can use last of the query.
For ascending order, we can use "asc" keyword
For descending order, we can use "desc" keyword
mysql> select min(sal),deptno from emp group by deptno order by deptno desc;
+----------+--------+
| min(sal) | deptno |
+----------+--------+
| 950.00 | 30 |
| 800.00 | 20 |
| 1300.00 | 10 |
+----------+--------+
3 rows in set (0.00 sec)
having():-
--------:-
It is one of the clause and it is used for conditions purpose in aggregate group functions.
mysql> select count(*),deptno from emp group by deptno having count(*)>=5 order by deptno
desc
-> ;
+----------+--------+
| count(*) | deptno |
+----------+--------+
Geethanjali College of Engineering Page 71
Database Management Systems Lab Dept. of CSE.
| 6 | 30 |
| 5 | 20 |
+----------+--------+
2 rows in set (0.00 sec)
General functions:-
------------------:-
* ifnull()
* case()
* nullif()
* isnull()
* version()
* database()
ifnull():-
-----------:-It has two expressions, if first expression is null it returns second expression or if first
expression is not null it returns first expression.
| NULL | 1.00 |
| 1400.00 | 1400.00 |
| NULL | 1.00 |
| NULL | 1.00 |
| NULL | 1.00 |
| NULL | 1.00 |
| 0.00 | 0.00 |
| NULL | 1.00 |
| NULL | 1.00 |
| NULL | 1.00 |
| NULL | 1.00 |
+---------+----------------+
14 rows in set (0.00 sec)
case():-
-------:-
It is used for elsif ladder purpose in mysql.
Syntax:-
--------:-
case col_name when <condition> then result when <condition> then result else result end;
ex:-
----:-
mysql> select job,sal,case job when upper('manager') then sal+1000
-> when upper('clerk') then sal-1000
-> else
-> sal+500
-> end as result from emp;
+-----------+---------+---------+
| job | sal | result |
+-----------+---------+---------+
| CLERK | 800.00 | -200.00 |
| SALESMAN | 1600.00 | 2100.00 |
| SALESMAN | 1250.00 | 1750.00 |
| MANAGER | 2975.00 | 3975.00 |
| SALESMAN | 1250.00 | 1750.00 |
Geethanjali College of Engineering Page 73
Database Management Systems Lab Dept. of CSE.
nullif():-
---------:- It has two parameters, if first parameter is equal to second parameter it returns null
value.If first parameter is not equal to second parameter it returns first parameter.
+----------------+
1 row in set (0.00 sec)
isnull():-
----------:- The isnull() function returns 1 or 0 depending on whether an expression is null. if
expression is null, this function returns 1 otherwise it returns 0.
ex:-
----:-
mysql> select isnull(null) ;
+--------------+
| isnull(null) |
+--------------+
| 1|
+--------------+
1 row in set (0.00 sec)
version():-
----------:-
It returns currrent version of the mysql database.
+-----------+
1 row in set (0.00 sec)
database():-
----------:-
It returns which database we are connected in mysql.
NESTED QUERIES:
------------:- A query within the query is called subquery or nested query.
* In this subquery first executes inner query and next executes outer query.
ex:-
-----:-
mysql> select * from emp where sal in(select min(sal) from emp group by deptno);
+-------+--------+-------+------+------------+---------+------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-------+------+------------+---------+------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
+-------+--------+-------+------+------------+---------+------+--------+
3 rows in set (0.00 sec)
Geethanjali College of Engineering Page 78
Database Management Systems Lab Dept. of CSE.
mysql> select * from emp where sal not in(select min(sal) from emp group by deptno);
+-------+--------+-----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
+-------+--------+-----------+------+------------+---------+---------+--------+
11 rows in set (0.04 sec)
mysql> select * from emp where sal>any(select min(sal) from emp group by deptno);
+-------+--------+-----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
| 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300.00 | NULL | 10 |
Geethanjali College of Engineering Page 79
Database Management Systems Lab Dept. of CSE.
+-------+--------+-----------+------+------------+---------+---------+--------+
13 rows in set (0.00 sec)
mysql> select * from emp where sal<any(select min(sal) from emp group by deptno);
+-------+--------+----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+----------+------+------------+---------+---------+--------+
| 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250.00 | 1400.00 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100.00 | NULL | 20 |
| 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950.00 | NULL | 30 |
+-------+--------+- ---------+------+------------+---------+---------+--------+
5 rows in set (0.00 sec)
mysql> select * from emp where sal<all(select min(sal) from emp group by deptno);
Empty set (0.00 sec)
mysql> select * from emp where sal>all(select min(sal) from emp group by deptno);
+-------+--------+-----------+------+------------+---------+--------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+--------+--------+
| 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600.00 | 300.00 | 30 |
| 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975.00 | NULL | 20 |
| 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850.00 | NULL | 30 |
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
| 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000.00 | NULL | 20 |
| 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500.00 | 0.00 | 30 |
| 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000.00 | NULL | 20 |
+-------+--------+-----------+------+------------+---------+--------+--------+
8 rows in set (0.00 sec)
Correlated subquery:-
----------------------:-
In this corelated subquery, first executes outer query and next executes inner query.
ex:-
---:-
mysql> select * from emp e where exists(select * from dept where deptno=e.deptno);
+-------+--------+-----------+------+------------+---------+---------+--------+
| empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------+--------+-----------+------+------------+---------+---------+--------+
| 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450.00 | NULL | 10 |
Geethanjali College of Engineering Page 80
Database Management Systems Lab Dept. of CSE.
mysql> select * from emp e where not exists(select * from dept where deptno=e.deptno);
Empty set (0.00 sec)
mysql> select * from dept d where not exists(select * from emp where deptno=d.deptno);
+--------+------------+--------+
| deptno | dname | loc |
+--------+------------+--------+
| 40 | OPERATIONS | BOSTON |
+--------+------------+--------+
1 row in set (0.00 sec)
mysql> select * from dept d where exists(select * from emp where deptno=d.deptno);
+--------+------------+----------+
| deptno | dname | loc |
+--------+------------+----------+
| 10 | ACCOUNTING | NEW YORK |
| 20 | RESEARCH | DALLAS |
| 30 | SALES | CHICAGO |
+--------+------------+----------+
3 rows in set (0.00 sec)
JOINS:-
---------:-Join is a query and it is used to retrieve data from multiple tables.
The joins are,
* Inner joins
* Outer joins
* Self join
Inner joins:-
------------:- It is used to retrieve data from multiple tables and it returns matching rows.
Geethanjali College of Engineering Page 81
Database Management Systems Lab Dept. of CSE.
* equi join
* non equi join
* cross join
* natural join
equi join:-
----------:-
It is used to retrieve data from multiple tables and it returns matching rows, here we can use '='
symbol.
this symbol we can use after where clause.
ex:-
----:-
ex:-
-----:-
mysql> select e.ename,e.sal,s.losal,s.hisal from emp e,salgrade s where e.sal between s.losal and
s.hisal;
Geethanjali College of Engineering Page 82
Database Management Systems Lab Dept. of CSE.
+--------+---------+-------+-------+
| ename | sal | losal | hisal |
+--------+---------+-------+-------+
| SMITH | 800.00 | 700 | 1200 |
| ALLEN | 1600.00 | 1401 | 2000 |
| WARD | 1250.00 | 1201 | 1400 |
| JONES | 2975.00 | 2001 | 3000 |
| MARTIN | 1250.00 | 1201 | 1400 |
| BLAKE | 2850.00 | 2001 | 3000 |
| CLARK | 2450.00 | 2001 | 3000 |
| SCOTT | 3000.00 | 2001 | 3000 |
| KING | 5000.00 | 3001 | 9999 |
| TURNER | 1500.00 | 1401 | 2000 |
| ADAMS | 1100.00 | 700 | 1200 |
| JAMES | 950.00 | 700 | 1200 |
| FORD | 3000.00 | 2001 | 3000 |
| MILLER | 1300.00 | 1201 | 1400 |
+--------+---------+-------+-------+
14 rows in set (0.00 sec)
cross join:-
----------:- It is used to retrieve data from multiple tables and it returns cross product result.
here we won't use where clause.
ex:-
----:-
| JONES | ACCOUNTING |
| MARTIN | OPERATIONS |
| MARTIN | SALES |
| MARTIN | RESEARCH |
| MARTIN | ACCOUNTING |
| BLAKE | OPERATIONS |
| BLAKE | SALES |
| BLAKE | RESEARCH |
| BLAKE | ACCOUNTING |
| CLARK | OPERATIONS |
| CLARK | SALES |
| CLARK | RESEARCH |
| CLARK | ACCOUNTING |
| SCOTT | OPERATIONS |
| SCOTT | SALES |
| SCOTT | RESEARCH |
| SCOTT | ACCOUNTING |
| KING | OPERATIONS |
| KING | SALES |
| KING | RESEARCH |
| KING | ACCOUNTING |
| TURNER | OPERATIONS |
| TURNER | SALES |
| TURNER | RESEARCH |
| TURNER | ACCOUNTING |
| ADAMS | OPERATIONS |
| ADAMS | SALES |
| ADAMS | RESEARCH |
| ADAMS | ACCOUNTING |
| JAMES | OPERATIONS |
| JAMES | SALES |
| JAMES | RESEARCH |
| JAMES | ACCOUNTING |
| FORD | OPERATIONS |
| FORD | SALES |
| FORD | RESEARCH |
| FORD | ACCOUNTING |
| MILLER | OPERATIONS |
| MILLER | SALES |
| MILLER | RESEARCH |
| MILLER | ACCOUNTING |
+--------+------------+
56 rows in set (0.00 sec)
| dname | losal |
+------------+-------+
| OPERATIONS | 700 |
| SALES | 700 |
| RESEARCH | 700 |
| ACCOUNTING | 700 |
| OPERATIONS | 1201 |
| SALES | 1201 |
| RESEARCH | 1201 |
| ACCOUNTING | 1201 |
| OPERATIONS | 1401 |
| SALES | 1401 |
| RESEARCH | 1401 |
| ACCOUNTING | 1401 |
| OPERATIONS | 2001 |
| SALES | 2001 |
| RESEARCH | 2001 |
| ACCOUNTING | 2001 |
| OPERATIONS | 3001 |
| SALES | 3001 |
| RESEARCH | 3001 |
| ACCOUNTING | 3001 |
+------------+-------+
20 rows in set (0.00 sec)
Natural join:-
-------------:-
+--------+---------+------------+----------+
14 rows in set (0.00 sec)
Outer joins:-
--------------:-It is used to retrieve data from multiple tables and it returns matching rows and non
matching rows.
The outer joins are,
ex:-
----:-
mysql> select e.ename,e.sal,d.dname,d.loc from ad_emp e right outer join ad_dept d on
e.deptno=d.deptno;
+--------+---------+------------+----------+
| ename | sal | dname | loc |
+--------+---------+------------+----------+
| MILLER | 1300.00 | ACCOUNTING | NEW YORK |
| KING | 5000.00 | ACCOUNTING | NEW YORK |
| CLARK | 2450.00 | ACCOUNTING | NEW YORK |
| FORD | 3000.00 | RESEARCH | DALLAS |
| ADAMS | 1100.00 | RESEARCH | DALLAS |
| SCOTT | 3000.00 | RESEARCH | DALLAS |
| JONES | 2975.00 | RESEARCH | DALLAS |
| SMITH | 800.00 | RESEARCH | DALLAS |
| JAMES | 950.00 | SALES | CHICAGO |
| TURNER | 1500.00 | SALES | CHICAGO |
Geethanjali College of Engineering Page 87
Database Management Systems Lab Dept. of CSE.
ex:-
-----:-
mysql> select e.ename,e.sal,d.dname,d.loc from ad_emp e left outer join ad_dept d on
e.deptno=d.deptno
-> union
-> select e.ename,e.sal,d.dname,d.loc from ad_emp e right outer join ad_dept d on
e.deptno=d.deptno;
+--------+---------+------------+----------+
| ename | sal | dname | loc |
+--------+---------+---- --------+----------+
| SMITH | 800.00 | RESEARCH | DALLAS |
| ALLEN | 1600.00 | SALES | CHICAGO |
| WARD | 1250.00 | SALES | CHICAGO |
| JONES | 2975.00 | RESEARCH | DALLAS |
| MARTIN | 1250.00 | SALES | CHICAGO |
| BLAKE | 2850.00 | SALES | CHICAGO |
| CLARK | 2450.00 | ACCOUNTING | NEW YORK |
| SCOTT | 3000.00 | RESEARCH | DALLAS |
| KING | 5000.00 | ACCOUNTING | NEW YORK |
| TURNER | 1500.00 | SALES | CHICAGO |
| ADAMS | 1100.00 | RESEARCH | DALLAS |
| JAMES | 950.00 | SALES | CHICAGO |
| FORD | 3000.00 | RESEARCH | DALLAS |
| MILLER | 1300.00 | ACCOUNTING | NEW YORK |
| AAA | NULL | NULL | NULL |
| NULL | NULL | OPERATIONS | BOSTON |
+--------+---------+------------+----------+
16 rows in set (0.04 sec)
Self join:-
----------:-
self join is a join and it is used to itself.
ex:-
Geethanjali College of Engineering Page 88
Database Management Systems Lab Dept. of CSE.
-------:-
mysql> select e.ename,e.sal,e1.ename,e1.job from emp e,emp e1 where e.empno=e1.mgr;
+-------+---------+--------+----------+
| ename | sal | ename | job |
+-------+---------+--------+----------+
| FORD | 3000.00 | SMITH | CLERK |
| BLAKE | 2850.00 | ALLEN | SALESMAN |
| BLAKE | 2850.00 | WARD | SALESMAN |
| KING | 5000.00 | JONES | MANAGER |
| BLAKE | 2850.00 | MARTIN | SALESMAN |
| KING | 5000.00 | BLAKE | MANAGER |
| KING | 5000.00 | CLARK | MANAGER |
| JONES | 2975.00 | SCOTT | ANALYST |
| BLAKE | 2850.00 | TURNER | SALESMAN |
| SCOTT | 3000.00 | ADAMS | CLERK |
| BLAKE | 2850.00 | JAMES | CLERK |
| JONES | 2975.00 | FORD | ANALYST |
| CLARK | 2450.00 | MILLER | CLERK |
+-------+---------+--------+----------+
13 rows in set (0.00 sec)
VIVA QUESTIONS
1. What is Equijoin?
An equijoin is a join with a join condition containing an equality operator.
An equijoin returns only the rows that have equivalent values for the specified columns.
An Non Equi Join /inner join is a join of two or more tables that returns only those rows
(compared using a comparison operator) that satisfy the join condition.
Work space:
QUERIES:
1: Display all the dept numbers available with the dept and emp tables avoiding duplicates.
Solution:
1. Use select from clause.
Query:
SET OPERATORS:-
----------------:-
The SQL Set operators is used to combine the two or more SQL SELECT statements.
* Union
* Union All
* Intersect (MySQL does not provide support for the "intersect" operator, alternatively we will
do)
* Minus (MySQL does not provide support for the "minus" operator, alternatively we will do)
UNION:-
------:-
* The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
* In the union operation, all the number of datatype and columns must be same in both the tables
on which UNION operation is being applied.
* The union operation eliminates the duplicate rows from its result set.
Syntax:-
----------:-
select */col_list from table_name1
union
select */col_list from table_name2;
ex:-
----:-
|2 |
|A |
|B |
|Y |
+------+
5 rows in set (0.06 sec)
mysql> select deptno from emp union select deptno from dept;
+--------+
| deptno |
+--------+
| 10 |
| 20 |
| 30 |
| 40 |
+--------+
4 rows in set (0.00 sec)
2: Display all the dept numbers available with the dept and emp tables.
Solution:
1. Use select from clause.
2. Use union all in select clause to get the result.
Query:
* UNION ALL:
==============:-
-> Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:-
---------:-
select */col_list from table_name1
union
select */col_list from table_name2;
ex:-
------:-
|Y |
+------+
10 rows in set (0.00 sec)
mysql> select deptno from emp union all select deptno from dept;
+--------+
| deptno |
+--------+
| 10 |
| 10 |
| 10 |
| 20 |
| 20 |
| 20 |
| 20 |
| 20 |
| 30 |
| 30 |
| 30 |
| 30 |
| 30 |
| 30 |
| 10 |
| 20 |
| 30 |
| 40 |
+--------+
18 rows in set (0.00 sec)
INTERSECT:-
===========
* It is used to combine two SELECT statements. The Intersect operation returns the common
rows from both the SELECT statements.
* In the Intersect operation, the number of datatype and columns must be the same.
* It has no duplicates and it arranges the data in ascending order by default.
=> In Mysql database there is no directly intersect operator but that resultant output we will do
alternatively. i,e.
Note:-
-----:- MySQL does not provide support for the INTERSECT operator. The below one shows us
how to emulate the INTERSECT query in MySQL using the JOIN clause.
ex:-
----:-
Geethanjali College of Engineering Page 95
Database Management Systems Lab Dept. of CSE.
MINUS:-
=========
* It combines the result of two SELECT statements. Minus operator is used to display the rows
which are present in the first query but absent in the second query.
* It has no duplicates and data arranged in ascending order by default.
NOTE:
------:- MySQL does not provide support for the MINUS operator. The below one shows you how
to simulate the MINUS query in MySQL using the JOIN clause.
ex:-
----:-
mysql> select id from tab1 left join tab2 using (id) where tab2.id is null;
+------+
| id |
+------+
|2 |
|A |
+------+
2 rows in set (0.00 sec)
mysql> select id from tab2 left join tab1 using (id) where tab1.id is null;
+------+
| id |
+------+
|3 |
|X |
+------+
2 rows in set (0.00 sec)
VIVA QUESTIONS
Work space:
VIEW: In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements
to a view and present the data as if the data were coming from one single table.
A view is a virtual table, which consists of a set of columns from one or more tables. It is similar
to a table but it does not store in the database. View is a query stored as an object.
Syntax: CREATE VIEW view name AS SELECT set of fields FROM relation name
WHERE (Condition)
SIMPLE VIEW:-
-------------:- It contains one base table and it retrieves data from that base table.It supports dml
commands.
ex:-
---:-
COMPLEX VIEW:-
-------------:-
It contains multiple base tables and it retrieves data from that base tables.It won't supports dml
commands.
mysql> create view c_view as select e.ename,e.sal,d.dname,d.loc from emp e,dept d where
e.deptno=d.deptno;
Query OK, 0 rows affected (0.80 sec)
general syntax:-
---------------:-
drop view view_name;
ex:-
----:-
VIVA QUESTIONS
2. Define View?
A view is a subset of a database that is generated from a query and stored as a permanent
object. Although the definition of a view is permanent, the data contained therein is
dynamic depending on the point in time at which the view is accessed. Views represent a
subset of the data contained in a table.
Work space:
Objectives:
Student will able to learn to monitor a database and take initiate action when a condition occurs.
Outcomes:
Student gains the ability to change database manager from a passive system to an active one.
MySQL Trigger:-
-----------------:-
A trigger in MySQL is a set of SQL statements that reside in a system catalog. It is a special type
of stored procedure that is invoked automatically in response to an event. Each trigger is associated
with a table, which is activated on any DML statement such as INSERT, UPDATE, or DELETE.
A trigger is called a special procedure because it cannot be called directly like a stored procedure.
The main difference between the trigger and procedure is that a trigger is called automatically
when a data modification event is made against a table. In contrast, a stored procedure must be
called explicitly.
Generally, triggers are of two types according to the SQL standard: row-level triggers and
statement-level triggers.
Row-Level Trigger: It is a trigger, which is activated for each row by a triggering statement such
as insert, update, or delete. For example, if a table has inserted, updated, or deleted multiple rows,
the row trigger is fired automatically for each row affected by the insert, update, or delete
statement.
Statement-Level Trigger: It is a trigger, which is fired once for each event that occurs on a table
regardless of how many rows are inserted, updated, or deleted.
Before Insert : It is activated before the insertion of data into the table.
After Insert : It is activated after the insertion of data into the table.
Before Update : It is activated before the update of data in the table.
After Update : It is activated after the update of the data in the table.
Before Delete : It is activated before the data is removed from the table.
After Delete : It is activated after the deletion of data from the table.
We can use the CREATE TRIGGER statement for creating a new trigger in MySQL. Below is the
syntax of creating a trigger in MySQL:
ex:-
----:-
mysql> CREATE TABLE employee(
name varchar(45) NOT NULL,
occupation varchar(35) NOT NULL,
working_date date,
working_hours varchar(10)
);
Query OK, 0 rows affected (7.45 sec)
Next, we will create a BEFORE INSERT trigger. This trigger is invoked automatically insert the
working_hours = 0 if someone tries to insert working_hours < 0.
ex:-
----:-
DELIMITER //
Create Trigger before_insert_empworkinghours
BEFORE INSERT ON employee FOR EACH ROW
BEGIN
IF NEW.working_hours < 0 THEN SET NEW.working_hours = 0;
END IF;
END //
Query OK, 0 rows affected (0.83 sec)
In this output, we can see that on inserting the negative values into the working_hours column of
the table will automatically fill the zero value by a trigger.
After Insert Trigger in MySQL is invoked automatically whenever an insert event occurs on the
table. In this article, we are going to learn how to create an after insert trigger with its syntax and
example.
Syntax:-
---------:-
The following is the syntax to create an AFTER INSERT trigger in MySQL:
* First, we will specify the name of the trigger that we want to create. It should be unique within
the schema.
* Second, we will specify the trigger action time, which should be AFTER INSERT clause to
invoke the trigger.
Geethanjali College of Engineering Page 106
Database Management Systems Lab Dept. of CSE.
* Third, we will specify the name of a table to which the trigger is associated. It must be written
after the ON keyword. If we did not specify the table name, a trigger would not exist.
* Finally, we will specify the trigger body that contains one or more statements for execution when
the trigger is activated.
If we want to execute multiple statements, we will use the BEGIN END block that contains a set of
SQL queries to define the logic for the trigger. See the below syntax:
DELIMITER $$
CREATE TRIGGER trigger_name AFTER INSERT
ON table_name FOR EACH ROW
BEGIN
variable declarations
trigger code
END$$
DELIMITER ;
+---------+-----------+-----------+---------+-------+------------+
| 1 | 101 | Mark | English | 68 | 3456789234 |
| 2 | 201 | Joseph | Physics | 69 | 3956789234 |
| 3 | 301 | Adams | Maths | 60 | 2956789234 |
+---------+-----------+-----------+---------+-------+------------+
3 rows in set (0.00 sec)
Next, we will use a CREATE TRIGGER statement to create an after_insert_details trigger on the
student_info table. This trigger will be fired after an insert operation is performed on the table.
DELIMITER //
Create Trigger after_insert_details
AFTER INSERT ON student_info FOR EACH ROW
BEGIN
INSERT INTO student_detail VALUES (new.stud_id, new.stud_code,
new.stud_name, new.subject, new.marks, new.phone, CURTIME());
END //
Query OK, 0 rows affected (0.25 sec)
mysql> INSERT INTO student_info VALUES (10, 110, 'Alexandar', 'Biology', 67, '2347346438');
Query OK, 1 row affected (0.30 sec)
The table that has been modified after the update query executes is student_detail. We can verify it
by using the SELECT statement as follows:
+---------+-----------+-----------+---------+-------+------------+-------------+
| 10 | 110 | Alexandar | Biology | 67 | 2347346438 | 09:18:33 |
+---------+-----------+-----------+---------+-------+------------+-------------+
1 row in set (0.00 sec)
In this output, we can see that on inserting values into the student_info table, the student_detail
table will automatically fill the records by invoking a trigger.
mysql> deliniter $$
-> ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near 'deliniter $$' at line 1
delimiter $$
create trigger neworderformedicine
before update on medicine
for each row
begin
if new.quantity<20 then
insert into neworder values(new.mid,sysdate(),200);
end if;
end;
$$
Query OK, 0 rows affected (0.24 sec)
After Update:-
=============:-
We will be creating two tables, patient_food_allergies,patient_allergy_modification_history and
inserting some rows into patient_food_allergies.
+------------+----------------------+
| patient_id | patient_food_allergy |
+------------+----------------------+
| 1 | Milk |
| 2 | Nuts |
| 3 | Wheat |
| 4 | Nuts |
| 5 | Nuts |
| 6 | Pumpkin |
+------------+----------------------+
6 rows in set (0.00 sec)
DELIMITER //
CREATE TRIGGER after_update_patient_food_allergies
AFTER UPDATE
ON patient_food_allergies FOR EACH ROW
BEGIN
IF (OLD.patient_food_allergy <> new.patient_food_allergy)
THEN
INSERT INTO patient_allergy_modification_history(patient_id,
patient_food_allergy, patient_food_allergy_changed, date_of_change)
VALUES(old.patient_id, old.patient_food_allergy, new.patient_food_allergy, sysdate());
END IF;
END//
| 3 | Wheat |
| 4 | Nuts |
| 5 | Nuts |
| 6 | Pumpkin |
+------------+----------------------+
6 rows in set (0.12 sec)
Before Delete:-
--------------:-
* create a trigger which will work before deleteion in employee table and create a copy of the
record in another table called emp-backup two tables.(employee,emp-backup)
employee(empid,ename,job,doj,salary)
emp_backup(empid,ename,job,doj,salary)
EX:-
----:-
delimiter //
create trigger bef_delete_emp before delete on employee for each row
begin
insert into emp_backup values(old.empid,old.ename,old.job,old.doj,old.salary);
end //
Query OK, 0 rows affected (0.19 sec)
+--------+-------+---------+------------+--------+
3 rows in set (0.03 sec)
After Delete:-
=============:-
It is activated after the deletion of data from the table.
Here we are taking two tables i,e. employe and salarybudget.
+--------+-------+---------+------------+--------+
| 111 | AAA | CLERK | 2021-01-01 | 1000.5 |
| 222 | BBB | MANAGER | 2021-02-01 | 2000.5 |
| 333 | CCC | ANALYST | 2021-03-01 | 3000.5 |
| 444 | DDD | ANALYST | 2021-04-01 | 4000.5 |
| 555 | EEE | ANALYST | 2021-05-01 | 5000.5 |
+--------+-------+---------+------------+--------+
5 rows in set (0.00 sec)
DELIMITER //
create trigger after_del after delete on employee for each row
begin
update salarybudget set total_salary=total_salary-old.salary;
end //
VIVA QUESTIONS
1. What is Trigger?
A trigger is a stored procedure in database which automatically invokes whenever a
special event in the database occurs. For example, a trigger can be invoked when a row is
inserted into a specified table or when certain table columns are being updated.
Work space:
Outcomes:
Student gains the knowledge to implement procedures and function for various operations.
Stored procedures:-
----------------------:- procedure is a database object, procedures may or maynot return a value.
The procedure parameters are, in, out, in out.
ex:-
----:-
mysql> DELIMITER $$
mysql> CREATE PROCEDURE get_merit_student ()
BEGIN
SELECT * FROM student_info WHERE marks > 60;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END $$
Query OK, 0 rows affected (0.25 sec)
+---------+-----------+-----------+---------+-------+------------+
| 1 | 101 | Mark | English | 68 | 3456789234 |
| 2 | 201 | Joseph | Physics | 69 | 3956789234 |
| 10 | 110 | Alexandar | Biology | 67 | 2347346438 |
+---------+-----------+-----------+---------+-------+------------+
3 rows in set (0.09 sec)
+---------------+
| Total_Student |
+---------------+
| 4|
+---------------+
1 row in set (0.13 sec)
mysql> DELIMITER $$
mysql> CREATE PROCEDURE get_student (IN var1 INT)
-> BEGIN
-> SELECT * FROM student_info LIMIT var1;
-> SELECT COUNT(stud_code) AS Total_Student FROM student_info;
-> END $$;
Query OK, 0 rows affected (0.36 sec)
-> $$
ERROR 1065 (42000): Query was empty
mysql> select * from student_info;
-> $$
+---------+-----------+-----------+---------+-------+------------+
| stud_id | stud_code | stud_name | subject | marks | phone |
+---------+-----------+-----------+---------+-------+------------+
| 1 | 101 | Mark | English | 68 | 3456789234 |
| 2 | 201 | Joseph | Physics | 69 | 3956789234 |
Geethanjali College of Engineering Page 119
Database Management Systems Lab Dept. of CSE.
+---------------+
| Total_Student |
+---------------+
| 4 |
+---------------+
1 row in set (0.03 sec)
+---------------+
| Total_Student |
+---------------+
| 4|
+---------------+
1 row in set (0.03 sec)
mysql> DELIMITER $$
mysql> CREATE PROCEDURE display_max_mark (OUT highestmark INT)
-> BEGIN
-> SELECT MAX(marks) INTO highestmark FROM student_info;
-> END $$;
Query OK, 0 rows affected (0.27 sec)
->
-> $$
ERROR 1065 (42000): Query was empty
mysql> call display_max_mark $$
ERROR 1318 (42000): Incorrect number of arguments for PROCEDURE
my_db.display_max_mark; expected 1, got 0
mysql> call display_max_mark(@a) $$
Query OK, 1 row affected (0.02 sec)
mysql> DELIMITER $$
mysql> CREATE PROCEDURE display_marks (INOUT var1 INT)
-> BEGIN
Geethanjali College of Engineering Page 121
Database Management Systems Lab Dept. of CSE.
-> SELECT marks INTO var1 FROM student_info WHERE stud_id = var1;
-> END $$
Query OK, 0 rows affected (0.23 sec)
mysql> select @a $$
+------+
| @a |
+------+
| 60 |
+------+
1 row in set (0.00 sec)
-+--------------------+
| get_merit_student | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE
DEFINER=`root`@`localhost` PROCEDURE `get_merit_student`()
COMMENT 'it displays all records'
BEGIN
SELECT * FROM student_info WHERE marks > 60;
SELECT COUNT(stud_code) AS Total_Student FROM student_info;
END | cp850 | cp850_general_ci | utf8mb4_0900_ai_ci |
+-------------------+--------------------------------------------+---------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------+----------------------+---------------------
-+--------------------+
1 row in set (0.00 sec)
drop procedure:-
===============:- It is used to remove the procedures from the database.
syntax:-
--------:- drop procedure procedure_name;
ex:-
---:-
VIVA QUESTIONS
3. What is PL/SQL?
PL/SQL is a block of codes that used to write the entire program blocks/ procedure/
function, etc. It is declarative, that defines what needs to be done, rather than how things
need to be done. PL/SQL is procedural that defines how the things needs to be done. It is
Work space:
| 31 | Lubber | 8 | 55.5 |
| 32 | Andy | 8 | 25.5 |
| 58 | Rusty | 10 | 35 |
| 64 | Horatio | 7 | 35 |
| 71 | Zorba | 10 | 16 |
| 74 | Horatio | 9 | 40 |
| 85 | Art | 3 | 25.5 |
| 95 | Bob | 3 | 63.5 |
+-----+---------+--------+------+
10 rows in set (0.00 sec)
mysql> create table boats(bid int primary key,
-> bname varchar(10),
-> color varchar(10));
Query OK, 0 rows affected (0.33 sec)
mysql> desc boats;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| bid | int | NO | PRI | NULL | |
| bname | varchar(10) | YES | | NULL | |
| color | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.04 sec)
mysql> insert into boats values(101,'Interlake','blue'),
-> (102,'Interlake','red'),
-> (103,'Clipper','green'),
-> (104,'Marine','red');
Query OK, 4 rows affected (0.31 sec)
Records: 4 Duplicates: 0 Warnings: 0
-> (22,102,'1998-10-10'),
-> (22,103,'1998-10-8'),
-> (22,104,'1998-10-7'),
-> (31,102,'1998-11-10'),
-> (31,103,'1998-11-6'),
-> (31,104,'1998-11-12'),
-> (64,101,'1998-9-5'),
-> (64,102,'1998-9-8'),
-> (74,103,'1998-9-8');
Query OK, 10 rows affected (0.34 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from reserves;
+-----+-----+---------------------+
| sid | bid | day |
+-----+-----+---------------------+
| 22 | 101 | 1998-10-10 00:00:00 |
| 64 | 101 | 1998-09-05 00:00:00 |
| 22 | 102 | 1998-10-10 00:00:00 |
| 31 | 102 | 1998-11-10 00:00:00 |
| 64 | 102 | 1998-09-08 00:00:00 |
| 22 | 103 | 1998-10-08 00:00:00 |
| 31 | 103 | 1998-11-06 00:00:00 |
| 74 | 103 | 1998-09-08 00:00:00 |
| 22 | 104 | 1998-10-07 00:00:00 |
| 31 | 104 | 1998-11-12 00:00:00 |
+-----+-----+---------------------+
10 rows in set (0.01 sec)
| Horatio | 40 |
| Art | 25.5 |
| Bob | 63.5 |
+---------+------+
10 rows in set (0.00 sec)
(or)
mysql> select s.sname,s.age from sailors s;
+---------+------+
| sname | age |
+---------+------+
| Dustin | 45 |
| Brutus | 33 |
| Lubber | 55.5 |
| Andy | 25.5 |
| Rusty | 35 |
| Horatio | 35 |
| Zorba | 16 |
| Horatio| 40 |
| Art | 25.5 |
| Bob | 63.5 |
+---------+------+
10 rows in set (0.00 sec)
Ex4:-
Find the names of sailors who have reserved a red boat, and list in the order of age.
mysql> SELECT S.sname, S.age
-> FROM Sailors S, Reserves R, Boats B
-> WHERE S.sid = R.sid AND R.bid = B.bid AND B.color ='red'
-> order by s.age;
+---------+------+
| sname | age |
+---------+------+
| Horatio | 35 |
| Dustin | 45 |
| Dustin | 45 |
| Lubber | 55.5 |
| Lubber | 55.5 |
+---------+------+
5 rows in set (0.05 sec)
Ex5:-
Find the names of sailors who have reserved at least one boat.
mysql> SELECT sname
-> FROM Sailors S, Reserves R
-> WHERE S.sid = R.sid;
+---------+
| sname |
+---------+
| Dustin |
Geethanjali College of Engineering Page 129
Database Management Systems Lab Dept. of CSE.
| Dustin |
| Dustin |
| Dustin |
| Lubber |
| Lubber |
| Lubber |
| Horatio |
| Horatio |
| Horatio |
+---------+
10 rows in set (0.00 sec)
Ex6:-
Find the ids and names of sailors who have reserved two different boats on the same day
mysql> SELECT DISTINCT S.sid, S.sname
-> FROM Sailors S, Reserves R1, Reserves R2
-> WHERE S.sid = R1.sid AND S.sid = R2.sid
-> AND R1.day = R2.day AND R1.bid <> R2.bid;
+-----+--------+
| sid | sname |
+-----+--------+
| 22 | Dustin |
+-----+--------+
1 row in set (0.00 sec)
Ex7:-
Find the ids of sailors who have reserved a red boat or a green boat
mysql> select r.sid from boats b, reserves r
-> where r.bid=b.bid and b.color='red'
-> union
-> select r2.sid
-> from boats b2,reserves r2
-> where r2.bid=b2.bid and b2.color='green';
+-----+
| sid |
+-----+
| 22 |
| 31 |
| 64 |
| 74 |
Geethanjali College of Engineering Page 130
Database Management Systems Lab Dept. of CSE.
+-----+
4 rows in set (0.00 sec)
Ex8:-
Find the All ids of sailors who have reserved a red boat or a green boat
mysql> select r.sid from boats b, reserves r
-> where r.bid=b.bid and b.color='red'
-> union all
-> select r2.sid
-> from boats b2,reserves r2
-> where r2.bid=b2.bid and b2.color='green';
+-----+
| sid |
+-----+
| 22 |
| 31 |
| 64 |
| 22 |
| 31 |
| 22 |
| 31 |
| 74 |
+-----+
8 rows in set (0.00 sec)
Ex9:-
Find the names of sailors who have reserved boat 103.
mysql> SELECT S.sname
-> FROM Sailors S
-> WHERE S.sid IN ( SELECT R.sid
-> FROM Reserves R
-> WHERE R.bid = 103 );
+---------+
| sname |
+---------+
| Dustin |
| Lubber |
| Horatio |
+---------+
3 rows in set (0.02 sec)
Geethanjali College of Engineering Page 131
Database Management Systems Lab Dept. of CSE.
Ex10:-
Find the name and the age of the youngest sailor.
mysql> SELECT S.sname, S.age
-> FROM Sailors S
-> WHERE S.age <= ALL ( SELECT age
-> FROM Sailors );
+-------+------+
| sname | age |
+-------+------+
| Zorba | 16 |
+-------+------+
1 row in set (0.01 sec)
Ex11:-
Find the names and ratings of sailor whose rating is better than some sailor called Horatio.
mysql> select s.sname,s.rating
-> from sailors s
-> where s.rating>any(select s2.rating from sailors s2 where s2.sname='Horatio');
+---------+--------+
| sname | rating |
+---------+--------+
| Lubber | 8 |
| Andy | 8 |
| Rusty | 10 |
| Zorba | 10 |
| Horatio | 9 |
+---------+--------+
5 rows in set (0.01 sec)
Ex12:-
Count the number of different sailor names
mysql> SELECT COUNT( DISTINCT S.sname )
-> FROM Sailors S;
+---------------------------+
| COUNT( DISTINCT S.sname ) |
+---------------------------+
| 9|
+---------------------------+
1 row in set (0.02 sec)
Geethanjali College of Engineering Page 132
Database Management Systems Lab Dept. of CSE.
Ex13:-
Calculate the average age of all sailors
mysql> SELECT AVG(s.age)
-> FROM Sailors S;
+------------+
| AVG(s.age) |
+------------+
| 37.4 |
+------------+
1 row in set (0.00 sec)
Ex14:-
Find the name and the age of the youngest sailor
mysql> SELECT S.sname, S.age
-> FROM Sailors S
-> WHERE S.age = (SELECT MIN(S2.age)
-> FROM Sailors S2 );
+-------+------+
| sname | age |
+-------+------+
| Zorba | 16 |
+-------+------+
1 row in set (0.00 sec)
Ex15:-
Find the average age of sailors for each rating level.
mysql> SELECT S.rating, AVG(S.age) AS avg_age
-> FROM Sailors S
-> GROUP BY S.rating;
+--------+---------+
| rating | avg_age |
+--------+---------+
| 7 | 40 |
| 1 | 33 |
| 8 | 40.5 |
| 10 | 25.5 |
| 9 | 40 |
| 3 | 44.5 |
+--------+---------+
Geethanjali College of Engineering Page 133
Database Management Systems Lab Dept. of CSE.
Ex16:-
Find the average age of sailors for each rating level that has at least two sailors.
mysql> SELECT S.rating, AVG(S.age) AS avg_age
-> FROM Sailors S
-> GROUP BY S.rating
-> HAVING COUNT(*) > 1;
+--------+---------+
| rating | avg_age |
+--------+---------+
| 7 | 40 |
| 8 | 40.5 |
| 10 | 25.5 |
| 3 | 44.5 |
+--------+---------+
4 rows in set (0.01 sec)
Ex17:-
An example shows difference between WHERE and HAVING:
mysql> SELECT S.rating, AVG(S.age) as avg_age
-> FROM Sailors S
-> WHERE S.age >=40
-> GROUP BY S.rating;
+--------+---------+
| rating | avg_age |
+--------+---------+
| 7 | 45 |
| 8 | 55.5 |
| 9 | 40 |
| 3 | 63.5 |
+--------+---------+
4 rows in set (0.01 sec)
mysql> SELECT S.rating, AVG(S.age) as avg_age
-> FROM Sailors S
-> GROUP BY S.rating
-> HAVING AVG(S.age) >= 40;
+--------+---------+
| rating | avg_age |
+--------+---------+
Geethanjali College of Engineering Page 134
Database Management Systems Lab Dept. of CSE.
| 7 | 40 |
| 8 | 40.5 |
| 9 | 40 |
| 3 | 44.5 |
+--------+---------+
4 rows in set (0.00 sec)
Ex18:-
Find the names of sailors who have reserved all boats
mysql> SELECT S.sname
-> FROM Sailors S
-> WHERE NOT EXISTS ( SELECT B.bid
-> FROM Boats B
-> WHERE NOT EXISTS ( SELECT R.bid
-> FROM Reserves R
-> WHERE R.bid = B.bid
-> AND R.sid = S.sid ) );
+--------+
| sname |
+--------+
| Dustin |
+--------+
1 row in set (0.01 sec)
Objectives:
Student will be able to learn to avoid problems that are associated with updating redundant data.
Outcomes:
Student gains the knowledge to build the database that does not have redundant data.
Work space: