Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 140

SQL Interview Questions & Answers

What is Database?

A database is an organized collection of data, stored and retrieved digitally from a remote or local
computer system and helps in collecting, storing and retrieving data. Databases can be vast and complex,
and such databases are developed using fixed design and modelling approaches.

What is DBMS?

DBMS stands for Database Management System which is responsible for the creating, updating, and
managing of the database it can also be defined as a structured form of data storage in a computer or
collection of data in an organized manner and can be accessed in various ways, It is also the collection of
schemas, tables, queries, views, etc. Databases help us with easily storing, accessing, and manipulating
data held on a computer. The Database Management System allows a user to interact with the
database. DBMS can be termed as File Manager that manages data in a database rather than saving it in
like file systems.

This system is like the modern version of keeping files filled with vital information. However, the
advancement in our technology, guided us to come up with a system where one can file so much
information for different purposes like update, retrieval, storage, security, backup, etc. 

Database Management System was first introduced in the year 1960 by Charles W. Bachman. The first
integrated database system for the company General Electric Company changed the way we store
information, use data for insightful purposes. 

For example, writing down the total sales for every day without any system will never bring any results
plus increase the chances of error. 

With the introduction of DBMS, one could store information and manage it for future decisions. 

 It helps maintain data uniformity

 Handles large set of data efficiently

 Versatile 

 Faster way of managing data

 What is RDBMS? How is it different from DBMS?

RDBMS stands for Relational Database Management System that stores data in the form of a collection of
tables, the key difference here, compared to DBMS, is that RDBMS stores data in the form of a collection
of tables, and relations can be defined between the common fields of these tables. Most modern
database management systems like MySQL, Microsoft SQL Server, Oracle, IBM DB2, and Amazon Redshift
are based on RDBMS. It also provides relational operators to manipulate the data stored into the tables.

The Relational Database Management System was introduced in the 1970’s itself. With the advent of
technology, everyone wants everything fast-paced, innovative, productive and efficient. It is this ideology
and belief that necessitated a shift from the traditional version of DBMS. 
The Traditional Database Management System introduced a better, more refined way of working with
databases. RDBMS not only is an improvised version of a database management system, it is a platform
of need and necessity. Data is growing at an exponential rate and to manage everything for scalable
operations, a proficient system is required. This generated the surging demand for RDBMS, making it one
of the popular forms of database management systems. 

 Allow multiple user access

 Store large pack of data

 Minimum Data Redundancy 

 Maintains Data Integration

 Better tools for structuring and Organizing Data

Parameter DBMS RDBMS

RDBMS is software that allows the


DBMS is a system software for
creation and management of
creating, storing, managing, updating
Function databases in a tabular format for
and retrieving data from the
efficient retrieval, updating and
databases.
storage of data.

In RDBMS, the data is stored in tables.


In DBMS, the storage of data is in the There is no hierarchy and instead,
Storage files. It is arranged either in a follow a relational model. Columns are
hierarchical form or navigational form. the headers and rows contain the
corresponding values.

Relational Database Management


Database Management System can
Number of Users System allows access to multiple users
only support a single user.
to the databases.

Normalization is enabled in RDBMS. In


Normalization
fact, it was introduced by Edgar F.
(organizing data in the DBMS does not support normalization.
Codd for his relational database
database)
model.

DBMS cannot store large quantities of RBMS allows users to store a large set
Data Type
data. of data.

In the database management system, In RDBMS, there are relationships


Data Relationships there are no relationships amongst formed amongst the data stored in
the data stored. tables.

The process of Data Fetching is faster,


The process of data fetching in DBMS
Data Fetching and efficient in RDBMS because of its
is slow.
relational model.

Distributed Databases DBMS does not support distribution of RDBMS supports distributed
databases.  Distributed database is a databases.
database that can be stored at
different locations.

In RDBMS, data redundancy is


The version of DBMS increases data
Data Redundancy eliminated that reduces wastage of
redundancy (repetition of data).
time and resources.

In RDBMS, hardware and software


Hardware and Software DBMS needs minimum software and
requirements are higher than the
Requirement hardware requirements.
classic DBMS.

Data Integrity
(the integrity constraints
Database Management System does Relational Database Management
that allows to maintain
not support any data integration System supports data integrity
the accuracy and
constraints or methods. constraints.
consistency in the
databases)

In DBMS, you can access only a single In RDBMS, you can access multiple
Data Access
file from a single database. data at a single time.

DBMS is more prone to data theft, and


RDBMS supports security measures
access to unauthorized users because
Data Security and is more secure than the traditional
it does not allow any data security
RDBMS.
measures.

ACID Properties (The ACID


properties are necessary DBMS does not support any ACID RDBMS supports ACID properties and
to ensure data properties. ensures no data inconsistencies.
consistency)

DBMS does not support client-server RDBMS support client-server


Data Client-Server
architecture. architecture

XML, File system, window registry, etc Oracle, MYSQL, SQL Server, etc are
Examples are some of the examples of database some of the examples of Relational
management systems. Database Management Systems.

Relational Database Management Systems and Database Management System is system software for
storing, creating and managing databases. 

However, the difference between DBMS and RDBMS is that a relational database management system is
an improvised version of DBMS and support better tools and features than DBMS. 

The data stored in DBMS is hierarchical and, in a file format with no relationship amongst the data
whereas, data stored in RDBMS is in a tabular format.  The structure plays a lot in defining the difference
between RDBMS and DBMS. 

DBMS was the first version of the software for maintaining databases and, hence, does not support
features and tools for data security, data integrity, data access, multiple-user access, or faster data
updating and fetching. RDBMS is faster, efficient, with properties that ensure no data inconsistencies and
data redundancy. 

There is no line set in stone that proves RDBMS is the best form of the database management system.
There are different database management systems but, RDBMS is better and faster than DBMS. 
Which one is better: DBMS or RDBMS?

RDBMS is the improved version of DBMS, and therefore, faster and more efficient than DBMS. 

Why is DBMS called RDBMS?

RDBMS is a type of database management system and is often confused with DBMS. However, RDBMS is
a different software with better tools and features but serving the same purpose as a DBMS. 

What are the different types of database management systems?

Database Management System is classified into four types:

 Hierarchical database: It is a tree-like structure where the data is stored in a hierarchical format.
In this database, the parent may have many children but a child should have a single parent.

 Network database: It is presented as a graph that allows many-to-many relationships. This


database allows children to have multiple children.

 Relational database: A relational database is represented as a table. The values in the columns
and rows are related to each other. It is the most widely used database because it is easy to use.

 Object-Oriented database: The data values and operations are stored as objects in this database.
All these objects have multiple relationships between them.

What is SQL?

SQL stands for Structured Query Language. It is the standard language for relational database
management systems. It is especially useful in handling organized data comprised of entities (variables)
and relations between different entities of the data. It is the primary language to interact with databases.
With the help of SQL, we can extract data from a database, modify this data and also update it whenever
there is a requirement. This query language is evergreen and is widely used across industries. For
example, if a company has records of all the details of their employees in the database. With the help of
SQL, all of this data can be queried to find out valuable insights in a short span of time.

What is the difference between SQL and MySQL?

SQL is a standard language for retrieving and manipulating structured databases. On the contrary, MySQL
is a relational database management system, like SQL Server, Oracle or IBM DB2, that is used to manage
SQL databases.

Is SQL a DBMS or RDBMS?

SQL is neither a DBMS or RDBMS. It is a programming language used to query data on either of the
database management systems. 

What are the subsets of SQL?

The following are the four significant subsets of the SQL:

 Data Definition Language: DDL is that part of SQL which defines the data structure of the
database in the initial stage when the database is about to be created. It is mainly used to create
and restructure database objects. Commands in DDL are:

o Create table

o Alter table
o Drop table

 Data Manipulation Language: DML is used to manipulate the already existing data in the
database. That is, it helps users retrieve and manipulate the data. It is used to perform
operations such as inserting data into the database through the insert command, updating the
data with the update command, and deleting the data from the database through the delete
command.

 Data Control Language: DCL is used to control access to the data in the database. DCL commands
are normally used to create objects related to user access and also to control the distribution of
privileges among users. The commands that are used in DCL are Grant and Revoke.

 Transaction Control Language: It is used to control the changes made by DML commands. It also
authorizes the statements to assemble in conjunction into logical transactions. The commands
that are used in TCL are Commit, Rollback, Savepoint, Begin, and Transaction.

What are Tables and Fields?

A table is an organized collection of data stored in the form of rows and columns. It enables users to store
and display records in the structure format. It is similar to worksheets in the spreadsheet application.
Here rows refer to the tuples, representing the simple data item, and columns are the attribute of the
data items present in a particular row. Columns can be categorized as vertical and rows as horizontal. The
columns in a table are called fields while the rows can be referred to as records.

Fields are the components to provide the structure for the table. It stores the same category of data in
the same data type. A table contains a fixed number of columns but can have any number of rows known
as the record. It is also called a column in the table of the database. It represents the attribute or
characteristics of the entity in the record.

What are Constraints in SQL?

Constraints are used to specify the rules concerning data in the table. It can be applied for single or
multiple fields in an SQL table during the creation of the table or after creating using the ALTER TABLE
command. The constraints are:

 NOT NULL - Restricts NULL value from being inserted into a column.

 CHECK - Verifies that all values in a field satisfy a condition.

 DEFAULT - Automatically assigns a default value if no value has been specified for the field.

 UNIQUE - Ensures unique values to be inserted into the field.

 INDEX - Indexes a field providing faster retrieval of records.

 PRIMARY KEY - Uniquely identifies each record in a table.

 FOREIGN KEY - Ensures referential integrity for a record in another table

What is a Primary Key?

The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain UNIQUE values and
has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or
multiple fields (columns).

CREATE TABLE Students ( /* Create table with a single field as primary key */

ID INT NOT NULL

Name VARCHAR(255)

PRIMARY KEY (ID)

);

CREATE TABLE Students ( /* Create table with multiple fields as primary key */

ID INT NOT NULL

LastName VARCHAR(255)

FirstName VARCHAR(255) NOT NULL,

CONSTRAINT PK_Student

PRIMARY KEY (ID, FirstName)

);

ALTER TABLE Students /* Set a column as primary key */

ADD PRIMARY KEY (ID);

ALTER TABLE Students /* Set multiple columns as primary key */

ADD CONSTRAINT PK_Student /*Naming a Primary Key*/

PRIMARY KEY (ID, FirstName);

What is a unique key?

A unique key is a single or combination of fields that ensure all values stores in the column will be unique.
It means a column cannot stores duplicate values. This key provides uniqueness for the column or set of
columns. For example, the email addresses and roll numbers of student's tables should be unique. It can
accept a null value but only one null value per column. It ensures the integrity of the column or group of
columns to store different values into a table.

We can define a foreign key into a table as follows:

CREATE TABLE table_name(    

    col1 datatype,    

    col2 datatype UNIQUE,    

    ...    

);  

What is a UNIQUE constraint?

A UNIQUE constraint ensures that all values in a column are different. This provides uniqueness for the
column(s) and helps identify each row uniquely. Unlike primary key, there can be multiple unique
constraints defined per table. The code syntax for UNIQUE is quite similar to that of PRIMARY KEY and
can be used interchangeably.

CREATE TABLE Students ( /* Create table with a single field as unique */

ID INT NOT NULL UNIQUE

Name VARCHAR(255)

);

CREATE TABLE Students ( /* Create table with multiple fields as unique */

ID INT NOT NULL

LastName VARCHAR(255)

FirstName VARCHAR(255) NOT NULL

CONSTRAINT PK_Student

UNIQUE (ID, FirstName)

);

ALTER TABLE Students /* Set a column as unique */

ADD UNIQUE (ID);

ALTER TABLE Students /* Set multiple columns as unique */

ADD CONSTRAINT PK_Student /* Naming a unique constraint */

UNIQUE (ID, FirstName);

What is a Foreign Key?

A FOREIGN KEY comprises of single or collection of fields in a table that essentially refers to the PRIMARY
KEY in another table. Foreign key constraint ensures referential integrity in the relation between two
tables.
The table with the foreign key constraint is labeled as the child table, and the table containing the
candidate key is labeled as the referenced or parent table.

CREATE TABLE Students ( /* Create table with foreign key - Way 1 */

ID INT NOT NULL

Name VARCHAR(255)

LibraryID INT

PRIMARY KEY (ID)

FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)

);

CREATE TABLE Students ( /* Create table with foreign key - Way 2 */

ID INT NOT NULL PRIMARY KEY

Name VARCHAR(255)
LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)

);

ALTER TABLE Students /* Add a new foreign key */

ADD FOREIGN KEY (LibraryID)

REFERENCES Library (LibraryID);

What is the difference between a primary key and a unique key?

The primary key and unique key both are essential constraints of the SQL. The main difference among
them is that the primary key identifies each record in the table. In contrast, the unique key prevents
duplicate entries in a column except for a NULL value. The following comparison chart explains it more
clearly:

Primary Key Unique Key

The primary key act as a unique identifier The unique key is also a unique identifier for records when
for each record in the table. the primary key is not present in the table.

We cannot store NULL values in the We can store NULL value in the unique key column, but only
primary key column. one NULL is allowed.

We cannot change or delete the primary


We can modify the unique key column values.
key column values.

How to create a table in SQL?

The command to create a table in sql is extremely simple:

CREATE TABLE table_name (

column1 datatype,

column2 datatype,

column3 datatype,

....

);

We will start off by giving the keywords, CREATE TABLE, then we will give the name of the table. After
that in braces, we will list out all the columns along with their datatypes.

For example, if we want to create a simple employee table:

CREATE TABLE employee (

name varchar(25),

age int,

gender varchar(25),
....

);

How to delete a table in SQL?

There are two ways to delete a table from sql: DROP and TRUNCATE. The DROP TABLE command is used
to completely delete the table from the database. This is the command:

DROP TABLE table_name;

The above command will completely delete all the data present in the table along with the table itself.

But if we want to delete only the data present in the table but not the table itself, then we will use the
truncate command:

DROP TABLE table_name ;

How to change a table name in SQL?

This is the command to change a table name in SQL:

ALTER TABLE table_name

RENAME TO new_table_name;

We will start off by giving the keywords ALTER TABLE, then we will follow it up by giving the original name
of the table, after that, we will give in the keywords RENAME TO and finally, we will give the new table
name.

For example, if we want to change the “employee” table to “employee_information”, this will be the
command:

ALTER TABLE employee

RENAME TO employee_information;

How to delete a row in SQL?

We will be using the DELETE query to delete existing rows from the table:

DELETE FROM table_name

WHERE [condition];

We will start off by giving the keywords DELETE FROM, then we will give the name of the table, after that
we will give the WHERE clause and give the condition on the basis of which we would want to delete a
row.

For example, from the employee table, if we would like to delete all the rows, where the age of the
employee is equal to 25, then this will the command:

DELETE FROM employee

WHERE [age=25];
What is a default constraint?

Constraints are used to specify some sort of rules for processing data and limiting the type of data that
can go into a table. Now, let’s understand the default constraint.

The default constraint is used to define a default value for a column so that the default value will be
added to all the new records if no other value is specified. For example, if we assign a default constraint
for the E_salary column in the below table and set the default value is 85000, then all the entries of this
column will have a default value of 85000 unless no other value has been assigned during the insertion.

What is a unique constraint?

Unique constraints ensure that all the values in a column are different. For example, if we assign a
unique constraint to the e_name column in the below table, then every entry in this column should have
a unique value.

What is the difference between SQL and PL/SQL?

The following comparison chart explains their main differences:

SQL PL/SQL

SQL is a database structured query language PL/SQL or Procedural Language/Structured Query Language
used to communicate with relational is a dialect of SQL used to enhance the capabilities of SQL.
databases. It was developed by IBM Oracle Corporation developed it in the early 90's. It uses
Corporations and first appeared in 1974. SQL as its database language.

SQL is a declarative and data-oriented


PL/SQL is a procedural and application-oriented language.
language.

SQL has no variables. PL/SQL can use variables constraints and data types.

SQL can execute only a single query at a


PL/SQL can execute a whole block of code at once.
time.

PL/SQL cannot be embedded in SQL as SQL does not


SQL query can be embedded in PL/SQL.
support any programming language and keywords.

SQL can directly interact with the database


PL/SQL cannot directly interact with the database server.
server.

SQL is like the source of data that we need


PL/SQL provides a platform where SQL data will be shown.
to display.

What is Normalization in a Database?

Normalization is used to minimize redundancy and dependency by organizing fields and table of a
database.

There are some rules of database normalization, which is commonly known as Normal From, and they
are:
 First normal form(1NF)

 Second normal form(2NF)

 Third normal form(3NF)

 Boyce-Codd normal form(BCNF)

Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be removed.

What is the primary use of Normalization?

Normalization is mainly used to add, delete or modify a field that can be made in a single table. The
primary use of Normalization is to remove redundancy and remove the insert, delete and update
distractions. Normalization breaks the table into small partitions and then links them using different
relationships to avoid the chances of redundancy.

What are the disadvantages of not performing database Normalization?

The major disadvantages are:

The occurrence of redundant terms in the database causes the waste of space in the disk.

Due to redundant terms, inconsistency may also occur. If any change is made in the data of one table but
not made in the same data of another table, then inconsistency will occur. This inconsistency will lead to
the maintenance problem and effects the ACID properties as well.

What is an inconsistent dependency?

An Inconsistent dependency refers to the difficulty of getting relevant data due to a missing or broken
path to the data. It leads users to search the data in the wrong table, resulting in an error as an output.

What is Denormalization in a Database?

Denormalization is a technique used by database administrators to optimize the efficiency of their


database infrastructure. The denormalization concept is based on Normalization, which is defined as
arranging a database into tables correctly for a particular purpose. This method allows us to add
redundant data into a normalized database to alleviate issues with database queries that merge data
from several tables into a single table. It adds redundant terms into the tables to avoid complex joins and
many other complex operations.

Denormalization doesn't mean that normalization will not be done. It is an optimization strategy that
takes place after the normalization process.

What are the various forms of Normalization?

Normal Forms are used to eliminate or reduce redundancy in database tables. The different forms are as
follows:

 First Normal Form:


A relation is in first normal form if every attribute in that relation is a single-valued attribute. If a
relation contains a composite or multi-valued attribute, it violates the first normal form. Let's
consider the following students table. Each student in the table, has a name, his/her address,
and the books they issued from the public library -

Students Table
Student  Address  Books Issued  Salutation

Amanora Park Town Until the Day I Die (Emily Carpenter), Inception (Christopher
Sara  Ms.
94  Nolan)

Ansh 62nd Sector A-10  The Alchemist (Paulo Coelho), Inferno (Dan Brown)  Mr.

24th Street Park


Sara  Beautiful Bad (Annie Ward), Woman 99 (Greer Macallister) Mrs.
Avenue 

Ansh  Windsor Street 777  Dracula (Bram Stoker) Mr.

As we can observe, the Books Issued field has more than one value per record, and to convert it into 1NF,
this has to be resolved into separate individual records for each book issued. Check the following table in
1NF form -

Students Table (1st Normal Form)

Student  Address  Books Issued  Salutation

Sara Amanora Park Town 94 Until the Day I Die (Emily Carpenter)  Ms.

Sara Amanora Park Town 94 Inception (Christopher Nolan)  Ms.

Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho)  Mr.

Ansh 62nd Sector A-10 Inferno (Dan Brown)  Mr.

Sara 24th Street Park Avenue Beautiful Bad (Annie Ward)  Mrs.

Sara 24th Street Park Avenue Woman 99 (Greer Macallister)  Mrs.

Ansh Windsor Street 777 Dracula (Bram Stoker)  Mr.

 Second Normal Form:

A relation is in second normal form if it satisfies the conditions for the first normal form and does not
contain any partial dependency. A relation in 2NF has no partial dependency, i.e., it has no non-prime
attribute that depends on any proper subset of any candidate key of the table. Often, specifying a single
column Primary Key is the solution to the problem. Examples -

Example 1 - Consider the above example. As we can observe, the Students Table in the 1NF form has a
candidate key in the form of [Student, Address] that can uniquely identify all records in the table. The
field Books Issued (non-prime attribute) depends partially on the Student field. Hence, the table is not in
2NF. To convert it into the 2nd Normal Form, we will partition the tables into two while specifying a new
Primary Key attribute to identify the individual records in the Students table. The Foreign Key constraint
will be set on the other table to ensure referential integrity.

Students Table (2nd Normal Form)

Student_ID  Student Address  Salutation

1 Sara Amanora Park Town 94  Ms.

2 Ansh 62nd Sector A-10  Mr.

3 Sara 24th Street Park Avenue  Mrs.


Student_ID  Student Address  Salutation

4 Ansh Windsor Street 777  Mr.

Books Table (2nd Normal Form)

Student_ID  Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)

WX -> Y [W and X together determine Y]

XY -> Z [X and Y together determine Z]

Here, WX is the only candidate key and there is no partial dependency, i.e., any proper subset of WX
doesn’t determine any non-prime attribute in the relation.

 Third Normal Form

A relation is said to be in the third normal form, if it satisfies the conditions for the second normal form
and there is no transitive dependency between the non-prime attributes, i.e., all non-prime attributes
are determined only by the candidate keys of the relation and not by any other non-prime attribute.

Example 1 - Consider the Students Table in the above example. As we can observe, the Students Table in
the 2NF form has a single candidate key Student_ID (primary key) that can uniquely identify all records in
the table. The field Salutation (non-prime attribute), however, depends on the Student Field rather than
the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal Form, we will once
again partition the tables into two while specifying a new Foreign Key constraint to identify the
salutations for individual records in the Students table. The Primary Key constraint for the same will be
set on the Salutations table to identify each record uniquely.

Students Table (3rd Normal Form)

Student_ID  Student  Address  Salutation_ID

1 Sara Amanora Park Town 94  1

2 Ansh 62nd Sector A-10  2

3 Sara 24th Street Park Avenue  3

4 Ansh Windsor Street 777  1

Books Table (3rd Normal Form)


Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Salutations Table (3rd Normal Form)

Salutation_ID Salutation

1 Ms.

2 Mr.

3 Mrs.

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)

P -> QR [P together determine C] 

RS -> T [B and C together determine D] 

Q -> S 

T -> P 

For the above relation to exist in 3NF, all possible candidate keys in the above relation should be {P, RS,
QR, T}.

 Boyce-Codd Normal Form

A relation is in Boyce-Codd Normal Form if satisfies the conditions for third normal form and for every
functional dependency, Left-Hand-Side is super key. In other words, a relation in BCNF has non-trivial
functional dependencies in form X –> Y, such that X is always a super key. For example - In the above
example, Student_ID serves as the sole unique identifier for the Students Table and Salutation_ID for the
Salutations Table, thus these tables exist in BCNF. The same cannot be said for the Books Table and there
can be several books with common Book Names and the same Student_ID

What are the different types of SQL operators?

Operators are the special keywords or special characters reserved for performing particular operations.
They are also used in SQL queries. We can primarily use these operators within the WHERE clause of SQL
commands. It's a part of the command to filters data based on the specified condition. The SQL operators
can be categorized into the following types:
 Arithmetic operators: These operators are used to perform mathematical operations on
numerical data. The categories of this operators are addition (+), subtraction (-), multiplication
(*), division (/), remainder/modulus (%), etc.

 Logical operators: These operators evaluate the expressions and return their results in True or
False. This operator includes ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR,
UNIQUE.

 Comparison operators: These operators are used to perform comparisons of two values and
check whether they are the same or not. It includes equal to (=), not equal to (!= or <>), less than
(<), greater than (>), less than or equal to (<=), greater than or equal to (>=), not less than (!<),
not greater than (!>), etc.

 Bitwise operators: It is used to do bit manipulations between two expressions of integer type. It
first performs conversion of integers into binary bits and then applied operators such as AND (&
symbol), OR (|, ^), NOT (~), etc.

 Compound operators: These operators perform operations on a variable before setting the
variable's result to the operation's result. It includes Add equals (+=), subtract equals (-=),
multiply equals (*=), divide equals (/=), modulo equals (%=), etc.

 String operators: These operators are primarily used to perform concatenation and pattern
matching of strings. It includes + (String concatenation), += (String concatenation assignment), %
(Wildcard), [] (Character(s) matches), [^] (Character(s) not to match), _ (Wildcard match one
character), etc.

What is a Join? List its different types.

The SQL Join clause is used to combine records (rows) from two or more tables in a SQL database based
on a related column between the two.

There are four different types of JOINs in SQL:

 (INNER) JOIN: Retrieves records that have matching values in both tables involved in the join.
This is the widely used join for queries.

SELECT *

FROM Table_A

JOIN Table_B;

SELECT *

FROM Table_A

INNER JOIN Table_B;

 LEFT (OUTER) JOIN: Retrieves all the records/rows from the left and the matched records/rows
