0% found this document useful (0 votes)
5 views17 pages

12_May_Interview Question SQL Group by, Case When, Partition By

The document outlines various SQL concepts including aggregation functions, subqueries, and joins, along with practical examples for querying data from tables. It provides specific SQL queries to calculate totals, remove duplicates, and analyze employee data based on different conditions. Additionally, it discusses the use of CASE statements and the handling of NULL values in SQL operations.
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)
5 views17 pages

12_May_Interview Question SQL Group by, Case When, Partition By

The document outlines various SQL concepts including aggregation functions, subqueries, and joins, along with practical examples for querying data from tables. It provides specific SQL queries to calculate totals, remove duplicates, and analyze employee data based on different conditions. Additionally, it discusses the use of CASE statements and the handling of NULL values in SQL operations.
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/ 17

group by

case when
subqueries
decode
lead lag
constraints all (pk,fk,unique,not,null,default,check)
operators (union , union all, minus/except, intersect)
JOINS

==============================
You have a table named orders with columns:
customer_id, order_amount, and order_date.
c101 3000 2022-01-01
c101 4000 2022-01-02

Write a query to calculate the total order amount for


each customer,
showing only customers with total orders exceeding $1000.

sel customer, sum(order_amount) as total_ord_amt


from order o1
group by customer
having sum(order_amount)> 1000;

sum(), max(), min(), avg()


prod(), first(), last()

=================
9_MAY_ASSIGNMENT _solve below query :
1>
cid cname city
c101 abc Hyd
c102 cde Hyd
c101 abc Hyd
Indore

q> populate city wise population


select city, count(distinct cid)
from cust
group by city
o/p
city population
Hyd 500
Indore 400

2> write query to remove dups

=====================================

select customer_id, sum(order_amount) from group by cutormer_id


having sum(order_amount) > = 1000;
customer_id, order_amount, and order_date.
101, 2000, 2023-01-02
101,3000, 2023-01-05
-----
having vs where
having for filtering aggragete data and it comes after group by
where is used for filtering normal column and it comes before group by clause.
============================
select customer_id,sum(order_amount) as total_order
from order
group by customer_id
having sum(order_amount) > 1000

==============================
--eid, ename, salary, did,dname, e_address...
101, abc, 2000, d01, PHYSICS, St01 HYD
sel count(1), did from emp group by did;

--Q> count the employees working in each department.

select * from emp_63;

select dept_id, count(*) from emp group by dept_id;


Q> The name of departments in which only one employee is working .
?
select dept_id, count(*) from emp where date >=2022-01-01 group by dept_id
having count(*)==1;

--eid, ename, salary, did,dname, e_address...


101, abc, 2000, d01, PHYSICS, St01 HYD
101, abc, 3000, d02, MATH...
102, CDE, 4000, d01, PHYSICS....
103,efg,5000....
103,efg,60.....

sel ename,count(1)
from emp
group by ename
having count(1) =1;

abc 2
CDE 1
efg 2

Q> Name of those employees who are working in single department?

eid ename did


e101 abc d01
e102 cde d01
e102 cde d02
e103 fatima d02
e103 fatima d01

sel ename
from table
group by ename
having count(ename) =1;
op
ename
abc

========================
Q> How to search duplicates id?
sel id, count(1)
from table
group by id
having count(1)>1

emp_name,dept_name

give all data (eid,name,salary, address,dname,did) of that employee.

--------------------

COMMANDS discussed up to now


--DDL -DML
create table EMP_63 (eid number(4), ename varchar(200), salary decimal(20,2), did
varchar(100));

alter table EMP_63 add address varchar(200);

insert into EMP_63 (eid, ename, salary, did,address)


values(101,'Kavita',30000,'d101','20, HYD');

insert into EMP_63 (eid, ename, salary, did,address)


values(103,'John',70000,'d101','40, HYD');

select '2'*(int)2 from dual;

insert ALL
into EMP_63 (eid, ename, salary, did,address) values(103,'John',70000,'d101','40,
HYD')
into EMP_63 (eid, ename, salary, did,address) values(103,'John',70000,'d101','40,
HYD')
into EMP_63 (eid, ename, salary, did,address) values(103,'John',70000,'d101','40,
HYD')
into EMP_63 (eid, ename, salary, did,address) values(103,'John',70000,'d101','40,
HYD')
select * from dual;
select unique count(*) from emp_63 ;
select count(unique eid) from emp_63 ;

select count(distinct ID) from emp_63 e;

count(1)
count(*)
select count(distinct eid) from emp_63;

select * from emp_63;

id name sal
101 ....
101 .......
101 ......
102

--Query for finding dups


ID dups
101 1
102 1
103 5

dups
select eid, count(*) from emp_63
group by eid
having count(*) > 1;

--eid, ename, salary, did,dname, address...

--Q> count the employees working in each department.


select * from emp_63;

select dept_id, count(*) from emp group by dept_id;


=========================================================================
Q> Q> fetch those employess who are working in single department... .
emp_name did name,salary, address,dname
abc d01 .....
abc d02 ...
cde d01
efg d02
efg d04

sel emp_name, count(1)


from emp
group by emp_name
having count(1) =1;
cde d01

select did count(*) group by did having count(1) =1;;--


deptwise emp count, the department having a single emp
d04 1

====================================================
Q>fetch the department names in which only one employee is working .

q2>for above query give all data (eid,name,salary, address,dname,did) of that


employee.

emp_name did name,salary, address,dname


abc d01 .....
abc d02 ...
cde d01
efg d02
efg d04

=============================
select t.* from
(
select u.*,
count(1) over(partition by items order by items) as cnt
from user_66 u
) t where t.cnt =1;

select u.*,
count(1) over(partition by items order by items) as cnt
from user_66 u ;

=======================================

insert 10 rows with some dups

select * from emp_63 ;


--ename, salary,did,address all details of those employee which are working in
single dept

select * from emp_63 where eid in (select eid from emp_63


group by eid
having count(*) = 1);

How many employees


create inser

ALL the data of employees who are working in single department;


select * from emp_63;

select * from customer;


select * from orders;
select * from agents;

select eid from emp_63 group by eid having count(1) =1;

select * from emp_63 where eid in (101,102);

select * from emp_63 where eid in (select eid from emp_63 group by eid having
count(1) =1);

select eid from emp_63


group by eid
having count(*) = 1;

IN
AND
OR
EXIST
BETWEEN
LIKE
select eid, count(*) from emp_63
group by eid
having count(*) > 1;

Unique records count(*) ==1


dups count(*) >1

having count(*) == 1

select * from emp_63 where eid='103';


select * from emp_63 ;
update emp_63 set DID='D_Mathmatics' where eid='103';

desc EMP_63;

commit;

select sysdate, 56+65 from dual;

sel cid,sum(order_amt)
from table
group by cid
having sum(order_amt)>1000

================================
Product Categories:
Consider a table named products with columns:
product_id, category_id, and price.
Write a query to find the average price for each product category.

select category_id,avg(price) from table group by category_id;

Log Analysis:
You have a table named log_data with columns:
user_id, action_type, and timestamp.
u01, login, 20241217 11.15:000
u01 changed pwd
u01 loogeout

Write a query to count the number of actions performed by each user,


and display the results in descending order of action count.
sel uid, count(1) from LOG group by uid order by count(1) desc;

uid count_of_action
u02 5
u01 3
u03 1

select user_id, count(action type) from log_data


group by user_id
order by count(action type) desc ;

where count(action type)=1 X wrong


having count(action type)=1; correct

grouped by user_id,
and display the results in descending order of action count.

select user_id,count(action_type) from table group by user_id


order by count(action_type) desc

Movie Ratings:
Given a table named movie_ratings with columns:
movie_id, user_id, and rating,movie_title.
m01,u01,4, 'Dr. Strange'
m01,u02,5, 'Dr. Strange'
m01,u03,2, 'Dr. Strange'

Write a query to find the average rating for each movie,


along with the movie title
op
movie_id avg_rating
m01 3.6

sel movie_title,movie_id,avg(rating) from movie_ratings


group by movie_title, movie_id

=================================
show all data of those students who got maximum marks classwise....
STUDENTS
student_id, marks,student_name,classID
s101,90,ABC,C101
s102,80,HBC,C101
s103,70,HBC,C101
C102

sel classid,max(marks)
from student
group by classid
c101 90
c102 80

select s.*, max(marks) over(partition by classid)


from student s

sel * from Student S1 where marks in (


select max(marks) from student s2 where s1.classid= s2.classid
group by classid)

C101 90
C102 80
C103 70
======================

select * from employee order by country asc , sal desc;

Q> country wise highest salary

select country,max(sal)
from employee
group by country;

Q> what is second max salary or 3rd max salary...nth max salary country wise

select e.*, row_number() over (partition by e.country order by e.sal desc) rownum1,
rank() over(partition by country order by e.sal desc) rank,
dense_rank() over(partition by country order by e.sal desc) dense_rank
from employee e;

select m.* from


(
select e.*, row_number() over (partition by e.country order by e.sal desc) rownum1,
rank() over(partition by country order by e.sal desc) rank,
dense_rank() over(partition by country order by e.sal desc) dense_rank
from employee e

) m
where m.dense_rank =&n;

=================================

------------------------------------
Q> the detail(name_) of those employees who earn max sal in their country
select m.*
from(
select e.*,max(sal) over(partition by e.country) max_sal
from employee e
) m
where m.max_sal =m.sal;

-----------------
select e.* from
(
select e1.*,avg(sal) over(partition by country) as avg
from employee e1 ) e
where e.sal > e.avg;

select e1.*,avg(sal) over(partition by country) as avg


from employee e1;

select country,avg(sal) from employee group by country;


---------------
JOINS
T1
c1 c2
a 1
a 2
b 3
c
d 8
_ _

from T1
join T2
on t1.c1= t2.c1;

-------
sel * from table where id is not null;

T2
c1 c2
_ _
a 11
a 12
a 13
b 14
b 15
c
g 20
----------------------
d 8 _ _

_ _ g 20

how many record ll be resulten of


LEFT==> 9 + 1 D ==10
right==>9 + 1 G ==10
inner==> a,a,a, a,a,a, b,b, c ==9
full outer==> 9 +1+1==11
cross==> 7 X 5=35

left anti
right anti
semi
===========================
NULLS ll be treated uniquly and not common and ll not resulten of\
ineer join
inner join ll not give common op on NULL
left and right join ll treate them uniquly extras

==================
self

UPCOMING
=================
Abinitio
JOIN key
JOIN {}
lookup key

without key
gather (union, union all, intersect, minus) ==> no. column and corresponding data
type of columns should be same

FUSE (keeping together all first record ...) keep one to one records together in
one record

-----------------------
CASE
when <cond> then <res>
when <cond> then <res>
....
else <res>
end as flag

select e.*,
case
when e.sal<700000 then 'LOW'
when e.sal < 900000 then 'avg'
else 'high'
end as status
from employee e;

select * from employee;


select mod(21,2) from dual;

Q> query for publish status of ID whether it is even or odd....


select e.* ,
case
when mod(e.id,2) = 0 then 'EVEN'
when mod(e.id,2)=1 then 'ODD'
end as status from employee e;

% ==> reminder
14%2== 1

Q> query for filter odd ID

select * from employee where mod(id,2)=1;


============================
CASE WHEN ===used for conditional purposes means if else
Select clause --for publishing status, or flag, indicator...
group by ( case when then)
order by ( case when then)
sum( case when then)
from ( case when then)

insert into emp values (( case when then),)


update ( case when then)

delete ( case when then)

==========================
DEPT Gender, name,...
IT , F
IT , M
IT, M
CS, M
CS, M
CS,M
CS, F

o/p
IT F 1
IT M 2
CS F 1
Cs M 3

sel dept, gender,count(1)


from dept
group dept, gender

o/p
Dept male_count, female_count
IT 2 1
CS 1 3

sel dept,
count(case when gender='M' then 1 ) as male_count,
count(case when gender='F' then 1 ) female_count
from dept
group by dept ;

=================================
select DEPT, (select count(1) from table T2 where T1.dept_id=T2.dept_id
gender='M' ) as MALE_count,
(select count(1) from table T2 where T1.dept_id=T2.dept_id
gender='F' ) as FEMALE_count
from table T1
group by DEPT

sel DEPT, sum(case when gender='M' then 1) as male_count,


sum(case when gender='F' then 1) as female_count,
from table
group by DEPT

select dept,gender,count(*) from table group by dept,gender


IT F 1
IT M 2
CS F 1
Cs M 2

select student_id,classid,marks from students s1 where marks in(


select max(marks) from student s2 where s1.classid =s2.classid
group by CLASSID
)

90,80,70

select max(marks) from student s2


group by CLASSID
C101 90
C102 80
C103 70

sel student_id,marks,
where marks=(
sel max(marks),cid
from table
group by cid )

table
A B
1 0
1 0
1 0

sel case when 1 then 0 else 1 end


from table;

==============
T1
A
2
3
2

o/p
3
2
3
2

T1
A
2
3
2
T2
A B
2 X
3 Y

o/p
Y
X
Y
X

UPDATE T1
SET A = T2.B
FROM T1
JOIN T2 ON T1.A = T2.A;

UPDATE T1
SET A = CASE
WHEN T1.A = 2 THEN (SELECT DISTINCT B FROM T2 WHERE A = 2)
WHEN T1.A = 3 THEN (SELECT DISTINCT B FROM T2 WHERE A = 3)
ELSE T1.A
END;
M=>F
F=>M

----------------------------
how to remove dups

Show the detail of those employees whose salary is greater


than avg_salary of all employee in their department.
EMp
id, name, salary, deptid
101,abc,20000,d01
102,cde,60000,d01
103,FDE,30000,d01
104,EDS,40000,d01

empno job deptno


101 software 10
102 QA 10
103 engineering 10
104 data engg 20
105 developer 30
106 manager 20
107 software 20
108 QA 20
109 Engineer 20
110 vice preside 40
This is the data.
Please write me a query to get the jobs common in dept 10 and 20

============
depid gender
IT M
IT F
IT F
CS M
CS F

o/p
deptid male_count female_count
IT 1 2
CS 1 1
=======================
I'd status
101 account
103 account
104 bad
102 nic
107 account
100 iso
105 bad
So we need status column like account >bad>nic>iso in that order
sel * from table
order by
case
when status='account' then 1
when status='bad' then 2
when status='nic' then 3
else 4
end;

================
case when
1> cond based column status
2> cond based counting of male , female
3> cond based ordering priority
===========================
id fname lname
1 sai null
1 null ram

in above table they need output in below one line format using join
1 Sai ram

sel id, max(fname), max(lname)


from
group id
======================
STORED PROC

/*================================================*/
/*delete duplicates*/
select e.*,rowid,rownum from emp e;
delete from emp91 where rowid not in (select max(rowid) from emp91 group by id);

select id,max(rowid) from emp91 group by id;

========================
windows function
row_number
rank
dense_rank
dept wise 5th highest salary
select e.*,
row_number() over (partition by e.country order by e.sal desc) rownum1,
rank() over (partition by e.country order by e.sal desc) rank,
dense_rank() over (partition by e.country order by e.sal desc) dense_rank,
rowid
from employee e

leg
lead
=============
delete from table where rowid not in
( sel max(rowid) from table group by id)

sel id,max(rowid) from table group by id;


eid
1 nnnnC
2 hhhhD

eid rowid
1 nnnnA
1 nhnnB
1 nnnnC
---------------------------

select e.country, e.sal, lag(sal,1) over( partition by country order by sal desc)
lag
from emp451 e;
----------------------------------
find out nth highest

select m.* from (


select e.*,
dense_rank() over (partition by e.country order by e.sal desc) dense_rank
from emp451 e) m
where m.dense_rank=&n;

================
how to delete nth
delete from (
select e.*,
dense_rank() over (partition by e.country order by e.sal desc) dense_rank
from emp451 e) m
where m.dense_rank=&n;

================
how to delete dups on ranks== rank basis dups removal

delete from emp451 where rowid not in (


select max(rowid)
from
(
select e.*,
dense_rank() over (partition by e.country order by e.sal desc) dense_rank,
rowid
from emp451 e
) m
--where m.dense_rank =2
group by m.country,m.dense_rank );
=======================

--+++++++++++++++++STORED PROC++++++++++++++++++++=

CREATE OR REPLACE PROCEDURE greet_person(name_in IN VARCHAR2)


IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello, ' || name_in || '!');
END greet_person;
/

call greet_person('Mina');
execute greet_person('John');

execute greet_person('Mina');

SET SERVEROUTPUT ON;

--========================================
--update order set ord_description='Delivered' where agent_code='A007';

--2024-11-06
select * from orders1;

create or replace procedure order_update (ord_desc IN varchar,agent_cd IN varchar)


IS
begin
update orders1
set ord_description = ord_desc
where trim(Agent_code) = trim(agent_cd);
commit;
dbms_output.put_line('done' || ord_desc || agent_cd);
end order_update ;
/

select * from orders1;


call order_update('Delivered','A007');

====================

select * from employee order by sal limit 5;

select * from generate_series( 1, 100)


limit 10 offset 20;
select level from dual connect by level <=100;

in oracle 11g we use, rownum, rowid, level for limiting and offsetting

Teradat top for limiting


mysql, mariadb, postgreysql use limit clause and offset operator
=============================================

select trunc(sysdate, 'MM') + level -1 as dt_series from dual connect by level


<=31;

select trunc(to_date('20250101','yyyymmdd'), 'MM') + level -1 as dt_series from


dual connect by level <=31;

capgemini
c
a
p

select substr('capgemini',level,1) as char_series from dual connect by level <=


length('capgemini');

-----------------
Real time ex
Seq Trigger on insert
view and materialized view
=================================
GROUp BY
CASE WHEN
SUBQUERY
Operators
===============================

docs--->
index
view mv
performance tuning..
===========================
join scd-2
SK
oracle seq +trigger for sk
=======================================

You might also like