0% found this document useful (0 votes)
104 views

Some Important SQL+DBMS

The document provides 43 SQL queries with explanations. The queries cover a wide range of SQL functions and operations including selecting, filtering, aggregating, joining, ordering data as well as more advanced concepts like ranking, top n queries, unions and more. The queries are designed to test understanding of core SQL as well as more complex queries.

Uploaded by

Saloni Jain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Some Important SQL+DBMS

The document provides 43 SQL queries with explanations. The queries cover a wide range of SQL functions and operations including selecting, filtering, aggregating, joining, ordering data as well as more advanced concepts like ranking, top n queries, unions and more. The queries are designed to test understanding of core SQL as well as more complex queries.

Uploaded by

Saloni Jain
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Some Important SQL Queries

Q-1. Write an SQL query to fetch “FIRST_NAME” from Worker table


using the alias name as <WORKER_NAME>.

Ans.
The required query is:

Select FIRST_NAME AS WORKER_NAME from Worker;

Q-2. Write an SQL query to fetch “FIRST_NAME” from Worker table in


upper case.

Ans.
The required query is:

Select upper(FIRST_NAME) from Worker;

Q-3. Write an SQL query to fetch unique values of DEPARTMENT from


Worker table.

Ans.
The required query is:

Select distinct DEPARTMENT from Worker;

Q-4. Write an SQL query to print the first three characters of 
FIRST_NAME from Worker table.

Ans.
The required query is:

Select substring(FIRST_NAME,1,3) from Worker;

Q-5. Write an SQL query to find the position of the alphabet (‘a’) in the
first name column ‘Amitabh’ from Worker table.

Ans.
The required query is:
Select INSTR(FIRST_NAME, BINARY'a') from Worker where
FIRST_NAME = 'Amitabh';

Notes.
 The INSTR method is in case-sensitive by default.
 Using Binary operator will make INSTR work as the case-sensitive function.
 

Q-6. Write an SQL query to print the FIRST_NAME from Worker table
after removing white spaces from the right side.

Ans.
The required query is:

Select RTRIM(FIRST_NAME) from Worker;

Q-7. Write an SQL query to print the DEPARTMENT from Worker table
after removing white spaces from the left side.

Ans.
The required query is:

Select LTRIM(DEPARTMENT) from Worker;

Q-8. Write an SQL query that fetches the unique values of


DEPARTMENT from Worker table and prints its length.

Ans.
The required query is:

Select distinct length(DEPARTMENT) from Worker;

Q-9. Write an SQL query to print the FIRST_NAME from Worker table
after replacing ‘a’ with ‘A’.

Ans.
The required query is:

Select REPLACE(FIRST_NAME,'a','A') from Worker;

 
Q-10. Write an SQL query to print the FIRST_NAME and LAST_NAME
from Worker table into a single column COMPLETE_NAME. A space
char should separate them.

Ans.
The required query is:

Select CONCAT(FIRST_NAME, ' ', LAST_NAME) AS 'COMPLETE_NAME'


from Worker;

Q-11. Write an SQL query to print all Worker details from the Worker
table order by FIRST_NAME Ascending.

Ans.
The required query is:

Select * from Worker order by FIRST_NAME asc;

Q-12. Write an SQL query to print all Worker details from the Worker
table order by FIRST_NAME Ascending and DEPARTMENT
Descending.

Ans.
The required query is:

Select * from Worker order by FIRST_NAME asc,DEPARTMENT desc;

Q-13. Write an SQL query to print details for Workers with the first
name as “Vipul” and “Satish” from Worker table.

Ans.
The required query is:

Select * from Worker where FIRST_NAME in ('Vipul','Satish');

Q-14. Write an SQL query to print details of workers excluding first


names, “Vipul” and “Satish” from Worker table.

Ans.
The required query is:
Select * from Worker where FIRST_NAME not in
('Vipul','Satish');

Q-15. Write an SQL query to print details of Workers with


DEPARTMENT name as “Admin”.

Ans.
The required query is:

Select * from Worker where DEPARTMENT like 'Admin%';

Q-16. Write an SQL query to print details of the Workers whose


FIRST_NAME contains ‘a’.

Ans.
The required query is:

Select * from Worker where FIRST_NAME like '%a%';

Q-17. Write an SQL query to print details of the Workers whose


FIRST_NAME ends with ‘a’.

Ans.
The required query is:

Select * from Worker where FIRST_NAME like '%a';

Q-18. Write an SQL query to print details of the Workers whose


FIRST_NAME ends with ‘h’ and contains six alphabets.

Ans.
The required query is:

