0% found this document useful (0 votes)
12 views9 pages

SQLL

The document contains a series of SQL queries and commands for managing and manipulating data in a database, including creating tables, inserting data, and performing various data retrieval operations. It covers a wide range of SQL functionalities such as filtering, grouping, joining, and using window functions. Additionally, it includes examples of how to handle duplicates, calculate percentages, and perform recursive queries.

Uploaded by

janitpandita04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

SQLL

The document contains a series of SQL queries and commands for managing and manipulating data in a database, including creating tables, inserting data, and performing various data retrieval operations. It covers a wide range of SQL functionalities such as filtering, grouping, joining, and using window functions. Additionally, it includes examples of how to handle duplicates, calculate percentages, and perform recursive queries.

Uploaded by

janitpandita04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

-- Online SQL Editor to Run SQL Online.

-- Use the editor to create new tables, insert data and all other SQL operations.

-- Q1: QUERY TO FETCH FIRST NAME FROM WORKER TABLE


SELECT FIRST_NAME AS WORKER_NAME FROM WORKER;

-- Q2: FETCH FIRST NAME IN UPPER WORDS


SELECT UPPER(FIRST_NAME) FROM WORKER;

-- Q3: SQL QUERY TO FETCH UNIQUE VALUES OF DEPT FROM WORKER TABLE
SELECT DISTINCT dept FROM WORKER;

-- Q4: SQL QUERY TO PRINT THE FIRST THREE CHARACTERS OF FIRST_NAME


SELECT SUBSTRING(FIRST_NAME,1,3) FROM WORKER;

-- Q5: QUERY TO FIND THE POSITION OF ALPHABET 'B' IN FIRST NAME


SELECT INSTR(FIRST_NAME,'B')FROM WORKER WHERE FIRST_NAME ='AMITABH';

-- 6: QUERT TO PRINT THE FIRST_NAME FROM WORKER AFTER REMOVING SPACES FROM
RIGHTSIDE
SELECT RTRIM(FIRST_NAME) FROM WORKER;

-- 7: SQL QUERY THAT FETCHES THE UNIQUE VALUE OF DEPT FROM WORKER AND PRINTS ITS
LENGTH
SELECT DISTINCT(department), LENGTH(department) FROM WORKER

-- 8 SQL QUERY TO PRINT FIRST_NAME AND REPLACING a WITH A


SELECT REPLACE(FIRST_NAME,'a','A') FROM WORKER;

-- 9 SQL query to print the FIRST_NAME and LAST_NAME from Worker table into a
single column COMPLETE_NAME
SELECT CONCAT(FIRST_NAME," ",LAST_NAME) AS COMPLETE_NAME FROM WORKERS

-- 10 query to print all Worker details from the Worker table order by FIRST NAME
Ascending
SELECT * FROM WORKER ORDER BY FIRST_NAME ASC;

-- 11 query to print all Worker details from the Worker table order by FIRST NAME
Ascending AND DEPT DESCENDING
SELECT * FROM WORKER ORDER BY FIRST_NAME ASC, department DESC;

-- 12 SQL QUERY TO FETCH DETAILS FOR WORKER WITH FIRST_NAME AS VIPUL AND SATISH
FROM WORKER
SELECT * FROM WORKER WHERE FIRST_NAME IN("VIPUL","SATISH")

-- 13 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")

-- 14 query to print details of Workers with DEPARTMENT name as "Admins".


SELECT * FROM WORKER WHERE DEPARTMENT='ADMIN'

-- 15 query to print details of the Workers whose FIRST_NAME contains 'a'.


SELECT * FROM WORKER WHERE FIRST_NAME LIKE'%a%'

-- 16 query to print details of the Workers whose FIRST_NAME ENDS WITH 'a'
SELECT * FROM WORKER WHERE FIRST_NAME LIKE'%a'

-- 17 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'

-- 18 Write an SOL query to print details of the Workers whose SALARY lies between
100000 and 500000.
SELECT* FROM WORKER WHERE SALARY BETWEEN 10000000 AND 25000000

