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

SQLAssignments

The document outlines an SQL assignment that includes creating a database and employee table, inserting sample data, and writing various SQL queries for data retrieval and manipulation. It covers tasks such as selecting records, aggregating data, formatting output, and using conditional statements. The assignment is structured with specific queries to demonstrate SQL functionalities like joins, group by, and case statements.

Uploaded by

n07.lincoln
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)
7 views

SQLAssignments

The document outlines an SQL assignment that includes creating a database and employee table, inserting sample data, and writing various SQL queries for data retrieval and manipulation. It covers tasks such as selecting records, aggregating data, formatting output, and using conditional statements. The assignment is structured with specific queries to demonstrate SQL functionalities like joins, group by, and case statements.

Uploaded by

n07.lincoln
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/ 24

2025

SQL ASSIGNMENT

GOPIKRISHNA UPPUTURI

4/21/2025
SQL ASSIGNME NT
Database , Tables , Constraints
1.Create new database & employee table (based on give sample data)
 create employee table with primary key (EmployeeID)

A)CREATE DATABASE company;

USE company;

CREATE TABLE employee (

EmployeeID INT NOT NULL AUTO_INCREMENT,

FirstName VARCHAR(50) NOT NULL,

LastName VARCHAR(50) NOT NULL,

Department VARCHAR(50),

Salary DECIMAL(10, 2),

DateOfHire DATE,

PRIMARY KEY (EmployeeID) );

2. Insert sample data into the table.

A). INSERT INTO employee (FirstName, LastName, Department, Salary,


DateOfHire)

VALUES

('John', 'Doe', 'HR', 55000.00, '2020-01-15'),

('Jane', 'Smith', 'Engineering', 80000.00, '2019-05-23'),

('Malli', 'Kumar', 'Sales', 45000.00, '2021-07-09'),

('Meena', 'Iyer', 'Marketing', 62000.00, '2018-11-12');


SQL ASSIGNME NT
3. Write a query to create a clone of an existing table using Create
Command.

A). CREATE TABLE employee_clone AS SELECT * FROM employee;

4.Write a query to get all employee detail from "employee" table.


A) .SELECT * FROM employee;

5.Select only top 1 record from employee table


A)SELECT * FROM employee LIMIT 1;

6.Select only bottom 1 record from employee table


A). SELECT * FROM employee ORDER BY EmployeeID DESC LIMIT 1;

7.How to select a random record from a table?


A). SELECT * FROM employee ORDER BY RAND() LIMIT 1;

8.Write a query to get


 “first_name” in upper case as
"first_name_upper"
 ‘first_name’ in lower case as
‘first_name_lower”
 Create a new column “full_name” by combining “first_name” & “last_name”
with space as a separator
 Add 'Hello ' to first_name and display result

A). SELECT
UPPER(FirstName) AS first_name_upper,
LOWER(FirstName) AS first_name_lower,
CONCAT(FirstName, ' ', LastName) AS full_name,
CONCAT('Hello ', FirstName) AS greeting
FROM employee;

9. Select the employee details of


 Whose “first_name” is ‘Malli’
 Whose “first_name” present in ("Malli","Meena", "Anjali")
SQL ASSIGNME NT
 Whose “first_name” not present in ("Malli","Meena", "Anjali")
 Whose “first_name” starts with “v”
 Whose “first_name” ends with “i”
 Whose “first_name” contains “o”

 Whose "first_name" start with any single character between 'm-v'


 Whose "first_name" not start with any single character between 'm-v'
 Whose "first_name" start with 'M' and contain 5 letters

A)-- Whose first_name is 'Malli'


SELECT * FROM employee WHERE FirstName = 'Malli';

-- Whose first_name is in ('Malli', 'Meena', 'Anjali')


SELECT * FROM employee WHERE FirstName IN ('Malli', 'Meena', 'Anjali');

-- Whose first_name is not in ('Malli', 'Meena', 'Anjali')


SELECT * FROM employee WHERE FirstName NOT IN ('Malli', 'Meena',
'Anjali');

-- Whose first_name starts with 'v'


SELECT * FROM employee WHERE FirstName LIKE 'v%';

