0% found this document useful (0 votes)
45 views108 pages

DBMS Manual2

The lab manual for the Database Management System course at Maharaja Agrasen Institute of Technology outlines the vision and mission of the institute and the Computer Science & Engineering department. It details the course objectives, outcomes, lab requirements, and a list of experiments, including both prescribed and additional tasks. The document also includes a marking scheme for practical exams and an introduction to database management systems, covering their architecture and components.

Uploaded by

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

DBMS Manual2

The lab manual for the Database Management System course at Maharaja Agrasen Institute of Technology outlines the vision and mission of the institute and the Computer Science & Engineering department. It details the course objectives, outcomes, lab requirements, and a list of experiments, including both prescribed and additional tasks. The document also includes a marking scheme for practical exams and an introduction to database management systems, covering their architecture and components.

Uploaded by

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

LAB MANUAL

Database Management System CIC-


256

Maharaja Agrasen Institute of Technology, PSP area,


Sector- 22, Rohini, New Delhi – 110085
Affiliated to Guru Gobind Singh Indraprastha University
New Delhi
MAIT/CSE
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

VISION
“To attain global excellence through education, innovation, research, and work ethics with
the commitment to serve humanity.”

MISSION
The Institute shall endeavour to incorporate the following basic missions in the teaching
methodology:

M1. To promote diversification by adopting advancement in science, technology, management, and


allied discipline through continuous learning

M2. To foster moral values in students and equip them for developing sustainable solutions to serve
both national and global needs in society and industry.

M3. To digitize educational resources and process for enhanced teaching and effective learning.

M4. To cultivate an environment supporting incubation, product development, technology transfer,


capacity building and entrepreneurship.

M5. To encourage faculty-student networking with alumni, industry, institutions, and other
stakeholders for collective engagement.

i
MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY

COMPUTER SCIENCE & ENGINEERING DEPARTMENT

VISION

“To attain global excellence through education, innovation, research, and work ethics in the field of
Computer Science and engineering with the commitment to serve humanity.”

MISSION

M1: To lead in the advancement of computer science and engineering through internationally
recognized research and education.
M2: To prepare students for full and ethical participation in a diverse society and encourage
lifelong learning.
M3: To foster development of problem solving and communication skills as an integral
component of the profession.
M4: To impart knowledge, skills and cultivate an environment supporting incubation, product
development, technology transfer, capacity building and entrepreneurship in the field of
computer science and engineering.
M5: To encourage faculty, student’s networking with alumni, industry, institutions, and other
stakeholders for collective engagement.

ii
Program Outcomes (POs)
Engineering Graduates will be able to:
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 modeling 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 indiverse
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
iii
Program Specific Outcome (PSO)

PSO1: Able to explore and apply emerging technologies in computer science and engineering such as
Artificial Intelligence, Machine Learning, Data Science, etc.

PSO2: Able to independently and collaboratively design, develop and evaluate innovative solutions to
existing problems, addressing the needs of industry and society.

PSO3: Able to pursue advanced studies, conduct research and development, and cultivate
entrepreneurship skills in the modern computing environment.

Program Educational Objectives (PEO)

PEO1: Graduates will work with the top institutions and researchers, dedicating themselves to lifelong
learning and social responsibility. (M1, M2)

PEO2: Graduates will exhibit outstanding communication skills and the capacity to collaborate
effectively within diverse teams. (M3)

PEO3: Graduates cultivating skills in computer science and engineering contribute to driving
innovation,
entrepreneurship, and economic growth. (M4)

PEO4: Graduates network with stakeholders to contribute to the growth of the department. (M5)

iv
INDEX OF THE CONTENTS
Page No:

1. Introduction to the lab……………………………………………………………………………… 1

2. Lab Requirements (details of H/W & S/W to be used)………………………………………….. 2

3. List of Experiments as per GGSIPU…………………………………………………………….. 3

4. List of experiments beyond the syllabus…………………………………………………………4

5. Format of the lab record to be prepared by the students………………………………………..5

6. Marking scheme for the Practical Exam………………………………………………………….7

7. Instructions for each Lab Experiment……………………………………………………….…..15

v
1. Introduction to the Lab

Course Objectives:

1. To introduce basic concepts, architecture and characteristics of database systems


2. To introduce relational model concepts and PL/SQL programming
3. To introduce relational database design and Normal forms based on functional dependencies
4. To introduce concepts of object-oriented & distributed databases

Revised Course Outcomes:

CO 1 Ability to understand the basics of database systems


CO 2 Ability to use SQL as DDL, DCL and DML
CO 3 Ability to understand and apply relational model concepts, SQL functions, advanced query
operations, and transaction control for efficient database management.
CO 4 Ability to understand and apply relational database design principles, normalization, transaction
management, concurrency control, recovery techniques, and PL/SQL programming for efficient and
reliable database systems.

Course Outcomes (CO) to Programme Outcomes (PO) mapping:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 3 3 2 2 1 1 1 1 2 1 2
CO2 3 3 3 2 2 1 1 1 1 2 1 2
CO3 3 3 3 2 3 2 1 2 1 2 1 2
CO4 3 3 3 2 3 1 1 1 2 2 1 2

Course Outcomes (CO) to Program Specific Outcome Mapping:

PSO1 PSO2 PSO3

CO1 2 2 1
CO2 2 2 1
CO3 3 3 2
CO4 3 3 3

1
2. LAB REQUIREMENTS

Hardware Detail

Intel i3 Processor/4 GB RAM/1TB HDD/MB/LAN Card/


Key Board/ Mouse/15” Color Monitor/ UPS 24 Nos

LaserJet Printer 1 No

Software Detail
Operating System: Fedora, Linux

Software: Maria DB

2
3. LIST OF EXPERIMENTS (As prescribed by G.G.S.I.P.U)

1. Experiments based on DDL commands – CREATE, ALTER, DROP and TRUNCATE. (CO1, CO2)

2. Apply the integrity constraints like Primary Key, Foreign key, Check, NOT NULL, etc. to the
tables. (CO3)

3. Experiments based on basic DML commands – SELECT, INSERT, UPDATE and DELETE. (CO2)

4. Write the queries for implementing Built-in functions, GROUP BY, HAVING and ORDER BY.
(CO3)

5. Write the queries to implement the joins. (CO3)

6. Write the queries to implement the subqueries. (CO3)

7. Write the queries to implement the set operations. (CO3)

8. Write the queries to create the views and queries based on views. (CO4)

9. Demonstrate the concept of Control Structures. (CO4)

10. Demonstrate the concept of Exception Handling. (CO4)

11. Demonstrate the concept of Functions and Procedures. (CO4)

12. Demonstrate the concept of Triggers. (CO4)

3
4. LIST OF EXPERIMENTS (beyond syllabus)

1. The Institute offers multiple B. Tech Courses. Students can take admission in any Course offered by the
Institute. Multiple subjects are taught in each branch. The institute has a Director and Hod of each B. Tech
Course. The HoD of another branch may be given additional responsibility to take charge of one more
department for a limited period in the absence of Hod of that branch. Faculties recruited in each B. Tech
Course can teach only a single same subject to students of different B.Tech Courses. For each subject,
there is a faculty coordinator responsible for coordinating all the faculties teaching the same subject. A
batch of 20 students is assigned a faculty mentor. The mentor takes counsellor meetings twice a month.

Data to be recorded in the database include:


Student – enrollment no, name, data of birth, address, contact no, email – id, qualifying exam
rank, Course
Faculty – Faculty name, contact no, email id, course
Parents data – Parents name, contact no, email id, Profession

Draw the ER diagram (Conceptual design) of the given problem statement. (CO1)

2. To demonstrate a connection to a MariaDB database using the following languages: C, Java and Python

4
Database Management System

CIC-256

Faculty name : Dr. Prerna Sharma Student name : Nikil Kumar Agrawal

RollNo: 08614802723

Semester: 4th

Maharaja Agrasen Institute of Technology, PSP Area,

Sector – 22, Rohini, New Delhi – 110085

5
Database Management System Lab (CIC - 256) Lab Assessment Sheet

Student Enrollment No: Student Name:

R1 R2 R3 R4 R5

Total
Faculty
S.No Experiment Marks Remarks
Signature
(10)

2 2 2 2 2
Marks Marks Marks Marks Marks

10

6
6. MARKING SCHEME FOR THE PRACTICAL EXAMS

There will be two practical exams in each semester.

i. Internal Practical Exam


ii. External Practical Exam

INTERNAL PRACTICAL EXAM

It is taken by the respective faculty of the batch.

MARKING SCHEME FOR THIS EXAM IS:

Total Marks: 40

Division of 10 marks per practical is as follows:

10 Marks POs and PSOs Covered


Rubrics 0
1 Marks 2 Marks PO PSO
Marks

Is able to identify and


PSO1,
R1 define the objective of the No Partially Completely PO1, PO2
PSO2
given problem?

Is proposed
PO1, PO2, PSO1,
R2 design/procedure/algorithm No Partially Completely
PO3 PSO2
solves the problem?
Has the understanding of
the tool/programming PO1, PO3, PSO1,
R3 No Partially Completely
language to implement the PO5 PSO2
proposed solution?
Are the result(s) verified
PO2, PO4,
R4 using sufficient test data to No Partially Completely PSO2
PO5
support the conclusions?

Individuality of PSO1,
R5 No Partially Completely PO8, PO12
submission? PSO3

Each experiment will be evaluated out of 10 marks. At the end of the semester, an average of 8 best
performed practical’s will be considered as marks out of 40.

EXTERNAL PRACTICAL EXAM

7
It is taken by the concerned lecturer of the batch and by an external examiner. In this exam, the
student needs to perform the experiment allotted at the time of the examination; a sheet will be
given to the student in which some details asked by the examiner need to be written, and at the
last, viva will be taken by the external examiner.

MARKING SCHEME FOR THIS EXAM IS:

Total Marks: 60

Division of 60 marks is as follows

1. Sheet filled by the student: 20

2. Viva Voice: 15

3. Experiment performance: 15

4. File submitted: 10

NOTE:

• Internal marks + External marks = Total marks given to the students (40
marks) (60 marks) (100 marks)

• Experiments given to perform can be from any section of the lab.


INTRODUCTION

Database Management System (DBMS)

A database management system (DBMS) is software that controls the storage, organization, and retrieval
of data. Typically, a DBMS has the following elements:

• Kernel code
This code manages memory and storage for the DBMS.
8
• Repository of metadata
This repository is usually called a data dictionary.

• Query language
This language enables applications to access the data.

A database application is a software program that interacts with a database to access and
manipulate data.

Types of Databases with generation:

Database Management Systems (DBMS) can be categorized into different generations based on
their development and features.

Architecture of a Database Management System:

The architecture of a Database Management System (DBMS) typically consists of several


components, including the evaluation engine. Here is a simplified overview of the architecture
of a DBMS with an evaluation engine: 1. User Interface:
- The user interface allows users to interact with the DBMS and perform various operations,
such as querying, data entry, and administration tasks. It can be a command- line interface,
graphical user interface (GUI), or web-based interface.

2. Query Compiler:
- The query compiler receives the user's query and performs the necessary analysis and
transformations to generate an optimized query execution plan. It analyzes the query syntax,

9
checks the query against the database schema, performs query optimization, and generates an
execution plan.

3. Query Optimizer:
- The query optimizer evaluates multiple possible execution plans for a given query and
selects the most efficient plan based on factors like cost estimation, data access paths, join
strategies, and index usage. The goal is to minimize the overall execution time and resource
utilization.

4. Execution Engine:
- The execution engine takes the optimized query execution plan and performs the actual
execution of the query against the database. It consists of several sub-components:

a. Relational Algebra Operators:


- These operators perform operations such as selection (filtering rows),
projection (selecting columns), join (combining data from multiple tables), and
aggregation (e.g., grouping and summarizing data).

b. Data Access Methods:


- The execution engine interacts with the storage layer to access and
manipulate data. It includes components like buffer management, file systems,
and access methods (e.g., B-trees, hash indexes) to efficiently retrieve and store
data on disk or in memory.

c. Transaction Manager:
- The transaction manager ensures the ACID properties of database
transactions (Atomicity, Consistency, Isolation, Durability). It handles
concurrency control, manages transaction boundaries, and ensures data
consistency during transaction execution.

d. Memory Manager:
- The memory manager handles the allocation and deallocation of memory
resources used by the DBMS. It optimizes memory usage to minimize disk I/O
operations and improve overall performance.

e. Error Handling and Logging:


- The execution engine includes mechanisms for error handling and
logging, capturing and reporting errors, and maintaining a transaction log for
recovery purposes.

5. Storage Manager:

10
- The storage manager is responsible for managing the physical storage of data on disk or
other storage devices. It handles tasks such as data organization, file management, disk space
allocation, and I/O operations.