-- 19 query to print details of the Workers who have joined in Feb 2014
SELECT * FROM WORKER WHERE YEAR(JOINING_DATE)=2014 AND MONTH(JOINING_MONTH)=02;

-- 20 QUERY TO FETCH COUNT OF EMPLOYEE WORKING IN DEPARTMENT ADMIN


SELECT DEPARTMENT, COUNT(EMPLOYEE) FROM WORKER WHERE DEPARTMENT='ADMIN'

-- BHAARI ON MIND
-- 21 QUERY TO FETCH NUMBER OF WORKER FOR EACH DEPT IN DESCENDING ORDER
SELECT DEPARTMENT, COUNT(EMPLOYEE) FROM WORKER GROUP BY DEPARTMENT ORDER BY
COUNT(EMPLOYEE) DESC

-- 22 SQL QUERY TO PRINT DETAILS OF WORKER WHO ARE MANAGERS


SELECT * FROM WORKER AS W INNER JOIN TITLE AS T ON W.WORKER_ID=T.TITLE_WORKER_REFID
WHERE T.WORKER_REFID='MANAGER';

-- 23 QUERY TO FETCH NUMBER OF SAME TITLES IN THE ORG OF DIFFERENT TYPES


SELECT WORKER_TITLE, COUNT(*)
CREATE TABLE employee (
empid INT PRIMARY KEY,
empname VARCHAR(100),
empsal DECIMAL(10, 2),
empphno VARCHAR(15),
empstate VARCHAR(50)
);

-- Insert 10 sample values into the employee table


INSERT INTO employee (empid, empname, empsal, empphno, empstate) VALUES
(1, 'John Doe', 50000.00, '1234567890', 'California'),
(2, 'Jane Smith', 60000.00, '1234567891', 'New York'),
(3, 'Alice Brown', 55000.00, '1234567892', 'Texas'),
(4, 'Bob Johnson', 75000.00, '1234567893', 'Florida'),
(5, 'Charlie Davis', 62000.00, '1234567894', 'Illinois'),
(6, 'Eve White', 70000.00, '1234567895', 'California'),
(7, 'Frank Green', 72000.00, '1234567896', 'Ohio'),
(8, 'Grace Adams', 52000.00, '1234567897', 'Georgia'),
(9, 'Hank Williams', 58000.00, '1234567898', 'Texas'),
(10, 'Ivy Clark', 80000.00, '1234567899', 'Washington');

--CTEFUNCTION USED TO FIND THE NTH LARGEST VALUE FROM A COLUMN


with rankedamount as(
select amount, dense_rank() over (order by amount desc) as amount_rank
from orders
)
SELECT amount
FROM rankedamount
where amount_rank is 3;

with rankedsal as(


select salary, dense_rank() over( order by salary desc) as ranked_sal
from employee
)
select salary from rankedsal
where ranked_sal = 3; --this will give me 3rd higest salary

WITH rankedsal AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS ranked_sal
FROM employee
)
SELECT salary
FROM rankedsal
WHERE ranked_sal = 3;

--TO GET ALL THE DATA OF PEOPLE WITH 3RD HIGHEST SALARY
with rankedsal as(
select *, dense_rank() over(order by empsal desc) as sal_rank
from employee
)
SELECT *
FROM rankedsal where sal_rank = 3;

--TO GET THE DUPLICATE ROWS OF DATA


select *, count(empid) from employees
group by empid
having count>=2;

--even and odd queries


select * from employees where mod(empid, 2)=2;
select * from employees where mod(empid, 2)!=2;

--even and odd queries using window function


select* from(select *, row_number() over (order by empid) as rownum from employees)
as emp where emp.rownum %2 ==0;
select* from(select *, row_number() over (order by empid) as rownum from employees)
as emp where emp.rownum %2 !=0;

select * from employee where empid = (select min(empid) from employee); --prints
the first data of employee table
select * from employee where empid = (select max(empid) from employee); --prints
last data od employee table