-- Whose first_name ends with 'i'


SELECT * FROM employee WHERE FirstName LIKE '%i';

-- Whose first_name contains 'o'


SELECT * FROM employee WHERE FirstName LIKE '%o%';

-- Whose first_name starts with any single character between 'm' and 'v'
SELECT * FROM employee WHERE FirstName REGEXP '^[m-v]';
-- Whose first_name does not start with any single character between 'm'
and'v'
SQL ASSIGNME NT

SELECT * FROM employee WHERE FirstName NOT REGEXP '^[m-v]';

-- Whose first_name starts with 'M' and contains 5 letters


SELECT * FROM employee WHERE FirstName LIKE 'M____';

10. Write a query to get all unique values of"department" from the employee
table.
A).SELECT DISTINCT Department FROM employee;

11. Query to check the total records present in a table.


A).SELECT COUNT(*) FROM employee;

12. Write down the query to print first letter of a Name in Upper Case and
all other letter in Lower Case.(EmployDetail table)
A).SELECT CONCAT(UPPER(SUBSTRING(FirstName, 1, 1)),

LOWER(SUBSTRING(FirstName, 2))) AS FormattedName FROM


employee;

13. Write down the query to display all employee name in one cell
separated by ','

ex:- "Vikas, nikita, Ashish, Nikhil , anish"(EmployDetail table).

A).SELECT GROUP_CONCAT(FirstName ORDER BY FirstName


SEPARATOR ', ') AS EmployeeNames FROM employee;

14. Query to get the below values of "salary" from employee table
 Lowest salary
 Highest salary
 Average salary
 Highest salary - Lowest salary as diff_salary
 % of difference betweenHighest salary and lowest salary. (sample output
format: 10.5%)
A).SELECT
MIN(Salary) AS LowestSalary,
MAX(Salary) AS HighestSalary,
AVG(Salary) AS AverageSalary,
SQL ASSIGNME NT
MAX(Salary) - MIN(Salary) AS diff_salary,
(MAX(Salary) - MIN(Salary)) / MIN(Salary) * 100 AS percent_difference FROM employee;

15. Select “first_name” from the employee table after removing


white spaces from

 Right side spaces


 Left side spaces Both
 right & left side spaces
A).-- Right side spaces removed
SELECT RTRIM(FirstName) AS FirstNameWithoutRightSpaces FROM employee;
-- Left side spaces removed
SELECT LTRIM(FirstName) AS FirstNameWithoutLeftSpaces FROM employee;

-- Both right & left side spaces removed


SELECT TRIM(FirstName) AS FirstNameWithoutSpaces FROM employee;

16. Query to check no.of records present in a table where


employees having 50k salary.

A) SELECT COUNT(*) FROM employee WHERE Salary = 50000;

17. Find the most recently hired employee in each department.


A).SELECT Department, FirstName, LastName, DateOfHire
FROM (
SELECT Department, FirstName, LastName, DateOfHire,

RANK() OVER (PARTITION BY Department ORDER BY DateOfHire


DESC) AS rank
FROM employee
) AS ranked
WHERE rank = 1;

Case When Then End Statement Queries

1.Display first_name and gender as M/F.(if male then M, if Female then F).
SQL ASSIGNME NT
A) SELECT FirstName,CASE
WHEN Gender = 'Male' THEN 'M'
WHEN Gender = 'Female' THEN 'F'
ELSE 'Other'

END AS Gender
FROM employee;

2. Display first_name, salary and a salary category. (If salary is below 50,000,
categorize as
'Low'; between 50,000 a 60,000 as 'Medium'; above 60,000 as 'High').

A).SELECT FirstName,Salary,

CASE

WHEN Salary < 50000 THEN 'Low'


WHEN Salary BETWEEN 50000 AND 60000 THEN 'Medium'
ELSE 'High'
END AS SalaryCategory
FROM employee;

3.Display first_name, department, and a department classification. (If


department is 'IT',
display 'Technical'; if 'HR', display 'Human Resources'; if 'Finance',
display 'Accounting';
otherwise, display 'Other')
A). SELECT FirstName,Department,CASE
WHEN Department = 'IT' THEN 'Technical'
WHEN Department = 'HR' THEN 'Human Resources'
WHEN Department = 'Finance' THEN 'Accounting'
ELSE 'Other'
END AS DepartmentClassification
FROM employee;

