0% found this document useful (0 votes)
22 views73 pages

DBMS Basics: Key Concepts Explained

The document provides a comprehensive overview of Database Management Systems (DBMS), including definitions of key concepts such as data, information, databases, and database systems. It discusses advantages of DBMS, issues like data redundancy and inconsistency, and various database languages and operations. Additionally, it covers normalization, data abstraction, and relationships within databases, along with their types and constraints.

Uploaded by

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

DBMS Basics: Key Concepts Explained

The document provides a comprehensive overview of Database Management Systems (DBMS), including definitions of key concepts such as data, information, databases, and database systems. It discusses advantages of DBMS, issues like data redundancy and inconsistency, and various database languages and operations. Additionally, it covers normalization, data abstraction, and relationships within databases, along with their types and constraints.

Uploaded by

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

SQL

DBMS Interview Question(Basics)

1. What is DBMS?

⇒ DBMS stands for Database Management System. DBMS provides us with an


interface or tool for performing different operations such as creating a database,
inserting data, deleting data from it, updating it, etc. DBMS is software in which
data is stored in a more secure way as compared to the file-based system. Using
DBMS, we can overcome many problems such as data redundancy, data
inconsistency, easy access, more organization and understanding, and so on.
There are the names of some popular Database Management Systems- MySQL,
Oracle, SQL Server, Amazon simple DB (Cloud-based), etc.

2. What is data?
⇒ Data is the collection of Information. Raw and isolated facts about an entity
are called data. Like text data, photos, audio, video, etc.

3. What is information?
⇒ Information is processed, meaningful usable data.

SQL 1
if the Book is data the assignments which we took from those books are called
information.

4. What is a Database?
⇒ Collection of similar or related data is called a Database. A Database is a
logical, consistent, and organized collection of data that can easily be
accessed, managed, and updated.
like: if the video is data then YouTube is the database. same if photos are data
then Google Photos is the database.

5. What is a database system?



The collection of database and DBMS software together is known as a
database system. Through the database system, we can perform many
activities as the data can be stored in the database with ease, and there are no
issues of data redundancy and data inconsistency. The data will be extracted
from the database using DBMS software whenever required. So, the
combination of database and DBMS software enables one to store, retrieve,
and access data with considerate accuracy and security.

6. What are the advantages of DBMS?



• Redundancy control
• Provides multiple user interfaces
• Provides backup and recovery
• Ensure data consistency

7. Data redundancy.
⇒ Redundancy in DBMS is the problem that arises when the database is not
normalized. It is the concept of storing multiple copies of the same data in
different parts of the database.

SQL 2
[Link]

Normalization: X_noem=(x-x_min)/(x_max-x_min)

8. Data Inconsistency

When the same data exists in different formats in multiple tables. This condition
is known as Data Inconsistency. It means that different files contain different
information about a particular object or person. This can cause unreliable and
meaningless information. Data Redundancy leads to Data Inconsistency.

Example – If we have an address of someone in many tables and when we


change it in only one table and in another table it may not be updated so there
is the problem of data inconsistency.

9. Difference between Data Redundancy and Data Inconsistency


SQL 3
[Link]
data-inconsistency/

10. What is a checkpoint?


⇒ The Checkpoint is a type of mechanism where all the previous logs are
removed from the system and permanently stored in the storage disk. If a
system crashes after a minimal point is called a checkpoint. A checkpoint is
used for recovery of the database if the system crashes.
1. It helps with the processing time, and it reduces the transaction time for
failure.
2. It reduces unnecessary transactions.
example: If an error occurs while the movie downloading, the download starts
from the checkpoint onwards, The salary distribution system.

In transactions, it helps a lot. (Redo, Undo list).

11. What do you mean by transparent DBMS?



The transparent DBMS is a type of DBMS that keeps its physical structure
hidden from users. it describes how the data is stored on disk.

12. What are the unary operations in Relational Algebra?



PROJECTION and SELECTION are the unary operations in relational algebra.
Unary operations are those operations that use single operands. Unary
operations are SELECTION, PROJECTION, and RENAME.
As in SELECTION relational operators are used for example - =,<=,>=, etc.

13. What are the database languages?

1. DDL⇒

SQL 4
Data Definition Language (DDL) is a set of special commands that allows us to
define and modify the structure and the metadata of the database. These
commands can be used to create, modify, and delete the database structures
such as schema, tables, indexes, etc. eg:
Create, Drop, Alter, Truncate, Rename.

2. DML⇒ Data Manipulation Language (DML) is a set of special commands that


allows us to access and manipulate data stored in existing schema objects.
These commands are used to perform certain operations such as insertion,
deletion, updation, and retrieval of the data from the database. eg: Select,
Update, Delete, Insert.

3. Data Control Language⇒

DCL stands for Data Control Language. It is used to retrieve stored or saved
data.

The DCL execution is transactional. It also has rollback parameters.

(But in the Oracle database, the execution of data control language does not have
the feature of rolling back.)
Here are some tasks that come under DCL:

Grant: It is used to give user access privileges to a database.

Revoke: It is used to take back permissions from the user.

4.

Transaction Control Language


TCL is used to run the changes made by the DML statement. TCL can be grouped
into logical transactions.
Here are some tasks that come under TCL:

Commit: It is used to save the transaction on the database.

Rollback: It is used to restore the database to the original since the last
Commit.

Savepoint: Used to rollback up to a point, not the whole program rollbacked.

SQL 5
[Link]

[Link]

1. What do you understand by Data Model?



The Data model is specified as a collection of conceptual tools for describing
data, data relationships, data semantics, and constraints. These models are
used to describe the relationship between the entities and their attributes.
the types of data models are:

• Hierarchical data model.


• Network model.
• Relational model.
• Entity-relationship model.

2. What is an Entity?
⇒ An entity in
DBMS(Database management System) is a real-world thing or a real-world
object that is distinguishable from other objects in the real world. For example,
a car is an entity. An attribute of an entity gives us information about the
characteristic features of an entity. For example, a black car entity has an
attribute called color which has a value of black.
The entity has two types:
1. Tangible: Entities which physically present in the real world are called
Tangible entities. Eg: Pen, Car.
2. Intangible: Entities that exist logically. Eg: Bank account.

Entity Set: An entity set is a collection or set of all entities of a particular entity type
at any point in time. The type of all the entities should be the same.

SQL 6
Example :

The collection of all the students from the student table at a particular instant in
time is an example of an entity set.

The collection of all the employees from the employee table at a particular
instant in time is an example of an entity set.

Diff. Between Entity:: Entity Type:: Entity Set:

Weak Entity Set: A weak entity set in DBMS is an entity set that does not have a
primary key, i.e., there exists no attribute that can uniquely represent each entity in
the entity set.

For Example, An entity set of cars having attributes such as a car's color, a car's
name is a weak entity since two cars can have the same color as well as the same

SQL 7
name. So, none of the attributes can be considered as the primary key and hence
the entity set is a weak entity set.

In entity-relationship diagrams, weak entity sets are represented by a double


rectangle.

Strong Entity Set: Strong entity set in DBMS is the entity set in which there exists a
primary key, i.e., there exists an attribute that can uniquely represent each element
in the entity.

* For Example, An entity set of cars having attributes such as a car's


registration number, car color, and car's name is a strong entity since no two
cars can’t have the same registration number. So, the attributes registration
number can be considered as the primary key, and hence the entity set is a
strong entity set.

In entity-relationship diagrams, strong entities are represented by a rectangle.

SQL 8
[Link]

[Link]
type/#:~:text=Tangible Entity %3A Entities that exist,Example%3A Bank
Account%2C etc.

16. What is an attribute?


⇒ Attributes are the units that describe the characteristics of entities.
An entity may contain any number of attributes while one of the attributes is
considered to be a primary key attribute.

In DBMS, there are various types of attributes available:

Simple Attributes

Composite Attributes

Single Valued Attributes

Multi-Valued Attributes

Derived Attributes

Complex Attributes (Rarely used attributes)

SQL 9
Key Attributes

Stored Attributes

Simple Attributes: Simple attribute⁸s in an ER model diagram are independent


attributes that can't be classified further and also, can't be subdivided into any
other component. These attributes are also known as atomic attributes.

Composite Attributes: Composite attributes have opposite functionality to that of


simple attributes as we can further subdivide composite attributes into different
components or sub-parts that form simple attributes. In simple terms, composite
attributes are composed of one or more simple attributes.

Single-Valued Attributes: Single valued attributes are those attributes that


consist of a single value for each entity instance and can't store more than one
value. The value of these single-valued attributes always remains the same just
like the name of a person.

SQL 10
Multi-Valued Attributes: Multi-valued attributes have opposite functionality to
that of single-valued attributes and as the name suggests, multi-valued
attributes can take up and store more than one value at a time for an entity
instance from a set of possible values.

