0% found this document useful (0 votes)
17 views8 pages

r23 Dbms Record

Uploaded by

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

r23 Dbms Record

Uploaded by

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

Experiment 3: Queries using Aggregate Functions

(COUNT, SUM, AVG, MAX, and MIN), GROUP BY,


HAVING, and Creation and Dropping of Views.
AIM

Queries using Aggregate Functions (COUNT, SUM, AVG, MAX, and MIN), GROUP
BY, HAVING, and Creation and Dropping of Views.

THEORY

Aggregate functions in SQL perform calculations on a set of values and return a single
summarized result. These functions are useful in analyzing large datasets and
extracting meaningful insights.

Importance of Aggregate Functions in Databases

• Data Summarization: Helps in generating summary statistics from large


datasets.
• Efficient Data Analysis: Used in business intelligence and reporting.
• Filtering and Grouping: Enables data classification using GROUP BY and
HAVING.
• Improved Performance: Reduces computation time by processing data at
the database level.

Common Aggregate Functions

1. COUNT() - Returns the number of rows.


2. SUM() - Returns the total sum of a column.
3. AVG() - Returns the average value of a column.
4. MAX() - Returns the maximum value in a column.
5. MIN() - Returns the minimum value in a column.

GROUP BY and HAVING Clause


• GROUP BY groups rows with the same values in specified columns.
• HAVING filters aggregated results based on a condition.

Views in SQL
A view is a virtual table based on a SELECT query. It provides a way to store query
results without physically storing data, improving security and performance.

• Creating a View: Allows simplified data access.


• Dropping a View: Removes the stored query representation without affecting
base tables. SQL provides powerful querying capabilities that allow data
retrieval based on specific conditions. Queries are essential for interacting with
databases efficiently and extracting meaningful insights from structured data.

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 9


This experiment covers advanced SQL querying techniques using subqueries,
set operations, and constraints.

Importance of Advanced SQL Queries

• Efficient Data Retrieval: Helps extract specific data quickly using optimized
queries.
• Data Integrity: Ensures constraints like PRIMARY KEY and FOREIGN KEY
maintain relationships.
• Structured Data Manipulation: Enables filtering, sorting, and aggregating
data based on conditions.
• Enhancing Performance: Using EXISTS, IN, and indexing optimizes query
execution.

Explanation of SQL Operators Used


• ANY & ALL: These are used with comparison operators to compare a value
with a list of values returned by a subquery.
o ANY: Returns true if any value in the subquery matches.
o ALL: Returns true if all values in the subquery match the condition.
• IN & EXISTS: Used for checking membership in a list or subquery.
o IN: Checks if a value exists within a specified set of values.
o EXISTS: Returns true if a subquery contains any rows.
o NOT EXISTS: Ensures records do not exist in a given dataset.
• UNION & INTERSECT: Used to combine results from multiple queries.
o UNION: Combines results from two SELECT queries, removing
duplicates.
o INTERSECT: Returns only the common rows from both queries.
• Constraints in Queries:
o PRIMARY KEY: Ensures uniqueness of each row in a table.
o FOREIGN KEY: Maintains referential integrity between tables.
o CHECK: Enforces specific conditions on column values.
o UNIQUE: Ensures no duplicate values exist in a column.

These SQL features are widely used in real-world applications such as:

• Banking Systems: Fetching customer transaction history.


• E-Commerce: Filtering products based on availability and price range.
• Healthcare: Querying patient records based on diagnosis or medication
history.

Advanced queries ensure efficient data processing and provide meaningful insights
from relational databases. SQL provides powerful querying capabilities that allow data
retrieval based on specific conditions. The following SQL clauses and operators are
commonly used for advanced querying:

• ANY & ALL: Used with comparison operators to compare a value with a set of
values returned by a subquery.
• IN & EXISTS: Filters records based on lists or subqueries.
• NOT EXISTS: Identifies records that do not exist in another table.

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 10


• UNION & INTERSECT: Combines or filters results from multiple queries.
• Constraints: Ensure data integrity, such as PRIMARY KEY, FOREIGN KEY,
and CHECK constraints.

PROCEDURE

1. Creating the Student Table

CREATE TABLE Student (


RollNo INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Age INT CHECK (Age >= 18),
Marks INT,
Rank INT
);

2. Inserting Data into the Table

INSERT INTO Student (RollNo, Name, Age, Marks, Rank) VALUES


(101, 'Alice', 20, 85, 2),
(102, 'Bob', 22, 90, 1),
(103, 'Charlie', 19, 75, 3),
(104, 'David', 21, 70, 4),
(105, 'Emma', 20, 65, 5);

3. Displaying Table Structure

DESC Student;

Output:

+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| RollNo | INT | NO | PRI | NULL | |
| Name | VARCHAR(50)| NO | | NULL | |
| Age | INT | NO | | NULL | |
| Marks | INT | YES | | NULL | |
| Rank | INT | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+

4. Displaying Data After Insertion

SELECT * FROM Student;

Output:

+--------+--------+-----+-------+------+
| RollNo | Name | Age | Marks | Rank |
+--------+--------+-----+-------+------+
| 101 | Alice | 20 | 85 | 2 |
| 102 | Bob | 22 | 90 | 1 |
| 103 | Charlie| 19 | 75 | 3 |
| 104 | David | 21 | 70 | 4 |
| 105 | Emma | 20 | 65 | 5 |
+--------+--------+-----+-------+------+

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 11


