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

DBMS interview1-merged-1

The document provides a comprehensive list of popular database interview questions and answers, covering fundamental concepts such as databases, DBMS, RDBMS, SQL, normalization, and various types of relationships. It also discusses advanced topics like data independence, views, functional dependencies, and different types of joins. Additionally, it addresses database transactions, indexing, and the importance of database partitioning, making it a valuable resource for interview preparation.

Uploaded by

radha krishnan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DBMS interview1-merged-1

The document provides a comprehensive list of popular database interview questions and answers, covering fundamental concepts such as databases, DBMS, RDBMS, SQL, normalization, and various types of relationships. It also discusses advanced topics like data independence, views, functional dependencies, and different types of joins. Additionally, it addresses database transactions, indexing, and the importance of database partitioning, making it a valuable resource for interview preparation.

Uploaded by

radha krishnan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Most Popular Database Interview Questions And Answers

Given below is a list of most popular Database interview questions and answers for your
reference.

Q #1) What do you understand by ‘Database’?

Answer: Database is an organized collection of related data where the data is stored and
organized to serve some specific purpose.

For Example, A librarian maintain a database of all the information related to the books
that are available in the library.

Q #2) Define DBMS.

Answer: DBMS stands for Database Management System. It is a collection of application


programs which allow the user to organize, restore and retrieve information about data
efficiently and as effectively as possible.

Some of the popular DBMS’s are MySql, Oracle, Sybase, etc.

Q #3) Define RDBMS.

Answer: Relational Database Management System(RDBMS) is based on a relational model


of data that is stored in databases in separate tables and they are related to the use of a
common column. Data can be accessed easily from the relational database using
Structured Query Language (SQL).

Q #4) Enlist the advantages of DBMS.

Answer: The advantages of DBMS includes:

Data is stored in a structured way and hence redundancy is controlled.


Validates the data entered and provide restrictions on unauthorized access to the
database.
Provides backup and recovery of the data when required.
It provides multiple user interfaces.

Q #5) What do you understand by Data Redundancy?

Answer: Duplication of data in the database is known as data redundancy. As a result of


data redundancy, duplicated data is present at multiple locations, hence it leads to
wastage of the storage space and the integrity of the database is destroyed.

Q #6) What are the various types of relationships in Database? Define them.

Answer: There are 3 types of relationships in Database:
One-to-one: One table has a relationship with another table having the similar kind
of column. Each primary key relates to only one or no record in the related table.
One-to-many: One table has a relationship with another table that has primary and
foreign key relations. The primary key table contains only one record that relates to
none, one or many records in the related table.
Many-to-many: Each record in both the tables can relate to many numbers of
records in another table.

Q #7) Explain Normalization and De-Normalization.

Answer:

Normalization is the process of removing redundant data from the database by splitting
the table in a well-defined manner in order to maintain data integrity. This process saves
much of the storage space.

De-normalization is the process of adding up redundant data on the table in order to


speed up the complex queries and thus achieve better performance.

Q #8) What are the different types of Normalization?

Answer: Different types of Normalization are:

First Normal Form (1NF): A relation is said to be in 1NF only when all the entities of
the table contain unique or atomic values.
Second Normal Form (2NF): A relation is said to be in 2NF only if it is in 1NF and all
the non-key attribute of the table is fully dependent on the primary key.
Third Normal Form (3NF): A relation is said to be in 3NF only if it is in 2NF and every
non-key attribute of the table is not transitively dependent on the primary key.

Q #9) What is BCNF?

Answer: BCNF is the Boyce Code Normal form. It is the higher version of 3Nf which does
not have any multiple overlapping candidate keys.

Q #10) What is SQL?

Answer: Structured Query language, SQL is an ANSI(American National Standard Institute)


standard programming language that is designed specifically for storing and managing the
data in the relational database management system (RDBMS) using all kinds of data
operations.

Q #11) How many SQL statements are used? Define them.

Answer: SQL statements are basically divided into three categories, DDL, DML, and DCL.

They can be defined as:
Data Definition Language (DDL) commands are used to define the structure that
holds the data. These commands are auto-committed i.e. changes done by the DDL
commands on the database are saved permanently.
Data Manipulation Language (DML) commands are used to manipulate the data of
the database. These commands are not auto-committed and can be rolled back.
Data Control Language (DCL) commands are used to control the visibility of the data
in the database like revoke access permission for using data in the database.

Q #12) Enlist some commands of DDL, DML, and DCL.

Answer: Data Definition Language (DDL) commands:

CREATE to create a new table or database.


ALTER for alteration.
TRUNCATE to delete data from the table.
DROP to drop a table.
RENAME to rename a table.

Data Manipulation Language (DML) commands:

INSERT to insert a new row.


UPDATE to update an existing row.
DELETE to delete a row.
MERGE for merging two rows or two tables.

Data Control Language (DCL) commands:

COMMIT to permanently save.


ROLLBACK to undo the change.
SAVEPOINT to save temporarily.

Q #13) Define DML Compiler.

Answer: DML compiler translates DML statements in a query language into a low-level
instruction and the generated instruction can be understood by Query Evaluation Engine.

Q #14) What is DDL interpreter?

Answer: DDL Interpreter interprets the DDL statements and records the generated
statements in the table containing metadata.

Q #15) Enlist the advantages of SQL.

Answer: Advantages of SQL are:

Simple SQL queries can be used to retrieve a large amount of data from the 
database very quickly and efficiently.
SQL is easy to learn and almost every DBMS supports SQL.
It is easier to manage the database using SQL as no large amount of coding is
required.

Q #16) Explain the terms ‘Record’, ‘Field’ and ‘Table’ in terms of database.

Answer:

Record: Record is a collection of values or fields of a specific entity. For Example, An


employee, Salary account, etc.

