some sql queries

Table - EmployeeDetails
EmpIdFullNameManagerIdDateOfJoining
121John Snow32101/31/2014
321Walter White98601/30/2015
421Kuldeep Rana87627/11/2016
Table - EmployeeSalary
EmpIdProjectSalary
121P18000
321P21000
421P112000

SQL Queries 

find firstName from FullName

select mid(FullName,1,locate(' ',FullName)) from employeedetails;

MySQL MID() extracts a substring from a string,

MID(str, pos, len)
MySQL LOCATE() returns the position of the first occurrence of a string within a string.
LOCATE(substr,str)
LOCATE (search str, str, [position])
find LastName from FullName
select substring_index(FullName,' ',-1) from employeedetails;
MySQL SUBSTRING_INDEX() returns the substring from the given string before a 
specified number of occurrences of a delimiter.
Write a SQL query to fetch all the Employees who are also managers from EmployeeDetails table
SELECT DISTINCT E.FullName
FROM EmpDetails E
INNER JOIN EmpDetails M
ON E.EmpID = M.ManagerID;
Write a SQL query to fetch all employee records from EmployeeDetails table who have a salary record in EmployeeSalary table.
SELECT * FROM EmployeeDetails E 
WHERE EXISTS 
(SELECT * FROM EmployeeSalary S WHERE  E.EmpId = S.EmpId);
Write a SQL query to fetch duplicate records from a table.
SELECT EmpId, Project, Salary, COUNT(*)
FROM EmployeeSalary
GROUP BY EmpId, Project, Salary
HAVING COUNT(*) > 1;
Write a SQL query to remove duplicates from a table 
DELETE FROM EmployeeSalary  
WHERE EmpId IN (
SELECT EmpId 
FROM EmployeeSalary       
GROUP BY Project, Salary
HAVING COUNT(*) > 1));
or
DELETE FROM EmployeeSalary
WHERE rowid NOT IN
(SELECT MAX(rowid) FROM EmployeeSalary GROUP BY EmpId);
or
select distinct * into #tmp From EmployeeSalary

       delete from EmployeeSalary

       insert into EmployeeSalary

       select * from #tmp drop table #tmp
 
       select * from EmployeeSalary
Write a SQL query to fetch only odd rows from table.
select * from emp where 
id in(select id from emp where id%2 <> 0)
Write a SQL query to fetch only even rows from table.
select * from emp where 
id in(select id from emp where id%2 = 0);





Comments