Select * from Worker where FIRST_NAME like '_____h';

Q-19. Write an SQL query to print details of the Workers whose


SALARY lies between 100000 and 500000.
Ans.
The required query is:

Select * from Worker where SALARY between 100000 and 500000;

Q-20. Write an SQL query to print details of the Workers who have
joined in Feb’2014.

Ans.
The required query is:

Select * from Worker where year(JOINING_DATE) = 2014 and


month(JOINING_DATE) = 2;

Q-21. Write an SQL query to fetch the count of employees working in


the department ‘Admin’.

Ans.
The required query is:

SELECT COUNT(*) FROM worker WHERE DEPARTMENT = 'Admin';

Q-22. Write an SQL query to fetch worker names with salaries >= 50000
and <= 100000.

Ans.
The required query is:

SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) As Worker_Name,


Salary

FROM worker

WHERE WORKER_ID IN

(SELECT WORKER_ID FROM worker

WHERE Salary BETWEEN 50000 AND 100000);

Q-23. Write an SQL query to fetch the no. of workers for each
department in the descending order.
Ans.
The required query is:

SELECT DEPARTMENT, count(WORKER_ID) No_Of_Workers

FROM worker

GROUP BY DEPARTMENT

ORDER BY No_Of_Workers DESC;

Q-24. Write an SQL query to print details of the Workers who are also
Managers.

Ans.
The required query is:

SELECT DISTINCT W.FIRST_NAME, T.WORKER_TITLE

FROM Worker W

INNER JOIN Title T

ON W.WORKER_ID = T.WORKER_REF_ID

AND T.WORKER_TITLE in ('Manager');

Q-25. Write an SQL query to fetch duplicate records having matching


data in some fields of a table.

Ans.
The required query is:

SELECT WORKER_TITLE, AFFECTED_FROM, COUNT(*)

FROM Title

GROUP BY WORKER_TITLE, AFFECTED_FROM

HAVING COUNT(*) > 1;

Q-26. Write an SQL query to show only odd rows from a table.

Ans.
The required query is:
SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) <> 0;

Q-27. Write an SQL query to show only even rows from a table.

Ans.
The required query is:

SELECT * FROM Worker WHERE MOD (WORKER_ID, 2) = 0;

Q-28. Write an SQL query to clone a new table from another table.

Ans.
The general query to clone a table with data is:

SELECT * INTO WorkerClone FROM Worker;

The general way to clone a table without information is:

SELECT * INTO WorkerClone FROM Worker WHERE 1 = 0;

An alternate way to clone a table (for MySQL) without is:

CREATE TABLE WorkerClone LIKE Worker;

Q-29. Write an SQL query to fetch intersecting records of two tables.

Ans.
The required query is:

(SELECT * FROM Worker)

INTERSECT

(SELECT * FROM WorkerClone);

Q-30. Write an SQL query to show records from one table that another
table does not have.

Ans.
The required query is:

SELECT * FROM Worker


MINUS

SELECT * FROM Title;

Q-31. Write an SQL query to show the current date and time.

Ans.
Following MySQL query returns the current date:

SELECT CURDATE();

Following MySQL query returns the current date and time:

SELECT NOW();

Following SQL Server query returns the current date and time:

SELECT getdate();

Following Oracle query returns the current date and time:

SELECT SYSDATE FROM DUAL;

Q-32. Write an SQL query to show the top n (say 10) records of a table.

Ans.
Following MySQL query will return the top n records using the LIMIT method:

SELECT * FROM Worker ORDER BY Salary DESC LIMIT 10;

Following SQL Server query will return the top n records using the TOP command:

SELECT TOP 10 * FROM Worker ORDER BY Salary DESC;

Following Oracle query will return the top n records with the help of ROWNUM:

SELECT * FROM (SELECT * FROM Worker ORDER BY Salary DESC)

WHERE ROWNUM <= 10;

Q-33. Write an SQL query to determine the nth (say n=5) highest salary
from a table.
Ans.
The following MySQL query returns the nth highest salary:

SELECT Salary FROM Worker ORDER BY Salary DESC LIMIT n-1,1;

The following SQL Server query returns the nth highest salary:

SELECT TOP 1 Salary