Field: A field refers to an area within a record that is reserved for specific data. For
Example, Employee ID.

Table: Table is the collection of records of specific types. For Example, the Employee table
is a collection of records related to all the employees.

Q #17) What do you understand by Data Independence? What are its two types?

Answer: Data Independence refers to the ability to modify the schema definition in one
level in such a way that it does not affect the schema definition in the next higher level.

The 2 types of Data Independence are:

Physical Data Independence: It modifies the schema at the physical level without
affecting the schema at the conceptual level.
Logical Data Independence: It modifies the schema at the conceptual level without
affecting or causing changes in the schema at the view level.

Q #18) Define the relationship between ‘View’ and ‘Data Independence’.

Answer: View is a virtual table that does not have its data on its own rather the data is
defined from one or more underlying base tables.

Views account for logical data independence as the growth and restructuring of base
tables are not reflected in views.

Q #19) What are the advantages and disadvantages of views in the database?

Answer: Advantages of Views:

As there is no physical location where the data in the view is stored, it generates
output without wasting resources.
Data access is restricted as it does not allow commands like insertion, updation, and
deletion.


Disadvantages of Views:
The view becomes irrelevant if we drop a table related to that view.
Much memory space is occupied when the view is created for large tables.

Q #20) What do you understand by Functional dependency?

Answer: A relation is said to be in functional dependency when one attribute uniquely


defines another attribute.

For Example, R is a Relation, X and Y are two attributes. T1 and T2 are two tuples. Then,

T1[X]=T2[X] and T1[Y]=T2[Y]

Means, the value of component X uniquely define the value of component Y.

Also, X->Y means Y is functionally dependent on X.

Q #21) When is functional dependency said to be the fully functional dependent?

Answer: To fulfill the criteria of fully functional dependency, the relation must meet the
requirement of functional dependency.

A functional dependency ‘A’ and ‘B’ are said to be fully functional dependent when removal
of any attribute say ‘X’ from ‘A’ means the dependency does not hold anymore.

Q #22) What do you understand by the E-R model?

Answer: E-R model is an Entity-Relationship model which defines the conceptual view of
the database.

The E-R model basically shows the real-world entities and their association/relations.
Entities here represent the set of attributes in the database.

Q #23) Define Entity, Entity type, and Entity set.

Answer:

Entity can be anything, be it a place, class or object which has an independent existence
in the real world.

Entity Type represents a set of entities that have similar attributes.

Entity Set in the database represents a collection of entities having a particular entity
type.

Q #24) Define a Weak Entity set.

Answer: Weak Entity set is the one whose primary key comprises its partial key as well as

the primary key of its parent entity. This is the case because the entity set may not have
sufficient attributes to form a primary key.

Q #25) Explain the terms ‘Attribute’ and ‘Relations’

Answer:

Attribute is described as the properties or characteristics of an entity. For Example,


Employee ID, Employee Name, Age, etc., can be attributes of the entity Employee.

Relation is a two-dimensional table containing a number of rows and columns where every
row represents a record of the relation. Here, rows are also known as ‘Tuples’ and columns
are known as ‘Attributes’.

Q #26) What are VDL and SDL?

Answer: VDL is View Definition Language which represents user views and their mapping to
the conceptual schema.

SDL is Storage Definition Language which specifies the mapping between two schemas.

Q #27) Define Cursor and its types.

Answer: Cursor is a temporary work area that stores the data, as well as the result set,
occurred after manipulation of data retrieved. A cursor can hold only one row at a time.

The 2 types of Cursor are:

Implicit cursors are declared automatically when DML statements like INSERT,
UPDATE, DELETE is executed.
Explicit cursors have to be declared when SELECT statements that are returning
more than one row are executed.

Q #28) What is the Database transaction?

Answer: Sequence of operation performed which changes the consistent state of the
database to another is known as the database transaction. After the completion of the
transaction, either the successful completion is reflected in the system or the transaction
fails and no change is reflected.

Q #29) Define Database Lock and its types.

Answer: Database lock basically signifies the transaction about the current status of the
data item i.e. whether that data is being used by other transactions or not at the present
point of time.

There are two types of Database lock: Shared Lock and Exclusive Lock.

Q #30) What is Data Warehousing?
Answer: The storage as well as access to data, that is being derived from the transactions
and other sources, from a central location in order to perform the analysis is called Data
Warehousing.

Q #31) What do you understand by Join?

Answer: Join is the process of deriving the relationship between different tables by
combining columns from one or more tables having common values in each. When a table
joins with itself, it is known as Self Join.

Q #32) What do you understand by Index hunting?

Answer: Index hunting is the process of boosting the collection of indexes which helps in
improving the query performance as well as the speed of the database.

Q #33) How to improve query performance using Index hunting?

Answer: Index hunting help in improving query performance by:

Using a query optimizer to coordinate queries with the workload.


Observing the performance and effect of index and query distribution.

Q #34) Differentiate between ‘Cluster’ and ‘Non-cluster’ index.

Answer: Clustered index alters the table and re-order the way in which the records are
stored in the table. Data retrieval is made faster by using the clustered index.

A Non-clustered index does alter the records that are stored in the table but creates a
completely different object within the table.

Q #35) What are the disadvantages of a Query?

Answer: Disadvantages of a Query are:

Indexes are not present.


Stored procedures are excessively compiled.
Difficulty in interfacing.

Q #36) What do you understand by Fragmentation?

Answer: Fragmentation is a feature that controls the logical data units, also known as
fragments that are stored at different sites of a distributed database system.

Q #37) Define Join types.

Answer: Given below are the types of Join, which are explained with respect to the tables

as an Example.
employee table:

employee_info table:

a) Inner JOIN: Inner JOIN is also known as a simple JOIN. This SQL query returns results
from both the tables having a common value in rows.