--TO COPY ALL THE DATA FROM ONE TABLE TO ANOTHER


create table employee2 as select * from employee
--to copy specific columns
create table empsal as select empid, empsal from employee
--when only scema needs to be copied then
create table newtable as select * from empid where 3=4; --this 3=4 returns false
and the whole scema will be copied

--to retrieve the name of employees with same salary


select e.name, e.sal from
employee e join employee e1
where e.sal = e1.sal and e.empid != e1.empid;

--TO SELECT THE LAST 3 ROWS FROM THE TABLE


WITH temp AS (SELECT * FROM employee ORDER BY empid DESC LIMIT 3)
SELECT *
FROM temp
ORDER BY empid ASC;

--WHERE NAM ENDS WITH a


select * from employee where empname like '%a';

--between
select * from employee where empsal between 100000 ans 300000

--cumulative salary addition : cross adding and storing in accordance to empid


select empid, empname, sum(salary) over (order by emppid) as cumulativesal from
employee;

CREATE TABLE employee (


empid INT PRIMARY KEY,
empname VARCHAR(100),
gender VARCHAR(10),
salary DECIMAL(10, 2)
);
INSERT INTO employee (empid, empname, gender, salary)
VALUES
(1, 'John Doe', 'Male', 50000),
(2, 'Jane Smith', 'Female', 55000),
(3, 'Mike Johnson', 'Male', 60000),
(4, 'Sara Parker', 'Female', 62000),
(5, 'David Miller', 'Male', 58000),
(6, 'Chris Evans', 'Male', 61000);

--find percentage of males and female employees


select
round((count(*) filter (where gender='M') * 100.0/ count(*)),2) as
malepercentage,
round((count(*) filter (where gender='F') * 100.0/ count(*)),2) as
femalepercentage
from employees;

--find 50% records from table employee


select * froom employees where empid<=(select count(empid)/2 from employees);
--concatination of XX in the end of salaries
--1: PostgreSQL
select empname, gender, salary,
concat(substring(salary::text, 1, length(salary::text)-2), 'XX') as concatsal
from employee;
--2: SQL
select empname, gender, salary,
concat(substring(cast(salary as char),1, length(cast(salary as char))-2), 'XX') as
concatsal
from employee;
--3:SQLlite
SELECT empname, gender, salary,
SUBSTR(salary, 1, LENGTH(salary) - 2) || 'XX' AS concatsal
FROM employee;

--Q5(a): Write a query to find all the Employee names whose name:
--• Begin with 'A'
--• Contains 'A' alphabet at second place
--• Contains 'Y' alphabet at second last place
--• Ends with 'L' and contains 4 alphabets
--• Begins with 'V' and ends with 'A'
SELECT * FROM Employee WHERE EmpName LIKE 'A%';
SELECT * FROM Employee WHERE EmpName LIKE '_a%';
SELECT * FROM Employee WHERE EmpName LIKE '%y-';
SELECT * FROM Employee WHERE EmpName LIKE '----l';
SELECT * FROM Employee WHERE EmpName LIKE 'V%a';

--to select employee names starting with vowels wihout duplicates


select distinct empname from employee where lower(empname) similar to '[a,e,i,o,u]
%';
select distint empname from employee where tolower(empname) similar to '%
[a,e,i,o,u]';

--Find and delete duplicates from table


--1: FIND
select *, count(*) as duplicatecount from employee group by empid having
duplicatecount >1; --instead of duplicatecount you can also use count(*)

--2: DELETE
DELETE from employee where empid in (select empid from employee group by empid
having count(*)>1);

--name and project name of people working on same project


with cte as(
select e.empid, e.empname, ed.project from
employee e join employeedetails ed
on e.empid = ed.empid
)
select c1.empname, c2.empname, c2.project from cte c1, cte c2
where c1.project = c2project and c1.empid != c2.empid and c1.empid < c2.empid;
--name and salary of employee with highest salary in each project with a follow up
to get the expenditure of project
select e.name, max(e.sal) as maxsal, sum(e.sal) as project_Expenditure, count(*) as
emp_count
from employee e join employeedetails ed on e.empid = ed.empid
group by ed.project order by project salary desc;