Derived Attributes: Derived attributes are those attributes whose values can be
derived from the values of other attributes. They are always dependent upon
other attributes for their value.

17. What is a Relationship?

SQL 11
⇒ Relationship is an association between two or more entities of the same or
different entity set.
The relation is 3 types:

One-to-One Relationship: Such a relationship exists when each record of one


table is related to only one record of the other table.

One-to-Many or Many-to-One Relationship:

Many-to-Many Relationship:

Participation Constraints:

The relationship can be between two strong entities or a strong entity and a weak
entity. Depending upon the type of entity participating in the relationship, the
participation can be partial or total. There are two types of participation
constraints:

Partial Participation

SQL 12
Total Participation

Partial Participation: Partial Participation exists when all the entity of an entity
type is not associated with one or the other entity of another entity type. This is
represented by joining the relationship with the entity type with the help of one line.
Example: We have two entity types ‘Customer’ and ‘Order’. Then there can be
‘Customers’ who have not done any orders. So, here there is partial participation of
the entity in the relationship.

Total Participation: Total Participation exists when all the entity of an entity type is
associated with one or the other entity of another entity type. This is represented
by joining the relationship with the entity type with the help of a double parallel line.
Such a relationship usually exist between a strong entity and a weak entity.
Example: We have two entity type ‘Employee’ and ‘Dependant’. Then all the
‘Dependent’ entity are related to one or the other ‘Employee’ entity. This is called
total participation of the entity in the relationship. But, it may be possible that some
‘Employee’ is not related to any of the ‘Dependant’ entity. So, ‘Employee’ is
showing partial participation whereas the ‘Dependant’ is showing total participation
in the relationship.

18. What are the disadvantages of file processing systems?


SQL 13
Inconsistent

Not secure

Data redundancy

Difficult in accessing data

Data isolation

Data integrity

Concurrent access is not possible

Limited data sharing

Atomicity problem

19.
What is data abstraction in DBMS?
⇒ Data abstraction in DBMS is a process of hiding irrelevant details from users.
Because database systems are made of complex data structures so, it makes
accessible the user interact with the database.

The following are three levels of data abstraction:

Physical level: It is the lowest level of abstraction. It describes how data are
stored.

Logical level: It is the next higher level of abstraction. It describes what data are
stored in the database and what the relationship among those data is.

View level: It is the highest level of data abstraction. It describes only part of the
entire database.

For example- The user interacts with the system using the GUI and fills in the
required details, but the user doesn't have any idea how the data is being used. So,
the abstraction level is entirely high in the VIEW LEVEL.

Then, the next level is for PROGRAMMERS as in this level the fields and records are
visible and the programmers have the knowledge of this layer. So, the level of
abstraction here is a little low in VIEW LEVEL.

And lastly, the physical level in which storage blocks are described.

SQL 14
20. What is Relational Algebra?

Relational Algebra is a Procedural Query Language that contains a set of
operations that take one or two relations as input and produce a new
relationship. Relational algebra is the basic set of operations for the relational
model.

There are a few fundamental operations of relational algebra:

select

project

set difference

union

rename, etc.

21. What is Relational Calculus?


⇒ Relational Calculus is a Non-procedural Query Language that uses
mathematical predicate calculus instead of algebra. Relational calculus doesn't
work on mathematics fundamentals such as algebra, differential, integration,
etc. That's why it is also known as predicate calculus.

There are two types of relational calculus:

Tuple relational calculus

Domain relational calculus

22. What is normalization?


⇒ Normalization is a process that is used to minimize redundancy and also to
minimize insertion, deletion, and update anomalies.

The most commonly used normal forms are:

SQL 15
First Normal Form(1NF)

Second Normal Form(2NF)

Third Normal Form(3NF)

Boyce & Codd Normal Form(BCNF)

[Link]

Why Do We Need Normalization?


As we have discussed above, normalization is used to reduce data redundancy. It


provides a method to remove the following anomalies from the database and bring
it to a more consistent state:
A database anomaly is a flaw in the database that occurs because of poor planning
and redundancy.

1. Insertion anomalies: This occurs when we are not able to insert data into a
database because some attributes may be missing at the time of insertion.

2. Updation anomalies: This occurs when the same data items are repeated with
the same values and are not linked to each other.

3. Deletion anomalies: This occurs when deleting one part of the data deletes the
other necessary information from the database.

4. 1NF: A relation is in 1NF if all its attributes have an atomic value.

5. 2NF: A relation is in 2NF if it is in 1NF and all non-key attributes are fully
functional and dependent on the candidate key.

6. 3NF: A relation is in 3NF if it is in 2NF and there is no transitive dependency.

7. BCNF: A relation is in BCNF if it is in 3NF and for every Functional Dependency,


LHS is the super key.

SQL 16
23. What is Denormalization?
⇒ Denormalization is the process of boosting database performance and adding
redundant data which helps to get rid of complex data. Denormalization is a part of
the database optimization technique.

24. What is functional Dependency?


⇒ Functional dependency is a relationship between attributes of a table
dependent on each other. It is written as A->B which means B is functionally
dependent on A.

25. What is the E-R model?


⇒ E-R model is a short name for the Entity-Relationship model. This model is
based on the real world. It contains necessary objects (known as entities) and
the relationship among these objects.

26. What are the integrity rules in DBMS?


⇒ There are two integrity rules in DBMS:
Entity Integrity: It specifies that the "Primary key cannot have a NULL value."
Referential Integrity: It specifies that "Foreign Key can be either a NULL value
or should be the Primary Key value of other relation. Referential integrity is
a term used in database design to describe the relationship between two
tables. It is important because it ensures that all data in a database remains
consistent and up to date. It helps to prevent incorrect records from being
added, deleted, or modified.

27. What is join?


⇒ As the name shows, JOIN means to combine something. In the case of SQL,
JOIN means "to combine two or more tables". In SQL, the JOIN clause is used
to combine the records from two or more tables in a database.
Types of SQL JOIN
1. INNER JOIN
2. LEFT JOIN

SQL 17
3. RIGHT JOIN

4. FULL JOIN

[Link]

28. Explain ACID properties


ACID properties are some basic rules, which have to be satisfied by every
transaction to preserve its integrity. These properties and rules are:

ATOMICITY: Atomicity is more generally known as the? all or nothing rule.' This
implies all are considered as one unit, and they either run to completion or are not
executed at all.

CONSISTENCY: This property refers to the uniformity of the data. Consistency


implies that the database is consistent before and after the transaction.
ISOLATION: This property states that the number of transactions can be executed
concurrently without leading to the inconsistency of the database state.

DURABILITY: This property ensures that once the transaction is committed it will
be stored in the non-volatile memory and a system crash can also not affect it
anymore.

[Link]

29. What is 2-Tier architecture?


SQL 18
The 2-Tier architecture is the same as the basic client-server. In the two-tier
architecture, applications on the client end can directly communicate with the
database on the server side.

30. What is the 3-Tier architecture?


The 3-Tier architecture contains another layer between the client and server. The
introduction of 3-tier architecture is for the ease of the users as it provides the GUI,
which, makes the system secure and much more accessible. In this architecture,
the application on the client end interacts with an application on the server which
further communicates with the database system.

SQL 19
31. What is the difference between a shared lock and an exclusive lock?
⇒ Shared lock: A shared lock is required for reading a data item. In the shared
lock, many transactions may hold a lock on the same data item. When more than
one transaction is allowed to read the data items then that is known as the shared
lock.

Exclusive lock: When any transaction is about to perform the write operation, then
the lock on the data item is exclusive. Because, if we allow more than one
transaction then that will lead to inconsistency in the database.

32. Describe the types of keys.


Keys: A key in DBMS is an attribute or a set of attributes that help to uniquely


identify a tuple (or row) in a relation (or table). Keys are also used to establish

SQL 20
relationships between the different tables and columns of a relational database.
Individual values in a key are called key values.

Types of Keys in DBMS:

1. Primary Key

2. Candidate Key

3. Super Key

4. Foreign Key

5. Composite Key

6. Alternate Key

7. Unique Key

Primary Key: The primary key is a column of a table or a set of columns that
helps to identify every record present in that table uniquely. There can be only
one primary Key in a table. Also, the primary Key cannot have the same values
repeating for any row. Every value of the primary key must be different with no
repetitions. Among many details, a primary key is the most significant one to
understand what are keys and what is a primary key in DBMS.

The PRIMARY KEY (PK) constraint put on a column or set of columns will not
allow them to have any null values or duplicates. One table can have only one
primary key constraint. Any value in the primary key cannot be changed by any
foreign keys which refer to it.

Super Key:
Super Key is the set of all the keys that help to identify rows in a table uniquely.
This means that all those columns of a table that are capable of identifying the
other columns of that table uniquely will all be considered super keys.