SQL Query:

SELECT * from employee, employee_info WHERE employee.EmpID = employee_info.EmpID ;

Result:


b) Natural JOIN: This is a type of Inner JOIN that returns results from both the tables
having the same data values in the columns of both the tables to be joined.

SQL Query:

SELECT * from employee NATURAL JOIN employee_info;

Result:

c) Cross JOIN: Cross JOIN returns the result as all the records where each row from the
first table is combined with each row of the second table.

SQL Query:

SELECT * from employee CROSS JOIN employee_info;

Result:

Let us do some modification in the above tables to understand Right JOIN, Left JOIN, and
Full JOIN.

employee table:

employee_info table:

a) Right JOIN: Right JOIN is also known as Right Outer JOIN. This returns all the rows as a
result from the right table even if the JOIN condition does not match any records in the
left table.

SQL Query:

SELECT * from employee RIGHT OUTER JOIN employee_info on (employee.EmpID = employee

Result:


b) Left JOIN: Left JOIN is also known as Left Outer JOIN. This returns all the rows as a
result of the left table even if the JOIN condition does not match any records in the right
table. This is exactly the opposite of Right JOIN.

SQL Query:

SELECT * from employee LEFT OUTER JOIN employee_info on (employee.EmpID = employee_

Result:

c) Outer/Full JOIN: Full JOIN return results in combining the result of both the Left JOIN
and Right JOIN.

SQL Query:

SELECT * from employee FULL OUTER JOIN employee_info on (employee.EmpID = employee_

Result:

Q #38) What do you understand by ‘Atomicity’ and ‘Aggregation’?

Answer: Atomicity is the condition where either all the actions of the transaction are
performed or none. This means, when there is an incomplete transaction, the database
management system itself will undo the effects done by the incomplete transaction.

Aggregation is the concept of expressing the relationship with the collection of entities
and their relationships. 
Q #39) Define Phantom deadlock.

Answer: Phantom deadlock detection is the condition where the deadlock does not
actually exist but due to a delay in propagating local information, deadlock detection
algorithms identify the deadlocks.

Q #40) Define checkpoint.

Answer: Checkpoint declares a point before which all the logs are stored permanently in
the storage disk and is the inconsistent state. In the case of crashes, the amount of work
and time is saved as the system can restart from the checkpoint.

Q #41) What is Database partitioning?

Answer: Database partitioning is the process of partitioning tables, indexes into smaller
pieces in order to manage and access the data at a finer level.

This process of partitioning reduces the cost of storing a large amount of data as well as
enhances the performance and manageability.

Q #42) Explain the importance of Database partitioning.

Answer: The importance of Database partitioning are:

Improves query performance and manageability.


Simplifies common administration tasks.
Acts as a key tool for building systems with extremely high availability requirements.
Allows accessing a large part of a single partition.

Q #43) Explain the Data Dictionary.

Answer: Data dictionary is a set of information describing the content and structure of the
tables and database objects. The job of the information stored in the data dictionary is to
control, manipulate and access the relationship between database elements.

Q #44) Explain the Primary Key and Composite Key.

Answer: Primary Key is that column of the table whose every row data is uniquely
identified. Every row in the table must have a primary key and no two rows can have the
same primary key. Primary key value can never be null nor can it be modified or updated.

Composite Key is a form of the candidate key where a set of columns will uniquely identify
every row in the table.

Q #45) What do you understand by the Unique key?


Answer: A Unique key is the same as the primary key whose every row data is uniquely
identified with a difference of null value i.e. Unique key allows one value as a NULL value.
Q #46) What do you understand by Database Triggers?

Answer: A set of commands that automatically get executed when an event like Before
Insert, After Insert, On Update, On Delete of row occurs in a table is called as Database
trigger.

Q #47) Define Stored procedures.

Answer: A Stored procedure is a collection of pre-compiled SQL Queries, which when


executed denotes a program taking input, process and gives the output.

Q #48) What do you understand by B-Trees?

Answer: B-Tree represents the data structure in the form of a tree for external memory
that reads and writes large blocks of data. It is commonly used in databases and file
systems where all the insertions, deletions, sorting, etc., are done in logarithmic time.

Q #49) Name the different data models that are available for database systems.

Answer: Different data models are:

Relational model
Network model
Hierarchical model

Q #50) Differentiate between ‘DELETE’, ‘TRUNCATE’ and ‘DROP’ commands.

Answer: After the execution of ‘DELETE’ operation, COMMIT and ROLLBACK statements
can be performed to retrieve the lost data.

After the execution of ‘TRUNCATE’ operation, COMMIT, and ROLLBACK statements cannot
be performed to retrieve the lost data.

‘DROP’ command is used to drop the table or key like the primary key/foreign key.

Q #51) Based on the given table, solve the following queries.

Employee table

a) Write the SELECT command to display the details of the employee with empid as 1004.

SQL Query:
SELECT empId, empName, Age, Address from Employee WHERE empId = 1004;

Result:

b) Write the SELECT command to display all the records of table Employees.

SQL Query:

SELECT * from Employee;

Result:

c) Write the SELECT command to display all the records of the employee whose name
starts with the character ‘R’.

SQL Query:

SELECT * from Employee WHERE empName LIKE ‘R%’;

Result:

d) Write a SELECT command to display id, age and name of the employees with their age
in both ascending and descending order.

SQL Query:

SELECT empId, empName, Age from Employee ORDER BY Age;

Result:


SELECT empId, empName, Age from Employee ORDER BY Age Desc;

Result:

e) Write the SELECT command to calculate the total amount of salary on each employee
from the below Emp table.

Emp table:

SQL Query:

SELECT empName, SUM(Salary) from Emp GROUP BY empName;

Result:

Conclusion
These are the set of Database interview questions and answers which are mostly asked in
the interview.