from the right table.

SELECT *

FROM Table_A A

LEFT JOIN Table_B B


ON A.col = B.col;

 RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the matched
records/rows from the left table.

SELECT *

FROM Table_A A

RIGHT JOIN Table_B B

ON A.col = B.col;

 FULL (OUTER) JOIN: Retrieves all the records where there is a match in either the left or right
table.

SELECT *

FROM Table_A A

FULL JOIN Table_B B

ON A.col = B.col;

What is a Self-Join?

A self JOIN is a case of regular join where a table is joined to itself based on some relation between its
own column(s). Self-join uses the INNER JOIN or LEFT JOIN clause and a table alias is used to assign
different names to the table within the query.

SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",

B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"

FROM employee A, employee B

WHERE A.emp_sup = B.emp_id;

What is a Cross-Join?

Cross join can be defined as a cartesian product of the two tables included in the join. The table after join
contains the same number of rows as in the cross-product of the number of rows in the two tables. If a
WHERE clause is used in cross join then the query will work like an INNER JOIN.

SELECT stu.name, sub.subject

FROM students AS stu

CROSS JOIN subjects AS sub;

What is an Index? Explain its different types.

A database index is a data structure that provides a quick lookup of data in a column or columns of a
table. It enhances the speed of operations accessing data from a database table at the cost of additional
writes and memory to maintain the index data structure.

CREATE INDEX index_name /* Create Index */

ON table_name (column_1, column_2);


DROP INDEX index_name; /* Drop Index */

There are different types of indexes that can be created for different purposes:

 Unique and Non-Unique Index:

Unique indexes are indexes that help maintain data integrity by ensuring that no two rows of data in a
table have identical key values. Once a unique index has been defined for a table, uniqueness is enforced
whenever keys are added or changed within the index.

CREATE UNIQUE INDEX myIndex

ON students (enroll_no);

Non-unique indexes, on the other hand, are not used to enforce constraints on the tables with which
they are associated. Instead, non-unique indexes are used solely to improve query performance by
maintaining a sorted order of data values that are used frequently.

 Clustered and Non-Clustered Index:

Clustered indexes are indexes whose order of the rows in the database corresponds to the order of the
rows in the index. This is why only one clustered index can exist in a given table, whereas, multiple non-
clustered indexes can exist in the table.

The only difference between clustered and non-clustered indexes is that the database manager attempts
to keep the data in the database in the same order as the corresponding keys appear in the clustered
index.

Clustering indexes can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.

What is the difference between Clustered and Non-clustered index?

As explained above, the differences can be broken down into three small factors -

 Clustered index modifies the way records are stored in a database based on the indexed column.
A non-clustered index creates a separate entity within the table which references the original
table.

 Clustered index is used for easy and speedy retrieval of data from the database, whereas,
fetching records from the non-clustered index is relatively slower.

 In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.

What is Data Integrity?

Data Integrity is the assurance of accuracy and consistency of data over its entire life-cycle and is a critical
aspect of the design, implementation, and usage of any system which stores, processes, or retrieves data.
It also defines integrity constraints to enforce business rules on the data when it is entered into an
application or a database.

What is a Query?
A query is a request for data or information from a database table or combination of tables. A database
query can be either a select query or an action query.

SELECT fname, lname /* select query */

FROM myDb.students

WHERE student_id = 1;

UPDATE myDB.students /* action query */

SET fname = 'Captain', lname = 'America'

WHERE student_id = 1;

What is a Subquery? What are its types?

A subquery is a query within another query, also known as a nested query or inner query. It is used to
restrict or enhance the data to be queried by the main query, thus restricting or enhancing the output of
the main query respectively. For example, here we fetch the contact information for students who have
enrolled for the maths subject:

SELECT name, email, mob, address

FROM myDb.contacts

WHERE roll_no IN (

SELECT roll_no

FROM myDb.students

WHERE subject = 'Maths');

There are two types of subquery - Correlated and Non-Correlated.

 A correlated subquery cannot be considered as an independent query, but it can refer to the
column in a table listed in the FROM of the main query.

 A non-correlated subquery can be considered as an independent query and the output of the
subquery is substituted in the main query.

What is the SELECT statement?

SELECT operator in SQL is used to select data from a database. The data returned is stored in a result
table, called the result-set.

SELECT * FROM myDB.students;

What are some common clauses used with SELECT query in SQL?

Some common SQL clauses used in conjuction with a SELECT query are as follows:

 WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.

 ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending (ASC) or
descending order (DESC).

SELECT *

FROM myDB.students
WHERE graduation_year = 2019

ORDER BY studentID DESC;

 GROUP BY clause in SQL is used to group records with identical data and can be used in
conjunction with some aggregation functions to produce summarized results from the database.

 HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since the WHERE clause cannot filter aggregated records.

SELECT COUNT(studentId), country

FROM myDB.students

WHERE country != "INDIA"

GROUP BY country

HAVING COUNT(studentID) > 5;

What are UNION, MINUS and INTERSECT commands?

The UNION operator combines and returns the result-set retrieved by two or more SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained by the second
SELECT query from the result-set obtained by the first SELECT query and then return the filtered results
from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT statements where
records from one match the other and then returns this intersection of result-sets.

Certain conditions need to be met before executing either of the above statements in SQL -

 Each SELECT statement within the clause must have the same number of columns

 The columns must also have similar data types

 The columns in each SELECT statement should necessarily have the same order

SELECT name FROM Students /* Fetch the union of queries */

UNION

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch the union of queries with duplicates*/

UNION ALL

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */

MINUS /* that aren't present in contacts */

SELECT name FROM Contacts;

SELECT name FROM Students /* Fetch names from students */

INTERSECT /* that are present in contacts as well */


SELECT name FROM Contacts;

What is Cursor? How to use a Cursor?

A database cursor is a control structure that allows for the traversal of records in a database. Cursors, in
addition, facilitates processing after traversal, such as retrieval, addition, and deletion of database
records. They can be viewed as a pointer to one row in a set of rows.

Working with SQL Cursor:

1. DECLARE a cursor after any variable declaration. The cursor declaration must always be
associated with a SELECT Statement.

2. Open cursor to initialize the result set. The OPEN statement must be called before fetching rows
from the result set.

3. FETCH statement to retrieve and move to the next row in the result set.

4. Call the CLOSE statement to deactivate the cursor.

5. Finally use the DEALLOCATE statement to delete the cursor definition and release the associated
resources.

DECLARE @name VARCHAR(50) /* Declare All Required Variables */

DECLARE db_cursor CURSOR FOR /* Declare Cursor Name*/

SELECT name

FROM myDB.students

WHERE parent_name IN ('Sara', 'Ansh')

OPEN db_cursor /* Open cursor and Fetch data into @name */

FETCH next

FROM db_cursor

INTO @name

CLOSE db_cursor /* Close the cursor and deallocate the resources */

DEALLOCATE db_cursor

What are Entities and Relationships?

Entity: An entity can be a real-world object, either tangible or intangible, that can be easily identifiable.
For example, in a college database, students, professors, workers, departments, and projects can be
referred to as entities. Each entity has some associated properties that provide it an identity.

Relationships: Relations or links between entities that have something to do with each other. For
example - The employee's table in a company's database can be associated with the salary table in the
same database.

List the different types of relationships in SQL.

 One-to-One - This can be defined as the relationship between two tables where each record in
one table is associated with the maximum of one record in the other table.
 One-to-Many & Many-to-One - This is the most commonly used relationship where a record in a
table is associated with multiple records in the other table.

 Many-to-Many - This is used in cases when multiple instances on both sides are needed for
defining a relationship.

 Self-Referencing Relationships - This is used when a table needs to define a relationship with
itself.

What is an Alias in SQL?

An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a temporary name assigned
to the table or table column for the purpose of a particular SQL query. In addition, aliasing can be
employed as an obfuscation technique to secure the real names of database fields. A table alias is also
called a correlation name.

An alias is represented explicitly by the AS keyword but in some cases, the same can be performed
without it as well. Nevertheless, using the AS keyword is always a good practice.

SELECT A.emp_name AS "Employee" /* Alias using AS keyword */

B.emp_name AS "Supervisor"

FROM employee A, employee B /* Alias without AS keyword */

WHERE A.emp_sup = B.emp_id;

What is a View?

A view in SQL 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.

What are the TRUNCATE, DELETE and DROP statements?

DELETE statement is used to delete rows from a table.

DELETE FROM Candidates

WHERE CandidateId > 1000;

TRUNCATE command is used to delete all the rows from the table and free the space containing the
table.

TRUNCATE TABLE Candidates;

DROP command is used to remove an object from the database. If you drop a table, all the rows in the
table are deleted and the table structure is removed from the database.

DROP TABLE Candidates;

What is the difference between DROP and TRUNCATE statements?

If a table is dropped, all things associated with the tables are dropped as well. This includes - the
relationships defined on the table with other tables, the integrity checks and constraints, access privileges
and other grants that the table has. To create and use the table again in its original form, all these
relations, checks, constraints, privileges and relationships need to be redefined. However, if a table is
truncated, none of the above problems exist and the table retains its original structure.
What is the difference between DELETE and TRUNCATE statements?

The TRUNCATE command is used to delete all the rows from the table and free the space containing the
table.
The DELETE command deletes only the rows from the table based on the condition given in the where
clause or deletes all the rows from the table if no condition is specified. But it does not free the space
containing the table.

What are Aggregate and Scalar functions?

An aggregate function performs operations on a collection of values to return a single scalar value.
Aggregate functions are often used with the GROUP BY and HAVING clauses of the SELECT statement.
Following are the widely used SQL aggregate functions:

 AVG() - Calculates the mean of a collection of values.

 COUNT() - Counts the total number of records in a specific table or view.

 MIN() - Calculates the minimum of a collection of values.

 MAX() - Calculates the maximum of a collection of values.

 SUM() - Calculates the sum of a collection of values.

 FIRST() - Fetches the first element in a collection of values.

 LAST() - Fetches the last element in a collection of values.

Note: All aggregate functions described above ignore NULL values except for the COUNT function.

A scalar function returns a single value based on the input value. Following are the widely used SQL scalar
functions:

 LEN() - Calculates the total length of the given field (column).

 UCASE() - Converts a collection of string values to uppercase characters.

 LCASE() - Converts a collection of string values to lowercase characters.

 MID() - Extracts substrings from a collection of string values in a table.

 CONCAT() - Concatenates two or more strings.

 RAND() - Generates a random collection of numbers of a given length.

 ROUND() - Calculates the round-off integer value for a numeric field (or decimal point values).

 NOW() - Returns the current date & time.

 FORMAT() - Sets the format to display a collection of values.

What is User-defined function? What are its various types?

The user-defined functions in SQL are like functions in any other programming language that accept
parameters, perform complex calculations, and return a value. They are written to use the logic
repetitively whenever required. There are two types of SQL user-defined functions:

 Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
 Table-Valued Functions: User-defined table-valued functions return a table as output.

o Inline: returns a table data type based on a single SELECT statement.

o Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT


statements can be used inside the function body.

What is OLTP?

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting
transaction-oriented programs. An essential attribute of an OLTP system is its ability to maintain
concurrency. To avoid single points of failure, OLTP systems are often decentralized. These systems are
usually designed for a large number of users who conduct short transactions. Database queries are
usually simple, require sub-second response times, and return relatively few records. Here is an insight
into the working of an OLTP system

What are the differences between OLTP and OLAP?

OLTP stands for Online Transaction Processing, is a class of software applications capable of supporting
transaction-oriented programs. An important attribute of an OLTP system is its ability to maintain
concurrency. OLTP systems often follow a decentralized architecture to avoid single points of failure.
These systems are generally designed for a large audience of end-users who conduct short transactions.
Queries involved in such databases are generally simple, need fast response times, and return relatively
few records. A number of transactions per second acts as an effective measure for such systems.

OLAP stands for Online Analytical Processing, a class of software programs that are characterized by the
relatively low frequency of online transactions. Queries are often too complex and involve a bunch of
aggregations. For OLAP systems, the effectiveness measure relies highly on response time. Such systems
are widely used for data mining or maintaining aggregated, historical data, usually in multi-dimensional
schemas.

What is Collation? What are the different types of Collation Sensitivity?

Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the
correct character sequence are used to sort the character data. It incorporates options for specifying case
sensitivity, accent marks, kana character types, and character width. Below are the different types of
collation sensitivity:

 Case sensitivity: A and a are treated differently.

 Accent sensitivity: a and á are treated differently.

 Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated differently.

 Width sensitivity: Same character represented in single-byte (half-width) and double-byte (full-
width) are treated differently.

What is a Stored Procedure?

A stored procedure is a subroutine available to applications that access a relational database


management system (RDBMS). Such procedures are stored in the database data dictionary. The sole
disadvantage of stored procedure is that it can be executed nowhere except in the database and occupies
more memory in the database server. It also provides a sense of security and functionality as users who
can't access the data directly can be granted access via stored procedures.

DELIMITER $$

CREATE PROCEDURE FetchAllStudents()

BEGIN

SELECT * FROM myDB.students;

END $$

DELIMITER ;

What is a Recursive Stored Procedure?

A stored procedure that calls itself until a boundary condition is reached, is called a recursive stored
procedure. This recursive function helps the programmers to deploy the same set of code several times
as and when required. Some SQL programming languages limit the recursion depth to prevent an infinite
loop of procedure calls from causing a stack overflow, which slows down the system and may lead to
system crashes.

DELIMITER $$ /* Set a new delimiter => $$ */

CREATE PROCEDURE calctotal( /* Create the procedure */

IN number INT, /* Set Input and Ouput variables */

OUT total INT

) BEGIN

DECLARE score INT DEFAULT NULL; /* Set the default value => "score" */

SELECT awards FROM achievements /* Update "score" via SELECT query */

WHERE id = number INTO score;

IF score IS NULL THEN SET total = 0; /* Termination condition */

ELSE

CALL calctotal(number+1); /* Recursive call */

SET total = total + score; /* Action after recursion */

END IF;

END $$ /* End of procedure */

DELIMITER ; /* Reset the delimiter */

How to create empty tables with the same structure as another table?

Creating empty tables with the same structure can be done smartly by fetching the records of one table
into a new table using the INTO operator while fixing a WHERE clause to be false for all records. Hence,
SQL prepares the new table with a duplicate structure to accept the fetched records but since no records
get fetched due to the WHERE clause in action, nothing is inserted into the new table.

SELECT * INTO Students_copy

FROM Students WHERE 1 = 2;

What is Pattern Matching in SQL?

SQL pattern matching provides for pattern search in data if you have no clue as to what that word should
be. This kind of SQL query uses wildcards to match a string pattern, rather than writing the exact word.
The LIKE operator is used in conjunction with SQL Wildcards to fetch the required information.

 Using the % wildcard to perform a simple search

The % wildcard matches zero or more characters of any type and can be used to define wildcards both
before and after the pattern. Search a student in your database with first name beginning with the letter
K:

SELECT *

FROM students

WHERE first_name LIKE 'K%'

 Omitting the patterns using the NOT keyword

Use the NOT keyword to select records that don't match the pattern. This query returns all students
whose first name does not begin with K.

SELECT *

FROM students

WHERE first_name NOT LIKE 'K%'

 Matching a pattern anywhere using the % wildcard twice

Search for a student in the database where he/she has a K in his/her first name.

SELECT *

FROM students

WHERE first_name LIKE '%Q%'

 Using the _ wildcard to match pattern at a specific position

The _ wildcard matches exactly one character of any type. It can be used in conjunction with % wildcard.
This query fetches all students with letter K at the third position in their first name.

SELECT *

FROM students

WHERE first_name LIKE '__K%'

 Matching patterns for a specific length

The _ wildcard plays an important role as a limitation when it matches exactly one character. It limits the
length and position of the matched results. For example - 
SELECT * /* Matches first names with three or more letters */

FROM students

WHERE first_name LIKE '___%'

SELECT * /* Matches first names with exactly four characters */

FROM students

WHERE first_name LIKE '____'

How to create empty tables with the same structure as another table?

To create empty tables:


Using the INTO operator to fetch the records of one table into a new table while setting a WHERE clause
to false for all entries, it is possible to create empty tables with the same structure. As a result, SQL
creates a new table with a duplicate structure to accept the fetched entries, but nothing is stored into the
new table since the WHERE clause is active.

What is PostgreSQL?

In 1986, a team lead by Computer Science Professor Michael Stonebraker created PostgreSQL under the
name Postgres. It was created to aid developers in the development of enterprise-level applications by
ensuring data integrity and fault tolerance in systems. PostgreSQL is an enterprise-level, versatile,
resilient, open-source, object-relational database management system that supports variable workloads
and concurrent users. The international developer community has constantly backed it. PostgreSQL has
achieved significant appeal among developers because to its fault-tolerant characteristics.
It’s a very reliable database management system, with more than two decades of community work to
thank for its high levels of resiliency, integrity, and accuracy. Many online, mobile, geospatial, and
analytics applications utilise PostgreSQL as their primary data storage or data warehouse.

What are SQL comments?

SQL Comments are used to clarify portions of SQL statements and to prevent SQL statements from being
executed. Comments are quite important in many programming languages. The comments are not
supported by a Microsoft Access database. As a result, the Microsoft Access database is used in the
examples in Mozilla Firefox and Microsoft Edge.
Single Line Comments: It starts with two consecutive hyphens (–).
Multi-line Comments: It starts with /* and ends with */.

What is the usage of the NVL() function?

You may use the NVL function to replace null values with a default value. The function returns the value
of the second parameter if the first parameter is null. If the first parameter is anything other than null, it
is left alone.

This function is used in Oracle, not in SQL and MySQL. Instead of NVL() function, MySQL have IFNULL()
and SQL Server have ISNULL() function.

Explain character-manipulation functions? Explains its different types in SQL.


Change, extract, and edit the character string using character manipulation routines. The function will do
its action on the input strings and return the result when one or more characters and words are supplied
into it.

The character manipulation functions in SQL are as follows:

A) CONCAT (joining two or more values): This function is used to join two or more values together. The
second string is always appended to the end of the first string.

B) SUBSTR: This function returns a segment of a string from a given start point to a given endpoint.

C) LENGTH: This function returns the length of the string in numerical form, including blank spaces.

D) INSTR: This function calculates the precise numeric location of a character or word in a string.

E) LPAD: For right-justified values, it returns the padding of the left-side character value.

F) RPAD: For a left-justified value, it returns the padding of the right-side character value.

G) TRIM: This function removes all defined characters from the beginning, end, or both ends of a string. It
also reduced the amount of wasted space.

H) REPLACE: This function replaces all instances of a word or a section of a string (substring) with the
other string value specified.

Write the SQL query to get the third maximum salary of an employee from a table named employees.

Employee table

employee_name salary

A 24000

C 34000

D 55000

E 75000

F 21000

G 40000

H 50000

SELECT * FROM(

SELECT employee_name, salary, DENSE_RANK() 

OVER(ORDER BY salary DESC)r FROM Employee) 

WHERE r=&n;

To find 3rd highest salary set n = 3

What is the difference between the RANK() and DENSE_RANK() functions?


The RANK() function in the result set defines the rank of each row within your ordered partition. If both
rows have the same rank, the next number in the ranking will be the previous rank plus a number of
duplicates. If we have three records at rank 4, for example, the next level indicated is 7.

The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the provided
column value, with no gaps. It always indicates a ranking in order of precedence. This function will assign
the same rank to the two rows if they have the same rank, with the next rank being the next consecutive
number. If we have three records at rank 4, for example, the next level indicated is 5.

What are Tables and Fields?

A table is a collection of data components organized in rows and columns in a relational database. A table
can also be thought of as a useful representation of relationships. The most basic form of data storage is
the table. An example of an Employee table is shown below.

ID Name Department Salary

1 Rahul Sales 24000

2 Rohini Marketing 34000

3 Shylesh Sales 24000

4 Tarun Analytics 30000

A Record or Row is a single entry in a table. In a table, a record represents a collection of connected data.
The Employee table, for example, has four records.

A table is made up of numerous records (rows), each of which can be split down into smaller units called
Fields(columns). ID, Name, Department, and Salary are the four fields in the Employee table above.

What is schema in SQL Server?

A schema is a visual representation of the database that is logical. It builds and specifies the relationships
among the database’s numerous entities. It refers to the several kinds of constraints that may be applied
to a database. It also describes the various data kinds. It may also be used on Tables and Views.

Schemas come in a variety of shapes and sizes. Star schema and Snowflake schema are two of the most
popular. The entities in a star schema are represented in a star form, whereas those in a snowflake
schema are shown in a snowflake shape.
Any database architecture is built on the foundation of schemas.

How to create a temp table in SQL Server?

Temporary tables are created in TempDB and are erased automatically after the last connection is closed.
We may use Temporary Tables to store and process interim results. When we need to store temporary
data, temporary tables come in handy.

The following is the syntax for creating a Temporary Table:

CREATE TABLE #Employee (id INT, name VARCHAR(25))


INSERT INTO #Employee VALUES (01, ‘Ashish’), (02, ‘Atul’)
Let’s move to the next question in this SQL Interview Questions.

hat is the case when in SQL Server?

The CASE statement is used to construct logic in which one column’s value is determined by the values of
other columns.

At least one set of WHEN and THEN commands makes up the SQL Server CASE Statement. The condition
to be tested is specified by the WHEN statement. If the WHEN condition returns TRUE, the THEN
sentence explains what to do.

When none of the WHEN conditions return true, the ELSE statement is executed. The END keyword
brings the CASE statement to a close.

CASE

WHEN condition1 THEN result1

WHEN condition2 THEN result2

WHEN conditionN THEN resultN

ELSE result

END;

What is the difference between NOW() and CURRENT_DATE()?


