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

SQL Interview Questions

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

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.

You can download a PDF version of Sql Interview Questions.

Download PDF

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

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

write a sql statement to add primary key 't_id' to the table 'teachers'.

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 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 type of integrity constraint does the foreign key ensure?

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

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

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 -

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

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

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

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

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

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

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;

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

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

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

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 employee's 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;

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 the 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 that 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 the 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:

 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
Sara  Ms.
94  (Christopher Nolan)
Ansh 62nd Sector A-10  The Alchemist (Paulo Coelho), Inferno (Dan Brown)  Mr.
24th Street Park Beautiful Bad (Annie Ward), Woman 99 (Greer
Sara  Mrs.
Avenue  Macallister)
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.
Student_ID  Student Address  Salutation
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 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.
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 are deleted and the table structure is removed from the database.

DROP TABLE Candidates;

Write a SQL statement to wipe a table 'Temporary' from memory.

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

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

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

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

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 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 */

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.

 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 '____'

PostgreSQL Interview Questions


42. What is PostgreSQL?

PostgreSQL was first called Postgres and was developed by a team led by Computer Science
Professor Michael Stonebraker in 1986. It was developed to help developers build enterprise-
level applications by upholding data integrity by making systems fault-tolerant. PostgreSQL is
therefore an enterprise-level, flexible, robust, open-source, and object-relational DBMS that
supports flexible workloads along with handling concurrent users. It has been consistently
supported by the global developer community. Due to its fault-tolerant nature, PostgreSQL has
gained widespread popularity among developers.

43. How do you define Indexes in PostgreSQL?

Indexes are the inbuilt functions in PostgreSQL which are used by the queries to perform search
more efficiently on a table in the database. Consider that you have a table with thousands of
records and you have the below query that only a few records can satisfy the condition, then it
will take a lot of time to search and return those rows that abide by this condition as the engine
has to perform the search operation on every single to check this condition. This is undoubtedly
inefficient for a system dealing with huge data. Now if this system had an index on the column
where we are applying search, it can use an efficient method for identifying matching rows by
walking through only a few levels. This is called indexing.

Select * from some_table where table_col=120

44. How will you change the datatype of a column?

This can be done by using the ALTER TABLE statement as shown below:
Syntax:

ALTER TABLE tname


ALTER COLUMN col_name [SET DATA] TYPE new_data_type;

45. What is the command used for creating a database in PostgreSQL?

The first step of using PostgreSQL is to create a database. This is done by using the createdb
command as shown below: createdb db_name
After running the above command, if the database creation was successful, then the below
message is shown:

CREATE DATABASE

46. How can we start, restart and stop the PostgreSQL server?

 To start the PostgreSQL server, we run:

service postgresql start

 Once the server is successfully started, we get the below message:

Starting PostgreSQL: ok

 To restart the PostgreSQL server, we run:

service postgresql restart

Once the server is successfully restarted, we get the message:

Restarting PostgreSQL: server stopped


ok

 To stop the server, we run the command:

service postgresql stop

Once stopped successfully, we get the message:

Stopping PostgreSQL: server stopped


ok

47. What are partitioned tables called in PostgreSQL?

Partitioned tables are logical structures that are used for dividing large tables into smaller
structures that are called partitions. This approach is used for effectively increasing the query
performance while dealing with large database tables. To create a partition, a key called
partition key which is usually a table column or an expression, and a partitioning method needs
to be defined. There are three types of inbuilt partitioning methods provided by Postgres:

 Range Partitioning: This method is done by partitioning based on a range of values. This
method is most commonly used upon date fields to get monthly, weekly or yearly data.
In the case of corner cases like value belonging to the end of the range, for example: if
the range of partition 1 is 10-20 and the range of partition 2 is 20-30, and the given
value is 10, then 10 belongs to the second partition and not the first.
 List Partitioning: This method is used to partition based on a list of known values. Most
commonly used when we have a key with a categorical value. For example, getting sales
data based on regions divided as countries, cities, or states.
 Hash Partitioning: This method utilizes a hash function upon the partition key. This is
done when there are no specific requirements for data division and is used to access
data individually. For example, you want to access data based on a specific product,
then using hash partition would result in the dataset that we require.

The type of partition key and the type of method used for partitioning determines how positive
the performance and the level of manageability of the partitioned table are.

48. Define tokens in PostgreSQL?

A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes identifier, or any
symbol that has a distinctive personality. They may or may not be separated using a space,
newline or a tab. If the tokens are keywords, they are usually commands with useful meanings.
Tokens are known as building blocks of any PostgreSQL code.

49. What is the importance of the TRUNCATE statement?

TRUNCATE TABLE name_of_table statement removes the data efficiently and quickly from the table.
The truncate statement can also be used to reset values of the identity columns along with data
cleanup as shown below:

TRUNCATE TABLE name_of_table


RESTART IDENTITY;

We can also use the statement for removing data from multiple tables all at once by
mentioning the table names separated by comma as shown below:

TRUNCATE TABLE
table_1,
table_2,
table_3;

50. What is the capacity of a table in PostgreSQL?


The maximum size of PostgreSQL is 32TB.

51. Define sequence.

A sequence is a schema-bound, user-defined object which aids to generate a sequence of


integers. This is most commonly used to generate values to identity columns in a table. We can
create a sequence by using the CREATE SEQUENCE statement as shown below:

CREATE SEQUENCE serial_num START 100;

To get the next number 101 from the sequence, we use the nextval() method as shown below:

SELECT nextval('serial_num');

We can also use this sequence while inserting new records using the INSERT command:

INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');

52. What are string constants in PostgreSQL?

They are character sequences bound within single quotes. These are using during data insertion
or updation to characters in the database.
There are special string constants that are quoted in dollars.
Syntax: $tag$<string_constant>$tag$ The tag in the constant is optional and when we are not
specifying the tag, the constant is called a double-dollar string literal.

53. How can you get a list of all databases in PostgreSQL?

This can be done by using the command \l -> backslash followed by the lower-case letter L.

54. How can you delete a database in PostgreSQL?

This can be done by using the DROP DATABASE command as shown in the syntax below:

DROP DATABASE database_name;

If the database has been deleted successfully, then the following message would be shown:

DROP DATABASE

55. What are ACID properties? Is PostgreSQL compliant with ACID?

ACID stands for Atomicity, Consistency, Isolation, Durability. They are database transaction
properties which are used for guaranteeing data validity in case of errors and failures.
 Atomicity: This property ensures that the transaction is completed in all-or-nothing way.
 Consistency: This ensures that updates made to the database is valid and follows rules
and restrictions.
 Isolation: This property ensures integrity of transaction that are visible to all other
transactions.
 Durability: This property ensures that the committed transactions are stored
permanently in the database.

PostgreSQL is compliant with ACID properties.

56. Can you explain the architecture of PostgreSQL?

 The architecture of PostgreSQL follows the client-server model.


 The server side comprises of background process manager, query processer, utilities and
shared memory space which work together to build PostgreSQL’s instance that has
access to the data. The client application does the task of connecting to this instance
and requests data processing to the services. The client can either be GUI (Graphical
User Interface) or a web application. The most commonly used client for PostgreSQL is
pgAdmin.
57. What do you understand by multi-version concurrency control?

MVCC or Multi-version concurrency control is used for avoiding unnecessary database locks
when 2 or more requests tries to access or modify the data at the same time. This ensures that
the time lag for a user to log in to the database is avoided. The transactions are recorded when
anyone tries to access the content.

For more information regarding this, you can refer here.

58. What do you understand by command enable-debug?

The command enable-debug is used for enabling the compilation of all libraries and
applications. When this is enabled, the system processes get hindered and generally also
increases the size of the binary file. Hence, it is not recommended to switch this on in the
production environment. This is most commonly used by developers to debug the bugs in their
scripts and help them spot the issues. For more information regarding how to debug, you can
refer here.

59. How do you check the rows affected as part of previous transactions?

SQL standards state that the following three phenomena should be prevented whilst
concurrent transactions. SQL standards define 4 levels of transaction isolations to deal with
these phenomena.

 Dirty reads: If a transaction reads data that is written due to concurrent uncommitted
transaction, these reads are called dirty reads.
 Phantom reads: This occurs when two same queries when executed separately return
different rows. For example, if transaction A retrieves some set of rows matching search
criteria. Assume another transaction B retrieves new rows in addition to the rows
obtained earlier for the same search criteria. The results are different.
 Non-repeatable reads: This occurs when a transaction tries to read the same row
multiple times and gets different values each time due to concurrency. This happens
when another transaction updates that data and our current transaction fetches that
updated data, resulting in different values.

To tackle these, there are 4 standard isolation levels defined by SQL standards. They are as
follows:

 Read Uncommitted – The lowest level of the isolations. Here, the transactions are not
isolated and can read data that are not committed by other transactions resulting in
dirty reads.
 Read Committed – This level ensures that the data read is committed at any instant of
read time. Hence, dirty reads are avoided here. This level makes use of read/write lock
on the current rows which prevents read/write/update/delete of that row when the
current transaction is being operated on.
 Repeatable Read – The most restrictive level of isolation. This holds read and write locks
for all rows it operates on. Due to this, non-repeatable reads are avoided as other
transactions cannot read, write, update or delete the rows.
 Serializable – The highest of all isolation levels. This guarantees that the execution is
serializable where execution of any concurrent operations are guaranteed to be
appeared as executing serially.

The following table clearly explains which type of unwanted reads the levels avoid:

Isolation levels  Dirty Reads  Phantom Reads  Non-repeatable reads


Read Uncommitted  Might occur Might occur Might occur
Read Committed  Won’t occur Might occur Might occur
Repeatable Read Won’t occur Might occur Won’t occur
Serializable Won’t occur Won’t occur Won’t occur

60. What can you tell about WAL (Write Ahead Logging)?

Write Ahead Logging is a feature that increases the database reliability by logging
changes before any changes are done to the database. This ensures that we have enough
information when a database crash occurs by helping to pinpoint to what point the work has
been complete and gives a starting point from the point where it was discontinued.

For more information, you can refer here.

61. What is the main disadvantage of deleting data from an existing table using the
DROP TABLE command?

DROP TABLE command deletes complete data from the table along with removing the complete
table structure too. In case our requirement entails just remove the data, then we would need
to recreate the table to store data in it. In such cases, it is advised to use the TRUNCATE
command.

62. How do you perform case-insensitive searches using regular expressions in


PostgreSQL?

To perform case insensitive matches using a regular expression, we can use


POSIX (~*) expression from pattern matching operators. For example:

'interviewbit' ~* '.*INTervIewBit.*'

63. How will you take backup of the database in PostgreSQL?


We can achieve this by using the pg_dump tool for dumping all object contents in the database
into a single file. The steps are as follows:

Step 1: Navigate to the bin folder of the PostgreSQL installation path.

C:\>cd C:\Program Files\PostgreSQL\10.0\bin

Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown below:

pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\sample_data.tar

The database dump will be stored in the sample_data.tar file on the location specified.

64. Does PostgreSQL support full text search?

Full-Text Search is the method of searching single or collection of documents stored on a


computer in a full-text based database. This is mostly supported in advanced database systems
like SOLR or ElasticSearch. However, the feature is present but is pretty basic in PostgreSQL.

65. What are parallel queries in PostgreSQL?

Parallel Queries support is a feature provided in PostgreSQL for devising query plans capable of
exploiting multiple CPU processors to execute the queries faster.
66. Differentiate between commit and checkpoint.

The commit action ensures that the data consistency of the transaction is maintained and it
ends the current transaction in the section. Commit adds a new record in the log that
describes the COMMIT to the memory. Whereas, a checkpoint is used for writing all changes
that were committed to disk up to SCN which would be kept in datafile headers and control
files.

Conclusion:

SQL is a language for the database. It has a vast scope and robust capability of creating and
manipulating a 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 many 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 an additional level of control and in-depth understanding of the
application.

PostgreSQL being an open-source database system having extremely robust and sophisticated
ACID, Indexing, and Transaction supports has found widespread popularity among the
developer community. 

Top 50 SQL Interview Questions and Answers for


Experienced & Freshers (2021 Update)
ByRichard PetersonUpdatedOctober 27, 2021

SQL stands for Structured Query Language is a domain specific programming


language for managing the data in Database Management Systems. SQL
programming skills are highly desirable and required in the market, as there is a
massive use of Database Management Systems (DBMS) in almost every software
application. In order to get a job, candidates need to crack the interview in which
they are asked various SQL interview questions.
Following is a curated list of SQL questions for interview with answers, which are
likely to be asked during the SQL interview. Candidates are likely to be
asked SQL basic interview questions to advance level SQL interview questions for 3
years experience professionals, depending on their experience and various other
factors. The below list covers all the SQL technical interview questions for freshers as
well as SQL server interview questions for experienced level candidates and some
SQL query interview questions.

Free PDF Download: SQL Interview Questions

Frequently Asked SQL Interview Questions and Answers


for Freshers and Experienced
1. What is DBMS?
A Database Management System (DBMS) is a program that controls creation,
maintenance and use of a database. DBMS can be termed as File Manager that
manages data in a database rather than saving it in file systems.

2. What is RDBMS?
RDBMS stands for Relational Database Management System. RDBMS store the data
into the collection of tables, which is related by common fields between the columns
of the table. It also provides relational operators to manipulate the data stored into
the tables.

Example: SQL Server.

3. What is SQL?
SQL stands for Structured Query Language , and it is used to communicate with the
Database. This is a standard language used to perform tasks such as retrieval,
updation, insertion and deletion of data from a database.
Standard SQL Commands are Select.

4. What is a Database?
Database is nothing but an organized form of data for easy access, storing, retrieval
and managing of data. This is also known as structured form of data which can be
accessed in many ways.

Example: School Management Database, Bank Management Database.


5. What are tables and Fields?
A table is a set of data that are organized in a model with Columns and Rows.
Columns can be categorized as vertical, and Rows are horizontal. A table has
specified number of column called fields but can have any number of rows which is
called record.

Example:.

Table: Employee.

Field: Emp ID, Emp Name, Date of Birth.

Data: 201456, David, 11/15/1960.

6. What is a primary key?


A primary key is a combination of fields which uniquely specify a row. This is a special
kind of unique key, and it has implicit NOT NULL constraint. It means, Primary key
values cannot be NULL.

7. What is a unique key?


A Unique key constraint uniquely identified each record in the database. This
provides uniqueness for the column or set of columns.

A Primary key constraint has automatic unique constraint defined on it. But not, in
the case of Unique Key.

There can be many unique constraint defined per table, but only one Primary key
constraint defined per table.

8. What is a foreign key?


A foreign key is one table which can be related to the primary key of another table.
Relationship needs to be created between two tables by referencing foreign key with
the primary key of another table.

9. What is a join?
This is a keyword used to query data from more tables based on the relationship
between the fields of the tables. Keys play a major role when JOINs are used.
10. What are the types of join and explain each?
There are various types of join which can be used to retrieve data and it depends on
the relationship between tables.

 Inner Join.

Inner join return rows when there is at least one match of rows between the tables.

 Right Join.

Right join return rows which are common between the tables and all rows of Right
hand side table. Simply, it returns all the rows from the right hand side table even
though there are no matches in the left hand side table.

 Left Join.

Left join return rows which are common between the tables and all rows of Left hand
side table. Simply, it returns all the rows from Left hand side table even though there
are no matches in the Right hand side table.

 Full Join.

Full join return rows when there are matching rows in any one of the tables. This
means, it returns all the rows from the left hand side table and all the rows from the
right hand side table.

11. What is normalization?


Normalization is the process of minimizing redundancy and dependency by
organizing fields and table of a database. The main aim of Normalization is to add,
delete or modify field that can be made in a single table.

12. What is Denormalization?


DeNormalization is a technique used to access the data from higher to lower normal
forms of database. It is also process of introducing redundancy into a table by
incorporating data from the related tables.

13. What are all the different normalizations?


The normal forms can be divided into 5 forms, and they are explained below -.
 First Normal Form (1NF):.

This should remove all the duplicate columns from the table. Creation of tables for
the related data and identification of unique columns.

 Second Normal Form (2NF):.

Meeting all requirements of the first normal form. Placing the subsets of data in
separate tables and Creation of relationships between the tables using primary keys.

 Third Normal Form (3NF):.

This should meet all requirements of 2NF. Removing the columns which are not
dependent on primary key constraints.

 Fourth Normal Form (4NF):.

Meeting all the requirements of third normal form and it should not have multi-
valued dependencies.

14. What is a View?


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

15. What is an Index?


An index is performance tuning method of allowing faster retrieval of records from
the table. An index creates an entry for each value and it will be faster to retrieve
data.

16. What are all the different types of indexes?


There are three types of indexes -.

 Unique Index.

This indexing does not allow the field to have duplicate values if the column is unique
indexed. Unique index can be applied automatically when primary key is defined.

 Clustered Index.
This type of index reorders the physical order of the table and search based on the
key values. Each table can have only one clustered index.

 NonClustered Index.

NonClustered Index does not alter the physical order of the table and maintains
logical order of data. Each table can have 999 nonclustered indexes.

17. What is a Cursor?


A database Cursor is a control which enables traversal over the rows or records in
the table. This can be viewed as a pointer to one row in a set of rows. Cursor is very
much useful for traversing such as retrieval, addition and removal of database
records.

18. What is a relationship and what are they?


Database Relationship is defined as the connection between the tables in a database.
There are various data basing relationships, and they are as follows:.

 One to One Relationship.


 One to Many Relationship.
 Many to One Relationship.
 Self-Referencing Relationship.

19. What is a query?


A DB query is a code written in order to get the information back from the database.
Query can be designed in such a way that it matched with our expectation of the
result set. Simply, a question to the Database.

20. What is subquery?


A subquery is a query within another query. The outer query is called as main query,
and inner query is called subquery. SubQuery is always executed first, and the result
of subquery is passed on to the main query.

21. What are the types of subquery?


There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as independent query, but it can refer
the column in a table listed in the FROM the list of the main query.

A Non-Correlated sub query can be considered as independent query and the output
of subquery are substituted in the main query.

22. What is a stored procedure?


Stored Procedure is a function consists of many SQL statement to access the
database system. Several SQL statements are consolidated into a stored procedure
and execute them whenever and wherever required.

23. What is a trigger?


A DB trigger is a code or programs that automatically execute with response to some
event on a table or view in a database. Mainly, trigger helps to maintain the integrity
of the database.

Example: When a new student is added to the student database, new records should
be created in the related tables like Exam, Score and Attendance tables.

24. What is the difference between DELETE and TRUNCATE


commands?
DELETE command is used to remove rows from the table, and WHERE clause can be
used for conditional set of parameters. Commit and Rollback can be performed after
delete statement.

TRUNCATE removes all rows from the table. Truncate operation cannot be rolled
back.

25. What are local and global variables and their differences?
Local variables are the variables which can be used or exist inside the function. They
are not known to the other functions and those variables cannot be referred or used.
Variables can be created whenever that function is called.

Global variables are the variables which can be used or exist throughout the
program. Same variable declared in global cannot be used in functions. Global
variables cannot be created whenever that function is called.
26. What is a constraint?
Constraint can be used to specify the limit on the data type of table. Constraint can
be specified while creating or altering the table statement. Sample of constraint are.

 NOT NULL.
 CHECK.
 DEFAULT.
 UNIQUE.
 PRIMARY KEY.
 FOREIGN KEY.

27. What is data Integrity?


Data Integrity defines the accuracy and consistency of data stored in a database. It
can also define integrity constraints to enforce business rules on the data when it is
entered into the application or database.

28. What is Auto Increment?


Auto increment keyword allows the user to create a unique number to be generated
when a new record is inserted into the table. AUTO INCREMENT keyword can be
used in Oracle and IDENTITY keyword can be used in SQL SERVER.

Mostly this keyword can be used whenever PRIMARY KEY is used.

29. What is the difference between Cluster and Non-Cluster Index?


Clustered index is used for easy retrieval of data from the database by altering the
way that the records are stored. Database sorts out rows by the column which is set
to be clustered index.

A nonclustered index does not alter the way it was stored but creates a complete
separate object within the table. It point back to the original table rows after
searching.

30. What is Datawarehouse?


Datawarehouse is a central repository of data from multiple sources of information.
Those data are consolidated, transformed and made available for the mining and
online processing. Warehouse data have a subset of data called Data Marts.
31. What is Self-Join?
Self-join is set to be query used to compare to itself. This is used to compare values
in a column with other values in the same column in the same table. ALIAS ES can be
used for the same table comparison.

32. What is Cross-Join?


Cross join defines as Cartesian product where number of rows in the first table
multiplied by number of rows in the second table. If suppose, WHERE clause is used
in cross join then the query will work like an INNER JOIN.

33. What is user defined functions?


User defined functions are the functions written to use that logic whenever required.
It is not necessary to write the same logic several times. Instead, function can be
called or executed whenever needed.

34. What are all types of user defined functions?


Three types of user defined functions are.

 Scalar Functions.
 Inline Table valued functions.
 Multi statement valued functions.

Scalar returns unit, variant defined the return clause. Other two types return table as
a return.

35. What is collation?


Collation is defined as set of rules that determine how character data can be sorted
and compared. This can be used to compare A and, other language characters and
also depends on the width of the characters.

ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?


Following are different types of collation sensitivity -.

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


 Accent Sensitivity.
 Kana Sensitivity – Japanese Kana characters.
 Width Sensitivity – Single byte character and double byte character.

37. Advantages and Disadvantages of Stored Procedure?


Stored procedure can be used as a modular programming – means create once, store
and call for several times whenever required. This supports faster execution instead
of executing multiple queries. This reduces network traffic and provides better
security to the data.

Disadvantage is that it can be executed only in the Database and utilizes more
memory in the database server.

38. What is Online Transaction Processing (OLTP)?


Online Transaction Processing (OLTP) manages transaction based applications which
can be used for data entry, data retrieval and data processing. OLTP makes data
management simple and efficient. Unlike OLAP systems goal of OLTP systems is
serving real-time transactions.

Example – Bank Transactions on a daily basis.

39. What is CLAUSE?


SQL clause is defined to limit the result set by providing condition to the query. This
usually filters some rows from the whole set of records.

Example – Query that has WHERE condition

Query that has HAVING condition.

40. What is recursive stored procedure?


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

41. What is Union, minus and Interact commands?


UNION operator is used to combine the results of two tables, and it eliminates
duplicate rows from the tables.
MINUS operator is used to return rows from the first query but not from the second
query. Matching records of first and second query and other rows from the first
query will be displayed as a result set.

INTERSECT operator is used to return rows returned by both the queries.

42. What is an ALIAS command?


ALIAS name can be given to a table or column. This alias name can be referred in
WHERE clause to identify the table or column.

Example-.

Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex. StudentID
Here, st refers to alias name for student table and Ex refers to alias name for exam
table.

43. What is the difference between TRUNCATE and DROP


statements?
TRUNCATE removes all the rows from the table, and it cannot be rolled back. DROP
command removes a table from the database and operation cannot be rolled back.

44. What are aggregate and scalar functions?


Aggregate functions are used to evaluate mathematical calculation and return single
values. This can be calculated from the columns in a table. Scalar functions return a
single value based on the input value.

Example -.

Aggregate – max(), count – Calculated with respect to numeric.

Scalar – UCASE(), NOW() – Calculated with respect to strings.

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


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

48. How to select unique records from a table?


Select unique records from a table by using DISTINCT keyword.

Select DISTINCT StudentID, StudentName from Student.


49. 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
50. 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.
PL/SQL stands for Procedural Language extensions to SQL (Structured Query Language). It was
created by Oracle in order to overcome the disadvantages of SQL for easier building and
handling of critical applications in a comprehensive manner.
Following are the disadvantages of SQL:

 There is no provision of decision-making, looping, and branching in SQL.


 Since the SQL statements get passed to the Oracle engine all at the same time, the
speed of execution decreases due to the nature of increased traffic.
 There is no feature of error checking while manipulating the data.

PL/SQL was introduced to overcome the above disadvantages by retaining the power of SQL
and combining it with the procedural statements. It is developed as a block-structured language
and the statements of the block are passed to the oracle engine which helps to increase the
speed of processing due to the decrease in traffic.

Crack your next tech interview with confidence!


Take a free mock interview, get instant⚡️feedback and recommendation💡
Take Free Mock Interview

PL/SQL Basic Interview Questions


1. What are the features of PL/SQL?

Following are the features of PL/SQL:

 PL/SQL provides the feature of decision making, looping, and branching by making use
of its procedural nature.
 Multiple queries can be processed in one block by making use of a single command
using PL/SQL.
 The PL/SQL code can be reused by applications as they can be grouped and stored in
databases as PL/SQL units like functions, procedures, packages, triggers, and types.
 PL/SQL supports exception handling by making use of an exception handling block.
 Along with exception handling, PL/SQL also supports error checking and validation of
data before data manipulation.
 Applications developed using PL/SQL are portable across computer hardware or
operating system where there is an Oracle engine.

2. What do you understand by PL/SQL table?

 PL/SQL tables are nothing but objects of type tables that are modeled as database
tables. They are a way to provide arrays that are nothing but temporary tables in
memory for faster processing.
 These tables are useful for moving bulk data thereby simplifying the process.
3. Explain the basic structure followed in PL/SQL?

 The basic structure of PL/SQL follows the BLOCK structure. Each PL/SQL code comprises
SQL and PL/SQL statement that constitutes a PL/SQL block.
 Each PL/SQL block consists of 3 sections:
o The optional Declaration Section
o The mandatory Execution Section
o The optional Exception handling Section

[DECLARE]
--declaration statements (optional)
BEGIN
--execution statements
[EXCEPTION]
--exception handling statements (optional)
END;
You can download a PDF version of Pl Sql Interview Questions.

Download PDF

4. What is a PL/SQL cursor?

 A PL/SQL cursor is nothing but a pointer to an area of memory having SQL statements
and the information of statement processing. This memory area is called a context area.
This special area makes use of a special feature called cursor for the purpose of
retrieving and processing more than one row.
 In short, the cursor selects multiple rows from the database and these selected rows are
individually processed within a program.
 There are two types of cursors:
o Implicit Cursor:
 Oracle automatically creates a cursor while running any of the commands
- SELECT INTO, INSERT, DELETE or UPDATE implicitly.
 The execution cycle of these cursors is internally handled by Oracle and
returns the information and status of the cursor by making use of the
cursor attributes- ROWCOUNT, ISOPEN, FOUND, NOTFOUND.
o Explicit Cursor:
 This cursor is a SELECT statement that was declared explicitly in the
declaration block.
 The programmer has to control the execution cycle of these cursors
starting from OPEN to FETCH and close.
 The execution cycle while executing the SQL statement is defined by
Oracle along with associating a cursor with it.
 Explicit Cursor Execution Cycle:
o Due to the flexibility of defining our own execution cycle, explicit cursors are
used in many instances. The following diagram represents the execution flow of
an explicit cursor:

 Cursor Declaration:
o The first step to use an explicit cursor is its declaration.
o Declaration can be done in a package or a block.
o Syntax: CURSOR cursor_name IS query; where cursor_name is the name of the cursor,
the query is the query to fetch data from any table.
 Open Cursor:
o Before the process of fetching rows from cursor, the cursor has to be opened.
o Syntax to open a cursor: OPEN cursor_name;
o When the cursor is opened, the query and the bind variables are parsed by
Oracle and the SQL statements are executed.
o The execution plan is determined by Oracle and the result set is determined after
associating the cursor parameters and host variables and post these, the cursor
is set to point at the first row of the result set.
 Fetch from cursor:
o FETCH statement is used to place the content of the current row into variables.
o Syntax: FETCH cursor_name INTO variable_list;
o In order to get all the rows of a result set, each row needs to be fetched.
 Close Cursor:
o Once all the rows are fetched, the cursor needs to be closed using the CLOSE
statement.
o Syntax: CLOSE cursor_name;
o The instructions tell Oracle to release the memory allocated to the cursor.
 Cursors declared in procedures or anonymous blocks are by default
closed post their execution.
 Cursors declared in packages need to be closed explicitly as the scope is
global.
 Closing a cursor that is not opened will result in INVALID_CURSOR
exception.

5. What is the use of WHERE CURRENT OF in cursors?

 We use this clause while referencing the current row from an explicit cursor. This clause
allows applying updates and deletion of the row currently under consideration without
explicitly referencing the row ID.
 Syntax:
UPDATE table_name SET field=new_value WHERE CURRENT OF cursor_name

6. How can a name be assigned to an unnamed PL/SQL Exception Block?

 This can be done by using Pragma called EXCEPTION_INIT.


 This gives the flexibility to the programmer to instruct the compiler to provide custom
error messages based on the business logic by overriding the pre-defined messages
during the compilation time.
 Syntax:

DECLARE
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT (exception_name, error_code);
BEGIN
// PL/SQL Logic
EXCEPTION
WHEN exception_name THEN
// Steps to handle exception
END;

7. What is a Trigger? Name some instances when “Triggers” can be used.

 As the name indicates, ‘Trigger’ means to ‘activate’ something. In the case of PL/SQL, a
trigger is a stored procedure that specifies what action has to be taken by the database
when an event related to the database is performed.
 Syntax:

TRIGGER trigger_name
trigger_event
[ restrictions ]
BEGIN
actions_of_trigger;
END;

In the above syntax, if the trigger_name the trigger is in the enabled state, the trigger_event causes


the database to fire actions_of_trigger if the restrictions are TRUE or unavailable.

 They are mainly used in the following scenarios:


o In order to maintain complex integrity constraints.
o For the purpose of auditing any table information.
o Whenever changes are done to a table, if we need to signal other actions upon
completion of the change, then we use triggers.
o In order to enforce complex rules of business.
o It can also be used to prevent invalid transactions.
 You can refer https://docs.oracle.com/database/121/TDDDG/tdddg_triggers.htm for
more information regarding triggers.

8. When does a DECLARE block become mandatory?

 This statement is used by anonymous blocks of PL/SQL such as non-stored and stand-
alone procedures. When they are being used, the statement should come first in the
stand-alone file.
9. How do you write comments in a PL/SQL code?

 Comments are those sentences that have no effect on the functionality and are used for
the purpose of enhancing the readability of the code. They are of two types:
o Single Line Comment: This can be created by using the symbol -- and writing
what we want to mention as a comment next to it.
o Multi-Line comment: These are the comments that can be specified over
multiple lines and the syntax goes like /* comment information */
 Example:

SET SERVEROUTPUT ON;


DECLARE

-- Hi There! I am a single line comment.


var_name varchar2(40) := 'I love PL/SQL' ;
BEGIN
/*
Hi! I am a multi line
comment. I span across
multiple lines
*/
dbms_output.put_line(var_name);
END;
/
Output:
I love PL/SQL

10. What is the purpose of WHEN clause in the trigger?

 WHEN clause specifies for what condition the trigger has to be triggered.

PL/SQL Intermediate Interview Questions


11. Can you explain the PL/SQL execution architecture?

The PL/SQL engine does the process of compilation and execution of the PL/SQL blocks and
programs and can only work if it is installed on an Oracle server or any application tool that
supports Oracle such as Oracle Forms.

 PL/SQL is one of the parts of Oracle RDBMS, and it is important to know that most of the
Oracle applications are developed using the client-server architecture. The Oracle
database forms the server-side and requests to the database form a part of the client-
side.
 So based on the above fact and the fact that PL/SQL is not a standalone programming
language, we must realize that the PL/SQL engine can reside in either the client
environment or the server environment. This makes it easy to move PL/SQL modules
and sub-programs between server-side and client-side applications.
 Based on the architecture shown below, we can understand that PL/SQL engine plays an
important role in the process and execute the PL/SQL statements and whenever it
encounters the SQL statements, they are sent to the SQL Statement Processor.

 Case 1: PL/SQL engine is on the server: In this case, the whole PL/SQL block gets passed
to the PL/SQL engine present on the Oracle server which is then processed and the
response is sent.
 Case 2: PL/SQL engine is on the client: Here the engine lies within the Oracle Developer
tools and the processing of the PL/SQL statements is done on the client-side.
o In case, there are any SQL statements in the PL/SQL block, then they are sent to
the Oracle server for SQL processing.
o When there are no SQL statements, then the whole block processing occurs at
the client-side.

12. Why is SYSDATE and USER keywords used?

 SYSDATE:
o This keyword returns the current time and date on the local database server.
o The syntax is SYSDATE.
o In order to extract part of the date, we use the TO_CHAR function on SYSDATE
and specify the format we need.
o Usage:
 SELECT SYSDATE FROM dual;
 SELECT id, TO_CHAR(SYSDATE, 'yyyy/mm/dd') from InterviewBitEmployeeTable where
customer_id < 200;
 USER:
o This keyword returns the user id of the current session.
o Usage:
 SELECT USER FROM dual;

13. Differentiate between implicit cursor and explicit cursor.

Implicit Cursor  Explicit Cursor


When a subquery returns more than one row, an
An implicit cursor is used when a query
explicit cursor is used. These rows are called Active
returns a single row value.
Set.
This is used for all DML operations like
This is used to process Multirow SELECT Statements.
DECLARE, OPEN, FETCH, CLOSE.
NO_DATA_FOUND Exception is handled
NO_DATA_FOUND cannot be handled here.
here.

14. Differentiate between SQL and PL/SQL.

SQL PL/SQL
SQL is a natural language meant for the interactive
PL/SQL is a procedural extension of SQL.
processing of data in the database.
PL/SQL supports all features of procedural
Decision-making and looping are not allowed in
language such as conditional and looping
SQL.
statements.
All SQL statements are executed at a time by the PL/SQL statements are executed one block
database server which is why it becomes a time- at a time thereby reducing the network
consuming process. traffic.
There is no error handling mechanism in SQL. This supports an error handling mechanism.

15. What is the importance of %TYPE and %ROWTYPE data types in PL/SQL?

 %TYPE: This declaration is used for the purpose of anchoring by providing the data type
of any variable, column, or constant. It is useful during the declaration of a variable that
has the same data type as that of its table column.
o Consider the example of declaring a variable named ib_employeeid which has the
data type and its size same as that of the column employeeid in table ib_employee. 
The syntax would be : ib_employeeid ib_employee.employeeid%TYPE;
 %ROWTYPE: This is used for declaring a variable that has the same data type and size as
that of a row in the table. The row of a table is called a record and its fields would have
the same data types and names as the columns defined in the table.
o For example: In order to declare a record named ib_emprecord for storing an
entire row in a table called ib_employee, the syntax is:
ib_emprecord ib_employee%ROWTYPE;

16. What are the various functions available for manipulating the character data?

 The functions that are used for manipulating the character data are called String
Functions.
o LEFT: This function returns the specified number of characters from the left part
of a string.
 Syntax: LEFT(string_value, numberOfCharacters).
 For example, LEFT(‘InterviewBit’, 9) will return ‘Interview’.
o RIGHT: This function returns the defined number of characters from the right
part of a string.
 Syntax: RIGHT(string_value, numberOfCharacters)
 For example, RIGHT(‘InterviewBit’,3) would return ‘Bit’.
o SUBSTRING: This function would select the data from a specified start position
through the number of characters defined from any part of the string.
 Syntax: SUBSTRING(string_value, start_position, numberOfCharacters)
 For example, SUBSTRING(‘InterviewBit’,2,4) would return ‘terv’.
o LTRIM: This function would trim all the white spaces on the left part of the
string.
 Syntax: LTRIM(string_value)
 For example, LTRIM(’ InterviewBit’) will return ‘InterviewBit’.
o RTRIM: This function would trim all the white spaces on the right part of the
string.
 Syntax: RTRIM(string_value)
 For example, RTRIM('InterviewBit ') will return ‘InterviewBit’.
o UPPER: This function is used for converting all the characters to the upper case
in a string.
 Syntax: UPPER(string_variable)
 For example, UPPER(‘interviewBit’) would return ‘INTERVIEWBIT’.
o LOWER: This function is used for converting all the characters of a string to
lowercase.
 Syntax: LOWER(string_variable)
 For example, LOWER(‘INterviewBit’) would return ‘interviewbit’.

17. What is the difference between ROLLBACK and ROLLBACK TO statements in


PL/SQL?

 ROLLBACK command is used for rolling back all the changes from the beginning of the
transaction.
 ROLLBACK TO command is used for undoing the transaction only till a SAVEPOINT. The
transactions cannot be rolled back before the SAVEPOINT and hence the transaction
remains active even before the command is specified.

18. What is the use of SYS.ALL_DEPENDENCIES?

 SYS.ALL_DEPENDENCIES is used for describing all the dependencies between


procedures, packages, triggers, functions that are accessible to the current user. It
returns the columns like name, dependency_type, type, referenced_owner etc.

19. What are the virtual tables available during the execution of the database
trigger?

 The THEN and NOW tables are the virtual tables that are available during the database
trigger execution. The table columns are referred to as THEN.column and NOW.column
respectively.
 Only the NOW.column is available for insert-related triggers.
 Only the THEN.column values are available for the DELETE-related triggers.
 Both the virtual table columns are available for UPDATE triggers.

20. Differentiate between the cursors declared in procedures and the cursors
declared in the package specifications.

 The cursors that are declared in the procedures will have the local scope and hence they
cannot be used by other procedures.
 The cursors that are declared in package specifications are treated with global scope
and hence they can be used and accessed by other procedures.

PL/SQL Advanced Interview Questions


21. What are COMMIT, ROLLBACK and SAVEPOINT statements in PL/SQL?

 These are the three transaction specifications that are available in PL/SQL.
 COMMIT: Whenever any DML operations are performed, the data gets manipulated
only in the database buffer and not the actual database. In order to save these DML
transactions to the database, there is a need to COMMIT these transactions.
o COMMIT transaction action does saving of all the outstanding changes since the
last commit and the below steps take place:
 The release of affected rows.
 The transaction is marked as complete.
 The details of the transaction would be stored in the data dictionary.
o Syntax: COMMIT;
 ROLLBACK: In order to undo or erase the changes that were done in the current
transaction, the changes need to be rolled back. ROLLBACK statement erases all the
changes since the last COMMIT.
o Syntax: ROLLBACK;
 SAVEPOINT: This statement gives the name and defines a point in the current
transaction process where any changes occurring before that SAVEPOINT would be
preserved whereas all the changes after that point would be released.
o Syntax: SAVEPOINT <savepoint_name>;

22. How can you debug your PL/SQL code?

 We can use DBMS_OUTPUT and DBMS_DEBUG statements for debugging our code:
o DBMS_OUTPUT prints the output to the standard console.
o DBMS_DEBUG prints the output to the log file.

23. What is the difference between a mutating table and a constraining table?

 A table that is being modified by the usage of the DML statement currently is known as
a mutating table. It can also be a table that has triggers defined on it.
 A table used for reading for the purpose of referential integrity constraint is called a
constraining table.

24. In what cursor attributes the outcomes of DML statement execution are saved?

 The outcomes of the execution of the DML statement is saved in the following 4 cursor
attributes:
o SQL%FOUND: This returns TRUE if at least one row has been processed.
o SQL%NOTFOUND: This returns TRUE if no rows were processed.
o SQL%ISOPEN: This checks whether the cursor is open or not and returns TRUE if
open.
o SQL%ROWCOUNT: This returns the number of rows processed by the DML
statement.

25. Is it possible to declare column which has the number data type and its scale
larger than the precision? For example defining columns like: column name
NUMBER (10,100), column name NUMBER (10,-84)

 Yes, these type of declarations are possible.


 Number (9, 12) indicates that there are 12 digits after decimal point. But since the
maximum precision is 9, the rest are 0 padded like 0.000999999999.
 Number (9, -12) indicates there are 21 digits before the decimal point and out of that
there are 9 possible digits and the rest are 0 padded like 999999999000000000000.0
PL/SQL Programs
26. Write a PL/SQL program using WHILE loop for calculating the average of the
numbers entered by user. Stop the entry of numbers whenever the user enters the
number 0.

DECLARE
n NUMBER;
average NUMBER :=0 ;
sum NUMBER :=0 ;
count NUMBER :=0 ;
BEGIN
-- Take input from user
n := &input_number;
WHILE(n<>0)
LOOP
-- Increment count to find total elements
count := count+1;
-- Sum of elements entered
sum := sum+n;
-- Take input from user
n := &input_number;
END LOOP;
-- Average calculation
average := sum/count;
DBMS_OUTPUT.PUT_LINE(‘Average of entered numbers is ’||average);
END;

27. Write a PL/SQL procedure for selecting some records from the database using
some parameters as filters.

 Consider that we are fetching details of employees from ib_employee table where
salary is a parameter for filter.

CREATE PROCEDURE get_employee_details @salary nvarchar(30)


AS
BEGIN
SELECT * FROM ib_employee WHERE salary = @salary;
END;

28. Write a PL/SQL code to count the number of Sundays between the two
inputted dates.

--declare 2 dates of type Date


DECLARE
start_date Date;
end_date Date;
sundays_count Number:=0;
BEGIN
-- input 2 dates
start_date:='&input_start_date';
end_date:='&input_end_date';
/*
Returns the date of the first day after the mentioned date
and matching the day specified in second parameter.
*/
start_date:=NEXT_DAY(start_date-1, 'SUNDAY');
--check the condition of dates by using while loop.
while(start_date<=end_date)
LOOP
sundays_count:=sundays_count+1;
start_date:=start_date+7;
END LOOP;

-- print the count of sundays


dbms_output.put_line('Total number of Sundays between the two dates:'||sundays_count);
END;
/

Input:
start_date = ‘01-SEP-19’
end_date = ‘29-SEP-19’

Output:
Total number of Sundays between the two dates: 5

29. Write PL/SQL code block to increment the employee’s salary by 1000 whose
employee_id is 102 from the given table below.

EMPLOYEE_I FIRST_NAM LAST_NAM EMAIL_I PHONE_NUMBE JOIN_DAT


JOB_ID  SALARY
D E E D R E
2020-06- AD_PRE 24000.0
100 ABC DEF abef 9876543210
06  S 0
2021-02- 17000.0
101 GHI JKL ghkl 9876543211  AD_VP
08 0
2016-05- 17000.0
102 MNO  PQR mnqr 9876543212 AD_VP
14 0
2019-06- IT_PRO
103 STU VWX stwx 9876543213 9000.00
24 G
DECLARE
employee_salary NUMBER(8,2);

PROCEDURE update_salary (
emp NUMBER,
salary IN OUT NUMBER
) IS
BEGIN
salary := salary + 1000;
END;

BEGIN
SELECT salary INTO employee_salary
FROM ib_employee
WHERE employee_id = 102;

DBMS_OUTPUT.PUT_LINE
('Before update_salary procedure, salary is: ' || employee_salary);

update_salary (100, employee_salary);

DBMS_OUTPUT.PUT_LINE
('After update_salary procedure, salary is: ' || employee_salary);
END;
/

Result:

Before update_salary procedure, salary is: 17000


After update_salary procedure, salary is: 18000

30. Write a PL/SQL code to find whether a given string is palindrome or not.

DECLARE
-- Declared variables string, letter, reverse_string where string is the original string.
string VARCHAR2(10) := 'abccba';
letter VARCHAR2(20);
reverse_string VARCHAR2(10);
BEGIN
FOR i IN REVERSE 1..LENGTH(string) LOOP
letter := SUBSTR(string, i, 1);
-- concatenate letter to reverse_string variable
reverse_string := reverse_string ||''||letter;
END LOOP;
IF reverse_string = string THEN
dbms_output.Put_line(reverse_string||''||' is palindrome');
ELSE
dbms_output.Put_line(reverse_string ||'' ||' is not palindrome');
END IF;
END;

31. Write PL/SQL program to convert each digit of a given number into its
corresponding word format.

DECLARE
-- declare necessary variables
-- num represents the given number
-- number_to_word represents the word format of the number
-- str, len and digit are the intermediate variables used for program execution
num INTEGER;
number_to_word VARCHAR2(100);
digit_str VARCHAR2(100);
len INTEGER;
digit INTEGER;
BEGIN
num := 123456;
len := LENGTH(num);
dbms_output.PUT_LINE('Input: ' ||num);
-- Iterate through the number one by one
FOR i IN 1..len LOOP
digit := SUBSTR(num, i, 1);
-- Using DECODE, get the str representation of the digit
SELECT Decode(digit, 0, 'Zero ',
1, 'One ',
2, 'Two ',
3, 'Three ',
4, 'Four ',
5, 'Five ',
6, 'Six ',
7, 'Seven ',
8, 'Eight ',
9, 'Nine ')
INTO digit_str
FROM dual;
-- Append the str representation of digit to final result.
number_to_word := number_to_word || digit_str;
END LOOP;
dbms_output.PUT_LINE('Output: ' ||number_to_word);
END;

Input: 12345
Output: One Two Three Four Five

32. Write PL/SQL program to find the sum of digits of a number.

DECLARE
--Declare variables num, sum_of_digits and remainder of datatype Integer
num INTEGER;
sum_of_digits INTEGER;
remainder INTEGER;
BEGIN
num := 123456;
sum_of_digits := 0;
-- Find the sum of digits until original number doesnt become null
WHILE num <> 0 LOOP
remainder := MOD(num, 10);
sum_of_digits := sum_of_digits + remainder;
num := TRUNC(num / 10);
END LOOP;
dbms_output.PUT_LINE('Sum of digits is '|| sum_of_digits);
END;

Input: 9874
Output: 28

PL/SQL Conclusion
33. PL SQL Interview

 PL/SQL is a programming extension of SQL developed by Oracle which combines the


power of SQL in the field of data manipulation and the power of procedural language
for faster and effective processing of data thereby resulting in the creation of powerful
queries.
 PL/SQL enhances the security, increases the platform portability, and makes it more
robust by means of instructing the compiler ‘what to do’ and ‘how to do’ using SQL
and procedural form respectively.
 Finally, it gives more power over the database to the programmers due to the feature
of decision making, filtering, and looping abilities thereby making it a more convenient
and reliable means for the programmers to work on it.

Top 65 PL/SQL Interview Questions & Answers


(2021 Update)
ByRichard PetersonUpdatedOctober 27, 2021

1) What is PL SQL ?
PL SQL is a procedural language which has interactive SQL, as well as procedural
programming language constructs like conditional branching and iteration.

2) Differentiate between % ROWTYPE and TYPE RECORD.

% ROWTYPE is used when a query returns an entire row of a table or view.

TYPE RECORD, on the other hand, is used when a query returns column of different
tables or views.

Eg. TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname %type)

e_rec smp %ROWTYPE


Cursor c1 is select smpno,dept from smp;

e_rec c1 %ROWTYPE

3) Explain uses of cursor.

Cursor is a named private area in SQL from which information can be accessed. They
are required to process each row individually for queries which return multiple rows.

4) Show code of a cursor for loop.


Cursor declares %ROWTYPE as loop index implicitly. It then opens a cursor, gets rows
of values from the active set in fields of the record and shuts when all records are
processed.

Eg. FOR smp_rec IN C1 LOOP

totalsal=totalsal+smp_recsal;

ENDLOOP;

5) Explain the uses of database trigger.

A PL/SQL program unit associated with a particular database table is called a


database trigger. It is used for :

1) Audit data modifications.

2) Log events transparently.

3) Enforce complex business rules.

4) Maintain replica tables

5) Derive column values

6) Implement Complex security authorizations

6) What are the two types of exceptions.


Error handling part of PL/SQL block is called Exception. They have two types :
user_defined and predefined.

7) Show some predefined exceptions.

DUP_VAL_ON_INDEX

ZERO_DIVIDE

NO_DATA_FOUND

TOO_MANY_ROWS

CURSOR_ALREADY_OPEN

INVALID_NUMBER

INVALID_CURSOR

PROGRAM_ERROR

TIMEOUT _ON_RESOURCE

STORAGE_ERROR

LOGON_DENIED

VALUE_ERROR

etc.

8) Explain Raise_application_error.
It is a procedure of package DBMS_STANDARD that allows issuing of user_defined
error messages from database trigger or stored sub-program.

9) Show how functions and procedures are called in a PL SQL block.

Function is called as a part of an expression.

total:=calculate_sal(‘b644’)
Procedure is called as a statement in PL/SQL.

calculate_bonus(‘b644’);

10) Explain two virtual tables available at the time of database trigger execution.

Table columns are referred as OLD.column_name and NEW.column_name.

For INSERT related triggers, NEW.column_name values are available only.

For DELETE related triggers, OLD.column_name values are available only.

For UPDATE related triggers, both Table columns are available.

11) What are the rules to be applied to NULLs whilst doing comparisons?

1) NULL is never TRUE or FALSE

2) NULL cannot be equal or unequal to other values

3) If a value in an expression is NULL, then the expression itself evaluates to NULL


except for concatenation operator (||)

12) How is a process of PL SQL compiled?

Compilation process includes syntax check, bind and p-code generation processes.

Syntax checking checks the PL SQL codes for compilation errors. When all errors are
corrected, a storage address is assigned to the variables that hold data. It is called
Binding. P-code is a list of instructions for the PL SQL engine. P-code is stored in the
database for named blocks and is used the next time it is executed.

13) Differentiate between Syntax and runtime errors.

A syntax error can be easily detected by a PL/SQL compiler. For eg, incorrect spelling.

A runtime error is handled with the help of exception-handling section in an PL/SQL


block. For eg, SELECT INTO statement, which does not return any rows.

14) Explain Commit, Rollback and Savepoint.

For a COMMIT statement, the following is true:


 Other users can see the data changes made by the transaction.
 The locks acquired by the transaction are released.
 The work done by the transaction becomes permanent.

A ROLLBACK statement gets issued when the transaction ends, and the following is
true.

 The work done in a transition is undone as if it was never issued.


 All locks acquired by transaction are released.

It undoes all the work done by the user in a transaction. With SAVEPOINT, only part
of transaction can be undone.

15) Define Implicit and Explicit Cursors.

A cursor is implicit by default. The user cannot control or process the information in
this cursor.

If a query returns multiple rows of data, the program defines an explicit cursor. This
allows the application to process each row sequentially as the cursor returns it.

16) Explain mutating table error.

It occurs when a trigger tries to update a row that it is currently using. It is fixed by
using views or temporary tables, so database selects one and updates the other.

17) When is a declare statement required?

DECLARE statement is used by PL SQL anonymous blocks such as with stand alone,
non-stored procedures. If it is used, it must come first in a stand alone file.

18) How many triggers can be applied to a table?

A maximum of 12 triggers can be applied to one table.

19) What is the importance of SQLCODE and SQLERRM?


SQLCODE returns the value of the number of error for the last encountered error
whereas SQLERRM returns the message for the last error.
20) If a cursor is open, how can we find in a PL SQL Block?

the %ISOPEN cursor status variable can be used.

21) Show the two PL/SQL cursor exceptions.

Cursor_Already_Open

Invaid_cursor

22) What operators deal with NULL?

NVL converts NULL to another specified value.

var:=NVL(var2,’Hi’);

IS NULL and IS NOT NULL can be used to check specifically to see whether the value
of a variable is NULL or not.

23) Does SQL*Plus also have a PL/SQL Engine?

No, SQL*Plus does not have a PL/SQL Engine embedded in it. Thus, all PL/SQL code is
sent directly to database engine. It is much more efficient as each statement is not
individually stripped off.

24) What packages are available to PL SQL developers?

DBMS_ series of packages, such as, DBMS_PIPE, DBMS_DDL, DBMS_LOCK,


DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_SQL,
DBMS_TRANSACTION, UTL_FILE.

25) Explain 3 basic parts of a trigger.

 A triggering statement or event.


 A restriction
 An action

26) What are character functions?


INITCAP, UPPER, SUBSTR, LOWER and LENGTH are all character functions. Group
functions give results based on groups of rows, as opposed to individual rows. They
are MAX, MIN, AVG, COUNT and SUM.

27) Explain TTITLE and BTITLE.

TTITLE and BTITLE commands that control report headers and footers.

28) Show the cursor attributes of PL/SQL.

%ISOPEN : Checks if the cursor is open or not

%ROWCOUNT : The number of rows that are updated, deleted or fetched.

%FOUND : Checks if the cursor has fetched any row. It is true if rows are fetched

%NOT FOUND : Checks if the cursor has fetched any row. It is True if rows are not
fetched.

29) What is an Intersect?


Intersect is the product of two tables and it lists only matching rows.

30) What are sequences?

Sequences are used to generate sequence numbers without an overhead of locking.


Its drawback is that the sequence number is lost if the transaction is rolled back.

31) How would you reference column values BEFORE and AFTER you have inserted
and deleted triggers?

Using the keyword “new.column name”, the triggers can reference column values by
new collection. By using the keyword “old.column name”, they can reference column
vaues by old collection.

32) What are the uses of SYSDATE and USER keywords?

SYSDATE refers to the current server system date. It is a pseudo column. USER is also
a pseudo column but refers to current user logged onto the session. They are used to
monitor changes happening in the table.
33) How does ROWID help in running a query faster?

ROWID is the logical address of a row, it is not a physical column. It composes of data
block number, file number and row number in the data block. Thus, I/O time gets
minimized retrieving the row, and results in a faster query.

34) What are database links used for?

Database links are created in order to form communication between various


databases, or different environments like test, development and production. The
database links are read-only to access other information as well.

35) What does fetching a cursor do?

Fetching a cursor reads Result Set row by row.

36) What does closing a cursor do?

Closing a cursor clears the private SQL area as well as de-allocates memory

37) Explain the uses of Control File.

It is a binary file. It records the structure of the database. It includes locations of


several log files, names and timestamps. They can be stored in different locations to
help in retrieval of information if one file gets corrupted.

38) Explain Consistency

Consistency shows that data will not be reflected to other users until the data is
commit, so that consistency is maintained.

39) Differ between Anonymous blocks and sub-programs.

Anonymous blocks are unnamed blocks that are not stored anywhere whilst sub-
programs are compiled and stored in database. They are compiled at runtime.

40) Differ between DECODE and CASE.


DECODE and CASE statements are very similar, but CASE is extended version of
DECODE. DECODE does not allow Decision making statements in its place.
select decode(totalsal=12000,’high’,10000,’medium’) as decode_tesr from smp
where smpno in (10,12,14,16);

This statement returns an error.

CASE is directly used in PL SQL, but DECODE is used in PL SQL through SQL only.

41) Explain autonomous transaction.

An autonomous transaction is an independent transaction of the main or parent


transaction. It is not nested if it is started by another transaction.

There are several situations to use autonomous transactions like event logging and
auditing.

42) Differentiate between SGA and PGA.

SGA stands for System Global Area whereas PGA stands for Program or Process
Global Area. PGA is only allocated 10% RAM size, but SGA is given 40% RAM size.

43) What is the location of Pre_defined_functions.

They are stored in the standard package called “Functions, Procedures and
Packages”

44) Explain polymorphism in PL SQL.

Polymorphism is a feature of OOP. It is the ability to create a variable, an object or


function with multiple forms. PL/SQL supports Polymorphism in the form of program
unit overloading inside a member function or package..Unambiguous logic must be
avoided whilst overloading is being done.

45) What are the uses of MERGE?

MERGE is used to combine multiple DML statements into one.

Syntax : merge into tablename

using(query)

on(join condition)
when not matched then

[insert/update/delete] command

when matched then

[insert/update/delete] command

46) Can 2 queries be executed simultaneously in a Distributed Database System?

Yes, they can be executed simultaneously. One query is always independent of the
second query in a distributed database system based on the 2 phase commit.

47) Explain Raise_application_error.

It is a procedure of the package DBMS_STANDARD that allow issuing a user_defined


error messages from the database trigger or stored sub-program.

48) What is out parameter used for eventhough return statement can also be used
in pl/sql?

Out parameters allows more than one value in the calling program. Out parameter is
not recommended in functions. Procedures can be used instead of functions if
multiple values are required. Thus, these procedures are used to execute Out
parameters.

49) How would you convert date into Julian date format?

We can use the J format string :

SQL > select to_char(to_date(’29-Mar-2013′,’dd-mon-yyyy’),’J’) as julian from dual;

JULIAN

50) Explain SPOOL

Spool command can print the output of sql statements in a file.

spool/tmp/sql_outtxt

select smp_name, smp_id from smp where dept=’accounts’;


spool off;

51) Mention what PL/SQL package consists of?

A PL/SQL package consists of

 PL/SQL table and record TYPE statements


 Procedures and Functions
 Cursors
 Variables ( tables, scalars, records, etc.) and constants
 Exception names and pragmas for relating an error number with an exception
 Cursors

52) Mention what are the benefits of PL/SQL packages?

It provides several benefits like

 Enforced Information Hiding: It offers the liberty to choose whether to keep


data private or public
 Top-down design: You can design the interface to the code hidden in the
package before you actually implemented the modules themselves
 Object persistence: Objects declared in a package specification behaves like a
global data for all PL/SQL objects in the application. You can modify the
package in one module and then reference those changes to another module
 Object oriented design: The package gives developers strong hold over how
the modules and data structures inside the package can be used
 Guaranteeing transaction integrity: It provides a level of transaction integrity
 Performance improvement: The RDBMS automatically tracks the validity of all
program objects stored in the database and enhance the performance of
packages.

53) Mention what are different methods to trace the PL/SQL code?

Tracing code is a crucial technique to measure the code performance during the
runtime. Different methods for tracing includes

 DBMS_APPLICATION_INFO
 DBMS_TRACE
 DBMS_SESSION and DBMS_MONITOR
 trcsess and tkproof utilities
54) Mention what does the hierarchical profiler does?

The hierarchical profiler could profile the calls made in PL/SQL, apart from filling the
gap between the loopholes and the expectations of performance tracing. The
efficiencies of the hierarchical profiler includes

 Distinct reporting for SQL and PL/SQL time consumption


 Reports count of distinct sub-programs calls made in the PL/SQL, and the time
spent with each subprogram call
 Multiple interactive analytics reports in HTML format by using the command
line utility
 More effective than conventional profiler and other tracing utilities

55) Mention what does PLV msg allows you to do?

The PLV msg enables you to

 Assign individual text message to specified row in the PL/SQL table


 It retrieves the message text by number
 It substitutes automatically your own messages for standard Oracle error
messages with restrict toggle
 Batch load message numbers and text from a database table directly PLV msg
PL/SQL table

56) Mention what is the PLV (PL/Vision) package offers?

 Null substitution value


 Set of assertion routines
 Miscellaneous utilities
 Set of constants used throughout PL vision
 Pre-defined datatypes

57) Mention what is the use of PLVprs and PLVprsps?

 PLVprs: It is an extension for string parsing for PL/SQL, and it is the lowest
level of string parsing functionality
 PLVprsps: It is the highest level package to parse PL/SQL source code into
separate atomics. It relies on other parsing packages to get work done.
58) Explain how you can copy a file to file content and file to PL/SQL table in
advance PL/SQL?

With a single program call – “fcopy procedure”, you can copy the complete contents
of one file into another file. While to copy the contents of a file directly into a PL/SQL
table, you can use the program “file2pstab”.

59) Explain how exception handling is done in advance PL/SQL?

For exception handling PL/SQl provides an effective plugin PLVexc. PLVexc supports
four different exception handling actions.

 Continue processing
 Record and then continue
 Halt processing
 Record and then halt processing

For those exceptions that re-occurs you can use the RAISE statement.

60) Mention what problem one might face while writing log information to a data-
base table in PL/SQL?

While writing log information to a database table, the problem you face is that the
information is only available only once the new rows are committed to the database.
This might be a problem as such PLVlog is usually deployed to track errors and in
many such instances the current transaction would fail or otherwise needed a
rollback.

61) Mention what is the function that is used to transfer a PL/SQL table log to a
database table?

To transfer a PL/SQL table log a database log table function “PROCEDURE ps2db” is


used.

62) When you have to use a default “rollback to” savepoint of PLVlog?

The default “rollback to” savepoint of PLVlog is used when the users has turned on
the rollback activity and has not provided an alternative savepoint in the call to
put_line. The default savepoint is initialized to the c none constant.

63) Why PLVtab is considered as the easiest way to access the PL/SQL table?
The PL/SQL table are the closest to arrays in PL/SQL, and in order to access this table
you have to first declare a table type, and then you have to declare PL/SQL table
itself. But by using PLVtab, you can avoid defining your own PL/SQL table type and
make PL/SQL data-table access easy.

64) Mention what does PLVtab enables you to do when you showthe contents of
PL/SQL tables?

PLVtab enables you to do following things when you show the contents of PL/SQL
tables

 Display or suppress a header for the table


 Display or suppress the row numbers for the table values
 Show a prefix before each row of the table

65) Explain how can you save or place your msg in a table?

To save msg in a table, you can do it in two ways

 Load individual messages with calls to the add_text procedure


 Load sets of messages from a database table with
the load_from_dbms procedure

66) Mention what is the use of function “module procedure” in PL/SQL?

The “module procedure” enables to convert all the lines of code in a definite
program unit with one procedure call. There are three arguments for modules

 module_in
 cor_in
 Last_module_in

67) Mention what PLVcmt and PLVrb does in PL/SQL?

PL/Vision offers two packages that help you manage transaction processing in
PL/SQL application. It is PLVcmt and PLVrb.

 PLVcmt: PLVcmt package wraps logic and complexity for dealing with commit
processing
 PLVrb: It provides a programmatic interface to roll-back activity in PL/SQL

You might also like