SQL All Assingment Answer
SQL All Assingment Answer
--out of 100 entries how many distict employees are there in salary
select count(distinct emp_no) from salary;
--sort by ascending
select * from dept_emp where from_date >="1990-01-01" order by from_date;
--sort by descending
select * from dept_emp where from_date >= "1990-01-01" order by to_date
desc;
-- employees having salary more than 50000 and from date is 1990-01-01
select * from salary where from_date >="1990-01-01" and salary>"50000"
order by salary;
--inner join
select e.emp_no, e.first_name, e.gender, s.salary from `employee` as e
inner join `salary` as s on e.emp_no=s.emp_no;
--left join
select e.emp_no, e.first_name, e.gender, avg(s.salary) from `employee` as e
left join `salary` as s on e.emp_no=s.emp_no group by e.emp_no;
--right join
select e.emp_no, e.first_name, e.gender, s.salary from `salary` as s left
join `employee` as e on e.emp_no=s.emp_no;
-- There is a problem
SELECT * FROM dept_emp WHERE from_date > '1990-01-01' AND dept_no = 'd005'
ORDER BY from_date DESC;
SELECT count (*) FROM titles where title="Engineer" and from_date >="1990-
01-01" and to_date <="2000-01-01"; -- Engineer who left company within 1990
and 2000
--4. Which year saw the highest and lowest no of countries participating in
Olympics?
select YEAR,min(nation_count) AS min_participant
FROM(
SELECT YEAR, COUNT(DISTINCT team) AS nation_count FROM olympic_2000 GROUP
BY YEAR
);
--7. Which Sports were just played only once in the Olympics?
SELECT sport, COUNT(DISTINCT YEAR) AS count_year
FROM olympic_2000
GROUP BY sport
HAVING count_year =1;
--10) Find the Ratio of male and female athletes participated in all
Olympic games.
SELECT 'a' AS gublu, SUM( CASE WHEN sex='M' THEN 1 ELSE 0 END) AS
male_count
, sum(CASE WHEN sex='F' THEN 1 ELSE 0 END ) AS female_count
,SUM( CASE WHEN sex='M' THEN 1 ELSE 0 END)/sum(CASE WHEN sex='F' THEN 1
ELSE 0 END ) AS ratio
FROM olympic_2000
GROUP BY gublu;
--11) Fetch the top 5 athletes who have won the most gold medals.
SELECT Name, Medal, COUNT(Medal) AS medal_count
FROM olympic_2000
WHERE Medal= 'Gold'
GROUP BY Name
ORDER BY medal_count DESC
LIMIT 5 ;
--12)Fetch the top 5 athletes who have won the most medals
(gold/silver/bronze).
SELECT Name, COUNT(Medal) AS total_medal_count
FROM olympic_2000
WHERE Medal IN ('Gold','Silver','Bronze')
GROUP BY Name
ORDER BY total_medal_count DESC LIMIT 5 ;
--18. Which countries have never won gold medal but have won silver/bronze
medals?
SELECT distinct Team
FROM olympic_2000
WHERE Medal <>'Gold'
AND medal IN ('Silver','Bronze');
--20)Break down all Olympic games where India won medal for Hockey and how
many medals in each Olympic game.
SELECT Team,YEAR, Sport, COUNT(Medal)
FROM olympic_2000
WHERE Team ='India'
AND Sport = 'Hockey'
GROUP BY 1,2,3;
SELECT YEAR,team,medal,COUNT(medal)
FROM olympic_2000
WHERE medal IN ('Gold','Silver','Bronze')
GROUP BY 1,2,3;
--Q-1. Write an SQL query to fetch “FIRST_NAME” from Worker table using the
alias name as <WORKER_NAME>.
SELECT first_name
AS WORKER_NAME
FROM Worker;
--Q-2. Write an SQL query to fetch “FIRST_NAME” from Worker table in upper
case.
SELECT upper (first_name)
AS upper_case_name
FROM Worker;
--Q-3. Write an SQL query to fetch unique values of DEPARTMENT from Worker
table.
Select distinct DEPARTMENT
from Worker;
--Q-4. Write an SQL query to print the first three characters of FIRST_NAME
from Worker table.
Select SUBSTRING(FIRST_NAME,1,3) AS three_characters
from Worker;
--Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the
first name column ‘Amitabh’
-- from Worker table.
SELECT distinct INSTR('Amitabh','A')
FROM Worker;
--Q-6. Write an SQL query to print the FIRST_NAME from Worker table after
removing
--white spaces from the right side.
Select TRIM(FIRST_NAME)
AS remove_right_whitespace
from Worker;
--Q-7. Write an SQL query to print the DEPARTMENT from Worker table after
removing white spaces
-- from the left side.
SELECT TRIM(department)
AS remove_left_whitespace
FROM Worker;
--Q-8. Write an SQL query that fetches the unique values of DEPARTMENT from
Worker table
-- and prints its length.
Select distinct length(DEPARTMENT),department AS len_dept
from Worker;
--Q-9. Write an SQL query to print the FIRST_NAME from Worker table after
replacing ‘a’ with ‘A’.
Select REPLACE(FIRST_NAME,'a','A') AS replace_first
from Worker;
--Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME from
Worker table into a
--single column COMPLETE_NAME. A space char should separate them.
SELECT (FIRST_NAME||' '|| LAST_NAME) -- Here CONCAT function is not
supported. So I use (||) this function.
AS complete_name
from Worker;
--Q-11. Write an SQL query to print all Worker details from the Worker
table order by FIRST_NAME Ascending.
SELECT first_name
FROM Worker
ORDER BY first_name;
--Q-12. Write an SQL query to print all Worker details from the Worker
--table order by FIRST_NAME Ascending and DEPARTMENT Descending.
SELECT first_name, department --(-- Query Run but bujhte parlam na)
FROM Worker
ORDER BY first_name ASC, department DESC;
--Q-13. Write an SQL query to print details for Workers with the first
--name as “Vipul” and “Satish” from Worker table.
SELECT *
FROM Worker
WHERE first_name
IN ('Vipul','Satish');
--Q-20. Write an SQL query to print details of the Workers who have (--
Parini)
--joined in Feb’2020.
SELECT first_name,last_name,joining_date
FROM Worker
WHERE STRFTIME('%Y',joining_date)='2020'
and STRFTIME('%m',joining_date)='02';
--Q-22. Write an SQL query to fetch worker names with salaries >= 50000
--and <= 100000.
SELECT first_name, last_name, salary
FROM Worker
WHERE salary
BETWEEN 50000 AND 100001;
--Q-23. Write an SQL query to fetch the no. of workers for each
--department in the descending order.
SELECT department,COUNT(first_name) AS emp_count
FROM Worker
GROUP BY department
ORDER BY emp_count DESC;
--Q-24. Write an SQL query to print details of the Workers who are also
Managers.
SELECT w.first_name, w.last_name, t.worker_title
FROM Worker AS w
INNER JOIN Title AS t
ON w.worker_id=t.worker_ref_id
WHERE worker_title ='Manager';
--Q-26. Write an SQL query to show only odd rows from a table.
SELECT * FROM Worker WHERE worker_id %2 <>0;
--Q-27. Write an SQL query to show only even rows from a table.
SELECT * FROM Worker WHERE mod(worker_id,2)=0;
--Q-28. Write an SQL query to clone a new table from another table.
--Q-30. Write an SQL query to show records from one table that another
--table does not have.
--Q-31. Write an SQL query to show the current date and time.
SELECT DATETIME();
--Q-32. Write an SQL query to show the top n (say 10) records of a table.
SELECT * FROM (
SELECT *,dense_rank() over (ORDER BY salary DESC) AS rnk
FROM Worker)
WHERE rnk IN (1,2,3);
--Q-33. Write an SQL query to determine the nth (say n=5) highest salary
--from a table.
-- Same as 32
--Q-34. Write an SQL query to determine the 5th highest salary without
--using TOP or limit method.
-- same as 32
--Q-35. Write an SQL query to fetch the list of employees with the same
--salary. (Same salary koto jon pay seti bar korar jonno )
Select W.WORKER_ID, W.FIRST_NAME, W.Salary
from Worker W join Worker W1
where W.Salary = W1.Salary
and W.WORKER_ID <> W1.WORKER_ID;
SELECT s.emp_no, s.salary -- ( Koto jon lok same salary pay seti
dekhar jonno)
FROM salary s, salary s1
WHERE s.salary=s1.salary
AND s.emp_no <> s1.emp_no;
--Q-36. Write an SQL query to show the second highest salary from a
--table.
--ans 1
SELECT * FROM (
SELECT *,dense_rank() over (ORDER BY salary DESC) AS rnk
FROM Worker)
WHERE rnk =2;
--ans 2
SELECT *, max(Salary) from Worker
where Salary not in (Select max(Salary) from Worker);
--Q-37. Write an SQL query to show one row twice in results from a
--table.
SELECT * from worker W WHERE -- ake row dubar kore dekhte chaile eti use
habe
W.DEPARTMENT='HR'
union all
select * from Worker W1 where
W1.DEPARTMENT='HR';
--Q-39. Write an SQL query to fetch the first 50% records from a table.
SELECT *
FROM WORKER
WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);
--Q-40. Write an SQL query to fetch the departments that have less than
--five people in it.
--Q-41. Write an SQL query to show all departments along with the
--number of people in there.
SELECT department, COUNT(department) as number_of_workers
FROM Worker
GROUP BY department;
--Q-42. Write an SQL query to show the last record from a table.
Select * from Worker
where worker_id = (SELECT max(worker_id) from Worker);
--Q-43. Write an SQL query to fetch the first row of a table.
SELECT * FROM Worker
WHERE worker_id = (SELECT min(worker_id)
FROM Worker);
--Q-44. Write an SQL query to fetch the last five records from a table.
SELECT * FROM Worker WHERE WORKER_ID <=5
UNION
SELECT * FROM (SELECT * FROM Worker W order by W.WORKER_ID
DESC) AS W1 WHERE W1.WORKER_ID <=5;
--45. Write an SQL query to print the name of employees having the
--highest salary in each department.
SELECT t.DEPARTMENT,t.FIRST_NAME,t.Salary
from(SELECT
max(Salary) as TotalSalary,DEPARTMENT
from Worker group by
DEPARTMENT) as TempNew
Inner Join Worker t on TempNew.DEPARTMENT=t.DEPARTMENT
and TempNew.TotalSalary=t.Salary;
--Q-46. Write an SQL query to fetch three max salaries from a table.
-- ans 1
SELECT distinct salary FROM (
SELECT *,dense_rank() over (ORDER BY salary DESC) AS rnk
FROM Worker)
WHERE rnk BETWEEN 1 AND 3;
--ans 2
SELECT distinct Salary from worker a WHERE 3 >= (SELECT
count(distinct Salary) from worker b WHERE a.Salary <=
b.Salary) order by a.Salary DESC;
-- Q-47. Write an SQL query to fetch three min salaries from a table.
--ans 1
SELECT distinct salary FROM (
SELECT *,dense_rank() over (ORDER BY salary ) AS rnk
FROM Worker)
WHERE rnk BETWEEN 1 AND 3
ORDER BY salary desc;
--ans 2
SELECT distinct Salary from worker a WHERE 3 >= (SELECT
count(distinct Salary) from worker b WHERE a.Salary >=
b.Salary) order by a.Salary desc;
--Q-48. Write an SQL query to fetch nth max salaries from a table.
SELECT distinct salary FROM (
SELECT *,dense_rank() over (ORDER BY salary desc ) AS rnk
FROM Worker)
WHERE rnk = 5
ORDER BY salary DESC;
--Q-49. Write an SQL query to fetch departments along with the total
--salaries paid for each of them.
SELECT department, sum(salary) AS sum_salary
from Worker
group by
department;
--Q-50. Write an SQL query to fetch the names of workers who earn the
--highest salary.
--Ans 1
SELECT FIRST_NAME, salary
from Worker
WHERE SALARY=(SELECT max(SALARY) from Worker);
-- Ans 2
SELECT first_name, salary FROM (
SELECT *,dense_rank() over (ORDER BY salary desc ) AS rnk
FROM Worker)
WHERE rnk = 1
ORDER BY salary DESC;
--2. How many permanent candidate take salary more than 5000.
SELECT * FROM emp_salary
WHERE salary >5000
AND is_permanent = 'Yes';
--4. Select the details of the employee who work either for department E-
104 or E-102.
SELECT * FROM Employee
WHERE department IN ('E-104','E-102');
--5. What is the department name for DeptID E-102?
SELECT dept_id,dept_name FROM emp_dept
WHERE dept_id= 'E-102';
-- ans 2
SELECT COUNT(project_id) FROM emp_project
WHERE start_year ='2010';
--11.select the name of the employee whose name's 3rd charactor is 'h'.
SELECT * FROM Employee
WHERE emp_name LIKE '__h%';
--Nested Queries
--ans 2
select dept_name,dept_id from emp_dept where dept_id in (select department
from
employee where emp_id>103);
--5. Select the name and email of the Dept Head who is
--not Permanent.
-- Ques.1. Write an SQL query to fetch the EmpId and FullName of all the
--employees working under Manager with id – ‘986’.
--ans : 1
SELECT COUNT(project) FROM employeesalary
WHERE project="P1";
--ans : 2
SELECT project, COUNT(empid) AS employee_count FROM employeesalary
WHERE project= 'P1'
GROUP BY project;
--4) Ques.4. Write an SQL query to find the maximum, minimum, AND
--average salary of the employees.
SELECT MAX(salary) AS max_salary, MIN(salary) AS min_salary,
AVG(salary) AS average_salary FROM employeesalary;
--Ques.5. Write an SQL query to find the employee id whose salary lies in
--the range of 9000 and 15000.
--Ques.7. Write an SQL query to fetch all the employees who either live
--in California or work under a manager with ManagerId – 321.
--Ques.8. Write an SQL query to fetch all those employees who work on
--Project other than P1.
--ans 1
SELECT * FROM employeesalary
WHERE project <> 'P1';
--ans 2
SELECT * FROM employeesalary
WHERE NOT project = 'P1';
SELECT *,
Salary+Variable as TotalSalary
FROM employeesalary;
SELECT fullname
FROM employeedetails
WHERE fullname LIKE '__hn%';
--Ques.11. Write an SQL query to fetch all the EmpIds which are present
--in either of the tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
CREATE TABLE managersalary -- First a same data diye akta table create koro
then use INTERSECT
AS SELECT * FROM employeesalary;
SELECT *
FROM EmployeeSalary
WHERE EmpId IN
(SELECT EmpId from ManagerSalary);
--Ques.13. Write an SQL query to fetch records that are present in one
--table but not in another table.
--Ques.14. Write an SQL query to fetch the EmpIds that are present in
--both the tables – ‘EmployeeDetails’ and ‘EmployeeSalary.
--Ques.15. Write an SQL query to fetch the EmpIds that are present in
--EmployeeDetails but not in EmployeeSalary.
--Ques.16. Write an SQL query to fetch the employee full names and
--replace the space with ‘-’.
--Ques.18. Write an SQL query to display both the EmpId and ManagerId
--together.
SELECT (empid||' '||managerid) AS New_ID
FROM employeedetails;
--Ques.20. Write an SQL query to upper case the name of the employee
--and lower case the city values.
SELECT UPPER(fullname)AS FIRST_NAME, LOWER(city) AS CITY
FROM employeedetails;
--Ques.21. Write an SQL query to find the count of the total occurrences
--of a particular character – ‘n’ in the FullName field.
SELECT FullName,
LENGTH(FullName) - LENGTH(REPLACE(FullName, 'n', '') ) -- kono word count
er soomoy
FROM EmployeeDetails;
--Ques.23. Fetch all the employees who are not working on any project.
--Ans 1
SELECT empid FROM managersalary
WHERE project NOT IN ('P1','P2');
-- Ans 2
SELECT EmpId
FROM EmployeeSalary
WHERE Project IS NULL;
--Ques.34. Write an SQL query to fetch only odd rows from the table
--Ans 1
SELECT * FROM employeedetails WHERE empid %2 <>0;
--Ans 2
SELECT * FROM EmployeeDetails
WHERE MOD (EmpId, 2) <> 0;
--Ques.35. Write an SQL query to fetch only even rows from the table.
--Ans 1
SELECT * FROM employeedetails WHERE empid %2 =0;
--Ans 2
SELECT * FROM EmployeeDetails
WHERE MOD (EmpId, 2) = 0;
--Ques.37. Write an SQL query to create an empty table with the same
structure as some other table.
CREATE TABLE NEW_TABLE AS
SELECT * FROM EmployeeSalary where 1=0;
SELECT * FROM (
SELECT *,dense_rank() over (ORDER BY salary DESC) AS rnk
FROM employeesalary)
WHERE rnk IN (9);
-- Ques.40. Write SQL query to find the 3rd highest salary from a table
--without using the TOP/limit keyword.
--Ans1 (Essy)
SELECT salary FROM (
SELECT *,DENSE_RANK() over (ORDER BY salary DESC) AS highest_rank
FROM employeesalary)
WHERE highest_rank IN (3);
--Ans 2 (Hard)
SELECT Salary
FROM EmployeeSalary Emp1
WHERE 2 = (
SELECT COUNT( DISTINCT ( Emp2.Salary ) )
FROM EmployeeSalary Emp2
WHERE Emp2.Salary > Emp1.Salary
);
--Q2. Write a SQL query to find the players from test match 1
--having popularity higher than the average popularity.
--Ans 1
SELECT o.player_id, t.player_name FROM cricket_1 o
INNER JOIN cricket_2 t
ON o.Player_Id=t.Player_Id;
--Ans 2
SELECT player_id, player_name FROM cricket_1
WHERE cricket_1.Player_Id IN (SELECT player_id FROM cricket_2);
--Q4. Retrieve player_id , runs, and player_name from
--cricket_1 table and display list of the players where the runs
--are more than the average runs.
SELECT DATETIME();
--Q6. Write a query to create a new table which consists of data and
--structure copied from the other table.
--Q8. Write a query to find the names of employees that begin with
--‘S’
--Ans:1
SELECT * FROM (
SELECT *,dense_rank() over (ORDER BY salary DESC) AS rnk
FROM EmployeePosition)
WHERE rnk IN (1,2,3);
--Ans:2
SELECT * FROM EmployeePosition ORDER BY Salary DESC LIMIT 3;
--Q12. Write a query to fetch all the records from the EmployeeInfo
--table ordered by EmpLname in descending order and Department
--in the ascending order.
--Ans:1
SELECT * FROM EmployeeInfo
WHERE empfname NOT IN ('Sanjay','Sonia');
--Ans:2
SELECT * FROM EmployeeInfo
WHERE empfname <>'Sanjay'
AND empfname <>'Sonia';
--Ans:1
SELECT * FROM EmployeeInfo
WHERE address IN ('Delhi(DEL)');
--Ans:2
SELECT * FROM EmployeeInfo WHERE Address
LIKE 'DELHI(DEL)%';
--Q16. Write a query to fetch all employees who also hold the
--managerial position.
--Q18. Write a query to calculate the even and odd records from a
--table.
--Q21. Write a query to find the Nth highest salary from the table
--without using TOP/limit keyword.
SELECT * FROM(
SELECT *,DENSE_RANK()over(ORDER BY salary DESC) AS rank
FROM EmployeePosition)
WHERE RANK IN (1,2,3);
SELECT * FROM (
SELECT *,DENSE_RANK()over(ORDER BY salary DESC) AS third_highest_salary
FROM EmployeePosition)
WHERE third_highest_salary IN (1,2,3);
--Q26. Write a query to display the first and the last record from the
--EmployeeInfo table.
--Q28. Write a query to retrieve Departments who have less than 2 employees
working in it.
--Q29. Write a query to retrieve EmpPostion along with total salaries paid
for each of them.
--Q30. Write a query to fetch 50% records from the EmployeeInfo table.
SELECT *
FROM EmployeeInfo WHERE
EmpID <= (SELECT COUNT(EmpID)/2 from EmployeeInfo);