[dba] data some answer with question
--select all data from salary table
select * from salary;
--select only choosen attributes
select emp_no,salary from salary;
select count(*) from salary;
--show 5 rows from salary table
select * from salary limit 3;
--to show output rows total number
select count(*) from employee;
--show distinct employee number
select distinct emp_no from salary;
--out of 100 entries how many distict employees are there in salary
select count(distinct emp_no) from salary;
select * from dept_emp;
--filter
select * from dept_emp where from_date >= "1990-01-01";
--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;
--employees having salary more than 50000 or joined after 2000-01-01
select * from salary where from_date >="1990-01-01" or salary>"50000" order
by salary;
--employees having change in their salary and how many times
select emp_no, count(*) from salary group by emp_no order by emp_no;
--employees having change in their salary more than 2 times
select emp_no, count(*) from salary group by emp_no having count(*)>2 order
by emp_no ;
--employees having change in their salary and their minimum salary
select emp_no, min(salary), count(*) from salary group by emp_no;
--employees having change in their salary and their maximum salary
select emp_no, max(salary), count(*) from salary group by emp_no;
--employees having change in their salary and their average salary
select emp_no, avg(salary), count(*) from salary group by emp_no;
--employees having change in their salary and their sum of salary
select emp_no, sum(salary), count(*) from salary group by emp_no;
select count(*) from employee;
select count(distinct emp_no) from employee;
select count(*) from salary;
select count(distinct emp_no) from salary;
--inner join
select e.emp_no, e.first_name, [Link], [Link] 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, [Link], avg([Link]) from `employee` as e
left join `salary` as s on e.emp_no=s.emp_no group by e.emp_no;
select COUNT(*) OVER () 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, [Link], [Link] from `salary` as s left
join `employee` as e on e.emp_no=s.emp_no;
--outer join using union and left and right join
select e.emp_no, e.first_name, [Link], [Link] from `employee` as e
left join `salary` as s on e.emp_no=s.emp_no
--UNION
select e.emp_no, e.first_name, [Link], [Link] from `salary` as s
left join `employee` as e on e.emp_no=s.emp_no;
learn substring and instr formula
SELECT * FROM email_details;
-- Amar @ er por theke chai
SELECT SUBSTRING(email_id,INSTR(email_id,'@')+1,LENGTH(email_id)) AS
AFTER_atthe
FROM email_details;
SELECT SUBSTRING (email_id, INSTR(email_id,'@'), LENGTH (email_id,'@'))
FROM email_details;
SELECT INSTR(email_id,'@')+1,length (email_id) FROM email_details;
Meaning of this formula
SUBSTRING(string, POSITION IN the string FOR START OF COUNT, WHERE the
COUNT will END);
@ er ager gulo dekhar somoy
SELECT SUBSTRING(email_id,1,INSTR(email_id,'@')-1) FROM email_details;
SELECT * FROM Worker;
-- Add extra string
Select SUBSTRING(first_name,1,3) AS first_characters,
SUBSTRING(last_name,1,3) AS last_characters,
lower(SUBSTRING(first_name,1,3)||SUBSTRING(last_name,1,3)||'@[Link]')
AS email_id
FROM Worker;
learn substring, instr ,formula add
email address ,strftime, ||[for join
column] , row_number, dense_rank,
rank, inner join
SELECT * FROM emp_name;
SELECT * FROM salary;
SELECT * FROM salary
WHERE STRFTIME('%Y',from_date)='2001';
SELECT * FROM emp_name
WHERE STRFTIME('%Y',date_of_birth) ='2000'
;
SELECT * FROM emp_details;
SELECT n.emp_name, n.last_name, n.date_of_birth, [Link],
d.monthly_salary
FROM emp_name AS n
INNER JOIN
emp_details AS d
ON n.emp_code=d.emp_code
WHERE monthly_salary >='30000'
AND (department='Sales'
OR monthly_salary >='98000');
SELECT * FROM email_details;
SELECT SUBSTRING(email_id,INSTR(email_id,'@'),LENGTH(email_id))AS as_athe
FROM email_details;
SELECT SUBSTRING(email_id,1,INSTR(email_id,'@')-1) AS olo
FROM email_details;
SELECT * FROM emp_name;
SELECT emp_name, last_name,date_of_birth, LOWER (emp_name||
last_name||'@[Link]') as email_id
FROM emp_name;
SELECT emp_name, last_name, date_of_birth,SUBSTRING(emp_name,1,3),
SUBSTRING(last_name,1,3),
LOWER(SUBSTRING(emp_name,1,3)||SUBSTRING(last_name,1,3)||'@[Link]') AS
email_id
FROM emp_name;
SELECT n.emp_name, n.last_name, n.date_of_birth, [Link],
d.monthly_salary
FROM emp_name AS n
INNER JOIN
emp_details AS d
ON n.emp_code=d.emp_code
ORDER BY monthly_salary DESC;
SELECT * FROM emp_details;
SELECT *,row_number()over(ORDER BY monthly_salary DESC) AS rnk
FROM emp_details;
Dba assignment solve by chordada
SELECT * FROM salary WHERE to_date = '9999-01-01';
SELECT emp_no, COUNT(from_date) AS date_count FROM salary GROUP BY emp_no;
SELECT to_date, emp_no, COUNT(*) AS count_todate FROM salary GROUP BY
to_date;
SELECT from_date, COUNT(emp_no) AS c_d FROM salary GROUP BY from_date;
-- chordada question answer
SELECT STRFTIME('%Y',from_date) AS count_year, COUNT(emp_no)AS emp_count
FROM salary GROUP BY count_year ;
-- There is a problem
SELECT to_date, MAX(frequency_count)AS freq_count FROM (
SELECT to_date, COUNT(emp_no) AS frequency_count FROM salary GROUP BY
to_date ORDER BY frequency_count DESC);
SELECT * FROM dept_emp;
SELECT * FROM dept_emp WHERE from_date > '1990-01-01' AND dept_no = 'd005'
ORDER BY from_date DESC;
SELECT COUNT(emp_no) FROM salary;
SELECT emp_no,from_date,salary FROM salary WHERE from_date >'1994-11-11'
AND (salary='40000' OR salary > '100000');
SELECT * FROM titles;
SELECT COUNT(*)FROM titles WHERE title="Engineer"AND ( from_date BETWEEN
'1990-01-01' AND '2000-01-01');
--Engineer working after 2000 as well
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
SELECT * FROM employee;
SELECT emp_no, first_name, last_name, hire_date FROM employee WHERE
hire_date BETWEEN '1990-01-01' AND '2000-01-02' ORDER BY hire_date DESC;
SELECT * FROM dept_emp;
SELECT dept_no, MIN(emp_count) AS least_emp FROM (
SELECT dept_no, COUNT(emp_no)AS emp_count FROM dept_emp GROUP BY dept_no);
SELECT * FROM titles;
SELECT * FROM salary;
SELECT title, MAX(avg_salary) FROM (
SELECT [Link], AVG([Link]) AS avg_salary
FROM titles a JOIN salary b
ON a.emp_no=b.emp_no
GROUP BY [Link]
ORDER BY avg_salary DESC);
SELECT * FROM departments;
SELECT * FROM dept_emp;
SELECT a.dept_name, COUNT(b.emp_no) AS emp_count
FROM departments a JOIN dept_emp b
ON a.dept_no=b.dept_no
GROUP BY 1
HAVING emp_count >=10;
Olympic data set answer with
question
-- First run olympic_2000 file.
SELECT * FROM olympic_2000;
-- 1. How many Olympics games have been held?
SELECT COUNT (DISTINCT year) FROM olympic_2000;
--2. List down all Olympics games held so far
SELECT DISTINCT sport FROM olympic_2000;
--How many times was a game played?
SELECT sport, COUNT( sport) AS count_sport FROM olympic_2000 GROUP BY
sport ;
--3)Mention the total no of nations who participated in each Olympics game?
SELECT YEAR, COUNT(DISTINCT team) AS count_team FROM olympic_2000 GROUP
BY YEAR;
--How many teams played in which year?
SELECT YEAR, COUNT(DISTINCT team) AS count_team FROM olympic_2000 GROUP BY
YEAR;
--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
);
--5. Which nation has participated in all of the Olympic games?
SELECT COUNT(DISTINCT YEAR) AS olympic_count FROM olympic_2000;
SELECT team, COUNT(DISTINCT YEAR) AS nation_count FROM olympic_2000 GROUP
BY team HAVING nation_count =8;
--6. Identify the sport which was played in all summer Olympics.
SELECT DISTINCT sport, season FROM olympic_2000 WHERE season = 'Summer';
--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;
--8. Fetch the total no of sports played in each Olympic game.
SELECT YEAR, COUNT(DISTINCT sport) AS count_sports
FROM olympic_2000
GROUP BY YEAR;
--9. Fetch details of the oldest athletes to win a gold medal.
SELECT Name,MAX(Age) AS max_age, Medal FROM (
SELECT Name, Age, Medal
FROM olympic_2000
WHERE Medal ='Gold'
ORDER BY Age DESC);
--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;
-- Ratio bar korar formula
WITH male AS (SELECT 'A' as column,sex,COUNT(sex)AS male_count FROM
olympic_2000 WHERE sex='M' GROUP BY sex)
,female AS (SELECT 'A' as COLUMN,sex,COUNT(sex)AS female_count FROM
olympic_2000 where sex='F' GROUP BY sex)
SELECT male_count, female_count, male_count/female_count AS ratio
FROM male JOIN female
on [Link]=[Link];
--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 ;
--13)Fetch the top 5 most successful countries in Olympics. Success is
defined by no of medals won.
SELECT Team, COUNT(Medal) AS medal_count
FROM olympic_2000
GROUP BY Name
ORDER BY 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');
--[Link] which Sport/event, India has won highest medals?
SELECT Team, Sport, MAX(medal_count) AS highest_medal FROM
(
SELECT team,sport, COUNT(Medal) AS medal_count
FROM olympic_2000
WHERE Team IN ('India')
GROUP BY team,sport
ORDER BY medal_count DESC);
--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;
--14) and 15) both
SELECT Team, YEAR,
SUM(CASE WHEN Medal = 'Gold' THEN 1 ELSE 0 END) AS gold_medal_count,
SUM(CASE WHEN Medal = 'Silver' THEN 1 ELSE 0 END) AS silver_medal_count,
SUM(CASE WHEN Medal = 'Bronze' THEN 1 ELSE 0 END) AS bronze_medal_count,
SUM(CASE WHEN Medal = 'Gold' THEN 1 ELSE 0 END)+SUM(CASE WHEN Medal =
'Silver' THEN 1 ELSE 0 END)+SUM(CASE WHEN Medal = 'Bronze' THEN 1 ELSE 0
END) AS total_medal_count
FROM olympic_2000
GROUP BY team,year
ORDER BY total_medal_count DESC;
--16)and 17) chesta cholche
SELECT
CASE WHEN YEAR='2002' AND MAX(gold_medal_count) THEN team END AS gold_2002
FROM (
SELECT Team, YEAR,
SUM(CASE WHEN Medal = 'Gold' THEN 1 ELSE 0 END) AS gold_medal_count,
SUM(CASE WHEN Medal = 'Silver' THEN 1 ELSE 0 END) AS silver_medal_count,
SUM(CASE WHEN Medal = 'Bronze' THEN 1 ELSE 0 END) AS bronze_medal_count,
SUM(CASE WHEN Medal = 'Gold' THEN 1 ELSE 0 END)+SUM(CASE WHEN Medal =
'Silver' THEN 1 ELSE 0 END)+SUM(CASE WHEN Medal = 'Bronze' THEN 1 ELSE 0
END) AS total_medal_count
FROM olympic_2000
GROUP BY team,year
ORDER BY total_medal_count DESC);
SELECT YEAR,team,medal,COUNT(medal)
FROM olympic_2000
WHERE medal IN ('Gold','Silver','Bronze')
GROUP BY 1,2,3;
Top 50 assignment queries with
answer
SELECT * FROM Worker;
--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-14. Write an SQL query to print details of workers excluding first
--names, “Vipul” and “Satish” from Worker table.
SELECT *
FROM Worker
WHERE first_name
NOT IN ('Vipul','Satish');
--Q-15. Write an SQL query to print details of Workers with
--DEPARTMENT name as “Admin”.
SELECT *
FROM Worker
WHERE department ='Admin';
--Q-16. Write an SQL query to print details of the Workers whose
--FIRST_NAME contains ‘a’.
SELECT *
FROM Worker
WHERE first_name
LIKE '%a%';
--Q-17. Write an SQL query to print details of the Workers whose
--FIRST_NAME ends with ‘a’.
SELECT *
FROM Worker
WHERE first_name
LIKE '%a';
--Q-18. Write an SQL query to print details of the Workers whose
--FIRST_NAME ends with ‘h’ and contains six alphabets.
SELECT *
from Worker
where FIRST_NAME
LIKE '%h'
AND LENGTH(first_name) = 6;
--Q-19. Write an SQL query to print details of the Workers whose
--SALARY lies between 100000 and 500000.
SELECT first_name,last_name,salary
FROM Worker
WHERE salary
BETWEEN 100000 AND 500000
ORDER BY salary DESC;
--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-21. Write an SQL query to fetch the count of employees working in
--the department ‘Admin’.
SELECT department, COUNT(department) AS count_department
FROM Worker
WHERE department ='Admin';
--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-25. Write an SQL query to fetch duplicate records having matching
--data in some fields of a table.
SELECT *, COUNT(*) AS count_duplicate
FROM Title
GROUP BY worker_title, affected_from
HAVING count_duplicate > 1;
--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.
--Ans: This is the process of backup table
CREATE TABLE worker_clone
AS SELECT * FROM Worker;
--Q-29. Write an SQL query to fetch intersecting records of two tables.
SELECT * FROM Worker
INTERSECT
SELECT * FROM worker_clone;
--Q-30. Write an SQL query to show records from one table that another
--table does not have.
SELECT w.*, t.worker_title
FROM Worker w
JOIN Title t
ON w.worker_id=t.worker_ref_id;
--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, [Link]
from Worker W join Worker W1
where [Link] = [Link]
and W.WORKER_ID <> W1.WORKER_ID;
SELECT s.emp_no, [Link] -- ( Koto jon lok same salary pay seti
dekhar jonno)
FROM salary s, salary s1
WHERE [Link]=[Link]
AND s.emp_no <> s1.emp_no;
select emp_no, row_number() over (order by emp_no)
from dept_emp;
--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
[Link]='HR'
union all
select * from Worker W1 where
[Link]='HR';
--Q-38. Write an SQL query to fetch intersecting records of two tables.
SELECT * FROM Worker
INTERSECT
SELECT * FROM worker_clone;
--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.
SELECT DEPARTMENT, COUNT(WORKER_ID) as numbers_of_worker
FROM Worker
GROUP BY DEPARTMENT
HAVING COUNT (WORKER_ID) < 5;
--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 [Link],t.FIRST_NAME,[Link]
from(SELECT
max(Salary) as TotalSalary,DEPARTMENT
from Worker group by
DEPARTMENT) as TempNew
Inner Join Worker t on [Link]=[Link]
and [Link]=[Link];
--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 [Link] <=
[Link]) order by [Link] 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 [Link] >=
[Link]) order by [Link] 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;
SELECT * FROM Worker;
--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;
Simple and nested queries
-- 1. Select the detail of the employee whose name start with P.
SELECT * FROM Employee
WHERE emp_name
LIKE 'P%';
--2. How many permanent candidate take salary more than 5000.
SELECT * FROM emp_salary
WHERE salary >5000
AND is_permanent = 'Yes';
--3. Select the detail of employee whose emailId is in gmail.
SELECT * FROM Employee
WHERE email_id LIKE '%[Link]';
--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';
--6. What is total salary that is paid to permanent employees?
SELECT sum(salary) AS salary_sum
FROM emp_salary
WHERE is_permanent = 'Yes';
--[Link] name of all employees whose name ends with a.
SELECT * FROM Employee
WHERE emp_name LIKE '%a';
--8. List the number of department of employees in each project.
select count(emp_id) as employee, project_id
from emp_project
group by
project_id;
--9. How many project started in year 2010.
-- ans 1
SELECT start_year,count(project_id)
FROM emp_project
WHERE start_year = '2010'
GROUP BY start_year;
-- ans 2
SELECT COUNT(project_id) FROM emp_project
WHERE start_year ='2010';
--[Link] many project started and finished in the same year.
SELECT COUNT(*) FROM emp_project
WHERE start_year=end_year;
--[Link] the name of the employee whose name's 3rd charactor is 'h'.
SELECT * FROM Employee
WHERE emp_name LIKE '__h%';
--Nested Queries
--1. Select the department name of the company
--which is assigned to the employee whose
--employee id is grater 103
-- ans 1
SELECT dept_id,dept_name FROM emp_dept
WHERE dept_id <'E-103';
--ans 2
select dept_name,dept_id from emp_dept where dept_id in (select department
from
employee where emp_id>103);
--2. Select the name of the employee who is working
--under Abhishek
select emp_name from Employee
where emp_head_id =(select emp_id from
employee where emp_name='Abhishek');
--3. Select the name of the employee who is department
--head of HR.
select emp_name from Employee
where emp_id =(select dept_head from emp_dept
where dept_name='HR');
--4. Select the name of the employee head who is
--permanent.
select emp_name from Employee
where emp_id in(select emp_head_id from
employee) and emp_id in(select emp_id from emp_salary where
is_permanent='Yes');
--5. Select the name and email of the Dept Head who is
--not Permanent.
SELECT emp_name, email_id FROM Employee
WHERE emp_id IN (SELECT emp_head_id FROM
Employee) AND emp_id IN (SELECT emp_id FROM emp_salary WHERE
is_permanent='No');
--6. Select the employee whose department off is
--monday
select emp_name,department from Employee
where department in(select dept_id from emp_dept
where dept_off='Monday');
--7. select the indian clients details.
SELECT client_name, cid FROM client_table
WHERE cid IN (SELECT cid FROM country
WHERE cname ='India');
--8. select the details of all employee working in
--development department.
SELECT * FROM Employee
WHERE department IN (SELECT dept_id FROM emp_dept
WHERE dept_name ='Development');
Top 40 interview queries with
answer
-- SQL Queries interview questions
-- Ques.1. Write an SQL query to fetch the EmpId and FullName of all the
--employees working under Manager with id – ‘986’.
SELECT empid, fullname FROM employeedetails
WHERE managerid = 986;
--Ques.2. Write an SQL query to fetch the different projects available
--from the EmployeeSalary table.
SELECT DISTINCT(project) FROM employeesalary;
--Ques.3. Write an SQL query to fetch the count of employees working
--in project ‘P1’.
--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.
SELECT empid,salary FROM employeesalary
WHERE salary BETWEEN 9000 AND 15000;
--Ques.6. Write an SQL query to fetch those employees who live in
--Toronto and work under manager with ManagerId – 321.
SELECT * FROM employeedetails
WHERE city = 'Toronto'
AND managerid = '321';
--Ques.7. Write an SQL query to fetch all the employees who either live
--in California or work under a manager with ManagerId – 321.
SELECT * FROM employeedetails
WHERE city = 'California'
OR 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';
--Ques.9. Write an SQL query to display the total salary of each
--employee adding the Salary with Variable value.
SELECT *,
Salary+Variable as TotalSalary
FROM employeesalary;
--Ques.10. Write an SQL query to fetch the employees whose name
--begins with any two characters, followed by a text “hn” and ending
--with any sequence of characters.
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’.
SELECT EmpId FROM EmployeeDetails
UNION
SELECT EmpId FROM EmployeeSalary;
--Ques.12. Write an SQL query to fetch common records between two
--tables.
CREATE TABLE managersalary -- First a same data diye akta table create koro
then use INTERSECT
AS SELECT * FROM employeesalary;
SELECT * FROM employeesalary
INTERSECT
SELECT * FROM managersalary;
-- For My SQL ( jehetu my sql a intersect option kaj korena)
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.
SELECT EmpId FROM
employeesalary
where EmpId Not IN
(SELECT EmpId FROM managersalary);
--Ques.14. Write an SQL query to fetch the EmpIds that are present in
--both the tables – ‘EmployeeDetails’ and ‘EmployeeSalary.
SELECT EmpId FROM
EmployeeDetails
where EmpId IN
(SELECT EmpId FROM employeesalary);
--Ques.15. Write an SQL query to fetch the EmpIds that are present in
--EmployeeDetails but not in EmployeeSalary.
SELECT EmpId FROM
EmployeeDetails
where EmpId Not IN
(SELECT EmpId FROM employeesalary);
--Ques.16. Write an SQL query to fetch the employee full names and
--replace the space with ‘-’.
Select REPLACE(fullname,' ','_') AS replace_first
from employeedetails;
--Ques.17. Write an SQL query to fetch the position of a given
--character(s) in a field.
SELECT fullname,INSTR(FullName, 'Snow')
FROM employeedetails;
--Ques.18. Write an SQL query to display both the EmpId and ManagerId
--together.
SELECT (empid||' '||managerid) AS New_ID
FROM employeedetails;
--Ques.19. Write a query to fetch only the first name(string before
--space) from the FullName column of the EmployeeDetails table.
SELECT SUBSTRING(fullname, 1, instr(' ',fullname)) AS small -- Parini
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.22. Write an SQL query to update the employee names by removing
leading and trailing spaces.
UPDATE employeedetails -- Table Update bolle eti
SET FullName = LTRIM(RTRIM(FullName));
SELECT TRIM( fullname) FROM employeedetails; -- Normal bolle eti
--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.24. Write an SQL query to fetch employee names having a salary
greater than
--or equal to 5000 and less than or equal to 10000.
SELECT [Link], [Link] FROM employeedetails AS d
INNER JOIN employeesalary AS s ON [Link]=[Link]
WHERE salary BETWEEN 5000 AND 10000;
--Ques.25. Write an SQL query to find the current date-time.
select DATETIME(); --[SQLite]
SELECT NOW(); -- [My SQL]
SELECT getdate(); -- [SQL Server]
SELECT SYSDATE FROM DUAL; -- [Oracle]
--Ques.26. Write an SQL query to fetch all the Employees details
--from EmployeeDetails table who joined in the Year 2020.
SELECT * FROM employeedetails
WHERE dateOfjoining BETWEEN '2020/01/01'
AND '2020/12/31';
SELECT * FROM employeedetails -- [ My SQL]
WHERE YEAR(dateOfJoining) = '2020';
--Ques.27. Write an SQL query to fetch all employee records from
--EmployeeDetails table who have a salary record in EmployeeSalary
--table
SELECT * FROM employeedetails E -- Using Exists
WHERE EXISTS
(SELECT * FROM EmployeeSalary S
WHERE [Link] = [Link]);
--Ques.28. Write an SQL query to fetch project-wise count of employees
--sorted by project’s count in descending order
SELECT Project, count(EmpId) AS EmpProjectCount
FROM EmployeeSalary
GROUP BY Project
ORDER BY EmpProjectCount DESC;
--Ques.29. Write a query to fetch employee names and salary records.
--Display the employee details even if the salary record is not present
--for the employee.
SELECT [Link], [Link]
FROM EmployeeDetails E
LEFT JOIN
EmployeeSalary S
ON [Link] = [Link];
-- Ques.30. Write an SQL query to join 3 tables.
SELECT column1, column2
FROM TableA
JOIN TableB ON TableA.Column3 = TableB.Column3
JOIN TableC ON TableA.Column4 = TableC.Column4;
--Ques. 31. Write an SQL query to fetch all the Employees
-- who are also managers from the EmployeeDetails table.
SELECT DISTINCT [Link]
FROM EmployeeDetails E
INNER JOIN EmployeeDetails M
ON [Link] = [Link];
--Ques.32. Write an SQL query to fetch duplicate records from
EmployeeDetails
-- (without considering the primary key – EmpId).
SELECT FullName, ManagerId, DateOfJoining, City, COUNT(*) AS
dublicate_count
FROM EmployeeDetails
GROUP BY FullName, ManagerId, DateOfJoining, City
HAVING COUNT(*) > 1;
--Ques.33. Write an SQL query to remove duplicates from a table without
using a temporary table.
DELETE E1 FROM EmployeeDetails E1 (--Parini vulval ache)
INNER JOIN EmployeeDetails E2
WHERE [Link] > [Link]
AND [Link] = [Link]
AND [Link] = [Link]
AND [Link] = [Link]
AND [Link] = [Link];
--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.36. Write an SQL query to create a new table
-- with data and structure copied from another table.
CREATE TABLE NewTable AS
SELECT * FROM employeesalary;
--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;
--Ques.38. Write an SQL query to fetch top n records?
SELECT * --[In My SQL]
FROM EmployeeSalary
ORDER BY Salary DESC LIMIT N;
SELECT TOP N * --[ IN sql server]
FROM EmployeeSalary
ORDER BY Salary DESC;
--Ques.39. Write an SQL query to find the nth highest salary from table.
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 ( [Link] ) )
FROM EmployeeSalary Emp2
WHERE [Link] > [Link]
);
great learning Cricket query
--Q1. Find all the players who were present in the test match 1
--or test match 2 .
SELECT trim(player_name) FROM cricket_1 -- White space remove kore dekhte
chaile
UNION
SELECT trim(player_name) FROM cricket_2;
--Q2. Write a SQL query to find the players from test match 1
--having popularity higher than the average popularity.
SELECT player_name, popularity FROM cricket_1
WHERE popularity > (SELECT AVG(popularity) FROM cricket_1);
--Q3. Find player_id and player_name that are common in the
--test match 1 and test match 2.
--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 player_id, player_name, runs FROM cricket_1
WHERE runs > (SELECT AVG(runs) FROM cricket_1);
--Q5. Write a query to extract the player_id, runs, and
--player_name from the table “cricket_1” where the runs are
--greater than 50.
SELECT player_id, player_name, runs FROM cricket_1
WHERE runs >50;
--Q6. Write a query to extract all the columns from cricket_1
--where player_name starts with ‘y’ and ends with ‘v’.
SELECT player_name FROM cricket_1
WHERE player_name LIKE 'y%v' ;
--Q7. Write a query to extract all the columns from cricket_1
--where player_name does not end with ‘t’
SELECT player_name FROM cricket_1
WHERE player_name NOT LIKE '%t';
Top 30 sql query with answer
--Q1. Write a query to fetch the EmpFname from the EmployeeInfo
--table in upper case and use the ALIAS name as EmpName.
SELECT upper(empfname) AS Empname FROM EmployeeInfo;
--Q2. Write a query to fetch the number of employees working in the
--department ‘HR’.
SELECT department,COUNT(empfname) AS Empcount FROM EmployeeInfo
WHERE department = 'HR'
GROUP BY department;
--Q3. Write a query to get the current date.
SELECT DATETIME();
--Q4. Write a query to retrieve the first four characters
--of EmpLname from the EmployeeInfo table.
Select emplname,SUBSTRING(emplname,1,4) AS retrieve_first_four_characters
from EmployeeInfo;
--Q5. Write a query to fetch only the place name(string before
--brackets) from the Address column of EmployeeInfo table.
SELECT SUBSTRING(address,1,INSTR(address,'(')-1) AS cut_place --{SQLITE]
FROM EmployeeInfo;
SELECT MID(Address, 0, LOCATE('(',Address)) FROM EmployeeInfo; --[MySQL]
--Q6. Write a query to create a new table which consists of data and
--structure copied from the other table.
CREATE TABLE NewTable AS --[SQLite]
SELECT * FROM EmployeeInfo;
SELECT * INTO NewTable --[My SQL]
FROM EmployeeInfo WHERE 1 = 0;
--Q7. Write q query to find all the employees whose salary is
--between 50000 to 100000.
SELECT * FROM EmployeePosition
WHERE salary BETWEEN 50000 AND 100000;
--Q8. Write a query to find the names of employees that begin with
--‘S’
SELECT empfname FROM EmployeeInfo
WHERE empfname LIKE 'S%';
--Q9. Write a query to fetch top N records.
--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;
--Q10. Write a query to retrieve the EmpFname and EmpLname in a
--single column as “FullName”. The first name and the last name
--must be separated with space.
SELECT (empfname||' '|| emplname)
AS FullName
from EmployeeInfo;
--Q11. Write a query find number of employees whose DOB is
--between 02/05/1970 to 31/12/1975 and are grouped according to
--gender
SELECT COUNT(*), empfname,Gender FROM EmployeeInfo
WHERE DOB BETWEEN '1970-05-02 ' AND '1975-12-31'
GROUP BY Gender;
--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.
SELECT * FROM EmployeeInfo --[Eta kono din somvob noy]
ORDER BY EmpLname desc, Department ASC;
--Q13. Write a query to fetch details of employees whose EmpLname
--ends with an alphabet ‘A’ and contains five alphabets.
SELECT emplname FROM EmployeeInfo
WHERE emplname LIKE '____a';
--Q14. Write a query to fetch details of all employees excluding the
--employees with first names, “Sanjay” and “Sonia” from the
--EmployeeInfo table.
--Ans:1
SELECT * FROM EmployeeInfo
WHERE empfname NOT IN ('Sanjay','Sonia');
--Ans:2
SELECT * FROM EmployeeInfo
WHERE empfname <>'Sanjay'
AND empfname <>'Sonia';
--Q15. Write a query to fetch details of employees with the address
--as “DELHI(DEL)”.
--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.
SELECT [Link],[Link],[Link] FROM EmployeeInfo i
INNER JOIN EmployeePosition p
ON [Link]=[Link]
WHERE empposition IN ('Manager');
--Q17. Write a query to fetch the department-wise count of
--employees sorted by department’s count in ascending order.
SELECT department,COUNT(empid) AS emp_count
FROM EmployeeInfo
GROUP BY department
ORDER BY emp_count ASC;
--Q18. Write a query to calculate the even and odd records from a
--table.
--Calculate Odd row
SELECT COUNT(*) AS count_odd_row FROM EmployeeInfo
WHERE empid %2 <> 0;
-- Calculate Even row
SELECT COUNT(*) AS count_odd_row FROM EmployeeInfo
WHERE empid %2 = 0;
--Q19. Write a SQL query to retrieve employee details from
--EmployeeInfo table who have a date of joining in the
--EmployeePosition table.
SELECT * FROM EmployeeInfo E --Bujhte parini
WHERE EXISTS
(SELECT * FROM EmployeePosition P WHERE [Link] = [Link]);
--Q20. Write a query to retrieve two minimum and maximum
--salaries from the EmployeePosition table.
SELECT DISTINCT Salary FROM EmployeePosition E1 -- Parini
WHERE 2 >= (SELECTCOUNT(DISTINCT Salary)FROM EmployeePosition E2
WHERE [Link] >= [Link]) ORDER BY [Link] DESC;
--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);
--Q22. Write a query to retrieve duplicate records from a table.
SELECT EmpID, EmpFname,emplname Department, COUNT(*) --[Mone hoy etai
Answer habe]
FROM EmployeeInfo
GROUP BY EmpID, EmpFname,emplname, Department
HAVING COUNT(*) > 1;
--Q23. Write a query to retrieve the list of employees working in the
[Parini]
--same department.
Select DISTINCT [Link], [Link], [Link]
FROM EmployeeInfo E, Employee E1
WHERE [Link] = [Link] AND [Link] <> [Link];
--Q24. Write a query to retrieve the last 3 records from the
--EmployeeInfo table.
SELECT * FROM EmployeeInfo -- Ami korechhi
ORDER BY empid DESC LIMIT 3;
SELECT * FROM EmployeeInfo WHERE -- Ora korechhe
EmpID <=3 UNION SELECT * FROM
(SELECT * FROM EmployeeInfo E ORDER BY [Link] DESC)
AS E1 WHERE [Link] <=3;
--Q25. Write a query to find the third-highest salary from the
--EmpPosition table.
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.
--Show first record
SELECT * FROM EmployeeInfo
WHERE EmpID = (SELECT MIN(EmpID) FROM EmployeeInfo);
--Show last record
SELECT * FROM EmployeeInfo
WHERE EmpID = (SELECT max(EmpID) FROM EmployeeInfo);
--Q27. Write a query to add email validation to your database [Parini]
ALTER TABLE EmployeeInfo
ADD COLUMN email_validation VARCHAR(30);
INSERT INTO EmployeeInfo (email_validation)
values ('sanjaymehra05@[Link]'),
('ananyamishra15@[Link]'),
('rohandiwan@[Link]'),
('soniakulkarni027@[Link]'),
('ankitkapoor@[Link]');
--Q28. Write a query to retrieve Departments who have less than 2 employees
working in it.
SELECT department, COUNT(empid) AS employee_count FROM EmployeeInfo
GROUP BY department
HAVING employee_count <2;
--Q29. Write a query to retrieve EmpPostion along with total salaries paid
for each of them.
SELECT EmpPosition, SUM(Salary) from EmployeePosition
GROUP BY EmpPosition;
--Q30. Write a query to fetch 50% records from the EmployeeInfo table.
SELECT *
FROM EmployeeInfo WHERE
EmpID <= (SELECT COUNT(EmpID)/2 from EmployeeInfo);