5. Selecting the Roll Number and Name of the Student Who Secured
Fourth Rank

SELECT RollNo, Name FROM Student WHERE Rank = 4;

Output:

+--------+--------+
| RollNo | Name |
+--------+--------+
| 104 | David |
+--------+--------+

6. Using IN and EXISTS

SELECT Name FROM Student WHERE Rank IN (1, 2, 3);

Output:

+--------+
| Name |
+--------+
| Bob |
| Alice |
| Charlie|
+--------+
SELECT Name FROM Student S WHERE EXISTS (
SELECT 1 FROM Student M WHERE M.RollNo = S.RollNo AND M.Marks > 80
);

Output:

+--------+
| Name |
+--------+
| Alice |
| Bob |
+--------+

7. Using UNION and INTERSECT

SELECT Name FROM Student WHERE Rank < 4


UNION
SELECT Name FROM Student WHERE Age > 19;

Output:

+--------+
| Name |
+--------+
| Alice |
| Bob |
| Charlie|
| David |
+--------+
SELECT Name FROM Student WHERE Rank < 3

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 12


INTERSECT
SELECT Name FROM Student WHERE Age > 18;

Output:

+--------+
| Name |
+--------+
| Alice |
| Bob |
+--------+

RESULT

The experiment successfully demonstrates the use of subqueries, constraints, and set
operations such as ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, and INTERSECT in
SQL.

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 13


Experiment 9: Stored Functions
AIM

Program development using creation of stored functions, invoking functions in SQL


statements, and writing complex functions.

THEORY

A stored function in PL/SQL is a subprogram that returns a single value and can be
called within SQL statements. Functions enhance modularity and reusability by
performing calculations and returning values based on input parameters.

• Key Features of Functions:


o Accepts parameters and returns a value.
o Can be used within SELECT statements.
o Must include a RETURN statement.
o Stored functions help in data consistency as they allow calculations to be
performed at the database level rather than in the application layer.
o Functions improve performance by reducing the need for repetitive
queries and calculations within application code.
o They promote reusability and modularity, making code maintenance
easier.

Types of Stored Functions in PL/SQL:

1. Scalar Functions: These return a single value, such as a number or string.


2. Table Functions: These return a set of rows, similar to a table.
3. Built-in Functions: Provided by SQL for common operations (e.g.,
LENGTH(), ROUND()).
4. User-defined Functions: Custom functions created for specific calculations
or operations.

Advantages of Using Stored Functions:


• Performance Optimization: Execution occurs at the database level,
reducing network overhead.
• Security: Access to specific data logic can be controlled by granting execution
privileges.
• Code Reusability: Functions can be used in different queries without
rewriting logic.
• Consistency: Ensures uniform data manipulation and validation across
applications.

PROCEDURE

1. Creating the Student Table

CREATE TABLE Student (


RollNo INT PRIMARY KEY,

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 31


Name VARCHAR(50) NOT NULL,
Marks INT
);

Created Table Structure:

Column | Data Type | Constraints


---------+--------------+------------------------
RollNo | INT | PRIMARY KEY
Name | VARCHAR(50) | NOT NULL
Marks | INT |

2. Inserting Data into the Table

INSERT INTO Student (RollNo, Name, Marks) VALUES


(1, 'Alice', 85),
(2, 'Bob', 92),
(3, 'Charlie', 40);

Table with Inserted Data:

RollNo | Name | Marks


--------+--------+-------
1 | Alice | 85
2 | Bob | 92
3 | Charlie| 40

3. Creating a Function to Determine Grade

CREATE OR REPLACE FUNCTION GetGrade (p_Marks IN INT) RETURN VARCHAR2 AS


v_Grade VARCHAR2(2);
BEGIN
IF p_Marks >= 90 THEN
v_Grade := 'A';
ELSIF p_Marks >= 75 THEN
v_Grade := 'B';
ELSE
v_Grade := 'C';
END IF;
RETURN v_Grade;
END;
/

4. Using the Function in a SQL Query

SELECT Name, Marks, GetGrade(Marks) AS Grade FROM Student;

Output:

Name | Marks | Grade


---------+-------+------
Alice | 85 | B
Bob | 92 | A
Charlie | 40 | C

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 32


5. Calling the Function within Another Function

CREATE OR REPLACE FUNCTION GetStudentPerformance (p_Marks IN INT) RETURN


VARCHAR2 AS
v_Performance VARCHAR2(20);
BEGIN
IF p_Marks >= 90 THEN
v_Performance := 'Excellent';
ELSIF p_Marks >= 75 THEN
v_Performance := 'Good';
ELSE
v_Performance := 'Needs Improvement';
END IF;
RETURN v_Performance;
END;
/

6. Using the Performance Function in a Query

SELECT Name, Marks, GetStudentPerformance(Marks) AS Performance FROM


Student;

Output:

Name | Marks | Performance


---------+-------+----------------
Alice | 85 | Good
Bob | 92 | Excellent
Charlie | 40 | Needs Improvement

RESULT
The experiment successfully demonstrates the creation and execution of stored
functions in PL/SQL, allowing SQL queries to invoke functions directly for
calculations and performance analysis.

RISE KRISHNA SAI GANDHI GROUP OF INSTITUTIONS - DBMS LAB 33

You might also like