NOW() returns a constant time that indicates the time at which the statement began to execute. (Within
a stored function or trigger, NOW() returns the time at which the function or triggering statement began
to execute.
The simple difference between NOW() and CURRENT_DATE() is that NOW() will fetch the current date
and time both in format ‘YYYY-MM_DD HH:MM:SS’ while CURRENT_DATE() will fetch the date of the
current day ‘YYYY-MM_DD’.

How to remove duplicate rows in SQL?

If the SQL table has duplicate rows, the duplicate rows must be removed.

Let’s assume the following table as our dataset:

ID Name Age

1 A 21

2 B 23

2 B 23

4 D 22

5 E 25

6 G 26

5 E 25
The following SQL query removes the duplicate ids from the  table:

DELETE FROM table WHERE ID IN (


SELECT 
ID, COUNT(ID) 
FROM   table
GROUP BY  ID
HAVING 
COUNT (ID) > 1); 

How to create a stored procedure using SQL Server?

A stored procedure is a piece of prepared SQL code that you can save and reuse again and over.
So, if you have a SQL query that you create frequently, save it as a stored procedure and then call it to
run it.
You may also supply parameters to a stored procedure so that it can act based on the value(s) of the
parameter(s) given.

Stored Procedure Syntax


CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
What is Database Black Box Testing?

Black Box Testing is a software testing approach that involves testing the functions of software
applications without knowing the internal code structure, implementation details, or internal routes.
Black Box Testing is a type of software testing that focuses on the input and output of software
applications and is totally driven by software requirements and specifications. Behavioral testing is
another name for it.

What are the different types of SQL sandbox?

Databases Training

SQL Sandbox is a secure environment within SQL Server where untrusted programmes can be run. There
are three different types of SQL sandboxes:

Safe Access Sandbox: In this environment, a user may execute SQL activities like as building stored
procedures, triggers, and so on, but they can’t access the memory or create files.

Sandbox for External Access: Users can access files without having the ability to alter memory allocation.

Unsafe Access Sandbox: This contains untrustworthy code that allows a user to access memory.

Where MyISAM table is stored?

Prior to the introduction of MySQL 5.5 in December 2009, MyISAM was the default storage engine for
MySQL relational database management system versions.  It’s based on the older ISAM code, but it
comes with a lot of extra features. Each MyISAM table is split into three files on disc (if it is not
partitioned). The file names start with the table name and end with an extension that indicates the file
type. The table definition is stored in a.frm file, however this file is not part of the MyISAM engine;
instead, it is part of the server. The data file’s suffix is.MYD (MYData). The index file’s extension is.MYI
(MYIndex). If you lose your index file, you may always restore it by recreating indexes.

How to find the nth highest salary in SQL?


The most typical interview question is to find the Nth highest pay in a table. This work can be
accomplished using the dense rank() function.
Employee table

employee_name salary

A 24000

C 34000

D 55000

E 75000

F 21000

G 40000

H 50000

 
SELECT * FROM(
SELECT employee_name, salary, DENSE_RANK() 
OVER(ORDER BY salary DESC)r FROM Employee) 
WHERE r=&n;
To find to the 2nd highest salary set n = 2
To find 3rd highest salary set n = 3 and so on.
What do you mean by table and field in SQL?

A table refers to a collection of data in an organised manner in form of rows and columns. A field refers
to the number of columns in a table. For example:

Table: StudentInformation
Field: Stu Id, Stu Name, Stu Marks

What is the difference between CHAR and VARCHAR2 datatype in SQL?

Both Char and Varchar2 are used for characters datatype but varchar2 is used for character strings of
variable length whereas Char is used for strings of fixed length. For example, char(10) can only store 10
characters and will not be able to store a string of any other length whereas varchar2(10) can store any
length i.e 6,8,2 in this variable.

What is the difference between DELETE and TRUNCATE statements?


DELETE vs TRUNCATE

DELETE TRUNCATE

Truncate is used to delete all the rows from a


Delete command is used to delete a row in a table.
table.

You can rollback data after using delete statement. You cannot rollback data.

It is a DML command. It is a DDL command.

It is slower than truncate statement. It is faster.

What do you understand by query optimization?

The phase that identifies a plan for evaluation query which has the least estimated cost is known as query
optimization.

The advantages of query optimization are as follows:

 The output is provided faster

 A larger number of queries can be executed in less time

 Reduces time and space complexity

What is the difference between the RANK() and DENSE_RANK() functions?

The RANK() function in the result set defines the rank of each row within your ordered partition. If both
rows have the same rank, the next number in the ranking will be the previous rank plus a number of
duplicates. If we have three records at rank 4, for example, the next level indicated is 7.

The DENSE_RANK() function assigns a distinct rank to each row within a partition based on the provided
column value, with no gaps. It always indicates a ranking in order of precedence. This function will assign
the same rank to the two rows if they have the same rank, with the next rank being the next consecutive
number. If we have three records at rank 4, for example, the next level indicated is 5.

What is SQL Injection?

SQL injection is a sort of flaw in website and web app code that allows attackers to take control of back-
end processes and access, retrieve, and delete sensitive data stored in databases. In this approach,
malicious SQL statements are entered into a database entry field, and the database becomes exposed to
an attacker once they are executed. By utilising data-driven apps, this strategy is widely utilised to get
access to sensitive data and execute administrative tasks on databases. SQLi attack is another name for it.

The following are some examples of SQL injection:

 Getting access to secret data in order to change a SQL query to acquire the desired results.

 UNION attacks are designed to steal data from several database tables.
 Examine the database to get information about the database’s version and structure

How many Aggregate functions are available in SQL?

SQL aggregate functions provide information about a database’s data. AVG, for example, returns the
average of a database column’s values.

SQL provides seven (7) aggregate functions, which are given below:

AVG(): returns the average value from specified columns.


COUNT(): returns the number of table rows, including rows with null values.
MAX(): returns the largest value among the group.
MIN(): returns the smallest value among the group.
SUM(): returns the total summed values(non-null) of the specified column.
FIRST(): returns the first value of an expression.
LAST(): returns the last value of an expression.

What is the default ordering of data using the ORDER BY clause? How could it be changed?

The ORDER BY clause in MySQL can be used without the ASC or DESC modifiers. The sort order is preset
to ASC or ascending order when this attribute is absent from the ORDER BY clause.

How do we use the DISTINCT statement? What is its use?

The SQL DISTINCT keyword is combined with the SELECT query to remove all duplicate records and return
only unique records. There may be times when a table has several duplicate records.
The DISTINCT clause in SQL is used to eliminate duplicates from a SELECT statement’s result set.

What are the syntax and use of the COALESCE function?

From a succession of expressions, the COALESCE function returns the first non-NULL value. The
expressions are evaluated in the order that they are supplied, and the function’s result is the first non-
null value. Only if all of the inputs are null does the COALESCE method return NULL.

The syntax of COALESCE function is COALESCE (exp1, exp2, …. expn) 

 What is the ACID property in a database?

ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data
transactions are processed reliably in a database system. 

 Atomicity: Atomicity refers to the transactions that are completely done or failed where
transaction refers to a single logical operation of a data. It means if one part of any transaction
fails, the entire transaction fails and the database state is left unchanged.

 Consistency: Consistency ensures that the data must meet all the validation rules. In simple
words,  you can say that your transaction never leaves the database without completing its state.

 Isolation: The main goal of isolation is concurrency control.

 Durability: Durability means that if a transaction has been committed, it will occur whatever may
come in between such as power loss, crash or any sort of error.

What do you mean by “Trigger” in SQL?


Trigger in SQL is are a special type of stored procedures that are defined to execute automatically in place
or after data modifications. It allows you to execute a batch of code when an insert, update or any other
query is executed against a specific table.

What are the different operators available in SQL?

There are three operators available in SQL, namely:

1. Arithmetic Operators

2. Logical Operators

3. Comparison Operators

Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this
technology, you can opt for structured training from edureka! 

Are NULL values same as that of zero or a blank space? 

A NULL value is not at all same as that of zero or a blank space. NULL value represents a value which is
unavailable, unknown, assigned or not applicable whereas a zero is a number and blank space is a
character.

What is the difference between cross join and natural join?

The cross join produces the cross product or Cartesian product of two tables whereas the natural join is
based on all the columns having the same name and data types in both the tables.

What is subquery in SQL?

A subquery is a query inside another query where a query is defined to retrieve data or information back
from the database. In a subquery, the outer query is called as the main query whereas the inner query is
called subquery. Subqueries are always executed first and the result of the subquery is passed on to the
main query. It can be nested inside a SELECT, UPDATE or any other query. A subquery can also use any
comparison operators such as >,< or =.

What are the different types of a subquery?

There are two types of subquery namely, Correlated and Non-Correlated.

Correlated subquery: These are queries which select the data from a table referenced in the outer query.
It is not considered as an independent query as it refers to another table and refers the column in a table.

Non-Correlated subquery: This query is an independent query where the output of subquery is
substituted in the main query.

List the ways to get the count of records in a table?

To count the number of records in a table in SQL, you can use the below commands:

SELECT * FROM table1

SELECT COUNT(*) FROM table1

SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2

Write a SQL query to find the names of employees that begin with ‘A’?
SELECT * FROM Table_name WHERE EmpName like 'A%'

Write a SQL query to get the third-highest salary of an employee from employee_table?

SELECT TOP 1 salary

FROM(

SELECT TOP 3 salary

FROM employee_table

ORDER BY salary DESC) AS emp

ORDER BY salary ASC;

What is the need for group functions in SQL? 

Group functions work on the set of rows and return one result per group. Some of the commonly used
group functions are: AVG, COUNT, MAX, MIN, SUM, VARIANCE.

What is a Relationship and what are they?

Relation or links are between entities that have something to do with each other. Relationships are
defined as the connection between the tables in a database. There are various relationships, namely:

 One to One Relationship.

 One to Many Relationship.

 Many to One Relationship.

 Self-Referencing Relationship.

How can you insert NULL values in a column while inserting the data?

NULL values in SQL can be inserted in the following ways:

 Implicitly by omitting column from column list.

 Explicitly by specifying NULL keyword in the VALUES clause

What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition
operator is used to check for values contained in a specific set of values.

 Example of BETWEEN:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;

Example of IN:

SELECT * FROM students where ROLL_NO IN (8,15,25);

Why are SQL functions used?

SQL functions are used for the following purposes:

 To perform some calculations on the data


 To modify individual data items

 To manipulate the output

 To format dates and numbers

 To convert the data types

What is the need for MERGE statement?

This statement allows conditional update or insertion of data into a table. It performs an UPDATE if a row
exists, or an INSERT if the row does not exist.

What do you mean by recursive stored procedure?

Recursive stored procedure refers to a stored procedure which calls by itself until it reaches some
boundary condition. This recursive function or procedure helps the programmers to use the same set of
code n number of times.

What is CLAUSE in SQL?

SQL clause helps to limit the result set by providing a condition to the query. A clause helps to filter the
rows from the entire set of records.

For example – WHERE, HAVING clause.

What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause and
whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to
each row before they are a part of the GROUP BY function in a query.

List the ways in which  Dynamic SQL can be executed?

Following are the ways in which dynamic SQL can be executed:

 Write a query with parameters.

 Using EXEC.

 Using sp_executesql.

What are the various levels of constraints?

Constraints are the representation of a column to enforce data entity and consistency. There are two
levels  of a constraint, namely:

 column level constraint

 table level constraint

How can you fetch common records from two tables?

You can fetch common records from two tables using INTERSECT. For example:

Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam

List some case manipulation functions in SQL?


There are three case manipulation functions in SQL, namely:

 LOWER: This function returns the string in lowercase. It takes a string as an argument and returns
it by converting it into lower case. Syntax:

LOWER(‘string’)

 UPPER: This function returns the string in uppercase. It takes a string as an argument and returns
it by converting it into uppercase. Syntax:

UPPER(‘string’)

 INITCAP: This function returns the string with the first letter in uppercase and rest of the letters
in lowercase. Syntax:

INITCAP(‘string’)

 What are the different set operators available in SQL?

Some of the available set operators are – Union, Intersect or Minus operators.

What is an ALIAS command?

ALIAS command in SQL is the name that can be given to any table or a column. This alias name can be
referred in WHERE clause to identify a particular table or a column.

Select emp.empID, dept.Result from employee emp, department as dept where emp.empID=dept.empID

In the above example, emp refers to alias name for employee table and dept refers to alias name for
department table.

What are aggregate and scalar functions?

Aggregate functions are used to evaluate mathematical calculation and returns a single value. These
calculations are done from the columns in a table. For example- max(),count() are calculated with respect
to numeric.

Scalar functions return a single value based on the input value. For example – UCASE(), NOW() are
calculated with respect to string.

How can you fetch alternate records from a table?

You can fetch alternate records i.e both odd and even row numbers. For example- To display even
numbers, use the following command:

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

Now, to display odd numbers:

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

Name the operator which is used in the query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % – It matches zero or more characters.

For example- select * from students where studentname like ‘a%’

_ (Underscore) – it matches exactly one character.


For example- select * from student where studentname like ‘abc_’
How can you select unique records from a table?

You can select unique records from a table by using the DISTINCT keyword.

Select DISTINCT studentID from Student

Using this command, it will print unique student id from the table Student.

How can you fetch first 5 characters of the string?

There are a lot of ways to fetch characters from a string. For example:

Select SUBSTRING(StudentName,1,5) as studentname from student

What is the main difference between SQL and PL/SQL?

SQL is a query language that allows you to issue a single query or execute a single insert/update/delete
whereas PL/SQL is Oracle’s “Procedural Language” SQL, which allows you to write a full program (loops,
variables, etc.) to accomplish multiple operations such as selects/inserts/updates/deletes. 

What is a View?

A view is a virtual table which consists of a subset of data contained in a table. Since views are not
present, it takes less space to store. View can have data of one or more tables combined and it depends
on the relationship.

What are Views used for?

A view refers to a logical snapshot based on a table or another view. It is used for the following reasons:

 Restricting access to data.

 Making complex queries simple.

 Ensuring data independence.

 Providing different views of same data.

What is a Stored Procedure?

A Stored Procedure is a function which consists of many SQL statements to access the database system.
Several SQL statements are consolidated into a stored procedure and execute them whenever and
wherever required which saves time and avoid writing code again and again.

List some advantages and disadvantages of Stored Procedure?

Advantages:

A Stored Procedure can be used as a modular programming which means create once, store and call for
several times whenever it is required. This supports faster execution. It also reduces network traffic and
provides better security to the data.

Disadvantage:

The only disadvantage of Stored Procedure is that it can be executed only in the database and utilizes
more memory in the database server.

List all the types of user-defined functions?

There are three types of user-defined functions, namely:


 Scalar Functions

 Inline Table-valued functions

 Multi-statement valued functions

Scalar returns the unit, variant defined the return clause. Other two types of defined functions return
table.

What do you mean by Collation?

Collation is defined as a set of rules that determine how data can be sorted as well as compared.
Character data is sorted using the rules that define the correct character sequence along with options for
specifying case-sensitivity, character width etc.

Let’s move to the next question in this SQL Interview Questions.

What are the different types of Collation Sensitivity?

Following are the different types of collation sensitivity:

 Case Sensitivity: A and a and B and b.

 Kana Sensitivity: Japanese Kana characters.

 Width Sensitivity: Single byte character and double-byte character.

 Accent Sensitivity.

What are Local and Global variables?

Local variables:

These variables can be used or exist only inside the function. These variables are not used or referred by
any other function.

Global variables:

These variables are the variables which can be accessed throughout the program. Global variables cannot
be created whenever that function is called.

What is Auto Increment in SQL?

Autoincrement keyword allows the user to create a unique number to get generated whenever a new
record is inserted into the table.
This keyword is usually required whenever PRIMARY KEY in SQL is used.

AUTO INCREMENT keyword can be used in Oracle and IDENTITY keyword can be used in SQL SERVER.

What is a Datawarehouse?

Datawarehouse refers to a central repository of data where the data is assembled from multiple sources
of information. Those data are consolidated, transformed and made available for the mining as well as
online processing. Warehouse data also have a subset of data called Data Marts.

What are the different authentication modes in SQL Server? How can it be changed?

Windows mode and Mixed Mode – SQL and Windows. You can go to the below steps to change
authentication mode in SQL Server:
 Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL
Enterprise Manager from the Microsoft SQL Server program group.

 Then select the server from the Tools menu.

 Select SQL Server Configuration Properties, and choose the Security page.

What are STUFF and REPLACE function?

STUFF Function: This function is used to overwrite existing character or inserts a string into another
string. Syntax:

STUFF(string_expression,start, length, replacement_characters)

where,
string_expression: it is the string that will have characters substituted

start: This refers to the starting position


length: It refers to the number of characters in the string which are substituted.

replacement_string: They are the new characters which are injected in the string.

REPLACE function: This function is used to replace the existing characters of all the occurrences. Syntax:

REPLACE (string_expression, search_string, replacement_string)

Here every search_string in the string_expression will be replaced with the replacement_string.

How can you create an empty table from an existing table?

Example will be -.

Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same structure with no rows copied.

How to fetch common records from two tables?

Common records result set can be achieved by -.

Select studentID from student INTERSECT Select StudentID from Exam

How to fetch alternate records from a table?

Records can be fetched for both Odd and Even row numbers -.

To display even numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

To display odd numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]

What is the command used to fetch first 5 characters of the string?

There are many ways to fetch first 5 characters of the string -.


Select SUBSTRING(StudentName,1,5) as studentname from student

Select LEFT(Studentname,5) as studentname from student

Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % – Matches zero or more characters.

2. _(Underscore) – Matching exactly one character.

Example -.

Select * from Student where studentname like 'a%'

Select * from Student where studentname like 'ami_'

What are transactions and their controls?

Answer: A transaction can be defined as the sequence task that is performed on databases in a logical
manner to gain certain results. Operations like Creating, updating, deleting records performed in the
database come from transactions.

In simple words, we can say that a transaction means a group of SQL queries executed on database
records.

There are 4 transaction controls such as

 COMMIT: It is used to save all changes made through the transaction.

 ROLLBACK: It is used to roll back the transaction. All changes made by the transaction are
reverted back and the database remains as before.

 SET TRANSACTION: Set the name of the transaction.

 SAVEPOINT: It is used to set the point where the transaction is to be rolled back.

What are the properties of the transaction?

Answer: Properties of the transaction are known as ACID properties. These are:

 Atomicity: Ensures the completeness of all transactions performed. Checks whether every
transaction is completed successfully or not. If not, then the transaction is aborted at the failure
point and the previous transaction is rolled back to its initial state as changes are undone.

 Consistency: Ensures that all changes made through successful transactions are reflected
properly on the database.

 Isolation: Ensures that all transactions are performed independently and changes made by one
transaction are not reflected on others.

 Durability: Ensures that the changes made in the database with committed transactions persist
as it is even after a system failure.

Explain the working of SQL Privileges?


Answer: SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user
environments. The administrator of the database can grant or revoke privileges to or from users of
database objects by using commands like SELECT, INSERT, UPDATE, DELETE, ALL, etc.

GRANT Command: This command is used to provide database access to users other than the
administrator.

Syntax:

GRANT privilege_name

 ON object_name

 TO {user_name|PUBLIC|role_name}

 [WITH GRANT OPTION];

In the above syntax, the GRANT option indicates that the user can grant access to another user too.

REVOKE command: This command is used to provide database deny or remove access to database
objects.

Syntax:

REVOKE privilege_name

 ON object_name

 FROM {user_name|PUBLIC|
role_name};

How many types of Privileges are available in SQL?

Answer: There are two types of privileges used in SQL, such as

 System privilege: System privilege deals with the object of a particular type and provides users
the right to perform one or more actions on it. These actions include performing administrative
tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP CREATE/ALTER/DELETE TABLE,
CREATE/ALTER/DELETE VIEW etc.

 Object privilege: This allows to perform actions on an object or object of another user(s) viz.
table, view, indexes etc. Some of the object privileges are EXECUTE, INSERT, UPDATE, DELETE,
SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.

How many row comparison operators are used while working with a subquery?

Answer: There are 3-row comparison operators that are used in subqueries such as IN, ANY and ALL.

What is the difference between Nested Subquery and Correlated Subquery?

Answer: Subquery within another subquery is called Nested Subquery.  If the output of a subquery
depends on column values of the parent query table then the query is called Correlated Subquery.

SELECT adminid(SELEC Firstname+' '+Lastname  FROM Employee WHERE

 empid=emp. adminid)AS EmpAdminId FROM Employee;

The result of the query is the details of an employee from the Employee table.
What are Nested Triggers?

Answer: Triggers may implement data modification logic by using INSERT, UPDATE, and DELETE
statements. These triggers that contain data modification logic and find other triggers for data
modification are called Nested Triggers.

What do we need to check in Database Testing?

Answer: In Database testing, the following thing is required to be tested:

 Database connectivity

 Constraint check

 Required application field and its size

 Data Retrieval and processing with DML operations

 Stored Procedures

 Functional flow

What is Database White Box Testing?

Answer: Database White Box testing involves:

 Database Consistency and ACID properties

 Database triggers and logical views

 Decision Coverage, Condition Coverage, and Statement Coverage

 Database Tables, Data Model, and Database Schema

 Referential integrity rules

How to select random rows from a table?

Answer: Using a SAMPLE clause we can select random rows.

For Example,

SELECT * FROM table_name


SAMPLE(10);

Which TCP/IP port does SQL Server run?

Answer: By default SQL Server runs on port 1433.

Write a SQL SELECT query that only returns each name only once from a table?

Answer: To get the result as each name only once, we need to use the DISTINCT keyword.

SELECT DISTINCT name FROM


table_name;

Can we rename a column in the output of the SQL query?

Answer: Yes, using the following syntax we can do this.

SELECT column_name AS new_name FROM table_name;


Give the order of SQL SELECT?

Answer: Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY. Only the
SELECT and FROM clauses are mandatory.

Suppose a Student column has two columns, Name and Marks. How to get names and marks of the top
three students.
Answer: SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM Students s2 WHERE
s1.marks = s2.marks)

What do you mean by ROWID?

Answer: It’s an 18 character long pseudo column attached with each row of a table.

What is Referential Integrity?

Answer: Set of rules that restrict the values of one or more columns of the tables based on the values of
the primary key or unique key of the referenced table.

Does View contain Data?

Answer: No, Views are virtual structures.

Can a View based on another View?

Answer: Yes, A View is based on another View.

What is the difference between the HAVING clause and WHERE clause?

Answer: Both specify a search condition but Having clause is used only with the SELECT statement and
typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaved like WHERE clause only.

What is the difference between Local and Global temporary tables?

Answer: If defined inside a compound statement a local temporary table exists only for the duration of
that statement but a global temporary table exists permanently in the DB but its rows disappear when
the connection is closed.

What is CTE?

Answer: A CTE or common table expression is an expression that contains temporary result set which is
defined in a SQL statement.

Can we embed Pl/SQL in SQL? Justify your answers.

PL/SQL is a procedural language, and it has one or more SQL statements in it, so SQL can be embedded in
a PL/SQL block; however, PL/SQL cannot be embedded in SQL as SQL executes a single query at a time.

/* this is a PL/SQL block */

DECLARE
qty_on_hand NUMBER(5);
BEGIN
SELECT quantity INTO qty_on_hand FROM inventory /* this is the SQL statement embedded in the
PL/SQL block */
WHERE product = 'TENNIS RACKET';
END;
What is SAVEPOINT in transaction control?

A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without
rolling back the entire transaction.

SQL> SAVEPOINT A

SQL> INSERT INTO TEST VALUES (1,'Savepoint A');


1 row inserted.
SQL> SAVEPOINT B

SQL> INSERT INTO TEST VALUES (2,'Savepoint B');


1 row inserted.
SQL> ROLLBACK TO B;
Rollback complete.
SQL> SELECT * FROM TEST;
ID MSG
-------- -----------
1 Savepoint A
Define COMMIT.

When a COMMIT is used in a transaction, all changes made are written into the database permanently.

BEGIN TRANSACTION;

DELETE FROM HumanResources.JobCandidate

WHERE JobCandidateID = 13;

COMMIT TRANSACTION;

The example above deletes a job candidate in an SQL server.

What is a composite key?

When more than one column is used to define the primary key, it is called a composite key. Here is a SQL
syntax to create a composite key in MySQL:

CREATE TABLE SAMPLE_TABLE

(COL1 integer,

COL2 varchar(30),
COL3 varchar(50),

PRIMARY KEY (COL1, COL2));

What is a shared lock?

When two transactions are granted read access to the same data, they are given a shared lock. This
enables reading the same data, and data is not updated until the shared lock is released.

What is a deadlock?

A deadlock is a situation where two or more transactions are waiting indefinitely for each other to release
the locks.

39. What is lock escalation?

Lock escalation is the process of converting row or page locks into table locks. It is an optimization
technique used by RDBMS like SQL Server dynamically.

What is a SYSTEM Privilege?

This is when rights are given to a user, usually by the DBA, to perform a particular action on the database
schema objects like creating tablespaces.

The following are examples of system privileges that can be granted to users:

 CREATE TABLE allows a grantee to create tables in the grantee's schema

 CREATE USER allows a grantee to create users in the database

 CREATE SESSION allows a grantee to connect to an Oracle database to create a user session

What are Object Privileges?

An object-level privilege is a permission granted to a database user account or role to perform some
action on a database object. These object privileges include SELECT, INSERT, UPDATE, DELETE, ALTER,
INDEX on tables, and so on.

The following examples are object privileges that can be granted to users:

 SELECT ON hr.employees TO myuser

 INSERT ON hr.employees TO myuser

What does the BCP command do?

The BCP (Bulk Copy) is a utility or a tool that exports/imports data from a table into a file and vice versa.

What does the VARIANCE function do?

This function returns the VARIANCE of a set of numbers:

CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,

ENAME VARCHAR2(10),

JOB VARCHAR2(9),

SAL NUMBER(7, 2),


DEPTNO NUMBER(2));

INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK', 800, 20);

INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1600, 30);

INSERT INTO EMP VALUES (3, 'WARD', 'SALESMAN', 1250, 30);

INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER', 2975, 20);

INSERT INTO EMP VALUES (5, 'MARTIN','SALESMAN', 1250, 30);

INSERT INTO EMP VALUES (6, 'BLAKE', 'MANAGER', 2850, 30);

INSERT INTO EMP VALUES (7, 'CLARK', 'MANAGER', 2850, 10);

INSERT INTO EMP VALUES (8, 'SCOTT', 'ANALYST', 3000, 20);

INSERT INTO EMP VALUES (9, 'KING', 'PRESIDENT',3000, 10);

INSERT INTO EMP VALUES (10,'TURNER','SALESMAN', 1500, 30);

INSERT INTO EMP VALUES (11,'ADAMS', 'CLERK', 1500, 20);

SQL> SELECT VARIANCE(sal)

2 FROM emp;

VARIANCE(SAL)

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

Does the data stored in the stored procedure increase access time or execution time?

Data stored in stored procedures can be retrieved much faster than the data stored in the SQL database.
Data can be precompiled and stored in stored procedures. This reduces the time gap between query and
compiling as the data has been pre-compiled and stored in the procedure. Procedures may or may not
return values.

Can a view be active if the base table is dropped?

No, the view cannot be active if the parent table is dropped.

What is the difference between null, zero, and blank space?

NULL refers to a value that is unknown, not available, inapplicable, or unassigned. Zero is a number, and
blank space is treated as a character.

Which function is used to return the remainder in a division operator in SQL?

The MOD function returns the remainder in the division operation.

What are case manipulation functions?

Case manipulation functions convert existing data in the table to lower, upper or mixed case characters.

What are the different case manipulation functions in SQL?


1. LOWER: Converts all the characters to lowercase