4.Display first_name, salary, and eligibility for a salary raise. (If salary is
less than 50,000,
mark as 'Eligible for Raise'; otherwise, 'Not Eligible')

SELECT FirstName,Salary,
SQL ASSIGNME NT
CASE
WHEN Salary < 50000 THEN 'Eligible for Raise'
ELSE 'Not Eligible'
END AS RaiseEligibility FROM employee;

5.Display first_name, joining_date, and employment status. (If joining


date is before
'2022-01-01', mark as 'Experienced'; otherwise, 'New Hire')

A) SELECT FirstName,DateOfHire AS JoiningDate,


CASE
WHEN DateOfHire < '2022-01-01' THEN 'Experienced'
ELSE 'New Hire'
END AS EmploymentStatus
FROM employee;

6.Display first_name, salary, and bonus amount. (If salary is above


60,000, add10% bonus;
if between 50,000 and 60,000, add 7%; otherwise, 5%)

A) SELECT FirstName,Salary,
CASE
WHEN Salary > 60000 THEN Salary * 0.10
WHEN Salary BETWEEN 50000 AND 60000 THEN Salary * 0.07
ELSE Salary * 0.05
END AS BonusAmount
FROM employee;

7.Display first_name, salary, and seniority level.

A) SELECT FirstName,Salary,
CASE
WHEN Salary > 60000 THEN 'Senior'
WHEN Salary BETWEEN 50000 AND 60000 THEN 'Mid-Level'
ELSE 'Junior'
END AS SeniorityLevel
FROM employee;

8.(If salary is greater than 60,000, classify as 'Senior'; between 50,000


and 60,000 as 'Mid-
SQL ASSIGNME NT
Level'; below 50,000 as 'Junior')

SELECT FirstName, Salary,


CASE
WHEN Salary > 60000 THEN 'Senior'

WHEN Salary BETWEEN 50000 AND 60000 THEN 'Mid-Level'


ELSE 'Junior'
END AS SeniorityLevel

FROM employee;

9.Display first_name, salary, and seniority level

A) SELECT FirstName, Salary,


CASE
WHEN Salary > 60000 THEN 'Senior'
WHEN Salary BETWEEN 50000 AND 60000 THEN 'Mid-Level'
ELSE 'Junior'
END AS SeniorityLevel
FROM employee;

10. (If salary is greater than 60,000, classify as 'Senior'; between 50,000 and
60,000 as
'Mid-Level'; below 50,000 as 'Junior')

A) SELECT FirstName,Salary,
CASE
WHEN Salary > 60000 THEN 'Senior'
WHEN Salary BETWEEN 50000 AND 60000 THEN 'Mid-Level'
ELSE 'Junior'
END AS SeniorityLevel
FROM employee;

11. Display first_name, department, and job level for IT employees. (If
department is 'IT'
And salary is greater than 55,000, mark as 'Senior IT Employee';
otherwise,'Other').
SQL ASSIGNME NT
A)SELECT FirstName, Department,

CASE
WHEN Department = 'IT' AND Salary > 55000 THEN 'Senior IT Employee'
ELSE 'Other'
END AS JobLevel
FROM employee
WHERE Department = 'IT';

12.Display first_name, joining_date, and recent joiner status. (If an


employee joined
after '2024-01-01', label as 'Recent Joiner'; otherwise, 'Long-Term
Employee')

A) SELECT FirstName, DateOfHire AS JoiningDate,


CASE
WHEN DateOfHire > '2024-01-01' THEN 'Recent Joiner'
ELSE 'Long-Term Employee'
END AS EmploymentStatus
FROM employee;

13. Display first_name, joining_date, and leave entitlement. (If joined


before '2021-01 01',
assign '10 Days Leave'; between '2021-01-01' and '2023-01-01', assign
'20 Days Leave';
otherwise, '25 Days Leave')

A) SELECT FirstName, DateOfHire AS JoiningDate,