FROM (

SELECT DISTINCT TOP n Salary

FROM Worker

ORDER BY Salary DESC

ORDER BY Salary ASC;

Q-34. Write an SQL query to determine the 5th highest salary without
using TOP or limit method.

Ans.
The following query is using the correlated subquery to return the 5th highest salary:

SELECT Salary

FROM Worker W1

WHERE 4 = (

SELECT COUNT( DISTINCT ( W2.Salary ) )

FROM Worker W2

WHERE W2.Salary >= W1.Salary

);

Use the following generic method to find nth highest salary without using TOP or limit.

SELECT Salary

FROM Worker W1
WHERE n-1 = (

SELECT COUNT( DISTINCT ( W2.Salary ) )

FROM Worker W2

WHERE W2.Salary >= W1.Salary

);

Q-35. Write an SQL query to fetch the list of employees with the same
salary.

Ans.
The required query is:

Select distinct W.WORKER_ID, W.FIRST_NAME, W.Salary

from Worker W, Worker W1

where W.Salary = W1.Salary

and W.WORKER_ID != W1.WORKER_ID;

Q-36. Write an SQL query to show the second highest salary from a
table.

Ans.
The required query is:

Select max(Salary) from Worker

where Salary not in (Select max(Salary) from Worker);

Q-37. Write an SQL query to show one row twice in results from a
table.

Ans.
The required query is:

select FIRST_NAME, DEPARTMENT from worker W where


W.DEPARTMENT='HR'
union all

select FIRST_NAME, DEPARTMENT from Worker W1 where


W1.DEPARTMENT='HR';

Q-38. Write an SQL query to fetch intersecting records of two tables.

Ans.
The required query is:

(SELECT * FROM Worker)

INTERSECT

(SELECT * FROM WorkerClone);

Q-39. Write an SQL query to fetch the first 50% records from a table.

Ans.
The required query is:

SELECT *

FROM WORKER

WHERE WORKER_ID <= (SELECT count(WORKER_ID)/2 from Worker);

Q-40. Write an SQL query to fetch the departments that have less than
five people in it.

Ans.
The required query is:

SELECT DEPARTMENT, COUNT(WORKER_ID) as 'Number of Workers'


FROM Worker GROUP BY DEPARTMENT HAVING COUNT(WORKER_ID) < 5;

Q-41. Write an SQL query to show all departments along with the
number of people in there.

Ans.
The following query returns the expected result:

SELECT DEPARTMENT, COUNT(DEPARTMENT) as 'Number of Workers'


FROM Worker GROUP BY DEPARTMENT;

Q-42. Write an SQL query to show the last record from a table.

Ans.
The following query will return the last record from the Worker table:

Select * from Worker where WORKER_ID = (SELECT max(WORKER_ID)


from Worker);

Q-43. Write an SQL query to fetch the first row of a table.

Ans.
The required query is:

Select * from Worker where WORKER_ID = (SELECT min(WORKER_ID)


from Worker);

Q-44. Write an SQL query to fetch the last five records from a table.

Ans.
The required query is:

SELECT * FROM Worker WHERE WORKER_ID <=5

UNION

SELECT * FROM (SELECT * FROM Worker W order by W.WORKER_ID


DESC) AS W1 WHERE W1.WORKER_ID <=5;

Q-45. Write an SQL query to print the name of employees having the
highest salary in each department.

Ans.
The required query is:
SELECT t.DEPARTMENT,t.FIRST_NAME,t.Salary from(SELECT
max(Salary) as TotalSalary,DEPARTMENT from Worker group by
DEPARTMENT) as TempNew

Inner Join Worker t on TempNew.DEPARTMENT=t.DEPARTMENT

and TempNew.TotalSalary=t.Salary;

Q-46. Write an SQL query to fetch three max salaries from a table.

Ans.
The required query is:

SELECT distinct Salary from worker a WHERE 3 >= (SELECT


count(distinct Salary) from worker b WHERE a.Salary <=
b.Salary) order by a.Salary desc;

Q-47. Write an SQL query to fetch three min salaries from a table.

Ans.
The required query is:

SELECT distinct Salary from worker a WHERE 3 >= (SELECT


count(distinct Salary) from worker b WHERE a.Salary >=
b.Salary) order by a.Salary desc;

Q-48. Write an SQL query to fetch nth max salaries from a table.

Ans.
The required query is:

SELECT distinct Salary from worker a WHERE n >= (SELECT


count(distinct Salary) from worker b WHERE a.Salary <=
b.Salary) order by a.Salary desc;

Q-49. Write an SQL query to fetch departments along with the total
salaries paid for each of them.

Ans.
The required query is:
 SELECT DEPARTMENT, sum(Salary) from worker group by
DEPARTMENT;

Q-50. Write an SQL query to fetch the names of workers who earn the
highest salary.

Ans.
The required query is:

SELECT FIRST_NAME, SALARY from Worker WHERE SALARY=(SELECT


max(SALARY) from Worker);

SELECT Email FROM EmployeeInfo WHERE NOT REGEXP_LIKE(Email,


‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);

DBMS Theory

1. What is DBMS? Mention advantages.

Database Management System (DBMS) is a software for storing and retrieving users' data
while considering appropriate security measures. Database Management System is a
software application used to access, create, and manage databases.
Advantages:
 Data Integrity
 Data Security
 Better data integration
 Minimized Data Inconsistency
 Faster Data Access

2. ‌What is Database?
A database is an organized collection of data, so that it can be easily accessed,
managed and updated.

3. ‌What is a database system?


Together, the data and the DBMS, along with the applications that are associated with
them, are referred to as a database system, often shortened to just database.
4. ‌What is RDBMS? Properties.
A Relational database management system (RDBMS) is a database management system
(DBMS) that is based on the relational model.
Properties of relational databases
 Values are atomic.
 All of the values in a column have the same data type.
 Each row is unique.
 The sequence of columns is insignificant.
 The sequence of rows is insignificant.
 Each column has a unique name.
 Integrity constraints maintain data consistency across multiple tables.

5. ‌Types of database languages: DDL, DML, DCL, TCL, DQL

6. ‌ACID properties (VVVVV IMP)

7. ‌Difference between vertical and horizontal scaling


 Scaling alters size of a system. In the scaling process, we either compress or
expand the system to meet the expected needs.
 Vertical Scaling: When new resources are added in the existing system to meet
the expectation, it is known as vertical scaling.
 Horizontal Scaling: When new server racks are added in the existing system to
meet the higher expectation, it is known as horizontal scaling.
8. ‌What is sharding
The word “Shard” means “a small part of a whole“. Hence Sharding means dividing a
larger part into smaller parts.
In DBMS, Sharding is a type of DataBase partitioning in which a large DataBase is
divided or partitioned into smaller data, also known as shards. These shards are not
only smaller, but also faster and hence easily manageable.

9. ‌Keys in DBMS: SK, CK, PK, FK


10. ‌Types of relationship: 1:1,1:N,N:1,N:N
11. ‌Data abstraction in DBMS, three levels of it

 Database systems comprise complex data-structures. In order to make the


system efficient in terms of retrieval of data, and reduce complexity in terms
of usability of users, developers use abstraction i.e. hide irrelevant details
from the users. This approach simplifies database design. 
There are mainly 3 levels of data abstraction: 
 Physical: This is the lowest level of data abstraction. It tells us how the data
is actually stored in memory. 
 Logical: This level comprises the information that is actually stored in the
database in the form of tables. It also stores the relationship among the data
entities in relatively simple structures.
 View: This is the highest level of abstraction. Only a part of the actual
database is viewed by the users. This level exists to ease the accessibility of
the database by an individual user. Users view data in the form of rows and
columns. Tables and relations are used to store data. Multiple views of the
same database may exist. Users can just view the data and interact with the
database, storage and implementation details are hidden from them. 

12. ‌Indexing in DBMS


Indexing is a way to optimize the performance of a database by minimizing the
number of disk accesses required when a query is processed. It is a data structure
technique which is used to quickly locate and access the data in a database.
13. ‌What is DDL (Data Definition Language)
DDL or Data Definition Language actually consists of the SQL commands that can
be used to define the database schema. It simply deals with descriptions of the
database schema and is used to create and modify the structure of database objects
in the database. 

14. ‌What is DML (Data Manipulation Language)


The SQL commands that deal with the manipulation of data present in the database
belong to DML or Data Manipulation Language and this includes most of the SQL
statements. 

15. ‌What is normalization? Types of them.


Normalization is a database optimization technique that helps to reduce redundancy
and eliminate undesired characteristics like insertion, deletion and update anomalies
from the database. Its types are – 1NF, 2NF, 3NF, BCNF(3.5NF)

16. ‌What is denormalization?


Denormalization is a database optimization technique in which we add redundant data
to one or more tables. This can help us avoid costly joins in a relational database. 

17. ‌What is functional dependency?


A functional dependency is a constraint that specifies the relationship between two
sets of attributes where one set can accurately determine the value of other sets.

18. ‌E-R Model?


ER Model is used to model the logical view of the system from data perspective. It
describes the structure of a database with the help of a diagram. It is a design or
blueprint of a database that can later be implemented as a database. 

19. ‌Conflict Serializability in DBMS.


A schedule is called conflict serializable if it can be transformed into a serial schedule
by swapping non-conflicting operations.

20. ‌Explain Normal forms in DBMS: same as question 15


21. ‌What is CCP? (Concurrency Control Protocols)
Concurrency Control Protocols in Database Management System manage
simultaneous operations without conflicting with each other. They ensure that
Database transactions are performed concurrently and accurately to produce correct
results without violating data integrity of the respective Database.

22. ‌Entity, Entity Type, Entity Set, Weak Entity Set.


 An Entity may be an object with a physical existence.
 An Entity is an object of Entity Type and set of all entities is called as entity
set.
 An entity that cannot be uniquely identified by its own attributes and relies on
the relationship with other entity is called weak entity. 
 A weak entity set is an entity set that does not contain sufficient attributes to
uniquely identify its entities. In other words, a primary key does not exist for
a weak entity set.
23. ‌What are SQL commands? Types of them.

SQL commands are the instructions used to communicate with a database to perform


tasks, functions, and queries with data. 
Types- DDL, DML, TCL, embedded etc

24. ‌Nested Queries in SQL?


 In nested queries, a query is written inside a query. The result of inner query is
used in execution of outer query. 
There are mainly two types of nested queries:
 Independent Nested Queries: In independent nested queries, query execution
starts from innermost query to outermost queries. The execution of inner query
is independent of outer query, but the result of inner query is used in execution
of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in
writing independent nested queries.
 Co-related Nested Queries: In co-related nested queries, the output of inner
query depends on the row which is being currently executed in outer query.

25. ‌What is JOIN. Explain types of JOINs


In DBMS, a join statement is mainly used to combine two tables based on a specified
common field between them.
Different types of Joins are:
 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL JOIN

26. ‌Inner and Outer Join


 The major difference between inner and outer joins is that inner joins result in
the intersection of two tables, whereas outer joins result in the union of two
tables.
 Inner join is an operation that returns a combined tuples between two or more
tables where at least one attribute in common. If there is no attribute in
common between tables then it will return nothing.
 Outer join is an operation that returns a combined tuples from a specified table
even the join condition will fail.
27. ‌Diff between 2 tier and 3 tier architectures
 A 2 Tier Architecture in DBMS is a Database architecture where the
presentation layer runs on a client (PC, Mobile, Tablet, etc.), and data is stored
on a server called the second tier. Two tier architecture provides added
security to the DBMS as it is not exposed to the end-user directly. It also
provides direct and faster communication.

 A 3 Tier Architecture in DBMS is the most popular client server architecture
in DBMS in which the development and maintenance of functional processes,
logic, data access, data storage, and user interface is done independently as
separate modules. Three Tier architecture contains a presentation layer(client-
PC, mobile), an application layer(server), and a database server.
28. ‌Difference between TRUNCATE and DELETE
S.NO Delete Truncate
1. The DELETE command is used While this command is used to delete all
to delete specified rows(one or the rows from a table.
more).
2. It is a DML(Data Manipulation While it is a DDL(Data Definition
Language) command. Language) command.
3. There may be WHERE clause in While there may not be WHERE clause
DELETE command in order to in TRUNCATE command.
filter the records.
4. In the DELETE command, a While in this command, data page is
tuple is locked before removing locked before removing the table data.
it.
5. The DELETE statement TRUNCATE TABLE removes the data
removes rows one at a time and by deallocating the data pages used to
records an entry in the store the table data and records only the
transaction log for each deleted page deallocations in the transaction
row. log.
6. DELETE command is slower While TRUNCATE command is faster
than TRUNCATE command. than DELETE command.
7. The delete can be used with Truncate cannot be used with indexed
indexed views. views.

29. ‌Difference between Intension and Extension in a Database


 Intension is the permanent part of the relation and comprises of two things: relation
schema and the integrity constraints. Relation schema defines the name and attributes
of the relation, and integrity constraints define key constraints, referential constraints.
etc. As it corresponds to the schema of the relation, it provides definition to all the
extensions of the relation and is time independent.
 Extension is the snapshot of the system at a particular time. It displays values for
tuples in a relation at the particular instance of time . It is dependent on time and it
keeps on changing as the tuples are added, deleted, edited.

30. ‌Difference between share lock and exclusive lock, definition of lock.
 A lock is a data variable which is associated with a data item. This lock
signifies what operations that can be performed on the data item. Locks in
DBMS help synchronize access to the database items by concurrent
transactions.
 A shared lock is also called a Read-only lock. With the shared lock, the data
item can be shared between transactions. This is because you will never have
permission to update data on the data item.
 With the Exclusive Lock, a data item can be read as well as written. This is
exclusive and can't be held concurrently on the same data item. Transactions
may unlock the data item after finishing the 'write' operation.

You might also like