You are on page 1of 30

Table 1:

SELECT * FROM PRODUCTS;

PRODUCT_ID PRODUCT_NAME
-----------------------
100 Nokia
200 IPhone
300 Samsung

Table 2:
SELECT * FROM SALES;

SALE_ID PRODUCT_ID YEAR QUANTITY PRICE


--------------------------------------
1 100 2010 25 5000
2 100 2011 16 5000
3 100 2012 8 5000
4 200 2010 10 9000
5 200 2011 15 9000
6 200 2012 20 9000
7 300 2010 20 7000
8 300 2011 18 7000
9 300 2012 20 7000

1. Write a SQL query to find the products which have continuous


increase in sales every year?
SELECT PRODUCT_NAME
FROM
(
SELECT P.PRODUCT_NAME,
S.QUANTITY -
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_DIFF
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
GROUP BY PRODUCT_NAME
HAVING MIN(QUAN_DIFF) >= 0;

2. Write a SQL query to find the products which does not have sales at
all?
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
LEFT OUTER JOIN
SALES S
ON (P.PRODUCT_ID = S.P
Or
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE P.PRODUCT_ID NOT IN
(SELECT DISTINCT PRODUCT_ID FROM SALES);
or
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE NOT EXISTS
(SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);

3. Write a SQL query to find the products whose sales decreased in


2012 compared to 2011?
SELECT P.PRODUCT_NAME
FROM PRODUCTS P,
SALES S_2012,
SALES S_2011
WHERE P.PRODUCT_ID = S_2012.PRODUCT_ID
AND S_2012.YEAR = 2012
AND S_2011.YEAR = 2011
AND S_2012.PRODUCT_ID = S_2011.PRODUCT_ID
AND S_2012.QUANTITY < S_2011.QUANTITY;

4. Write a query to select the top product sold in each year?


SELECT PRODUCT_NAME,
YEAR
FROM
(
SELECT P.PRODUCT_NAME,
S.YEAR,
RANK() OVER (
PARTITION BY S.YEAR
ORDER BY S.QUANTITY DESC
) RNK
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
WHERE RNK = 1;

5. Write a query to find the total sales of each product.?


SELECT P.PRODUCT_NAME,
NVL( SUM( S.QUANTITY*S.PRICE ), 0) TOTAL_SALES
FROM PRODUCTS P
LEFT OUTER JOIN
SALES S
ON (P.PRODUCT_ID = S.PRODUCT_ID)
GROUP BY P.PRODUCT_NAME;

6. Write a query to display only Friday dates from Jan, 2000 to till now?
SELECT C_DATE, TO_CHAR(C_DATE,'DY') FROM (SELECT TO_DATE('01-JAN-2000','DD-
MON-YYYY')+LEVEL-1 C_DATE FROM DUAL CONNECT BY LEVEL <=(SYSDATE -
TO_DATE('01-JAN-2000','DD-MON-YYYY')+1)) WHERE TO_CHAR(C_DATE,'DY') = 'FRI';

7. A column has some negative values and some positive values. It is


required to find the sum of negative numbers and the sum of the
positive numbers in two separate columns.
create table neg_pos(num number);
insert into neg_pos values(-1);
insert into neg_pos values(-2);
insert into neg_pos values(-3);
insert into neg_pos values(-4);
insert into neg_pos values(1);
insert into neg_pos values(2);
insert into neg_pos values(3);
insert into neg_pos values(4);
commit;
select * from neg_pos ;
num
-1
-2
-3
-4
1
2
3
4

gives
————-
neg | pos
————-
-10 | 10
————-
SELECT SUM(CASE WHEN num < 0 THEN num ELSE 0 END) neg,
SUM(CASE WHEN num > 0 THEN num ELSE 0 END)pos
FROM neg_pos;

8. From the given table, find those employees who are more than 21
years of age.
Table Name:- Emp
Name ​Birth_date
Akash ​12-MAR-93
Rahul ​23-APR-96
Sagar ​14-JAN-92
Mahesh ​07-Dec-00
Nitin ​14-FEB-97 ​
Kiran ​ ​ 15-OCT-98

SELECT NAME FROM Emp WHERE birth_date < (SELECT add_months(SYSDATE,-(12*21))


FROM dual);
9. Get the following OUTPUT using dual
1LR
—————
111
112
113
121
122
123
131
132
133
SELECT * FROM (SELECT 1 FROM dual), (SELECT LEVEL FROM dual CONNECT BY
LEVEL <4), (SELECT LEVEL FROM dual CONNECT BY LEVEL <4);

10. Get the last day of the year


SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL

11. Get number of days in current month


1. SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days from dual;
12. Get number of days left in current month.
2. SELECT SYSDATE, LAST_DAY (SYSDATE) "Last", LAST_DAY (SYSDATE) - SYSDATE "Days
left" FROM DUAL;

13. Display each months start and end date upto last month of the year
3. SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date, TRUNC (LAST_DAY
(ADD_MONTHS (SYSDATE, i))) end_date FROM XMLTABLE ('for $i in 0 to xs:int(D) return
$i' PASSING XMLELEMENT (d,FLOOR (MONTHS_BETWEEN (ADD_MONTHS (TRUNC
(SYSDATE, 'YEAR') - 1, 12),SYSDATE)))COLUMNS i INTEGER PATH '.');

Data dictionary queries


14. Check if a column exists in a table

4. SELECT column_name AS FOUND FROM user_tab_cols WHERE table_name = 'TABLE_NAME' AND


column_name = 'COLUMN_NAME';
15. Convert number to words,
Eg. Pass the Object:- “1526” and Display the output: one thousand five hundred twenty-six
5. SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
16. Find the last record from a table.
6. SELECT * FROM employees WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);

(OR)

7. SELECT *FROM employees MINUS SELECT * FROM employees WHERE ROWNUM <
(SELECT COUNT (*) FROM employees);

17. if exp1 and exp2 are not equal it should print first exp if both exp
are same then it will display 'no_match' string.output should be in
this way.

SQL> ex1 ex2 Result


---------- ---------- ----------------------------------------
5 11 5
6 5 6
7 5 7
7 6 7
5 5 no_match
5 7 5
6 6 no_match
7 7 no_match
5 5 no_match

8. Selectlength(first_name) “expr1” ,length(last-name) “expr2”, case when


length(first_name)=length(last_name) then ‘no match’ when length(first_name)
!=length(last_name) then to_char(length(first_name),’99’) end as “Result” from employees;