CASE
WHEN DateOfHire < '2021-01-01' THEN '10 Days Leave'
WHEN DateOfHire BETWEEN '2021-01-01' AND '2023-01-01' THEN '20
Days Leave'
ELSE '25 Days Leave'
END AS LeaveEntitlement
FROM employee;

14. Display first_name, salary, department, and promotion eligibility. (If


salary is above
SQL ASSIGNME NT
60,000 and department is 'IT', mark as 'Promotion Eligible'; otherwise,
'Not
Eligible')

A) SELECT FirstName, Salary,Department,


CASE
WHEN Salary > 60000 AND Department = 'IT' THEN 'Promotion Eligible'
ELSE 'Not Eligible'
END AS PromotionEligibility FROM employee;

15. Display first_name, salary, and overtime pay eligibility. (If salary is
below 50,000,
mark as 'Eligible for Overtime Pay'; otherwise, 'Not Eligible')

A) SELECT FirstName, Salary,


CASE
WHEN Salary < 50000 THEN 'Eligible for Overtime Pay'
ELSE 'Not Eligible'
END AS OvertimePayEligibility
FROM employee;

16. Display first_name, department, salary, and job title. (If department
is 'HR' and salary is
above 60,000, mark as 'HR Executive'; if department is 'Finance' and
salary is above
55,000, mark as 'Finance Manager'; otherwise, 'Regular Employee')

A) SELECT FirstName, Department, Salary,


CASE
WHEN Department = 'HR' AND Salary > 60000 THEN 'HR Executive'
WHEN Department = 'Finance' AND Salary > 55000 THEN 'Finance
Manager'
ELSE 'Regular Employee'
END AS JobTitle
FROM employee;

17. Display first_name, salary, and salary comparison to the company


average. (If salary is
above the company’s average salary, mark as 'Above Average';
otherwise, 'Below Average')
SQL ASSIGNME NT
A) SELECT FirstName, Salary,
CASE
WHEN Salary > (SELECT AVG(Salary) FROM employee) THEN 'Above
Average'
ELSE 'Below Average'
END AS SalaryComparison FROM employee;

Group by
1.Write the query to get the department and department wise
total(sum) salary, display it
in ascending and descending order according to salary.

A) -- Ascending Order
SELECT Department, SUM(Salary) AS TotalSalary

FROM employee
GROUP BY Department
ORDER BY TotalSalary ASC;

-- Descending Order
SELECT Department, SUM(Salary) AS TotalSalary
FROM employee

GROUP BY Department
ORDER BY TotalSalary DESC;

2.Write down the query to fetch Project name assign to more than one
Employee

A) SELECT ProjectName FROM ProjectDetail


GROUP BY ProjectName
HAVING COUNT(EmployeeID) > 1;

3.Write the query to get the department, total no. of departments, total(sum)
salary with

Respect to department from "employee table" table.


SQL ASSIGNME NT
A)SELECT Department,COUNT(DISTINCT Department) OVER() AS
TotalDepartments,

SUM(Salary) AS TotalSalary
FROM employee
GROUP BY Department;

4.Get the department-wise salary details from the


"employee table"table:

 What is the average salary? (Order by salary


ascending)

 What is the maximum salary? (Order by salary


ascending)

A) -- Average Salary

SELECT Department, AVG(Salary) AS AvgSalary FROM employee

GROUP BY Department ORDER BY AvgSalary ASC;

-- Maximum Salary

SELECT Department, MAX(Salary) AS MaxSalary FROM employee

GROUP BY Department ORDER BY MaxSalary ASC;

5. Display department-wise employee count and categorize based on


size. (If a department
has more than 5 employees, label it as 'Large'; between 3 and 5 as
'Medium'; otherwise,'Small')

A) SELECT Department, COUNT(*) AS EmployeeCount,


CASE
WHEN COUNT(*) > 5 THEN 'Large'
WHEN COUNT(*) BETWEEN 3 AND 5 THEN 'Medium'
ELSE 'Small'
END AS SizeCategory
FROM employee GROUP BY Department;
SQL ASSIGNME NT
6. Display department-wise average salary and classify pay levels. (If the
average salary in a
department is above 60,000, label it as 'High Pay'; between 50,000 and 60,000
as 'Medium Pay';
otherwise, 'Low Pay').