2. UPPER: Converts all the characters to uppercase

3. INITCAP: Converts initial character of each word to uppercase

What are the different character manipulation functions?

 CONCAT: Joins two or more string values

 SUBSTR: Extracts string of a specific length

 LENGTH: Returns the length of the string

 INSTR: Returns the position of the specific character

 LPAD: Padding of the left-side character value for right-justified value

 RPAD: Padding of right-side character value for left-justified value

 TRIM: Removes the defined character from beginning and end or both

 REPLACE: Replaces a specific sequence of characters with another sequence of characters

Define inconsistent dependency.

The difficulty of accessing data as the path may be broken or missing defines inconsistent dependency.
Inconsistent dependency enables users to search for data in the wrong different table which afterward
results in an error as an output.

What are GROUP functions? Why do we need them?

Group functions work on a set of rows and return a single result per group. The popularly used group
functions are AVG, MAX, MIN, SUM, VARIANCE, COUNT

Distinguish between BETWEEN and IN conditional operators.

BETWEEN displays the rows based on a range of values. IN checks for values contained in a specific set of
values.

Example:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;

SELECT * FROM students where ROLL_NO IN (8,15,25);

What is the MERGE statement?

The statement enables conditional updates or inserts into the table. It updates the row if it exists or
inserts the row if it does not exist.

Explain the recursive stored procedure.

A stored procedure calling itself until it reaches some boundary condition is a recursive stored procedure.
It enables the programmers to use a set of code any number of times.

How can dynamic SQL be executed?

It can be executed in the following ways:

 By executing the query with parameters.


 By using EXEC

 By using sp_executesql

What is auto increment?

This keyword allows a new unique number to be generated whenever a new record is inserted into the
table. It can be used wherever we need the PRIMARY KEY.

What is a data warehouse?

Data from multiple sources of information is stored in a central repository called the data warehouse.
Data warehouses have subsets of data called data marts. The data stored is transformed and used for
online mining and processing.

What are user-defined functions?

Functions written to use the specific logic whenever required are user-defined functions. It avoids
redundancy by avoiding writing the same logic again.

What is the ALIAS command?

This command provides another name to a table or a column. It can be used in the WHERE clause of a
SQL query using the as keyword.

Example:

SELECT S.StudentID, E.Result from student S, Exam as E where S.StudentID = E.StudentID

S and E are alias names for student table and exam table respectively.

What is Collation?

Collation is defined as the set of rules that determines how to store and compare data.

Mention the different types of collation sensitivity.

The following are the types of collation sensitivity:

 Case

 Kana

 Width

 Accent

What are STUFF and REPLACE functions?

STUFF: Overwrites the existing character or inserts a string into another string. The syntax is:

STUFF(string_expression,start, length, replacement_characters)

REPLACE: replaces the existing characters of all the occurrences. The syntax is:

REPLACE (string_expression, search_string, replacement_string)

Define SQL Order by the statement?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending
according to one or more columns.
 By default ORDER BY sorts the data in ascending order.

 We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort
in ascending order.

Explain SQL Having statement?

HAVING is used to specify a condition for a group or an aggregate function used in the select statement.
The WHERE clause selects before grouping. The HAVING clause selects rows after grouping. Unlike the
HAVING clause, the WHERE clause cannot contain aggregate functions.

Explain SQL AND OR statement with example?

In SQL, the AND & OR operators are used for filtering the data and getting precise results based on
conditions.

The AND and OR operators are used with the WHERE clause.

These two operators are called conjunctive operators.

AND Operator: This operator displays only those records where both the conditions condition1 and
condition2 evaluates to True.

OR Operator: This operator displays the records where either one of the conditions condition1 and
condition2 evaluates to True. That is, either condition1 is True or condition2 is True.

What are the advantages of PL/SQL functions?

Advantages of PL / SQL functions as follows: 

 We can make a single call to the database to run a block of statements. Thus, it improves the
performance against running SQL multiple times. This will reduce the number of calls between
the database and the application.

 We can divide the overall work into small modules which becomes quite manageable, also
enhancing the readability of the code.

 It promotes reusability.

 It is secure since the code stays inside the database, thus hiding internal database details from
the application(user). The user only makes a call to the PL/SQL functions. Hence, security and
data hiding is ensured.

What is the SQL query to display the current date?

CURRENT_DATE returns to the current date. This function returns the same value if it is executed more
than once in a single statement, which means that the value is fixed, even if there is a long delay between
fetching rows in a cursor.

Syntax:

CURRENT_DATE

oder

CURRENT DATE

59. What is ETL in SQL?


ETL is a process in Data Warehousing and it stands for Extract, Transform and Load. It is a process in
which an ETL tool extracts the data from various data source systems, transforms it in the staging area,
and then finally, loads it into the Data Warehouse system. These are three database functions that are
incorporated into one tool to pull data out from one database and to put data into another database.

In what sequence SQL statements are processed?

The clauses of the select are processed in the following sequence

1. FROM clause

2. WHERE clause

3. GROUP BY clause

4. HAVING clause

5. SELECT clause

6. ORDER BY clause

7. TOP clause

Can we write a distributed query and get some data that is located on another server and on Oracle
Database?

SQL Server can be lined to any server provided it has an OLE-DB provider from Microsoft to allow a link.

For E.g. Oracle has an OLE-DB provider for oracle that Microsoft provides to add it as a linked server to
the SQL Server group.

If we drop a table, does it also drop related objects like constraints, indexes, columns, defaults, Views,
and Stored Procedures?

YES, SQL Server drops all related objects, which exist inside a table like constraints, indexes, columns,
defaults, etc. BUT dropping a table will not drop Views and Stored Procedures as they exist outside the
table.

How would you determine the time zone under which a database was operating?

Can we add an identity column to the decimal datatype?

YES, SQL Server support this

What is the difference between LEFT JOIN with WHERE clause & LEFT JOIN with nowhere clause?

OUTER LEFT/RIGHT JOIN with WHERE clause can act like an INNER JOIN if not used wisely or logically.

What are the multiple ways to execute a dynamic query?

 EXEC sp_executesql,

 EXECUTE()

What is the Difference between COALESCE() & ISNULL()?

ISNULL accepts only 2 parameters. The first parameter is checked for a NULL value, if it is NULL then the
second parameter is returned, otherwise, it returns the first parameter.
COALESCE accepts two or more parameters. One can apply 2 or as many parameters, but it returns only
the first non NULL parameter,

How do you generate file output from SQL?

While using SQL Server Management Studio or Query Analyzer, we have an option in Menu BAR.QUERTY
>> RESULT TO >> Result to FILE

How do you prevent SQL Server from giving you informational messages during and after a SQL
statement execution?

SET NOCOUNT OFF

By Mistake, Duplicate records exists in a table, how can we delete the copy of a record? 

with T as

select * , row_number() over (partition by Emp_ID order by Emp_ID) as rank

from employee

delete

from T

where rank > 1

WHAT OPERATOR PERFORMS PATTERN MATCHING?

The pattern matching operator is LIKE and it has to use with two attributes

1. %  means matches zero or more characters and 

2. _ ( underscore ) means matching exactly one character

What’s the logical difference, if any, between the following SQL expressions?

-- Statement 1

SELECT COUNT ( * ) FROM Employees

-- Statement 2

SELECT SUM ( 1 ) FROM Employees

They’re the same unless table Employee table is empty, in which case the first yields a one-column, a
one-row table containing zero, and the second yields a one-column, one-row table "containing a null."

Is it possible to update the Views? If yes, How, If Not, Why?

Yes, We can modify views but a DML statement on a join view can modify only one base table of the view
(so even if the view is created upon a join of many tables, only one table, the key preserved table can be
modified through the view).
Could you please name different kinds of Joins available in SQL Server?

 OUTER JOIN – LEFT, RIGHT, CROSS, FULL ;

 INNER JOIN

How important do you consider cursors or while loops for a transactional database?

would like to avoid cursor in the OLTP database as much as possible, Cursors are mainly only used for
maintenance or warehouse operations.

What is a correlated subquery?

When a subquery is tied to the outer query. Mostly used in self joins.

What is faster, a correlated subquery or an inner join?

Correlated subquery.

You are supposed to work on SQL optimization and given a choice which one runs faster, a correlated
subquery or an exists?

Exists

Can we call. DLL from the SQL server?

YES, We can call. Dll from SQL Server. 

What are the pros and cons of putting a scalar function in a queries select list or in the where clause?

Should be avoided if possible as Scalar functions in these places make the query slow down dramatically.

What are user-defined data types and when you should go for them?

User-defined data types let you extend the base SQL Server data types by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case, you could create a
user-defined data type called Flight_num_type of varchar(8) and use it across all your tables.

See sp_addtype, sp_droptype in books online.

Can You Explain Integration Between SQL Server 2005 And Visual Studio 2005?

This integration provides a wider range of development with the help of CLR for database servers
because CLR helps developers to get flexibility for developing database applications and also provides
language interoperability just like Visual C++, Visual Basic .Net and Visual C# .Net.

The CLR helps developers to get the arrays, classes and exception handling available through
programming languages such as Visual C++ or Visual C# which is used in stored procedures, functions and
triggers for creating database application dynamically and also provide more efficient reuse of code and
faster execution of complex tasks. We particularly liked the error-checking powers of the CLR
environment, which reduces run-time errors

Write down the general syntax for a SELECT statement covering all the options.

Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax)

SELECT select_list

[INTO new_table_]
FROM table_source

[WHERE search_condition]

[GROUP BY group_by__expression]

[HAVING search_condition]

[ORDER BY order__expression [ASC | DESC] ]

What is the OSQL utility?

OSQL is a command-line tool that is used to execute the query and display the result the same as a query
analyzer but everything is in the command prompt.

What Is the Difference Between OSQL And Query Analyzer?

OSQL is the command-line tool that executes the query and displays the result the same as a query
analyzer but the query analyzer is graphical and OSQL is a command-line tool. OSQL is quite useful for
batch processing or executing remote queries.

What Is Cascade delete/update?

CASCADE allows deletions or updates of key values to cascade through the tables defined to have foreign
key relationships that can be traced back to the table on which the modification is performed.

What are some of the join algorithms used when SQL Server joins tables.

1. Loop Join (indexed keys unordered)

2. Merge Join (indexed keys ordered)

3. Hash Join (non-indexed keys)

What is the maximum number of tables that can join in a single query?

256, check SQL Server Limits

What are Magic Tables in SQL Server?

The MAGIC tables are automatically created and dropped, in case you use TRIGGERS. SQL Server has two
magic tables named, INSERTED and DELETED

These are maintained by the SQL server for their Internal processing. When we use update insert or
delete on tables these magic tables are used. These are not physical tables but are Internal tables.
Whenever we use insert statement is fired the Inserted table is populated with newly inserted Row and
whenever delete statement is fired the Deleted table is populated with the deleted row. 

But in case of update statement is fired both Inserted and Deleted tables used for records the Original
row before updating get stored in the Deleted table and the new row Updated gets store in Inserted
table.

Can we disable a trigger? if yes HOW?

YES, we can disable a single trigger on the database by using  “DISABLE TRIGGER triggerName ON <>”

we also have an option to disable all the triggers by using, “DISABLE Trigger ALL ON ALL SERVER”

Why do you need indexing? where is Stored and what do you mean by schema object? For what
purpose we are using view?
We can’t create an Index on an Index... The index is stored in the user_index table. Every object that has
been created on Schema is Schema Object like Table, View etc. If we want to share the particular data to
various users we have to use the virtual table for the Base table. So that is a view.

Indexing is used for faster search or to retrieve data faster from the various tables. Schema containing a
set of tables, basically schema means logical separation of the database. The view is crated for faster
retrieval of data. It’s a customized virtual table. we can create a single view of multiple tables. Only the
drawback is..view needs to be get refreshed for retrieving updated data.

What is the difference between UNION and UNION ALL?

Union will remove the duplicate rows from the result set while Union all doesn't.

Which system table contains information on constraints on all the tables created?

USER_CONSTRAINTS,

system table contains information on constraints on all the tables created

What is a live lock?

A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses
further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a
write transaction to wait indefinitely.

How SQL Server executes a statement with nested subqueries?

When SQL Server executes a statement with nested subqueries, it always executes the innermost query
first. This query passes its results to the next query and so on until it reaches the outermost query. It is
the outermost query that returns a result set.

How do you add a column to an existing table?

ALTER TABLE Department ADD (AGE, NUMBER);

Can one drop a column from a table?

YES, to delete a column in a table, use  ALTER TABLE table_name DROP COLUMN column_name

Which statement do you use to eliminate padded spaces between the month and day values in a
function TO_CHAR(SYSDATE,’Month, DD, YYYY’)?

To remove padded spaces, you use the "fm" prefix before the date element that contains the spaces.
TO_CHAR(SYSDATE,’fmMonth DD, YYYY’)

Which operator do you use to return all of the rows from one query except rows are returned in a
second query?

You use the EXCEPT operator to return all rows from one query except where duplicate rows are found in
a second query. The UNION operator returns all rows from both queries minus duplicates. The UNION
ALL operator returns all rows from both queries including duplicates. The INTERSECT operator returns
only those rows that exist in both queries. 

How will you create a column alias?

The AS keyword is optional when specifying a column alias.

In what sequence SQL statements are processed?


The clauses of the subselect are processed in the following sequence (DB2):

1. FROM clause

2. WHERE clause 

3. GROUP BY clause

4. HAVING clause 

5. SELECT clause 

6. ORDER BY clause 

7. FETCH FIRST clause

How can we determine what objects a user-defined function depends upon?

sp_depends system stored procedure or query the says depends on system table to return a list of
objects that a user-defined function depends upon

SELECT DISTINCT so1.name, so2.name FROM sysobjects so1

INNER JOIN sysdepends sd

ON so1.id = sd.id

INNER JOIN sysobjects so2

ON so2.id = sd.depid

WHERE so1.name = '<>'

What is lock escalation?

A query first takes the lowest level lock possible with the smallest footprint (row-level). When too many
rows are locked (requiring too much RAM) the lock is escalated to a range or page lock. If too many pages
are locked, it may escalate to a table lock.

What are the main differences between #temp tables and @table variables and which one is
preferred? 

1. SQL Server can create column statistics on #temp tables

2. Indexes can be created on #temp tables

3. @table variables are stored in memory up to a certain threshold.

What are Checkpoint In SQL Server?

When we did the operation on SQL SERVER that is not committed directly to the database. All operations
must be logged in to Transaction Log files after that they should be done on to the main
database.CheckPoint is the point that alerts SQL Server to save all the data to the main database if no
checkpoint is there then log files get full we can use the Checkpoint command to commit all data in the
SQL SERVER. When we stop the SQL Server it will take a long time because Checkpoint is also fired.

Why we use the OPEN XML clause?

OPENXML parses the XML data in SQL Server in an efficient manner. Its primary ability is to insert XML
data into the DB.
Can we store PDF files inside the SQL Server table?

YES, we can store this sort of data using a blob datatype.

Can we store Videos inside the SQL Server table?

YES, we can store Videos inside SQL Server by using FILESTREAM data type, which was introduced in SQL
Server 2008.

Can we hide the definition of a stored procedure from a user?

YES, while creating stored procedure we can use WITH ENCRYPTION which will convert the original text of
the CREATE PROCEDURE statement to an encrypted format.

What have included columns when we talk about SQL Server indexing?

Indexed with included columns were developed in SQL Server 2005 that assists in covering queries.
Indexes with Included Columns are non clustered indexes that

have the following benefits:

 Columns defined in the include statement, called non-key columns, are not counted in the
a number of columns by the Database Engine.

 Columns that previously could not be used in queries, like nvarchar(max), can be included
as a non-key column.

 A maximum of 1023 additional columns can be used as non-key columns.

What is an execution plan? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods
chosen by the SQL Server query optimizer for a stored procedure or ad-hoc query and is a very useful tool
for a developer to understand the performance characteristics of a query or stored procedure since the
plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query.

From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop-down
menu). If this option is turned on it will display the query execution plan in a separate window when the
query is run again.

Explain UNION, MINUS, UNION ALL, INTERSECT?

INTERSECT returns all distinct rows selected by both queries.

MINUS: returns all distinct rows selected by the first query but not by the second.

UNION: returns all distinct rows selected by either query

UNION  ALL:  returns  all  rows  selected  by  either query, including all duplicates

Write a Query to display the date after 15 days? 

SELECT DATEADD(dd, 15,getdate())

Write a Query to display the date after 12 months?

SELECT DATEADD(mm, 2, getdate())

Write a Query to display the date before 15 days? 


SELECT DATEADD(dd, -15, getdate())

SQL Server DATEDIFF() Function

Write a Query to display employee details along with exp?

SELECT *

DATEDIFF(yy, doj, getdate()) AS ‘Exp’ FROM employee

Write a Query to display employee details who is working in ECE department & who his having more
than 3 years of exp?

SELECT *

DATEDIFF(yy, doj, getdate()) AS ‘Exp’

FROM employee

WHERE DATEDIFF(yy, doj, getdate())>3 AND dept_name=’ECE’

Write a Query to display employee details along with age?

SELECT *

DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee

Write a Query to display employee details whose age >18?

SELECT *

DATEDIFF(yy, dob, getdate()) AS ‘Age’ FROM employee

WHERE DATEDIFF(yy, dob, getdate())>18

SQL Server Multi-Row Functions

Write a Query to display the minimum salary of an employee?

SELECT MIN (salary)

FROM employee

Write a Query to display the maximum salary of an employee?

SELECT MAX(salary)

FROM employee

Write a Query to display the total salary of all employees?

SELECT SUM(salary) FROM employee

Write a Query to display the average salary of an employee?

SELECT AVG(salary) FROM employee

Write a Query to count the number of employees working in the company?

SELECT COUNT(*) FROM employee

Write a Query to display the minimum & maximum salary of the employee?
SELECT MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’ FROM employee

Write a Query to count the number of employees working in the ECE department?

SELECT COUNT(*) FROM employee WHERE dept_name=’ECE’

Write a Query to display the second max salary of an employee?

SELECT MAX(salary)

FROM employee

WHERE salary < (SELECT MAX(salary) FROM emp)

Write a Query to display the third max salary of an employee?

SELECT MAX(salary)

FROM employee

WHERE salary < (SELECT MAX(salary) FROM emp where salary < (SELECT MAX(salary) FROM emp))

SQL SERVER: GROUP BY Clause

Write a Query to display the total salary of employees based on the city?

SELECT city, SUM(salary)

FROM employee

GROUP BY city;

Write a Query to display a number of employees based on the city?

SELECT city, COUNT(emp_no)

FROM employee

GROUP BY city;

(OR)

SELECT city, COUNT(emp_no) AS ‘no.of employees’

FROM employee

GROUP BY city;

Write a Query to display the total salary of employees based on region?

SELECT region, SUM(salary) AS ‘total_salary’

FROM employee

GROUP BY region;

Write a Query to display the number of employees working in each region?

SELECT region, COUNT(gender)

FROM employee
GROUP BY region;

(OR) 

SELECT region, COUNT(gender) AS ‘no.of males’

FROM employee

GROUP BY region;

Write a Query to display minimum salary & maximum salary based on dept_name?

SELECT dept_name, MIN(salary) AS ‘min sal’, MAX(salary) AS ‘max sal’

FROM employee

GROUP BY dept_name

Write a Query to display the total salary of employees based on dept_name?

SELECT dept_name, SUM(salary) AS ‘total_sal’

FROM employee

GROUP BY dept_name

Write a Query to display no. of males in each department?

SELECT dept_name, COUNT(gender)

FROM employee

GROUP BY dept_name

WHERE gender=’male’

(OR)

SELECT dept_name, COUNT(gender) AS ‘no.of males’

FROM employee

WHERE gender=’male’

GROUP BY dept_name;

Note: We cannot apply where condition in GROUP BY CLAUSE if we want to apply use having clause.

We have to use WHERE condition before GROUP BY but cannot apply where condition after GROUP BY.

SQL SERVER: Having Clause

Write a Query to display the total salary of employees based on whose total salary > 12000?

SELECT city, SUM(salary) AS ‘total_salary’

FROM employee

GROUP BY city

HAVING SUM(salary)>12000;
Write a Query to display the total salary of all employees based on a city whose average salary >=
23000?

SELECT city, SUM(salary) AS ‘total_salary’

FROM employee

GROUP BY city

HAVING AVG(salary) >= 23000;

SQL SERVER: SUB QUERIES

Write a Query to display employee details whose employee numbers are 101, 102?

SELECT *

FROM employee

WHERE Emp_No in (101, 102)

(OR)

SELECT * FROM employee

WHERE Emp_No in (select emp_no from emp)

Write a Query to display employee details belongs to the ECE department?

SELECT Emp_No, Emp_Name, Salary

FROM employee

WHERE dept_no in (select dept_no from dept where dept_name = ‘ECE’)

SQL SERVER TOP Clause

Write a Query to display the first record from the table?

SELECT TOP 1 *

FROM employee

Write a Query to display the top 3 records from the table?

SELECT TOP 3 *

FROM employee

Write a Query to display the last record from the table?

SELECT TOP 1 *

FROM employee

ORDER BY emp_no descending

SQL SERVER: Ranking Functions

Student Details Table:

Student_No Student_Name Percentage Row_ID Rank_ID DenseRank_ID


105 James 87 1 1 1

106 John 83 2 2 2

101 Anil 83 3 2 2

104 Vijay 83 4 2 2

108 Rakesh 76 5 5 3

102 Sunil 76 6 5 3

103 Ajay 76 7 5 3

107 Ram 75 8 8 4

Write a Query to display student details along with the row_no order by student name?

SELECT *, ROW_NUMBER() OVER (ORDER BYstudent_name) AS ‘Row_ID’

FROM employee

Write a Query to display even records from the table?

SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY student_no) AS ‘ Row_ID’ FROM student)

WHERE row_id %2=0

Write a Query to display odd records from the student table?

SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY student_no) AS Row_ID FROM student)

WHERE row_id %2!=0


EmployeeInfo Table:

EmpID EmpFname EmpLname Department Project Address DOB Gender

1 Sanjay Mehra HR P1 Hyderabad(HYD) 01/12/1976 M

2 Ananya Mishra Admin P2 Delhi(DEL) 02/05/1968 F

3 Rohan Diwan Account P3 Mumbai(BOM) 01/01/1980 M

4 Sonia Kulkarni HR P1 Hyderabad(HYD) 02/05/1992 F

5 Ankit Kapoor Admin P2 Delhi(DEL) 03/07/1994 M

EmployeePosition Table:

EmpID EmpPosition DateOfJoining Salary

1 Manager 01/05/2022 500000

2 Executive 02/05/2022 75000

3 Manager 01/05/2022 90000

2 Lead 02/05/2022 85000

1 Executive 01/05/2022 300000

Write a query to fetch the EmpFname from the EmployeeInfo table in upper case and use the ALIAS
name as EmpName.

1SELECT UPPER(EmpFname) AS EmpName FROM EmployeeInfo;

Write a query to fetch the number of employees working in the department ‘HR’.

1SELECT COUNT(*) FROM EmployeeInfo WHERE Department = 'HR';

Write a query to get the current date.

You can write a query as follows in SQL Server:

1SELECT GETDATE();

Write a query to retrieve the first four characters of  EmpLname from the EmployeeInfo table.

1SELECT SUBSTRING(EmpLname, 1, 4) FROM EmployeeInfo;

Write a query to fetch only the place name(string before brackets) from the Address column of
EmployeeInfo table.

Using the MID function in MySQL

1SELECT MID(Address, 0, LOCATE('(',Address)) FROM EmployeeInfo;

Using SUBSTRING
1SELECT SUBSTRING(Address, 1, CHARINDEX('(',Address)) FROM EmployeeInfo;

Write a query to create a new table which consists of data and structure copied from the other table.

Using the SELECT INTO command:

1SELECT * INTO NewTable FROM EmployeeInfo WHERE 1 = 0;

Using the CREATE command in MySQL:

1CREATE TABLE NewTable AS SELECT * FROM EmployeeInfo;

Write q query to find all the employees whose salary is between 50000 to 100000.

1SELECT * FROM EmployeePosition WHERE Salary BETWEEN '50000' AND '100000';

Write a query to find the names of employees that begin with ‘S’

1SELECT * FROM EmployeeInfo WHERE EmpFname LIKE 'S%';

Write a query to fetch top N records.

By using the TOP command in SQL Server:

1SELECT TOP N * FROM EmployeePosition ORDER BY Salary DESC;

By using the LIMIT command in MySQL:

1SELECT * FROM EmpPosition ORDER BY Salary DESC LIMIT N;

Write a query to retrieve the EmpFname and EmpLname in a single column as “FullName”. The first
name and the last name must be separated with space.

