0% found this document useful (0 votes)
15 views

DBMS)

Lec

Uploaded by

minabazar786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

DBMS)

Lec

Uploaded by

minabazar786
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Bahria University, Lahore Campus

Department of Computer Sciences


Lab Journal 09
(Fall 2024)

Course: DBMS Lab Date: 19-11-2024


Course Code: CSL 220 Max Marks: 20
Faculty’s Name: Muhammad Shahid Muhammad Shahid

Name: Minahil Zameer


Enroll No:03-135231-020

Lab 9:

OBJECTIVE:
Functions in SQL are predefined operations or expressions that can be used to perform computations
on data, manipulate strings, numbers, dates, or even return aggregated values. They help simplify
and streamline queries, making them more efficient and readable. SQL functions are typically
divided into two categories

Aggregate Functions: These operate on a set of values and return a single result for the entire set.

Aggregate Functions
Aggregate functions perform calculations on multiple rows of a table and return a single result. They
are often used with the GROUP BY clause to perform calculations for specific groups of data.

SUM():Calculates the sum of a numeric column.


Syntax: SELECT SUM(column_name) FROM table_name WHERE condition;

AVG(): Returns the average of a numeric column.


Syntax: SELECT AVG(column_name) FROM table_name WHERE condition;

COUNT(): Returns the number of rows or non-null values in a column.


Syntax: SELECT COUNT(column_name) FROM table_name WHERE condition;

MAX(): Returns the maximum value of a column.


Syntax: SELECT MAX(column_name) FROM table_name WHERE condition;

MIN(): Returns the minimum value of a column.


Syntax: SELECT MIN(column_name) FROM table_name WHERE condition;

User Defined Functions: Allow users to create their own logic for specific needs that cannot be
fulfilled by standard SQL functions. UDFs can be written to perform operations like mathematical
calculations, data transformations, or complex business logic.

There are two main types of UDFs:


1. Scalar UDFs: Return a single value.
2. Table-Valued UDFs (TVFs): Return a table.
Syntax to Create a Scalar Function:
CREATE FUNCTION function_name (@param1 data_type, @param2 data_type, ...)
RETURNS return_data_type
AS
BEGIN
-- Function logic
RETURN value_or_expression
END;

Example: A function to calculate a bonus (10% of salary).


CREATE FUNCTION dbo.CalculateBonus (@salary DECIMAL)
RETURNS DECIMAL
AS
BEGIN
RETURN @salary * 0.1; -- 10% bonus
END;

Using the Scalar UDF:


SELECT empno, ename, dbo.CalculateBonus(sal) AS bonus FROM emp;

Syntax to Create a Table-Valued Function:


CREATE FUNCTION function_name (@param1 data_type, @param2 data_type, ...)
RETURNS TABLE
AS
RETURN
(
-- Query returning a table
SELECT column1, column2, ...
FROM table_name
WHERE condition
);

Example: A function to get employees by department.

CREATE FUNCTION dbo.GetEmployeesByDept (@dept_id INT)


RETURNS TABLE
AS
RETURN
(
SELECT empno, ename, sal
FROM emp
WHERE deptno = @dept_id
);

Using the Table-Valued UDF:


SELECT * FROM dbo.GetEmployeesByDept(20);

Scenario: Run SQL to create Tables and insert Data.

-- Create tables
CREATE TABLE dept (
deptno INT,
dname VARCHAR(14),
loc VARCHAR(13),
CONSTRAINT pk_dept PRIMARY KEY (deptno)
);

CREATE TABLE emp (


empno INT,
ename VARCHAR(10),
job VARCHAR(9),
mgr INT,
hiredate DATE,
sal DECIMAL(7, 2),
comm DECIMAL(7, 2),
deptno INT,
CONSTRAINT pk_emp PRIMARY KEY (empno),
CONSTRAINT fk_deptno FOREIGN KEY (deptno) REFERENCES dept (deptno)
);

-- Insert statements
INSERT INTO dept VALUES
(10, 'ACCOUNTING', 'NEW YORK'),
(20, 'RESEARCH', 'DALLAS'),
(30, 'SALES', 'CHICAGO'),
(40, 'OPERATIONS', 'BOSTON'),
(50, 'MARKETING', 'LOS ANGELES'),
(60, 'HR', 'NEW YORK'),
(70, 'IT', 'SEATTLE');

INSERT INTO emp VALUES


