DBMS interview1-merged-1
DBMS interview1-merged-1
Given below is a list of most popular Database interview questions and answers for your
reference.
Answer: Database is an organized collection of related data where the data is stored and
organized to serve some specific purpose.
For Example, A librarian maintain a database of all the information related to the books
that are available in the library.
Q #6) What are the various types of relationships in Database? Define them.
Answer: There are 3 types of relationships in Database:
One-to-one: One table has a relationship with another table having the similar kind
of column. Each primary key relates to only one or no record in the related table.
One-to-many: One table has a relationship with another table that has primary and
foreign key relations. The primary key table contains only one record that relates to
none, one or many records in the related table.
Many-to-many: Each record in both the tables can relate to many numbers of
records in another table.
Answer:
Normalization is the process of removing redundant data from the database by splitting
the table in a well-defined manner in order to maintain data integrity. This process saves
much of the storage space.
First Normal Form (1NF): A relation is said to be in 1NF only when all the entities of
the table contain unique or atomic values.
Second Normal Form (2NF): A relation is said to be in 2NF only if it is in 1NF and all
the non-key attribute of the table is fully dependent on the primary key.
Third Normal Form (3NF): A relation is said to be in 3NF only if it is in 2NF and every
non-key attribute of the table is not transitively dependent on the primary key.
Answer: BCNF is the Boyce Code Normal form. It is the higher version of 3Nf which does
not have any multiple overlapping candidate keys.
Answer: SQL statements are basically divided into three categories, DDL, DML, and DCL.
They can be defined as:
Data Definition Language (DDL) commands are used to define the structure that
holds the data. These commands are auto-committed i.e. changes done by the DDL
commands on the database are saved permanently.
Data Manipulation Language (DML) commands are used to manipulate the data of
the database. These commands are not auto-committed and can be rolled back.
Data Control Language (DCL) commands are used to control the visibility of the data
in the database like revoke access permission for using data in the database.
Answer: DML compiler translates DML statements in a query language into a low-level
instruction and the generated instruction can be understood by Query Evaluation Engine.
Answer: DDL Interpreter interprets the DDL statements and records the generated
statements in the table containing metadata.
Simple SQL queries can be used to retrieve a large amount of data from the
database very quickly and efficiently.
SQL is easy to learn and almost every DBMS supports SQL.
It is easier to manage the database using SQL as no large amount of coding is
required.
Q #16) Explain the terms ‘Record’, ‘Field’ and ‘Table’ in terms of database.
Answer:
Field: A field refers to an area within a record that is reserved for specific data. For
Example, Employee ID.
Table: Table is the collection of records of specific types. For Example, the Employee table
is a collection of records related to all the employees.
Q #17) What do you understand by Data Independence? What are its two types?
Answer: Data Independence refers to the ability to modify the schema definition in one
level in such a way that it does not affect the schema definition in the next higher level.
Physical Data Independence: It modifies the schema at the physical level without
affecting the schema at the conceptual level.
Logical Data Independence: It modifies the schema at the conceptual level without
affecting or causing changes in the schema at the view level.
Answer: View is a virtual table that does not have its data on its own rather the data is
defined from one or more underlying base tables.
Views account for logical data independence as the growth and restructuring of base
tables are not reflected in views.
Q #19) What are the advantages and disadvantages of views in the database?
As there is no physical location where the data in the view is stored, it generates
output without wasting resources.
Data access is restricted as it does not allow commands like insertion, updation, and
deletion.
Disadvantages of Views:
The view becomes irrelevant if we drop a table related to that view.
Much memory space is occupied when the view is created for large tables.
For Example, R is a Relation, X and Y are two attributes. T1 and T2 are two tuples. Then,
Answer: To fulfill the criteria of fully functional dependency, the relation must meet the
requirement of functional dependency.
A functional dependency ‘A’ and ‘B’ are said to be fully functional dependent when removal
of any attribute say ‘X’ from ‘A’ means the dependency does not hold anymore.
Answer: E-R model is an Entity-Relationship model which defines the conceptual view of
the database.
The E-R model basically shows the real-world entities and their association/relations.
Entities here represent the set of attributes in the database.
Answer:
Entity can be anything, be it a place, class or object which has an independent existence
in the real world.
Entity Set in the database represents a collection of entities having a particular entity
type.
Answer: Weak Entity set is the one whose primary key comprises its partial key as well as
the primary key of its parent entity. This is the case because the entity set may not have
sufficient attributes to form a primary key.
Answer:
Relation is a two-dimensional table containing a number of rows and columns where every
row represents a record of the relation. Here, rows are also known as ‘Tuples’ and columns
are known as ‘Attributes’.
Answer: VDL is View Definition Language which represents user views and their mapping to
the conceptual schema.
SDL is Storage Definition Language which specifies the mapping between two schemas.
Answer: Cursor is a temporary work area that stores the data, as well as the result set,
occurred after manipulation of data retrieved. A cursor can hold only one row at a time.
Implicit cursors are declared automatically when DML statements like INSERT,
UPDATE, DELETE is executed.
Explicit cursors have to be declared when SELECT statements that are returning
more than one row are executed.
Answer: Sequence of operation performed which changes the consistent state of the
database to another is known as the database transaction. After the completion of the
transaction, either the successful completion is reflected in the system or the transaction
fails and no change is reflected.
Answer: Database lock basically signifies the transaction about the current status of the
data item i.e. whether that data is being used by other transactions or not at the present
point of time.
There are two types of Database lock: Shared Lock and Exclusive Lock.
Q #30) What is Data Warehousing?
Answer: The storage as well as access to data, that is being derived from the transactions
and other sources, from a central location in order to perform the analysis is called Data
Warehousing.
Answer: Join is the process of deriving the relationship between different tables by
combining columns from one or more tables having common values in each. When a table
joins with itself, it is known as Self Join.
Answer: Index hunting is the process of boosting the collection of indexes which helps in
improving the query performance as well as the speed of the database.
Answer: Clustered index alters the table and re-order the way in which the records are
stored in the table. Data retrieval is made faster by using the clustered index.
A Non-clustered index does alter the records that are stored in the table but creates a
completely different object within the table.
Answer: Fragmentation is a feature that controls the logical data units, also known as
fragments that are stored at different sites of a distributed database system.
Answer: Given below are the types of Join, which are explained with respect to the tables
as an Example.
employee table:
employee_info table:
a) Inner JOIN: Inner JOIN is also known as a simple JOIN. This SQL query returns results
from both the tables having a common value in rows.
SQL Query:
Result:
b) Natural JOIN: This is a type of Inner JOIN that returns results from both the tables
having the same data values in the columns of both the tables to be joined.
SQL Query:
Result:
c) Cross JOIN: Cross JOIN returns the result as all the records where each row from the
first table is combined with each row of the second table.
SQL Query:
Result:
Let us do some modification in the above tables to understand Right JOIN, Left JOIN, and
Full JOIN.
employee table:
employee_info table:
a) Right JOIN: Right JOIN is also known as Right Outer JOIN. This returns all the rows as a
result from the right table even if the JOIN condition does not match any records in the
left table.
SQL Query:
Result:
b) Left JOIN: Left JOIN is also known as Left Outer JOIN. This returns all the rows as a
result of the left table even if the JOIN condition does not match any records in the right
table. This is exactly the opposite of Right JOIN.
SQL Query:
Result:
c) Outer/Full JOIN: Full JOIN return results in combining the result of both the Left JOIN
and Right JOIN.
SQL Query:
Result:
Answer: Atomicity is the condition where either all the actions of the transaction are
performed or none. This means, when there is an incomplete transaction, the database
management system itself will undo the effects done by the incomplete transaction.
Aggregation is the concept of expressing the relationship with the collection of entities
and their relationships.
Q #39) Define Phantom deadlock.
Answer: Phantom deadlock detection is the condition where the deadlock does not
actually exist but due to a delay in propagating local information, deadlock detection
algorithms identify the deadlocks.
Answer: Checkpoint declares a point before which all the logs are stored permanently in
the storage disk and is the inconsistent state. In the case of crashes, the amount of work
and time is saved as the system can restart from the checkpoint.
Answer: Database partitioning is the process of partitioning tables, indexes into smaller
pieces in order to manage and access the data at a finer level.
This process of partitioning reduces the cost of storing a large amount of data as well as
enhances the performance and manageability.
Answer: Data dictionary is a set of information describing the content and structure of the
tables and database objects. The job of the information stored in the data dictionary is to
control, manipulate and access the relationship between database elements.
Answer: Primary Key is that column of the table whose every row data is uniquely
identified. Every row in the table must have a primary key and no two rows can have the
same primary key. Primary key value can never be null nor can it be modified or updated.
Composite Key is a form of the candidate key where a set of columns will uniquely identify
every row in the table.
Answer: A Unique key is the same as the primary key whose every row data is uniquely
identified with a difference of null value i.e. Unique key allows one value as a NULL value.
Q #46) What do you understand by Database Triggers?
Answer: A set of commands that automatically get executed when an event like Before
Insert, After Insert, On Update, On Delete of row occurs in a table is called as Database
trigger.
Answer: B-Tree represents the data structure in the form of a tree for external memory
that reads and writes large blocks of data. It is commonly used in databases and file
systems where all the insertions, deletions, sorting, etc., are done in logarithmic time.
Q #49) Name the different data models that are available for database systems.
Relational model
Network model
Hierarchical model
Answer: After the execution of ‘DELETE’ operation, COMMIT and ROLLBACK statements
can be performed to retrieve the lost data.
After the execution of ‘TRUNCATE’ operation, COMMIT, and ROLLBACK statements cannot
be performed to retrieve the lost data.
‘DROP’ command is used to drop the table or key like the primary key/foreign key.
Employee table
a) Write the SELECT command to display the details of the employee with empid as 1004.
SQL Query:
SELECT empId, empName, Age, Address from Employee WHERE empId = 1004;
Result:
b) Write the SELECT command to display all the records of table Employees.
SQL Query:
Result:
c) Write the SELECT command to display all the records of the employee whose name
starts with the character ‘R’.
SQL Query:
Result:
d) Write a SELECT command to display id, age and name of the employees with their age
in both ascending and descending order.
SQL Query:
Result:
SELECT empId, empName, Age from Employee ORDER BY Age Desc;
Result:
e) Write the SELECT command to calculate the total amount of salary on each employee
from the below Emp table.
Emp table:
SQL Query:
Result:
Conclusion
These are the set of Database interview questions and answers which are mostly asked in
the interview.
Mostly the basics of every subject are questioned in the interviews. It is a well-known fact
to everyone that, if your basics are clear, you can reach top heights.
However, there may be some more tricky questions. Just be confident and face each
question with clarity in your subject knowledge.
Are you preparing for your sql developer interview?
This guide will help you to brush up your SQL skills, regain your confidence and be job
ready!
In this guide you will find a collection of real world SQL interview questions asked in
companies like Google, Oracle, Amazon and Microsoft etc. Each question comes with a
perfectly written answer inline, saving your interview preparation time.
This guide also contains some sql practice problems which you can solve right away
which is simply the fastest and easiest way for clearing your basic concepts of SQL.
1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a remote or local
computer system. Databases can be vast and complex, and such databases are developed using fixed
design and modeling approaches.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system software responsible for the
creation, retrieval, updation and management of the database. It ensures that our data is consistent,
organized and is easily accessible by serving as an interface between the database and its end users
or application softwares.
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.
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)
);
Q => Write a SQL statement to add PRIMARY KEY 't_id' to the table 'teachers'. +
Q => Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a' and fields
'col_b, col_c'. +
Q => What type of integrity constraint does the foreign key ensure? +
Q => Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references
'col_pk' in 'table_x'. +
(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;
Q => Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1' and
'Table_2', on columns 'Col_1' and 'Col_2' respectively. +
There are different types of indexes that can be created for different purposes:
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.
The only difference between clustered and non-clustered indexes is that the database manager
attempts to keep the data in the database in the same order as the corresponding keys appear in the
clustered index.
Clustering index can improve the performance of most query operations because they provide a linear-
access path to data stored in the database.
Q => Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for fields
"column_1" & "column_2". +
1. Clustered index modifies the way records are stored in a database based on the indexed column.
Non-clustered index creates a separate entity within the table which references the original table.
2. Clustered index is used for easy and speedy retrieval of data from the database, whereas, fetching
records from the non-clustered index is relatively slower.
3. In SQL, a table can have a single clustered index whereas it can have multiple non-clustered
indexes.
A correlated subquery cannot be considered as an independent query, but it can refer the column in
a table listed in the FROM of the main query.
A non-correlated subquery can be considered as an independent query and the output of subquery
is substituted in the main query.
Q => Write a SQL query to update the field "status" in table "applications" from 0 to 1. +
Q => Write a SQL query to select the field "app_id" in table "applications" where "app_id"
less than 1000. +
Q => Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is equal
to the above collection of "app_id". +
WHERE clause in SQL is used to filter records that are necessary, based on specific conditions.
ORDER BY clause in SQL is used to sort the records based on some field(s) in ascending (ASC) or
descending order (DESC).
SELECT *
FROM myDB.students
WHERE graduation_year = 2019
ORDER BY studentID DESC;
GROUP BY clause in SQL is used to group records with identical data and can be used in
conjuction with some aggregation functions to produce summarized results from the database.
HAVING clause in SQL is used to filter records in combination with the GROUP BY clause. It is
different from WHERE, since WHERE clause cannot filter aggregated records.
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 with duplicates*/
UNION ALL
SELECT name FROM Contacts;
Q => Write a SQL query to fetch "names" that are present in either table "accounts" or in
table "registry". +
Q => Write a SQL query to fetch "names" that are present in "accounts" but not in table
"registry". +
Q => Write a SQL query to fetch "names" from table "contacts" that are neither present in
"accounts.name" nor in "registry.name". +
Relationships: Relations or links between entities that have something to do with each other. For
example - The employees table in a company's database can be associated with the salary table in the
same database.
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.
Q => Write an SQL statement to select all from table "Limited" with alias "Ltd". +
Students Table
As we can observe, the Books Issued field has more than one values per record and to convert it into
1NF, this has to be resolved into separate individual records for each book issued. Check the following
table in 1NF form -
Example 1 - Consider the above example. As we can observe, Students Table in 1NF form has a
candidate key in the form of [Student, Address] that can uniquely identify all records in the table. The
field Books Issued (non-prime attribute) depends partially on the Student field. Hence, the table is not in
2NF. To convert it into 2nd Normal Form, we will partition the tables into two while specifying a new
Primary Key attribute to identify the individual records in the Students table. The Foreign Key constraint
will be set on the other table to ensure referential integrity.
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.
Example 1 - Consider the Students Table in the above example. As we can observe, Students Table
in 2NF form has a single candidate key Student_ID (primary key) that can uniquely identify all records
in the table. The field Salutation (non-prime attribute), however, depends on the Student Field rather
than the candidate key. Hence, the table is not in 3NF. To convert it into 3rd Normal Form, we will once
again partition the tables into two while specifying a new Foreign Key constraint to identify the
salutations for individual records in the Students table. The Primary Key constraint for the same will be
set on the Salutations table to identify each record uniquely.
Salutation_ID Salutation
1 Ms.
2 Mr.
3 Mrs.
For the above relation to exist in 3NF, all possible candidate keys in above relation should be {P, RS,
QR, T}.
TRUNCATE command is used to delete all the rows from the table and free the space containing the table.
DROP command is used to remove an object from the database. If you drop a table, all the rows in the table
is deleted and the table structure is removed from the database.
DROP TABLE Candidates;
Q => Write a SQL query to remove first 1000 records from table 'Temporary' based on 'id'. +
Q => Write a SQL statement to delete the table 'Temporary' while keeping its relations intact.
+
Scalar Function: As explained earlier, user-defined scalar functions return a single scalar value.
Table Valued Functions: User-defined table-valued functions return a table as output.
Inline: returns a table data type based on a single SELECT statement.
Multi-statement: returns a tabular result-set but, unlike inline, multiple SELECT statements can be
used inside the function body.
OLAP stands for Online Analytical Processing, a class of software programs which are characterized
by relatively low frequency of online transactions. Queries are often too complex and involve a bunch of
aggregations. For OLAP systems, the effectiveness measure relies highly on response time. Such
systems are widely used for data mining or maintaining aggregated, historical data, usually in multi-
dimensional schemas.
37. What is Collation? What are the different types of
Collation Sensitivity?
Collation refers to a set of rules that determine how data is sorted and compared. Rules defining the
correct character sequence are used to sort the character data. It incorporates options for specifying
case-sensitivity, accent marks, kana character types and character width. Below are the different types
of collation sensitivity:
DELIMITER $$
CREATE PROCEDURE FetchAllStudents()
BEGIN
SELECT * FROM myDB.students;
END $$
DELIMITER ;
39. What is a Recursive Stored Procedure?
A stored procedure which calls itself until a boundary condition is reached, is called a recursive stored
procedure. This recursive function helps the programmers to deploy the same set of code several times
as and when required. Some SQL programming languages limit the recursion depth to prevent an
infinite loop of procedure calls from causing a stack overflow, which slows down the system and may
lead to system crashes.
SELECT *
FROM students
WHERE first_name LIKE 'K%'
SELECT *
FROM students
WHERE first_name NOT LIKE 'K%'
SELECT *
FROM students
WHERE first_name LIKE '%Q%'
SELECT *
FROM students
WHERE first_name LIKE '__K%'
A table in SQL must have a primary key associated with it to uniquely identify its
records.
Primary key may or may not be unique but can be comprised of multiple fields.
Foreign Key uniquely identifies all the records in the referenced table.
Foreign key may or may not be unique but can be comprised of multiple fields.
Q - What is a Query?
A SELECT or UPDATE statement in SQL.
MODIFY
UPDATE
ALTER TABLE
SAVE AS
Sorts the result set in descending order using the DESC keyword.
It does not require additonal memory and allows for speedy retrieval of records.
Q - An SQL query to delete a table from the database and memory while keeping
the structure of the table intact?
SELF JOIN
INNER JOIN
VIEW
NONE
Q #1) What is SQL?
Answer: Structured Query Language SQL is a database tool that is used to create and
access the database to support software applications.
Answer: The table is a collection of record and its information at a single view.
Answer:
a) DDL (Data Definition Language): It is used to define the database structure such as
tables. It includes three statements such as CREATE, ALTER, and DROP.
ALTER: The ALTER table is used for modifying the existing table object in the database.
OR
b) DML (Data Manipulation Language): These statements are used to manipulate the data
in records. Commonly used DML statements are INSERT, UPDATE, and DELETE.
The SELECT statement is used as a partial DML statement, used to select all or relevant
records in the table.
c) DCL (Data Control Language): These statements are used to set privileges such as
GRANT and REVOKE database access permission to the specific user.
Answer: The DISTINCT statement is used with the SELECT statement. If the record
contains duplicate values then the DISTINCT statement is used to select different values
among duplicate records.
Syntax:
Answer:
WHERE Clause: This clause is used to define the condition, extract and display only those
records which fulfill the given condition.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition;
GROUP BY Clause: It is used with SELECT statement to group the result of the executed
query using the value specified in it. It matches the value with the column name in tables
and groups the end result accordingly.
Further reading => MySQL Group By Tutorial
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name;
HAVING clause: This clause is used in association with the GROUP BY clause. It is applied
to each group of results or the entire result as a single group. It is much similar as WHERE
clause but the only difference is you cannot use it without GROUP BY clause
Syntax:
SELECT column_name(s)
FROM table_name
GROUP BY column_name
HAVING condition;
ORDER BY clause: This clause is used to define the order of the query output either in
ascending (ASC) or in descending (DESC). Ascending (ASC) is set as the default one but
descending (DESC) is set explicitly.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;
USING clause: USING clause comes in use while working with SQL JOIN. It is used to check
equality based on columns when tables are joined. It can be used instead of the ON clause
in JOIN.
Syntax:
SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);
Q #6) Why do we use SQL constraints? Which constraints we can use while creating a
database in SQL?
Answer: Constraints are used to set the rules for all records in the table. If any constraints
get violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.
Answer:
4 major types of Joins are used while working on multiple tables in SQL databases:
INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one matching column.
Syntax:
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON column_name1=column_name2;
For Example,
The second table’s name is Joining.
Enter the following SQL statement:
LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its
matched rows from a RIGHT table.
Syntax:
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON column_name1=column_name2;
For Example,
There will be 4 records selected. You will see the following results:
RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table and its
matched rows from the LEFT table.
Syntax:
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON column_name1=column_name2;
For Example,
Output:
Emp_id Joining_Date
E0012 2016/04/18
E0013 2016/04/19
E0014 2016/05/01
FULL JOIN (FULL OUTER JOIN): This joins returns all results when there is a match either
in the RIGHT table or in the LEFT table.
Syntax:
SELECT column_name(s)
FROM table_name1
FULL OUTER JOIN table_name2
ON column_name1=column_name2;
For Example,
Enter the following SQL statement:
There will be 8 records selected. These are the results that you should see.
In simple words, we can say that a transaction means a group of SQL queries executed on
database records.
Answer: Properties of the transaction are known as ACID properties. These are:
Answer: SQL Aggregate functions determine and calculate values from multiple columns in
a table and return a single value.
Answer: Scalar functions are used to return a single value based on the input values.
Action and Event are two main components of SQL triggers. When certain actions are
performed, the event occurs in response to that action.
Syntax:
Answer: A View can be defined as a virtual table that contains rows and columns with
fields from one or more tables.
Syntax:
Answer: SQL CREATE and REPLACE can be used for updating the view.
Syntax:
Answer: SQL GRANT and REVOKE commands are used to implement privileges in SQL
multiple user environments. The administrator of the database can grant or revoke
privileges to or from users of database objects by using commands like SELECT, INSERT,
UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to users other than
the administrator.
Syntax:
GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];
In the above syntax, the GRANT option indicates that the user can grant access to another
user too.
REVOKE command: This command is used to provide database deny or remove access to
database objects.
Syntax:
REVOKE privilege_name
ON object_name
FROM {user_name|PUBLIC|role_name};
System privilege: System privilege deals with the object of a particular type and
provides users the right to perform one or more actions on it. These actions include
performing administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP
CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
Object privilege: This allows to perform actions on an object or object of another
user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE,
INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
Answer: SQL Injection is a type of database attack technique where malicious SQL
statements are inserted into an entry field of database in a way that once it is executed,
the database is exposed to an attacker for the attack. This technique is usually used for
attacking data-driven applications to have access to sensitive data and perform
administrative tasks on databases.
For Example,
Answer: SQL Sandbox is a safe place in the SQL server environment where untrusted
scripts are executed. There are 3 types of SQL sandbox:
Safe Access Sandbox: Here a user can perform SQL operations such as creating
stored procedures, triggers etc. but cannot have access to the memory as well as
cannot create files.
External Access Sandbox: Users can access files without having the right to
manipulate the memory allocation.
Unsafe Access Sandbox: This contains untrusted codes where a user can have
access to memory.
Answer: SQL is a Structured Query Language to create and access databases whereas
PL/SQL comes with procedural concepts of programming languages.
Answer: SQL is a Structured Query Language that is used for manipulating and accessing
the relational database. On the other hand, MySQL itself is a relational database that uses
SQL as the standard database language.
Answer: NVL function is used to convert the null value to its actual value.
Answer: The output of Cross Join is called a Cartesian product. It returns rows combining
each row from the first table with each row of the second table. For Example, if we join
two tables having 15 and 20 columns the Cartesian product of two tables will be
15×20=300 rows.
Answer: Query within another query is called as Subquery. A subquery is called inner query
which returns output that is to be used by another query.
Q #24) How many row comparison operators are used while working with a subquery?
Answer: There are 3-row comparison operators that are used in subqueries such as IN,
ANY and ALL.
One table can have only one clustered index but multiple non-clustered indexes.
Clustered indexes can be read rapidly rather than non-clustered indexes.
Clustered indexes store data physically in the table or view whereas, non-clustered
indexes do not store data in the table as it has separate structure from the data row.
Answer: The differences are:
The basic difference in both is DELETE command is DML command and the
TRUNCATE command is DDL.
DELETE command is used to delete a specific row from the table whereas the
TRUNCATE command is used to remove all rows from the table.
We can use the DELETE command with WHERE clause but cannot use the
TRUNCATE command with it.
Answer: TRUNCATE removes all rows from the table which cannot be retrieved back, DROP
removes the entire table from the database and it also cannot be retrieved back.
Q #28) How to write a query to show the details of a student from Students table whose
name start with K?
Answer: Query:
Q #29) What is the difference between Nested Subquery and Correlated Subquery?
Answer: Subquery within another subquery is called Nested Subquery. If the output of a
subquery depends on column values of the parent query table then the query is called
Correlated Subquery.
The result of the query is the details of an employee from the Employee table.
Answer: Normalization is used to organize the data in such a manner that data redundancy
will never occur in the database and avoid insert, update and delete anomalies.
First Normal Form (1NF): It removes all duplicate columns from the table. It creates
a table for related data and identifies unique column values.
First Normal Form (2NF): Follows 1NF and creates and places data subsets in an
individual table and defines the relationship between tables using the primary key.
Third Normal Form (3NF): Follows 2NF and removes those columns which are not
related through the primary key.
Fourth Normal Form (4NF): Follows 3NF and does not define multi-valued
dependencies. 4NF is also known as BCNF.
Q #31) What is a Relationship? How many types of Relationships are there?
Answer: The relationship can be defined as the connection between more than one table
in the database.
Syntax:
Answer: Triggers may implement data modification logic by using INSERT, UPDATE, and
DELETE statements. These triggers that contain data modification logic and find other
triggers for data modification are called Nested Triggers.
Answer: Collation is a set of rules that check how the data is sorted by comparing it. Such
as character data is stored using correct character sequence along with case sensitivity,
type, and accent.
Database connectivity
Constraint check
Required application field and its size
Data Retrieval and processing with DML operations
Stored Procedures
Functional flow
Data Mapping
Data stored and retrieved
Use of Black Box testing techniques such as Equivalence Partitioning and Boundary
Value Analysis (BVA)
Answer: The index can be defined as the way to retrieve the data more quickly. We can
define indexes using CREATE statements.
Syntax:
Further, we can also create a Unique Index using the following syntax:
Answer: To select all the records from the table we need to use the following syntax:
Answer: Join keyword is used to fetch data from two or more related tables. It returns
rows where there is at least one match in both the tables included in the join. Read more
here.
Type of joins are:
1. Right join
2. Outer join
3. Full join
4. Cross join
5. Self join.
For Example,
Answer: To add another column in the table, use the following command:
ALTER TABLE table_name ADD (column_name);
Recommended reading =>> How to add a column to a table in MySQL
Answer: DELETE is used to delete a row or rows from a table based on the specified
condition.
The basic syntax is as follows:
Answer: A Primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused.
Answer: When a table’s primary key field is added to related tables in order to create the
common field which relates the two tables, it called a foreign key in other tables. Foreign
key constraints enforce referential integrity.
Answer: A CHECK constraint is used to limit the values or type of data that can be stored
in a column. They are used to enforce domain integrity.
Q #51) Is it possible for a table to have more than one foreign key?
Answer: Yes, a table can have many foreign keys but only one primary key.
Q #52) What are the possible values for the BOOLEAN data field?
Answer: For a BOOLEAN data field, two values are possible: -1(true) and 0(false).
Answer: A stored procedure is a set of SQL queries that can take input and send back
output.
Answer: An identity column in where SQL automatically generates numeric values. We can
define a start and increment value of the identity column.
Q #55) What is Normalization?
Answer: The process of table design to minimize the data redundancy is called
normalization. We need to divide a database into two or more table and define the
relationship between them.
Answer: The Trigger allows us to execute a batch of SQL code when table event occurs
(INSERT, UPDATE or DELETE commands are executed against a specific table).
For Example,
Q #59) Write a SQL SELECT query that only returns each name only once from a table?
Answer: To get the result as each name only once, we need to use the DISTINCT keyword.
Answer: DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are
DML statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL
statements.
Answer: Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY, HAVING,
ORDER BY. Only the SELECT and FROM clauses are mandatory.
Q #63) Suppose a Student column has two columns, Name and Marks. How to get names
and marks of the top three students.
Answer: SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM
Students s2 WHERE s1.marks = s2.marks)
Answer: SQL comments can be inserted by adding two consecutive hyphens (–).
Answer:
DELETE removes some or all rows from a table based on the condition. It can be
rolled back.
TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The
operation cannot be rolled back
DROP command removes a table from the database completely.
Answer: Generally, these properties are referred to as ACID properties. They are:
1. Atomicity
2. Consistency
3. Isolation
4. Durability.
Answer: It’s an 18 character long pseudo column attached with each row of a table.
Answer:
MINUS – returns all distinct rows selected by the first query but not by the second.
UNION – returns all distinct rows selected by either query
UNION ALL – returns all rows selected by either query, including all duplicates.
INTERSECT – returns all distinct rows selected by both queries.
Answer: A transaction is a sequence of code that runs against a database. It takes the
database from one consistent state to another.
Q #70) What is the difference between UNIQUE and PRIMARY KEY constraints?
Answer: The differences are as follows:
A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys.
The primary key cannot contain Null values whereas the Unique key can contain Null
values.
Answer: The primary key created on more than one column is called composite primary
key.
Answer: A Subquery is a subset of select statements whose return values are used in
filtering conditions of the main query.
Answer: Set of rules that define how data is stored, how case-sensitivity and Kana
character can be treated etc.
Answer: Set of rules that restrict the values of one or more columns of the tables based
on the values of the primary key or unique key of the referenced table.
Answer: Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions
and returns one of the multiple possible result expressions.
Answer: A temp table is a temporary storage structure to store the data temporarily.
Answer: By using the DISTINCT keyword, duplication of records in a query can be avoided.
Q #80) Explain the difference between Rename and Alias?
Answer: A view is a virtual table that contains data from one or more tables. Views restrict
data access of the table by selecting only required values and make complex queries easy.
Views restrict access to the data because the view can display selective columns
from the table.
Views can be used to make simple queries to retrieve the results of complicated
queries. For Example, views can be used to query information from multiple tables
without the user knowing.
Q #83) List the various privileges that a user can grant to another user?
Answer: A table is the basic unit of data storage in the database management system.
Table data is stored in rows and columns.
Q #88) What is the difference between the HAVING clause and WHERE clause?
Answer: Both specify a search condition but Having clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaved like WHERE clause only.
Q #89) What is the difference between Local and Global temporary tables?
Answer: If defined inside a compound statement a local temporary table exists only for the
duration of that statement but a global temporary table exists permanently in the DB but
its rows disappear when the connection is closed.
Conclusion
SQL is an essential component of the database system. Having well-versed knowledge of
database along with SQL concepts will definitely be beneficial to crack the interview for
the concerned profile.
Apart from some major concepts, there are some hidden facts that remain unseen and
affect your performance in the interview. In this tutorial, I have tried to recollect some of
those concepts which seem small but should not be neglected.
Hope in this article, you will find answers to most frequently asked SQL interview
questions. The knowledge of SQL is a must for any tester and this article will help you in
preparing the interview.
Recommended Reading
Interview Questions and Answers
Top Oracle Interview Questions: Oracle Basic, SQL, PL/SQL Questions
30 Most Important PL/SQL Interview Questions and Answers In 2021
ETL Testing Interview Questions and Answers
Top Teradata Interview Questions and Answers
Some Tricky Manual Testing Questions & Answers
25 Best Agile Testing Interview Questions and Answers
Spock Interview Questions with Answers (Most Popular)
About SoftwareTestingHelp
Helping our community since 2006! Most popular portal for Software professionals
with 100 million+ visits and 300,000+ followers! You will absolutely love our
tutorials on QA Testing, Development, Software Tools and Services Reviews and
more!