1SELECT CONCAT(EmpFname, ' ', EmpLname) AS 'FullName' FROM EmployeeInfo;

Write a query find number of employees whose DOB is between 02/05/1970 to 31/12/1975 and are
grouped according to gender

SELECT COUNT(*), Gender FROM EmployeeInfo WHERE DOB BETWEEN '02/05/1970 ' AND '31/12/1975'
1
GROUP BY Gender;

Write a query to fetch all the records from the EmployeeInfo table ordered by EmpLname in
descending order and Department in the ascending order.

To order the records in ascending and descnding order, you have to use the ORDER BY statement in SQL.

1SELECT * FROM EmployeeInfo ORDER BY EmpFname desc, Department asc;

Write a query to fetch details of employees whose EmpLname ends with an alphabet ‘A’ and contains
five alphabets.

To fetch details mathcing a certain value, you have to use the LIKE operator in SQL.

1SELECT * FROM EmployeeInfo WHERE EmpLname LIKE '____a';

Write a query to fetch details of all employees excluding the employees with first names, “Sanjay” and
“Sonia” from the EmployeeInfo table.

1SELECT * FROM EmployeeInfo WHERE EmpFname NOT IN ('Sanjay','Sonia');


Write a query to fetch details of employees with the address as “DELHI(DEL)”.

1SELECT * FROM EmployeeInfo WHERE Address LIKE 'DELHI(DEL)%';

Write a query to fetch all employees who also hold the managerial position.

1SELECT E.EmpFname, E.EmpLname, P.EmpPosition

2FROM EmployeeInfo E INNER JOIN EmployeePosition P ON

3E.EmpID = P.EmpID AND P.EmpPosition IN ('Manager');

Write a query to fetch the department-wise count of employees sorted by department’s count in
ascending order.

1SELECT Department, count(EmpID) AS EmpDeptCount

2FROM EmployeeInfo GROUP BY Department

3ORDER BY EmpDeptCount ASC;

Write a query to calculate the even and odd records from a table.

To retrieve the even records from a table, you have to use the MOD() function as follows:

1SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=0;

Similarly, to retrieve the odd records from a table, you can write a query as follows:

1SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=1;

Write a SQL query to retrieve employee details from EmployeeInfo table who have a date of joining in
the EmployeePosition table.

1SELECT * FROM EmployeeInfo E

2WHERE EXISTS

3(SELECT * FROM EmployeePosition P WHERE E.EmpId = P.EmpId);

Write a query to retrieve two minimum and maximum salaries from the EmployeePosition table.

To retrieve two minimum salaries, you can write a query as below:

1SELECT DISTINCT Salary FROM EmployeePosition E1

2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary)FROM EmployeePosition E2

3  WHERE E1.Salary >= E2.Salary) ORDER BY E1.Salary DESC;

To retrieve two maximum salaries, you can write a query as below:

1SELECT DISTINCT Salary FROM EmployeePosition E1

2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary) FROM EmployeePosition E2

3  WHERE E1.Salary <= E2.Salary) ORDER BY E1.Salary DESC;


Write a query to find the Nth highest salary from the table without using TOP/limit keyword.

SELECT Salary
1
FROM EmployeePosition E1
2
WHERE N-1 = (
3
      SELECT COUNT( DISTINCT
4
( E2.Salary ) )
5
      FROM EmployeePosition E2
6
      WHERE E2.Salary >  E1.Salary );

Write a query to retrieve duplicate records from a table.

1SELECT EmpID, EmpFname, Department COUNT(*)

2FROM EmployeeInfo GROUP BY EmpID, EmpFname, Department

3HAVING COUNT(*) > 1;

Write a query to retrieve the list of employees working in the same department.

1Select DISTINCT E.EmpID, E.EmpFname, E.Department

2FROM EmployeeInfo E, Employee E1

3WHERE E.Department = E1.Department AND E.EmpID != E1.EmpID;

Write a query to retrieve the last 3 records from the EmployeeInfo table.

1SELECT * FROM EmployeeInfo WHERE

2EmpID <=3 UNION SELECT * FROM

3(SELECT * FROM EmployeeInfo E ORDER BY E.EmpID DESC)

4AS E1 WHERE E1.EmpID <=3;

Write a query to find the third-highest salary from the EmpPosition table.

1SELECT TOP 1 salary

2FROM(

3SELECT TOP 3 salary

4FROM employee_table

5ORDER BY salary DESC) AS emp

6ORDER BY salary ASC;

Write a query to display the first and the last record from the EmployeeInfo table.

To display the first record from the EmployeeInfo table, you can write a query as follows:

1SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MIN(EmpID) FROM EmployeeInfo);

To display the last record from the EmployeeInfo table, you can write a query as follows:
1SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MAX(EmpID) FROM EmployeeInfo);

Write a query to add email validation to your database

SELECT Email FROM EmployeeInfo WHERE NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]


1
{2,4}’, ‘i’);

Write a query to retrieve Departments who have less than 2 employees working in it.

SELECT DEPARTMENT, COUNT(EmpID) as 'EmpNo' FROM EmployeeInfo GROUP BY DEPARTMENT


1
HAVING COUNT(EmpD) < 2;

Write a query to retrieve EmpPostion along with total salaries paid for each of them.

1SELECT EmpPosition, SUM(Salary) from EmployeePosition GROUP BY EmpPosition;

Write a query to fetch 50% records from the EmployeeInfo table.

1SELECT *

2FROM EmployeeInfo WHERE

3EmpID <= (SELECT COUNT(EmpID)/2 from EmployeeInfo);

Orders table
OrderId int Checked
Deptno int Checked
Amount int Checked

sales table
orderId int Checked
salesmanId int Checked

Get the highest earning salesman in each department.

Answer

select salesmanId, Deptno from sales inner join orders on sales.orderId=orders.OrderId where amount in
(select MAX(Amount) from sales inner join orders on sales.orderId=orders.OrderId group by Deptno)

When will union and union all behave the same?

Union will give a record only once even if it occurs several times. Union all will give a record as many
times as it occurs. So union and union all will behave the same when each record is distinct in all the
participating tables.

select name, id from Emp1 union select name, id from Emp2

select name, id from Emp1 union all select name, id from Emp2

Case 1

Emp1

ID Name

11 N1
12 N2

Emp2

ID Name

21 p1

22 p2

Union Output and union all output:

ID Name

11 N1

12 N2

13 p2

14 p2

Case 2

Emp1

ID Name

11 N1

12 N2

11 N1

Emp2

ID Name

21 p1

22 p2

Union all output:

ID Name

11 N1

12 N2

11 N1

21 p1

22 p2
Union output:

ID Name

11 N1

12 N2

21 p1

22 p2

Case 3

Emp1

ID Name

11 N1

12 N2

Emp2

ID Name

21 p1

22 p2

12 N2

Union all output:

ID Name

11 N1

12 N2

21 p1

22 p2

12 N2

Union output:

ID Name

11 N1

12 N2

21 p1
22 p2

In case 1 both union and union all will behave the same. But, for case2 and case3 union and union all will
behave differently.

When does a session actually start?

Answer

A session actually starts when a visitor requests your site for the first time. A new session starts when the
request doesn't contain any SessionID or the sessionID references an expired session. The
Session_OnStart event in Global.asax can be used for tracking session-related information.

How is a session maintained?

Answer

When a web app is requested for the first time, the server creates a sessionID and saves it in the cookie
of the client browser. This sessionID is sent to the server in all the subsequent requests. If cookieless is
made true, sessionID is sent in the URL else the cookie file is sent. This way the session is maintained with
SessionID.

What does UNION do? What is the difference between UNION and UNION ALL?

UNION merges the contents of two structurally-compatible tables into a single combined table. The
difference between UNION and UNION ALL is that UNION will omit duplicate records whereas UNION ALL
will include duplicate records.

It is important to note that the performance of UNION ALL will typically be better than UNION, since
UNION requires the server to do the additional work of removing any duplicates. So, in cases where is is
certain that there will not be any duplicates, or where having duplicates is not a problem, use of UNION
ALL would be recommended for performance reasons.

Given two tables created and populated as follows:

CREATE TABLE dbo.envelope(id int, user_id int);

CREATE TABLE dbo.docs(idnum int, pageseq int, doctext varchar(100));

INSERT INTO dbo.envelope VALUES

(1,1),

(2,2),

(3,3);

INSERT INTO dbo.docs(idnum,pageseq) VALUES

(1,5),

(2,6),

(null,0);

What will the result be from the following query:


UPDATE docs SET doctext=pageseq FROM docs INNER JOIN envelope ON envelope.id=docs.idnum

WHERE EXISTS (

SELECT 1 FROM dbo.docs

WHERE id=envelope.id

);

Explain your answer.

The result of the query will be as follows:

idnum pageseq doctext

1 5 5

2 6 6

NULL 0 NULL

The EXISTS clause in the above query is a red herring. It will always be true since ID is not a member of
dbo.docs. As such, it will refer to the envelope table comparing itself to itself!

The idnum value of NULL will not be set since the join of NULL will not return a result when attempting a
match with any value of envelope.

Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).

If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be
displayed in the result of the following SQL query:

Select * From Emp, Dept

Explain your answer.

The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever
the ‘where’ clause is omitted.

Given two tables created as follows

create table test_a(id numeric);

create table test_b(id numeric);

insert into test_a(id) values

(10),

(20),

(30),

(40),

(50);

insert into test_b(id) values


(10),

(30),

(50);

Write a query to fetch values in table test_a that are and not in test_b without using the NOT keyword.

Note, Oracle does not support the above INSERT syntax, so you would need this instead:

insert into test_a(id) values (10);

insert into test_a(id) values (20);

insert into test_a(id) values (30);

insert into test_a(id) values (40);

insert into test_a(id) values (50);

insert into test_b(id) values (10);

insert into test_b(id) values (30);

insert into test_b(id) values (50);

In SQL Server, PostgreSQL, and SQLite, this can be done using the except keyword as follows:

select * from test_a

except

select * from test_b;

In Oracle, the minus keyword is used instead. Note that if there are multiple columns, say ID and Name,
the column should be explicitly stated in Oracle queries: Select ID from test_a minus select ID from test_b

MySQL does not support the except function. However, there is a standard SQL solution that works in all
of the above engines, including MySQL:

select a.id

from test_a a

left join test_b b on a.id = b.id

where b.id is null;

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

What are the steps you will take to improve the performance of a poor-performing query?

This is a very open-ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures, and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.
Some of the tools/ways that help you troubleshooting performance problems are:

 SET SHOWPLAN_ALL ON

 SET SHOWPLAN_TEXT ON

 SET STATISTICS IO ON

 SQL Server Profiler

 Windows NT /2000 Performance monitor

 Graphical execution plan in Query Analyzer.

You are being you being assigned a task to move 5 million rows from one server to another using T-SQL
with a linked server. What will you consider to avoid transaction log fill up at destination server?

We will prefer to use SET ROWCOUNT and a while loop to commit data in batches.

What is the optimal Disk configuration for a database server and what RAID configurations would you
use if budget is not a constraint?

1. RAID 1 for the OS / Applications

2. RAID 1 for the page file

3. RAID 10 for the Data file (or RAID 5 for few writes)

4. RAID 1 (or 10) for the transaction log

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a
lock on the other’s piece. Each process would wait indefinitely for the other to release the lock unless one
of the user processes is terminated. SQL Server detects deadlocks and terminates one user’s process.

A livelock is one, where a  request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses
further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a
write transaction to wait indefinitely.

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection
requires a conflicting lock type. This forces the second connection to wait, blocked on the first.

What are statistics, under what circumstances do they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. The query optimizer
uses these indexes in determining whether to choose an index or not while executing a query.

Some situations under which you should update statistics:

1. If there is a significant change in the key values in the index

2. If a large amount of data in an indexed column has been added, changed, or removed (that is if
the distribution of key values has changed), or the table has been truncated using the TRUNCATE
TABLE statement and then repopulated
3. The database is upgraded from a previous version

UPDATE STATISTICS,

STATS_DATE,

DBCC SHOW_STATISTICS,

CREATE STATISTICS,

DROP STATISTICS,

sp_autostats,

sp_createstats,

sp_updatestats

Could you please some items which you may see in an execution plan indicating the query is not
optimized. 

1. Index Scan or Table Scan

2. Hash Joins

3. Thick arrows (indicating large work tables)

4. Parallel streams (Parallelism)

5. Bookmark lookup (or key lookup)

What structure can you implement for the database to speed up table reads? 

Follow the rules of DB tuning we have to:

 properly use indexes ( different types of indexes)

  properly locate different DB objects across different tablespaces, files, and so on.

 3 create a special space (tablespace) to locate some of the data with special datatype ( for
example CLOB, LOB, and …)

Difference between SQL Server and Postgre SQL

SQL Server vs PostgreSQL

Feature Microsoft SQL Server PostgreSQL

Operating System Windows Windows, IOS, Unix, and Linux

Licensing Free and commercial Open Source

Installation and Maintenance Expert advice needed Medium

Windows default drivers Yes No

Drivers available ODBC, JDBC, ADO.NET ODBC, JDBC, ADO.NET

Read-Only Views Yes Yes

Open Source Other than CodePlex/.NET Moderately


SQL Server vs PostgreSQL

Modifying columns Can modify without dropping Cannot

Dropping tables and views Can drop tables and views Can't drop tables

Write a SQL query to find the 10th highest employee salary from an Employee table. Explain your
answer.

(Note: You may assume that there are at least 10 records in the Employee table.)

This can be done as follows:

SELECT TOP (1) Salary FROM

SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC

) AS Emp ORDER BY Salary

This works as follows:

First, the SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC query will select the
top 10 salaried employees in the table. However, those salaries will be listed in descending order. That
was necessary for the first query to work, but now picking the top 1 from that list will give you the
highest salary not the the 10th highest salary.

Therefore, the second query reorders the 10 records in ascending order (which the default sort order)
and then selects the top record (which will now be the lowest of those 10 salaries).

Not all databases support the TOP keyword. For example, MySQL and PostreSQL use the LIMIT keyword,
as follows:

SELECT Salary FROM

SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 10

) AS Emp ORDER BY Salary LIMIT 1;

Or even more concisely, in MySQL this can be:

SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 9,1;

And in PostgreSQL this can be:

SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 9;

Write a SQL query using UNION ALL (not UNION) that uses the WHERE clause to eliminate duplicates.
Why might you want to do this?

You can avoid duplicates using UNION ALL and still run much faster than UNION DISTINCT (which is
actually same as UNION) by running a query like this:

SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X
The key is the AND a!=X part. This gives you the benefits of the UNION (a.k.a., UNION DISTINCT)
command, while avoiding much of its performance hit.

Given the following tables:

SELECT * FROM users;

user_id username

1 John Doe

2 Jane Don

3 Alice Jones

4 Lisa Romero

SELECT * FROM training_details;

user_training_id user_id training_id training_date

1 1 1 "2015-08-02"

2 2 1 "2015-08-03"

3 3 2 "2015-08-02"

4 4 2 "2015-08-04"

5 2 2 "2015-08-03"

6 1 1 "2015-08-02"

7 3 2 "2015-08-04"

8 4 3 "2015-08-03"

9 1 4 "2015-08-03"

10 3 1 "2015-08-02"

11 4 2 "2015-08-04"

12 3 2 "2015-08-02"

13 1 1 "2015-08-02"

14 4 3 "2015-08-03"

Write a query to to get the list of users who took the a training lesson more than once in the same day,
grouped by user and training lesson, each ordered from the most recent lesson date to oldest date.

SELECT

u.user_id,

username,
training_id,

training_date,

count( user_training_id ) AS count

FROM users u JOIN training_details t ON t.user_id = u.user_id

GROUP BY u.user_id,

username,

training_id,

training_date

HAVING count( user_training_id ) > 1

ORDER BY training_date DESC;

user_id username training_id training_date count

4 Lisa Romero 2 August, 04 2015 00:00:00 2

4 Lisa Romero 3 August, 03 2015 00:00:00 2

1 John Doe 1 August, 02 2015 00:00:00 3

3 Alice Jones 2 August, 02 2015 00:00:00 2

What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods
chosen by the SQL server’s query optimizer for a stored procedure or ad hoc query. Execution plans are
very useful for helping a developer understand and analyze the performance characteristics of a query or
stored procedure, since the plan is used to execute the query or stored procedure.

In many SQL systems, a textual execution plan can be obtained using a keyword such as EXPLAIN, and
visual representations can often be obtained as well. In Microsoft SQL Server, the Query Analyzer has an
option called “Show Execution Plan” (located on the Query drop down menu). If this option is turned on,
it will display query execution plans in a separate window when a query is run.

List and explain each of the ACID properties that collectively guarantee that database transactions are
processed reliably.

ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee that database
transactions are processed reliably. They are defined as follows:

 Atomicity. Atomicity requires that each transaction be “all or nothing”: if one part of the
transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic
system must guarantee atomicity in each and every situation, including power failures, errors,
and crashes.

 Consistency. The consistency property ensures that any transaction will bring the database from
one valid state to another. Any data written to the database must be valid according to all
defined rules, including constraints, cascades, triggers, and any combination thereof.

 Isolation. The isolation property ensures that the concurrent execution of transactions results in
a system state that would be obtained if transactions were executed serially, i.e., one after the
other. Providing isolation is the main goal of concurrency control. Depending on concurrency
control method (i.e. if it uses strict - as opposed to relaxed - serializability), the effects of an
incomplete transaction might not even be visible to another transaction.

 Durability. Durability means that once a transaction has been committed, it will remain so, even
in the event of power loss, crashes, or errors. In a relational database, for instance, once a group
of SQL statements execute, the results need to be stored permanently (even if the database
crashes immediately thereafter). To defend against power loss, transactions (or their effects)
must be recorded in a non-volatile memory.

Given a table dbo.users where the column user_id is a unique numeric identifier, how can you
efficiently select the first 100 odd user_id values from the table?

(Assume the table contains well over 100 records with odd user_id values.)

SELECT TOP 100 user_id FROM dbo.users WHERE user_id % 2 = 1 ORDER BY user_id

What are the NVL and the NVL2 functions in SQL? How do they differ?

Both the NVL(exp1, exp2) and NVL2(exp1, exp2, exp3) functions check the value exp1 to see if it is null.

With the NVL(exp1, exp2) function, if exp1 is not null, then the value of exp1 is returned; otherwise, the
value of exp2 is returned, but case to the same data type as that of exp1.

With the NVL2(exp1, exp2, exp3) function, if exp1 is not null, then exp2 is returned; otherwise, the value
of exp3 is returned.

How can you select all the even number records from a table? All the odd number records?

To select all the even number records from a table:

Select * from table where id % 2 = 0

To select all the odd number records from a table:

Select * from table where id % 2 != 0

What is the difference between the RANK() and DENSE_RANK() functions? Provide an example.

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”;
i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-
consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when
there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will
be no gaps between the integer ranking values in the case of a tie).

For example, consider the set {25, 25, 50, 75, 75, 100}. For such a set, RANK() will return {1, 1, 3, 4, 4, 6}
(note that the values 2 and 5 are skipped), whereas DENSE_RANK() will return {1,1,2,3,3,4}.

What is the difference between the WHERE and HAVING clauses?

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

 The WHERE clause is used to filter records from a result. The filtering occurs before any
groupings are made.
 The HAVING clause is used to filter values from a group (i.e., to check conditions after
aggregation into groups has been performed).

Given a table Employee having columns empName and empId, what will be the result of the SQL query
below?

select empName from Employee order by 2 desc;

“Order by 2” is only valid when there are at least two columns being used in select statement. However,
in this query, even though the Employee table has 2 columns, the query is only selecting 1 column name,
so “Order by 2” will cause the statement to throw an error while executing the above sql query.

What will be the output of the below query, given an Employee table having 10 records?

BEGIN TRAN

TRUNCATE TABLE Employees

ROLLBACK

SELECT * FROM Employees

This query will return 10 records as TRUNCATE was executed in the transaction. TRUNCATE does not itself
keep a log but BEGIN TRANSACTION keeps track of the TRUNCATE command.

1. What is the difference between single-row functions and multiple-row functions?

2. What is the group by clause used for?

1. Single-row functions work with single row at a time. Multiple-row functions work with data of
multiple rows at a time.

2. The group by clause combines all those records that have identical values in a particular field or
any group of fields.

Imagine a single column in a table that is populated with either a single digit (0-9) or a single character
(a-z, A-Z). Write a SQL query to print ‘Fizz’ for a numeric value or ‘Buzz’ for alphabetical value for all
values in that column.

Example:

['d', 'x', 'T', 8, 'a', 9, 6, 2, 'V']

…should output:

['Buzz', 'Buzz', 'Buzz', 'Fizz', 'Buzz','Fizz', 'Fizz', 'Fizz', 'Buzz']

SELECT col, case when upper(col) = lower(col) then 'Fizz' else 'Buzz' end as FizzBuzz from table;

What is the difference between char and varchar2?

When stored in a database, varchar2 uses only the allocated space. E.g. if you have a varchar2(1999) and
put 50 bytes in the table, it will use 52 bytes.

But when stored in a database, char always uses the maximum length and is blank-padded. E.g. if you
have char(1999) and put 50 bytes in the table, it will consume 2000 bytes.
Write an SQL query to display the text CAPONE as:

Or in other words, an SQL query to transpose text.

Declare @a nvarchar(100)='capone';

Declare @length INT;

Declare @i INT=1;

SET @lenght=LEN(@a)

while @i<=@length

BEGIN

print(substring(@a,@i,1));

set @i=@i+1;

END

In Oracle SQL, this can be done as follows:

SELECT SUBSTR('CAPONE', LEVEL, 1)

FROM DUAL CONNECT BY LEVEL <= LENGTH('CAPONE');

Can we insert a row for identity column implicitly?

Yes, like so:

SET IDENTITY_INSERT TABLE1 ON

INSERT INTO TABLE1 (ID,NAME)

SELECT ID,NAME FROM TEMPTB1

SET IDENTITY_INSERT OFF

Given this table:

Testdb=# Select * FROM "Test"."EMP";

ID

----

2
3

(5 rows)

What will be the output of below snippet?

Select SUM(1) FROM "Test"."EMP";

Select SUM(2) FROM "Test"."EMP";

Select SUM(3) FROM "Test"."EMP";

Table is as follows:

ID C1 C2 C3

1 Red Yellow Blue

2 NULL Red Green

3 Yellow NULL Violet

Print the rows which have ‘Yellow’ in one of the columns C1, C2, or C3, but without using OR.

SELECT * FROM table

WHERE 'Yellow' IN (C1, C2, C3)

Write a query to insert/update Col2’s values to look exactly opposite to Col1’s values.

Col1 Col2

1 0

0 1

0 1

0 1

1 0

0 1

1 0

1 0

update table set col2 = case when col1 = 1 then 0 else 1 end

Or if the type is numeric:

update table set col2 = 1 - col1

How do you get the last id without the max function?

In MySQL:
select id from table order by id desc limit 1

In SQL Server:

select top 1 id from table order by id desc

What is the difference between IN and EXISTS?

IN:

 Works on List result set

 Doesn’t work on subqueries resulting in Virtual tables with multiple columns

 Compares every value in the result list

 Performance is comparatively SLOW for larger resultset of subquery

EXISTS:

 Works on Virtual tables

 Is used with co-related queries

 Exits comparison when match is found

 Performance is comparatively FAST for larger resultset of subquery

Suppose in a table, seven records are there.

The column is an identity column.

Now the client wants to insert a record after the identity value 7 with its identity value starting from
10.

Is it possible? If so, how? If not, why not?

Yes, it is possible, using a DBCC command:

create table tableA