6. Data Dictionary:
- The data dictionary (also called the system catalog) stores metadata about the database,
including the schema definition, data types, constraints, indexes, and other information. It is
used by the DBMS components for query analysis, optimization, and execution.

The evaluation engine, encompassing the query compiler, query optimizer, and execution
engine, plays a crucial role in processing user queries and ensuring efficient execution. It
transforms high-level queries into low-level operations, optimizes their execution, and
coordinates the various components involved in retrieving and manipulating data.

Relational Database Management Systems (RDBMS) Properties:

1. Tabular Structure: RDBMS organizes data into tables or relations, with rows
representing individual records and columns representing attributes or fields. This tabular
structure allows for structured and organized storage of data.

2. ACID Compliance: RDBMS ensures ACID properties for transactions:

11
3. Data Integrity: RDBMS enforces integrity constraints to ensure the accuracy and reliability
of the data. Constraints include primary keys, foreign keys, unique constraints, and check
constraints, which maintain the relationships between tables and prevent inconsistent or
invalid data.

4. Query Language: RDBMS uses SQL (Structured Query Language) as a standardized


language for interacting with the database. SQL provides powerful and flexible querying
capabilities for data retrieval, modification, and manipulation.

5. Relationships and Joins: RDBMS supports relationships between tables through primary
key and foreign key associations. Joins allow for combining data from multiple tables based
on related columns, enabling complex data retrieval and analysis.

6. Data Independence: RDBMS provides logical and physical data independence. Logical data
independence allows applications to be isolated from changes in the database structure,
while physical data independence separates the logical view of data from the physical
storage details.

7. Scalability and Performance: RDBMS can handle large amounts of data and support
highperformance operations. Techniques like indexing, query optimization, and
caching are employed to improve query response times and overall system performance.

8. Security: RDBMS offers built-in security mechanisms to control access to the data. This
includes authentication, authorization, and privileges management to ensure that only
authorized users can access and modify the data.

12
9. Data Backup and Recovery: RDBMS provides mechanisms for data backup and recovery to
protect against data loss or system failures. This includes features like transaction logging,
point-in-time recovery, and database backups.

POPULAR DATABASES TOOLS :-

• DB2
• MySQL
• Maria DB
• Oracle
• PostgreSQL
• SQL Server
• Sybase

Structured Query Language (SQL):

Structured Query Language is a database computer language designed for managing data in
relational database management systems (RDBMS), and originally based upon Relational
Algebra. Its scope includes data query and update, schema creation and modification, and data
access control.
SQL was one of the first languages for Edgar F. Codd's relational model and became the most
widely used language for relational databases.

• IBM developed SQL in mid of 1970’s.


• Oracle incorporated in the year 1979.
• SQL used by IBM/DB2 and DS Database Systems.
• SQL adopted as standard language for RDBS by ASNI in 1989.
Types of SQL Statements

The tables in the following sections provide a functional summary of SQL statements and
are divided into these categories:

• Data Definition Language (DDL) Statements


• Data Manipulation Language (DML) Statements
• Data Control Language (DCL Statements)

Data Types:

13
Data Type Description Example
INT Integer age
INT
VARCHAR(n) Variable-length character string name
VARCHAR(50)
CHAR(n) Fixed-length character string code
CHAR(10)
TEXT Variable-length text description
TEXT
DATE Date birth_date
DATE
TIME Time entry_time
TIME
DATETIME Date and time created_at
DATETIME
BOOLEAN / BOOL Boolean value (0 or 1) is_active
BOOLEAN
DECIMAL(p, s) Fixed-point decimal number price
DECIMAL(8, 2)
FLOAT(p) Floating-point number salary
FLOAT(10)
DOUBLE(p) Double-precision floating-point number distance
DOUBLE(8)
ENUM Enumeration (a list of permitted values) status ENUM('active',
'inactive')
SET Set (a list of permitted values) permissions SET('read',
'write')
BLOB Binary Large Object (for binary data) image
BLOB
JSON JSON data type metadata
JSON

7. INSTRUCTIONS FOR EACH LAB EXPERIMENT

Experiment-1

14
Experiment-1

Aim: Experiments based on DDL commands – CREATE, ALTER, DROP and TRUNCATE.
Tool Used: Maria DB
SYNTAX:
CREATE TABLE table_name
(column1 datatype, column2
datatype, column3 datatype,
);
PART-I: Creation of tables

Table Name: CLIENT_MASTER


Description: Used to store client information.
INPUT QUERY:

CREATE TABLE CLIENT_MASTER (CLIENT_NO CHAR (6),


NAME VARCHAR (20),
ADDRESS1 VARCHAR (30), ADDRESS2 VARCHAR (30),
CITY VARCHAR (15), PINCODE int (8),
STATE VARCHAR (15), BAL_DUE decimal(10, 2));

OUTPUT TABLE:

Table Name: PRODUCT_MASTER


Description: Used to store product information
INPUT QUERY:
CREATE TABLE PRODUCT_MASTER(
PRODUCTION VARCHAR(6),
15
DESCRIPTION VARCHAR(15) , PROFITPERCENT decimal (4,2) ,
UNITMEASURE VARCHAR(10) , QTYONHAND decimal (8) ,
REORDERLVL decimal (8), SELLPRICE decimal (8,2) ,
COSTPRICE decimal (8,2) );

OUTPUT TABLE:

Table Name: SALESMAN_MASTER


Description: Used to store salesman information working

INPUT QUERY:
CREATE TABLE SALESMAN_MASTER(SALESMANNO VARCHAR(6),
SALESMANNAME VARCHAR(220),
ADDRESS1 VARCHAR(30), ADDRESS2 VARCHAR(30),
CITY VARCHAR(20) , PINCODE INT(11) , STATE VARCHAR(20),
SALAMT DECIMAL(8,2) );
OUTPUT TABLE:

16
PART-II: Alter of values into tables

SYNTAX: ALTER COMMAND


ALTER TABLE table_name [ADD COLUMN col_name datatype]
[MODIFY COLUMN col_name datatype]
[DROP COLUMN col_name];

Input Query to add a new Column in CLIENT_MASTER tables;

ALTER TABLE CLIENT_MASTER ADD COLUMN EMAIL VARCHAR(50);

Query to modify data type of BAL_DUE Column in CLIENT_MASTER tables;

ALTER TABLE CLIENT_MASTER MODIFY COLUMN BAL_DUE decimal(10, 3);

17
 Input Query to drop the ADDRESS2 column from SALESMAN_MASTER table;

ALTER TABLE SALESMAN_MASTER DROP COLUMN ADDRESS2;

PART-III: Drop of values into tables

SYNTAX: DROP COMMAND


DROP TABLE table_name;
 Input Query to drop CLIENT_MASTER tables;
DROP TABLE CLIENT_MASTER;

 Input Query to drop PRODUCT_MASTER tables;


DROP TABLE PRODUCT_MASTER;

 Input Query to drop SALESMAN_MASTER tables;


DROP TABLE SALESMAN_MASTER;

PART-IV: Truncate of values into tables


SYNTAX: TRUNCATE COMMAND
TRUNCATE TABLE table_name;

Input Query to Truncate CLIENT_MASTER tables;


TRUNCATE TABLE CLIENT_MASTER;
18
Input Query to Truncate PRODUCT_MASTER tables;
TRUNCATE TABLE PRODUCT_MASTER;

Input Query to Truncate SALESMAN_MASTER tables;


TRUNCATE TABLE SALESMAN_MASTER;

19
PRACTICE QUESTIONS:
1. Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

2. Add a new column; HIREDATE to the existing relation.

3. Change the datatype of JOB_ID from char to varchar2.

4. Change the name of column/field Emp_no to E_no.

20
5. Modify the column width of the job field of emp table

Drop the "Employee" table from the database.

6. Truncate the data from the "Orders" table, keeping the table structure intact.

VIVA - QUESTIONS:

21
Que1. What is a NULL value and how does it differ from a zero value?

Que2. What are SQL Constraints?

Que3. What are different Data Types in SQL?

Que4. What is the difference between CHAR and VARCHAR?

Que 5. What is Difference between NUMBER, INTEGER and INT DataTypes?


Experiment-2

Aim: Apply the integrity constraints like Primary Key, Foreign key, Check, NOT NULL, etc. to the
tables.

Tool Used: Maria DB


Theory and Procedure: In this experiment we will see what constraints for a table are and how these
constraints can be applied to each column /attributes of a table with their role for an attribute.
SQL Constraints:

The following constraints are commonly used in SQL:

• NOT NULL - Ensures that a column cannot have a NULL value


• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition  DEFAULT -
Sets a default value for a column when no value is specified

NOT NULL Constraint:


The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record, or
update a record without adding a value to this field.

The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values when the "Persons" table is created:

CREATE TABLE
Persons ( ID int
NOT NULL,
22
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT
NULL, Age int );

UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a

column or set of columns.


A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
UNIQUE
(ID)
);

PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a database table. Primary keys
must contain UNIQUE values, and cannot contain NULL values.
A table can have only one primary key, which may consist of single or multiple fields.

CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

FOREIGN KEY Constraint


A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in
another table.
The table containing the foreign key is called the child table, and the table containing the
candidate key is called the referenced or parent table.