A) SELECT Department, AVG(Salary) AS AvgSalary,


CASE
WHEN AVG(Salary) > 60000 THEN 'High Pay'
WHEN AVG(Salary) BETWEEN 50000 AND 60000 THEN 'Medium Pay'
ELSE 'Low Pay'
END AS PayLevel
FROM employee GROUP BY Department;
7. Display department, gender, and count of employees in each category.
(Group by
department and gender, showing total employees in each combination)
A) SELECT Department, Gender,
COUNT(*) AS EmployeeCount
FROM employee GROUP BY Department, Gender;

8. Display the number of employees who joined each year and categorize
hiring trends. (Ifa year had more than 5 hires, mark as 'High Hiring'; 3 to 5 as
'Moderate Hiring'; otherwise,'Low Hiring')
A) SELECT
YEAR(DateOfHire) AS HireYear,
COUNT(*) AS EmployeeCount,

CASE
WHEN COUNT(*) > 5 THEN 'High Hiring'
WHEN COUNT(*) BETWEEN 3 AND 5 THEN 'Moderate Hiring'
ELSE 'Low Hiring'
END AS HiringTrend
FROM employee GROUP BY YEAR(DateOfHire) ORDER BY HireYear;

9. Display department-wise highest salary and classify senior roles. (If the
highest salary in a department is above 70,000, label as 'Senior Leadership';
otherwise, 'Mid-Level')

A)SELECT Department, MAX(Salary) AS MaxSalary,


CASE
WHEN MAX(Salary) > 70000 THEN 'Senior Leadership'
SQL ASSIGNME NT
ELSE 'Mid-Level'
END AS RoleClassification
FROM employee GROUP BY Department;

10. Display department-wise count of employees earning more than 60,000.


(Group
employees by department and count those earning above 60,000, labeling
departments
with more than 2 such employees as 'High-Paying Team')
A) SELECT Department, COUNT(*) AS HighEarners,
CASE
WHEN COUNT(*) > 2 THEN 'High Paying Team'
ELSE 'Standard'
END AS TeamCategory
FROM employee WHERE Salary > 60000 GROUP BY Department;

Date time related queries


1 .Query to extract the below things from joining_date column. (Year,
Month, Day, Current Date)

A) SELECT first_name, joining_date,


YEAR(joining_date) AS JoiningYear,
MONTH(joining_date) AS JoiningMonth,
DAY(joining_date) AS JoiningDay,

CURDATE() AS CurrentDate
FROM employee;

2.Create two new columns that calculate the difference between


joining_date and the
current date. One column should show the difference in months, and the
other should
show the difference in days.

A) SELECT first_name,
joining_date,
TIMESTAMPDIFF(MONTH, joining_date, CURDATE()) AS
MonthsSinceJoining,
SQL ASSIGNME NT
DATEDIFF(CURDATE(), joining_date) AS DaysSinceJoining
FROM employee;

3. Get all employee details from the employee table whose joining year is
2020.

A) SELECT *
FROM employee
WHERE YEAR(joining_date) = 2020;

4.Get all employee details from the employee table whose joining month is
Feb.

A) SELECT *
FROM employee
WHERE MONTH(joining_date) = 2;

5.Get all employee details from employee table whose joining date between
"2021-01-01"
and "2021-12-01"

A) SELECT *
FROM employee
WHERE joining_date BETWEEN '2021-01-01' AND '2021-12-01';

Joins Related queries


1.Get the employee name and project name from the "employee
table" and
"ProjectDetail" for employees who have been assigned a project,
sorted by first name.

A) SELECT e.first_name, p.ProjectName


FROM employee e

JOIN ProjectDetail p ON e.EmployeeID = p.EmployeeID


ORDER BY e.first_name;
SQL ASSIGNME NT
2.Get the employee name and project name from the "employee
table" and "ProjectDetail"
for all employees, including those who have not been assigned a
project, sorted by first name.

A) SELECT e.first_name, p.ProjectName


FROM employee e