(id int identity,

name nvarchar(50)

insert into tableA values ('ram')

insert into tableA values ('rahim')

insert into tableA values ('roja')

insert into tableA values ('rahman')

insert into tableA values ('rani')

insert into tableA values ('raja')

insert into tableA values ('raga')

select * From tableA


DBCC CHECKIDENT(tableA,RESEED,9)

insert into tableA values ('roli')

insert into tableA values ('rosy')

insert into tableA values ('raka')

insert into tableA values ('rahul')

insert into tableA values ('rihan')

insert into tableA values ('bala')

insert into tableA values ('gala')

How can you use a CTE to return the fifth highest (or Nth highest) salary from a table?

Declare @N int

set @N = 5;

WITH CTE AS

SELECT Name, Salary, EmpID, RN = ROW_NUMBER()

OVER (ORDER BY Salary DESC)

FROM Employee

SELECT Name, Salary, EmpID

FROM CTE

WHERE RN = @N

Given the following table named A:

------

-2

-4

-3

Write a single query to calculate the sum of all positive values of x and he sum of all negative values of
x.
select sum(case when x>0 then x else 0 end)sum_pos,sum(case when x<0 then x else 0 end)sum_neg
from a;

Given the table mass_table:

weight

5.67

34.567

365.253

34

Write a query that produces the output:

weight kg gms

5.67 5 67

34.567 34 567

365.253 365 253

34 34 0

select weight, trunc(weight) as kg, nvl(substr(weight - trunc(weight), 2), 0) as gms

from mass_table;

Consider the Employee table below.

Emp_Id Emp_name Salary Manager_Id

10 Anil 50000 18

11 Vikas 75000 16

12 Nisha 40000 18

13 Nidhi 60000 17

14 Priya 80000 18

15 Mohit 45000 18

16 Rajesh 90000 –

17 Raman 55000 16

18 Santosh 65000 17

Write a query to generate below output:


Manager_Id Manager Average_Salary_Under_Manager

16 Rajesh 65000

17 Raman 62500

18 Santosh 53750

select b.emp_id as "Manager_Id",

b.emp_name as "Manager",

avg(a.salary) as "Average_Salary_Under_Manager"

from Employee a,

Employee b

where a.manager_id = b.emp_id

group by b.emp_id, b.emp_name

order by b.emp_id;

How do you copy data from one table to another table ?

INSERT INTO table2 (column1, column2, column3, ...)

SELECT column1, column2, column3, ...

FROM table1

WHERE condition;

Find the SQL statement below that is equal to the following: SELECT name FROM customer WHERE state
= 'VA';

1. SELECT name IN customer WHERE state IN ('VA');

2. SELECT name IN customer WHERE state = 'VA';

3. SELECT name IN customer WHERE state = 'V';

4. SELECT name FROM customer WHERE state IN ('VA');

1. SELECT name FROM customer WHERE state IN ('VA');

Given these contents of the Customers table:

Id Name ReferredBy

1 John Doe NULL

2 Jane Smith NULL

3 Anne Jenkins 2

4 Eric Branford NULL

5 Pat Richards 1

6 Alice Barnes 2
Here is a query written to return the list of customers not referred by Jane Smith:

SELECT Name FROM Customers WHERE ReferredBy <> 2;

What will be the result of the query? Why? What would be a better way to write it?

Although there are 4 customers not referred by Jane Smith (including Jane Smith herself), the query will
only return one: Pat Richards. All the customers who were referred by nobody at all (and therefore have
NULL in their ReferredBy column) don’t show up. But certainly those customers weren’t referred by Jane
Smith, and certainly NULL is not equal to 2, so why didn’t they show up?

SQL Server uses three-valued logic, which can be troublesome for programmers accustomed to the more
satisfying two-valued logic (TRUE or FALSE) most programming languages use. In most languages, if you
were presented with two predicates: ReferredBy = 2 and ReferredBy <> 2, you would expect one of them
to be true and one of them to be false, given the same value of ReferredBy. In SQL Server, however, if
ReferredBy is NULL, neither of them are true and neither of them are false. Anything compared to NULL
evaluates to the third value in three-valued logic: UNKNOWN.

The query should be written in one of two ways:

SELECT Name FROM Customers WHERE ReferredBy IS NULL OR ReferredBy <> 2

…or:

SELECT Name FROM Customers WHERE ISNULL(ReferredBy, 0) <> 2; -- (Or COALESCE() )

Watch out for the following, though!

SELECT Name FROM Customers WHERE ReferredBy = NULL OR ReferredBy <> 2

This will return the same faulty set as the original. Why? We already covered that: Anything compared to
NULL evaluates to the third value in the three-valued logic: UNKNOWN. That “anything” includes NULL
itself! That’s why SQL Server provides the IS NULL and IS NOT NULL operators to specifically check for
NULL. Those particular operators will always evaluate to true or false.

Even if a candidate doesn’t have a great amount of experience with SQL Server, diving into the intricacies
of three-valued logic in general can give a good indication of whether they have the ability learn it quickly
or whether they will struggle with it.

Given a table TBL with a field Nmbr that has rows with the following values:

1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1

Write a query to add 2 where Nmbr is 0 and add 3 where Nmbr is 1.

This can be done as follows:

update TBL set Nmbr = case when Nmbr = 0 then Nmbr+2 else Nmbr+3 end;

Suppose we have a Customer table containing the following data:

CustomerID CustomerName

1 Prashant Kaurav

2 Ashish Jha

3 Ankit Varma

4 Vineet Kumar
5 Rahul Kumar

Write a single SQL statement to concatenate all the customer names into the following single
semicolon-separated string:

Prashant Kaurav; Ashish Jha; Ankit Varma; Vineet Kumar; Rahul Kumar

SELECT CustomerName+ '; '

From Customer

For XML PATH('')

This is close, but will have an undesired trailing ;. One way of fixing that could be:

SELECT top 1

LTRIM(STUFF((SELECT '; ' + c1.CustomerName FROM Customer c1 FOR XML PATH


('')), 1, 1,'')) as SSV

from Customer c2;

In PostgreSQL one can also use this syntax to achieve the fully correct result:

SELECT array_to_string(array_agg(CustomerName), '; '::text)

FROM Customer

How do you get the Nth-highest salary from the Employee table without a subquery or CTE?

SELECT salary from Employee order by salary DESC LIMIT 2,1

This will give the third-highest salary from the Employee table. Accordingly we can find out Nth salary
using LIMIT (N-1),1.

But MS SQL Server doesn’t support that syntax, so in that case:

SELECT salary from Employee order by salary DESC

OFFSET 2 ROWS

FETCH NEXT 1 ROW ONLY

OFFSET’s parameter corresponds to the (N-1) above.

How to find a duplicate record?

1. duplicate records with one field

2. duplicate records with more than one field

1. duplicate records with one field

2. SELECT name, COUNT(email)

3. FROM users

4. GROUP BY email

5. HAVING COUNT(email) > 1

6. duplicate records with more than one field


7. SELECT name, email, COUNT(*)

8. FROM users

9. GROUP BY name, email

10. HAVING COUNT(*) > 1

Considering the database schema displayed in the SQLServer-style diagram below, write a SQL query to
return a list of all the invoices. For each invoice, show the Invoice ID, the billing date, the customer’s
name, and the name of the customer who referred that customer (if any). The list should be ordered by
billing date.

SELECT i.Id, i.BillingDate, c.Name, r.Name AS ReferredByName

FROM Invoices i

JOIN Customers c ON i.CustomerId = c.Id

LEFT JOIN Customers r ON c.ReferredBy = r.Id

ORDER BY i.BillingDate;

This question simply tests the candidate’s ability take a plain-English requirement and write a
corresponding SQL query. There is nothing tricky in this one, it just covers the basics:

 Did the candidate remember to use a LEFT JOIN instead of an inner JOIN when joining the
customer table for the referring customer name? If not, any invoices by customers not referred
by somebody will be left out altogether.

 Did the candidate alias the tables in the JOIN? Most experienced T-SQL programmers always do
this, because repeating the full table name each time it needs to be referenced gets tedious
quickly. In this case, the query would actually break if at least the Customer table wasn’t aliased,
because it is referenced twice in different contexts (once as the table which contains the name of
the invoiced customer, and once as the table which contains the name of the referring
customer).

 Did the candidate disambiguate the Id and Name columns in the SELECT? Again, this is something
most experienced programmers do automatically, whether or not there would be a conflict. And
again, in this case there would be a conflict, so the query would break if the candidate neglected
to do so.

Note that this query will not return Invoices that do not have an associated Customer. This may be the
correct behavior for most cases (e.g., it is guaranteed that every Invoice is associated with a Customer, or
unmatched Invoices are not of interest). However, in order to guarantee that all Invoices are returned no
matter what, the Invoices table should be joined with Customers using LEFT JOIN:

SELECT i.Id, i.BillingDate, c.Name, r.Name AS ReferredByName

FROM Invoices i

LEFT JOIN Customers c ON i.CustomerId = c.Id

LEFT JOIN Customers r ON c.ReferredBy = r.Id

ORDER BY i.BillingDate;

Here is the best and top SQL interview questions and answers.

Consider the below two tables for reference while trying to solve the SQL queries

Table – EmployeeDetails

EmpId FullName ManagerId DateOfJoining City

121 John Snow 321 01/31/2014 Toronto

321 Walter White 986 01/30/2015 California

421 Kuldeep Rana 876 27/11/2016 New Delhi

Table – EmployeeSalary

EmpId Project Salary Variable

121 P1 8000 500

321 P2 10000 1000

421 P1 12000 0

Ques.1. Write an SQL query to fetch the EmpId and FullName of all the employees working under
Manager with id – ‘986’.
Ans. We can use the EmployeeDetails table to fetch the employee details with a where clause for the
manager-

SELECT EmpId, FullName


FROM EmployeeDetails

WHERE ManagerId = 986;

Ques.2. Write an SQL query to fetch the different projects available from the EmployeeSalary table.
Ans. While referring to the EmployeeSalary table, we can see that this table contains project values
corresponding to each employee, or we can say that we will have duplicate project values while selecting
Project values from this table.

So, we will use the distinct clause to get the unique values of the Project.

SELECT DISTINCT(Project)

FROM EmployeeSalary;

Ques.3. Write an SQL query to fetch the count of employees working in project ‘P1’.
Ans. Here, we would be using aggregate function count() with the SQL where clause-

SELECT COUNT(*)

FROM EmployeeSalary

WHERE Project = 'P1';

Ques.4. Write an SQL query to find the maximum, minimum, and average salary of the employees.
Ans. We can use the aggregate function of SQL to fetch the max, min, and average values-

SELECT Max(Salary),

Min(Salary),

AVG(Salary)

FROM EmployeeSalary;

Ques.5. Write an SQL query to find the employee id whose salary lies in the range of 9000 and 15000.
Ans. Here, we can use the ‘Between’ operator with a where clause.

SELECT EmpId, Salary

FROM EmployeeSalary

WHERE Salary BETWEEN 9000 AND 15000;

Ques.6. Write an SQL query to fetch those employees who live in Toronto and work under manager
with ManagerId – 321.
Ans. Since we have to satisfy both the conditions – employees living in ‘Toronto’ and working in Project
‘P2’. So, we will use AND operator here-

SELECT EmpId, City, ManagerId

FROM EmployeeDetails

WHERE City='Toronto' AND ManagerId='321';

Ques.7. Write an SQL query to fetch all the employees who either live in California or work under a
manager with ManagerId – 321.
Ans. This interview question requires us to satisfy either of the conditions – employees living in
‘California’ and working under Manager with ManagerId ‘321’. So, we will use the OR operator here-
SELECT EmpId, City, ManagerId

FROM EmployeeDetails

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

Ques.8. Write an SQL query to fetch all those employees who work on Project other than P1.
Ans. Here, we can use the NOT operator to fetch the rows which are not satisfying the given condition.

SELECT EmpId

FROM EmployeeSalary

WHERE NOT Project='P1';

Or using the not equal to operator-

SELECT EmpId

FROM EmployeeSalary

WHERE Project <> 'P1';

Ques.9. Write an SQL query to display the total salary of each employee adding the Salary with
Variable value.
Ans. Here, we can simply use the ‘+’ operator in SQL.

SELECT EmpId,

Salary+Variable as TotalSalary

FROM EmployeeSalary;

Ques.10. Write an SQL query to fetch the employees whose name begins with any two characters,
followed by a text “hn” and ending with any sequence of characters.
Ans. For this question, we can create an SQL query using like operator with ‘_’ and ‘%’ wild card
characters, where ‘_’ matches a single character and ‘%’ matches ‘0 or multiple characters’.

SELECT FullName

FROM EmployeeDetails

WHERE FullName LIKE ‘__hn%’;

Ques.11. Write an SQL query to fetch all the EmpIds which are present in either of the tables –
‘EmployeeDetails’ and ‘EmployeeSalary’.
Ans. In order to get unique employee ids from both the tables, we can use Union clause which can
combine the results of the two SQL queries and return unique rows.

SELECT EmpId FROM EmployeeDetails

UNION

SELECT EmpId FROM EmployeeSalary;

Ques.12. Write an SQL query to fetch common records between two tables.
Ans. SQL Server – Using INTERSECT operator-

SELECT * FROM EmployeeSalary


INTERSECT

SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have INTERSECT operator so we can use the sub query-

SELECT *

FROM EmployeeSalary

WHERE EmpId IN

(SELECT EmpId from ManagerSalary);

Ques.13. Write an SQL query to fetch records that are present in one table but not in another table.
Ans. SQL Server – Using MINUS- operator-

SELECT * FROM EmployeeSalary

MINUS

SELECT * FROM ManagerSalary;

MySQL – Since MySQL doesn’t have MINUS operator so we can use LEFT join-

SELECT EmployeeSalary.*

FROM EmployeeSalary

LEFT JOIN

ManagerSalary USING (EmpId)

WHERE ManagerSalary.EmpId IS NULL;

Ques.14. Write an SQL query to fetch the EmpIds that are present in both the tables –  
‘EmployeeDetails’ and ‘EmployeeSalary.
Ans. Using sub query-

SELECT EmpId FROM

EmployeeDetails

where EmpId IN

(SELECT EmpId FROM EmployeeSalary);

Ques.15. Write an SQL query to fetch the EmpIds that are present in EmployeeDetails but not in
EmployeeSalary.
Ans. Using sub query-

SELECT EmpId FROM

EmployeeDetails

where EmpId Not IN

(SELECT EmpId FROM EmployeeSalary);


Ques.16. Write an SQL query to fetch the employee full names and replace the space with ‘-’.
Ans. Using ‘Replace’ function-

SELECT REPLACE(FullName, ' ', '-')

FROM EmployeeDetails;

Ques.17. Write an SQL query to fetch the position of a given character(s) in a field.
Ans. Using ‘Instr’ function-

SELECT INSTR(FullName, 'Snow')

FROM EmployeeDetails;

Ques.18. Write an SQL query to display both the EmpId and ManagerId together.
Ans. Here we can use the CONCAT command.

SELECT CONCAT(EmpId, ManagerId) as NewId

FROM EmployeeDetails;

Ques.19. Write a query to fetch only the first name(string before space) from the FullName column of
the EmployeeDetails table.
Ans. In this question, we are required to first fetch the location of the space character in the FullName
field and then extract the first name out of the FullName field.

For finding the location we will use the LOCATE method in MySQL and CHARINDEX in SQL SERVER and for
fetching the string before space, we will use the SUBSTRING OR MID method.

MySQL – using MID

SELECT MID(FullName, 1, LOCATE(' ',FullName))

FROM EmployeeDetails;

SQL Server – using SUBSTRING

SELECT SUBSTRING(FullName, 1, CHARINDEX(' ',FullName))

FROM EmployeeDetails;

Ques.20. Write an SQL query to upper case the name of the employee and lower case the city values.
Ans. We can use SQL Upper and Lower functions to achieve the intended results.

SELECT UPPER(FullName), LOWER(City)

FROM EmployeeDetails;

Ques.21. Write an SQL query to find the count of the total occurrences of a particular character – ‘n’ in
the FullName field.
Ans. Here, we can use the ‘Length’ function. We can subtract the total length of the FullName field with a
length of the FullName after replacing the character – ‘n’.

SELECT FullName,

LENGTH(FullName) - LENGTH(REPLACE(FullName, 'n', ''))

FROM EmployeeDetails;
Ques.22. Write an SQL query to update the employee names by removing leading and trailing spaces.
Ans. Using the ‘Update’ command with the ‘LTRIM’ and ‘RTRIM’ function.

UPDATE EmployeeDetails

SET FullName = LTRIM(RTRIM(FullName));

Ques.23. Fetch all the employees who are not working on any project.
Ans. This is one of the very basic interview questions in which the interviewer wants to see if the person
knows about the commonly used – Is NULL operator.

SELECT EmpId

FROM EmployeeSalary

WHERE Project IS NULL;

Ques.24. Write an SQL query to fetch employee names having a salary greater than or equal to 5000
and less than or equal to 10000.
Ans. Here, we will use BETWEEN in the ‘where’ clause to return the EmpId of the employees with salary
satisfying the required criteria and then use it as subquery to find the fullName of the employee from
EmployeeDetails table.

SELECT FullName

FROM EmployeeDetails

WHERE EmpId IN

(SELECT EmpId FROM EmployeeSalary

WHERE Salary BETWEEN 5000 AND 10000);

Ques.25. Write an SQL query to find the current date-time.


Ans. MySQL-

SQL Server-

Oracle-

SELECT SYSDATE FROM DUAL;

Ques.26. Write an SQL query to fetch all the Employees details from EmployeeDetails table who joined
in the Year 2020.
Ans. Using BETWEEN for the date range ’01-01-2020′ AND ’31-12-2020′-

SELECT * FROM EmployeeDetails

WHERE DateOfJoining BETWEEN '2020/01/01'

AND '2020/12/31';

Also, we can extract year part from the joining date (using YEAR in mySQL)-

SELECT * FROM EmployeeDetails

WHERE YEAR(DateOfJoining) = '2020';


Ques.27. Write an SQL query to fetch all employee records from EmployeeDetails table who have a
salary record in EmployeeSalary table.
Ans. Using ‘Exists’-

SELECT * FROM EmployeeDetails E

WHERE EXISTS

(SELECT * FROM EmployeeSalary S

WHERE E.EmpId = S.EmpId);

Ques.28. Write an SQL query to fetch project-wise count of employees sorted by project’s count in
descending order.
Ans. The query has two requirements – first to fetch the project-wise count and then to sort the result by
that count.

For project-wise count, we will be using the GROUP BY clause and for sorting, we will use the ORDER BY
clause on the alias of the project-count.

SELECT Project, count(EmpId) EmpProjectCount

FROM EmployeeSalary

GROUP BY Project

ORDER BY EmpProjectCount DESC;

Ques.29. Write a query to fetch employee names and salary records. Display the employee details even
if the salary record is not present for the employee.
Ans. This is again one of the very common interview questions in which the interviewer just wants to
check the basic knowledge of SQL JOINS.

Here, we can use left join with EmployeeDetail table on the left side of the EmployeeSalary table.

SELECT E.FullName, S.Salary

FROM EmployeeDetails E

LEFT JOIN

EmployeeSalary S

ON E.EmpId = S.EmpId;

Ques.30. Write an SQL query to join 3 tables.


Ans. Considering 3 tables TableA, TableB, and TableC, we can use 2 joins clauses like below-

SELECT column1, column2

FROM TableA

JOIN TableB ON TableA.Column3 = TableB.Column3

JOIN TableC ON TableA.Column4 = TableC.Column4;

Ques. 31. Write an SQL query to fetch all the Employees who are also managers from the
EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the EmployeeDetails table as
two tables. We will use different aliases ‘E’ and ‘M’ for the same EmployeeDetails table.
SELECT DISTINCT E.FullName

FROM EmployeeDetails E

INNER JOIN EmployeeDetails M

ON E.EmpID = M.ManagerID;

To learn more about Self Join along with some more queries, you can watch the below video that
explains the self join concept in a very simple way.

Self Join and Its Demonstration

Ques.32. Write an SQL query to fetch duplicate records from EmployeeDetails (without considering the
primary key – EmpId).
Ans. In order to find duplicate records from the table, we can use GROUP BY on all the fields and then use
the HAVING clause to return only those fields whose count is greater than 1 i.e. the rows having duplicate
records.

SELECT FullName, ManagerId, DateOfJoining, City, COUNT(*)

FROM EmployeeDetails

GROUP BY FullName, ManagerId, DateOfJoining, City

HAVING COUNT(*) > 1;

Ques.33. Write an SQL query to remove duplicates from a table without using a temporary table.
Ans. Here, we can use delete with alias and inner join. We will check for the equality of all the matching
records and them remove the row with higher EmpId.

DELETE E1 FROM EmployeeDetails E1

INNER JOIN EmployeeDetails E2

WHERE E1.EmpId > E2.EmpId

AND E1.FullName = E2.FullName

AND E1.ManagerId = E2.ManagerId

AND E1.DateOfJoining = E2.DateOfJoining

AND E1.City = E2.City;

Ques.34. Write an SQL query to fetch only odd rows from the table.
Ans. In case we have an auto-increment field e.g. EmpId then we can simply use the below query-

SELECT * FROM EmployeeDetails

WHERE MOD (EmpId, 2) <> 0;

In case we don’t have such a field then we can use the below queries.

Using Row_number in SQL server and checking that the remainder when divided by 2 is 1-

SELECT E.EmpId, E.Project, E.Salary

FROM (
SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber

FROM EmployeeSalary

)E

WHERE E.RowNumber % 2 = 1;

Using a user defined variable in MySQL-

SELECT *

FROM (

SELECT *, @rowNumber := @rowNumber+ 1 rn

FROM EmployeeSalary

JOIN (SELECT @rowNumber:= 0) r

)t

WHERE rn % 2 = 1;

Ques.35. Write an SQL query to fetch only even rows from the table.
Ans. In case we have an auto-increment field e.g. EmpId then we can simply use the below query-

SELECT * FROM EmployeeDetails

WHERE MOD (EmpId, 2) = 0;

In case we don’t have such a field then we can use the below queries.

Using Row_number in SQL server and checking that the remainder when divided by 2 is 1-

SELECT E.EmpId, E.Project, E.Salary

FROM (

SELECT *, Row_Number() OVER(ORDER BY EmpId) AS RowNumber

FROM EmployeeSalary

)E

WHERE E.RowNumber % 2 = 0;

Using a user defined variable in MySQL-

SELECT *

FROM (

SELECT *, @rowNumber := @rowNumber+ 1 rn

FROM EmployeeSalary

JOIN (SELECT @rowNumber:= 0) r

)t
WHERE rn % 2 = 0;

Ques.36. Write an SQL query to create a new table with data and structure copied from another table.
Ans.

CREATE TABLE NewTable

SELECT * FROM EmployeeSalary;

Ques.37. Write an SQL query to create an empty table with the same structure as some other table.
Ans. Here, we can use the same query as above with False ‘WHERE’ condition-

CREATE TABLE NewTable

SELECT * FROM EmployeeSalary where 1=0;

Ques.38. Write an SQL query to fetch top n records?


Ans. In MySQL using LIMIT-

SELECT *

FROM EmployeeSalary

ORDER BY Salary DESC LIMIT N;

In SQL server using TOP command-

SELECT TOP N *

FROM EmployeeSalary

ORDER BY Salary DESC;

Ques.39. Write an SQL query to find the nth highest salary from table.
Ans, Using Top keyword (SQL Server)-

SELECT TOP 1 Salary

FROM (

SELECT DISTINCT TOP N Salary

FROM Employee

ORDER BY Salary DESC

ORDER BY Salary ASC;

Using limit clause(MySQL)-

SELECT Salary

FROM Employee

ORDER BY Salary DESC LIMIT N-1,1;


Ques.40. Write SQL query to find the 3rd highest salary from a table without using the TOP/limit
keyword.
Ans. This is one of the most commonly asked interview questions. For this, we will use a correlated
subquery.

In order to find the 3rd highest salary, we will find the salary value until the inner query returns a count of
2 rows having the salary greater than other distinct salaries.

SELECT Salary

FROM EmployeeSalary Emp1

WHERE 2 = (

SELECT COUNT( DISTINCT ( Emp2.Salary ) )

FROM EmployeeSalary Emp2

WHERE Emp2.Salary > Emp1.Salary

For nth highest salary-

SELECT Salary

FROM EmployeeSalary Emp1

WHERE N-1 = (

SELECT COUNT( DISTINCT ( Emp2.Salary ) )

FROM EmployeeSalary Emp2

WHERE Emp2.Salary > Emp1.Salary

Q1. How to delete duplicate records?

Using rowi

SQL > delete from emp where rowid not in (select max (rowid) from emp group by empno);

This technique can be applied to almost scenarios. Group by operation should be on

The columns which identify the duplicates.


using self-join

SQL > delete from emp e1 where rowid not in (select max (rowid) from emp e2 where e1.empno =
e2.empno );

Using row_number()

SQL > delete from emp where rowid in (select rid from ( select rowid rid, row_number() over(partition by
empno order by empno) rn from emp )where rn > 1);

This is another efficient way to delete duplicates

Using dense_rank ( )

SQL > delete from emp where rowid in (select rid from (select rowid rid, dense_rank() over(partition by
empno order by rowid) rn from emp ) where rn > 1 );

Here you can use both rank ( ) and dens_rank()

since both will give unique records when order by rowid.

Using group by

SQL > delete from emp where empno,empname,salary) in ( select max(empno),empname,salary from
emp group by empname,salary );

This technique is only applicable in few scenarios.

Q2. What is Materialized View in database?

Materialized views are also logical view of our data driven by select query but the result of the query will
get stored in the table or disk, also definition of the query will also store in the database .When we see
the performance of Materialized view it is better than normal View because the data of materialized view
will stored in table and table may be indexed so faster for joining also joining is done at the time of
materialized views refresh time so no need to every time fire join statement as in case of view.
Q3. Difference between View vs Materialized View in database

1) In Views query result is not stored in the disk or database but Materialized view allow to store query
result in disk or table. When we create view using any table, rowid of view is same as original table but in
case of Materialized view rowid is different. In case of View we always get latest data but in case of
Materialized view. we need to refresh the view for getting latest data. Performance of View is less than
Materialized view. In case of view its only the logical view of table no separate copy of table but in case of
Materialized view we get physically separate copy of table. In case of Materialized view we need extra
trigger or some automatic method so that we can keep MV refreshed, this is not required for views in
database.

Q4. What are oracle defined or pre-defined Exceptions?

-to_many_rows

-zero_divid_errors

-no_data_found

-invalid_cursor

-dup_value_on_index

Q5. Display the 10th record of the emp table? ( without using row id)

SELECT *

FROM EMP

WHERE ROWNUM <= 10

MINUS
SELECT *

FROM EMP

WHERE ROWNUM < 10;

Q6. Delete the 10th record of EMP table?

DELETE

FROM EMP

WHERE ENAME= (SELECT ENAME

FROM EMP

WHERE ROWNUM<=10

MINUS SELECT ENAME

FROM EMP

WHERE ROWNUM<10);

Q7. What are Schema Objects?

Schema objects is Structures of database’s data. tables, views, sequences, synonyms, indexes are schema
objects.

Q8. What is Data?

Data is collection of information or collection of attribute, example Ravi it’s a data. The information of
Ravi is height, weight, education, age, etc..
Q9. What is a Table?

A table is collection of data to storage in any database. Table data is stored in rows and columns.

Q10. What is a View?

A View is not a original table It’s called virtual table. It’s based on original table

There are three type of tables

Simple view

Complex view

Inline view

Q11. What is an Index?

An index is direct access to rows, used to increase the performance of data retrieval. Index can be
created on one or more columns of a table.

Q12. What is the difference between UNIQUE or PRIMARY KEY Constraint?

UNIQUE constraints allowed NULLs values. PRIMARY KEY constraints cannot contain NULLs.

Q13. What is difference between TRUNCATE and DELETE?

Truncate is after deleting entire table, Cannot be rolled back options. Delete allows the single row and
multiple rows. Deleted records can be rolled back or committed

Q14.What is a join? Explain the different types of joins?

Join is retrieves data from related columns or rows from multiple tables.
Cross Join

Inner join

equi join

non equi join

Outer join

left outer join

right outer join

full outer join

Self join

Q15. What is a Subquery?

Subquery is a query embedded with another query called subquery its return values from mainquery

Q16. What are Difference between SUBSTR and INSTR?

INSTR(str1, str2 [,starting,[howmuch]])

INSTR is returns the position of the character.

SUBSTR(stri1, starting, howmuch)

SUBSTR returns a single or multiple character string

Q17. What is UNION, MINUS, UNION ALL, INTERSECT?

UNION returns all unique rows .

UNION ALL returns all rows included all duplicates.

INTERSECT returns all common row and unique rows selected by both queries.
MINUS returns all unique rows selected by the first query but not by the second.

Q18. What is ROWID?

ROWID is a pseudo column attached to each row of a table. Its create table database assign the rowed in
each rows

Q19. What is PRIMARY KEY, UNIQUE KEY, FOREIGN KEY?

Primary key is a column or a combination of columns of a table which cab be used to uniquely identify a
row of the table. PRIMARY KEY cannot be null.

UNIQUE KEY is a column or a combination of columns of a table, which can be used to identify a row of
the table uniquely. UNIQUE KEY can be null.

FOREIGN KEY is a column or a combination of column which is the primary key or unique key of the
referenced table. FOREIGN KEY can be null.

Q20. What is ON DELETE CASCADE?

Database maintains referential integrity by automatically removing dependent foreign key values if a
referenced primary or unique key value is removed.

Q21. What will be returned from NVL2 (-22,0)?

22

NULL

Q22. Which one is single row subquery operator except one?

>=
<=

in

Q23, An operator is used to get and display the common records

Ans Intersect

Q24. What is database?

A database is a collection of data. Representing some aspect of real world.

Q25. How to check the leap year?

select decode(mod(2004,4),0,’leap year’, ‘not a leap year’) from dual

Q26. Differences between DATE and TIMESTAMP in Oracle?

Date is used to store date and time values including month, day, year, century, hours, minutes and
seconds. It fails to provide granularity and order of execution when finding difference between 2
instances (events) having a difference of less than a second between them. Time Stamp datatype stores
everything that Date stores and additionally stores fractional seconds.

Q27. How many columns can a table have?

Maximum 254 in single table

Q28. When to create indexes?

To be created when table is queried for less in the table rows and need fastest Retrival

Q29. What is the difference between foreign key and reference key ?
Foreign key is which refers to another table primary key. Reference key is the primary key of table
referred by another table.

Q30.How to Get the database file names from Oracle:?

SELECT NAME FROM SYS.V_$DATAFILE;

SELECT NAME FROM SYS.V_$CONTROLFILE;

SELECT MEMBER FROM SYS.V_$LOGFILE;

Q31. What is SQL*Loader?

SQL*Loader is a loader utility used for moving data from external files into the Oracle database in bulk. It
is used for high-performance data loads.

Q32. What are the original Export and Import Utilities?

SQL*Loader, External Tables

Q33. created both procedures.

You new invoke the insert_location procedure using the followingcommand:

Q34. What do you mean by Correlated subquery?

Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query.
Depending on how the subquery is written, it can be executed once for the parent query or it can be
executed once for each row returned by the parent query. If the subquery is executed for each row of the
parent, this is called a correlated subquery.

Q35. Display the depart numbers with more than three employees in each dept.

SQL>select deptno, count(deptno) from emp group by deptno having

count(*)>3;
Q36. Display the various jobs along with a total number of employees in each job?

The output should contain only those jobs with more than three employees.

SQL>select job,count(empno) from emp group by job having count(job)>3

Q37. Display the names of clerks who earn a salary more than the lowest salary of any salesman.

SQL>select ename from emp where job=’CLERK’ and sal>(select min(sal)

from emp

where job=’SALESMAN’);

Q38. Display the names of employees from department number 10 with a salary greater than that of any
employee working in other departments?

SQL>select ename from emp where deptno=10 and sal>any(select sal from

emp where deptno not in 10).

Q39. Can one rename a column in a table? No, this is listed as Enhancement Request
163519.Workarounds:

Rename t1 to t1_base;

Create view t1 <column list with new name> as select * from t1_base;

create table t2 <column list with new name> as select * from t1;

Drop table t1;


Rename t2 to t1;

Q40.To find The Max Salary without MAX Function.

SELECT DISTINCT SAL FROM EMP1 WHERE SAL NOT IN (SELECT SAL FROM EMP1 WHERE SAL < ANY
(SELECT SAL FROM EMP1))

2.SELECT SAL FROM EMP WHERE SAL >= ALL (SELECT SAL FROM EMP)

Q41. Alternate for DESC. SELECT COLUMN_NAME NAME, DECODE (NULLABLE,’N’,’NOT NULL’,’Y’,’ ‘)

“NULL”, CONCAT (DATA_TYPE, DATA_LENGTH) TYPE FROM USER_TAB_COLUMNS

WHERE TABLE_NAME = ‘DEPT’

Q42. SQL> Example for startwith, connect by and prior SELECT ENAME, JOB, LEVEL, EMPNO, MGR FROM
EMP111 CONNECT BY PRIOR EMPNO=MGR START WITH ENAME = ‘RAJA’

SELECT EMPNO, LPAD (‘ ‘, 6*(LEVEL – 1)) || ENAME “EMPLOYEE NAME” FROM EMP START

WITH ENAME=’KING’ CONNECT BY PRIOR EMPNO = MGR

Q43. What is ER Diagram?

Entity – Relational diagram

Could be (a) one to one

(b) One to many (crowfoot style)

(c) Many to many

Q44. Describe Referential Integrity?


A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only
if the value for the column or set of columns matches a value in a column of a related table. It also
specifies the type of data manipulation allowed on referenced data and the action to be performed on
dependent data as a result of any action on referenced data.

Q45.What are the Referential actions supported by FOREIGN KEY integrity constraint?

UPDATE and DELETE Restrict – A referential integrity rule that disallows the update or deletion of
referenced data.

DELETE CASCADE – when a referenced row is deleted, all associated dependent rows are deleted.

Q46.What is self-referential integrity constraint?

If a foreign key reference a parent key of the same table it is called self-referential integrity constraint.

Q47.What are the limitations of a CHECK constraint?

The condition must be a Boolean expression evaluated using the values in the row being inserted or
updated, and cannot contain subqueries, sequences, the SYSDATE, UID, USER, or USERENV SQL functions,
or the pseudocolumns LEVEL or ROWNUM.

Q48. Which script displays ’01-JAN-02′ when the ENROLL_DATE value is ’01-JUL-01′?

A. SELECT ROUND(enroll_date, ‘DAY’) FROM student;

B. SELECT ROUND(enroll_date, ‘YEAR’) FROM student;

C. SELECT ROUND(enroll_date, ‘MONTH’) FROM student;

D. SELECT ROUND(TO_CHAR(enroll_date, ‘YYYY’)) FROM student;

Q49.Which statement is true?

A. The statement will achieve the desired results.

B. The statement will execute, but will NOT enable the PRIMARY KEY constraint.
C. The statement will execute, but will NOT verify that values in the ID column do NOT violate the
constraint.

D. The statement will return a syntax error.

Q50. What is the difference between a view and a synonym?

The synonym is another name of the table used for multiple links of a database. A view is created with
many tables, and virtual columns and with conditions.

Q51. Display the names of employees who earn a salary more than that of Jones or that of salary greater
than that of scott.?

SQL>select ename,sal from emp where sal>(select sal from emp where ename=’JONES’)and sal> (select
sal from emp where ename=’SCOTT’);

Q52. EXECUTE insert_location (19, .San Francisco .) What is the result in this EXECUTE command?

The locations, departments, and employees tables are empty.

The departments table has one row. The locations and the employees tables are empty.

The location table has one row. The departments and the employees tables are empty.

The locations table and the departments table both have one row. The employees table is empty.

Answer(s) D

Q53.What is meant by Auto Close ? Related to database properties.

Auto close is a database property : if this is turned ON, the SQL server database engine will automatically
close the connectivity to user database if its not being used. When new user tried to access the database,
the database will come online.

Q54.What is Auto Update stats and Auto create stats? How its going to affect the database performance?

When Auto create stats is enabled the Query Optimizer creates statistics on individual columns used in a
predicate, if these statistics are not already available. These statistics are necessary to generate the query
plan. They are created on columns that do not have a histogram in an existing statistics object. The name
of the auto-created statistics includes the column name and the object ID in hexadecimal format. Its
going to increase the database performance instead of waiting for the maintenance plan and manual
creation of stats.

Auto update stats is going to update the stats every time whenever a new stats are creating, which in
turn leads optimizer to select the best execution plan and increases the query performance.

Q55.What is SQLOS?

SQLOS is thin layer which allows the communication between the SQL server database engine and
Operating system

Main Objective of SQL OS ::::

Scheduler and IO completion. The SQLOS is responsible for scheduling threads for CPU consumption.
Most threads in SQL Server are run in cooperative mode, which means the thread is responsible for
yielding so that other threads can obtain CPU time. Most IO is asynchronous. The SQLOS is responsible
for signalling threads when IO is completed.

Synchronization primitives: SQL server is a multi-threaded application, so SQLOS is responsible for


managing thread synchronizations.

Memory management: Different components within SQL Server, example plan cache, CLR, lock manager
etc request memory from the SQLOS. Therefore, the SQLOS can control how much memory a component
within SQL Server is consuming.

Deadlock detection and management of the same.

Exception handling framework.

Hosting services for external components such as CLR and MDAC. SQL Server will run threads that are
associated with external component in pre-emptive mode. Pre-emptive mode allows the SQLOS to
prevents runaway threads (threads which will not yield and allow other threads to get CPU execution).
Also the SQLOS can keep track of the memory these external components consume. For example, for CLR
the SQLOS can invoke garbage collection if the CLR process is taking up too much memory.

Q56.What do you mean by SQL server memory Capping?

Limiting the memory of the SQL server, means assigning the maximum and minimum memory to SQL
server. Depending on the Memory allocated to the OS we can assign/allocate memory to SQL server. As
per the recommendation we need to assign approx. 80% of total allocated memory to SQL server.

Q57.What is max memory and minimum memory in SQL server?

Maximum memory is the amount of memory a SQL server instance can pull from the physical memory
allocation at OS level, when ever the SQL server is required. Depending on the memory utilization SQL
server demands the memory from OS.
Minimum memory is the amount of memory SQL server needed to start, generally SQL server database
engine required only 20MB of memory to start the services. But once will allocate minimum memory in
GB then what will happen is SQL server will not release that memory once it will approach that value.

Q58.What are the reasons of SQL server installation failure?

SQL server setup.exe file is corrupted.

Hardware and softwareís are not compatible.

MSI and MSP files are missing.

Donít have enough permission to perform write operation on installation path.

AgentSigning Certificate is not creating.

SQL service account is not having enough permission or it has not been configured in the proper way.

Q59.Where to check for SQL server installation failure reason?

We need to read the details.txt.

SQL server error logs.

Eventviewer at OS level.

Temp folder.

Q60.What is ACID property in SQL server?

ACID (an acronym for Atomicity, Consistency Isolation, Durability) is a concept that Database
Professionals generally look for when evaluating databases and application architectures.

Q61.Explain ACID properties in database?

Atomicity is an all-or-none proposition means its going to treat all the transaction as one or none.

Consistency guarantees that a transaction never leaves your database in a half-finished state, what all
transactions are got committed that transaction will be available and if not the transaction will be
rollback.

Isolation keeps transactions separated from each other until theyíre finished, again its depends on which
isolation level the transaction is running.
Durability guarantees that the database will keep track of pending changes in such a way that the server
can recover from an abnormal termination, its going to calculate the recovery phase based on last
checkpoint.

Q62.What do you mean by Transaction in SQL server?

A transaction consists of a single command or a group of commands that execute as a package.


Transactions allow you to combine multiple operations into a single unit of work. If a failure occurs at one
point in the transaction, all of the updates can be rolled back to their pre-transaction state.

A transaction must conform to the ACID propertiesóatomicity, consistency, isolation, and durabilityóin
order to guarantee data consistency. Most relational database systems, such as Microsoft SQL Server,
support transactions by providing locking, logging, and transaction management facilities whenever a
client application performs an update, insert, or delete operation.

Q63.What do you mean by concurrency in SQL server?

Concurrency is the ability of multiple users to access data at the same time. When the number of
simultaneous operations that the database engine can support is large, the database concurrency is
increased. In Microsoft SQL Server Compact, concurrency control is achieved by using locks to help
protect data. The locks control how multiple users can access and change shared data at the same time
without conflicting with each other.

Q64.What are different types of concurrency in SQL server?

Optimistic concurrency: Optimistic concurrency control works on the assumption that resource conflicts
between multiple users are unlikely, and it permits transactions to execute without locking any
resources. The resources are checked only when transactions are trying to change data. This determines
whether any conflict has occurred (for example, by checking a version number). If a conflict occurs, the
application must read the data and try the change again. Optimistic concurrency control is not provided
with the product, but you can build it into your application manually by tracking database access.

Pessimistic concurrency: Pessimistic concurrency control locks resources as needed, for the duration of a
transaction. SQL Server Compact supports pessimistic concurrency control that locks resources as needed
for the duration of a transaction.

Q65.What are different level of transaction Isolation level? Explain them.

Uncommitted Read: Uncommitted Read, or dirty read, lets a transaction read any data currently on a
data page, whether or not that data has been committed. For example, although another user might have
a transaction in progress that has updated data, and that transaction is holding exclusive locks on the
data, your transaction can read the data anyway, and possibly take further actions based on the values
you read. The other user might then decide to roll back his or her transaction, so logically, those changes
never occurred. Although this scenario isn’t desirable, with Uncommitted Read you won’t get stuck
waiting for a lock, nor will your reads acquire share locks that might affect others.

Committed Read: Committed Read is SQL Server’s default isolation level. It ensures that an operation will
never read data another application has changed but not yet committed. Because you can never read
uncommitted data, if a transaction running with Committed Read isolation revisits data, that data might
have changed, or new rows might appear that meet the criteria of the original query. Rows that appear in
this way are called phantoms.

Repeatable Read: If you want the read operations to be repeatable, choose the third repeatable Read.
The Repeatable Read isolation level adds to the properties of Committed Read by ensuring that if a
transaction revisits data or if a query is reissued, the data will not have changed. In other words, issuing
the same query twice within a transaction won’t pick up any changes to data values that another user’s
transaction has made. No other user can modify the data that your transaction visits as long as you have
not yet committed or rolled back your transaction.

Serializable: The Serializable isolation level ensures that if a query is reissued, no data will have changed
and no new rows will appear in the interim. In other words, you won’t see phantoms if the same query is
issued twice within a transaction. Rerun the example from the Repeatable Reads section, inserting a row
with a col1 value of 35. But this time, set your isolation level to SERIALIZABLE. The second connection will
block when you try to do the INSERT, and the first connection will read exactly the same rows each time.

SNAPSHOT: Specifies that data read by any statement in a transaction will be the transaction ally
consistent version of the data that existed at the start of the transaction. The transaction can only
recognize data modifications that were committed before the start of the transaction. Data modifications
made by other transactions after the start of the current transaction are not visible to statements
executing in the current transaction. The effect is as if the statements in a transaction get a snapshot of
the committed data as it existed at the start of the transactions.

Q66.Can we restore the database to point of time in simple recovery mode?

No, it not possible to restore the database in point of time in simple recovery mode.

Cause in simple recovery mode, we are not having the transaction log backup.

Q67.What is .tuf file and .wrk file in log shipping?

TUF File: Its Transaction Undo File. It Generated only when you Have Configured Log Shipping with Stand
by Option. Since in Stand by Log Shipping Secondary Database is Available to User. So TUF Keep Pending
Transaction Which are in Log File Came from Primary So That when Next Log Backup Will Come from
Primary They Can Be Synchronized at Secondary.

WRK: This Extension Is Given to A File Which is Being Copied from Primary Backup Location to Secondary
and Once Copy Process has been completed these files are renamed with .trn file.

Q68.Can we configure Log shipping for multiple secondary? If yes how?


Yes, we can configure the multiple secondaries in log shipping. As the log shipping is a database level
configuration. We can have the appropriate permission to the network path where the log backup is
getting generated.

Q69.What is meant by RPO and RTO?

RTO stands for Recovery Time Objective: In simple terms, you can think of RTO as a measure of how
much downtime is acceptable, or how quickly must the data be made accessible again. RTO is often
talked about in terms of the number of nines of desirable up time or accessibility for the
data/database/system.

RPO stands for Recovery Point Objective: Again, in simple terms, you can think of RPO as a measure of
how much data or work itís acceptable to lose. Itís relatively easy to achieve very minimal or even zero
data/work loss using backups but depending on the amount of damage the database suffered when the
disaster hit, recovering might take a lot of time. For instance, if an entire database is destroyed,
depending on the architecture of the database and the backups that exist, it may take a significant
amount of time to recover the database up to the point of the disaster. Most RPOs are defined as the
amount of time for which work may be lost.

Both RTO and RPO together called as SLA.

Q70.What is your Backup strategy for Production servers?

Generally: We will schedule a Full backup on every weekend followed by differential backup every day
post business hours like 10 PM, followed by log backup every one hour.

If the database is highly critical, we will schedule a full backup every day post business hour like 10PM
followed by log backup every 1 hour or 30 mins.

Depending on the Recovery model and transactions will configure the log backup in range of 15mins to
60 mins.

Q71.What is fill factor? How its affect the database performance?

Fill factor is the value that determines the percentage of space on each leaf-level page to be filled with
data. In an SQL Server, the smallest unit is a page, which is made of page with size 8K. Every page can
store one or more rows based on the size of the row. The default value of the Fill Factor is 100, which is
same as value 0. The default Fill Factor (100 or 0) will allow the SQL Server to fill the leaf-level pages of an
index with the maximum numbers of the rows it can fit. There will be no or very little empty space left in
the page, when the fill factor is 100.

Fill factor will play a significant role in database performance by minimising the affect of page split which
in turns leads to the optimal performance at IO level.
Q72. Can we configure mirroring from lower to higher version? Is this recommended?

Yes we can configure the mirroring between two different SQL server versions.

But this is not recommended, as its not going to support the backward compatibility during mirroring
failover.

Q73.What is Lock escalation?

Lock escalation is the process of converting many fine-grained locks (such as row or page locks) into table
locks. Microsoft SQL Server dynamically determines when to perform lock escalation. When making this
decision, SQL Server takes into account the number of locks that are held on a particular scan, the
number of locks that are held by the whole transaction, and the memory that is being used for locks in
the system as a whole.

Q74.What is wait_types? How we can get the information about wait_type?

wait types represent the discrete steps in query processing, where a query waits for resources as the
instance completes the request.

To get the information for wait type we will use below mentioned DMV.

Sys.dm_os_wait_stats

Sys.dm_os_waiting_tasks

Q75.What is the difference between PAGEIOLATCH and PAGELATCH?

Page Latch ñ These are waits that occur when a worker needs to wait for a page to become available. This
typically occurs on a page is already available in memory.

Page IO Latch ñ These are waits that occur when a needs to wait for a page due to physical I/O. Such as
when a page needs to be made available in the buffer pool for reading or writing and SQL Server needs to
retrieve it from disk or mount points.

Q76.List out some of the requirements to setup a SQL Server failover cluster.

Virtual network name for the SQL Server, Virtual IP address for SQL Server, IP addresses for the Public
Network and Private Network(also referred as Heartbeat) for each node in the failover cluster, shared
drives for SQL Server Data and Log files, Quorum Disk, and MSDTC Disk.
Q77.Can we read the mirror database? How?

We canít read the mirror database, as the database is in restoring mode always. So read and write
operations cannot be performed on the database.

To read a mirror database we need to create a snapshot of that database.

Q78.Can we migrate a 500GB database without having downtime? How?

Yes, we can migrate a 500GB or of any size database without downtime or minimal downtime of few
mins like 5mins.

By configuring a high availability concepts like log shipping or mirroring.

Q79.Can we add a new data file on primary in log shipping? How its going to affect the log shipping
setup?

Yes, we can add the new data file on primary database in log shipping.

If the primary and secondary servers is having the same disk configuration i.e. the data file locations on
both the servers are exactly same in that case there will be no affect on the log shipping behaviour and if
not then the changes made on the primary will not reflect on the secondary.

Q80.Can we create a blank database of size 2MB on SQL 2016?

No, its not possible, cause the blank database will take the template from model database and the size of
model database is 16 MB (8 MB for data and 8 MB for log). So, we must have to provide size either equal
to model or more than model database.

Q81.Explain what stored procedure sp_replcounters is used for?

Sp_replcounters is a system stored procedure that returns information about the transaction rate,
latency, and first and last log sequence number (LSN) for each publication on a server. This is run on the
publishing server. Running this stored procedure on a server that is acting as the distributor or
subscribing to publications from another server will not return any data.

Q82.Can you tell me some of the common replication DMV’s and their use?
sys.dm_repl_articles – Contains information about each article being published. It returns data from the
database being published and returns a row for each object being published in each article.

sys.dm_repl_schemas – Contains information about each table and column being published. It returns
data from the database being published and returns one row for each column in each object being
published

sys.dm_repl_traninfo – Contains information about each transaction in a transactional replication.

Q83.How to troubleshoot if SQL server service is not coming online on cluster network?

In this case we need to pull out the dependency report first. After that we need to see on which all
factors the SQL server service is dependent and which factor is right now creating issue while SQL
services is trying to come online.

Like : SQL server service is dependent on shared disks, ip addresses, storage. May be the dependency is
either OR or AND.

Q84.Does AlwaysON supports on Bulk and simple recovery mode?

No, it supports only on Full recovery mode.

Q85.Can we take the T-Log backup of a newly created database?

No, we cannot take a T-Log backup of a newly created database. Until and unless we will not take the full
backup of database in spite of database recovery model, the database will behave as its being configured
on simple recovery mode.

Q86.Is it possible to create additional indexes on read-only secondary replicas to improve query
performance in AlwaysON?

No, itís not possible.

Q87.Is it possible to create additional statistics on read-only secondaries to improve query performance
in AlwaysON?

No, but we can allow SQL server to automatically create statistics on read only secondary replicas.

Q88.What is read intent option in AlwaysON?


There are two options to configure secondary replica for running read workload. The first option ëRead-
intent-onlyí is used to provide a directive to AlwaysOn secondary replica to accept connections that have
the property ApplicationIntent=ReadOnly set. The word ëintentí is important here as there is no
application check made to guarantee that there are no DDL/DML operations in the application connecting
with ëReadOnlyí but an assumption is made that customer will only connect read workloads.

Q89.Does AlwaysOn Availability Groups repair the data page corruption as Database Mirroring? Explain

Yes. If a corrupt page is detected, SQL Server will attempt to repair the page by getting it from another
replica.

Q90.Whatís the difference between AGs in SQL 2012 and SQL 2014?

SQL Server 2014ís biggest improvement is that the replicaís databases stay visible when the primary
drops offline ñ as long as the underlying cluster is still up and running. If we have one primary and four
secondary replicas, and we lose just my primary, the secondaries are still online servicing read-only
queries. (Now, you may have difficulties connecting to them unless youíre using the secondaryís name,
but thatís another story.) Back in SQL 2012, when the primary dropped offline, all of the secondariesí
copies immediately dropped offline ñ breaking all read-only reporting queries.

Q91.What is maxdop? What is the recommended setting?

When SQL Server runs on a computer with more than one processor or CPU, it detects the best degree of
parallelism, that is the number of processors employed to run a single statement, for each query that has
a parallel execution plan. You can use the max degree of parallelism option to limit the number of
processors to use for parallel plan execution and to prevent run-away queries from impacting SQL Server
performance by using all available CPUs.

The default value for MAXDOP is 0 (zero) and can be set or viewed using (sp_configure). A value of 0
means that SQL Server will use all processors if a query runs in parallel.

Q92.What is the significant of log_reuse_wait_desc column in sys.databases?

It will tell us why the database log file isnít clearing out. By reading the column we will get to know what
action needs to be performed on log file in order to truncate the log file.

Q93.Can checkpoint be used for crash recovery, if a checkpoint starts but doesnít finish before a crash
occurs?
No.

The purpose of a checkpoint is to bring the pages in the data files up-to-date with whatís in the
transaction log. When a checkpoint ends, thereís a guarantee that as of the LSN of the LOP_BEGIN_CKPT
log record, all changes from log records before that point are persisted in the data files on disk. Thereís
no guarantee about logged changes after that point, only before it. In other words, all the log records
before the LSN of the LOP_BEGIN_CKPT log record are no longer required for crash recovery, unless
thereís a long running transaction that started before that LSN.

Q94.Can SQL Server guarantee that thereís always one complete checkpoint in the active portion of the
log, in case a crash occurs?

The answer is that log clearing/truncation of a VLF containing an LOP_BEGIN_CKPT log record cannot
happen until another complete checkpoint has occurred. In other words, a complete checkpoint has to
occur since the last log clearing/truncation before the next one can happen. If a checkpoint hasnít
occurred, the log_reuse_wait_desc for the database in sys.databases will return CHECKPOINT. Itís not
common to see this occur, but you might see it if thereís a very long running checkpoint (e.g. a very large
update on a system with a slow I/O subsystem so the flushing of data file pages takes a long time) and
very frequent log backups, so two log backups occur over the time taken by a single checkpoint
operation. It could also happen if youíve messed with the sp_configure recovery interval and set it higher
than the default.

Q95.Does ghost records occur in heaps? Explain

No.

When snapshot isolation is enabled, deletes from a heap are ghosted, as part of the overall versioning
process, which can lead to some interesting side-effects. A versioned record has an extra 14-bytes tagged
on the end, so a heap record that suddenly becomes versioned is 14-bytes longer ñ which may mean it
doesnít fit on the page any longer. This could lead to it being moved, resulting in a forwarding/forwarded
record pair ñ just because the record was deleted! Now, the page has to be full for this time happen, and
the Storage Engine will take steps to avoid this happening for rows less than 32 bytes long.

Q96.If a table is truncated during a transaction, does the integrity of the tableís pages protected in case
the transaction rolls back? Explain.

All the pages and extents are locked. The table doesnít show them as allocated any more but because
theyíre exclusively locked, the allocation subsystem canít really deallocate them until the locks are
dropped (when the transaction commits).

They canít be reused until theyíre really deallocated. If a transaction rollback happens, the pages are just
marked as allocated again.
Use the DMV sys.dm_tran_locks.

Q97.A databaseís log grew so large that I had to delete it, but on restarting SQL Server the database was
in RECOVERY_PENDING mode and inaccessible! Whatís gone wrong? Explain

If there was a clean shut down, SQL Server marks it in database boot page, and so knows that it does not
need to run recovery, during restart, and therefore does not need the original transaction log. In such
cases, we can attach the database without the log, and SQL Server will simply create a new log.

However, if there is no mark indicating a clean shutdown, and this is never guaranteed, then SQL Server
must run recovery during restart, which it canít do without the original log, and which is the reason why
youíve ended up with a RECOVERY_PENDING database. It simply means there wasnít a clean shutdown
and SQL Server canít start the recovery process because you whacked the log.

The recovery process uses the contents of the log to re-establish transactional consistency. During
recovery SQL Server will redo the effects of any transaction that was not included in the last CHECKPOINT
to run before the database went offline, and undo the effects of any uncommitted transaction that was
included in the last CHECKPOINT.

Q98.After checking DBCC LOGINFO found that log had 2000 VLFs. Is it something to worry about? Explain.

It could be a problem, yes. Generally, it depends on the overall size of the log. Itís common, and not really
an issue, to see a very large transaction log with several hundred VLFs, but several thousand is a concern
regardless of overall log size.

Always try to shrink the log file, which will help us in reducing the VLF numbers.

Q99.If all operations are logged, what happens during non-logged operations? Like Truncate.

The TRUNCATE command is not a non-logged operation. In fact, it is fully logged. With very few
exceptions, namely one or two operations in tempdb such as operations on the version store, there is no
such thing as a non-logged operation in SQL Server. Operations such as TRUNCATE TABLE and DROP
TABLE are fully logged, but SQL Server uses an efficient, deferred de-allocation mechanism that means
the commands seem to be instantaneous, regardless of the size of the table. This fact, coupled with some
misleading terminology, including in several Microsoft articles, lead to the mistaken belief that these
operations are not logged at all.

Q100.I take regular log backups, but the log has still grown to a massive size and DBCC SHRINKFILE is
having no effect at all Why? And what can I do about it?

When operating a database in FULL or BULKLOGGED recovery model, all log records must remain in the
log, as part of the active log, until they have been captured in a log backup. Otherwise, the log backups
could not guarantee to capture the complete, unbroken chain of LSNs that are required for database
restore and recovery.

In these recovery models, only a log backup will cause SQL Server to run the ìlog clearingî process, also
referred to as log truncation. During log truncation, SQL Server will mark as inactive any VLFs that contain
no part of the active log, i.e. VLFs that contain no log records that SQL Server still requires for recovery, or
for log backup, or for any other process.

SQL Server will run log truncation after every log backup and, each time, any inactive VLFs that result will
be available for reuse to store new log records, overwriting the existing log records that are no longer
required. Therefore, when SQL Server reaches the end of the log.

However, itís possible that there will be periods where successive log truncations produce zero inactive
VLFS, because there are other factors that can prevent SQL Server reusing space in the log. If there are no
inactive VLFs available, then SQL Server has no other choice but to grow the log, adding more VLFs.

This is likely what is happening in this case; some other process is forcing SQL Server to retain log records
in the active log, and so successive executions of the log truncation process arenít producing any more
inactive VLFs. Attempts to shrink the log will have no effect in this situation as there is no free space to
remove! DBCCSHRINKFILE can only physically remove unused or inactive VLFs that are at the end of the
log file.

Q101.How many data files preferred for TempDB for better performance?

We must have data files equivalent to number of CPU processors or if CPU is greater than 8, then at least
we have 8 data files for TempDB and the size of data files must be same.

As well always mount the TempDB on separate disk for better performance.

Q102.How checkpoint affect TempDB?

A checkpoint is only done for tempdb when the tempdb log file reaches 70% full ñ this is to prevent the
tempdb log from growing if at all possible, that a long-running transaction can still essentially hold the log
hostage and prevent it from clearing.

This does not happen for tempdb. Tempdb is not recovered in the event of a crash, and so there is no
need to force dirty tempdb pages to disk, except in the case where the lazy writer process (part of the
buffer pool) has to make space for pages from other databases. Of course, when you issue a *manual*
CHECKPOINT, all the dirty pages are flushed, but for automatic checkpoints theyíre not.

Q103.Buffer pool contains so many of dirty pages related to TempDB? Why?

The reasons that checkpoint exists is to limit the duration of the “redo” phase of crash recovery ñ where
log records are replayed on disk pages where the updated page image hadn’t been written to disk after
the transactions committed. Automatic checkpoints are done in databases to do this.
Tempdb, however, isn’t recovered after a crash ñ it’s recreated. This means that the time for recovery of
tempdb isn’t an issue so there’s no need for automatic checkpoints. This means that the trigger of an
automatic checkpoint for tempdb when it’s log file reaches 70% full. For this reason, on busy systems, it’s
likely that the user databases are being checkpointed way more often than tempdb, and on a system
where tempdb is used heavily too, there will likely be way more dirty pages from tempdb in the buffer
pool at any time.

Q104.What all Transaction Log is available in Full backup? What is its significance?

The full backup has to include all the transaction log from the begin LSN of the oldest active transaction at
the time the data read portion of the backup ends, until the LSN at which the data read portion ends. If
that begin LSN is later in time than the LSN of the checkpoint that backup does initially.

Which is going to help in point in time Recovery.

Q105.What is the cause, log_reuse_wait_desc is showing Replication and still the Replication has not
been configured on database?

The issue happened due to CDC ñ change data capture. Check the is_cdc_enabled flag in sys.databases.

CDC uses the replication log scanning mechanism to harvest changes from the database, either backing
on replicationís Log Reader Agent job or creating itís own capture job if replication isnít configured. If CDC
is configured but the capture job isnít running, the log_reuse_wait_desc will show as REPLICATION, as the
log manager doesnít have any way to know why the replication log scanner is configured, just that it is,
and it hasnít run.

Q106. How to write sql query to get the data from table but column should contain the unique values?

SELECT DISTINCT(COL_NAME) FROM TABLE_NAME

Q107. How View works ?

View is work like sql query which can be write to select the data based on condition. So instead of
executing that big query and frequently write the same query again we can use view.

Select * from view_name

Q108. What is indexing and why to use?


Indexing applied on key columns of table which frequently used to get the records form database and it
helps the database to search for the selected records and give the result fast.

Q109. How to fetch data from employee details who are from Bangalore city?

Select * from employee where city=’’Bangalore’;

Q110. What is the command to get back the privileges provided by the GRANT command?

Revoke command used to get back the privileges.

Q111. How to create a table by copying only the structure of another table?

Below is the sql command to perform the same.

CREATE TABLE EMPLOYEE_DETAILS AS SELECT * FROM EMPLOYEES_INFO WHERE 1=2

Q112. How to drop a column from a table?

Using Drop along with alter table command , column can be drop. Below is the query for the same.

ALTER TABLE TAB_NAME DROP COLUMN COL_NAME

Q113. What is the use recursive stored procedure?

This stored procedure used to perform some activity based on threshold and get called based on
configuration which saves code to perform some external operation.

Q114. How to use Alias?

Alias can can be given on table/column. This is just define a name for table/column which is referred the
table/column with different name which helps to short query and achieve joins to identify the same
column from different table. Below is the example for the same.
SELECT EMP.EMLOYEE_ID, DEPT.EMPLOYEE_ID FROM EMPLOYEE EMP , DEPARTEMENT DEPT

Q115. Difference between TRUNCATE and DROP statements?

Truncate – This delete all the record from table

Drop – This delete/Remove the table from database.

Q116. How to create database in mysql?

Below is the sql to create database

CREATE DATABASE DB_NAME;

Q117. How to drop database in mysql?

Below is the sql to drop database

DROP DATABASE DB_NAME;

Q118. How to create a replica of existing table?

CREATE TABLE NEW_TABLE_NAME LIKE EXISTING_TABLE_NAME;

Q119. Write a SQL statement to display all the record from employee table which has salary above 50000

Select * from employee where salary >50000;

Q120. What is Union and how to write sql?


This used to join multiple tables or combine result set of two or more tables and it allows only distinct
values.

SELECT col1,col2 FROM TABLE_1

UNION

SELECT col1,col2 FROM TABLE_2;

Q121. What is Union All and how to apply on tables ?

This is used to combine multiple table and it allows duplicate values.

SELECT col1,col2 FROM TABLE_1

UNION ALL

SELECT col1,col2 FROM TABLE_2;

Q122. What is like and how to use it?

It’s an operator which is used filter the data based on keyword. This is mostly used to perform search
operation when exact word don’t remember. SELECT * FROM EMPLOYEE WHERE EMP_NAME LIKE
‘Sac%’;

Q123. What does MIN(),MAX() functions do?

MIN()- This function returns the minimum value of a column on which applied.

MAX()- This function returns the maximum value of a column on which applied.

SELECT MIN(SALARY) AS LOWEST_SALARY FROM EMPLOYEE_DETAILS;


SELECT MAX(SALARY) AS HIGHEST_SALARY FROM EMPLOYEE_DETAILS;

Q124. What is BETWEEN and how it works?

It’s an operator which works to select values within a given range. Below is the example

SELECT * FROM EMPLOYEE WHERE EMP_ID BETWEEN 1011 AND 2021;

Q125. How the UPDATE statement works internally and how to use it?

Update statement works concurrently , Below is the example for the same.

UPDATE EMPLOYEE_DETAILS SET EMP_NAME = ‘Bansal Ashok’, CITY= ‘KOTA’ WHERE EMP_ID = 1;

Q126. What is join and what are the types of joins is there?

Join used to combine two or more tables using joins.Below are the list of joins which are categorized.

Full join

Left Join

Right join

Inner join

Self Join

Q127. How Left Join works?

This gives the entire record form left table and the matched respective records from the linked table.

Q128. How to get the total number of records present in a table?

To get the count we use COUNT(*) function , below is the query for the same.
SELECT COUNT(*) FROM EMPLOYEES_DETAILS;

Q129. How to search a substring of name?

LIKE operator can be use in where clause to get the records for substring

Select EMP_ID,EMP_NAME EMPLOYEE_DETAILS WHERE EMP_NAME like ‘%Agar’;

Q130. How to take table records with some limit in Mysql?

LIMIT need to use with table while writing selection sql,below is the sql for the same.

SELECT * FROM EMP_DETAILS LIMIT 5;

Q131. What is distinct keyword and how it works?

Distinct keyword used to filter the record and works as exclude the duplicate values for the selected
column in table.

Q132. What is Where clause?

When the data has to filter based on some condition that can be achieved using where clause.

Q133. What is AND operator in SQL?

This AND operator applied between multiple condition to select the records(Data) , if all the conditions
are satisfied then only it produce the output.

Q134. What is the NULL value in SQL?

NULL referred no value , It’s not referred to 0 as well. This is give definition as data not available.

Q135. What is NOT operator in SQL?


This operators works when you need the data against the matched condition so this will be applied on
condition which will exclude the satisfied data.

Q136. What is OR operator?

This operator works two or more condition on the selected data , This will be giving results even if one
condition is satisfied.

Q137. What is Order by Statement in SQL?

Order by the statement is used to sort the produced result in SQL. When the result Is generated, and we
want it to get produced in any of the sorted format, order by is the statement to be used. Also, order by
works with both Ascending & Descending order.

Q138. How Insert into Statement works?

When data need to insert in existing table , insert into can be use which will append data from one to
another table.

Q139. How to update multiple column in same table using an update?

Below is the query for the same.

Update table_name set col1=val1 , col2=val2 where col3=val3;

Q140. How DELETE works in SQL?

Delete works on records of table. Record can be deleted based on conditions which can be write with
where clause and select data will get deleted from table.

Q141. What is the use of right Join?


Join used to perform to get the record from multiple tables and right join select the complete record
from right table and matched records from the linked table.

Q142. What is the use of TOP keyword?

This used to give the number of records from the table which you have observed and it works with order
by to sort in the same manner.

Q143. How do get the lowest and highest data from a table?

MIN(),MAX() can be used to get the same.

Q144. What is the commonly used aggregate function in SQL?

SUM(), AVG() & COUNT() – These are mostly used in sql to work on calculation.

Q145. What is the use of IN operator in SQL?

IN operator helps to get the multiple records pass as condition and IN helps to write sub query as well.

Q146. What is the mean by SQL Join?

Join is helps to get the records from multiple tables based on conditions , that can be categorized in inner
join , full outer join, left join , right join , self join.

Q147. What is the use of INNER join in SQL?

Inner JOIN select the data from both the tables which has common reference key data in both the tables.

Q148. What is the use of FULL OUTER join in SQL?

FULL OUTER JOIN select the all the records from both the tables. If any value not matching also it will put
null on that place.
Q149. What is the use of SELF join in SQL?

SELF JOIN used to perform on the same table based on the key matching.

Q150. How to write to display a string like ‘Life is all about the next step’?

Select “Life is all about the next step”

Q151. How to write sql query to get 3 numbers in 3 columns?

Select 5, 10, 15

Q152. How to write query to get the sum of 100 and 55?

Select 100 + 55

Q153. How change database from one to another?

Use DATABASE_NAME

Q154. Which are the conditional clauses in SQL?

Below two is the conditional clause

Where

Having

Q155. What is the difference between Where and Having?


Bothe are conditional clauses whereas Where can executed before retrieving the records but having can
be used after getting the records.

Q156. Difference between Group and Order by?

Group by is used to categorized/classify the records and order by used to get the data in ascending and
descending order.

Q157. What is the use of stored procedure?

To run the set of sql statement together which can accept input and can produce result. Whenever c that
sql statements has to execute will call procedure so internally it will execute sql statements.

Q1. What is PL/SQL?

PL/SQL is a procedural language that has both interactive SQL and procedurl programming language
constructs such as iteration ,conditional branching etc.

Q2. What is the basic structure of PL/SQL?

PL/SQL uses block structure as its basic structure and Anonymous blocks or nested blocks can be used in
PL/SQL.

Q3. What is cursor ? Why cursor is required?

Cursor is named private SQL area from where information can be accessed and Cursors are required to
process rows individually for queries returning multiple rows.

Q4. Explain the two types of cursors?

There are two types of cursors

i. Implicit cursors

ii. Explicit cursors


Q5. What is the cursor attributes used in PL/SQL? OPEN

Q6. What is Exception in Oracle?

Errors during runtime processing due to hardware / network failure / application logic errors are
exception.

Q7. When is the CURSOR_ALRADY_OPEN exception raised?

This exception is raised when the program the program tries to open an already opened cursor. The
cursor be closed before it can opened again.

Q8. Is there a limit on the size of a PL/SQL block?

Currently the maximum parsed size of a PL/SQL block is 64K and the maxium code size is 100K.

Q9. What are the advantages of Stored Procedures?

Precompile, Extensible, Modular, Reusable, Maintainable

Q10. Can standalone programs be overloaded?

No, Stand-alone programs cannot be overloaded. However packaged sub programs can be overloaded
within the same package.

Q11. What is a database of data?

A database is a collection for quicker and easier access, storage, and manipulation in a manner. It can also
be defined as a set of tables, schemas, views, and other objects in the database.

Q12. What is a Warehouse for Data?

The data center refers to a shared of various data sources. These data are consolidated, converted, and
made available for mining and online processing purposes.
Q13.In a database, what is a table?

A table is a database object to store in the form of columns and rows holding data in a field.

Q14. In a database, what is a field?

A field in a database is inside a table to store a specific record.

Q15. In a database, what is a record?

An set of similar data in a table is also called a row of data.

Q16. What is a Table Column?

A column is a vertical object in a table containing all of the information associated with a particular table
area.

Q17. What is a DBMS system?

The Database Management System is a series of programs that allowed a user to store, retrieve, set
update and delete data from a database.

Q18. What kinds of DBMS are there?

There are two types of DBMS that are

Method for Relational Database Management (RDBMS)

Method of Non-Relational Database Management

Q19. What does RDBMS mean?


RDBMS stands for Management Framework for Relational Databases. RDBMS is a framework for
database management (DBMS) based on a relational model. It is possible to access data from a relational
database

Q20. What are the IT industry's common database management systems?

Oracle, MySQL, Microsoft SQL Server, PostgreSQL, Sybase, Microsoft Access, MongoDB, DB2, etc.

Q21. And what's SQL?

SQL stands for Language of Queries. It is a standard from the American National Standard Institute (ANSI).
It is a databases to be and manipulated. Some of the actions we can do using SQL are to tables, stored
procedures (SP’s), queries, retrieve, attach, update.

Q22. In SQL, what are the various DDL commands?

To describe or alter the layout of the database, DDL commands are used. Build: To create databases and
objects for databases

ALTER: To alter current artifacts of the database DROP: Removing items from databases and databases

Q23. In SQL, what are the various DML commands?

For the management of data in the database, DML commands are used. SELECT: To select a database
unique data

INSERT: Inserting new records into a table UPDATE: Reviewing latest records

Q24. In SQL, what are the various DCL commands?

To build positions, grant permission and monitor access to database objects, DCL commands are used.
GRANT: Ensuring access for user

DENY: To deny account authorization to users REVOKE: Removing user access


Q25. In SQL, what are the various TCL commands?

To control the changes made by DML statements, TCL commands are used. COMMIT: To write and store
database changes

ROLLBACK: To recover the database from the last committed date

Q26. What's an Index, then?

To speed up the efficiency of queries, an index is used. This makes the extraction of data from the table
easier. It is possible to construct an index for one column or a group of columns.

Q27. What are all the various index types?

There are three kinds of indexes that are

Unique Index: Unique Indexes help to preserve data integrity by ensuring that there are no equivalent
key values in two rows of data in a database. It is possible to automatically add a unique index when a
primary key is specified. This means that the values are unique in the index key

Clustered Index: The clustered index registers the physical order of the table and searches for key values.
Just cluster is going to

Q28. What is the distinction between the index of clusters and the index of non-clusters?

The clustered and non-clustered index variations in SQL are as follows:

Index Clustered:

It is used for quick database data retrieval and it is quicker. An only clustered index can have a table

It changes the way records are stored in a database by sorting rows by the column set to index clusters.
Index Non-Clustered:
Q29. What are the constraints of SQL?

SQL constraints are the collection of rules that have placed such limits as data is added, removed or
modified in databases.

Q30. What are the benefits of opinions?

Some of the benefits provided by Views are Views don’t occupy space

Q31. What is a partnership and what are these relationships?

The database relationship is known as the link in the database between the tables. Different database
relationships exist, namely,

Relation One to One

One Friendship with Many

Relationship Many to One

Relationship Self-referencing

Q32. What is a search?

A request for data or information from a database table or combination of tables is a database query.
Either a pick query or an action query may be a database query.

Q33. What's the Subquisition?

A Subquery is a SQL query within a separate It is a subset of the Select statement whose return values are
used when the key query.

Q34. What types of sub-queries are there?

Two types of sub- exist:


Correlated: A Correlated is in a SQL database query that uses outer query values to complete the
query. Since the needs that the outer query be first the Correlated be executed once for each row of the
query. It is often referred to as a synchronized

Non-Correlated: A Non-Correlated is a that includes both the internal and the external

Q35. What is the Integrity of Data?

The accuracy and of the data stored in a database is specified by data integrity. It also defines integrity
constraints when entering into an application or a database to impose business rules on the data.

Q36. In SQL, what is Auto Increment?

It’s one of the important questions for the Oracle DBA Interview.

The Auto Increment the user to create a number when a new record is inserted into a table to be
created. You may use the Auto increase keyword whenever the primary key is used.

Oracle uses the AUTO INCREMENT keyword, and SQL Server uses the IDENTITY keyword.

Q37. What's a temp table about?

Ans. ANS. A temporary storage system to temporarily store the data is a temp table.

Q38. In SQL, what is CLAUSE?

By having a requirement for a SQL query, SQL CLAUSE to restrict the result collection. A CLAUSE helps to
filter the rows from the record collection. SQL CLAUSES are Getting & When.

Q39. SQL Data Forms Explain?

In SQL Server, each has a name and a data form in a database table. When constructing a SQL table, we
need to data to store within each and every column of a table.
Q40. What is the procedure for storage?

A Stored Procedure is a of SQL that have been created to perform a specific task and stored in the
database. Input parameters are accepted and processed by the stored procedure and return a single
value, such as a number or text value or a result set.

There is more to interviewing than tricky technical questions, so these are intended merely as a guide.
Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all
guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work.

So this brings us to the end of the SQL interview questions. I hope this set of SQL Interview Questions will
help you ace your job interview. All the best for your interview!

You might also like