Candidate Key

SQL 21
Candidate keys are those attributes that uniquely identify rows of a table. The
Primary Key of a table is selected from one of the candidate keys. So, candidate
keys have the same properties as the primary keys explained above. There can
be more than one candidate key in a table.

There can be more candidate keys than just one for any table, but they can
never be empty. Every candidate key carries unique information and value.
Besides these characteristics, a combination of attributes also works as a set of
candidate keys.

Alternate Key
As stated above, a table can have multiple choices for a primary key; however, it
can choose only one. So, all the keys that did not become the primary Key are
called alternate keys.

Foreign Key:
Foreign Key is used to establish relationships between two tables. A foreign key
will require each value in a column or set of columns to match the Primary Key
of the referential table. Foreign keys help to maintain data and referential
integrity.

Foreign keys are essential for maintaining a difference between two entities that
might be linked with the same information but do not share similar information.
In such cases, the tables are linked to maintaining a connection but do not
entirely work as a replacement for each other. For instance, any individual
working for the marketing department might have marketing department
information in its employee table, but that does not mean the table can be
similar to the department table held by the marketing department.

Composite key:

SQL 22
A composite Key is a set of two or more attributes that help identify each tuple
in a table uniquely. The attributes in the set may not be unique when considered
separately. However, when taken all together, they will ensure uniqueness. The
‘concatenated key’ is another name for a composite key.

Unique Key:
A unique Key is a column or set of columns that uniquely identify each record in
a table. All values will have to be unique in this Key. A unique Key differs from a
primary key because it can have only one null value, whereas a primary Key
cannot have any null values.

Among the seven types of keys available in the DBMS, a few other types of
keys in SQL are also accessible. The key type is called Artificial Keys. An
artificial has no relevance or meaning to the business but is often used to tackle
conflicting data management situations. For example, if there is no attribute that
comprises all required primary key properties or if the primary keys are
complex.

[Link] primary
key is used,used to identify a row.

33. Difference between DBMS and RDBMS.


Difference between RDBMS and DBMS

RDBMS DBMS

SQL 23
The data stored is in table format The data stored is in the file format

Multiple data elements are accessible together Individual access to data elements

Data in the form of a table are linked together No connection between the data

Normalization is not achievable There is normalization

No support for distributed


Support distributed database
database

Data is stored in a large amount Data stored in a small quantity

Here, the redundancy of data is reduced with the help


Data redundancy is common
of key and indexes in RDBMS

RDBMS supports multiple users DBMS supports a single-user

It features multiple layers of security while handling There is only low security while
data handling data

The software and hardware


The software and hardware requirements are higher
requirements are low

Oracle, SQL Server. XML, Microsoft Access.

34. Do we consider NULL values the same as that of Blank space or zero?
⇒ NULL value represents a value that is unavailable, unknown, or not
applicable whereas zero is a Number and blank space is a character.

35. Difference between Triggers and Stored Procedures.


S. No. Parameters Triggers Procedures

A trigger is a stored
procedure that runs Stored procedures are
automatically when pieces of code written in
1. Basics
various events happen PL/SQL to do some specific
(eg: update, insert, task.
delete).

2. Action When an event occurs, a A procedure helps to


trigger helps to execute perform a specified task

SQL 24
an action automatically. when it is invoked.

Only nesting of triggers


can be achieved in a We can define/call
3. Define/ call table. We cannot procedures inside another
define/call a trigger procedure.
inside another trigger.

In a database, the syntax In a database, the syntax to


to define a trigger: define a procedure: is
4. Syntax
CREATE TRIGGER CREATE PROCEDURE
TRIGGER_NAME PROCEDURE_NAME.

Transaction statements
All transaction statements
such as COMMIT,
Transaction such as COMMIT and
5. ROLLBACK, and
statements ROLLBACK are allowed in
SAVEPOINT are not
procedures.
allowed in triggers.

Triggers are used to


maintain referential Procedures are used to
6. Usage integrity by keeping a perform tasks defined or
record of activities specified by the users.
performed on the table.

We cannot return values


We can return 0 to n
in a trigger. Also, as an
7. Return value values. However, we can
input, we cannot pass
pass values as parameters.
values as a parameter.

Trigger:

Create or Replace trigger t1


before delete on main
for each row
begin
insert into Backup Values(:[Link], :[Link]);
end;

procedures:

SQL 25
DELIMITER //

CREATE PROCEDURE GetEmployee(IN emp_id INT)


BEGIN
SELECT * FROM employees WHERE employee_id = emp_id;
END //

DELIMITER ;

Trigger: [Link]

36. Difference between clustered and non-clustered index.


CLUSTERED INDEX NON-CLUSTERED INDEX

A clustered index is faster. A non-clustered index is slower.

A clustered index requires less memory Non-clustered index requires more memory for
for operations. operations.

In a clustered index, the index is the In the Non-Clustered index, the index is the copy
main data. of data.

A table can have only one clustered


A table can have multiple non-clustered index.
index.

Clustered index has inherent ability of Non-clustered index does not have inherent
storing data on the disk. ability of storing data on the disk.

Clustered index store pointers to block Non-Clustered index store both value and a
not data. pointer to actual row that holds data.

In Non-Clustered index leaf nodes are not the


In Clustered index leaf nodes are actual
actual data itself rather they only contains
data itself.
included columns.

In Clustered index, Clustered key In Non-Clustered index, index key defines order
defines order of data within table. of data within index.

A Clustered index is a type of index in A Non-Clustered index is a special type of index


which table records are physically in which logical order of index does not match
reordered to match the index. physical stored order of the rows on disk.

The size of clustered index is large. Size of non-clustered index is comparatively

SQL 26
smaller.

Composite key when used with unique


Primary Keys of the table by default are
constraints of the table act as non-clustered
clustered index.
index.

[Link]
clustered-index/

37. Difference between Delete, Drop, and Truncate.


Drop command: The SQL DROP command is a DDL (Data Definition Language)
command that deletes the defined table with all its table data, associated
indexes, constraints, triggers, and permission specifications. The DROP
command drops the existing table from the database. It only requires the table
name to be dropped from the database.
Syntax: DROP TABLE table_name;

Truncate Command: The SQL TRUNCATE command is a DDL (Data Definition


Language) command that modifies the data in the database. The TRUNCATE
command helps us delete the complete records from an existing table in the
database. It resets the table without removing it from the database. It does not
use the WHERE clause like the DELETE command to apply the condition. It
requires the table name to delete the records. It has faster performance due to
the absence of condition checking.
syntax: TRUNCATE TABLE table_name;

Delete commands:
The SQL DELETE command is a DML (Data Manipulation Language) command
that deletes existing records from the table in the database. It can delete one or
more rows from the table depending on the condition given with the WHERE

SQL 27
clause. Thus the deletion of data is controlled according to the user's needs
and requirements. The DELETE statement does not delete the table from the
database. It just deletes the records present inside it and maintains a
transaction log of each deleted row.
syntax: DELETE FROM table_name WHERE condition;

Difference:

DELETE Command DROP Command TRUNCATE Command

The DELETE The TRUNCATE


The DROP command is
command is Data command is a Data
Language Data Definition
Manipulation Definition Language
Language Command.
Language Command. Command.

The TRUNCATE
The DELETE
Command deletes all
command deletes one The DROP Command
the rows from the
Use or more existing drops the complete
existing table, leaving
records from the table table from the database.
the row with the
in the database.
column names.

We can restore any We cannot get the We cannot restore all


deleted row or complete table deleted the deleted rows from
Transition multiple rows from the from the database using the database using
database using the the ROLLBACK the ROLLBACK
ROLLBACK command. command. command.

The DELETE The TRUNCATE


The DROP command
command does not command does not
removes the space
Memory Space free the allocated free the space
allocated for the table
space of the table allocated for the table
from memory.
from memory. from memory.

Performance The DELETE The DROP Command The TRUNCATE


Speed command performs has faster performance command works
slower than the DROP than DELETE Command faster than the DROP
command and but not as compared to command and
TRUNCATE command the Truncate Command DELETE command
as it deletes one or because the DROP because it deletes all
command deletes the the records from the

SQL 28
more rows based on a table from the database table without any
specific condition. after deleting the rows. condition.

The Integrity The Integrity


The Integrity Constraints
Integrity Constraints remain Constraints will not
get removed for the
Constraints the same in the get removed from the
DROP command.
DELETE command. TRUNCATE command.

We need ALTER
permission on the
DELETE permission is schema to which the We need table ALTER
Permission required to delete the table belongs and permission to use the
rows of the table. CONTROL permission TRUNCATE command.
on the table to use the
DROP command.

DELETE FROM
DROP TABLE TRUNCATE TABLE
Syntax table_name WHERE
table_name; table_name;
condition;