--if nth salary needed


with cte as(
select empname, project, sal, row_number() over (partition by project order by
sal decs) as ranked_rows
from employee e join employeedetails ed on e.empid = ed.empid
group by ed.project order by project salary desc;
)
select empname, project, sal from cte where ranked_rows = n; --n to get nth highest
salary

--FIND min and maximum salary of a particular department: tech tfq


select *,
max(salary) over (partition by department order by desc) as highest_salary,
min(salary) over (partition by department order by desc range etween unbounded
preceding and unbounded following) as lowest_Sal
from employee;

--number of employees joined every year


select extract('year' from doj) as joining_year, count(*) as employee_count
from employee e join employeedetails ed on e.empid = ed.empid
group by joining_year order by employee_count asc; --ot can use joining_year asc

--group salaries in 3 colunms with high, medium and lower

select empname, empsal,


case
when sal>=200000 then 'high'
when sal>=100000 and sal<200000 then 'medium'
else 'low'
end as salary_Rating
from employees ;

--bonus question
select empid,empname,
sum(case when city = 'mathura' then salary end) as mathura,
sum(case when city = 'pune' then salary end) as pune,
sum(case when city = 'delhi' then salary end) as delhi;
from employee group by empname, empid;

--FIND THE DIST TRAVELLED BY CAR: TECH TFQ :TABLE IS GIVEN WITH CUMULATIVE DISTANCE
COVERED ND WE NEED TO FIND THE ACTUAL DIST TRAVELLED EACH DAY

CREATE TABLE cars (


cars VARCHAR(40),
days VARCHAR(10),
cumulative_distance INT
);
INSERT INTO cars (cars, days, cumulative_distance)
VALUES
('Car1', 'Day1', 50),
('Car1', 'Day2', 100),
('Car1', 'Day3', 200),
('Car2', 'Day1', 0),
('Car3', 'Day1', 0),
('Car3', 'Day2', 50),
('Car3', 'Day3', 50),
('Car3', 'Day4', 100);

SELECT *,
cumulative_dist - LAG(cumulative_dist, 1, 0) over (partition by cars order by days)
as dist_travelled_per_Day
from cars;

--given a table of states and dist b/w them remove the redundant data
with cte as(
select city1, city2, row_number() over (order by dist)--this over() can also
remain empty
as src_dest_dis from dist_table
)

select t1.city1, t1.city2, t1.dist from cte t1 join cte t2


on
t1.src_dest_dis < t2.src_dest_dis and t1.city1 = t2.city2 and t1.city2 = t2.city1;

--Q-5: table is given and we need to ungrp data


--:for this we need to use recursive sql
--important example in which interviewer will ask to print counting without using
any table

with recursive my_cte as(


select 1 as n;
union all

select n+1 from my_cte


where n<3
)
select * from my_cte

--query 7 pivot table


--nhi hoga

--Q-8 find herarchichy of employees working under asha


with cte as (
select * from employees where ename = 'asha'
union all
select e.*
from cte join employee e on e.empid = cte.empid;
)
select * from cte;
--Q9 - difference between average sales for each month of 2023 and 24
with cte as(
select yearid, monthid, to_char(order_date, 'mon') as mon, avg(sales) as
avg_sales_per_month
from salesorder s
where yearid(2003, 2004)
group by yearid, monthid, to_char(order_date, 'mon')
)
select y03.mon, round(absolute(y03.avg_sales_per_month - y04.avg_sales_per_month),
2) --abs is used here to eliminate all the -ve values
as diff_in_sales
from cte y03 join cte y04 on yo3.mon = y04.mon
where y03.yearid = 2003 and y04.yearid = 2004
order by y03.monthid;

You might also like