LEFT JOIN ProjectDetail p ON e.EmployeeID = p.EmployeeID


ORDER BY e.first_name;

3.Get the employee name and project name from the "employee
table" and
"ProjectDetail" for all employees. If an employee has no assigned
project, display "-No Project Assigned," sorted by first name.

A) SELECT e.first_name,
COALESCE(p.ProjectName, '-No Project Assigned') AS ProjectName
FROM employee e
LEFT JOIN ProjectDetail p ON e.EmployeeID = p.EmployeeID
ORDER BY e.first_name;

4.Get all project names from the "ProjectDetail" table, even if they are
not linked to any employee, sorted by first name from the "employee
table"
and "ProjectDetail" table.

A) SELECT e.first_name, p.ProjectName


FROM ProjectDetail p
LEFT JOIN employee e ON p.EmployeeID = e.EmployeeID
ORDER BY e.first_name;

5.Find the project names from the "ProjectDetail" table that have not
been assigned to any employee using the "employee table" and
"ProjectDetail" table.

A) SELECT ProjectName
FROM ProjectDetail
WHERE EmployeeID NOT IN (SELECT EmployeeID FROM employee);\
SQL ASSIGNME NT
6.Get the employee name and project name for employees who are
assigned to more than one project.

A) SELECT e.first_name, p.ProjectName


FROM employee e
JOIN ProjectDetail p ON e.EmployeeID = p.EmployeeID
WHERE e.EmployeeID IN (
SELECT EmployeeID
FROM ProjectDetail

GROUP BY EmployeeID

HAVING COUNT(*) > 1)


ORDER BY e.first_name;

7.Get the project name and the employee names of employees


working on projects that have more than one employee assigned.

A) SELECT p.ProjectName, e.first_name


FROM ProjectDetail p
JOIN employee e ON p.EmployeeID = e.EmployeeID
WHERE p.ProjectName IN (
SELECT ProjectName
FROM ProjectDetail
GROUP BY ProjectName
HAVING COUNT(DISTINCT EmployeeID) > 1)
ORDER BY p.ProjectName;

8.Get records from the "ProjectDetail" table where the corresponding


employee ID does not exist in the "employee table."

A) SELECT *FROM ProjectDetail


WHERE EmployeeID NOT IN (SELECT EmployeeID FROM employee);

Ranking Functions
1.Get all project names from the "ProjectDetail" table, even if they are
not linked to any employee, sorted by first name from the "employee
table" and "ProjectDetail" table.
SQL ASSIGNME NT
A) SELECT e.first_name, p.ProjectName
FROM ProjectDetail p
LEFT JOIN employee e ON p.EmployeeID = e.EmployeeID
ORDER BY e.first_name;

2.Find the project names from the "ProjectDetail" table that have not
been assigned to
any employee using the "employee table" and "ProjectDetail" table.

A) SELECT p.ProjectName
FROM ProjectDetail p
LEFT JOIN employee e ON p.EmployeeID = e.EmployeeID
WHERE e.EmployeeID IS NULL;

3.Get the employee name and project name for employees who are
assigned to more than one project.

A) SELECT e.first_name, p.ProjectName


FROM employee e
JOIN ProjectDetail p ON e.EmployeeID = p.EmployeeID
WHERE e.EmployeeID IN (
SELECT EmployeeID
FROM ProjectDetail GROUP BY EmployeeID
HAVING COUNT(*) > 1) ORDER BY e.first_name;

4.Get the project name and the employee names of employees


working on projects that have more than one employee assigned.

A) SELECT p.ProjectName, e.first_name


FROM ProjectDetail p
JOIN employee e ON p.EmployeeID = e.EmployeeID
WHERE p.ProjectName IN (
SELECT ProjectName FROM ProjectDetail
GROUP BY ProjectName HAVING COUNT(DISTINCT EmployeeID) > 1)
ORDER BY p.ProjectName, e.first_name;

5.Get records from the "ProjectDetail" table where the corresponding


employee ID does not
exist in the "employee table."
SQL ASSIGNME NT
A) SELECT p.*
FROM ProjectDetail p
LEFT JOIN employee e ON p.EmployeeID = e.EmployeeID
WHERE e.EmployeeID IS NULL