[Link]

38. SQL Constraints.


SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures
the accuracy and reliability of the data in the table. If there is any violation between
the constraint and the data action, the action is aborted.

Constraints can be column level or table level. Column-level constraints apply to a


column, and table-level constraints apply to the whole table.

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value

UNIQUE - Ensures that all values in a column are different

SQL 29
PRIMARY KEY - A combination of a NOT NULL and UNIQUE . Uniquely identifies each
row in a table

FOREIGN KEY - Prevents actions that would destroy links between tables

CHECK - Ensures that the values in a column satisfy a specific condition

DEFAULT - Sets a default value for a column if no value is specified

CREATE INDEX - Used to create and retrieve data from the database very quickly

39. Difference Between where and having clause.


=>

What is the “Where Clause”?


Where Clause is used to fetch/filter the records into rows before they are grouped.
These data should specify or meet the mentioned condition. It will select and filter
only the required data. Meanwhile, SQL will also implement ‘and’, ‘or’, and ‘not’ in
the Where Clause, similar to the boolean condition. Operations such as “select,
update, and delete” are also carried out by this clause.

Example: Consider a table given below for “BOOKS”

BOOK_ID BOOK_NAME PRICE

89 A 230

90 B 430

91 C 324

92 D 730

Take the “Query” for example


SELECT BOOK_ID, PRICE FROM BOOKS WHERE PRICE > 350

Output for this query can be given as

BOOK_ID PRICE

B 430

D 730

SQL 30
What is the “Having Clause”?
Data from a group is fetched with the help of the “Having” clause. It tries to cater to
the conditions expected in the final result. The clause is applicable only with Select
statements. The clause is used in column functions.

Example: Take the table below for BOOKS

BOOK_ID BOOK_NAME LANGUAGE PRICE

89 A Hindi 22000

90 B Hindi 20000

91 C English 25000

Consider, we want the count of books with the count of language > 1. Apply the
“Having” clause to the content in the table.

SELECT COUNT(BOOK_ID), LANGUAGE

FROM BOOKS

GROUP BY LANGUAGE
HAVING COUNT(LANGUAGE) > 1;

The output of this is mentioned below:

COUNT(BOOK_ID) LANGUAGE

2 Hindi

What is the Difference between Where and Having


Clause in SQL?
If the “Where” clause is used to filter the records from a table that is based on a
specified condition, then the “Having” clause is used to filter the records from the
groups based on the specified condition. Learn more about what is the difference
between Where and Having Clause in SQL from the table below.

Difference between Where and Having Clause in SQL


Where Clause in SQL Having Clause in SQL

Filter table-based data catering to a


Group-based data under a set condition
specific condition

SQL 31
Applicable without GROUP BY clause Does not function without GROUP BY clause

Row functions Column functions

Select, update, and delete statements Only select statement

Applied before GROUP BY clause Used after GROUP BY clause

Used with single row operations such as Applicable with multiple row functions such as
Upper, Lower and so on Sum, count and so on

40. Difference Between Having and Groupby clause.

Having Clause: Having Clause is basically like the aggregate function with the
GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate
functions. While the GROUP BY Clause groups rows that have the same values into
summary rows. The having clause is used with the where clause to find rows with
certain conditions. The having clause is always used after the Group By clause.

SELECT COUNT (SALARIES) AS COUNT_SALARIES, EMPLOYEES


FROM EMPLOYEES
GROUP BY SALARIES
HAVING COUNT(SALARIES) > 1;

Group By Clause : The GROUP BY clause is often used with aggregate functions
(MAX, SUM, AVG) to group the results by one or more columns or In simple words
we can say that The GROUP BY clause is used in collaboration with the SELECT
statement to arrange required data into groups. The GROUP BY statement groups
rows that have the same values. This Statement is used after the where clause.
This statement is often used with some aggregate function like SUM, AVG, COUNT
atc. to group the results by one or more columns.

SELECT COUNT (SALARIES) AS COUNT_SALARIES, EMPLOYEES


FROM EMPLOYEES
GROUP BY SALARIES;

Difference between Having clause and Group by clause :

[Link]. Having Clause GroupBy Clause

SQL 32
The group by clause is used to
It is used for applying some extra
1. group the data according to a
conditions to the query.
particular column or row.

Having can’t be used without group by group by can be used without


2. clause, in an aggregate function, in that having a clause with the select
case it behaves like a where clause. statement.

The having clause can contain It cannot contain aggregate


3.
aggregate functions. functions.

It restricts the query output by using It groups the output on basis of


4.
some conditions some rows or columns.

42. Difference between where and from


clauses?

FROM WHERE

1. It is used to select the dataset on 1. It is used for conditional checking to


which operations have to be done. filter the result.

2. It is mandatory for any


2. It is optional.
operations.

43. Change the name & address of the student with ID 103 to RITA and DELHI
respectively.

UPDATE STUDENT
SET STUDENT_NAME=’RITA’; ADDRESS = ‘DELHI’
WHERE STUDENT_ID=103;

44. Print the details of the student obtaining the highest marks(if there is more than
one student getting marks then the highest will be according to the alphabetical
order of their names).

SELECT *

SQL 33
FROM STUDENT
WHERE MARKS=(SELECT MAX(MARKS) FROM STUDENT)
ORDER BY STUDENT_NAME LIMIT 1;

45. Display the name & address of the students where the name’s second
letter is ‘U’.

SELECT student_name, Address
FROM STUDENT
WHERE Student_name LIKE ‘_u%’.

46. Print the Marks and numbers of students having marks more than the
average marks of the students from NOIDA city.

SELECT Marks, COUNT (DISTINCT Student_ID)
FROM STUDENT

GROUP BY Marks

HAVING Marks>(SELECT AVG(Marks) FROM STUDENT WHERE


Address=’NOIDA’);

47. Difference between order by and group by clause in SQL


Order By :

Order by keyword sort the result-set either in ascending or descending order.


This clause sorts the result set in ascending order by default. To sort the result-
set in descending order DESC keyword is used.

Order By Syntax –

SQL 34
SELECT column_1, column_2, column_3...........
FROM Table_Name
ORDER BY column_1, column_2, column_3....... ASC|DESC;

Group By :

Group by statement is used to group the rows that have the same value. It is
often used with aggregate functions for example:AVG(), MAX(), COUNT(),
MIN() etc. One thing to remember about the group by clause is that the tuples
are grouped based on the similarity between the attribute values of tuples.

Group By Syntax –

SELECT function_Name(column_1), column_2


FROM Table_Name
WHERE condition
GROUP BY column_1, column_2
ORDER BY column_1, column_2;

function_Name: Name of the aggregate function, for example:

SUM(), AVG(), COUNT() etc.

Table_Name: Name of the table.

Difference:

[Link] GROUP BY ORDER BY

Whereas Order by statement sort


Group by statement is used to group
1. the result-set either in ascending
the rows that have the same value.
or in descending order.

It may be allowed in CREATE VIEW While it does not use in CREATE


2.
statement. VIEW statement.

While in select statement, it is


In select statement, it is always used
3. always used after the group by
before the order by keyword.
keyword.

SQL 35
Whereas in order by statement,
Attribute cannot be in the group by
4. attribute can be under aggregate
statement under aggregate function.
function.

In group by clause, the tuples are


Whereas in order by clause, the
grouped based on the similarity
5. result-set is sorted based on
between the attribute values of
ascending or descending order.
tuples.

Group by controls the presentation of While order by clause controls the


6.
tuples(rows). presentation of columns.

48. What is aggregation?

Aggregation:⇒ In aggregation, the relation between two entities is treated as a


single entity. In aggregation, relationship with its corresponding entities is
aggregated into a higher-level entity.

For example: Center entity offers the Course entity act as a single entity in the
relationship which is in a relationship with another entity visitor. In the real world, if
a visitor visits a coaching center then he will never enquiry about the Course only
or just about the Center instead he will ask the enquiry about both.

49. Even or Odd rows from SQL Server table.


⇒ select * from employee where id%2=0 → Even

select * from employee where id%2=1 → Odd

50. Using an existing table, make an empty one.


⇒ SELECT * FROM <ExistingTable> INTO <NewTable> WHERE 1=2

SQL 36
or
create an SQL table from another table without copying any values from the
old table→ Create Table new_table as(select * from old_table where 1=2).

CREATE TABLE new_table

AS (SELECT *

FROM old_table WHERE 1=2);

51. SQL View with advantages. Why Company use View that much?

In SQL, a view is a virtual table based on the result set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.

You can add SQL statements and functions to a view and present the data as if the
data were coming from one single table.

A view is created with the CREATE VIEW statement.

Syn:

CREATE VIEW view_name AS

SELECT column1,column2, ...

FROM table_name

WHERE condition;

Advantages:

Benefits of Using Views


Design Flexibility: By using a view instead of a query in an application, it is
easier to make changes to the underlying table structure.

Improved Security: By using a view to return data from tables instead of a


SELECT, you can hide the WHERE clause or other columns to which you do not

SQL 37
want the user to have access.

Query Simplification: You can write simple select statements against views,
which handle complex queries and joins.

51. Trigger in SQL?


⇒ A trigger is a stored procedure in a database that automatically invokes
whenever a special event in the database occurs. For example, a trigger can be
invoked when a row is inserted into a specified table or when certain table
columns are being updated.
syntax:

create trigger [trigger_name]


[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
---------------------------------------------
1. create trigger [trigger_name]: Creates or replaces an exis
2. [before | after]: This specifies when the trigger will be
3. {insert | update | delete}: This specifies the DML operati
4. on [table_name]: This specifies the name of the table asso
5. [for each row]: This specifies a row-level trigger, i.e.,
6. [trigger_body]: This provides the operation to be performe

create trigger stud_marks


before INSERT
on
Student

SQL 38
for each row
set [Link] = Student.subj1 + Student.subj2 + Student.s

52. Stored Procedure in SQL,


Stored procedures are prepared SQL code that you save so you can reuse it over
and over again. So if you have an SQL query that you write over and over again,
save it as a stored procedure and call it to run it. You can also pass parameters to
stored procedures so that the stored procedure can act on the passed parameter
values.

Stored Procedures are created to perform one or more DML operations on the
Database. It is nothing but the group of SQL statements that accepts some input in
the form of parameters performs some task and may or may not return a value.

CREATE PROCEDURE procedure_name


(parameter1 data_type, parameter2 data_type, …)
AS
BEGIN
— SQL statements to be executed
END
----------------------------------
To Execute the procedure

EXEC procedure_name parameter1_value, parameter2_value, .

1. BEGIN: This is what directly executes or we can say that it is an executable


part.

2. END: Up to this, the code will get executed.

-- Create a stored procedure named "GetCustomersByCountry"


CREATE PROCEDURE GetCustomersByCountry
@Country VARCHAR(50)
AS

SQL 39
BEGIN
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = @Country;
END;

-- Execute the stored procedure with parameter "Sri lanka"


EXEC GetCustomersByCountry @Country = 'Sri lanka';

53. Difference between Stored Procedure and Functions.

1. A procedure can have both input and output parameters, but a function can
only
have input parameters.

2. Inside a procedure, we can use DML (INSERT/UPDATE/DELETE) statements.


But
inside a function, we can't use DML statements.

3. We can't utilize a Stored Procedure in a Select statement. But we can use a


function
in a Select statement.

4. We can use a Try-Catch Block in a Stored Procedure but inside a function, we


can't
use a Try-Catch block.

5. We can use transaction management in a procedure but we can't in a function.

6. We can't join a Stored Procedure but we can join functions.

7. Stored Procedures cannot be used in the SQL statements anywhere in the


WHERE/HAVING/SELECT section. But we can use a function anywhere.

8. A procedure can return 0 or n values (max 1024). But a function can return only
1
mandatory value.

9. A procedure can't be called from a function but we can call a function from a
procedure

SQL 40
54.

Query

𝘊𝘰𝘯𝘴𝘪𝘥𝘦𝘳 𝘢 𝘵𝘢𝘣𝘭𝘦 𝘯𝘢𝘮𝘦𝘥 "𝘦𝘮𝘱𝘭𝘰𝘺𝘦𝘦𝘴" 𝘸𝘪𝘵𝘩 𝘵𝘩𝘦 𝘧𝘰𝘭𝘭𝘰𝘸𝘪𝘯𝘨 𝘤𝘰𝘭𝘶𝘮𝘯𝘴:

𝘪𝘥 (𝘪𝘯𝘵𝘦𝘨𝘦𝘳)

𝘯𝘢𝘮𝘦 (𝘵𝘦𝘹𝘵)

𝘴𝘢𝘭𝘢𝘳𝘺 (𝘯𝘶𝘮𝘦𝘳𝘪𝘤)

𝘥𝘦𝘱𝘢𝘳𝘵𝘮𝘦𝘯𝘵 (𝘵𝘦𝘹𝘵)

𝘩𝘪𝘳e_𝘥𝘢𝘵𝘦 (𝘥𝘢𝘵𝘦) #sql

1. Write an SQL query to find the top 3 highest-paid employees in each


department.

select * from (select e.*, rank() over (partition by dept_name order by salary
desc) as rnk from employee e) x where [Link]<4;

2. Write an SQL query to find the name and salary of the lowest-paid employee in
each department.

select name,salary from (select e*, rank() over (partition by dept_name order by
salary) as rnk) x where [Link]<2

SQL 41
3. Write an SQL query to find the name and salary of the highest-paid employee
in each department who was hired in the last year.
⇒ select max(salary) from (select name,salary,dept, RANK() OVER(PARTITION
BY DEPT order by salary) as rnk from employees where
(select *, DATEDIFF(YEAR,HireDate, GETDATE()) as Different from Employees
where DATEDIFF(YEAR,HireDate, GETDATE()) between 0 and 1
order by HireDate ASC)

4. Query for employees who were hired in the last year.

⇒select *, DATEDIFF(YEAR,HireDate, GETDATE()) as Different from Employees


where DATEDIFF(YEAR,HireDate, GETDATE()) between 0 and 1
order by HireDate ASC.

5. Write an SQL query to find the name and salary of the highest-paid employee
in each department who has been with the company for at least 5 years.

6. 5. Write an SQL query to find the names of all employees who have the same
name as another employee in the company.

7. 6. Write an SQL query to find the name and salary of the employee who has the
highest salary among all employees who were hired in the last year.

8. 7. Write an SQL query to find the name and salary of the employee who has the
highest salary among all employees who have been with the company for at
least 10 years.

SQL 42
9. 8. Write an SQL query to find the name and department of all employees who
have been with the company for more than 10 years and have a salary greater
than $100,000.

10. 9. Write an SQL query to find the name and salary of the employee who has the
second-highest salary in the company.

11. 10. Write an SQL query to find the name and department of all employees who
have the same manager as another employee in the company.

12. Write an SQL query to report all the duplicate emails. You can return the result
table in any order.

select email
from Person
group by email
having count(email) > 1;

13. Construct a SQL query to provide each player's first login date. You can return
the result table in any order.

select playerId, min(eventDate) as firstLogin from Activity g


---------------------
select distinct(playerId),
FIRST_VALUE(eventDate) OVER(PARTITION BY playerId ORDER BY ev
from Activity;

SQL 43
14. Write an SQL query to report all customers who never order anything. You can
return the result table in any order.

select [Link] as 'Customers' from Customers c


left join Orders o ON ([Link] = [Link])
where [Link] is null

15. 1. Write an SQL query to report the movies with an odd-numbered ID and a
description that is not "boring". Return the result table ordered by rating in
descending order.

SELECT *
FROM Cinema
WHERE id % 2 = 1 AND description NOT LIKE '%boring%'
ORDER BY rating DESC;

16. 1. Construct a SQL query to display the names and balances of people who
have a balance greater than $10,000. The balance of an account is equal to the
sum of the amounts of all transactions involving that account. You can return
the result table in any order.

SELECT [Link], SUM([Link]) AS balance


FROM Users u natural join Transactions t
GROUP BY t.account_number
HAVING balance> 10000;

17. 1. Write a SQL query that detects managers with at least 5 direct reports from
the Employee table.

SQL 44
SELECT Name
FROM Employee
WHERE id IN
(SELECT ManagerId
FROM Employee
GROUP BY ManagerId
HAVING COUNT(DISTINCT Id) >= 5);

18. Construct an SQL query that retrieves the fname in upper case from the
Employee table and uses the ALIAS name as the EmployeeName in the result.

SELECT UPPER(fname) AS EmployeeName FROM Employee;

19. Construct an SQL query to find out how many people work in the "HR"
department

SELECT COUNT(*) FROM Employee WHERE department = 'HR';

20. Construct an SQL query to retrieve the first four characters of the ‘lname’
column from the Employee table.

SELECT SUBSTRING(lname, 1, 4) FROM Employee;

21. Construct a new table with data and structure that are copied from the
existing table ‘Employee’ by writing a query. The name of the new table
should be ‘SampleTable’.

select * INTO SampleTable from Employee where 1=0;

22. Construct an SQL query to find the names of employees whose first names
start with "S".

SQL 45
Select * from employee where fname like's%'

23. Construct an SQL query to count the number of employees grouped by


gender whose dateOfBirth is between 01/03/1975 and 31/12/1976.

select count(*),gender from employee where dateOfBirth Betwee

24. Construct an SQL query to retrieve all employees who are also managers.

select [Link], [Link], [Link]


from Employee emp inner join salary sal
on [Link] = [Link] and [Link] IN('Managers')

25. Construct an SQL query to retrieve the employee count broken down by
department and ordered by department count in an ascending manner.

select department,count(id) as Dept_count


from employee group by department
order by Dept_count ASC;

26. Construct an SQL query to retrieve duplicate records from the Employee
table.

select fname,dept,count(id) as Count from employee group by i

27. Write an SQL query to fetch the EmpId and FullName of all the employees
working under the Manager with id – ‘986’.

select EmpId,FullName
from Emp_details

SQL 46
where Manager_id=986;

28. Write an SQL query to fetch the different projects available from the
EmployeeSalary table.

select distinct(project)
from EmployeeSalary

29. Write an SQL query to fetch the count of employees working in project ‘P1’.

select count(*)
from empsalary
where project = 'p1'

30. Write an SQL query to find the maximum, minimum, and average salary of
the employees.

select Max(salary)
min(salary)
avg(salary)
from Emp_sal

31. Write an SQL query to find the employee id whose salary lies in the range of
9000 and 15000.

select emp_id
from sal_details
where salary between 9000 and 15000;

32. Write an SQL query to fetch those employees who live in Toronto and work
under the manager with ManagerId – 321.

SQL 47
select emp_id, city, ManagerId
from emp_details
where ManagerId=321 and city='Toronto'

33. Write an SQL query to fetch all the employees who either live in California or
work under a manager with ManagerId – 321.

SELECT empid, City, ManagerId


FROM EmployeeDetails
WHERE City='California' OR ManagerId='321';

34. Write an SQL query to fetch all those employees who work on Projects other
than P1.

select empid
from employee salary
where not Project='P1';
-------------------------------------
SELECT EmpId
FROM EmployeeSalary
WHERE Project <> 'P1';

35. Write an SQL query to display the total salary of each employee adding the
Salary with Variable value.

select empid, salary+Variable as Total_salary


from EmployeeSalary;

36. Write an SQL query to fetch the employees whose name begins with any two
characters, followed by a text “hn” and ends with any sequence of
characters.

SQL 48
select FullName
from EmployeeDetails
where Fullname like '__hn%';

37. Write an SQL query to fetch all the EmpIds which are present in either of the
tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.

Select empid from EmployeeDetails


union
select empid from EmployeeSalary

38. Write an SQL query to fetch common records between two tables.

select * from EmployeeDetails


intersect
select * from EmployeeSalary
----------------------------------------
MySQL – Since MySQL doesn’t have INTERSECT operator so we can
SELECT *
FROM EmployeeSalary
WHERE EmpId IN
(SELECT EmpId from ManagerSalary);

39. Write an SQL query to fetch records that are present in one table but not in
another table.

Select * from Emp_sal


Minus
select * from Man_sal
--------------------
MySQL – Since MySQL doesn’t have a MINUS operator so we can u

SQL 49
select emp_sal.*
from emp_sal
Left Join
Man_sal using(emp_id)
where man_sal.emp_id Is Null;

40. Write an SQL query to fetch the EmpIds that are present in both the tables –
‘EmployeeDetails’ and ‘EmployeeSalary.

select empid
from EmployeeDetails
where empid in
(select empid from EmployeeSalary);

41. Write an SQL query to fetch the EmpIds that are present in
EmployeeDetails but not in EmployeeSalary.

SELECT EmpId FROM


EmployeeDetails
where EmpId Not IN
(SELECT EmpId FROM EmployeeSalary);

42. Write an SQL query to fetch the employees’ full names and replace the
space with ‘-’.

select replace(FullName,'','-')
from EmployeeDetails;

43. Write an SQL query to fetch the position of a given character(s) in a field.

SELECT INSTR(FullName, 'Snow')


FROM EmployeeDetails;

SQL 50
44. Write an SQL query to display both the EmpId and ManagerId together.

select concat(EmpId,ManagerId) as newId


from Emp_details

45. Write a query to fetch only the first name(string before space) from the
FullName column of the EmployeeDetails table.

MySql-

select mid(FullName,1,LOCATE('',FullName))
from EmployeeDetails;

SQL Server-

select substring(FullName,1,CharIndex('',FullName))
from EmployeeDetails;

46. Write an SQL query to uppercase the name of the employee and
lowercase the city values.

select upper(Name),lower(city)
from EmployeeDetails;

47. Write an SQL query to find the count of the total occurrences of a
particular character – ‘n’ in the FullName field.

select FullName
Length(FullName)-Length(Replace(FullName,'n',''))
from EmployeeDetails;

48. Write an SQL query to update the employee names by removing leading
and trailing spaces.

SQL 51

Update Emp_details
set FullName=LTRIM(RTRIM(FullName));

49. Nth Highest Salary


CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT


BEGIN
SET N=N-1;
RETURN (
# Write your MySQL query statement below.
select distinct salary from employee order by salary
limit 1 OFFSET N

);
END

50. 2nd highest salary.


select max(salary) as max_sal from employee


where salary <(select max(salary) from employee)

51. Rank Scores


select score,DENSE_RANK() over(order by salary desc) as "r


from employee;

52. 3 Consecutive Numbers


SELECT distinct([Link]) as ConsecutiveNums


FROM Logs a,Logs b, Logs c

SQL 52
where [Link]=[Link]-1 and [Link]=[Link]-1
and [Link]=[Link] and [Link]=[Link];

53. Duplicate emails


select enail
from customer
group by email
having count(*)>1;

54. Customers Who Never Order


select [Link] as customers


from customers c
left join orders o
on [Link]=o.customer_id
where c.customer_id is null;

55. Department Highest Salary


select [Link],[Link],[Link]
from Employee e
join Department d
on [Link]=[Link]
where (DepartmentId,salary) in
(select DepartmentId,max(salary)
from employee
group by DepartmentId)

56. You have been given a database schema consisting of two tables orders
and order items. Write a SQL query that calculates the total revenue
generated from each order. The total revenue should be calculated b
multiplying the price item by the quantity and summing up the results for
each order. The results should be sorted by order_id in ascending order.

SQL 53
Orders(order_id, customer_I'd, order_date). Order_items( order_item_I'd,
order_id, product_name, price, quantity)

SELECT
o.order_id,
SUM([Link] * [Link]) AS total_revenue
FROM
orders o
JOIN
order_items oi ON o.order_id = oi.order_id
GROUP BY
o.order_id
ORDER BY
o.order_id ASC;

57.

Write a SQL query that retrieves the employee information along with an
additional column names bonus, based on the following conditions:

1. If an employee's salary is greater than 5000 the bonus should be 10%


of the salary.

2. If an employee's salary is between 3000 and 5000(both inclusive), the


bonus should be 5% of the salary

3. If an employee's salary is less than 3000 the bonus should be 2% of


the salary
Results column contains: I'd name salary department bonus

SELECT
Id,
name,
salary,
department,

SQL 54
CASE
WHEN salary > 5000 THEN salary * 0.10
WHEN salary BETWEEN 3000 AND 5000 THEN salary * 0.
ELSE salary * 0.02
END AS bonus
FROM
employees;

58.

Employee table contains I'd first_name last_name salary. Write a query that
satisfy the conditions

1. Sort the data in descending order of salary

2. Retrve the data from the 5th row up to the 10th row (both inclusive)

SELECT
Id,
first_name,
last_name,
salary
FROM
Employee
ORDER BY
salary DESC
LIMIT 6 OFFSET 4;

59.

Leetcode → [Link]
problem-solving#175-combine-two-tables--easy--leetcode

[Link]
questions-easy/

SQL 55
char_length → Length of the characters.

New
1. Write an SQL query to render a column. Why do we use OFFSET command?

To render a column in SQL, you can use the SELECT statement to specify the
column you want to retrieve from a table. Here's an example of an SQL query
that selects a column named column_name from a table named table_name :

SELECT column_name
FROM table_name;

Why do we use the OFFSET command?


The OFFSET command in SQL is used to skip a specified number of rows before
starting to return rows from the query result. It is commonly used in pagination
to control which subset of rows is returned, especially when dealing with large
datasets.

For example, if you want to skip the first 10 rows and then return the next set of
rows, you can use:

SELECT column_name
FROM table_name
ORDER BY some_column
OFFSET 10;
----------------------------------------------
Offset for a Range -

SELECT column_name
FROM table_name
ORDER BY some_column
OFFSET 10
LIMIT 5;

SQL 56
This would skip the first 10 rows and return all rows after that.

2. What is the order of execution of SQL commands?


3. Write a SQL query to get second highest query using sub query.

SELECT MAX(salary) AS second_highest_salary


FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

4. Write a SQL query to find all the student names Nitin in a table

SELECT *
FROM students
WHERE name = 'Nitin';

5. Write a query to get all the students with name length 10, starting with K and
ending with z.

SELECT *
FROM students
WHERE LENGTH(name) = 10 AND name LIKE 'K%z';

6. Get the second highest query using ranking.



To get the second highest value using ranking functions, you can use the
ROW_NUMBER() , RANK() , or DENSE_RANK() functions in SQL. These functions allow you

to assign a rank to each row within a partition of a result set. Here's an example
using the RANK() function to find the second highest salary from a table named
employees .

SELECT salary
FROM (

SQL 57
SELECT salary, RANK() OVER (ORDER BY salary DESC) AS rank
FROM employees
) ranked_salaries
WHERE rank = 2;
-------------------------------------------------------------
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) A
FROM employees
) ranked_salaries
WHERE rank = 2;

7. Can you use HAVING without any aggregate function?



Yes, you can use
HAVING without an aggregate function in SQL. However, it is less common and

often redundant because the HAVING clause is typically used to filter groups of
rows created by GROUP BY . When used without GROUP BY , HAVING acts similarly to
a WHERE clause, but it's evaluated after the SELECT statement.

SELECT name
FROM students
HAVING name LIKE 'A%';

8. Select the winner using SQL queries.


SELECT name, score


FROM contest_results
ORDER BY score DESC
LIMIT 1;

9. What would be the result of row number, rank, and dense rank ?

The ROW_NUMBER() , RANK() , and DENSE_RANK() window functions in SQL are used to
assign a unique rank or number to rows within a result set, usually based on

SQL 58
some ordering. The way each function handles ties (rows with the same value)
differs, and this affects the output rankings.

Let's consider an example to illustrate the differences between ROW_NUMBER() ,


RANK() , and DENSE_RANK() .

Example Table
Suppose we have a table students with columns name and score :

name score

Alice 90

Bob 95

Carol 90

Dave 95

Eve 85

SQL Queries to Use Each Function


Here are the SQL queries using each of the window functions:

1. ROW_NUMBER() :

SELECT name, score,


ROW_NUMBER() OVER (ORDER BY score DESC) AS row_nu
mber
FROM students;

2. RANK() :

SELECT name, score,


RANK() OVER (ORDER BY score DESC) AS rank
FROM students;

3. DENSE_RANK() :

SELECT name, score,


DENSE_RANK() OVER (ORDER BY score DESC) AS dense_

SQL 59
rank
FROM students;

Result Explanation
Assuming we run these queries on the example table above, here are the
results and the differences:

name score row_number rank dense_rank

Bob 95 1 1 1

Dave 95 2 1 1

Alice 90 3 3 2

Carol 90 4 3 2

Eve 85 5 5 3

Differences Explained:
1. ROW_NUMBER() :

Unique Numbers: Assigns a unique number to each row regardless of


duplicates in the ORDER BY column.

No Ties Handling: It does not consider ties, so each row gets a distinct
number in sequence (1, 2, 3, ...).

2. RANK() :

Handles Ties: Assigns the same rank to rows with identical values in
the ORDER BY column.

Gaps in Ranks: If there are ties, the next rank skips numbers
accordingly. For example, if two rows tie at rank 1, the next rank is 3
(not 2).

3. DENSE_RANK() :

Handles Ties: Also assigns the same rank to rows with identical values
in the ORDER BY column.

No Gaps in Ranks: Unlike RANK() , DENSE_RANK() does not skip any rank
numbers after ties. If two rows tie at rank 1, the next rank is 2.

SQL 60
Conclusion
Use ROW_NUMBER() when you need a unique number for each row.

Use RANK() when you want to assign the same rank to tied rows but have
gaps in subsequent rankings.

Use DENSE_RANK() when you want to assign the same rank to tied rows
without any gaps in the ranking sequence.

10. Find all the students who either are male or live in Mumbai.

SELECT *
FROM students
WHERE gender = 'Male' OR city = 'Mumbai';

11. Extract all the distinct email ID domains from all the employee.

SELECT DISTINCT SUBSTRING_INDEX(email, '@', -1) AS domain


FROM employees;

12. Can you join two tables without any common column?

Yes, you can join two tables without any common column, but this type of join
is less common and has specific use cases. When you join two tables without a
common column, the result is typically a Cartesian product (or cross join) of the
two tables. This means every row from the first table is combined with every
row from the second table.

Cartesian Product (Cross Join)


In SQL, you can use the CROSS JOIN or simply JOIN without an ON clause to
achieve this. Here's an example:

Example Tables
Assume you have two tables:

table1 :

SQL 61
id name

1 Alice

2 Bob

table2 :

code city

A Paris

B Tokyo

SQL Query for Cartesian Product

SELECT *
FROM table1
CROSS JOIN table2;

Explanation:
: Produces a Cartesian product of table1 and table2 . Every
CROSS JOIN

combination of rows from the two tables is included in the result set.

Result Set
The result will be:

id name code city

1 Alice A Paris

1 Alice B Tokyo

2 Bob A Paris

2 Bob B Tokyo

When to Use
Generating Combinations: When you need to create all possible
combinations of rows from the two tables.

Testing: For generating sample data or testing queries.

Caution

SQL 62
Large Datasets: Be cautious when using CROSS JOIN with large tables, as it
can produce a large number of rows and may impact performance.

Unexpected Results: Ensure that the Cartesian product is what you intend,
as it can sometimes produce unexpected or unwanted results if not
carefully planned.

In summary, while you can join tables without a common column using a
Cartesian product, it's essential to use this approach thoughtfully based on
your specific needs.

13. Find the output.


Select case when null=null then ‘Amit’ else ‘Rahul’ end from dual

In SQL, when dealing with NULL values, any comparison involving NULL always
results in NULL because NULL represents an unknown or missing value. This
includes comparisons like NULL = NULL .

The SQL query you provided is:

SELECT CASE
WHEN NULL = NULL THEN 'Amit'
ELSE 'Rahul'
END
FROM dual;

Explanation:
: This comparison evaluates to NULL because NULL represents an
NULL = NULL

unknown value, and the result of comparing two unknown values is also
unknown.

CASE WHEN NULL = NULL THEN 'Amit' ELSE 'Rahul' END : Since the condition NULL =
NULLevaluates to NULL (not true), the CASE statement defaults to the ELSE
clause.

ELSE 'Rahul' : Given that the condition is not true (i.e., it evaluates to NULL ),
the ELSE part of the CASE statement is executed.

Output:
The result of the query will be:

SQL 63
RAHUL

This is because the condition in the CASE statement is NULL , and thus the ELSE

branch is chosen, returning 'Rahul' .

14. Differentiate between COUNT(*) and COUNT(ColName)


and COUNT(ColName) are both aggregate functions used to count rows in


COUNT(*)

SQL, but they have different behaviors and use cases:

COUNT(*)

Counts Rows: COUNT(*) counts the total number of rows in a table or a result
set, regardless of whether any columns contain NULL values.

Includes All Rows: It includes all rows in the count, even if some columns
contain NULL values or if there are no values in specific columns.

Performance: Generally, COUNT(*) is optimized by the database engine and


may be faster in certain cases because it doesn't need to inspect individual
column values.

Example:

SELECT COUNT(*) AS total_rows


FROM employees;

This query counts all rows in the employees table.

COUNT(ColName)

Counts Non-NULL Values: COUNT(ColName) counts the number of non- NULL


values in the specified column ( ColName ).

Excludes NULLs: It excludes rows where the specified column has a NULL

value from the count.

Column Specific: The count is specific to the column you provide and does
not count rows where the column value is NULL .

Example:

SQL 64
SELECT COUNT(email) AS email_count
FROM employees;

This query counts the number of non- NULL email addresses in the employees

table.

Key Differences:
Scope of Counting:

COUNT(*) counts all rows.

COUNT(ColName) counts only the rows where ColName is not NULL .

Null Handling:

COUNT(*) is unaffected by NULL values.

COUNT(ColName) ignores NULL values in the specified column.

Use Case:

Use COUNT(*) when you need the total number of rows in a table or
result set.

Use COUNT(ColName) when you need to count only the rows where a
specific column has non- NULL values.

Example with Data:


Assume the employees table has the following data:

id name email

1 Alice alice@[Link]

2 Bob NULL

3 Carol carol@[Link]

4 Dave NULL

COUNT(*) would return 4 (total number of rows).

COUNT(email) would return 2 (only the rows where email is not NULL ).

Understanding these differences helps in writing accurate SQL queries based


on the specific data counting needs.

SQL 65
15. How do we create a table with all the employee Names and Manager Names?

To create a table that includes both employee names and their manager names,
you'll need to join the employees table with itself. This is commonly done using a
self-join, where the table is joined with itself based on a relationship between
employees and their managers.

Assumptions
employees Table: Contains columns like employee_id , employee_name , and
manager_id .

manager_id : Refers to the employee_id of the employee's manager.

Steps
1. Create the Table: First, ensure you have the employees table created with
the necessary columns.

2. Join the Table: Use a self-join to match employees with their managers.

SQL Example
Here is an example SQL query that creates a new table to store the employee
names and their manager names:

Step 1: Create the employees Table (if it doesn’t already exist)

CREATE TABLE employees (


employee_id INT PRIMARY KEY,
employee_name VARCHAR(100),
manager_id INT
);

Step 2: Populate the Table with Sample Data

INSERT INTO employees (employee_id, employee_name, manager_


id) VALUES
(1, 'Alice', NULL), -- Alice has no manager, perhaps CE
O or top-level

SQL 66
(2, 'Bob', 1), -- Bob is managed by Alice
(3, 'Carol', 1), -- Carol is managed by Alice
(4, 'Dave', 2); -- Dave is managed by Bob

Step 3: Create a New Table with Employee and Manager Names

CREATE TABLE employee_manager AS


SELECT
e1.employee_name AS employee_name,
e2.employee_name AS manager_name
FROM
employees e1
LEFT JOIN
employees e2 ON e1.manager_id = e2.employee_id;

Explanation:
employees e1 : Alias for the employee records in the first instance of the
employees table.

employees e2 : Alias for the manager records in the second instance of the
employees table.

: Ensures that all employees are included in the result, even if they
LEFT JOIN

don't have a manager (e.g., the CEO with NULL as manager_id ).

ON e1.manager_id = e2.employee_id : Joins the employees with their managers


based on the manager’s ID.

Query to Verify the Data


To verify the contents of the employee_manager table, you can use:

SELECT * FROM employee_manager;

Result:
Given the sample data, the result might look like:

employee_name manager_name

SQL 67
Alice NULL

Bob Alice

Carol Alice

Dave Bob

This table shows each employee along with the name of their manager. If an
employee does not have a manager, the manager_name will be NULL .

16. Write a query for collecting the names of children who pursuing their
graduation in their residential city.

SELECT [Link]
FROM children c
JOIN education e ON [Link] = e.child_id
WHERE c.residential_city = e.institution_city;

17. What is indexing in SQL?


Indexing in SQL is a technique used to optimize the performance of database


queries by allowing faster retrieval of records from a table. An index creates an
ordered data structure (like a B-tree or hash table) that the database uses to
locate rows more quickly than it could by scanning the entire table.

Key Points:
Purpose: To speed up the retrieval of data by reducing the amount of data
the database engine needs to scan.

Types: Common types include primary indexes, unique indexes, and


composite indexes.

Use Case: Often used on columns frequently queried with WHERE clauses,
join operations, or used in sorting ( ORDER BY ).

Trade-Offs: While indexes speed up read operations, they can slow down
write operations (like INSERT , UPDATE , DELETE ) because the index must also
be updated.

Indexes are essential for improving query performance in large databases.

SQL 68
18. Show how to write a query to show details of an HR whose name starts with M.
=

19. What is the use of the FETCH command?


Give the number of duplicate names and their frequency.
Get alternate record from table.
How would you partition data for optimum performance?
Over-weigh
arrange the employees with respect to their Joining date, most experienced
employees coming on the top followed by others.
Find employees that satisfy the condition.
Find employees satisfying the given condition & create a new table.
Write an SQL Query find number of employees whose DOB is between
01/07/1965 to 31/12/1975.
How can you create an empty table from an existing table? Write the steps and
explain the working.
What is the use of IFNULL and ISNULL in SQL?
Write a SQL query to create a Table 3 that contains the following columns- Id,
First_Name, Last_Name, Salary
.Creating subqueries.
Remove duplicate entries from the table.
How can you eliminate duplicate rows from a query result?
Which join is used to join a table with itself?
Guess the [Link] wildcards in MySQL.
Perform the SQL instructions as specified.
List the products from each brand.
Write query for the problem statement.
How the triggers will execute if two or more triggers?
What are the primitive operations common to all database management
systems?
Provide detailed queries to retrieve the answers to the following questions.
Pivot a table in SQL using the pivot function.
What is the function of OFFSET command?
Use regular expression to render records as specified.
Important conditions for joining two tables on a key? Question
Which join takes more processing time?
Differentiate between NVL and NVL2 functions.
What is NTILE with syntax?

SQL 69
How to get the cumulative sum in a table?
Find the Nth largest salary from employee table.
Write valid query.
Write a SQL query to find the common records between two tables.
Write a query to get all the employee detail from EmployeeDetail table.
How to calculate the output of the functions?
How to do database integrity?
Use regular expression to find the number of people who are from Delhi and
have arrived in Patna in the last 7 days, as specified.
Create a ranking row without using Rank function in SQL.
Does the data stored in the stored procedure increase access time or execution
time? Explain.
What is the function of COALESCE()?
Write a valid query for the given problem.
What is a RANK() function?
How to fetch only even rows from a table?
What do you understand by Fuzzy merging?
Which language will you use to handle it?
Get the Emp_id for employees whose Dept_id is either invalid or not present in
the database.
If we drop a table, does it also drop related objects like constraints, indexes,
columns,
Define DDL, DML and DCL.
What is the use of NVL function in Oracle?
How to generate row number in a table without using ROWNUM() ?
How would you select the top 100 customers with the highest spend over a
year-long period?
What are the differences among ROWNUM, RANK and DENSE_RANK?
All you have to do is to go through the code and comment the question for
which the following is an answer of the given.
What are the steps you will take to improve the performance of a poor
performing query?
What is parser?
How many rows will be populated ?
How would you group the users together in meaningful segments?
Get all employee detail from EmployeeDetail table whose “FirstName” not start
with any single character between ‘a-p’

SQL 70
Write a SQL query to find the date along with the IDs whose temperature is
lower from the next day.
How can you create an empty table from an existing table?
What is the difference between DELETE and TRUNCATE commands?
Given two tables, one of customers and another of car accidents, write a SQL
query to get the top car accidents by day.
Write a query to find employees who have completed more than 2 years in the
company.
Find the hours for which the product ‘A’ was out of stock, assuming this is all
the data for one day only
Give some problems or scenarios where map-reduce concept works well and
where it doesn’t work.
Guess the question.
What is the correct order of writing SQL query from given tags?
Print the message ‘NUMBER’ if valid, ‘NOT NUM’ if not.
Query the list of CITY names from STATION that does not start with vowels and
do not end with vowels.
calculate the count distinct ids which are there present for last 7 days with
respect to given date.
Arrange the Emp_name in alphabetical order in the new table that only has the
salary and Emp_name column in it.
State some biases that you are likely to encounter when cleaning a database.
Write a query to replace “not provided” where there is null in the below table
and then show the department manager column.
What will be the output of Following SQL Query.
To create a sql script so that it keeps information of all the user’s badge swipe
in the last 30 days only and truncates the rest of the dataList the total number
of products of each brand.
List the total numbers of products of each [Link] the appropriate result.
Write a query using above tables to display the Emp_no, name and Experience
( in year and month)from joining date to current date. Question
Refer to the following table and answer the questions related to it.
For what purpose we are using view?
Guess the question.
How can you create an empty table from an existing table?
UNANSWERED
Can we have another column in a table other than a primary key column which

SQL 71
will act as a primary key?
You are provided with a poor performing query, suggest some methods to
improve it and satisfy the required conditions.
Suggest some ways to handle Duplicate Records.

After entering the data from the front-end application interface, how do you test
whether a database is updated or not?
Find the 4th highest employee salary from the table
What are different types of UDF in SQL?
What changes can you recommend to reduce the use of triggers?
If a table contains duplicate rows, does a query result display the duplicate values
by default?
How can you use a CTE to return the fifth highest salary from a table?
What is Hash Join?
List the id , marks of all students whose marks don’t fall under any grade.
How will you update a table without using Update statement?
Can you modify the rows in a table based on values from another table? Explain.
Find no. of subscribers each month or MoM.
What do you understand by Fuzzy merging?
What is the purpose of the group functions in SQL?

Write a SQL query to find total number of employees who are inside the office at
4PM . Consider all possible cases .
What is the role of “Database Testing” in SQL?
What’s the actual practical use of OFFSET? SQL
Find the output.
The wildcard in a WHERE clause is useful when?
How do you go about investigating the slowness and helping them to improve
queries?
Which expressions or functions allow you to implement conditional processing in a
SQL statement?
Explain the difference between “long” and “wide” format data.
Explain PARTITION key.
How can you use a CTE to return the fifth highest (or Nth highest) salary from a
table?
What is the difference between Case and Searched Case statements in SQL? How
do data management procedures like missing data handling make selection bias
worse?

SQL 72
🧿 SQL

SQL 73

You might also like