18. Find those employees whose last name ends with n letter. (don’t use
like operator)
9. Selectlast_name from employees where length(Last_name)-length(trim(trailing( ‘n’ from
last_name))=1;
19. Display the output. Date, hour, min, day—
Date hour min day
------------- ---------- -- -- -- ---------
22-feb-11 05:49:42 05 49 TUESDAY

10. select(to_date(sysdate,’DD-mon-yy)) as ”date”,( to_char(sysdate,'hh:mi:ss') as “hour”,


to_char(sysdate,'mi:ss') as “min”, to_char(to_date(sysdate,'dd-mon-yy'),'day') as “day” from
dual;

20. Round these dates in month and year.


- 15-feb-11
- March-12-11
- 2011-june-21
- 04-2011-Oct
SQL> select round(to_date(’15-feb-11’,’dd-mon-yy’),’year’) as raound_year from dual;
SQL> select round(to_date(’15-feb-11’,’dd-mon-yy’),’month’) as raound_month from dual;
SQL> select round(to_date(’feb-12-11’,’mon-dd-yy’),’year’) as raound_year from dual;
SQL> select round(to_date(’2011-jun-21’,’yy-mon-dd’),’year’) as raound_year from dual;
SQL> select round(to_date(’2011-jun-21’, ’yy-mon-dd’),’month’) as raound_month from dual;
SQL> select round(to_date(’04-11-oct’,’dd-yy-mon’),’year’) as raound_year from dual;
SQL> select round(to_date(’04-11-oct’,’dd-yy-mon’),’month’) as raound_month from dual;

21. use the hire_date column from employees table and prove that yy
works on current century and rr uses internal algorithm. display the
output.
rr-date yy-date
---------------------- --------------------
11-jul-1998 11-jul-2098
19-dec-1999 19-dec-2099
04-feb-1996 04-feb-2096
03-mar-1997 03-mar-2097
11. SQL> selectto_char(hire_date,'dd-mon-yyyy') "rr-date", add_months(to_char(hire_date, 'dd
mon-yyyy'), 1200) “yy-date” from employees;

22. .display the output. (use sysdate function from dual table)
SQL> seventeen of 10 th

SQL> select to_char(to_date(sysdate,'dd-mm-yy'),'ddspth')||' of '||to_char(to_date(sysdate, 'dd-mm-


yy'),'mmth') from dual;

23. convert this value '$20,000.00' in number. (20000) ?

12. Select To_number(‘$20,000.00’,’$99,999.99’) as “number” from dual;

24. add 5 days in 'march-2011-12'


13. SQL> Select to_date(‘'march-2011-12',’month-yyyy-dd ​)+5 f;rom dual;
25. find the no of days between '12-feb-2011' and 'march-12-1999'.
14. SQL> Selectto_date('12-feb-2011',’dd-mon-yyyy’)-to_date('march-12-1999’,month-dd-yyyy’) “no
of days” from dual;

26. findout the day for the date ('15-jan-11')-- use dual table.?
15. SQL> Select to_char(to_date('15-jan11','dd-mon-yy'),'day') from dual;

27. prompt the value for date and it should display the day for prompted
date.
16. SQL> select to_char(to_date('&date','dd-mm-yy'),'day') from dual;

28. Display Region and total number of employees from that region in
the following format
East West North South
------- -------- --------- ---------
10 40 34 76
17. SQL>Selectmax(decode(Region,'East',count(region))) “East”,
max(decode(Region,'West',count(Region))) “West”,
min(decode(Region,'North',count(Region))) “North”,
avg(decode(Region,’South’,count(Region))) “South”
from Region group by region_name;


29. replace AA where a in the last_name. display the output..

NAME LAST_NAME
--------------- -------------------------
TAAylor Taylor
TobiAAs Tobias
TuvAAult Tuvault
UrmAAn Urman
Ans :
18. SQL> select replace(last_name,'a','AA') from employees;

30. dispaly the output.first letter from the first_name column and then
aad '_' and then last_name column
then '@focus.com' string.

J_Urman@focus.com
P_Vargas@focus.com
C_Vishney@focus.com
S_Vollman@focus.com
A_Walsh@focus.com
19. SQL> select concat(substr(first_name,1,1), concat('_',concat(last_name,'@focus.com'))) from
employees;
31. display the employee number, hire date, number of years employed,
six-month review date, first Friday after hire date, and last day of the
hire month for all employees who have been employed for more then
15 years.

ID HIRE_DATE TENURE REVIEW first_FRI


Last_DAY
---------- ​---------------- ------------- ​------------ ------------
---------------
109 ​ ​ 16-AUG-94 16 ​ ​16-FEB-95 ​19-
AUG-94 Wednesday
114 07-DEC-94 16 07-JUN-95 09-DEC-94
Wednesday

20. SQL> select


employee_id id, hire_date, round(months_between(sysdate,hire_date)/12) tenure,
add_months(hire_date,6) review,next_day(hire_date,'friday')
"first_FRI",to_char(last_day(hire_date),'day') "Last_DAY" from employees;

21. SQL> selectemployee_id id, hire_date,(round((sysdate-hire_date)/30/12)) tenure,


add_months(hire_date,6) review,next_day(hire_date,'friday') first_fri,
to_char(last_day(hire_date),'day') "Last_DAY" from employees;

32. if employee does not report to a manager then print 'no manager'
else print 'reports to manager and manager_name'.

LAST_NAME MGR_NAME
------------------------- --------------------------------------
Urman reports to ==Greenberg
Vargas reports to ==Mourgos
Vishney reports to ==Errazuriz
Vollman reports to ==King

"by using Decode"


22. SQL> select e.last_name, decode(e.manager_id,NULL,'no_manager',concat('reports to == ',
m.first_name)) mgr_name
from employees e left join employees m on(e.manager_id=m.employee_id);

"by using case"


23. SQL> select e.last_name,case when e.manager_id is NUll then 'NO Match' else concat(
'reports to == ',m.first_name) end "mgr_name"
from employees e left join employees m on (e.manager_id=m.employee_id);

33. Display those employees who are getting more then '$15000,00'. i
have to compare the salary column in this format ('$15000.00') only.
SQL> select salary from employees wheresalary > to_number ('$15000.00','$99999.99');

34. Display those employees whose hire_date is greater then march-


1999-01. i have to compare hire_date column in this format ('march-
1999-01') only, but display the output in this way...

HIRE_DATE
---------------------------------------------------------------------------
twenty-three-november of nineteen ninety-nine
nineteen-march of nineteen ninety-nine
twenty-four-january of two thousand
twenty-three-february of two thousand
twenty-four-march of two thousand ​

SQL> select to_char(to_date('12-jan-1998','DD-mon-yy'),'ddspth-month')||'of '|| to_char (


to_date ('12-jan-1998', 'DD-mon-yy'), 'year') from dual;

35. Dsplay total no. of employees.


SQL> select count(employee_id) from employees;

36. Display employees’s first name and last name and sort them by
last_name.
SQL> select first_name, last_name from employees order by last_name;

37. Display full name of employees and full name his manager.

SQL> select (e.last_name||' '||e.first_name) "full_name of employees",(m.last_name||' '||


m.first_name) "full_name of his manager" from employees e left join employees m
on (e.manager_id=m.employee_id) order by e.employee_id;

38. Display a list full name of employees and their salaries . Display
only top 5 employees.

SQL> select * from (select first_name||' '||last_name FULL_NAME , employee_id employee,


salary from employees order by salary desc) where rownum <= 5;

39. Display employees’s full name and the department of that


employees.
SQL> select e.first_name||’ ‘||e.last_name Full_name, d.department_name department from
employees e, departments d;

40. Display list of departments and total number of employees in it.


SQL> select d.department_name, count(e.employee_id) from employees e join departments d
on(e.department_id=d.department_id) group by d.department_name;
41. Display list of departments and employees in that list even if a
department does not have any employee in it.
SQL> select d.department_name ,count(e.employee_id) from employees e right join departments
d on(d.department_id=e.department_id) group by d.department_name;

42. Display the list of departments and total salary of that


department.Display only list of departments whose total salary is
more than 50000.
SQL> select d.department_name, sum(e.salary) from employees e join departments d
on(e.department_id=d.department_id) group by d.department_name having
sum(e.salary)>50000;

43. Display list of employees (employee full name and department


name) who are not from the accounting department.
SQL> select e.first_name||' '||e.last_name full_name, d.department_name from employees e,
departments d where d.department_name<>'Accounting';

44. Display employees name,salary, job_title of employees who were


hired in the year of 1994.
SQL> select first_name from employees where extract(year from hire_date)=1996;

45. Which country has the maximum no of employees.


SQL> select c.country_name,count(*) from countries c left join locations l on
(c.country_id=l.country_id) join departments d on (l.location_id=d.location_id) join employees e
on(d.department_id=e.department_id) group by c.country_name having count(*)=(select
max(count(*)) from countries c left join locations l on (c.country_id=l.country_id) join
departments d on (l.location_id=d.location_id) join employees e
on(d.department_id=e.department_id) group by c.country_name);

46. Display the employee_id, last_name, and salary increased by 15.5%


(expressed as a whole number) for each employee. Lable the column
New Salary. And then add a column that substract the old salary from
the new salary. Label the column increase.
SQL> select employee_id,last_name,salary,round(15.5*salary/100)+ salary "New Salary",
(round(15.5*salary)/100) "Increase" from employees;

47. Increase the salary range of all jobs from executive department by
20%..
SQL> select e.salary,e.salary*0.20 "incr_sal by 20%",d.department_id from employees e join
departments d on (d.department_id=e.department_id) where department_name='Executive' ;

48. Display a list of departments and their managers along with their
phone_number. Do not display country code of phone_number.
SQL> select case length(phone_number) when 12 then phone_number else
substr(phone_number,8) end from employees;

49. List of the employees and their salaries whose salary is less than the
average salary of the company.
SQL> select last_name, salary from employees where salary<(select avg(salary) from employees);

50. List of the employees and their salaries whose salary is more than
the average salary of the company.
SQL> select last_name, salary from employees where salary>(select avg(salary) from employees);

51. Display the list of employees who have a and e in their name.
SQL> select first_name from employees where first_name like '%a%' and first_name like'%e%';

52. Display the department_name,location,lastname, job_id salary of


those employees who work in a specific location. Prompt the user for
the location.
SQL> select e.last_name,e.job_id,e.salary ,d.department_name,d.location_id location from
employees e join departments d on(d.department_id=e.department_id) where
d.location_id='&location';

53. Display the jobs that are found in the Administration and Executive
departments.Also display the no of employees for these jobs. Show
the job with the highest no of employee first.
SQL> select e.job_id ,count(e.employee_id) employee from employees e join departments d
on(d.department_id=e.department_id) where d.department_name
in('Administration','Executive') group by job_id order by employee desc;

54. Show all employees who were hired in the first half of the
month(before the 16th of the month).
SQL> select employee_id,last_name, hire_date from employees where
to_number(to_char(hire_date,'dd'))<16;

55. Display the No Commission where commission_pct is null.


SQL> select last_name, decode(commission_pct,'','no commission',commission_pct) commission_pct
from employees;

56. Create a table named dept using departments table, and truncate dept
and then use the merge statement to get the data back.
step1) Create a table named dept using departments table -
SQL> create table dept as select * from departments;

step2) truncate dept -


SQL> truncate table dept;

step3) Use the merge statement to get the data back -


SQL> merge into dept dt using departments d on (dt.department_id=d.department_id)
when matched then update set dt.DEPARTMENT_NAME= d.DEPARTMENT_NAME,
dt.MANAGER_ID=d.MANAGER_Id, dt.LOCATION_ID=d.LOCATION_ID
when not matched then insert values(d.DEPARTMENT_ID,
d.DEPARTMENT_NAME,d.MANAGER_ID,d.LOCATION_ID);

57. Create two tables emp1 and dept1 and establish a relationship
between both tables.
{we create relationship between table emp1 & dept1 with (primary key & foreign key)
relationship}
step1)
SQL> CREATE table emp1(EMPLOYEE_ID NUMBER(6),
FIRST_NAME VARCHAR2(20), LAST_NAME VARCHAR2(25),
EMAIL VARCHAR2(25), PHONE_NUMBER VARCHAR2(20),
HIRE_DATE DATE,JOB_ID VARCHAR2(10),SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),MANAGER_ID NUMBER(6), DEPARTMENT_ID
NUMBER(4));

step2)
SQL> CREATE table dept1(DEPARTMENT_ID NUMBER(4),
DEPARTMENT_NAME VARCHAR2(30),MANAGER_ID NUMBER(6),
LOCATION_ID NUMBER(4));

step3)
SQL> ALTER table dept1 add constraint dept1_pk primary key(department_id);

step4)
SQL> ALTER table emp1 add constraint emp1_fk foreign key(department_id) references
dept1(department_id);

58. Drop the table employees and the get back it using FLASHBACK
statement from recyclebin.
step1)
SQL> DROP table employees;

step2)
SQL> FLASHBACK table employees to before drop;

59. Produce a company organization chart that shows a management


hierarchy. Start with the person at the top level, exclude all those job
ID IT_PROG, and exclude De Haan and those employees who report
to De Haan.
SQL> select e.employee_id,e.last_name ,e.salary from employees e
join employees m on(e.manager_id=m.employee_id)
where m.last_name<>'De Haan' and e.last_name<>'De Haan' and e.job_id!='IT_PROG'
order by e.salary desc;

60. Create a table EMP_NEW and col name should be


(EMP_NO,NAME,and SALARY), apply the constraint on salary
column that salary should not be less then 1000.
SQL> create table EMP_NEW(EMP_NO NUMBER, NAME VARCHAR2(20), SALARY
NUMBER CHECK (SALARY<10000));

61. Display City and total no. of employees in that city. List only top 5
cities
SQL> select * from (SELECT L.CITY,COUNT(E.EMPLOYEE_ID) FROM EMPLOYEES E
JOIN DEPARTMENTS D ON(D.DEPARTMENT_ID=E.DEPARTMENT_ID) JOIN
LOCATIONS L ON(L.LOCATION_ID=D.LOCATION_ID) GROUP BY L.CITY ORDER BY
COUNT(E.EMPLOYEE_ID) DESc) where rownum <=5;

62. Delete any 10 rows from employee


SQL> delete from emp_new where rownum <= 3;
63. Display total number of employees from the Acounting Department
SQL> select count(e.employee_id) Accounting from departments d join employees e
on(d.department_id=e.department_id) where d.department_name='Accounting' group by
d.department_name;

64. Display Department name and total number of employees


SQL> select d.department_name,count(e.employee_id) from departments d join employees e
on(d.department_id=e.department_id) group by d.department_name

65. Display region and total number of employees from that region
SQL> select r.region_name ,count(e.employee_id) from regions r join countries c
on(r.region_id=c.region_id) join locations l on(c.country_id=l.country_id) join departments d
on(l.location_id=d.location_id) join employees e on(d.department_id=e.department_id) group
by r.region_name ;

**To verify the total number of regions**

SQL> select r.region_name ,e.employee_id from regions r


left join countries c on(r.region_id=c.region_id)
left join locations l on(c.country_id=l.country_id)
left join departments d on(l.location_id=d.location_id) ​
left join employees e on(d.department_id=e.department_id) order by r.region_name ;

66. Display City and total no. of employees in that city. List only top 5
cities.
SQL> select * from (select l.city, count(e.employee_id) from locations l left join departments d
on(l.location_id=d.location_id) left join employees e on(d.department_id=e.department_id) group
by l.city order by count(e.employee_id) desc) where rownum <= 5;
Or

SQL> select * from (select l.city, count(e.employee_id) from locations l


left join departments d on(l.location_id=d.location_id)
left join employees e on(d.department_id=e.department_id)
group by l.city order by count(e.employee_id) desc) where rownum <= 5;

67. give the info of those employees whose manager belong to the same
city as of employees?

Select e.employee_id employee_id , e.first_name||’ ‘||e.last_name as emp_name , l.city as emp_city,


m.employee_id manager_id , m.first_name||’ ‘||m.last_name as mngr_name , ml.city mngr_city
from employees e join employees m on(e.manager_id=m.employee_id) join departments d
on(d.department_id=e.department_id) join departments md
on(md.department_id=m.department_id) join locations l on(l.location_id=d.location_id) join
locations ml on(ml.location_id=md.location_id) where l.city=ml.city;

68. write a sql query such that it will display employees name there
manager name and there manager's manager name. and make sure it
will display all employees name (107 rows) if any employee is not
having any manager then it will display "no manager"?

Select e.employee_ide,first_name, decode(m.first_name,null,’no manager’,m.first_name) m_name,


decode(mm.first_name,null,’No Manager’,mm.first_name) m_m_name from employees e join
employees m on(e.manager_id=m.employee_id) left join employees mm
on(m.manager_id=mm.employee_id);

69. write a query which will display the details of those employees who
belong to the same region as of employee 149?
Select e.employee_id, e.last_name, e. salary, r.region_id, r.region_name from employees e join
departments d on(d.department_id=e.department_id) join locations l
on(l.location_id=d.location_id) join countries c on(c.country_id=l.country_id) join regions r
on(r.region_id=c.region_id) where region=(select r.region from employees e join departments d
on(d.department_id=e.department_id) join locations l on(l.location_id=d.location_id) join
countries c on(c.country_id=l.country_id) join regions r on(r.region_id=c.region_id) where
e.employee_id=149);

70. write a query to count total no of character 'e' in last_name and first
name of the employees table?
Select first_name, regexp_count(first_name,’e’), last_name, regexp_count(last_name,’e’) from
employees;

71. write a query to sort employees table day wise from tuesday to
monday?
SQL> select days from (select mod(to_char(hire_date,'d')+4,7) ,to_char(hire_date,'day') days from
employees order by 1);

72. write a query to see which department_id are not used in employees
table.(write atleast 3 ways to solve the same question)?
SQL>Select department_id from departments minus select department_id from employees;
SQL> select d.department_id from departments d where d.department_id not in(select
department_id from employees where department_id=d.department_id);

73. write a query to dispaly those employees who are having salary less
than the salary of any employee of department 80(write atleast two
query)?
SQL> Select employee_id , salary from employees where salary <any (select salary from employees
where department_id=80);
SQL> Select salary from employees where salary>(select max(salary) from employees where
department_id=80);

74. prompt a two date from a user see how many weeks there between
these two dates?
Select round((to_date(‘&Max_date’)-to_date(‘&min_date’)/7) from dual;

75. write a query to replace only second occurrence of character 'e' with
'#' in last_name of employees table?
Select regexp_replace(last_name,’e’,’#’1,2) last_name from employees;

76. write a query to display total number of primary key present in your
schema?
Select count(constraint_name) from user_constraints where constraint_type=’P’;

77. write a query to display day on which least number of employees


got hired?
Select to_char(hire_date,’day’), count(employee_id) from employees group by
rollup(to_char(hire_date,’day’));

78. write a query to display middle character of last_name?


Select last_name , substr(last_name,round(length(last_name)*0.5),1) from employees;

79. prompt job_title from user and show the details of employees who
are working in that department?(dont use join).
Select department_id , employee_id, last_name , job_id from employees where job_id=’&Job_title’;l

80. grant any user such that he can only select your employees table
without using your schema name?
Create public synonym local_emp for employees;

81. write a query to find total number of rows present in your


employees,department,locations and countries,copy_emp tables?
(here in above question copy_emp is a copy table of employees)
select employees , departments, locations , copy_emp from (select count(*) employees from employees),
(select count(*) departments from departments),(select count(*) locations from locations),(select
count(*) copy_emp from copy_emp);

82. write a query to display third highest salary of employees table?


SQL> select salary from (select salary salary ,dense_rank() over (order by salary desc) rank from
employees)where rank=3;

83. prompt a number from user and show that numbers salary from each
department?
SQL> select department_id, salary, rank from (select distinct department_id ,salary, dense_rank() over
(partition by department_id order by salary desc) rank from employees order by 3) where rank
=&number;

84. display the details of those employees who reports to 'king'?(1.using


subquery,2.using join)?
SQL> select employee_id,last_name, manager_id from employees where manager_id in(select
employee_id from employees where last_name='King');
SQL> select e.employee_id,e.last_name, e.manager_id, m.employee_id from employees e join
employees m on(e.manager_id=m.employee_id) where m.last_name='King';

85. display last_name like but total length should be exactly 50?
​***************last_name****************
SQL> select rpad(lpad(last_name,length(last_name)+21,'#'),50,'#') from employees;

86. display employee_id,department_id,manager_id such that if


manager_id is null it should display department_id and
if department_id is null then it shoul display salary?
SQL> select employee_id, nvl(manager_id,department_id), nvl(department_id,salary), salary from
employees;

87. show the date of first saturday of date 'august-2015-01'?


SQL> select next_day(to_date('august-2015-01','mon-yyyy-dd'),'saturday') first_saturdey from dual;
88. show the details of those employees whose length of last_name and
employee_id is even?
SQL> select * from employees where mod(employee_id,2)=0 and mod(length(last_name),2)=0 order by
employee_id;

89. write a query to display how many employees got hired in each
month of year 1996?
SQL> select to_char(hire_date,'Mon'),count(employee_id) from employees where
to_char(hire_date,'yyyy')=1996 group by to_char(hire_date,'Mon');

90. create a view of employee table such that no one can perform dml
operations on that view?
Create or replace view emp as (select * from employees) with read only;

91. fire some sql statements such that it will raise an dead lock error?
U1 => User1 and U2 => User2 ,

they work in their SQl prompt at a time

U1: update t1 set salary=50000 where id=101;


U2: update t2 set salary=60000 where id=102;
U1: delete from U2.t2 where id=102;
U2: delete from U1.t1 where id=101;

92. Give Table Products:


P_Group ​ ​P_name
-------------------- ------------------------
Softdrink ​ ​Pepsi
Softdrink ​ ​Miranda
Softdrink ​ ​7up
Softdrink ​ ​Sprite
Colddrink ​ ​Pepsi
Colddrink ​ ​Miranda
Colddrink ​ ​7up
Colddrink ​ ​Sprite

With the help of Given table obtain Output with company name
“PRODUCT’s”:
Company_name ​P_Group_name ​ ​P_name
------------------------- ---------------------------- -----------------------
PRODUCTS ​ ​Softdrink,Colddrink ​pepsi,Miranda,7up,Sprite ​ ​

Slect ‘PRODUCT’’s’ company_name, listagg(p_g,’, ‘) within group (order by p_g) group_name,


P_name from (select p_group p_g,listagg(p_name,’, ‘) within group (order by p_name) as
p_name from products group by 1) group by 3;

93. List the employees in the ascending order of designation of those


joined after the second half of 1981
Select * from employees where hire_date > (’30-june-1981’) and to_char(hire_date,’yyyy’)=1981 order
by job asc;

94. List the employees those joined 01-may-1981,03-dec,1981,17-dec-


1981,19-jan-1980 in asc order of seniority
Select * from employees where hire_date in (‘01-may-1981’,’03-dec,1981’,’17-dec-1981’,’19-jan-
1980’)order by hire_date asc;
95. List all employees who joined before or after 1981.
Select * from employees where to_char(hire_date,’yyyy’) not in (‘1981’);
Or
Select * from employees where to_char(hire_date,’yyyy’) <> 1981;

96. Display employee number,employee name,their salary,department


number,job of all employees working at CJICAGO or working for
ACCOUNTING dept with annual salary >28000,but the salary should
not be=3000 or 2800 who does not belongs to the manager and whose
no is having a digit 7 or 8 in3rd position in the asc order of
department number and desc order of job.
Select e.employee_id,e.first_name,e.salary,d.department_name,d.location,e.department_id,e.job from
employees e ,departments d where (d.location=’ CJICAGO’ or d.department_name=’
ACCOUNTING’) and e.department_id=d. department_id and e.employee_id in (select e.employee_id
from employees e where (12*e.salary) > 28000 and e.salary not in (3200,2800) and
e.job!=’MANAGER’ and (e.employee_id like ‘__7%’ or e.employee_id like ‘__8%’)) order by
e.department_id asc,e.job desc;

97. List the employees who joined in 1981 with the job same as the
most senior person of the year 1981.
Select * from employees where job in (select job from employees where hire_date in (select
min(hire_date) from employees where to_char(hire_date,’yyyy’)=’1981’));

98. List the employees who salary is equal to the average of maximum
and minimum.
Select * from employees where salary =(select (max(salary)+ min(salary))/2 from employees);

99. Find out leat earners of the company.


Select rownum rank,employee_id,first_name,job,salary from (select * from employees order by salary
asc) where rownum < 6 ;
Or
select * from employees e where 5 > (select count(distinct salary) from employees where e.salary> salary
);

100. List the employees whose first 2 charcter from hire date =last 2
charcter of salary.
select * from employees where substr(hire_date,1,2)= substr(salary,length(salary)-1, length(salary));

101. Employee hired on or before 15 of any month are paid on the last
th

Friday of that month those hired after 15 are paid on the first Friday
th

of the following month.print a list of employee their hire date and the
first pay the date.sort on the hire date.
Select first_name,hire_date,next_day(last_day(hire_date),’FRIDAY’)-7 from employees where
tp_char(hire_date,’dd’) <=15
union
Select first_name,hire_date,next_day(last_day(hire_date),’FRIDAY’) from employees where
tp_char(hire_date,’dd’) >15 ;

102. Find average salary and average total remuneration for each job
type.
Select avg(salary),avg(salary+nvl(commission_pct,0)) from employees
103. Check whether all the employees number are indeed unique
Select employee_id,count(*) from employees group by employee_id;

104. Find out the job that was filled in the falf of 1993 and same job that
was filled during the same period of 1984.
Select * from employees where to_cahr(hire_date,’mm’) <=06 and to_cahr(hire_date,’yyyy’) =1984)
and job in (select job from employees where to_cahr(hire_date,’mm’) <=06 and
to_cahr(hire_date,’yyyy’) <=1983);

105. List the manager who are senior to king and who are junior to
smith
Select * from employees where employee_id in(select manager_id from employees where hire_date
<(select hire_date from employee where first_name=’KING’) and hire_date > ( select hire_date from
employees where first_name=’SMITH’ ) and manager_id is not null;

106. list the employee number,employee name,salary of the employees


with / ann salary <34000 but receiving some column.which should
not be >salary and desg should be sales ,man working for department
number 30.
Select employee_id,first_name,salary,job from employees where 12*(salary+nvl(commission_pct,0))<
34000 and comm. Is not null and comm < salary and job=’SALESMAN’ and department_id=30;

107. list the employee who are working for department number 10 or 20
with desg as clerk or analyst with a salary is either 3 or 4 digits with
an experience>8yearsbut does not belong to mons of mar,apr,sep and
working gor manager and numner is not ending with 88 and 56.
Select * from employees where department_id in (10,20) and job in (‘CLERK’,’ANALYST’) and
(length(salary) in (3,4)) and ((months_between(sysdate,hire_date))/12)>8 and to_char(hire_date,’mon’)
not in (‘mar’,’sep’,’apr’) and (manager_id not like ‘%88’ and manager_id not like ‘%56’);

108. list the highest paid employees working under king.


Select * from employees where salary in(select max(salary) from employees where manager_id in
(select employee_id from employees where first_name=’KING’));

===================================================
============================================
Table_name – Employee_Detail
Employee_id First_Name Last_Name Salary Joining Date Department Gender
1 Vikas Jain 27000 2000-07-19 MEC M
2 Nikita Das 22500 1998-09-19 IT F
3 Ashish Kumar 9000 2004-12-19 CE M
4 Navin Sharma 19000 2009-05-19 MEC M
5 Sonali Gupta 17500 2012-02-19 ELE F

109. Display first name and Gender as M/F.(if male then M, if Female
then F).
select First_Name, case when Gender = 'Male' then 'M' when gender = 'female' then 'F'
end from Employee_Detail ;
110. To generate the even/odd numbers from dual. for eg..generate odd
numbers between 1 to 10. or generate even numbers between 1..10.
select * from (select case when mod(rownum,2)=0 then rownum end even from dual connect by
rownum <=&num) where even is not null ;
select * from (select case when mod(rownum,2)=1 then rownum end odd from dual connect by rownum <=&num)
where odd is not null ;

111. To find the sum of negative numbers and the sum of the positive
numbers in two separate columns.

Table_name – Neg_Pos
number
-1
-2
-3
1
2
3

select sum(case when number < 0 then num else 0 end) neg, sum(case when number > 0 then num else 0
end)pos from Neg_Pos ;

112. Write a query to select only those rows which contains


alphanumeric values.
Table_name – Alpha_numeric
Colu_Name
1000
A1093b
23b24f
277
89ns6
391

select * from Alpha_Numeric where length(trim(translate(Colu_Name,'1234567890',' '))>0);

113. To find those employees who are more than 21 years of age.
select name from Find_Age where dob < (select add_months(sysdate,-(12*21)) from dual);

114. To find the missing number between the minimum and maximum
number for each id. text column can be ignored.
Test_Number
Id Name Text
1 1 aa
1 3 cc
1 7 gg
1 11 kk
2 1 ll
2 2 mm
2 3 nn
2 6 qq
3 2 bb
3 5 ee

Test_Number_Min_Max
Id Min Max
1 1 11
2 1 5
3 1 2

output :
ID SEQ
12
14
15
16
17
19
1 10
24
25
31
33
34

select r id ,l seq from (select level l from dual connect by level <13), (select level r from dual connect by
level <4), Test_Number_Min_Max where r=id and l>=mn and l<=mx and (r,l) not in (select id,seq from
Test_Number);

115. Beginner question based on the above logic. From the table given
below, all the numbers should be on the first column and the
alphabets on the second column.
ALPA RANK
==============
a1
b2
c4
x5
y6
z8
9g
0f
7e
à select p.project_name , e.first_name from project_details p inner
join employee_details e
on p.employe_id = e.id where p.project_name in(select project_name
from project_details group by project_name having count(1)>1) ;All
the alphabets on column B and all numbers in column A
OUTPUT:
AB
——–
0f
1a
2b
3d
4c
5x
6y
7e
8z
9g

SELECT least(alpa,rank) a,greatest(alpa,rank) b FROM test_b ORDER BY 1

116. Write down the query to fetch Project Name on which more than
one employee are working along with Employee Name
Table_name – EmployeeDetail
Employee_id First_Name Last_Name Salary Joining Date Department Gender
1 Vikas Jain 27000 2000-07-19 MEC M
2 Nikita Das 22500 1998-09-19 IT F
3 Ashish Kumar 9000 2004-12-19 CE M
4 Navin Sharma 19000 2009-05-19 MEC M
5 Sonali Gupta 17500 2012-02-19 ELE F
Project _Details
Project_id Employee_id Project_Name
1 1 Task Track
2 1 CLP
3 1 Survey Management
4 2 HR Management
5 3 Task Track
6 3 GRS
7 3 DDS
8 4 HR Management
9 6 GL Management

select p.project_name , e.first_name from project_details p inner join employee_details e


on p.employe_id = e.id where p.project_name in(select project_name from project_details group by
project_name having count(1)>1) ;

117. rite down the query to fetch employee_name & project who has
assign more than one project.

select employee_id, first_name, project_name from employee_detail e inner join project_detail p


on e.employee_id = p.employee_details where employee_id in
(select employee_detailsfrom project_detail group by employee_details having count(*) >1 ) ;

118. Get complete record (employee_name, project _name) from both


tables(employee_details,project_details) , if no match found in any
table then show NULL.
select first_name,project_name from employee_details a full outer join project_details b
on a.employee_id = b.employee_details order by first_name ;

119. Write down the query to fetch Project_name assign to more than
one Employee.
Select project_name,Count(*) from Project_details group by project_name having count(*)>1;

120. "employee_details" table after removing white spaces from right


side
select rtrim(first_name) as first_name from employee_details ;

121. To find how many employee exist in "employee_details" table.


To find how many employee exist in "employee_details" table.

122. Get the first_name, current _date, joining_date and diff between
current_date and joining-date in days.
select first_name, sysdate, joining_date, datediff(dd,joining_date,sysdate) as total_months
from employee_details;

123. Get the first_name, current _date, joining_date and diff between
current_date and joining-date in months.
select first_name, sysdate, joining_date, date, datediff(mm,joining_date,sysdate) as total-
months from employee_details;

124. To display Greatest number (10, 0, 88, 11, 900, 166)


Select greatest (10, 0, 88, 11, 900,166) from dual;

125. To display least number (10, 0, 88, 11, 900, 166)


Select Least (10, 0, 88,11, 900,166) from dual;

126. Produce a company organization chart that shows a management


hierarchy. Start with the person at thetop level, exclude all those job
ID IT_PROG, and exclude De Haan and those employees who report
to DeHaan.
select e.employee_id,e.last_name ,e.salary from employees e join employees m
on(e.manager_id=m.employee_id) where m.last_name<>'De Haan' and e.last_name<>'De Haan' and
e.job_id!='IT_PROG' order by e.salarydesc;

127. Create a table named dept using departments table, and truncate
dept and then use the mergestatement to get the data back.
create table dept as select * from departments;
truncate table dept;

merge into deptdt using departments d


on (dt.department_id=d.department_id)
when matched then
update set dt.department_name=d.department_name,
dt.manager_id=d.manager_id,dt.location_id=d.location_id
when not matched then
insert values(d.department_id,
d.department_name,d.manager_id,d.location_id);

128. Show all employees who were hired in the first half of the month
(before the 16th of the month).
select employee_id,last_name, hire_date from employees where to_number(to_char(hire_date,'dd'))<16;

129. Get number of days left in current month.


select sysdate, last_day(sysdate), last_day(sysdate) - sysdate from dual ;
130. Get number of seconds passed since today (since 00:00 hr)
select (sysdate - trunc (sysdate)) * 24 * 60 * 60 num_of_sec_since_morning from dual;

131. get number of seconds left today (till 23:59:59 hr)


select (trunc (sysdate+1) - sysdate) * 24 * 60 * 60 num_of_sec_left from dual;

132. Check if a column exists in a table


select column_name as found from user_tab_cols where table_name=’ table_name’ and column_name=’
column_name’;

133. To fetch alternate records from a table (Even Number)


select * from employees where rowid in (select decode(mod(rownum,2),0,rowid, null) from employees);

134. To fetch alternate records from a table (OddNumber)


select * from employees where rowid in (select decode(mod(rownum,2),0, null, rowid) from employees);

135. select first n records from a table


select * from employees minus select * from employees where rownum<=(select count(*) - &n from
employees );

136. How to get nth max salaries


select distinct hire_date from employees a where &n = (select count(distinct salary) from employees b
where a.salary >= b.salary);

137. How to delete duplicate rows in a table.


delete from employees a where rowid != (select max(rowid) from employees b where
a.empolyee_id=b.employee_id);

138. Display employee name start with g and end with e and also shows
position of second e but without using like operator.
Select last_name,instr(last_name,’e’,1,2) from employees where substr(last_name,1,1)=’G’ and
substr(last_name,1,1)=’e’ ;

139. Show the middle character of the string last_name.


Select last_name ,substr(last_name,round(length(last_name)/2,1) from employees;

140. Write a program length of name should be same but it end with
character e.
Select first_name, last_name from employees where length(first_name)= length(last_name) and last_name
like %e% ;

141. Input:-aaabbb Display bbbaaa without using reverse operator


Select concat(replace(substr(‘aaabbb’,1,3),’a’,’b’) ,replace(substr(‘aaabbb’,4,6) ,’b’,’a’)) From dual;

142. Input:-aaabbb Display Aaabbb without using Initcap operator.


Select concat(upper(substr(‘aaabbb’,1,1),1,1), substr(‘aaabbb’,2,6)) from dual ;

143. Input:-aaabbb Display aaabbbB without using reverse operator.


Select concat(substr(‘aaabbb’,1,5),’1’,’1’), upper(substr(‘aaabbb’,1,6))) from dual ;

144. Input:-aaabbb Display AaabbbB without using reverse operator.


Select concat(upper(substr(‘aaabbb’,1,1)), concat(substr(‘aaabbb’,2,5),upper((substr(‘aaabbb’,6)))) from
dual ;

145. Length of first_name and last_name is same then print EQUAL if


not same then print NOTEQUAL.
Select nvl2 (nullif(length(‘first_name’), length(‘last_name’),’ EQUAL’,’ NOTEQUAL’ from employees;

146. Display the number of employee work in department_id=50


Select count(*) from employees where department_id=50;\

147. Who are entitled to earn commission department_id=50


Select count(commission_pct) from employees where department_id=50;

148. Distinct number of department values that are in employee table.


Select count (distinct (department_id)) from employees ;

149. Display of employee name that is first and last is an alphabetic of


an employee
Select min (last-name) – max (last-name) from employees ;

150. Display Junior and Senior of employee.


Select avg (salary), department_id, job_id from employees where job_id =’IT’ or department_id=50
group by department_id, job_id having avg (salary)>5000 order by 2 ;

151. Count the employee for same job_id


Select count (employee_id),job_id from employees group by job_id

152. Show the total character in last_name of employee table


Select sum(length (last-name)) from employees ;

153. Create a query that will display the total number of employee hired
in 1995,1996.
Select to_char(hire_date,’yyyy’),count(employee_id) where to_char(hire_date,’yyyy’) in (1995,1996)
group by to_char(hire_date,’yyyy’) order by to_char(hire_date,’yyyy’) ;

154. Display the manager number and salary of the lowest paid
employee for that manager,avg(sal)<6000.sort the output is
ascending order
Select manager_id from employees having avg(salary)<6000 group by manager_id order by manager_id
;

155. Display number of people with the same job_id.


Select job_id,count(employee_id) from employees group by job_id ;

156. Display last_name and commission_pct if employee does not earn


commission_pct put no commission label the column ‘comm’
Select last_name,replace(nvl(commission_pct),0) , ‘0’, ‘no common’)) as comm. From employees ;

157. Using decode function grade of employee based on the value of the
column job_id as per the following data. AD_PRES -A
ST_MAN -B
IT_PROG - C
SA_REP - D
Other -0
Select job_id,decode(job_id,’ AD_PRES ‘ , ‘A’ ,
‘ST_MAN’, ‘ B ‘ ,
‘ IT_PROG , ‘C’ ,
‘SA_REP’ ,’ D’ ,
‘Other ‘ ,‘0’ ) from employees group by job_id ;

158. Hire_date -31 dec –day find out.


Select hire_date,last_day(add_months(trunc(hire_date,’year’ ),11)) from employees;

159. Display employee whose job_id is the same as that of employee id


is 141
Select job_id from employees where job_id =( Select job_id from employees where employee_id=141)
;

160. Display manager_id whose last_name=John &department_id


whose employee_id=141.
Select * from employees where manager-id=(select manager_id from employees where last_name=’
John’) or department_id=(select department_id from employees where employee_id=141 );

161. Display employee last_name,job_id & salary of all employees


whose salary is equal to the min(salary)
Select employee last_name,job_id ,salary from employees where salary=(select min(salary) from
employees) ;

162. Display all the department that have a min(sal) >


department_id=50
Select department_id , min(salary) from employees group by department_id having min(salary) > =
(select min(salary) from employees where department_id=50) ;

163. Display the details of employee who work in the same department
& have the same manager as John.
Select * from employees where manager_id in (Select manager_id from employees where
first_name=’John’) and department_id in (Select department_id from employees where
first_name=’John’) ;

164. Find the employee who earn the same salary as the salary for
department =90 & department =50
Select job_id,salary from employees where salary in (select salary from employees where department_id
in (90,50) ;

165. Top 5 salaries are displayed.


Select * from (select salary from employees order by salary 1 desc ) where rownum <=5 ;

166. Lowest 5 salary are displayed


Select * from (select salary from employees order by salary 1 asc ) where rownum <=5 ;

167. Find the employee who earn more than avg(salary) in their
department.
Select last-name,salary,department_id from employees outer where salary > (select avg(salary) from
employees where department_id=outer. department_id ) ;

168. Find the employee who has at least one person reporting to them.
(exist operator)
Select employee_id,last_name from employees outer where exists (select ‘a’ from employees where
employee_id=outer.employee_id ) ;

169. Department that do not have any employee. (Non-exist operator)


Select department_id,ldepartment_name from departments outer where not exists (select ‘a’ from
employees where department_id=outer.department_id ) ;

170. Display department_id,department_name,location_id,city (Using


Join)
Select department_id,department_name,location_id,city from departments natural join locations ;

171. Display department_id,department_name,location_id,city &


department_id=20,50 (Using Join)
Select department_id,department_name,location_id,city from departments natural join locations where
department_id in (20,50) ;

172. Display region_name is Africa & location_id is 1700 (using on


clause)
Select e.employee_id,r.region_name,l.location_id from employees e join departments d on
(e.department_id=d. department_id) join locations l on (d.location_id=l. location_id) join countries c on
(l.country_id=c. country_id) join regions r on (c.region_id=r.region_id) where l.location_id=1700 ;

173. Display employee_id,last_name,location_id , & department_id


(using clause)
Select employee_id,last_name,location_id ,department_id from employees join departments
using(department_id);

174. Display employee_name & their manager_name.


Select e.last_name,m. last_name from employees e join employees m on (e.manager_id=m.employee_id)
;

175. Display employee_id, department_name & city of the employee.


Select e.lemployee_id ,d. department_name ,l.city from employees e join departments on (e.
department_id=d. department_id) join locations l on (d.location_id=l.location_id) ;

176. Get the last day of the year


SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL;

177. Get number of days in current month


SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days from dual;

178. Get number of days left in current month.


SELECT SYSDATE, LAST_DAY (SYSDATE) "Last", LAST_DAY (SYSDATE) - SYSDATE "Days
left" FROM DUAL;

179. Display each months start and end date upto last month of the year
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date, TRUNC (LAST_DAY
(ADD_MONTHS (SYSDATE, i))) end_date FROM XMLTABLE ('for $i in 0 to xs:int(D) return $i'
PASSING XMLELEMENT (d,FLOOR (MONTHS_BETWEEN (ADD_MONTHS (TRUNC
(SYSDATE, 'YEAR') - 1, 12),SYSDATE)))COLUMNS i INTEGER PATH '.');

Data dictionary queries


180. Check if a column exists in a table

SELECT column_name AS FOUND FROM user_tab_cols WHERE table_name = 'TABLE_NAME' AND


column_name = 'COLUMN_NAME';
181. Pass the Object:- “1526” and Display the output: one thousand five hundred twenty-six
SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;
182. Find the last record from a table.
SELECT * FROM employees WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);

(OR)

SELECT * FROM employees MINUS SELECT * FROM employees WHERE ROWNUM <(SELECT
COUNT (*) FROM employees);

Table 1:
SELECT * FROM PRODUCTS;

PRODUCT_ID PRODUCT_NAME
-----------------------
100 Nokia
200 IPhone
300 Samsung

Table 2:
SELECT * FROM SALES;

SALE_ID PRODUCT_ID YEAR QUANTITY PRICE


--------------------------------------
1 100 2010 25 5000
2 100 2011 16 5000
3 100 2012 8 5000
4 200 2010 10 9000
5 200 2011 15 9000
6 200 2012 20 9000
7 300 2010 20 7000
8 300 2011 18 7000
9 300 2012 20 7000

183. Write a SQL query to find the products which have continuous
increase in sales every year?
SELECT PRODUCT_NAME
FROM
(
SELECT P.PRODUCT_NAME,
S.QUANTITY -
LEAD(S.QUANTITY,1,0) OVER (
PARTITION BY P.PRODUCT_ID
ORDER BY S.YEAR DESC
) QUAN_DIFF
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
GROUP BY PRODUCT_NAME
HAVING MIN(QUAN_DIFF) >= 0;
184. Write a SQL query to find the products which does not have sales
at all?
SELECT P.PRODUCT_NAME FROM PRODUCTS P LEFT OUTER JOIN SALES S
ON(P.PRODUCT_ID = S.P
Or
SELECT P.PRODUCT_NAME FROM PRODUCTS P WHERE P.PRODUCT_ID NOT IN(SELECT
DISTINCT PRODUCT_ID FROM SALES);
Or
SELECT P.PRODUCT_NAME
FROM PRODUCTS P
WHERE P.PRODUCT_ID NOT IN
(SELECT DISTINCT PRODUCT_ID FROM SALES);
Or
SELECT P.PRODUCT_NAME FROM PRODUCTS P
WHERE NOT EXISTS (SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);

185. Write a SQL query to find the products whose sales decreased in
2012 compared to 2011?
SELECT P.PRODUCT_NAME
FROM PRODUCTS P,
SALES S_2012,
SALES S_2011
WHERE P.PRODUCT_ID = S_2012.PRODUCT_ID
AND S_2012.YEAR = 2012
AND S_2011.YEAR = 2011
AND S_2012.PRODUCT_ID = S_2011.PRODUCT_ID
AND S_2012.QUANTITY < S_2011.QUANTITY;

186. Write a query to select the top product sold in each year?
SELECT PRODUCT_NAME,
YEAR
FROM
(
SELECT P.PRODUCT_NAME,
S.YEAR,
RANK() OVER (
PARTITION BY S.YEAR
ORDER BY S.QUANTITY DESC
) RNK
FROM PRODUCTS P,
SALES S
WHERE P.PRODUCT_ID = S.PRODUCT_ID
)A
WHERE RNK = 1;

187. Write a query to find the total sales of each product.?


SELECT P.PRODUCT_NAME,
NVL( SUM( S.QUANTITY*S.PRICE ), 0) TOTAL_SALES
FROM PRODUCTS P
LEFT OUTER JOIN
SALES S
ON (P.PRODUCT_ID = S.PRODUCT_ID)
GROUP BY P.PRODUCT_NAME;

188. Write a query to display only Friday dates from Jan, 2000 to till
now?
SELECT C_DATE, TO_CHAR(C_DATE,'DY') FROM (SELECT TO_DATE('01-JAN-2000','DD-
MON-YYYY')+LEVEL-1 C_DATE FROM DUAL CONNECT BY LEVEL <=(SYSDATE -
TO_DATE('01-JAN-2000','DD-MON-YYYY')+1)) WHERE TO_CHAR(C_DATE,'DY') = 'FRI';
189. Write a query to duplicate each row based on the value in the repeat column? The input table data looks like as
below.
Products Repeat
--------- -------
A, 3​
B, 5​
C, 2​

Now in the output data, the product A should be repeated 3 times, B should be repeated 5 times and C should be
repeated 2 times. The output will look like as below
Products ​Repeat
-------- ​--------
A 3​
A 3​
A 3​
B 5​
B 5​
B 5​
B 5​
B 5​
C 2​
C 2​

Date Format convert with To_char function

Oracle date format

Format Mask ​ ​Description


CC ​ ​ ​ Century
SCC ​ ​ ​Century BC prefixed with -
YYYY ​ ​ ​Year with 4 numbers
SYYY ​ ​ ​Year BC prefixed with -
IYYY ​ ​ ​ISO Year with 4 numbers
YY ​ ​ ​Year with 2 numbers
RR ​ ​ ​Year with 2 numbers with Y2k compatibility
YEAR ​ ​ ​Year in characters
SYEAR ​ ​ ​Year in characters, BC prefixed with -
BC / AD ​ ​BC/AD Indicator *
Q ​ ​ ​Quarter in numbers (1,2,3,4)
MM ​ ​ ​Month of year 01, 02...12
MONTH ​ ​Month in characters (i.e. January)
MON ​ ​ ​JAN, FEB
WW ​ ​ ​Week number (i.e. 2)
W ​ ​ ​Week number of the month (i.e. 3)
IW ​ ​ ​Week number of the year in ISO standard.
DDD ​ ​ ​Day of year in numbers (i.e. 234)
DD ​ ​ ​Day of the month in numbers (i.e. 28)
D ​ ​ ​Day of week in numbers(i.e. 7)
DAY ​ ​ ​Day of the week in characters (i.e. Monday)
FMDAY ​ ​ ​Day of the week in characters (i.e. Monday)
DY ​ ​ ​Day of the week in short character description (i.e.
SUN)
J ​ ​ ​Julian Day (number of days since January 1 4713 BC,
where January 1 4713 BC is 1 in Oracle)
HH ​ ​ ​Hour number of the day (1-12)
HH12 ​ ​ ​Hour number of the day (1-12)
HH24 ​ ​ ​Hour number of the day with 24Hours notation (1-
24)
AM ​ ​ ​AM or PM
PM ​ ​ ​AM or PM
MI ​ ​ ​Number of minutes (i.e. 59)
SS ​ ​ ​Number of seconds (i.e. 59)
SSSS ​ ​ ​Number of seconds this day.

SELECT ename, hiredate, TO_CHAR( hiredate ,


'fmDY.Mon.YYY' ) FROM EMP;

SELECT sysdate, TO_CHAR ( sysdate, 'fmDD.MM.YYYY


fmHH:MI:SS PM' ) Zaman FROM dual ;

SELECT sysdate, TO_CHAR ( sysdate, 'fmDD.MM.YYYY


fmHH12:MI:SS PM' ) Zaman FROM dual ;

SELECT sysdate, TO_CHAR ( sysdate, 'fmDD.MM.YYYY


fmHH24:MI:SS' ) Zaman FROM dual ;

SELECT sysdate, TO_CHAR ( sysdate, 'fmDD.MM.YYYY


fmHH24:MI:SS AM' ) Zaman FROM dual ;

SELECT sysdate, TO_CHAR ( sysdate, 'fmDD.MM.YYYY


fmHH24:MI:SS AM' ) Zaman FROM dual ;

SELECT TO_CHAR( TO_DATE('28-11-1942') , 'YY') date


FROM dual;

SELECT TO_CHAR( TO_DATE('28-11-1942') , 'CC') date


FROM dual;

SELECT TO_CHAR( TO_DATE('28-11-2942') , 'SCC') Date


FROM dual;

SELECT TO_CHAR( TO_DATE('28-11-1942') , 'fmd' ) "Day Of


Week" FROM dual ;
SELECT TO_CHAR( TO_DATE('28-11-1942') , 'fmdd' ) "Day Of
Month" FROM dual ;

SELECT TO_CHAR( TO_DATE('28-11-2942') , 'fmddd' ) "Day


Of Year" FROM dual ;

The next example outputs the Julian Day; the number of days since 31
December 4713 BC of the given date.
SELECT TO_CHAR( TO_DATE('28-11-2942') , 'fmJ' ) "Julian
Day" FROM dual ;
SELECT TO_CHAR( TO_DATE('28-11-1942') , 'fmBC' ) "BC
Indicator" FROM dual ;
SELECT TO_CHAR( TO_DATE('28-11-1942') , 'fmBC' ) "AD
Indicator" FROM dual ;
SELECT ename, hiredate, TO_CHAR(hiredate, 'fmCC') FROM
EMP ;
SELECT TO_CHAR( TO_DATE('18-09-1972') , 'w' ) "Week of
Month" FROM dual ;
SELECT TO_CHAR( TO_DATE('18-09-1972') , 'ww' ) "Week of
Year" FROM dual ;

You might also like