23
CREATE TABLE Orders ( OrderID
int NOT NULL,
OrderNumber int NOT
NULL, PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.If you
define a CHECK constraint on a single column it allows only certain values for this column.If
you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row

CREATE TABLE
Persons ( ID
int NOT
NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

DEFAULT Constraint
The DEFAULT constraint is used to provide a default value for a column.
The default value will be added to all new records IF no other value is specified

CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

Schema Diagram:

24
Table Creation

CREATE TABLE STUDENT (


USN VARCHAR (10) PRIMARY
KEY, SNAME VARCHAR (25),
ADDRESS VARCHAR (25),
PHONE NUMBER (10),
GENDER CHAR (1));

CREATE TABLE SEMSEC (


SSID VARCHAR (5) PRIMARY
KEY, SEM NUMBER (2), SEC
CHAR (1));

CREATE TABLE
CLASS ( USN
VARCHAR (10),
SSID VARCHAR (5),
PRIMARY KEY (USN,
SSID),
FOREIGN KEY (USN) REFERENCES STUDENT
(USN), FOREIGN KEY (SSID) REFERENCES SEMSEC
(SSID));

CREATE TABLE SUBJECT (


SUBCODE VARCHAR (8),
TITLE VARCHAR (20),
SEM NUMBER (2),
CREDITS NUMBER (2),
PRIMARY KEY

25
(SUBCODE));

CREATE TABLE
IAMARKS ( USN
VARCHAR (10),
SUBCODE VARCHAR (8),
SSID VARCHAR (5),
TEST1 NUMBER (2),
TEST2 NUMBER (2),
TEST3 NUMBER (2),
FINALIA NUMBER (2),
PRIMARY KEY (USN, SUBCODE, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT (USN),
FOREIGN KEY (SUBCODE) REFERENCES SUBJECT (SUBCODE),
FOREIGN KEY (SSID) REFERENCES SEMSEC (SSID));

Table Descriptions DESC


STUDENT;

DESC SEMSEC;

DESC CLASS;

DESC SUBJECT;

26
DESC IAMARKS;

27
PRACTICE QUESTIONS:

Schema Diagram

Consider the schema for Company Database:

Apply the Integrity Constraints on the given schema.

VIVA – QUESTIONS:

Que1. What are different Constraints in SQL?

Que2. What is the purpose of Null Constraint?

Que 3. What is the function of Reference Constraint?

Que 4. What is Index Constraint?

Que 5. What is the purpose of Default Constraint


Experiment-3
Aim: Experiments based on basic DML commands – SELECT, INSERT, UPDATE and DELETE

Tool Used: Maria DB


28
Creation of tables

Table Name: CLIENT_MASTER


Description: Used to store client information.
SAMPLE OUTPUT TABLE:

Column Name Data Type Size Default Attributes


CLIENTNO Varchar2 6
Name Varchar2 20
ADDREESS1 Varchar2 30
ADDREESS2 Varchar2 30
CITY Varchar2 15
PINCODE Varchar2 8
STATE Varchar2 15
BALDUE Number 10.2
Table Name: PRODUCT_MASTER
Description: Used to store product information
SAMPLE OUTPUT TABLE:

Column Name Data Type Size Default Attributes


PRODUCTION Varchar2 6
DESCRIPTION Varchar2 15
PROFITPERCENT Number 4.2
UNITMEASURE Varchar2 10
QTYONHAND Number 8
REORDERLVL Number 8
SELLPRICE Number 8.2
COSTPRICE Number 8.2

PART-I: Insertion of values into tables


29
SYNTAX: INSERT COMMAND
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Data for CLIENT _MASTER table:
INPUT QUERY:
insert into client_master values('C00001','Ivan','','',' Mumbai ','Maharashtra',400054,15000);
insert into client_master values('C00002', MamtaMuzumdar ','','','Madras','Tamil Nadu',780001,0);
insert into client_master values('C00003', ChhayaBankar ','','',' Mumbai
','Maharashtra',400057,5000);
insert into client_master values('C00004',' Ashwini Joshi,'','',' Bangalore ','
Karnataka ', 560001,0);
insert into client_master values('C00005',' Hansel Colaco ','','',' Mumbai ',’ Maharashtra
‘'', 400060,2000);
insert into client_master values('C00006',' Deepak Sharma ','','',' Mangalore ','
Karnataka ', 560050,0);
After executing the above commands you will get following table:

Client No Name City Pin code State Bal Due


C00001 Ivan Mumbai 400054 Maharashtra 15000
C00002 MamtaMuzumdar Madras 780001 Tamil Nadu 0
C00003 ChhayaBankar Mumbai 400057 Maharashtra 5000
C00004 Ashwini Joshi Bangalore 560001 Karnataka 0
C00005 Hansel Colaco Mumbai 400060 Maharashtra 2000
C00006 Deepak Sharma Mangalore 560050 Karnataka 0

INPUT QUERY:
insert into product_master values('P00001',' T-Shirts ',5,'Piece',200,50,5350,250); insert into
product_master values('P0345',' Shirts ',6,'Piece',150,50,500,350);
insert into product_master values('P06734',' Cotton Jeans ',5,'Piece',100,20,600,450); insert
into product_master values('P07865',' Jeans ',5,'Piece',100,20,750,500); insert into
product_master values('P07868','Trousers',2,'Piece',150,50,850,550); insert into
product_master values('P07885',' Pull Overs ',2.5,'Piece',80,30,700,450); insert into
product_master values('P07965',' Denim Shirts ',4,'Piece',100,40,350,250); insert into
product_master values('P07975',' Lycra Tops’,5,'Piece',70,30,300,175); insert into
product_master values('P08865',' Skirts ',5,'Piece',75,30,450,300);

After executing the above commands you will get following table:

Product Description Profit Unit Qty On Reorder Sell Price Cost


No Percent Measure Hand Lvl Price
P00001 T-Shirts 5 Piece 200 50 350 250
P0345 Shirts 6 Piece 150 50 500 350
P06734 Cotton 5 Piece 100 20 600 450

30
Jeans
P07865 Jeans 5 Piece 100 20 750 500
P07868 Trousers 2 Piece 150 50 850 550
P07885 Pull Overs 2.5 Piece 80 30 700 450
P07965 Denim 4 Piece 100 40 350 250
Shirts
P07975 Lycra Tops 5 Piece 70 30 300 175
P08865 Skirts 5 Piece 75 30 450 300

PART-II: In this experiment we will be focusing on SELECT command which comes under
DDL and WHERE clause.

SYNTAX: SELECT COMMAND


SELECT column1,
column2, ...
FROM
table_name; OR
SELECT * FROM
table_name;

SYNTAX : WHERE CLAUSE


SELECT column1, column2, ...
FROM table_name
WHERE condition;

Client No Name City Pin code State Bal Due


C00001 Ivan Mumbai 400054 Maharashtra 15000
C00002 MamtaMuzumdar Madras 780001 Tamil Nadu 0
C00003 ChhayaBankar Mumbai 400057 Maharashtra 5000
C00004 Ashwini Joshi Bangalore 560001 Karnataka 0
C00005 Hansel Colaco Mumbai 400060 Maharashtra 2000
C00006 Deepak Sharma Mangalore 560050 Karnataka 0

a. Find out the names of all the clients.


INPUT QUERY: SELECT NAME FROM CLIENT_MASTER;

SAMPLE OUTPUT DATA:

Name
Ivan
MamtaMuzumdar
ChhayaBankar
Ashwini Joshi

31
Hansel Colaco
Deepak Sharma

b. Retrieve the entire contents of the Client_Master table.


INPUT QUERY: SELECT * FROM CLIENT_MASTER;

SAMPLE OUTPUT DATA:


Client Name City Pin State Bal
No code Due
C00001 Ivan Mumbai 400054 Maharashtra 15000
C00002 MamtaMuzumdar Madras 780001 Tamil Nadu 0
C00003 ChhayaBankar Mumbai 400057 Maharashtra 5000
C00004 Ashwini Joshi Bangalore 560001 Karnataka 0
C00005 Hansel Colaco Mumbai 400060 Maharashtra 2000
C00006 Deepak Sharma Mangalore 560050 Karnataka 0

c. Retrieve the list of names, city and the state of all the clients.
INPUT QUERY: SELECT NAME, CITY, STATE FROM CLIENT_MASTER;

SAMPLE OUTPUT DATA:

Name City State


Ivan Mumbai Maharashtra
MamtaMuzumdar Madras Tamil Nadu
ChhayaBankar Mumbai Maharashtra
Ashwini Joshi Bangalore Karnataka
Hansel Colaco Mumbai Maharashtra
Deepak Sharma Mangalore Karnataka

d. Find names of client from client-master whose BalDue is`0’.

INPUT QUERY: SELECT NAME FROM CLIENT_MASTER WHERE BAL_DUE=0

SAMPLE OUTPUT DATA:

Name
MamtaMuzumdar
Ashwini Joshi
Deepak Sharma
32
e.List all the clients who are located in Mumbai.
INPUT QUERY: SELECT NAME FROM CLIENT_MASTER WHERE CITY = ‘Mumbai’;

SAMPLE OUTPUT DATA:

Name
ChhayaBankar
Hansel Colaco

PART-III: In this experiment we will be focusing on commands like update and delete
commands which comes under DML .We will be applying these commands on records we
already created in experiment 1.

SYNTAX: UPDATE

UPDATE table_name
SET column1 = value1, column2 =
value2, WHERE condition;

SYNTAX: DELETE

DELETE FROM table_name


WHERE condition;

Data for CLIENT _MASTER table:

Client No Name City Pin code State Bal Due


C00001 Ivan Mumbai 400054 Maharashtra 15000
C00002 MamtaMuzumdar Madras 780001 Tamil Nadu 0
C00003 ChhayaBankar Mumbai 400057 Maharashtra 5000
C00004 Ashwini Joshi Bangalore 560001 Karnataka 0
C00005 Hansel Colaco Mumbai 400060 Maharashtra 2000
C00006 Deepak Sharma Mangalore 560050 Karnataka 0
a. Change the city of ClientNo `C00005’ to `Bangalore’

INPUT QUERY: update client_master set city='Bangalore' where client_no='C00005';

SAMPLE OUTPUT DATA:

Client No City
33
C00005 Bangalore

b. Change the BalDue of ClientNo `C00001’ to Rs. 1000.


INPUT QUERY: update client_master
set bal_due=1000
where client_no='C00001';

SAMPLE OUTPUT DATA:

Client No Bal Due


C00001 1000

Data for PRODUCT_MASTER table:

Product Description Profit Unit Qty On Reorder Sell Price Cost


No Percent Measure Hand Lvl Price
P00001 T-Shirts 5 Piece 200 50 350 250
P0345 Shirts 6 Piece 150 50 500 350
P06734 Cotton 5 Piece 100 20 600 450
Jeans
P07865 Jeans 5 Piece 100 20 750 500
P07868 Trousers 2 Piece 150 50 850 550
P07885 Pull Overs 2.5 Piece 80 30 700 450
P07965 Denim 4 Piece 100 40 350 250
Shirts
P07975 Lycra Tops 5 Piece 70 30 300 175
P08865 Skirts 5 Piece 75 30 450 300
c.Change the cost price of `Trousers’ to Rs. 950.00.
INPUT QUERY: update product_master set
cost_price=950 where
description='Trousers'

SAMPLE OUTPUT DATA:

Product Description Profit Unit Qty On Reorder Sell Cost


No Percent Measure Hand Lvl Price Price
P07868 Trousers 2 Piece 150 50 850 950

34
 In same Manner values can be inserted into SALESMAN_MASTER table :

SalesmanNo Name Address1 Address2 City Pin Code State


S00001 Aman A/14 Worli Mumbai 400002 Maharashtra
S00002 Omkar 65 Nariman Mumbai 400001 Maharashtra
S00003 Raj 7 Bandra Mumbai 400032 Maharashtra
S00004 Ashish A/5 Juhu Mumbai 400044 Maharashtra

Salesman No Sal Amt Tgt To Get YtdSales Remarks


S00001 3000 100 50 Good
S00002 3000 200 100 Good
S00003 3000 200 100 Good
S00004 3500 200 150 Good

d. Delete all salesmen from the Salesman_Master whose salaries are equal to Rs. 3500.
INPUT QUERY: delete salesmen from salesmen_master where salary='3500';

SAMPLE OUTPUT DATA: It will delete all the salemen from salesmen_master table where
salary od salemen is 3500.

e. Delete all product from Product_Master where the quantity on hand us equal to 100.
INPUT QUERY: Similar to the one above.
SAMPLE OUTPUT DATA: It will delete all the products from Product_master table where
quantity on hand is 100

f. Delete from Client_Master where the column state holds the value “Tamil Nadu”.
INPUT QUERY: Similar to the one above.

SAMPLE OUTPUT DATA: It will delete from Client_master table where state holds “Tamil
Nadu”.

35
PRACTICE QUESTIONS:

Create a table EMPLOYEE with following schema:


(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

Write SQL queries for following question:

1. Insert aleast 5 rows in the table.

2. Display all the information of EMP table.

3. Display the record of each employee who works in department D10.

4. Update the city of Emp_no-12 with current city as Nagpur.

5. Display the details of Employee who works in department MECH.

6. Delete the email_id of employee James.

7. Display the complete record of employees working in SALES Department

VIVA- QUESTIONS:

Que1. What is the use of SELECT command?

Que2. What is the purpose of WHERE clause?

Ques3. Which language supports SELECT command?

Que4. How to select entire content of a table.

Que5. What are different DML commands?

Que6. What is the purpose of DELETE command?

Que7. What is difference between ALTER and UPDATE commands?

36
Experiment-4

Aim: Write the queries for implementing Built-in functions, GROUP BY, HAVING and ORDER BY.
Tool Used: Maria DB

PART-I : In this experiment we will be working on Built-in functions

MIN() Syntax: The MIN() function returns the smallest value of the selected column.
SELECT
MIN(column_
name) FROM
table_name
WHERE
condition;
Example: SELECT MIN (Sal) FROM emp;
MAX() Syntax: The MAX() function returns the largest value of the selected column.
SELECT
MAX(column
_name)
FROM
table_name
WHERE
condition;
Example: SELECT MAX (Sal) FROM emp;
COUNT() Syntax: The COUNT() function returns the number of rows that matches a specified
criteria.
SELECT
COUNT(column_n
ame) FROM
table_name
WHERE
condition;
Example: SELECT COUNT (Sal) FROM emp;
AVG() Syntax: The AVG() function returns the average value of a numeric column.
SELECT
AVG(column_
name) FROM
table_name
WHERE
condition;
Example: Select AVG (10, 15, 30) FROM DUAL;
SUM() Syntax: The SUM() function returns the total sum of a numeric column.

37
SELECT
SUM(column_
name) FROM
table_name
WHERE
condition;
Example: SELECT SUM (Sal) From emp;

PART-II : In this experiment we will be working on clauses like HAVING, GROUP BY and
ORDER BY to be applied on a table .

GROUP BY: The GROUP BY statement is often used with aggregate functions (COUNT, MAX,
MIN, SUM, AVG) to group the result-set by one or more columns.
SELECT column_name(s)
FROM
table_name WHERE
condition
GROUP BY column_name(s)
ORDER BY column_name(s);

A) The following SQL statement lists the number of customers in each country:

SQL> SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country;

B) The following SQL statement lists the number of customers in each country, sorted high to low:

SELECT COUNT(CustomerID),

38
Country FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

HAVING clause: The HAVING clause was added to SQL because the WHERE
keyword could not be used with aggregate functions. Syntax: SELECT
column_name(s) FROM
table_name WHERE
condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

A) The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:

SELECT COUNT(CustomerID),
Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5 ;

B) The following SQL statement lists the number of customers in each country, sorted high to
low (Only include countries with more than 5 customers):

SELECT COUNT(CustomerID),
Country FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID)
DESC;
Now some Queries using the above clauses:

Sales:
product_id sales_date quantity_sold
1 2023-01- 10
01
1 2023-01- 15
02
2 2023-01- 5
01
2 2023-01- 20
02
39
3 2023-01- 8
01
3 2023-01- 12
02

1. Count the number of sales for each product: SELECT product_id, COUNT(*) AS sales_count FROM
Sales GROUP BY product_id;

Output:

product_id Sales_count
1 2
2 2
3 2

2. Calculate the total quantity sold for each product:


SELECT product_id, SUM(quantity_sold) AS
total_quantity_sold FROM Sales GROUP BY
product_id;

Output:

product_id total_quantity_sold
1 25
2 25
3 20

3. Find products that have sold more than 20 units:


SELECT product_id, SUM(quantity_sold) AS
total_quantity_sold FROM Sales GROUP BY
product_id
HAVING SUM(quantity_sold) > 20;

product_id total_quantity_sold
1 25
2 25

40
4. Find products with an average sales quantity greater than 10 units:
SELECT product_id, AVG(quantity_sold) AS avg_quantity_sold
FROM Sales
GROUP BY product_id
HAVING AVG(quantity_sold) > 10;

product_id avg_quantity_sold
1 12.5
2 12.5
3 10

ORDER BY:

This query is used to display a selected set of fields from a relation in an ordered manner base on some
field.

Syntax: SELECT <set of fields> FROM <relation_name> ORDER BY <field_name>;

Example: SQL> SELECT empno, ename, job FROM emp ORDER BY job;

41
PRACTICE QUESTIONS:

Schema:

Sales

product_id sales_date quantity_sold

1. Calculate the total quantity sold for each product, but only show products with a total quantity
sold greater than or equal to 25.

2. Count the number of sales for each product and sales date, but only show those with more than
one sale on any date.

3. Find products that have never sold more than 10 units in a single sale.

4. Calculate the total quantity sold for each product and show only those with an average quantity
sold less than or equal to 15 units.

VIVA – QUESTIONS:

Que1. Explain HAVING and GROUPBY clause.

Que2. What are the syntax of HAVING clause?

Que3. What is the Syntax of GROUPBY clause?

Que4. Difference between HAVING AND WHERE clauses.

Que5. Difference between ORDERBY and GROUPBY clause.


Experiment- 5

Aim: Write the queries to implement the joins


Tool Used: Maria DB
Theory and Procedure: Sql joins are used to fetch/retrieve data from two or more data
tables, based on a join condition. A join condition is a relationship among some columns in
the data tables that take part in Sql join. Basically data tables are related to each other with
keys. We use these keys relationship in sql joins.

Types of Joins

42
In Sql Server we have only three types of joins. Using these joins we fetch the data from multiple
tables based on condition.

Inner Join

Inner join returns only those records/rows that match/exists in both the tables. Syntax for Inner
Join is as

Select * from table_1 as


t1 inner join table_2 as
t2 on t1.IDcol=t2.IDcol

Outer Join
We have three types of Outer Join.
Left Outer Join
Left outer join returns all records/rows from left table and from right table returns only
matched records. If there are no columns matching in the right table, it returns NULL
values. Syntax for Left outer Join is as :
Select * from table_1 as t1 left outer join table_2 as t2 on t1.IDcol=t2.IDcol

Right Outer Join

Right outer join returns all records/rows from right table and from left table returns only
matched records. If there are no columns matching in the left table, it returns NULL
values. Syntax for right outer Join is as :

43
Select * from
table_1 as t1 right
outer join table_2 as
t2 on
t1.IDcol=t2.IDcol

Full Outer Join

Full outer join combines left outer join and right outer join. This join returns all
records/rows from both the tables.If there are no columns matching in the both tables, it
returns NULL values. Syntax for full outer Join is as :
Select * from table_1 as t1
full outer join table_2 as t2 on
t1.IDcol=t2.IDcol

Cross Join

Cross join is a cartesian join means cartesian product of both the tables. This join does not
need any condition to join two tables. This join returns records/rows that are
multiplication of record number from both the tables means e ach row on left table will
related to each row of right table. Syntax for right outer Join is as :
Select *
from table_1
cross join
table_2

Self-Join

Self-join is used to join a database table to itself, particularly when the table has a Foreign
key that references its own Primary Key. Basically we have only three types of joins :
Inner join, Outer join and Cross join. We use any of these three JOINS to join a table to
itself. Hence Self join is not a type of Sql join.

44
Next we will solve some Queries which uses above different types of JOIN operations. Customer:

Customer_id Customer_Name Email


1 John Smith [email protected]
2 Alice Johnson [email protected]
3 Bob Brown [email protected]

Order:

Order_id Customer_id Order_Date Total_Amount


101 1 2023-01-01 100.00
102 2 2023-01-02 50.00
103 1 2023-01-03 75.00
104 3 2023-01-04 120.00

Queries:
1. INNER JOIN to Retrieve Customer Orders with Customer Details:

SELECT O.order_id, C.customer_name, O.order_date,


O.total_amount FROM Orders O
INNER JOIN Customers C ON O.customer_id = C.customer_id;

2. LEFT JOIN to Retrieve All Customers and Their Orders (Including Customers with No
Orders):

SELECT C.customer_name, O.order_id, O.order_date,


O.total_amount FROM Customers C

45
LEFT JOIN Orders O ON C.customer_id = O.customer_id;

3. RIGHT JOIN to Retrieve Orders and Their Associated Customers:

SELECT C.customer_name, O.order_id, O.order_date,


O.total_amount FROM Customers C
RIGHT JOIN Orders O ON C.customer_id = O.customer_id;

4. SELF JOIN to Find Customers with the Same Email Address:


SELECT C1.customer_name, C2.customer_name AS other_customer_name,
C1.email FROM Customers C1
INNER JOIN Customers C2 ON C1.email = C2.email AND C1.customer_id <> C2.customer_id;

5. Cross Join Between Orders and Customers:

SELECT * FROM
46
Orders CROSS JOIN
Customers;

47
; PRACTICE
QUESTIONS:

Consider the following schema:

Sailors (sid, sname, rating, age)


Boats (bid, bname, color)
Reserves (sid, bid, day(date))

1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the same day.
6. Find the ids of sailors who have reserved a red boat or a green boat.
48
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.

VIVA - QUESTIONS:

Que1. What is a JOIN Operation?

Que2. Difference between JOIN and PRODUCT operation?

Que3. What are different types of JOIN Operations?

Que4. Difference between RIGHT OUTER and LEFT OUTER join?

Que5. What is an INNER join?


Experiment-6

Aim: Write the queries to implement the Subqueries.

Tool Used: Maria DB

Theory:

SUBQUERIES: The query within another is known as a sub query. A statement containing sub query is
called parent statement. The rows returned by sub query are used by the parent statement or in other
words A subquery is a SELECT statement that is embedded in a clause of another SELECT statement You
can place the subquery in a number of SQL clauses:

• WHERE clause
• HAVING clause
• FROM clause
• OPERATORS( IN.ANY,ALL,<,>,>=,<= etc.)
Types
1. Sub queries that return several values
Sub queries can also return more than one value. Such results should be made use along with the operators in
and any.

2. Multiple queries
49
Here more than one sub query is used. These multiple sub queries are combined by means of ‘and’ & ‘or’
keywords.

3. Correlated sub query

A sub query is evaluated once for the entire parent statement whereas a correlated Sub query is evaluated once per
row processed by the parent statement.

Queries: 10 queries to implement subqueries in SQL on the student database.

Student Database

Student_name Student_id subject score City


Ram S1 Hindi 80 New York
Sham S2 Sst 99 Atlanta
Aditya S3 math 78 Delhi
Advik S4 Science 78 Hyderabad
Prerna S5 Computer 89 New Jersey
Neetu S6 Biology 90 Calcutta
karuna S7 chemistry 68 Bangalore

Course database

Course_id Course_name department fees


CSC101 Computer science Computer 132000
science
CSC102 AI Computer2 133000
CSC103 Data mining Computer3 132000
CSC104 ECE Electronics 134000
CSC105 EEE Electronics3 134000

50
CSC106 IT Computer4 135000
CSC107 Mechanical mech 123000

Registration database

Student_id Course_id
S1 CSC101
S2 CSC102
S3 CSC103
S4 CSC104
S5 CSC105
S6 CSC106
S7 CSC107

1. Find all students who have scored higher than the average score in a specific subject:
SELECT
student_name
FROM students
WHERE score > (SELECT AVG(score) FROM scores WHERE subject = 'Math'); Output:

2. Get the list of students who have not registered for any course:
SELECT
student_name
FROM students
WHERE student_id NOT IN (SELECT DISTINCT student_id FROM registrations);

PRACTICE QUESTIONS:

1. Retrieve the details of students who have scored the highest marks in each subject.
51
2. Find the courses taken by students from a specific city.
3. Retrieve the names of students who have taken all available courses.
4. Find the courses with the highest enrolment.
5. Get the list of students who have scored lower than the average score in all subjects.
6. Retrieve the names of students who have not registered for a specific course.
7. Find the courses with no registered students.
8. Retrieve the names of students who have registered for all courses in a specific department.

VIVA - QUESTIONS:

1. What is a subquery, and how is it different from a regular query?

2. How can subqueries be used to filter data in a SELECT statement?

3. Explain the difference between a scalar subquery and a multiple-row subquery.

4. What is a correlated subquery, and when would you use it?

5. How can subqueries be used to perform calculations or aggregations?

Experiment- 7

Aim: Write the queries to implement the Set Operations.

52
Tool Used: Maria DB

Theory: Set operations in DBMS are operations that allow you to combine or compare the results of two or more
queries.
1.UNION: Combines results from multiple SELECT statements, removing duplicates, and returns all distinct rows
from each query. Requires the same number of columns with compatible data types.
2.UNION ALL: Similar to UNION but includes duplicate rows in the result set. It returns all rows from each query
without removing duplicates.
3.INTERSECT: Retrieves common rows between SELECT statements, finding the intersection of sets. Requires
matching column count and data types.
4.EXCEPT (or MINUS): Returns rows from the first SELECT statement not found in subsequent SELECT
statement(s). Subtracts rows from the second SELECT(s) from the first SELECT's result.

Student Database
Student_name Student_id subject score City
Ram S1 Hindi 80 New York
Sham S2 Sst 99 Atlanta
Aditya S3 math 78 Delhi
Advik S4 Science 78 Hyderabad
Prerna S5 Computer 89 New Jersey
Neetu S6 Biology 90 Calcutta
karuna S7 chemistry 68 Bangalore

Course database
Course_id Course_name department fees
CSC101 Computer science Computer science 132000
CSC102 AI Computer2 133000
CSC103 Data mining Computer3 132000
CSC104 ECE Electronics 134000
CSC105 EEE Electronics3 134000
CSC106 IT Computer4 135000
CSC107 Mechanical mech 123000

Registration database
Student_id Course_id
S1 CSC101
S2 CSC102
S3 CSC103
S4 CSC104
S5 CSC105
S6 CSC106
S7 CSC107
New_students
Student_name Student_id subject score City
Ram S1 Hindi 80 New York
Sham S2 Sst 99 Atlanta
53
Aditya S3 math 78 Delhi
Advik S4 Science 78 Hyderabad
Prerna S5 Computer 89 New Jersey
Divya S6 SSt 89 Delhi
Dimple S7 maths 89 kerela

Create Table: CREATE TABLE Students ( Student_name VARCHAR(50),Student_id VARCHAR(10),


subject VARCHAR(50),score INT,City VARCHAR(50));

Create Table: CREATE TABLE courses ( course_id VARCHAR(10) PRIMARY KEY,


course_name VARCHAR(100), department VARCHAR(50), fees INT);

Create Table: CREATE TABLE registrations ( student_id VARCHAR(10),


course_id VARCHAR(10),FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (course_id) REFERENCES course(course_id));

Create Table: CREATE TABLE new_students ( student_name VARCHAR(50),


student_id VARCHAR(10) PRIMARY KEY, subject VARCHAR(50), score INT, city VARCHAR(50) );

Insert Records:
INSERT INTO Students (Student_name, Student_id, subject, score, City)
VALUES ('Ram', 'S1', 'Hindi', 80, 'New York'),('Sham', 'S2', 'Sst', 99, 'Atlanta'),
('Aditya', 'S3', 'Math', 78, 'Delhi'), ('Advik', 'S4', 'Science', 78, 'Hyderabad'),
('Prerna', 'S5', 'Computer', 89, 'New Jersey'),('Neetu', 'S6', 'Biology', 90, 'Calcutta'),
('Karuna', 'S7', 'Chemistry', 68, 'Bangalore');

Insert Records:
INSERT INTO courses (course_id, course_name, department, fees) VALUES
('CSC101', 'Computer science', 'Computer science', 132000), ('CSC102', 'AI', 'Computer2', 133000),
('CSC103', 'Data mining', 'Computer3', 132000), ('CSC104', 'ECE', 'Electronics', 134000),
('CSC105', 'EEE', 'Electronics3', 134000), ('CSC106', 'IT', 'Computer4', 135000),
('CSC107', 'Mechanical', 'mech', 123000);

Insert Records:
INSERT INTO registrations(student_id, course_id)VALUES ('S1', 'CSC101'),('S2', 'CSC102'),
('S3', 'CSC103'),('S4', 'CSC104'),('S5', 'CSC105'),('S6', 'CSC106'),('S7', 'CSC107');

Insert Records:
INSERT INTO new_students (student_name, student_id, subject, score, city)VALUES
('Ram', 'S1', 'Hindi', 80, 'New York'),('Sham', 'S2', 'Sst', 99, 'Atlanta'),
('Aditya', 'S3', 'math', 78, 'Delhi'),('Advik', 'S4', 'Science', 78, 'Hyderabad'),
('Prerna', 'S5', 'Computer', 89, 'New Jersey'),('Divya', 'S6', 'SSt', 89, 'Delhi'),
('Dimple', 'S7', 'maths', 89, 'Kerela');

Queries: Queries to implement set operations in SQL on the student database

54
1. Combine the names of students from the "students" and "new_students" tables without
duplicates:

Input Query : SELECT student_name FROM


students UNION SELECT student_name FROM new_students;
Output:

2.Get the names of students who are present in both the "students" and "new_students" tables:
Input Query : SELECT student_name FROM students INTERSECT
SELECT student_name FROM new_students;
Output:

PRACTICE QUESTIONS:

1.Retrieve a list of student names from the "students" table, excluding those present in the "new_students" table.
Input Query :
Output:

2.Combine the names of students from the "students" and "new_students" tables, including duplicates.

55
Input Query : SELECT student_name FROM studentsUNION ALLSELECT student_name FROM
new_students;
Output:

3.Get the names of students who are either in the "students" table or in the "new_students" table, but not in both.
Input Query :
Output:

4.Retrieve a list of student names who have registered for at least one course from either the "students" or
"new_students" tables.
Input Query :
Output:

5.Combine the student names from the "students" and "new_students" tables, including duplicates, and sort the result
in ascending order.
Input Query :
Output:

6.Retrieve the student names from the "students" table who have not registered for any courses.
Input Query :
Output:

7.Get the names of students who are present in both the "students" table and the "new_students" table, including
56
duplicates.
Input Query :
Output:

VIVA - QUESTIONS:

1. What is the difference between the UNION and UNION ALL operations in DBMS?
2. How does the INTERSECT operation work in DBMS, and what is its purpose?
3. Explain the EXCEPT (or MINUS) operation in DBMS and provide an example.
4. Can you combine multiple set operations in a single query? If so, provide an example.
5. What happens if the SELECT statements in a set operation have different column names or
incompatible data types?

Experiment- 8

Aim: Write the queries to create the views and queries based on views.

Tool Used: Maria DB


Theory and Procedure: A VIEW is a virtual table, through which a selective portion of the
data from one or more tables can be seen. Views do not contain data of their own. They are
used to restrict access to the database or to hide data complexity. A view is stored as a
57
SELECT statement in the database. DML operations on a view like INSERT, UPDATE,
DELETE affects the data in the original table upon which the view is based.

Syntax:
CREATE VIEW view_name
AS SELECT column1,
column2, ... FROM
table_name
WHERE condition;

view_name is the name of the VIEW.


The SELECT statement is used to define the columns and rows that you want to display in
the view.

Example:
SQL> CREATE VIEW employee AS SELECT empno,ename,job FROM EMP
WHERE job = ‘clerk’; SQL>
View created.

SQL> CREATE VIEW all_employee AS SELECT empno,ename,job FROM EMP;


SQL> View created.

58
UPDATING A VIEW : A view can updated by using the following syntax : Syntax :
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM
table_name
WHERE
condition;

Queries: Queries to implement operations on view in SQL on the employee database

1. Count Employees by Job Title:


SELECT e.job, COUNT(*) AS
job_count FROM all_employee e
GROUP BY e.job;

Output:

2. Find Employees with the Same Job Title as John Smith:


SELECT e.empno, e.ename,
e.job FROM all_employee e
WHERE e.job = (SELECT job FROM employee WHERE ename = 'John Smith');

Output:

59
PRACTICE QUESTIONS:

Table: Students

Student ID Student Name Department ID Grade

1 John Doe 1 A

2 Jane Smith 2 B

3 Mike Johnson 1 A-

Table: Departments

Department ID Department Name


1 Computer Science
2 Mathematics
3 Physics

Write an SQL query to create a view named "Student Grades" that retrieves the Student ID, Student
Name, and Grade from the Students table.

Write an SQL query to retrieve the contents of the "Student Grades" view created in the previous question.

Write an SQL query to create a view named "Top Students" that retrieves the Student ID, Student Name,
and Grade of students who have a grade of "A".

Write an SQL query to retrieve the contents of the "Top Students" view created in the previous question.

Write an SQL query to create a view named "Department Summary" that retrieves the Department ID,
Department Name, and the total number of students in each department.

Write an SQL query to retrieve the contents of the "Department Summary" view created in the previous
question.

Write an SQL query to create a view named "Top Scoring Departments" that retrieves the Department ID,
Department Name, and the average grade of students in each department, sorted in descending order by
the average grade.

VIVA - QUESTIONS:

Que1. What is a view?

60
Que2. How we create a view?

Que3. What is the purpose of creating a VIEW?

Que4. What is the syntax of creating a VIEW?

Que5. How many VIEWS can be created for a table?

61
Experiment- 9

Aim: Demonstrate the concept of Control Structures.

Theory:

• The selection structure tests a condition, then executes one sequence of statements instead of
another, depending on whether the condition is true or false. A condition is any variable or
expression that returns a BOOLEAN value (TRUE or FALSE).
• The iteration structure executes a sequence of statements repeatedly as long as a condition holds
true.
• The sequence-structure simply executes a sequence of statements in the order in which they occur.

Conditional Control: IF and CASE Statements

Often, it is necessary to take alternative actions depending on circumstances. The IF statement lets you
execute a sequence of statements conditionally. That is, whether the sequence is executed or not depends
on the value of a condition. There are three forms of IF statements: IF-THEN, IF- THEN-ELSE, and
IFTHEN-ELSIF. The CASE statement is a compact way to evaluate a single condition and choose
between many alternative actions.

IF-THEN Statement:

The simplest form of IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF (not ENDIF), as follows:

IF condition THEN
sequence_of_statements
END IF;

The sequence of statements is executed only if the condition is true. If the condition is false or null, the IF
statement does nothing. In either case, control passes to the next statement. An example follows:

IF sales > quota THEN


compute_bonus(empid);
UPDATE payroll SET pay = pay + bonus WHERE empno =
emp_id; END IF;
You might want to place brief IF statements on a single line, as in

IF x > y THEN high := x; END IF;

IF-THEN-ELSE Statement:

62
The second form of IF statement adds the keyword ELSE followed by an alternative sequence of
statements, as follows:

IF condition THEN
sequence_of_statements1
ELSE
sequence_of_state
ments2 END IF;

The sequence of statements in the ELSE clause is executed only if the condition is false or null. Thus, the
ELSE clause ensures that a sequence of statements is executed. In the following example, the first UPDATE
statement is executed when the condition is true, but the second UPDATE statement is executed when
the condition is false or null:

IF trans_type = 'CR' THEN


UPDATE accounts SET balance = balance + credit
WHERE ... ELSE
UPDATE accounts SET balance = balance - debit WHERE
... END IF;

The THEN and ELSE clauses can include IF statements. That is, IF statements can be nested, as the
following example shows:

IF trans_type = 'CR' THEN


UPDATE accounts SET balance = balance + credit
WHERE ... ELSE
IF new_balance >= minimum_balance THEN
UPDATE accounts SET balance = balance - debit
WHERE ... ELSE
RAISE
insufficient_funds;
END IF;
END IF;

IF-THEN-ELSIF Statement:

Sometimes you want to select an action from several mutually exclusive alternatives. The third form of IF
statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_state
ments3 END IF;

63
If the first condition is false or null, the ELSIF clause tests another condition. An IF statement can have
any number of ELSIF clauses; the final ELSE clause is optional. Conditions are evaluated one by one
from top to bottom. If any condition is true, its associated sequence of statements is executed and control
passes to the next statement. If all conditions are false or null, the sequence in the ELSE clause is
executed. Consider the following example:

BEGIN
...
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus :=
500;
ELSE
bonus :=
100; END
IF;
INSERT INTO payroll VALUES (emp_id, bonus,
...); END;

If the value of sales is larger than 50000, the first and second conditions are true. Nevertheless, bonus is
assigned the proper value of 1500 because the second condition is never tested. When the first condition is
true, its associated statement is executed and control passes to the INSERT statement.

CASE Statement:

Like the IF statement, the CASE statement selects one sequence of statements to execute. However, to
select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. To
compare the IF and CASE statements, consider the following code that outputs descriptions of school
grades:

IF grade = 'A' THEN


dbms_output.put_line('Excellent');
ELSIF grade = 'B' THEN dbms_output.put_line('Very
Good');
ELSIF grade = 'C' THEN
dbms_output.put_line('Go
od'); ELSIF grade = 'D'
THEN
dbms_output. put_line('Fair');
ELSIF grade = 'F' THEN
dbms_output.put_line('Po
or'); ELSE
dbms_output.put_line('No such
grade'); END IF;
64
Notice the five Boolean expressions. In each instance, we test whether the same variable, grade, is equal to
one of five values: 'A', 'B', 'C', 'D', or 'F'. Let us rewrite the preceding code using the CASE statement, as
follows:

CASE grade
WHEN 'A' THEN
dbms_output.put_line('Excellent'); WHEN 'B'
THEN dbms_output.put_line('Very Good');
WHEN 'C' THEN
dbms_output.put_line('Good'); WHEN 'D' THEN
dbms_output.put_line('Fair'); WHEN 'F'
THEN dbms_output.put_line('Poor');
ELSE dbms_output.put_line('No such
grade'); END CASE;

The CASE statement is more readable and more efficient. So, when possible, rewrite lengthy IF-
THENELSIF statements as CASE statements.

The CASE statement begins with the keyword CASE. The keyword is followed by a selector, which is the
variable grade in the last example. The selector expression can be arbitrarily complex. For example, it can
contain function calls. Usually, however, it consists of a single variable. The selector expression is
evaluated only once. The value it yields can have any PL/SQL datatype other than BLOB, BFILE, an
object type, a PL/SQL record, an index-by-table, a varray, or a nested table.

The selector is followed by one or more WHEN clauses, which are checked sequentially. The value of the
selector determines which clause is executed. If the value of the selector equals the value of a WHENclause
expression, that WHEN clause is executed. For instance, in the last example, if grade equals 'C', the program
outputs 'Good'. Execution never falls through; if any WHEN clause is executed, control passes to the next
statement.

The ELSE clause works similarly to the ELSE clause in an IF statement. In the last example, if the grade is
not one of the choices covered by a WHEN clause, the ELSE clause is selected, and the phrase 'No such
grade' is output. The ELSE clause is optional. However, if you omit the ELSE clause, PL/SQL adds the
following implicit ELSE clause:

ELSE RAISE CASE_NOT_FOUND;

If the CASE statement selects the implicit ELSE clause, PL/SQL raises the predefined exception
CASE_NOT_FOUND. So, there is always a default action, even when you omit the ELSE clause.

The keywords END CASE terminate the CASE statement. These two keywords must be separated by a
space. The CASE statement has the following form:

65
[<<label_na
me>>]
CASE
selector
WHEN expression1 THEN
sequence_of_statements1; WHEN expression2 THEN
sequence_of_statements2;
...
WHEN expressionN THEN
sequence_of_statementsN; [ELSE
sequence_of_statementsN+1;]
END CASE [label_name];

Like PL/SQL blocks, CASE statements can be labeled. The label, an undeclared identifier enclosed by
double angle brackets, must appear at the beginning of the CASE statement. Optionally, the label name
can also appear at the end of the CASE statement.

Exceptions raised during the execution of a CASE statement are handled in the usual way. That is, normal
execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram.

PRACTICE QUESTIONS:

1. Write a PL/SQL block that checks if a variable named "age" is greater than or equal to 18. If it is,
display the message "You are eligible for voting."

2. Write a PL/SQL block that checks if a number variable named "score" is greater than 90. If it is,
display the message "Congratulations, you passed!" Otherwise, display the message "Sorry, you
did not pass."

3. Write a PL/SQL block that uses a FOR loop to display the numbers from 1 to 10 on separate lines.

4. Write a PL/SQL block that uses a WHILE loop to display the even numbers between 1 and 20 on
separate lines.

5. Write a PL/SQL block that uses a CASE statement to determine the grade based on a variable named
"percentage." Display the corresponding grade message (e.g., "A", "B", "C", etc.) depending on the
percentage value.

VIVA - QUESTIONS:

1) How many nested IF clauses can be included within an IF clause? ...

66
2) Which structure executes a sequence of statements repeatedly as long as a condition holds true?

3) What is the maximum number of ELSE clauses that can be included in an IF clause that is not
nested?

4) Which statements execute a sequence of statements multiple times?

Experiment- 10

Aim: Demonstrate the concept of Exception Handling.

Theory:

An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides us the
exception block which raises the exception thus helping the programmer to find out the fault and resolve
it.
There are two types of exceptions defined in PL/SQL

1. System defined exceptions.


2. User defined exception.

Syntax to write an exception

WHEN exception THEN


statement;

DECLARE
declarations section;

BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code
*/ END;

67
Note:
When other keyword should be used only at the end of the exception handling block as no exception
handling part present later will get executed as the control will exit from the block after executing the
WHEN OTHERS.
1. System defined exceptions:
These exceptions are predefined in PL/SQL which get raised WHEN certain database
rule is violated.
System-defined exceptions are further divided into two categories:
1. Named system exceptions.
2. Unnamed system exceptions.
3. Named system exceptions: They have a predefined name by the system like
ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the
list is quite big.
So, we will discuss some of the most commonly used exceptions: Let’s create
a table geeks.

create table geeks(g_id int , g_name varchar(20), marks


int); insert into geeks values(1, 'Suraj',100); insert into
geeks values(2, 'Praveen',97); insert into geeks
values(3, 'Jessie', 99);

1. NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement returns no rows. For eg:

68
DECLARE
temp varchar(20);

BEGIN
SELECT g_id into temp from geeks where g_name='GeeksforGeeks';

exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR');
dbms_output.put_line('there is no name as');
dbms_output.put_line('GeeksforGeeks in geeks table');
end;

Output:
ERROR
there is no name as GeeksforGeeks in geeks table

2. TOO_MANY_ROWS: It is raised WHEN a SELECT INTO statement returns more than one
row.

DECLARE
temp varchar(20);

BEGIN

-- raises an exception as SELECT


-- into trying to return too many rows
SELECT g_name into temp from geeks;
dbms_output.put_line(temp);

EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too many rows');

end;
Output:
error trying to SELECT too many rows

3. VALUE_ERROR:This error is raised WHEN a statement is executed that resulted in an


arithmetic, numeric, string, conversion, or constraint error. This error mainly results from
programmer error or invalid data input.
69
DECLARE
temp number;

BEGIN
SELECT g_name into temp from geeks where g_name='Suraj'; dbms_output.put_line('the
g_name is '||temp);

EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
dbms_output.put_line('Change data type of temp to varchar(20)');

END;

Output:
Error
Change data type of temp to varchar(20)

4. ZERO_DIVIDE = raises exception WHEN dividing with zero.


DECLARE
a int:=10;
b int:=0;
answer
int;

BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);

exception
WHEN zero_divide THEN
dbms_output.put_line('dividing by zero please check the values
again'); dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;
Output: dividing by zero please check the
values again the value of a is 10 the
value of b is 0

1. Unnamed system exceptions: Oracle doesn’t provide name for some system exceptions called
unnamed system exceptions. These exceptions don’t occur frequently. These exceptions have

70
two parts code and an associated message. The way to handle to these exceptions is to
assign name to them using Pragma EXCEPTION_INIT Syntax:
 PRAGMA EXCEPTION_INIT(exception_name, -error_number);

error_number are pre-defined and have negative integer range from -20000 to - 20999.
Example:

DECLARE
exp exception;
pragma exception_init (exp, -20015);

n int:=10;

BEGIN
FOR i IN 1..n LOOP
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE exp;
END IF;
END LOOP;

EXCEPTION
WHEN exp THEN
dbms_output.put_line('Welcome to GeeksforGeeks');

END;
Output:
1
4
9
16
25
36
Welcome to GeeksforGeeks

2. User defined exceptions:


This type of users can create their own exceptions according to the need and to raise
these exceptions explicitly raise command is used. Example:
 Divide non-negative integer x by y such that the result is greater than or equal to 1. From the
given question we can conclude that there exist two exceptions
1. Division be zero.
2. If result is greater than or equal to 1 means y is less than or equal to x.
71
DECLARE
x int:=&x; /*taking value at run time*/ y int:=&y;
div_r float;
exp1 EXCEPTION; exp2 EXCEPTION;

BEGIN

IF y=0 then
raise exp1;

ELSEIF y > x then


raise exp2;

ELSE
div_r:= x / y; dbms_output.put_line('the
result is '||div_r);

END IF;

EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');

WHEN exp2 THEN


dbms_output.put_line('Error');
dbms_output.put_line('y is greater than x please check the input');

END;
Input 1:
x = 20
y = 10

Output:
the result is 2

Input 2:
x = 20
y=0

Output:
Error
division by zero not allowed

72
Input 3:
x=20 y =
30

Output:
<.em>
Error
y is greater than x please check the input
3. RAISE_APPLICATION_ERROR:
It is used to display user-defined error messages with error number whose range is in between
20000 and -20999. When RAISE_APPLICATION_ERROR executes it returns error message and
error code which looks same as Oracle built-in error. Example:
DECLARE myex
EXCEPTION; n
NUMBER :=10;

BEGIN
FOR i IN 1..n LOOP
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE myex;
END IF;
END LOOP;

EXCEPTION
WHEN myex THEN
RAISE_APPLICATION_ERROR(-20015, 'Welcome to GeeksForGeeks');

END;
Output:
Error report:
ORA-20015: Welcome to
GeeksForGeeks ORA-06512: at
line 13

1
4
9
16
25
36

Note: The output is based on Oracle Sql developer, the output order might change IF you’re
running this code somewhere else.

73
Scope rules in exception handling:
• We can’t DECLARE an exception twice but we can
DECLARE the same exception in two different blocks.
• Exceptions DECLARED inside a block are local to that block and global to all its subblocks.
As a block can reference only local or global exceptions, enclosing blocks cannot reference
exceptions DECLARED in a sub-block.
If we REDECLARE a global exception in a sub-block, the local declaration prevails i.e., the scope of
local is more.

Example:
DECLARE
GeeksforGeeks
EXCEPTION; age
NUMBER:=16; BEGIN

-- sub-block BEGINs
DECLARE

-- this declaration prevails


GeeksforGeeks EXCEPTION;
age NUMBER:=22;

BEGIN
IF age > 16 THEN
RAISE GeeksforGeeks; /* this is not handled*/
END IF;

END;
-- sub-block ends

EXCEPTION
-- Does not handle raised exception
WHEN GeeksforGeeks THEN
DBMS_OUTPUT.PUT_LINE
('Handling GeeksforGeeks exception.');

WHEN OTHERS THEN


DBMS_OUTPUT.PUT_LINE
('Could not recognize exception GeeksforGeeks in this scope.');
END;
Output:
Could not recognize exception GeeksforGeeks in this scope.

Advantages:

74
• Exception handling is very useful for error handling, without it we have to issue the
command at every point to check for execution errors:
Example:
Select ..
.. check for 'no data found'
error Select ..
.. check for 'no data found'
error Select ..
.. check for 'no data found' error
Here we can see that it is not robust as error processing is not separated from normal
processing and IF we miss some line in the code than it may lead to some other kind of error.
• With exception handling we handle errors without writing statements multiple times and we
can even handle different types of errors in one exception block:

Example:
BEGI
N
SEL
EC
T ...
SELECT ...
SELECT ...
.
.
.
exception
WHEN NO_DATA_FOUND THEN /* catches all 'no data found' errors */
...
WHEN ZERO_DIVIDE THEN /* different types of */
WHEN value_error THEN /* errors handled in same
block */
...

From above code we can conclude that exception handling:

75
1. Improves readability by letting us isolate error-handling routines and thus providing
robustness.
2. Provides reliability, instead of checking for dIFferent types of errors at every point we can
simply write them in exception block and IF error exists exception will be raised thus helping
the programmer to find out the type of error and eventually resolve it.
Uses: One of the real-life uses of exception can be found in online train reservation system. While filling
the station code to book the ticket IF we input wrong code it shows us the exception that the code doesn’t
exist in database.

76
PRACTICE QUESTIONS:

1. Write a PL/SQL block that raises an exception if a variable named "balance" is negative. Handle
the exception by displaying a custom error message.

2. Write a PL/SQL block that includes a division operation. Handle the "ZERO_DIVIDE" exception
using the WHEN OTHERS clause to display a user-friendly message.

3. Define a user-defined exception named "InvalidInputException." Write a PL/SQL block that raises
this exception if a variable named "input" is not within the range of 1 to 100.

4. Define an exception named "CustomException." Associate it with the Oracle error code "ORA-
00001" using the EXCEPTION_INIT pragma. Write a PL/SQL block that handles the "CustomException"
and displays a specific error message for that error code.

5. Write a PL/SQL block that includes a subprogram. Inside the subprogram, raise an exception.
Handle the exception in the main block and display an appropriate message indicating the exception's
occurrence.

VIVA - QUESTIONS:

1. In PL/SQL, a warning or error condition is called an exception.

2. For which Exception, if a SELECT statement attempts to retrieve data based on its conditions, this
exception is raised when no rows satisfy the SELECT criteria?

3. What is the difference between Errors and Exceptions?

4. How do you handle exceptions?

5. How do you differentiate between errors in SQL and PL/SQL?


Experiment- 11

Aim: Demonstrate the concept of Function and Procedures

Theory:

77
Procedures and Functions are the subprograms which can be created and saved in the database as database
objects. They can be called or referred inside the other blocks also.

Terminologies in PL/SQL Subprograms


Before we learn about PL/SQL subprograms, we will discuss the various terminologies that are the part of
these subprograms. Below are the terminologies that we are going to discuss.

Parameter:
The parameter is variable or placeholder of any valid PL/SQL datatype through which the PL/SQL
subprogram exchange the values with the main code. This parameter allows to give input to the
subprograms and to extract from these subprograms.

• These parameters should be defined along with the subprograms at the time of creation.
• These parameters are included in the calling statement of these subprograms to interact the values
with the subprograms.
• The datatype of the parameter in the subprogram and the calling statement should be same.
• The size of the datatype should not mention at the time of parameter declaration, as the size is
dynamic for this type.

Based on their purpose parameters are classified as

1. IN Parameter
2. OUT Parameter
3. IN OUT Parameter

IN Parameter:

• This parameter is used for giving input to the subprograms.


• It is a read-only variable inside the subprograms. Their values cannot be changed inside the
subprogram.
• In the calling statement, these parameters can be a variable or a literal value or an expression, for
example, it could be the arithmetic expression like ‘5*8’ or ‘a/b’ where ‘a’ and ‘b’ are variables. 
By default, the parameters are of IN type.
OUT Parameter:

• This parameter is used for getting output from the subprograms.


• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
• In the calling statement, these parameters should always be a variable to hold the value from the
current subprograms.

IN OUT Parameter:

• This parameter is used for both giving input and for getting output from the subprograms.
• It is a read-write variable inside the subprograms. Their values can be changed inside the
subprograms.
78
• In the calling statement, these parameters should always be a variable to hold the value from the
subprograms.

These parameter type should be mentioned at the time of creating the subprograms.

RETURN
RETURN is the keyword that instructs the compiler to switch the control from the subprogram to the
calling statement. In subprogram RETURN simply means that the control needs to exit from the
subprogram. Once the controller finds RETURN keyword in the subprogram, the code after this will be
skipped.

Normally, parent or main block will call the subprograms, and then the control will shift from those parent
block to the called subprograms. RETURN in the subprogram will return the control back to their parent
block. In the case of functions RETURN statement also returns the value. The datatype of this value is
always mentioned at the time of function declaration. The datatype can be of any valid PL/SQL data type.

What is Procedure in PL/SQL?


A Procedure in PL/SQL is a subprogram unit that consists of a group of PL/SQL statements that can be
called by name. Each procedure in PL/SQL has its own unique name by which it can be referred to and
called. This subprogram unit in the Oracle database is stored as a database object. Note: Subprogram is
nothing but a procedure, and it needs to be created manually as per the requirement. Once created they will
be stored as database objects.

Below are the characteristics of Procedure subprogram unit in PL/SQL:

• Procedures are standalone blocks of a program that can be stored in the database.
• Call to these PLSQL procedures can be made by referring to their name, to execute the PL/SQL
statements.
• It is mainly used to execute a process in PL/SQL.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into Oracle procedure or fetched from the procedure through parameters.
• These parameters should be included in the calling statement.
• A Procedure in SQL can have a RETURN statement to return the control to the calling block, but
it cannot return any values through the RETURN statement.
• Procedures cannot be called directly from SELECT statements. They can be called from another
block or through EXEC keyword.

Syntax:
CREATE OR REPLACE PROCEDURE
<procedure
_n
a
m
e>
(
79
<parameterl IN/OUT <datatype>
..
.
)
[
IS
|
A
S]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;

• CREATE PROCEDURE instructs the compiler to create new procedure in Oracle. Keyword ‘OR
REPLACE’ instructs the compile to replace the existing procedure (if any) with the current one. 
Procedure name should be unique.
• Keyword ‘IS’ will be used, when the stored procedure in Oracle is nested into some other blocks.
If the procedure is standalone then ‘AS’ will be used. Other than this coding standard, both have
the same meaning.

Example1: Creating Procedure and calling it using EXEC

In this example, we are going to create an Oracle procedure that takes the name as input and prints the
welcome message as output. We are going to use EXEC command to call procedure.

CREATE OR REPLACE PROCEDURE welcome_msg (p_name IN


VARCHAR2) IS BEGIN
dbms_output.put_line (‘Welcome '||
p_name); END;
/
EXEC welcome_msg (‘Guru99’);

Code Explanation:

• Code line 1: Creating the procedure with name ‘welcome_msg’ and with one parameter
‘p_name’ of ‘IN’ type.
• Code line 4: Printing the welcome message by concatenating the input name.
• Procedure is compiled successfully.
• Code line 7: Calling the procedure using EXEC command with the parameter ‘Guru99’.
Procedure is executed, and the message is printed out as “Welcome Guru99”.

80
What is Function?
Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique name by
which it can be referred. These are stored as PL/SQL database objects. Below are some of the
characteristics of functions.  Functions are a standalone block that is mainly used for calculation
purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at the time
of creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in functions.
• Function with no DML statements can be directly called in SELECT query whereas the function
with DML operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the parameters.
• These parameters should be included in the calling statement.
• A PLSQL function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with assignment
operator to populate the variables.

Syntax
CREATE OR REPLACE FUNCTION
<procedure
_name> (
<parameterl IN/OUT <datatype>
)
RETURN
<datatype> [
IS | AS ]
<declaration_
part> BEGIN

<executi
on part>
EXCEPT
ION
<exception handling
part> END;

• CREATE FUNCTION instructs the compiler to create a new function. Keyword ‘OR REPLACE’
instructs the compiler to replace the existing function (if any) with the current one.
• The Function name should be unique.
• RETURN datatype should be mentioned.
• Keyword ‘IS’ will be used, when the procedure is nested into some other blocks. If the procedure
is standalone then ‘AS’ will be used. Other than this coding standard, both have the same meaning.

Example1: Creating Function and calling it using Anonymous Block


81
In this program, we are going to create a function that takes the name as input and returns the welcome
message as output. We are going to use anonymous block and select statement to call the function.

CREATE OR REPLACE FUNCTION welcome_msgJune ( p_name IN VARCHAR2) RETURN


VAR.CHAR2 IS
BEGIN
RETURN (‘Welcome ‘||
p_name); END;
/
DE
CL
AR
E
lv_msg
VARCHAR2(250); BEGIN
lv_msg := welcome_msg_func
(‘Guru99’);
dbms_output.put_line(lv_msg);
END;
SELECT welcome_msg_func(‘Guru99:) FROM DUAL;

Code Explanation:

82
• Code line 1: Creating the Oracle function with name ‘welcome_msg_func’ and with one
parameter ‘p_name’ of ‘IN’ type.
• Code line 2: declaring the return type as VARCHAR2
• Code line 5: Returning the concatenated value ‘Welcome’ and the parameter value.
• Code line 8: Anonymous block to call the above function.
• Code line 9: Declaring the variable with datatype same as the return datatype of the function.
• Code line 11: Calling the function and populating the return value to the variable ‘lv_msg’.
• Code line 12: Printing the variable value. The output you will get here is “Welcome Guru99”
• Code line 14: Calling the same function through SELECT statement. The return value is directed
to the standard output directly.

Similarities between Procedure and Function

• Both can be called from other PL/SQL blocks.


• If the exception raised in the subprogram is not handled in the subprogram exception handling
section, then it will propagate to the calling block.
• Both can have as many parameters as required.
• Both are treated as database objects in PL/SQL.

Procedure V/s Function: Key Differences

Procedure Function
 Used mainly to a execute certain process  Used mainly to perform some calculation

 Cannot call in SELECT statement  A Function that contains no DML statemen called
in SELECT statement

 Use OUT parameter to return the value  Use RETURN to return the value

 It is not mandatory to return the value 


It is mandatory to return the value

 RETURN will simply exit the control from 


RETURN will exit the control from subprogra
subprogram. and also returns the value

• Return datatype will not be specified at the  Return datatype is mandatory at the time of time of
creation
creation

83
PRACTICE QUESTIONS:

1. Write a PL/SQL code snippet to create a function named "calculate_area" that accepts the radius of
a circle as a parameter and returns the calculated area of the circle.

2. Write a PL/SQL code snippet to create a procedure named "insert_employee" that inserts a new
employee record into an "Employees" table. The procedure should accept parameters such as employee
name, ID, and department.

3. Create two functions named "calculate_area" that accept different parameters. One function should
calculate the area of a rectangle based on its length and width, while the other function should calculate
the area of a square based on its side length.

4. Create a procedure named "get_employee_name" that accepts an employee ID as input and returns
the corresponding employee name as an OUT parameter.

5. Create a function named "divide_numbers" that accepts two numbers as parameters and returns the
result of dividing the first number by the second number. Handle the "ZERO_DIVIDE" exception and
return NULL if the second number is 0.

VIVA - QUESTIONS:

1. What are subprograms in PL/SQL and what are the advantages of subprograms?

2. What are the types of subprograms in PL/SQL?

3. What is a Stored Procedure in PL/SQL?

4. What is Stored Function?

5. What is the difference between anonymous block and subprograms?

6. What are the modes for passing parameters to stored Procedure or Function?
Experiment- 12

84
Aim: Demonstrate the concept of Triggers
Theory:

PL/SQL:
PL/SQL is a combination of SQL along with the procedural features of programming
languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities
of SQL. PL/SQL is one of three key programming languages embedded in the Oracle Database,
along with SQL itself and Java. This tutorial will give you great understanding on PL/SQL to
proceed with Oracle database and other advanced RDBMS concepts.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database. Following are
certain notable facts about PL/SQL −

• PL/SQL is a completely portable, high-performance transaction-processing language.


• PL/SQL provides a built-in, interpreted and OS
independent programming environment.

• PL/SQL can also directly be called from the command-line SQL*Plus interface.
• Direct call can also be made from external programming language calls to database.
• PL/SQL's general syntax is based on that of ADA and Pascal programming language.

• Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.

Features of PL/SQL
PL/SQL has the following features −

• PL/SQL is tightly integrated with SQL.


• It offers extensive error checking.
• It offers numerous data types.
• It offers a variety of programming structures.
• It supports structured programming through functions and procedures.
• It supports object-oriented programming.
• It supports the development of web applications and server pages.

Advantages of PL/SQL
PL/SQL has the following advantages −
• SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and
transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL
statements in PL/SQL blocks.
• PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
85
• PL/SQL gives high productivity to programmers as it can query, transform, and update data
in a database.
• PL/SQL saves time on design and debugging by strong features, such as exception
handling, encapsulation, data hiding, and object-oriented data types.
• Applications written in PL/SQL are fully portable.

• PL/SQL provides high security level.


• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for developing Web Applications and Server Pages.

TRIGGERS: Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to any of the
following events −

• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)

• A database definition (DDL) statement (CREATE, ALTER, or DROP).

• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or


SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is associated.

Benefits of Triggers

Triggers can be written for the following purposes −

• Generating some derived column values automatically


• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions CreatingTriggers
The syntax for creating a trigger is −

86
CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

[OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n]

[FOR EACH ROW]

WHEN (condition)

DECLARE

Declaration-statements

BEGIN

Executable-statements

EXCEPTION

Exception-handling-statements

END;

Where,

• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an


existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed.
The INSTEAD OF clause is used for creating trigger on a view.
• {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the trigger.
• [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for
various DML statements, such as INSERT, UPDATE, and DELETE.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed
for each row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger would fire.
This clause is valid only for row-level triggers.

87
PRACTICE QUESTIONS:

1. Write a PL/SQL trigger that fires before inserting a new record into a table named
"Employees." The trigger should automatically set the "created_date" column to the current date
and time.

2. Create a PL/SQL trigger that fires after updating the "Salary" column in a table named
"Employees." The trigger should log the old and new values of the salary in an audit table named
"Salary_Audit."

3. Write a PL/SQL trigger that fires instead of deleting a record from a table named "Orders."
The trigger should perform additional validation checks and prevent the deletion if specific
conditions are not met.

4. Create a PL/SQL compound trigger that fires before and after updating the "Quantity"
column in a table named "Inventory." The trigger should log the old and new values of the quantity
in separate audit tables named "Quantity_Before_Update" and "Quantity_After_Update."

5. Write a PL/SQL trigger that fires after inserting, updating, or deleting records from both the
"Customers" and "Orders" tables. The trigger should perform a specific action whenever a change
occurs in either of the tables.

VIVA - QUESTIONS:

1. What is a triggering event?

2. Types of trigger based on triggering event?

3. What are some use cases of Triggers?

4. Difference between Triggers and Constraints?

5. What is a DML Trigger?

LIST OF EXPERIMENTS (beyond syllabus) Experiment 1

88
Aim: The Institute offers multiple B. Tech Courses. Students can take admission in any Course offered by
the Institute. Multiple subjects are taught in each branch. The institute has a Director and Hod of each B.
Tech Course. The HoD of another branch may be given additional responsibility to take charge of one
more department for a limited period in the absence of Hod of that branch. Faculties recruited in each B.
Tech Course can teach only a single same subject to students of different B.Tech Courses. For each
subject, there is a faculty coordinator responsible for coordinating all the faculties teaching the same
subject. A batch of 20 students is assigned a faculty mentor. The mentor takes counsellor meetings twice a
month.
Data to be recorded in the database include:
Student – enrollment no, name, data of birth, address, contact no, email – id, qualifying exam
rank, Course
Faculty – Faculty name, contact no, email id, course
Parents data – Parents name, contact no, email id, Profession

Draw the ER diagram (Conceptual design) of the given problem statement. (CO1)

Entity-Relationship Diagram (ERD) for the given problem statement:

Entities and Attributes


1. Student:
o EnrollmentNo (Primary Key) o Name
o DateOfBirth o Address o ContactNo o EmailID o QualifyingExamRank o CourseID
(Foreign Key)
2. Faculty:
o FacultyID (Primary Key) o Name o ContactNo o EmailID
o CourseID (Foreign Key)
3. Course:
o CourseID (Primary Key) o CourseName
o HoDID (Foreign Key to FacultyID)
4. Subject:
o SubjectID (Primary Key)
o SubjectName
o CoordinatorID (Foreign Key to FacultyID)
5. Batch:
o BatchID (Primary Key)
o MentorID (Foreign Key to FacultyID)
6. Director:
o DirectorID (Primary Key) o Name o ContactNo o EmailID
7. Parents:
o ParentID (Primary Key)
o ParentName o ContactNo o EmailID o Profession o StudentID (Foreign Key)

89
Relationships
1. Student - Course:
o A student enrolls in one course, but a course can have multiple students. o (1:N
relationship)
2. Course - Faculty:
o A course has multiple faculties assigned, and a faculty teaches one subject in one or more
courses.
o (1:N relationship)
3. Course - HoD:
o Each course has one HoD, but a faculty can be an HoD for more than one course
temporarily. o (1:1 relationship)
4. Subject - Faculty: o A subject has multiple faculties teaching it, but each subject has one coordinator. o
(1:N relationship)
5. Batch - Student: o A batch consists of multiple students, but a student belongs to one batch. o (1:N
relationship)
6. Batch - Mentor (Faculty):
o Each batch is assigned a mentor, but a faculty member can mentor multiple batches.
o (1:N relationship)
7. Director:
o The institute has one Director. o (1:1 relationship)
8. Parents - Student: o Each student is associated with their parents. o (1:1 relationship)

Experiment 2

Aim: To demonstrate a connection to a MariaDB database using the following languages: C, Java and
Python

The MariaDB database has been deployed on another virtual machine in the same intranet in advance,
and the database username and password for remote connection have been created. Here, assume that
our new username is proxysql and the password is proxypassword. Use the default port number 3306 for
the port number.

C:

First, install the connector library

1. sudo apt install libmariadbclient-dev

Then, create a new C language file version.c and enter the following code:
#include<mysql.h>

90
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char **argv)


{ printf("MySQL client version: %s\
n", mysql_get_client_info());
exit(0); }
Compile and execute:

1 gcc version.c -o version `mysql_config --cflags --libs`


2 ./version
You can see the output as follows:
MySQL client version: 10.1.47-MariaDB
It shows that the client version can be printed out successfully.
Next, we create a new createdb.c file, enter the following code, test the function of creating a database
#include<mysql.h>
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
MYSQL *con = mysql_init(NULL);

if (con == NULL)
{ fprintf(stderr, "%s\n",
mysql_error(con));
exit(1);
}

if (mysql_real_connect(con, "192.168.0.204", "proxysql",


"proxypassword", NULL, 0, NULL, 0) == NULL)
{ fprintf(stderr, "%s\n",
mysql_error(con)); mysql_close(con);
exit(1);
}

if (mysql_query(con, "CREATE DATABASE testdb"))


{ fprintf(stderr, "%s\n",
mysql_error(con)); mysql_close(con);
exit(1);
}

mysql_close(co
n); exit(0);
91
}

Compile and execute

1 gcc createdb.c -o createdb `mysql_config --cflags --libs`


2 ./createdb
Next, we create a new testdb.cfile, enter the following code, and test the functions of adding
new tables, inserting records, querying tables, associating queries, updating, deleting records,
and deleting tables.
#include<mysql.h
>
#include<stdio.h>
#include<stdlib.h>

void finish_with_error(MYSQL *con)


{ fprintf(stderr, "%s\
n",
mysql_error(con));
mysql_close(con);
exit(1);
}

int main(int argc, char **argv)


{
MYSQL *con = mysql_init(NULL);

if (con == NULL)
{ fprintf(stderr, "%s\n",
mysql_error(con));
exit(1);
}

if (mysql_real_connect(con, "192.168.0.204", "proxysql", "proxypassword",


"testdb", 0, NULL, 0) == NULL)
{ finish_with_error(con);
}

if (mysql_query(con, "DROP TABLE IF EXISTS cars;"))


{ finish_with_error(con);
}
if (mysql_query(con, "DROP TABLE IF EXISTS people;"))
{ finish_with_error(con);
}
if (mysql_query(con, "CREATE TABLE cars(id INT PRIMARY
92
KEY AUTO_INCREMENT, name VARCHAR(255), price
INT)"))
{ finish_with_error(con);
}
if (mysql_query(con, "CREATE TABLE people(id INT, name
VARCHAR(255), car_id INT)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(1,'Audi',52642)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(2,'Mercedes',57127)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(3,'Skoda',9000)")) {

finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(4,'Volvo',29000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(5,'Bentley',350000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(6,'Citroen',21000)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(7,'Hummer',41400)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO cars VALUES(8,'Volkswagen',21600)"))
{ finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(1,'Jim',7)")) { finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(1,'Jim',8)")) { finish_with_error(con);
}
if (mysql_query(con, "INSERT INTO people
VALUES(2,'Tom',6)"))
{ finish_with_error(con); }

if (mysql_query(con, "SELECT * FROM cars"))


{ finish_with_error(con);
}
MYSQL_RES *result =
93
mysql_store_result(con); if (result ==
NULL)
{ finish_with_error(con);
}
int num_fields =
mysql_num_fields(result); MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{ for(int i = 0; i < num_fields; i++)
{ printf("%s ", row[i] ? row[i] :
"NULL");

}
printf("\n");
}
mysql_free_result(result);

if (mysql_query(con, "update cars set price = 42400 where name = 'Hummer'"))


{ finish_with_error(con);
}

if (mysql_query(con, "SELECT people.name,cars.name,cars.price FROM


cars,people where cars.id = people.car_id"))
{ finish_with_error(con);
} result
=
mysql_store_result(con);
if (result == NULL)
{ finish_with_error(con);
} num_fields =
mysql_num_fields(result); while
((row =
mysql_fetch_row(result)))
{ for(int i = 0; i < num_fields; i++)
{ printf("%s ", row[i] ? row[i] :
"NULL"); }
printf("\n");
}
mysql_free_result(result);

if (mysql_query(con, "delete from people where id = 1"))


{ finish_with_error(con);
}

if (mysql_query(con, "drop table people;"))


{ finish_with_error(con);
}
94
if (mysql_query(con, "drop table cars;"))
{ finish_with_error(con);
}
mysql_close(con)
; exit(0);
}
Compile and execute:

1 gcc testdb.c -o testdb `mysql_config --cflags --libs` 2


./testdb

The output is as follows:

1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000 5 Bentley 350000 6 Citroen 21000 7 Hummer 41400
8 Volkswagen 21600
Jim Hummer 42400
Jim Volkswagen 21600
Tom Citroen 21000
According to the above test, it can be found that C language connects to MariaDB database,
adds, deletes, changes and queries, creates tables, deletes tables, and other functions are all
normal on the 64-bit processing.

Java:

First, ensure the latest OpenJDK and Apache Maven versions have been installed on the test virtual
machine. Create a sample project with Apache Maven:
mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -
DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Then in the generated pom.xml dependencies module, add the following content:

<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.7.0</version>
</dependency>

95
Then edit src/main/java/com/mycompany/app the App.javafile in the directory, the content is as follows

package com.mycompany.app;

import java.sql.*;

public class App {


public static void main( String[] args ) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:mariadb://192.168.0.204/",
"proxysql", "proxypassword")) { // create a Statement try (Statement stmt = conn.createStatement()) {
//execute query try (ResultSet rs = stmt.executeQuery("SELECT
'Hello World!'")) {
//position result to first
rs.first();
System.out.println(rs.getString(1)); //result is "Hello World!"
}
}
}
}
}
Then execute the following command to compile.

1 mvn install
Execute the following command to execute.

1 mvn exec:java -Dexec.mainClass="com.mycompany.app.App" The


output is Hello World!

The above is just a test of relatively simple functions. Below we test the connection pool function and
perform functions such as adding, deleting, modifying, and query.

The revised App.javacontent is as follows:

package
com.mycompany.app;

import java.sql.*;

public class App {

public static void main( String[] args ) throws SQLException {


//option "pool" must be set to indicate that pool has to be used
String connectionString =
"jdbc:mariadb://192.168.0.204/testdb?
user=proxysql&password=proxypassword&maxPoolSize=10&poo l ";

96
try (Connection connection =
DriverManager.getConnection(connectionString)) { try (Statement stmt =
connection.createStatement()) {
ResultSet rs = stmt.executeQuery("DROP TABLE IF EXISTS cars;");
stmt.executeQuery("CREATE TABLE cars(id INT PRIMARY KEY
AUTO_INCREMENT, name
VARCHAR(255), price INT)"); stmt.executeQuery("INSERT
INTO cars
VALUES(1,'Audi',52642)"); stmt.executeQuery("INSERT INTO
cars VALUES(2,'Mercedes',57127)"); rs =
stmt.executeQuery("SELECT * FROM cars");
rs.next();
System.out.println(rs.getStri
ng(2));
}
}

try (Connection connection =


DriverManager.getConnection(connectionString)) { try (Statement stmt =
connection.createStatement()) { stmt.executeQuery("update cars set
name = 'VolksWagen' where id = 1"); stmt.executeQuery("delete from
cars where id = 2");
ResultSet rs = stmt.executeQuery("SELECT * FROM cars");
rs.next();
System.out.println(rs.getString(2));
}
}
}
}
Compile and execute, output successfully.

Audi
Volks
Wage
n

After the above test, the connection pool and addition, deletion, modification, and checking functions are
also normal.

Java’s connector functions are relatively rich, and it also implements load balancing or read-write
separation for clusters or primary replica databases. Next, we test the read-write separation function.
Before doing so, please ensure you have set up the MariaDB primary-replica database environment.

Change App.java to the following code. Note that the replication keyword is added to the JDBC
connection string, which represents primary-replica replication. If it is in other load-balancing
environments, keywords such as load balance are also supported. For details, refer to the official MariaDB
97
documentation. Also note that in the connection string, the primary database address is first, and the
replica database address is last. When the connection attribute is changed to ReadOnly, the statement will
go to the replica database to query.

package com.mycompany.app;

import java.sql.*;

public class App {

public static void main( String[] args ) throws


SQLException { String connectionString =
"jdbc:mysql:replication://192.168.0.204,192.168.0.64/testdb?user=proxysql&password=proxypassword&
maxPoolSize=10&pool";

try (Connection connection =


DriverManager.getConnection(connectionString)) { try (Statement stmt
= connection.createStatement()) { stmt.executeQuery("INSERT INTO cars
VALUES(2,'Mercedes',57127)"); connection.setReadOnly(true);
ResultSet rs = stmt.executeQuery("SELECT * FROM
cars"); rs.next();
System.out.println(rs.getString(2));
}
}
}
}
Compile and execute, the output is as follows:

VolksWage
n
execution
succeed.

The above demonstrated project uses Maven as an example. If you are not using Maven, you can also refer
to the instructions of other tools in the official MariaDB documentation:
https://mariadb.com/kb/en/mariadb-connector-j/

Python:

First make sure that Python3 and pip3 have been installed on the test virtual machine.

To connect MariaDB in Python, you need to install the C language connector first, you can execute the
following command to install

98
apt install libmariadb-dev
However, the current version of the mariadb package that comes with the current Ubuntu 18.04 version is
older and cannot meet the python version requirements. We compile one from the source code.

Execute the following command to download the connector source code and unzip it

wget https://downloads.mariadb.org/interstitial/connector-c-3.1.11/mariadb-connector-c-
3.1.11-src.zip unzip mariadb-connector-c-3.1.11-src.zip Start
compiling.

Create a separate compilation directory, compile in this directory, and install

mkdir build-
mariadbconnector-c
cd buildmariadb-
connector-c
cmake ../mariadb-connector-c-3.1.11-src -DCMAKE_BUILD_TYPE=Release -
DCMAKE_INSTALL_PREFIX=/usr/
local make
make install
echo "/usr/local/lib/mariadb/" >
/etc/ld.so.conf.d/mariadb.conf ldconfig
Then execute the following command to install the Python connector:

pip3 install mariadb


Next, we directly test the connection pool function, and simply test the query and new functions.

Edit the following code and name it to testmariadb.py

import mariadb

pool =
mariadb.ConnectionPool( user="proxysql",
password="proxypassword
" , host="192.168.0.204",
port=3306,
pool_name="we
b-app",
pool_size=20
)

try:
pconn =
pool.get_connection(
) cur =
pconn.cursor()
data = [(3, 'Skoda', 9000),(4, 'Volvo', 29000),(5, 'Bently', 350000)]
99
cur.executemany("INSERT INTO testdb.cars(id, name, price) VALUES (?, ?, ?)", data)
cur.execute("select * from testdb.cars") cars = [] for (id,name,price) in cur:
cars.append(f"{id} {name}
{price}") print("\
n".join(cars))
except mariadb.PoolError as e:
# Report Error
printf("Error opening connection from pool: {e}")
Execute:

python3 testmariadb.py
The output is as follows

Volkswagen 52642
Mercedes 57127
Skoda 9000
Volvo 29000
Bently 350000

For other functions of the Python connector, you can refer to the
following link: https://mariadb.com/docs/appdev/connector-python/

Another Method for a connection to a MariaDB database using Python

To demonstrate a connection to a MariaDB database using Python, you can use the mysql-
connectorpython library. MariaDB is compatible with MySQL, so you can use the same library that is
used to connect to MySQL databases. Here's an example of how to connect to a MariaDB database using
Python:
Prerequisites:
1. Install MariaDB: If you haven't already, install MariaDB on your computer. You can download it from
the official website (https://mariadb.org/download/).
2. Install the mysql-connector-python library:
pip install mysql-connector-python

Python Example:
import mysql.connector

# Database connection
parameters db_params = {
'host': 'localhost', # Change to your database

100
host 'database': 'mydb', # Change to your
database name 'user': 'myuser', # Change to
your database username
'password': 'mypassword' # Change to your database
password }
try:
# Establish a connection to the database conn
= mysql.connector.connect(**db_params)

if conn.is_connected():
print("Connected to the database successfully.")

# Create a cursor object to interact with the


database cursor = conn.cursor()

# Execute a simple SQL query


cursor.execute("SELECT VERSION();")
db_version = cursor.fetchone()
print(f"Database version: {db_version[0]}")

# Close the cursor and the connection


cursor.close()
conn.close()

except mysql.connector.Error
as e: print(f"Error:
{e}")

Replace the db_params dictionary values with your specific database connection details

(host, database name, username, and password).

This Python script uses the mysql-connector-python library to connect to a MariaDB database, execute a
simple SQL query to fetch the database version, and then closes the connection.
Make sure you have MariaDB running and that you've created the specified database with the appropriate
user and permissions before running this script.

101

You might also like