(7839, 'KING', 'PRESIDENT', NULL, '1981-11-17', 5000, NULL, 10),
(7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, NULL, 30),
(7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 4450, NULL, 10),
(7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 3975, NULL, 20),
(7788, 'SCOTT', 'ANALYST', 7566, '1987-07-13', 3000, NULL, 20),
(7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20),
(7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, NULL, 20),
(7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30),
(7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30),
(7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30),
(7844, 'TURNER', 'SALESMAN', 7698, '1981-09-08', 1500, 0, 30),
(7876, 'ADAMS', 'CLERK', 7788, '1987-07-13', 1100, NULL, 20),
(7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, NULL, 30),
(7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10),
(7905, 'CHEN', 'ANALYST', 7566, '1982-12-03', 2800, NULL, 20),
(7909, 'SKINNER', 'CLERK', 7902, '1983-02-15', 1200, NULL, 20),
(7914, 'MORGAN', 'CLERK', 7902, '1983-01-10', 1300, NULL, 20),
(7919, 'CHANG', 'ENGINEER', 7566, '1984-05-20', 4000, NULL, 20),
(7923, 'LEE', 'MANAGER', 7839, '1985-08-12', 4500, NULL, 10);

Tasks:

Task 1: Aggregate function


a. Calculate the total salary of all employees.:
b. Calculate the total salary of employees grouped by department.
c. Calculate the average salary of all employees.
d. Calculate the average salary of employees grouped by department.
e. Count the total number of employees.
f. Count the number of employees in each department.
g. Find the highest salary among all employees.
h. Find the highest salary in each department.
i. Find the lowest salary among all employees.
j. Find the lowest salary in each department.
Code:
SELECT SUM(salary) AS TotalSalary FROM employees;
SELECT department_id, SUM(salary) AS TotalSalary FROM employees GROUP BY
department_id;
SELECT AVG(salary) AS AverageSalary FROM employees;
SELECT department_id, AVG(salary) AS AverageSalary FROM employees GROUP BY
department_id;
SELECT COUNT(*) AS TotalEmployees FROM employees;
SELECT department_id, COUNT(*) AS EmployeesCount FROM employees GROUP BY
department_id;
SELECT MAX(salary) AS HighestSalary FROM employees;
SELECT department_id, MAX(salary) AS HighestSalary FROM employees GROUP BY
department_id;
SELECT MIN(salary) AS LowestSalary FROM employees;
SELECT department_id, MIN(salary) AS LowestSalary FROM employees GROUP BY
department_id;

Task 2: UDF
a. Create a function to get current date.
b. Capitalize first letter of employee name and lowercase remaining characters.
c. Create a scalar Function to Calculate Employee's Annual Salary.
d. Create a scalar Function to Check If an Employee is a manager.
e. Check if an employee's salary is above 3000.
f. Find number of employees in each department. (without function)
g. Create a Table-Valued Function to Get Employees in each Department.
h. Table-Valued Function to Get Employees in a Specific Location.
Code:
CREATE FUNCTION GetCurrentDate()
RETURNS DATE
AS
BEGIN
RETURN GETDATE();
END;

CREATE FUNCTION CapitalizeName(@name NVARCHAR(50))


RETURNS NVARCHAR(50)
AS
BEGIN
RETURN UPPER(LEFT(@name, 1)) + LOWER(SUBSTRING(@name, 2, LEN(@name)));
END;

CREATE FUNCTION CalculateAnnualSalary(@monthly_salary FLOAT)


RETURNS FLOAT
AS
BEGIN
RETURN @monthly_salary * 12;
END;

CREATE FUNCTION IsManager(@job_title NVARCHAR(50))


RETURNS BIT
AS
BEGIN
RETURN CASE WHEN @job_title = 'Manager' THEN 1 ELSE 0 END;
END;

CREATE FUNCTION IsSalaryAbove3000(@salary FLOAT)


RETURNS BIT
AS
BEGIN
RETURN CASE WHEN @salary > 3000 THEN 1 ELSE 0 END;
END;

Task 3: Homework:
Learn and implement the following built-in functions:
a. String functions: Upper(), Lower(), Concat(),
b. Date-Difference: DATEDIFF()
c. Round()

Code:
SELECT
UPPER(employee_name) AS UpperCaseName,
LOWER(employee_name) AS LowerCaseName,
CONCAT('Employee: ', employee_name) AS FullName
FROM employees;

SELECT DATEDIFF(DAY, hire_date, GETDATE()) AS DaysWorked FROM employees;

SELECT ROUND(salary, 2) AS RoundedSalary FROM employees;

You might also like