Partitioning Data

1. Assign a row number to each employee within their department


based on salary in descending order.

A).SELECT
first_name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary
DESC) AS row_num
FROM employee;

2. Rank employees within each department based on salary using RANK().

A).SELECT
first_name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
salary_rank
FROM employee;

3. Rank employees within each department based on salary using


DENSE_RANK().

A).SELECT
first_name, department, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
dense_rank
FROM employee;

4. Find the highest-paid employee in each department using RANK().

A).SELECT *
FROM (
SELECT
SQL ASSIGNME NT
first_name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
rank_within_dept
FROM employee

) ranked
WHERE rank_within_dept = 1;

5. Find the second highest-paid employee in each department using RANK().

A).SELECT *
FROM (
SELECT
first_name, department, salary,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
rank_within_dept
FROM employee) ranked WHERE rank_within_dept = 2;

6. Rank employees based on their years of experience within each department.

A).SELECT
first_name, department, joining_date,
TIMESTAMPDIFF(YEAR, joining_date, CURDATE()) AS years_experience,

RANK() OVER (PARTITION BY department ORDER BY TIMESTAMPDIFF(YEAR,


joining_date, CURDATE()) DESC) AS exp_rank
FROM employee;

7. Find the employee with the earliest join date in each department using
RANK().

A).SELECT *
FROM (
SELECT
first_name, department, joining_date,
RANK() OVER (PARTITION BY department ORDER BY joining_date ASC) AS
join_rank
FROM employee
) ranked
WHERE join_rank = 1;
SQL ASSIGNME NT
Complex Ranking Scenarios
1. Find the employees who earn more than the average salary of their
department.

A).SELECT *
FROM employee e
WHERE salary > (

SELECT AVG(salary)
FROM employee
WHERE department = e.department
);

2. Rank employees within each job title in every department based on salary.

A).SELECT
first_name, department, job_title, salary,
RANK() OVER (PARTITION BY department, job_title ORDER BY salary DESC) AS
salary_rank
FROM employee;

3.Find the top 3 highest-paid employees in each department.

A).SELECT *cFROM (
SELECT *,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS
dept_salary_rank
FROM employee
) rankedvvWHERE dept_salary_rank <= 3;

4.Find employees who belong to the top 10% earners within their
department using PERCENT_RANK().

A).SELECT * FROM (
SELECT *,
SQL ASSIGNME NT
PERCENT_RANK() OVER (PARTITION BY department ORDER BY
salary DESC) AS pct_rank
FROM employee
) ranked WHERE pct_rank <= 0.10;

5. Assign row numbers to employees based on their joining year


using PARTITION BY YEAR(join_date).

A).SELECT
first_name, joining_date,
ROW_NUMBER() OVER (PARTITION BY YEAR(joining_date) ORDER BY
joining_date ASC) AS row_num_by_year
FROM employee;

6.Rank employees based on the number of projects handled within each


department.

A).SELECT
e.first_name, e.department, COUNT(p.project_id) AS project_count,
RANK() OVER (PARTITION BY e.department ORDER BY COUNT(p.project_id)
DESC) AS project_rank FROM employee e
JOIN ProjectDetail p ON e.employee_id = p.employee_id
GROUP BY e.employee_id, e.first_name, e.department;

7.Find employees who are the only ones in their department


(departments with only one employee).
A).SELECT * FROM employee
WHERE department IN (
SELECT department
FROM employee
GROUP BY department
HAVING COUNT(*) = 1
);

8.Find the highest-paid employee in each job role within a department.


A).SELECT * FROM (
SELECT *,
RANK() OVER (PARTITION BY department, job_title ORDER BY salary DESC) AS
job_salary_rank
SQL ASSIGNME NT
FROM employee
) ranked
WHERE job_salary_rank = 1;

9.Find employees who have been working in the company the longest in
each department.
A).SELECT * FROM (
SELECT *,
RANK() OVER (PARTITION BY department ORDER BY joining_date ASC) AS
seniority_rank
FROM employee
) ranked
WHERE seniority_rank = 1;

Thank You

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy