Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views18 pages

SQL

The document provides an overview of SQL as a database language, distinguishing it from programming languages and explaining its various sub-languages including DDL, DML, DQL, TCL, and DCL. It details types of queries that can be executed, examples of SQL commands, and common interview questions related to SQL data types and operations. Additionally, it covers join queries and provides examples of SQL queries for data retrieval from multiple tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

SQL

The document provides an overview of SQL as a database language, distinguishing it from programming languages and explaining its various sub-languages including DDL, DML, DQL, TCL, and DCL. It details types of queries that can be executed, examples of SQL commands, and common interview questions related to SQL data types and operations. Additionally, it covers join queries and provides examples of SQL queries for data retrieval from multiple tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

SQL

Introduction: SQL is a database language. But not a programming language. Generally, a programming
language used to write a program by collection of many instructions and by executing the program, we get
a complete problem solution. A programming language only develops code to provide logical solution for
the problem but it doesn’t interact with database and doesn’t perform operations on database. On the
other hand, a database language supports commands and when these commands are executed, they
perform operations on database. Generally, the database language commands are executed individually
but not as a group. When we are developing a software for business application, we write programs to
provide logical business solutions and we use database language to perform database operations. In this
scenario we need to execute both business solutions and database operations at a time. That means we
need to write programs by combining both programming language code and database language code
together. This is called embedded SQL.
Example: ODBC, JDBC and ADODAO
To implement database operations, we have different types of sub languages in SQL
1. DDL
2. DML
3. DRL or DQL
4. TCL
5. DCL

DDL:
It means data definition language, it contains commands to ‘create’ database schema (Tables), and also to
create integrity constraints. It also contains ‘alter’ to modify the schema and integrity constraints and it also
contains ‘drop’ to remove the database schema and also integrity constraints from the database.

DML:
It means data manipulation language. It contains commands to store new records of data and to update
existing records of data and to delete existing records of data. For this we have ‘insert’, ‘update’ and
‘delete’.

DRL or DQL:
It is data retrieval language or data query language. It contains only one command called ‘select’, to
retrieve or extract data from database tables. Extracting data from database is called query.

TCL:
It is transaction control language. It contains commands to control execution of transactions. There three
commands
1. Commit
2. Rollback
3. Save point

DCL:
It is data control language. It contains ‘create’, ‘grant’ and ‘revoke’, to create users, to provide privileges for
users, to cancel privileges from users and also uses ‘drop’ to delete users.
Types of queries:
There are different types of queries we can execute using DRL (Select).
1. Entire database table (retrieve all)
2. Selection (restriction)
3. Projection
4. Selection + Projection
5. Join queries
a. Outer-join
b. Inner-join
c. Self-join
6. Sub queries (Nested queries)
7. Aggregation queries
8. Aggregated sub queries
9. Co-related sub queries
10. Windows queries

Queries:
Consider following two relations EMP and DEPT.
The schema of EMP is: The schema of DEPT is:
EMP NUMBER (4) DNO NUMBER (2)
EMPNAME STRING DNAME STRING
JOB STRING LOCATION STRING
MGR NUMBER (4)
SALARY NUMBER (10,2)
COMM NUMBER (6,2)
DNO NUMBER (2)
DOJ DATE
Oracle supports following several string data types:
1. Char
2. Var char (2)
3. Nchar
4. Nvarchar (2).
Few Interview Questions:
1. What is the difference between char and varchar (2)? which is efficient in storing string data?
A) The size of varchar (2) is larger than char. We can define larger strings in varchar (2) than char. Char
supports fixed size allocation and varchar (2) supports variable size allocation.

2. What is the difference between char and nchar in storing string data?
A) Char stores at maximum 256 bits and nchar stores 2000 bits. Char uses ASCII code and nchar uses
universal alphabet code (UNI code).

3. Is there any relation between nchar in oracle and char data type in java?
A) Both are same.
Example Queries:
1. Retrieve all from EMP table (All records from table and all fields in record): select * from EMP;
2. Display name and job of all the employees (Projection): select EMPName, Job from EMP;
3. Display all the details of employees working in department 10 (selection or restriction):
select * from EMP where dno=10;
4. Display only name and job of employees working in department 10:
Select EMPName, Job from EMP where dno=10;
5. Display Job of all the employees working in either department 10,20,40 with alias name
profession for Job field:
Select Job as Profession from EMP where dno in (10,20,40);
6. Display all the employees working in either 10 or 40 department but their salary should be less
than 50K:
Select EMPName from EMP where dno in (10,40) and salary < 50000;
7. Display only first 5 letters of employee names who joined in the year 2000:
Select SUBSTRING(EMPName,1,5) from EMP where DOJ BETWEEN ’2000-01-01’ and ’2000-12-31’;
8. Find names and jobs of all the employees drawing above 1L salary and joined before 2000:
Select EMPName and Job from EMP where salary > 100000 and DOJ < ‘2000-01-01’;
9. Find total salary of all the employees’ employee wise as sum of salary + commission in the
department 10 or 40 and joined before 1990:
Select salary + commission as Total_Salary from EMP where dno in (10,40) and DOJ < ‘1990-01-01’;
10. Display employee number and their manager number who are working in department 10 or 40:
Select EMP, MGR from EMP where dno in (10,40);
11. Find maximum salary of all the employees working in various departments in Chicago location:
Select MAX (salary) from EMP where dno = (select dno from DEPT where LOCATION = ‘Chicago’);
12. Find the number of employees working in marketing department:
Select count (EMP) from EMP where dno = (select dno from DEPT where DNAME=’Marketing’);
13. Display employees drawing more salary than ‘Allen’:
Select EMPName from EMP where salary > (select salary from EMP where EMPName = ‘Allen’);
14. Find number of employees working in the same department as John:
Select count (EMPName) from EMP where dno = (select dno from EMP where EMPName = ‘John’);
15. Find highest salary in each department, department wise:
Select MAX (salary) from EMP group by DNO;
16. Find the department numbers where minimum 5 employees are working:
Select DNO from EMP group by DNO having count (EMP) >= 5;
17. Find names of all the employees working in Chicago location drawing more salary than ‘Allen’ and
joined after 2000:
Select EMPName from EMP where salary > (select salary from EMP where EMPName = ‘Allen’) and
DOJ > ‘2000-12-31’ and dno = (select dno from DEPT where location = ‘Chicago’);
18. Display first 3 employee details:
Select top 3* from EMP; or select * from EMP limit 3; or select * from EMP fetch 3 rows only;
19. Display last 3 employee details:
Select * from EMP where rownum > (select count (*) from emp) - 3;
20. Display both first and last 3 employee details:
Select head (3), tail (3) from EMP;
21. Display first 5 employees having highest salary:
Select top 5 * from EMP order by salary DESC;
22. Display details of 5 employees having salary:
Select top 5 * from EMP order by salary;
23. Display details of 50% employees in table:
Select top 50 percent * from EMP;
24. Display half of the employees drawing less than 1L salary:
Select 50 percent * from EMP where salary < 100000;
25. Display first 2 employees drawing 45K salary:
Select * from EMP where salary = 45000 limit = 2;
26. Display first 2 employees in alphabetical order of employee name drawing 45K salary:
Select top 2 * from EMP where salary = 45000 order by EMPName;
27. Display details of 3,4 records:
Select * from EMP where rownum in (3,4); or select * from emp limit 2 offset 2;
28. Find highest salary in the company:
Select MAX (salary) from EMP;
29. Find Name and Job of salary with highest salary:
Select EMPName, Job from EMP where salary = (select MAX (salary) from EMP);
30. Find 2nd highest salary in the company:
Select * from EMP where rownum = 2 order by salary DESC; or
select MAX (salary) from EMP where salary < (Select MAX (salary) from EMP); or
select * from EMP order by salary DESC limit 1 offset 1; or
select salary from (select salary, Dense_rank() over (Order by salary desc) as rank from EMP) ranked
data where rank =2; or
select distinct salary from (select distinct salary, row_number() over (Order by distinct salary rn
from EMP) date where rn=2;
31. Display first 2 employees having highest salary and last 2 employees having least salary:
Select * from EMP order by salary DESC limit 2 union select * from EMP order by salary limit 2;
32. Display both 2nd highest and 2nd least salary:
Select * from EMP order by salary DESC limit 1 offset 1 union select * from EMP order by salary limit
1 offset 1;

Consider following relations in data base:


Student Course Enrolled Faculty
Snum int Name String Snum int Fid int
Name String Time String CourseName String Name String
Major String Room String Dept String
Level char (2) Fid int
Age int
Questions:
1. Find names of all CS majors’ who are enrolled in the course Math92.
Select Name from Student where Major = ‘CS’ and Snum in (select Snum from Enrolled where
CourseName = ‘Math92’); or
Select Name from Student S, Enrolled E where S.Snum = E.Snum and S.Major=’CS’ and
E.CourseName = ’Math92’;
2. Find names of all the CS majors, who are enrolled in the course Math92 and older than some
history freshman (Level – fr).
Select Name from Student where Major = ‘CS’ and Snum in (select Snum from Enrolled where
CourseName = ‘Math92’) and Age > any (Select Age from Student where Level = ‘fr’);
3. Find all the names of all courses that are either meet in room R128 or taught by H. Merlin.
Select Name from courses where roomid = ‘R128’ union select name from courses where fid =
(Select fid from faculty where name = ‘H.Merlin’); or
Select Name from Course, Faculty where Course.Room = ‘R128’ or Course.Fid = Faculty.Fid and
Faculty.Name = ‘H. Merlin’;
4. Find the names of all pair of students who are enrolled in some course together.
Select (select s1.Name from Student s1 where s1.Snum = e1.Snum), (select s2.Name from student
s2 where s2.Name = e2.Name) from Enrolled e1, Enrolled e2 where e1.CourseName =
e2.CourseName and e1.Snum < e2.Snum;
5. Print level and average age of students for that level for each level.
Select level, AVG (age) from student group by level;
6. Find names of all students who are not enrolled in any class taught by H. Merlin.
Select Name from student where snum not in (select snum from Enrolled where CourseName in
(select Name from Courses where fid = (select fid from Faculty where Name = ‘H.Merlin’)));
7. Find names of students who enrolled in most classes.
Select Name from Student where Snum in (Select Snum from Enrolled group by Snum having count
(CourseName) = (select MAX (c) from (select count (CourseName) as c from Enrolled group by
Snum) as sub));
8. Find names of all juniors (level = ‘jr’) who are enrolled in a class taught by ‘I. Teach’.
Select s.Name from Student S, Enrolled E, Course c, Faculty F where s.Snum = E.Snum and
E.CourseName = c.Name and c.fid = F.fid and F.Name = ‘I.Teach’ and s.level=’jr’; or
Select s.Name from student s where s.level=’jr’ and s.Snum in (select E.snum from Enrolled E where
E.CourseName in (select CourseName from Course where fid in (select fid from Faculty F where
F.name = ‘I. Teach’)));

Join Queries:
Generally, a query written using select command extracts data records from a single table. We know a
database contains multiple different tables for storing data about business application. Sometimes we need
to extract or retrieve data from multiple tables at a time where tables have common fields. That means we
need to extract data from two or more tables at a time, where records of one table matched with records
of another table using common field. Here common field means, a field or column representing same type
of data in two tables. Its datatype and size should be same in two tables. The field name can be different. A
query which extracts this kind of data is called join query. When we write a join query, during execution
first it performs cross product of two tables then applies join condition which filters the records in such a
way that only matched records are extracted and unmatched records are ignored. This condition is called
join condition and it is formed using common field. Apart from join condition, we can have any number of
other conditions depending on the requirement.
Syntax:
1. select field lists from table1, table2 where table1.field = table2.field (Join condition)
2. select field lists from table1 t1, table2 t2 where t1.field = t2.field (Join condition)
3. select field lists from table1 t1 join table2 t2 on t1.field = t2.field

Consider following three tables or relations in database:


Suppliers Parts Catalogue
Sid Integer Pid Integer Sid Integer
Sname String Pname String Pid Integer
Address String Color String Cost Real
Questions:
1. find pnames of parts for which there is some supplier.
Select Pname from parts where pid in (select pid from Catalogue);
2. Find snames of supplier who supply every parts.
Select Sname from suppliers where sid in (select sid from Catalogue group by Sid having count(pid)
= (select count(pid) from Parts));
3. Find snames of supplier who supply red parts.
Select sname from suppliers where sid in (select sid from catalogue where pid in (select pid from
parts where color = ‘red’));
4. Find pnames of parts supplied by ‘ACME’ but not by other suppliers.
Select pname from parts where pid in (select pid from Catalogue where sid = (select sid from
suppliers where sname = ‘ACME’) group by pid having count (sid) =1)
5. Find sid of suppliers who supply red part or green part.
Select sid from catalogue where pid in (select pid from parts where color=’red’ or color= ‘green’);
6. Find sid of suppliers who supply red part and green part.
Select sid from catalogue where pid in (select pid from parts where color=’red’) intersect select sid
from catalogue where pid in (select pid from parts where color=’green’);

Example 2:
1. Write SQL query to fetch first name from student table and convert it to upper case using alias
name
Select UPPER(First_Name) as UPPERNAME from student;
2. Write SQL query to fetch unique values of major subjects from student table. (Write query
without group by clause.)
Select distinct major from student;
3. Write SQL query to fetch unique values of major subjects from student table. (Write query with
group by clause.)
Select major from student group by major;
4. Write SQL query to print first 3 characters from first_student table.
Select substr(first_name,1,3) from student;
5. Write SQL query to find position of alphabet ‘a’ in first_name column for student ‘shivansh’.
Select locate (‘a’, first_name) from student where first_name=’shivansh’;
6. Write SQL query to fetch unique values of major subjects and also print their length. (Note:
without using group by clause.)
Select major, length(major) from (select distinct major from student);
7. Write SQL query to fetch unique values of major subjects and also print their length. (Note: with
using group by clause.)
Select major, length(major) from student group by major.
8. Write SQL query to print first_name from student table after replacing ‘a’ with ‘A’.
Select replace (first_name, ‘a’, ‘A’) from student;
9. Write SQL query to print first_name and last_name from student table as single column
‘complete_name’.
Select concat (first_name, last_name) as Complete_Name from student;
10. Write SQL query to print first_name and last_name from student table as single column
‘complete_name’ with separator space.
select concat (first_name,concat(‘ ‘, last_name)) from student;
11. Write SQL query to print all student details from student table sorted by first_name ascending
then major subject descending.
Select * from student order by first_name, major desc;
12. Write SQL query to print details of students with first_name as either ‘Prem’ or ‘Shivansh’.
Select * from student where first_name in (‘Shivansh’, ‘Prem’);
13. Write SQL query to print details of students except students with first_name as ‘Prem’ or
‘Shivansh’.
Select * from student where first_name not in (‘Shivansh’, ‘Prem’);
14. Write SQL query to print details of students where first_name ends with ‘a’.
Select * from student where first_name like ‘%a’;
15. Write SQL query to print details of students where first_name starts with ‘a’.
Select * from student where first_name like ‘a%’;

16. Write SQL query to print details of students where first_name starts with ‘a’ and ends with ‘a’.
Select * from student where first_name like ‘a%’ and first_name like ‘%a’;
17. Write SQL query to fetch details of students where first_name contains ‘a’ as 4 th letter.
Select *from student where substr(first_name,4,1) = ’a’;
18. Write SQL query to print details of students where first_name ends with ‘a’ and contains only 5
alphabets.
select * from student where first_name like ‘%a’ and length(first_name) = 5;
19. Write SQL query to display count of students having major subject as Computer Science.
Select major, count(first_name) from student group by major having major=’cs’;
20. Combine first name and last name as single name for all the subjects with GPA between 8.5 and
9.5
Select concat(first_name, last_name) from student where GPA >= 8.5 and GPA<= 9.5;
21. Write SQL query to find number of students for each major subject in the descending order of
count value.
Select major, count(major) from student group by major order by count(major) DESC;
22. Display details of students who received scholarship, the details include scholarship details,
amount, date.
select s1.first_name, s1.last_name, s2.amount, s2.date from student s1, scholarship s2 where s1.sid
= s2.sid;
23. Display details of students who have odd student id numbers.
Select * from students where mod(sid,2)=1;
24. Display details of students who have received scholarships with computer science as major
subject.
Select *from student where major = ‘cs’ and sid in (select sid from scholarship);
25. Display even positioned student records only.
Select * from student where mod(rownum,2) = 0;
26. List all students and their scholarship amount if they received, if a student hasn’t received scholar
ship, display null for their scholarship details.
SELECT s.sid, s.first_name, s.last_name, s.major, sch.amount FROM student s LEFT OUTER JOIN
scholarship sch ON s.sid = sch.sid;
27. Display top 5 records of student table according to descending order of GPA.
Select * from students order by GPA DESC fetch first 5 rows only;
28. Find 5th highest GPA without limit keyword.
Select * from student order by GPA DESC offset 4 fetch next 1 rows only;
29. Display list of students with same GPA. Try with group by.
Select * from students where GPA in (select GPA from students group by GPA having count (*) > 1);
30. Find list of student ids how doesn’t get scholarship.
Select sid from students where sid not in (Select sid from scholarship);
31. Find major subject that has less than 4 people in it. Display count also along with subject.
Select major, count (major) as count from student group by major having count(major) < 4;
32. Write SQL query to fetch 3 maximum GPA using co-related sub query.

33. Display names of the students who has highest GPA.


Select SName from student where GPA = (select MAX(GPA) from student);
34. Create a new table that consists same data and same structure as student table.
Create table student1 as select * from student;
35. Write SQL query to find students who has same GPA as ‘Shivansh Mahajan’
Select SName from student where GPA = (Select GPA from student where SName = ‘Shivansh
Mahajan’);

What is a trigger and what is its uses in business applications?


A) A trigger is a stored procedure or function (stored data base object) that is attached to a specific
database table for a specific operation. It is executed automatically whenever the specific operation
takes place on database table. Triggering means executing automatically when event takes place,
event means execution of operations on a database table. Triggers can be used for following
reasons:
a. To enforce data integrity rules.
b. To verify validity of input values.
c. To perform automated actions.
d. To implement security and access control on database tables.
e. To implement database auditing.

Example 3:
 Consider following tables
 Sailors(sid,sname,age,rating) .
 Reserved(sid,Bid,day) .
 Boats(Bid,Bname,color) .
 Now write sql Queris to retrieve data for the following problems .
 [Note: if we can solve a query using join and sub query try both versions] .

1) find names of sailors who have reserved boat 103


select s.sname from sailors s , Reserved R where s.sid = R.sid and R.Bid=103;
select s.sname from sailors s JOIN Reserved r ON s.sid=r.sid where r.Bid = 103;
select s.sname from sailors s where s.sid in (select r.sid from reserved r where r.bid=103);
2) find names of sailors who have reserved a red boat
select s.sname from sailors s , reserved r , boats b where s.sid=r.sid AND r.bid = b.bid AND
b.color=’red’;
select s.sname from sailors s JOIN reserved r ON s.sid =r.sid JOIN boats b ON r.bid=b.bid AND
b.color=’red’;
select s.sname from sailors s where s.sid in(select r.sid from reserved r where r.bid in (select
b.bid from boats where color=’red’;
3) find the colors of the boats reserved by lubber
select b.color from boats b , sailors s , reserved r where b.bid = r.bid AND r.sid = s.sid AND
s.sname=`lubber`;
select b.color from boats b JOIN reserved r ON b.bid = r.bid JOIN sailors s ON s.sid=r.sid AND
s.sname=’lubber’;
select b.color from boats b where b.bid in(select r.bid from reserved r where r.sid in(select s.sid
from sailors s where s.sname=’lubber’));
4) find names of sailors who reserved at least one boat
select s.sname from sailors s , reserved r where r.sid=s.sid;
select s.sname from sailors s JOIN reserved r ON r.sid=s.sid;
select s.sname from sailors s where s.sid in (select r.sid from reserved r);
select s.sname from sailors s where EXISTS (select 1 from reserved r where r.sid=s.sid);
5) names of sailors who reserved no boats
select s.sname from sailors s where s.sid NOT IN(select r.sid from reserved r);
select s.sname from sailors s where NOT EXISTS ( select 1 from reserved r where r.sid =s.sid);

6) find names of sailors who reserved either red or green boat


select s.sname from sailors s , reserved r , boats b where s.sid=r.sid AND r.bid=b.bid AND color
IN(`red`,`green`);
select s.sname from sailors s JOIN reserved r ON r.sid=s.sid JOIN boats b ON r.bid=b.bid where
color IN(`red`,`green`);
select s.sname from sailors s where s.sid in (select r.sid from reserved r where r.bid in(select
b.bid from boats b where b.color in(`red`,`green`)));
select s.sname from sailors s where EXISTS ( Select 1 from reserved r JOIN boats b ON r.bid
=b.bid Where r.sid = s.sid AND b.color In (`red`,`green`));

7) find names of sailors who reserved both red and green boats

8) find names of sailors who reserved at least 2 boats ***


9) find sids of sailors with age over 20 and not reserved red boat
10) find sailor name, boat id and reservation day for each reservation
11) find sids of sailors who reserved red boat ***
12) find names of sailors who have reserved a red boat **
13) find ratings of the persons who have signed 2 different boats on the same day
14) find ages of the sailors whos name begins with b and ends with b and should contain atleast 3
characters
15) find names of sailors who reserved red boats but not green boats
16) find names of sailors who reserved whose rating is better then sailor called Horatio
17) find name ,age , rating of the sailor with highest rating
18) find names and age of sailors according to alphabetical order of the name with highest rating
19) find name and age of the oldest sailor
20) find names of sailors who are older then oldest sailor with rating 10
21) find the age of youngest sailor for each rating
22) for each red boat find no reservation for this boat
23) find average age of sailors at each rating level that has at least 2 sailors

Example 4:

Consider table EMP


Emp(empid integer(4) , empname String , Job String , MgrNo int(4) , salary Number(10,2) , comm
number(6,2) , DNO number(2))
1) Find names of the employees , whose salary is greater than there manager salary?
Select empname from emp1 from emp e1,emp e2 where e1.mgrno=e2.empid and
e1.salary>e2.salary;
2) Write the sql statements to swap all the f and m values (change all f values to m vise versa )
with single update statement and no intermediate
Note: do not write any select statement for this solution .

EXAMPLE 5 :

Consider following table schema


Country( name String , Continent String , area int , population int , gdp bigint )

1) A country is big if
1.it has an area of atleast 3 million sq.kms .
2. it has population of atleast 25 million .
Now write sql query to find name , population and area of big countries and result the
result in any order
2) Find name , population of big countries in order of highest to least area .

EXAMPLE 6 :

Consider 2 tables
Product(prod_id int , Category String , name String, Price Decimal)
Orders(ord_id int , prod_id int ,order_value decimal , order_date date)

1) Calculate the average order value for each category ?

SQL Queries Using With clause


The with clause defines a temporary relation and the definition of the relation , data related to relation is
available only to the query where we use “with” clause .
This concept is explained by using following examples .
EXAMPLE 1:

Instructor (Id char(5) , Name string , Dept_name string , Salary number(10))


Dept (dept_name string , location string , budget integer )
Student ( sid string , sname string , dept_name string , total_credits int )
Course ( cid string , title string , dept_name string , credits int )
Takes(sis String , cid string ,sec_id string , semester string , year int , grade char )
Teaches (id char(5) , cid string , sec_id string ,semester string , year int )

1) Find all the departments where the total salary is greater than the average of the total salary
of all departments .
With dept_total(dept_name ,value) as (select dept_name , sum(salary) from instructor group by
dept_name) , dept_total_avg(value) as (select avg(value) from dept_total ) select dept_name
from dept_total,dept_total_avg where dept_total.value > dept_total_avg.value;
2) Find all the departments whose budget same as maximum budget
Select dept_name from dept where budget = (select max(budget) from dept);
With dept_maxbudget(budget) as (select max(budget) from dept ) select dept_name from
dept , dept_maxbudget where dept.budget=dept_maxbudget.budget;
3) Find the names of all the instructors who have taught some course along with course id
Select I.name T.cid from instructor I Join teaches T On I.id=T.id;
4) Find the names of all the instructors in the dept who have taught same course .
select ( select I1.name from Instructor I1 where I1.id=T1.id ), (select I2.name from Instructor I2
where I2.id = T2.id ) from teaches T1 , Teaches T2 where T1.cid=T2.cid and T1.id<T2.id;
select I1.name as instructor1 , I2.name as Instructor2 , T1.cid from Teach T1 JOIN Teach T2 ON
t1.cid=T2.cid AND T1.cid <T2.cid JOIN Instructor I1 ON T1.id = I1.cid JOIN Instructor I1 ON T1.id
= I1.cid where I1.dept_name = T1.dept_name;
5) Find the names of all the instructors who have higher salary than some instructor in the
computer science department .
Select I.name from Instructor where salary > ANY (select salary from Instructor where
dept_name =`computer science`) And dept_name != `computer science ` ;
6) Find the names of all the instructors who have higher salary than all the instructors in the
computer science department .
Select I.name from Instructor where salary > ALL (select salary from Instructor where
dept_name =`computer science`) And dept_name != `computer science ` ;
7) Find the names of all instructors whose salary between 90000 and 150000 .
Select name from Instructor where salary between 90000 and 150000;
Select name from Instructor where salary >90000 and salary<150000
8) Find total no.of instructors who teach a course in spring 2010 semester (fall sem, spring sem) .
Select count(*) from instructor I Join Teaches T On I.id=T.id And T.semester=’spring’;
9) Find average salary of instructors in each department higher than average salary of all the
departments .
Select average(salary) as avg from instructor group by dept_name having avg >(select
average(salary) from instructors );
With
10) Find dept_name and average salary for each department where average salary should be
above 50000 .

11) Find names of all the courses offered in fall 2009 and spring 2010 .
12) Find names of all the courses offered in fall 2009 but not in spring 2010 .
13) Find all courses taught in both fall 2009 semester and spring 2010 semester .
14) Find all the students who have taken all the courses offered in the biology department .
15) Find titles of the courses that have 3 credits .
16) Find the id’s of all students , who were taught instructor named einstein .
[note : make sure that thee are no duplicates in the result ]
17) Find highest salary of instructor .
18) Find name of the instructors having highest salary among all
19) Find the enrollment of each section that was offerd In fall 2017 .
20) Find maximum enrollment across all sections in fall 2017 .
21) Find section id’s of all the sections having maximum enrollment In fall 2017 .

EXAMPLE 2:
Consider the following tables

Actors(AID int , name String )


Movies(MID int , title String )
Actor_role(MID int , AID int , rolename string)

1) Write a query to list all the movies in which actor “Charlie Champlin “ has acted along with
no.of roles he had played in that movie ?
select m.title , count(*) from movies m Join Actor_role ar ON m.mid=ar.aid JOIN Actors a ON
a.AID = ar.AID where a.name=`Charlie Champlin` group by m.title;
2) Write a query to list all the actors , who have not acted in any movie ?
select name from actors where Aid NOT IN(select AID from actor_role );
3) List names of the actors along with titles of movies they have acted in , if they have not
acted in any movie , show the movie title as null ?
Select a.name as actor , m.title as title from Actors a left Join Actor_role ar ON ar.AID=a.AID
left JOIN movies m ON ar.mid =m.mid ;

EXAMPLE 3:
Consider the following schema
Filghts Air_craft Certified emp
Flno int aid int eid int eid int
From string aname string aid int ename string
To string cruising_range int salary int
Distance int
Depart time
Arrive time
Price real
Aid int
Employees mean pilots and every pilots are certified, only those pilots certified for air crafts allowed to fly
1) Find the names of the air crafts such that all pilots are certified to them, more than 80000 salary?
SELECT ar.aname
FROM air_craft ar
WHERE NOT EXISTS (
SELECT *
FROM emp e
WHERE e.salary > 80000
AND NOT EXISTS (
SELECT *
FROM certified c
WHERE c.aid = ar.aid AND c.eid = e.eid
)
);
2) For each pilot, who is certified more than 3 aircrafts, find aid maximum cruising range aircraft for
which he/she certified?
Select
3) Find the names of the pilots whose salary is less than the price of the cheapest route from los
angeles to Honolulu?
4) For all the air craft with cruising range over thousand miles, find age of the air craft and average
salary of pilots certified for that aircraft.
5) Find the names of the pilots certified for some bowing air craft?
6) Find aid`s of all aircrafts that can be used on routes from los angeles to Chicago?
7) Identify the routes that can be piloted by every pilot, who makes more than 1lakh?
8) Print names of pilots, who can operate aircrafts with cruising range, greater than 3 thousand
miles, but are not certified on any bowing aircraft?
9) Compute the difference between average salary of pilots and average salary of all other
employees [note: only some employees are pilots in emp table]
10) Print name and salary of every non-pilot, whose salary is more than average salary of pilots?
11) Print names of the pilots who are certified only on aircrafts with cruising range more than 2000
miles?
12) Print names of pilots who are certified only on aircrafts with cruising range more than 2000 miles
and thee should be atleast 2 such air crafts?

EXAMPLE 3:
Consider the following tables
EMP(empid, firstname, lastname, deptid, salary, hiredate, managerid)
Orders(Orderid, empid, productid, quantity, orderdate)
Products(productid, productname, price, category)
1) Write a Query to rank employees, based on their salary within each department, display rank
also?
Select empid, firstname, lastname, deptid, salary, Rank() Over(partition by deptid order by salary
desc) from emp;
#dense_rank()
2) Retrieve the Cumulative sales for each product (totalrevenue=sum of quantity*price)?
select orderid,productid,quantity,sum(quantity) Over(partition by productid order by orderdate) as
cumulative_sales from orders;
3) Identify the department with highest salary expenditure?
select deptid , sum(salary) as salary_expenditure from emp group by deptid order by
salary_expenditure desc limit 1;
4) Identify the products that have not been ordered?
select p.productid from products p where NOT EXISTS (select * from orders o where
p.productid=o.productid);
5) Find employees, who have same manager and earn more than 70000?
select firstname,salary,managerid from emp where salary>70000 and managerid in (select
managerid from emp group by managerid having count(*)>1);
6) Write a query to detect duplicate rows in the orders table, display only those duplicate rows?
select * from orders group by orderid having count(*)>1;
select * from orders where productid in(select productid from orders group by productid having
count(*)>1);
7) Fetch the details of orders placed on same day by multiple employees?
select * from orders where orderdate in(select orderdate from orders group by orderdate having
count(distinct empid)>1);

8) Write a query, to fetch the employees, whose total order quantity is between 50 and 100?
9) Fetch the 2nd highest quantity for each product?
10) Find the minimum and maximum ordered quantities for each employee?
11) Write a query to split employee salaries into quartiles? (entile function)
12) Create a temporary table for orders, with revenue greater than 5000. Revenue means
quantity*price?
13) Fetch the names of employees, who have placed more than 10 orders?
14) Write a Query to create a view, that shows employee names and department names?
15) List the departments with no employees assigned?
16) Find 2nd & 3rd highest salary from employee table?
17) Write a query to fetch total revenue generated by each employee?
18) Find the employees who joined the company as the same year as their manager?
19) Display details of products for which total sales exceed 10000?
20) Display names of all employees along with total no. of orders have handled?
21) Write a query to fetch the details of most recently hired employees?
22) Find the names of employees who have not placed any order?
23) Display top 3 products with highest total quantity sold? (sum of quantity)
24) Display names of the employees earning more than the average salary?
25) Find the no. of employees hired each year?
26) Find total quantity of products ordered for each product?
27) Display details of top 3 highest paid employees?
28) Find employees who do not have manager?
29) Find the average product price for each category?
30) Display id of the department, which has total highest salary among all departments?
31) Find last day of next month using SQL(general query)?

INTERVIEW QUESTIONS
1) What is meta data ?
 Meta data means data about data , that means information about the data base tables , also stored
as data in database .
 That means the information about the structure of the tables , the information about user using
tables , the information about physical disk where tables are permanently placed also stored as data
in database . this is called meta data .
 In DBMS software , there is a built in table called universal table or tab .
 When ever we create a new tables , we modify the existing tables , we create a new users . Then the
structure of new tables , the structure of new users again stores in built in table is called meta data .
 The built-in table ( Where we store Meta data ) is called system catalog or data dictionary .And the
record in the built-in table is meta data .
2) How many types of meta Data , we have in data Database ?
 The following are the types of the meta data :
 Structural metadata : it related to the schema like table name , no.of columns ,column names ,
datatypes , size of each column , primary key and foreign key and relations between each table .
 Descriptive meta data : It is related to purpose of the database content , Generally it is placed in
comments use full for search engines , it is just a collection of keywords .
 Administrative meta data : it includes data ownership , access permissions , creation data and
modification history .
 Technical metadata : It includes storage locations , file name , file size and indexing methods .
 ISAM : Indexed sequential Access method

3) Views in database: A view is an important database objects in DBMS Environment too manage data
in database.
 Generally, we use tables to store and manage data.
 When we perform data manipulation operations tables are primary database objects also called
base tables.
 Some times in addition to tables we use views for storing and managing the data views are
secondary database objects.
 A view is created from existing table (Without Base table Views cannot be created).
 A view is a virtual table or temporary table created based on the SQL query.
 That means we define SQL query and save it. when ever this query is executed, it extracts data
from another base table places in a temporary memory.
 Now onwards this temporary memory acts as a table. On this Temporary memory we can insert
records, we can delete records and we can update records just like any table. Thus, view is a
permanent query acts as a table.
4) Uses of views:
 In a client-server network environment, we can central database in a server which is accessed by
multiple concurrent users at a time from different client computer systems performing different
database operations.
 In the environment sometimes multiple users executing multiple programs, performing
operations on same database table.
 In such a case the execution of programs becomes slow means performance decreases.
 Now, to avoid this problem and increase the performance, we can use views, there for a base
table different views are created. Some users performing database operations on base table,
and some users on different views. Because, on this load on database table is reduced and
balanced.
 VIEWS are useful for data access control.
 View does not occupy any Physical disk space, but occupies RAM.
5) What is Synonym in Database?
 It is another database object, created from base table.
 It is also Secondary database object.
 It is like a view and used for implementing the same benefits as view. it is also a permanent
query. But it has separate disk space.
6) CODD’S RULES?
 Initially, we have DBMS and database is created using DBMS. It has some problems and issues to
overcome those problems E.F. CODD designed 12 rules and proposed every database must
satisfy these 12 rules. when data base satisfies these 12 rules this is called RDBMS.
 That 12 rules are (13 rules).
 RULE 0: FOUNDATION RULE: THE DATA BASE SYSTEM MUST MANAGE THE DATA ENTIRELY TO
RELATION.
 RULE 1: INFORMATION RULE: ALL DATA INCLUDING META DATA MUST BE STORED AS DATA
RECORDS IN DATA BASE.
 RULE 2: RULE OF GAURNTED ACCESS: EVERY PIECE OF DATA, MUST BE ACCESSED BY USER
USING COMBINATION OF COLUMN NAMES, TABLE NAMES AND PRIMARY KEY.
 RULE 3: SYSTEMATIC TREATMENT OF NULL VALUES: IF ANY DATA IS NOT AVALIABLE AT THE
TIME OF STORAGE, THAT SHOULD BE TREATED AS NULL VALUE. [NULL MEANS IS UNKNOWN
DATA IT IS NOT INT OR STRING].
 RULE 4: DYNAMIC ONLINE CATALOG: THIS RULE SAYS THAT META DATA SHOULD BE STORED
AND ACCESSBLE LIKE REGULAR DATA AND IT IN A SEPARATE BUILT-IN TABLES.
 RULE 5: COMPHRAHENSIVE DATA: THIS RULE STATES THAT THAT A SEPARATE SUBLANGUAGE
MUST BE AVAILABLE
i. DATA RETRIVAL.
ii. TRANSACTION MANAGEMENT.
iii. DATA ACCESS CONTROL.
iv. DATA MANIPULATION.
v. DATA DEFINITION
 RULE 6: VIEW UPDATION RULE: VIEWS MUST BE SUPPORT UPDATION OPERATIONS (CHANGING
OF DATA THROUGH VIEW SHOULD BE POSSIBLE)
 RULE 7: HIGH LEVEL INSERT, UPDATE AND DELETE: According to this rule data manipulation
operations insert update delete should support sets of roles not just single row.
 RULE 8: PHYSICAL DATA INDEPENDENCE: Changes to physical storage of data (changing indexing
methods, increasing disk space, changing disk configuration etc..), should not requires changes
to application program. (Application programs are logical data structure)
 RULE 9: LOGICAL DATA INDEPENDENCE: changes to logical structure of database should not
require changes to physical storage.
 RULE 10: INTEGRITY INDEPENCE RULE: Integrity (correctness and completeness) constraints
should be defined and stored in database.
 RULE 11: DISTRIBUTION INDEPENDENCE RULE: It should be transparent to end users whether
database should be centralised (One server in database and all connected to that database) or
distributed (no. of databases in multiple servers and multiple users access multiple servers).
 RULE 12: NON-SUBVERSION RULE: the system should not access to data, that bypasses the
integrity constraints.
7) Data Storage and Model Evolution ?
 First File Systems :
o Initial storage involved saving file records directly to memory and then to disk.
o These systems helped reduce application development time but did not support
relational or mathematical operations using simple commands.
o All data handling and querying had to be done via custom procedural code.
 Evolution of Data Models:
o File System Model: A basic, hierarchical structure for storing files. Examples include base
files and systems like FoxPro (FoxBase, FoxPro for DOS/Windows).
o Hierarchical Model: Data organized in a tree-like structure (parent-child relationships).
Navigating relationships was complex and rigid.
o Network Model: Improved flexibility over the hierarchical model using graph-based
structures to represent more complex relationships.
Examples: Informix, Ingres—some early systems stored graphs in memory for faster
access.
o Relational Model: Introduced by E.F. Codd, this model uses tables (relations) with rows
and columns.
Supports powerful querying with SQL, allowing relational and mathematical operations
easily.
o Object-Relational (OR) Model (Recent Advancement)
 Combines features of object-oriented programming with relational databases.
 Supports complex data types (e.g., multimedia, user-defined types).
 Supported in Oracle 8 and later, PostgreSQL, and other advanced DBMSs.
 Useful for modern applications involving rich and hierarchical data structures.

8) What is the difference between sub query and correlated sub query ?
 In case of sub query first inner most query is executed and their results are buffer , and by
comparing those results from buffer , outer most queries are executed
 Incase of a correlated sub query the inner query and outer query executes parallel to each other
, the inner query starts execution a fraction of time in advance , the inner query produces
result , the outer query compares those records one by one and executes parallel . this is
multithreading in Querying.

9) What is Dynamic SQL?


 Dynamic SQL is a programming technique that allows you to construct and execute SQL
statements at runtime, rather than hardcoding them in advance.
 Use of Prepared statement in JDBC is called dynamic SQL .
10) What do you mean by cursor?
 In JDBC the ResultSet is a cursor . A cursor or pointer to a table-like structure in memory that
contains the rows returned from a database query.
 In JDBC (Java Database Connectivity), a ResultSet is an object that holds the data returned by a
SQL query, typically a SELECT statement.
11) What is the relation between xml and database?
12) What is denormalization?
13) What is intension and extension in database?

You might also like