Mostly the basics of every subject are questioned in the interviews. It is a well-known fact
to everyone that, if your basics are clear, you can reach top heights.

However, there may be some more tricky questions. Just be confident and face each 
question with clarity in your subject knowledge.
Are you preparing for your sql developer interview?

Then you have come to the right place.

This guide will help you to brush up your SQL skills, regain your confidence and be job
ready!

In this guide you will find a collection of real world SQL interview questions asked in
companies like Google, Oracle, Amazon and Microsoft etc. Each question comes with a
perfectly written answer inline, saving your interview preparation time.

This guide also contains some sql practice problems which you can solve right away
which is simply the fastest and easiest way for clearing your basic concepts of SQL.

Let’s dive right in..

1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a remote or local
computer system. Databases can be vast and complex, and such databases are developed using fixed
design and modeling approaches.

2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software responsible for the
creation, retrieval, updation and management of the database. It ensures that our data is consistent,
organized and is easily accessible by serving as an interface between the database and its end users
or application softwares.

3. What is RDBMS? How is it different from DBMS?


RDBMS stands for Relational Database Management System. 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.
4. 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.

5. 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.

6. What are Tables and Fields?


A table is an organized collection of data stored in the form of rows and columns. 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.

7. 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 creation of table or after creationg 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.

8. 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);

Q => Write a SQL statement to add PRIMARY KEY 't_id' to the table 'teachers'. +

Q => Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'. +

9. 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);

10. What is a Foreign Key?


A FOREIGN KEY comprises of single or collection of fields in a table that essentially refer 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 labelled as the child table, and the table containing the
candidate key is labelled 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);

Q => What type of integrity constraint does the foreign key ensure? +
Q => Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references
'col_pk' in 'table_x'. +

11. 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;

12. 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;

13. 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 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;
Q => Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1' from
table_1 & 'col_2' from table_2 respectively. Do not use alias. +

Q => Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively. +

14. What is an Index? Explain its different types.


A database index is a data structure that provides 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 correspond 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 index can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.

Q => Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields
"column_1" & "column_2". +

15. What is the difference between Clustered and Non-


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

1. Clustered index modifies the way records are stored in a database based on the indexed column.
Non-clustered index creates a separate entity within the table which references the original table.
2. 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.
3. In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.

16. 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 to 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.

17. 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;
18. What is a Subquery? What are its types?
A subquery is a query within another query, also known as 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 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 subquery
is substituted in the main query.

Q => Write a SQL query to update the field "status" in table "applications" from 0 to 1. +

Q => Write a SQL query to select the field "app_id" in table "applications" where "app_id"
less than 1000. +

Q => Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is equal
to the above collection of "app_id". +

19. 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;

20. 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
conjuction 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 WHERE clause cannot filter aggregated records.

SELECT COUNT(studentId), country


FROM myDB.students
WHERE country != "INDIA"
GROUP BY country
HAVING COUNT(studentID) > 5;

21. 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;

Q => Write a SQL query to fetch "names" that are present in either table "accounts" or in
table "registry". +

Q => Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry". +

Q => Write a SQL query to fetch "names" from table "contacts" that are neither present in
"accounts.name" nor in "registry.name". +

22. What is Cursor? How to use a Cursor?


A database cursor is a control structure that allows for 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

23. 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 employees table in a company's database can be associated with the salary table in the
same database.

24. 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.

25. 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;

Q => Write an SQL statement to select all from table "Limited" with alias "Ltd". +

26. 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.

27. What is Normalization?


Normalization represents the way of organizing structured data in the database efficiently. It includes
creation of tables, establishing relationships between them, and defining rules for those relationships.
Inconsistency and redundancy can be kept in check based on these rules, hence, adding flexibility to
the database.
28. What is Denormalization?
Denormalization is the inverse process of normalization, where the normalized schema is converted
into a schema which has redundant information. The performance is improved by using redundancy
and keeping the redundant data consistent. The reason for performing denormalization is the
overheads produced in query processor by an over-normalized structure.

29. 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:

1. 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 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

Until the Day I Die (Emily


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

The Alchemist (Paulo Coelho),


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

24th Street Park Beautiful Bad (Annie Ward),


Sara Mrs.
Avenue Woman 99 (Greer Macallister)

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

As we can observe, the Books Issued field has more than one values 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

Amanora Park Town Until the Day I Die (Emily


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

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

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

24th Street Park


Sara Beautiful Bad (Annie Ward) Mrs.
Avenue

24th Street Park


Sara Woman 99 (Greer Macallister) Mrs.
Avenue

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

2. Second Normal Form


A relation is in second normal form if it satisfies the conditions for 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, Students Table in 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 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.

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 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.

3. Third Normal Form


A relation is said to be in the third normal form, if it satisfies the conditions for 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, Students Table
in 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 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 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 above relation should be {P, RS,
QR, T}.

4. 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 the 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. Same cannot be said for the
Books Table and there can be several books with common Book Names and same Student_ID.

30. 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
is deleted and the table structure is removed from the database.
DROP TABLE Candidates;

Q => Write a SQL statement to wipe a table 'Temporary' from memory. +

Q => Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'. +

Q => Write a SQL statement to delete the table 'Temporary' while keeping its relations intact.
+

31. 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.

32. 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.

33. 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 given length.
ROUND() - Calculates the round off integer value for a numeric field (or decimal point values).
NOW() - Returns the current data & time.
FORMAT() - Sets the format to display a collection of values.

34. 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.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be
used inside the function body.

35. 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 [ Note - The figure is not important for interviews ] -
36. 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. Number of transactions per second acts as an effective measure for such
systems.

OLAP stands for Online Analytical Processing, a class of software programs which are characterized
by 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.
37. 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.

38. 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 ;
39. What is a Recursive Stored Procedure?
A stored procedure which 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 */

40. 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;
41. 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.

1. 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%'

2. 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%'

3. 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%'

4. 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%'

5. Matching patterns for 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 '____'
Conclusion
SQL is a language for the database. It has a vast scope and robust capability of creating and
manipulating variety of database objects using commands like CREATE, ALTER, DROP etc and also in
loading the database objects using commands like INSERT. It also provides options for Data
Manipulation using commands like DELETE, TRUNCATE and also does effective retrieval of data using
cursor commands like FETCH, SELECT etc. There are many such commands which provide a large
amount of control to the programmer to interact with the database in an efficient way without wasting
much resources. The popularity of SQL has grown so much that almost every programmer relies on
this to implement their application's storage functionalities thereby making it an exciting language to
learn. Learning this provides the developer a benefit of understanding the data structures used for
storing the organization's data and giving additional level of control and in-depth understanding of the
application.

Practice SQL Questions asked in


Interviews

Q - Which statement is true for a PRIMARY KEY constraint?

Primary key defines a realtionship between two tables.

A table in SQL must have a primary key associated with it to uniquely identify its
records.

A table in SQL is indexed by default based on its primary key.

Primary key may or may not be unique but can be comprised of multiple fields.

Q - Which statement is false for a FOREIGN KEY constraint?

Foreign key defines a relationship between two tables.

Foreign Key is automatically created when two tables are joined.

Foreign Key uniquely identifies all the records in the referenced table.

Foreign key may or may not be unique but can be comprised of multiple fields.

Q - What is a Query?
A SELECT or UPDATE statement in SQL.

A request for data from a table in the database.

A request to input data from the user.

A request for data from single or multiple tables in the database.

Q - What does SQL stand for?

Structured Question Language

Strong Query Language

Structured Query Language

Strong Question Language

Q - Which statement is used to update data in the database?

MODIFY

UPDATE

ALTER TABLE

SAVE AS

Q - Query to select all records with "bar" in their name?

SELECT * FROM people WHERE name = "%bar%";

SELECT * FROM people WHERE name LIKE "%bar%";

SELECT * FROM people WHERE name IN ("bar");

SELECT * FROM people WHERE name = "_bar_"

Q - Which statement is false for ORDER BY statement?

Requires a ASC or DESC keyword explicitly to sort the result set.

Sorts the result set in descending order using the DESC keyword.

Can sort based on multiple columns.

None of the above.

Q - SQL query used to fetch unique values from a field?


SELECT UNIQUE column_name FROM table_name;

SELECT DISTINCT column_name FROM table_name;

SELECT column_name FROM table_name WHERE COUNT(column_name) = 1;

SELECT UNIQUE column_name FROM table_name WHERE COUNT(column_name) = 1;

Q - What is the main advantage of a clustered index over a non-clustered index?

It is easier to create and manipulate.

It requires extra memory but allows for speedy retrieval of records.

It does not require additonal memory and allows for speedy retrieval of records.

None of the above.

Q - Normalization which has neither composite values nor partial


dependencies?

Second Normal Formal

Third Normal Form

Boyce-Codd Normal Form

All of the above

Q - An SQL query to delete a table from the database and memory while keeping
the structure of the table intact?

DROP TABLE table_name;

DROP FROM TABLE table_name;

DELETE FROM TABLE table_name;

TRUNCATE TABLE table_name;

Q - Which of the following is known as a virtual table in SQL?

SELF JOIN

INNER JOIN

VIEW

NONE
Q #1) What is SQL?

Answer: Structured Query Language SQL is a database tool that is used to create and
access the database to support software applications.

Q #2) What are tables in SQL?

Answer: The table is a collection of record and its information at a single view.

Q #3) What are the different types of statements supported by SQL?

Answer:

There are 3 types of SQL statements:

a) DDL (Data Definition Language): It is used to define the database structure such as
tables. It includes three statements such as CREATE, ALTER, and DROP.

Also read =>> MySQL Create Table Tutorial

Some of the DDL Commands are listed below:

CREATE: It is used for creating the table.

CREATE TABLE table_name


column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),

ALTER: The ALTER table is used for modifying the existing table object in the database.

ALTER TABLE table_name


ADD column_name datatype

OR

ALTER TABLE table_name


DROP COLUMN column_name

b) DML (Data Manipulation Language): These statements are used to manipulate the data
in records. Commonly used DML statements are INSERT, UPDATE, and DELETE.

The SELECT statement is used as a partial DML statement, used to select all or relevant
records in the table.

c) DCL (Data Control Language): These statements are used to set privileges such as
GRANT and REVOKE database access permission to the specific user.

Q #4) How do we use the DISTINCT statement? What is its use?

Answer: The DISTINCT statement is used with the SELECT statement. If the record
contains duplicate values then the DISTINCT statement is used to select different values
among duplicate records.

Syntax:

SELECT DISTINCT column_name(s)


FROM table_name;

Q #5) What are the different Clauses used in SQL?

Answer:

WHERE Clause: This clause is used to define the condition, extract and display only those
records which fulfill the given condition.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition;

GROUP BY Clause: It is used with SELECT statement to group the result of the executed
query using the value specified in it. It matches the value with the column name in tables
and groups the end result accordingly. 
Further reading => MySQL Group By Tutorial

Syntax:

SELECT column_name(s)
FROM table_name
GROUP BY column_name;

HAVING clause: This clause is used in association with the GROUP BY clause. It is applied
to each group of results or the entire result as a single group. It is much similar as WHERE
clause but the only difference is you cannot use it without GROUP BY clause

Syntax:

SELECT column_name(s)
FROM table_name
GROUP BY column_name
HAVING condition;

ORDER BY clause: This clause is used to define the order of the query output either in
ascending (ASC) or in descending (DESC). Ascending (ASC) is set as the default one but
descending (DESC) is set explicitly.

Syntax:

SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;

USING clause: USING clause comes in use while working with SQL JOIN. It is used to check
equality based on columns when tables are joined. It can be used instead of the ON clause
in JOIN.

Syntax:

SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);

Q #6) Why do we use SQL constraints? Which constraints we can use while creating a
database in SQL?

Answer: Constraints are used to set the rules for all records in the table. If any constraints
get violated then it can abort the action that caused it.

Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.

There are 5 major constraints are used in SQL, such as



NOT NULL: That indicates that the column must have some value and cannot be left
NULL.
UNIQUE: This constraint is used to ensure that each row and column has a unique
value and no value is being repeated in any other row or column.
PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE
constraints such as on one or the combination of more than one column to identify
the particular record with a unique identity.
FOREIGN KEY: It is used to ensure the referential integrity of data in the table. It
matches the value in one table with another using the PRIMARY KEY.
CHECK: It ensures whether the value in columns fulfills the specified condition.

Q #7) What are different JOINS used in SQL?

Answer:

4 major types of Joins are used while working on multiple tables in SQL databases:

INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one matching column.

Syntax:

SELECT column_name(s)
FROM table_name1 
INNER JOIN table_name2
ON column_name1=column_name2;

For Example,

In this example, we have a table Employee with the following data:


The second table’s name is Joining.
Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date


FROM Employee
INNER JOIN Joining
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;

There will be 4 records selected. Results are:

Employee and Orders tables have a matching customer_id value.

LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its
matched rows from a RIGHT table.

Syntax:

SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON column_name1=column_name2;

For Example,

In this example, we have a table Employee with the following data:

The second table’s name is Joining.



Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date


FROM Employee
LEFT OUTER JOIN Joining
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;

There will be 4 records selected. You will see the following results:

RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table and its
matched rows from the LEFT table.

Syntax:

SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON column_name1=column_name2;

For Example,

In this example, we have a table Employee with the following data:

The second table’s name is Joining. 


Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee


RIGHT JOIN Joining
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;

Output:

Emp_id Joining_Date

E0012 2016/04/18

E0013 2016/04/19

E0014 2016/05/01

FULL JOIN (FULL OUTER JOIN): This joins returns all results when there is a match either
in the RIGHT table or in the LEFT table.

Syntax:

SELECT column_name(s)
FROM table_name1
FULL OUTER JOIN table_name2
ON column_name1=column_name2;

For Example,

In this example, we have a table Employee with the following data:

The second table’s name is Joining.


Enter the following SQL statement:

SELECT Employee.Emp_id, Joining.Joining_Date


FROM Employee
FULL OUTER JOIN Joining
ON Employee.Emp_id = Joining.Emp_id
ORDER BY Employee.Emp_id;

There will be 8 records selected. These are the results that you should see.

Also Read => MySQL Join Tutorial

Q #8) 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.

Q #9) 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.

Q #10) How many Aggregate functions are available in SQL?

Answer: SQL Aggregate functions determine and calculate values from multiple columns in
a table and return a single value.

There are 7 aggregate functions in SQL:

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


COUNT(): Returns number of table rows.
MAX(): Returns the largest value among the records.
MIN(): Returns smallest value among the records.
SUM(): Returns the sum of specified column values.
FIRST(): Returns the first value.
LAST(): Returns last value.

Q #11) What are Scalar functions in SQL?

Answer: Scalar functions are used to return a single value based on the input values.

Scalar Functions are as follows:

UCASE(): Converts the specified field in the upper case.


LCASE(): Converts the specified field in lower case.
MID(): Extracts and returns character from the text field.
FORMAT(): Specifies the display format.
LEN(): Specifies the length of the text field.
ROUND(): Rounds up the decimal field value to a number.

Q #12) What are triggers?
Answer: Triggers in SQL is kind of stored procedures used to create a response to a
specific action performed on the table such as INSERT, UPDATE or DELETE. You can invoke
triggers explicitly on the table in the database.

Action and Event are two main components of SQL triggers. When certain actions are
performed, the event occurs in response to that action.

Syntax:

CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}


ON table_name [FOR [EACH] {ROW|STATEMENT}]
EXECUTE PROCEDURE functionname {arguments}

Q #13) What is View in SQL?

Answer: A View can be defined as a virtual table that contains rows and columns with
fields from one or more tables.

Syntax:

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

Q #14) How we can update the view?

Answer: SQL CREATE and REPLACE can be used for updating the view.

Execute the below query to update the created view.

Syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

Q #15) 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};

Q #16) 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.

Q #17) What is SQL Injection?

Answer: SQL Injection is a type of database attack technique where malicious SQL
statements are inserted into an entry field of database in a way that once it is executed,
the database is exposed to an attacker for the attack. This technique is usually used for
attacking data-driven applications to have access to sensitive data and perform
administrative tasks on databases.

For Example,

SELECT column_name(s) FROM table_name WHERE condition;

Q #18) What is SQL Sandbox in SQL Server?

Answer: SQL Sandbox is a safe place in the SQL server environment where untrusted
scripts are executed. There are 3 types of SQL sandbox:

Safe Access Sandbox: Here a user can perform SQL operations such as creating
stored procedures, triggers etc. but cannot have access to the memory as well as
cannot create files.
External Access Sandbox: Users can access files without having the right to
manipulate the memory allocation. 
Unsafe Access Sandbox: This contains untrusted codes where a user can have
access to memory.

Q #19) What is the difference between SQL and PL/SQL?

Answer: SQL is a Structured Query Language to create and access databases whereas
PL/SQL comes with procedural concepts of programming languages.

Q #20) What is the difference between SQL and MySQL?

Answer: SQL is a Structured Query Language that is used for manipulating and accessing
the relational database. On the other hand, MySQL itself is a relational database that uses
SQL as the standard database language.

Q #21) What is the use of the NVL function?

Answer: NVL function is used to convert the null value to its actual value.

Q #22) What is the Cartesian product of the table?

Answer: The output of Cross Join is called a Cartesian product. It returns rows combining
each row from the first table with each row of the second table. For Example, if we join
two tables having 15 and 20 columns the Cartesian product of two tables will be
15×20=300 rows.

Q #23) What do you mean by Subquery?

Answer: Query within another query is called as Subquery. A subquery is called inner query
which returns output that is to be used by another query.

Q #24) 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.

Q #25) What is the difference between clustered and non-clustered indexes?

Answer: The differences between the two are as follows:

One table can have only one clustered index but multiple non-clustered indexes.
Clustered indexes can be read rapidly rather than non-clustered indexes.
Clustered indexes store data physically in the table or view whereas, non-clustered
indexes do not store data in the table as it has separate structure from the data row.

Q #26) What is the difference between DELETE and TRUNCATE?


Answer: The differences are:
The basic difference in both is DELETE command is DML command and the
TRUNCATE command is DDL.
DELETE command is used to delete a specific row from the table whereas the
TRUNCATE command is used to remove all rows from the table.
We can use the DELETE command with WHERE clause but cannot use the
TRUNCATE command with it.

Q #27) What is the difference between DROP and TRUNCATE?

Answer: TRUNCATE removes all rows from the table which cannot be retrieved back, DROP
removes the entire table from the database and it also cannot be retrieved back.

Q #28) How to write a query to show the details of a student from Students table whose
name start with K?

Answer: Query:

SELECT * FROM Student WHERE Student_Name like ‘K%’;

Here ‘like’ operator is used to perform pattern matching.

Q #29) 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.

Q #30) What is Normalization? How many Normalization forms are there?

Answer: Normalization is used to organize the data in such a manner that data redundancy
will never occur in the database and avoid insert, update and delete anomalies.

There are 5 forms of Normalization:

First Normal Form (1NF): It removes all duplicate columns from the table. It creates
a table for related data and identifies unique column values.
First Normal Form (2NF): Follows 1NF and creates and places data subsets in an
individual table and defines the relationship between tables using the primary key.
Third Normal Form (3NF): Follows 2NF and removes those columns which are not
related through the primary key.
Fourth Normal Form (4NF): Follows 3NF and does not define multi-valued
dependencies. 4NF is also known as BCNF.

Q #31) What is a Relationship? How many types of Relationships are there?
Answer: The relationship can be defined as the connection between more than one table
in the database.

There are 4 types of relationships:

One to One Relationship


Many to One Relationship
Many to Many Relationship
One to Many Relationship

Q #32) What do you mean by Stored Procedures? How do we use it?

Answer: A stored procedure is a collection of SQL statements that can be used as a


function to access the database. We can create these stored procedures earlier before
using it and can execute them wherever required by applying some conditional logic to it.
Stored procedures are also used to reduce network traffic and improve performance.

Syntax:

CREATE Procedure Procedure_Name


(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END

Q #33) State some properties of Relational databases?

Answer: Properties are as follows:

In relational databases, each column should have a unique name.


The sequence of rows and columns in relational databases is insignificant.
All values are atomic and each row is unique.

Q #34) 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.

Q #35) What is a Cursor?

Answer: A cursor is a database object which is used to manipulate data in a row-to-row


manner.

Cursor follows steps as given below:



Declare Cursor
Open Cursor
Retrieve row from the Cursor
Process the row
Close Cursor
Deallocate Cursor

Q #36) What is Collation?

Answer: Collation is a set of rules that check how the data is sorted by comparing it. Such
as character data is stored using correct character sequence along with case sensitivity,
type, and accent.

Q #37) 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

Q #38) 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

Q #39) What is Database Black Box Testing?

Answer: Database Black Box testing involves:

Data Mapping
Data stored and retrieved
Use of Black Box testing techniques such as Equivalence Partitioning and Boundary
Value Analysis (BVA)

Q #40) What are Indexes in SQL?

Answer: The index can be defined as the way to retrieve the data more quickly. We can
define indexes using CREATE statements. 
Syntax:

CREATE INDEX index_name


ON table_name (column_name)

Further, we can also create a Unique Index using the following syntax:

CREATE UNIQUE INDEX index_name


ON table_name (column_name)

UPDATE: We have added few more short questions for practice.

Q #41) What does SQL stand for?

Answer: SQL stands for Structured Query Language.

Q #42) How to select all records from the table?

Answer: To select all the records from the table we need to use the following syntax:

Select * from table_name;

Q #43) Define join and name different types of joins?

Answer: Join keyword is used to fetch data from two or more related tables. It returns
rows where there is at least one match in both the tables included in the join. Read more
here.
Type of joins are:

1. Right join
2. Outer join
3. Full join
4. Cross join
5. Self join.

Q #44) What is the syntax to add a record to a table?

Answer: To add a record in a table INSERT syntax is used.

For Example,

INSERT into table_name VALUES (value1, value2..);

Q #45) How do you add a column to a table?

Answer: To add another column in the table, use the following command: 
ALTER TABLE table_name ADD (column_name);
Recommended reading =>> How to add a column to a table in MySQL

Q #46) Define the SQL DELETE statement.

Answer: DELETE is used to delete a row or rows from a table based on the specified
condition.
The basic syntax is as follows:

DELETE FROM table_name


WHERE <Condition>

Q #47) Define COMMIT?

Answer: COMMIT saves all changes made by DML statements.

Q #48) What is the Primary key?

Answer: A Primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused.

Q #49) What are Foreign keys?

Answer: When a table’s primary key field is added to related tables in order to create the
common field which relates the two tables, it called a foreign key in other tables. Foreign
key constraints enforce referential integrity.

Q #50) What is CHECK Constraint?

Answer: A CHECK constraint is used to limit the values or type of data that can be stored
in a column. They are used to enforce domain integrity.

Q #51) Is it possible for a table to have more than one foreign key?

Answer: Yes, a table can have many foreign keys but only one primary key.

Q #52) What are the possible values for the BOOLEAN data field?

Answer: For a BOOLEAN data field, two values are possible: -1(true) and 0(false).

Q #53) What is a stored procedure?

Answer: A stored procedure is a set of SQL queries that can take input and send back
output.

Q #54) What is identity in SQL?

Answer: An identity column in where SQL automatically generates numeric values. We can
define a start and increment value of the identity column.

Q #55) What is Normalization?

Answer: The process of table design to minimize the data redundancy is called
normalization. We need to divide a database into two or more table and define the
relationship between them.

Q #56) What is a Trigger?

Answer: The Trigger allows us to execute a batch of SQL code when table event occurs
(INSERT, UPDATE or DELETE commands are executed against a specific table).

Q #57) 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);

Q #58) Which TCP/IP port does SQL Server run?

Answer: By default SQL Server runs on port 1433.

Q #59) 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;

Q #60) Explain DML and DDL?

Answer: DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are
DML statements.

DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL
statements.

Q #61) 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;

Q #62) 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.


Q #63) 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)

Q #64) What is SQL comments?

Answer: SQL comments can be inserted by adding two consecutive hyphens (–).

Q #65) Difference between TRUNCATE, DELETE and DROP commands?

Answer:

DELETE removes some or all rows from a table based on the condition. It can be
rolled back.
TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The
operation cannot be rolled back
DROP command removes a table from the database completely.

Q #66) What are the properties of a transaction?

Answer: Generally, these properties are referred to as ACID properties. They are:

1. Atomicity
2. Consistency
3. Isolation
4. Durability.

Q #67) What do you mean by ROWID?

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

Q #68) Define UNION, MINUS, UNION ALL, INTERSECT?

Answer:

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.
INTERSECT – returns all distinct rows selected by both queries.

Q #69) What is a transaction?

Answer: A transaction is a sequence of code that runs against a database. It takes the
database from one consistent state to another.

Q #70) What is the difference between UNIQUE and PRIMARY KEY constraints?


Answer: The differences are as follows:
A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys.
The primary key cannot contain Null values whereas the Unique key can contain Null
values.

Q #71) What is a composite primary key?

Answer: The primary key created on more than one column is called composite primary
key.

Q #72) What is an Index?

Answer: An Index is a special structure associated with a table to speed up the


performance of queries. The index can be created on one or more columns of a table.

Q #73) What is the Subquery?

Answer: A Subquery is a subset of select statements whose return values are used in
filtering conditions of the main query.

Q #74) What do you mean by query optimization?

Answer: Query optimization is a process in which a database system compares different


query strategies and select the query with the least cost.

Q #75) What is Collation?

Answer: Set of rules that define how data is stored, how case-sensitivity and Kana
character can be treated etc.

Q #76) 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.

Q #77) What is the Case function?

Answer: Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions
and returns one of the multiple possible result expressions.

Q #78) Define a temp table?

Answer: A temp table is a temporary storage structure to store the data temporarily.

Q #79) How can we avoid duplicating records in a query?

Answer: By using the DISTINCT keyword, duplication of records in a query can be avoided.

Q #80) Explain the difference between Rename and Alias?

Answer: Rename is a permanent name given to a table or column whereas Alias is a


temporary name given to a table or column.

Q #81) What is a View?

Answer: A view is a virtual table that contains data from one or more tables. Views restrict
data access of the table by selecting only required values and make complex queries easy.

Q #82) What are the advantages of Views?

Answer: Advantages of Views are:

Views restrict access to the data because the view can display selective columns
from the table.
Views can be used to make simple queries to retrieve the results of complicated
queries. For Example, views can be used to query information from multiple tables
without the user knowing.

Q #83) List the various privileges that a user can grant to another user?

Answer: SELECT, CONNECT, RESOURCES.

Q #84) What is schema?

Answer: A schema is a collection of database objects of a User.

Q #85) What is a Table?

Answer: A table is the basic unit of data storage in the database management system.
Table data is stored in rows and columns.

Q #86) Does View contain Data?

Answer: No, Views are virtual structures.

Q #87) Can a View based on another View?

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

Q #88) 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.

Q #89) 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.

Q #90) 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.

Conclusion
SQL is an essential component of the database system. Having well-versed knowledge of
database along with SQL concepts will definitely be beneficial to crack the interview for
the concerned profile.

Apart from some major concepts, there are some hidden facts that remain unseen and
affect your performance in the interview. In this tutorial, I have tried to recollect some of
those concepts which seem small but should not be neglected.

Hope in this article, you will find answers to most frequently asked SQL interview
questions. The knowledge of SQL is a must for any tester and this article will help you in
preparing the interview.

Further Reading => All about Database Testing

Recommended Reading
Interview Questions and Answers
Top Oracle Interview Questions: Oracle Basic, SQL, PL/SQL Questions
30 Most Important PL/SQL Interview Questions and Answers In 2021
ETL Testing Interview Questions and Answers
Top Teradata Interview Questions and Answers
Some Tricky Manual Testing Questions & Answers
25 Best Agile Testing Interview Questions and Answers
Spock Interview Questions with Answers (Most Popular)

About SoftwareTestingHelp

Helping our community since 2006! Most popular portal for Software professionals
with 100 million+ visits and 300,000+ followers! You will absolutely love our
tutorials on QA Testing, Development, Software Tools and Services Reviews and
more!

You might also like