SQL Interview Questions and Answers
SQL Interview Questions and Answers
1) What is SQL?
SQL stands for the Structured Query Language. It is the standard language used to maintain the
relational database and perform many different data manipulation operations on the data. SQL
was initially invented in 1970. It is a database language used for database creation, deletion,
fetching and modifying rows, etc. sometimes, it is pronounced as 'sequel.' We can also use it to
handle organized data comprised of entities (variables) and relations between different entities of
the data.
Example
1. CREATE TABLE Students
2. (
3. Roll_no INT,
4. Name VARCHAR(45),
5. Branch VARCHAR(30),
6. );
Example
1. INSERT INTO Student VALUES (111, 'George', 'Computer Science')
GRANT: It enables system administrators to assign privileges and roles to the specific user
accounts to perform specific tasks on the database.
REVOKE: It enables system administrators to revoke privileges and roles from the user accounts so
that they cannot use the previously assigned permission on the database.
Example
1. GRANT * ON mydb.Student TO javatpoint@localhsot;
Fields are the components to provide the structure for the table. It stores the same category of
data in the same data type. A table contains a fixed number of columns but can have any number
of rows known as the record. It is also called a column in the table of the database. It represents
the attribute or characteristics of the entity in the record.
Example
Table: Student
13) What is the difference between a primary key and a unique key?
The primary key and unique key both are essential constraints of the SQL. The main difference
among them is that the primary key identifies each record in the table. In contrast, the unique key
prevents duplicate entries in a column except for a NULL value. The following comparison chart
explains it more clearly:
The primary key act as a unique The unique key is also a unique identifier for records
identifier for each record in the table. when the primary key is not present in the table.
We cannot store NULL values in the We can store NULL value in the unique key column,
primary key column. but only one NULL is allowed.
We cannot change or delete the We can modify the unique key column values.
primary key column values.
There are some rules of database normalization, which is commonly known as Normal From, and
they are:
o First normal form(1NF)
o Second normal form(2NF)
o Third normal form(3NF)
o Boyce-Codd normal form(BCNF)
Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be
removed.
The occurrence of redundant terms in the database causes the waste of space in the disk.
Due to redundant terms, inconsistency may also occur. If any change is made in the data of one
table but not made in the same data of another table, then inconsistency will occur. This
inconsistency will lead to the maintenance problem and effects the ACID properties as well.
Denormalization doesn't mean that normalization will not be done. It is an optimization strategy
that takes place after the normalization process.
23) What are the different types of SQL operators?
Operators are the special keywords or special characters reserved for performing particular
operations. They are also used in SQL queries. We can primarily use these operators within the
WHERE clause of SQL commands. It's a part of the command to filters data based on the specified
condition. The SQL operators can be categorized into the following types:
o Arithmetic operators: These operators are used to perform mathematical operations on
numerical data. The categories of this operators are addition (+), subtraction (-),
multiplication (*), division (/), remainder/modulus (%), etc.
o Logical operators: These operators evaluate the expressions and return their results in True
or False. This operator includes ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT,
OR, UNIQUE.
o Comparison operators: These operators are used to perform comparisons of two values
and check whether they are the same or not. It includes equal to (=), not equal to (!= or
<>), less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=),
not less than (!<), not greater than (!>), etc.
o Bitwise operators: It is used to do bit manipulations between two expressions of integer
type. It first performs conversion of integers into binary bits and then applied operators
such as AND (& symbol), OR (|, ^), NOT (~), etc.
o Compound operators: These operators perform operations on a variable before setting the
variable's result to the operation's result. It includes Add equals (+=), subtract equals (-=),
multiply equals (*=), divide equals (/=), modulo equals (%=), etc.
o String operators: These operators are primarily used to perform concatenation and pattern
matching of strings. It includes + (String concatenation), += (String concatenation
assignment), % (Wildcard), [] (Character(s) matches), [^] (Character(s) not to match), _
(Wildcard match one character), etc.
For example: Suppose we have a book which carries the details of the countries. If you want to
find out information about India, why will you go through every page of that book? You could
directly go to the index. Then from the index, you can go to that particular page where all the
information about India is given.
Example
1. CREATE TABLE Employee(
2. ID int AUTO_INCREMENT PRIMARY KEY,
3. Name varchar(45),
4. Phone varchar(15),
5. City varchar(25),
6. );
Suppose we want to make a Phone column as a unique index. We can do this like below:
1. CREATE UNIQUE INDEX index_name_phone ON Employee (Phone);
The purpose of creating a non-clustered index is for searching the data. Its best example is a book
where the content is written in one place, and the index is at a different place. We can create 0 to
249 non-clustered indexes in each table. The non-clustered indexing improves the performance of
the queries which use keys without assigning the primary key.
30) What are the differences between SQL, MySQL, and SQL Server?
The following comparison chart explains their main differences:
SQL or Structured Query MySQL is the popular database SQL Server is an RDBMS
Language is useful for management system used for database system mainly
managing our relational managing the relational developed for the Windows
databases. It is used to query database. It is a fast, scalable, system to store, retrieve, and
and operate the database. and easy-to-use database. access data requested by the
developer.
SQL first appeared in 1974. MySQL first appeared on May SQL Server first appeared on
23, 1995. April 24, 1989.
SQL was developed by IBM MySQL was developed by SQL Server was developed by
Corporation. Oracle Corporation. Microsoft Company.
SQL is a query language for MySQL is database software SQL Server is also a software
managing databases. that uses SQL language to that uses SQL language to
conduct with the database. conduct with the database.
SQL has no variables. MySQL can use variables SQL Server can use variables
constraints and data types. constraints and data types.
SQL PL/SQL
SQL has no variables. PL/SQL can use variables constraints and data types.
SQL can execute only a single query at PL/SQL can execute a whole block of code at once.
a time.
SQL query can be embedded in PL/SQL. PL/SQL cannot be embedded in SQL as SQL does not
support any programming language and keywords.
SQL can directly interact with the PL/SQL cannot directly interact with the database
database server. server.
SQL is like the source of data that we PL/SQL provides a platform where SQL data will be
need to display. shown.
A clustered index is a table or view where the The indexes other than PRIMARY indexes
data for the rows are stored. In a relational (clustered indexes) are called non-clustered
database, if the table column contains a indexes. It has a structure separate from the
primary key, MySQL automatically creates a data row. The non-clustered indexes are
clustered index named PRIMARY. also known as secondary indexes.
Clustered indexes store the data information Non-clustered indexes stores only the
and the data itself. information, and then it will refer you to the
data stored in clustered data.
There can only be one clustered index per There can be one or more non-clustered
table. indexes in a table.
A clustered index determines how data is It creates a logical ordering of data rows
stored physically in the table. Therefore, and uses pointers for accessing the physical
reading from a clustered index is faster. data files. Therefore, reading from a
clustered index is slower.
35) Which are joins in SQL? Name the most commonly used SQL joins?
SQL joins are used to retrieve data from multiple tables into a meaningful result set. It is performed
whenever you need to fetch records from two or more tables. They are used with SELECT
statement and join conditions.
SQL triggers have two main components one is action, and another is an event. When certain
actions are taken, an event occurs as a result of those actions.
We use the CREATE TRIGGER statement for creating a trigger in SQL. Here is the syntax:
1. CREATE TRIGGER trigger_name
2. (AFTER | BEFORE) (INSERT | UPDATE | DELETE)
3. ON table_name FOR EACH ROW
4. BEGIN
5. --variable declarations
6. --trigger code
7. END;
A SELF JOIN is required when we want to combine data with other data in the same table itself. It is
often very useful to convert a hierarchical structure to a flat structure.
Example
A. UNION: It combines two or more results from multiple SELECT queries into a single result set. It
has a default feature to remove the duplicate rows from the tables. The following syntax illustrates
the Union operator:
1. SELECT columns FROM table1
2. UNION
3. SELECT columns FROM table2;
B. UNION ALL: This operator is similar to the Union operator, but it does not remove the duplicate
rows from the output of the SELECT statements. The following syntax illustrates the UNION ALL
operator:
1. SELECT columns FROM table1
2. UNION ALL
3. SELECT columns FROM table2;
C. INTERSECT: This operator returns the common records from two or more SELECT statements. It
always retrieves unique records and arranges them in ascending order by default. Here, the
number of columns and data types should be the same. The following syntax illustrates the
INTERSECT operator:
1. SELECT columns FROM table1
2. INTERSECT
3. SELECT columns FROM table2;
D. MINUS: This operator returns the records from the first query, which is not found in the second
query. It does not return duplicate values. The following syntax illustrates the MINUS operator:
1. SELECT columns FROM table1
2. MINUS
3. SELECT columns FROM table2;
This operator is used to selects the It is a logical operator to determine whether or not
range of data between two values. The a specific value exists within a set of values. This
values can be numbers, text, and dates operator reduces the use of multiple OR conditions
as well. with the query.
It returns records whose column value It compares the specified column's value and
lies in between the defined range. returns the records when the match exists in the
set of values.
The following syntax illustrates this The following syntax illustrates this operator:
operator: SELECT * FROM table_name
SELECT * FROM table_name WHERE column_name IN ('value1','value 2');
WHERE column_name BETWEEN
'value1' AND 'value2';
Column Level Constraints: These constraints are only applied to a single column and limit the
type of data that can be stored in that column.
Table Level Constraints: These constraints are applied to the entire table and limit the type of
data that can be entered.
46) How to write an SQL query to find students' names start with 'A'?
We can write the following query to get the student details whose name starts with A:
1. SELECT * FROM student WHERE stud_name like 'A%';
Here is the demo example where we have a table named student that contains two names starting
with the 'A' character.
47) Write the SQL query to get the third maximum salary of an employee
from a table named employees.
The following query is the simplest way to get the third maximum salary of an employee:
1. SELECT * FROM `employees` ORDER BY `salary` DESC LIMIT 1 OFFSET 2
Here is the demo example that shows how to get the third maximum salary of an employee.
The following are the alternative way to get the third-highest salary of an employee:
B. Using Subquery
1. SELECT salary
2. FROM
3. (SELECT salary
4. FROM employees
5. ORDER BY salary DESC
6. LIMIT 3) AS Temp
7. ORDER BY salary LIMIT 1;
1) The delete statement removes single or The truncate command deletes the whole
multiple rows from an existing table contents of an existing table without the
depending on the specified condition. table itself. It preserves the table structure or
schema.
3) We can use the WHERE clause in the We cannot use the WHERE clause with
DELETE command. TRUNCATE.
6) You can roll back data after using the It is not possible to roll back after using
DELETE statement. the TRUNCATE statement.
7) DELETE query takes more space. TRUNCATE query occupies less space.
The ACID property is an acronym for Atomicity, Consistency, Isolation, and Durability.
Atomicity: It ensures that all statements or operations within the transaction unit must be
executed successfully. If one part of the transaction fails, the entire transaction fails, and the
database state is left unchanged. Its main features are COMMIT, ROLLBACK, and AUTO-COMMIT.
Consistency: This property ensures that the data must meet all validation rules. In simple words,
we can say that the database changes state only when a transaction will be committed
successfully. It also protects data from crashes.
Isolation: This property guarantees that the concurrent property of execution in the transaction
unit must be operated independently. It also ensures that statements are transparent to each
other. The main goal of providing isolation is to control concurrency in a database.
Durability: This property guarantees that once a transaction has been committed, it persists
permanently even if the system crashes, power loss, or failed.
LOWER: This function is used to converts a given character into lowercase. The following example
will return the 'STEPHEN' as 'stephen':
1. SELECT LOWER ('STEPHEN') AS Case_Reault FROM dual;
UPPER: This function is used to converts a given character into uppercase. The following example
will return the 'stephen' as 'STEPHEN':
1. SELECT UPPER ('stephen') AS Case_Reault FROM dual;
INITCAP: This function is used to converts given character values to uppercase for the initials of
each word. It means every first letter of the word is converted into uppercase, and the rest is in
lower case. The following example will return the 'hello stephen' as 'Hello Stephen':
1. SELECT INITCAP ('hello stephen') AS Case_Reault FROM dual;
A) CONCAT: This function is used to join two or more values together. It always appends the
second string into the end of the first string. For example:
Output: Information-technology
B) SUBSTR: It is used to return the portion of the string from a specified start point to an
endpoint. For example:
Output: Management
C) LENGTH: This function returns the string's length in numerical value, including the blank
spaces. For example:
Output: 16
D) INSTR: This function finds the exact numeric position of a specified character or word in a given
string. For example:
Output: 7
E) LPAD: It returns the padding of the left-side character value for right-justified value. For
example:
Output: ***200
F) RPAD: It returns the padding of the right-side character value for left-justified value. For
example:
Output: 200***
G) TRIM: This function is used to remove all the defined characters from the beginning, end, or
both. It also trimmed extra spaces. For example:
Output: BCDCB
H) REPLACE: This function is used to replace all occurrences of a word or portion of the string
(substring) with the other specified string value. For example:
Input: SELECT REPLACE ( 'It is the best coffee at the famous coffee shop.', 'coffee', 'tea');
56) What are the syntax and use of the COALESCE function?
The COALESCE() function evaluates the arguments in sequence and returns the first NON-NULL
value in a specified number of expressions. If it evaluates arguments as NULL or not found any
NON-NULL value, it returns the NULL result.
Example:
1. SELECT COALESCE(NULL, 'Hello', 'Javatpoint', NULL) AS Result;
Suppose we have a table 'customer' containing eight records in which the name column has some
duplicate values.
If we want to get the name column without any duplicate values, the DISTINCT keyword is
required. Executing the below command will return a name column with unique values.
58) What is the default ordering of data using the ORDER BY clause?
How could it be changed?
The ORDER BY clause is used to sort the table data either in ascending or descending order. By
default, it will sort the table in ascending order. If we want to change its default behavior, we need
to use the DESC keyword after the column name in the ORDER BY clause.
We have taken a customer table in the previous example. Now, we will demonstrate the ORDER BY
clause on them as well.
In the below output, we can see that the first query will sort the table data in ascending order
based on the name column. However, if we run the second query by specifying the DESC keyword,
the table's order is changed in descending order.
Answer: No. The above query does not return the output because we cannot use the WHERE
clause to restrict the groups. We need to use the HAVING clause instead of the WHERE clause to
get the correct output.
60) What is the difference between the WHERE and HAVING clauses?
The main difference is that the WHERE clause is used to filter records before any groupings are
established, whereas the HAVING clause is used to filter values from a group. The below
comparison chart explains the most common differences:
WHERE HAVING
This clause is implemented in row operations. This clause is implemented in column
operations.
It does not allow to work with aggregate It can work with aggregate functions.
functions.
This clause can be used with the SELECT, UPDATE, This clause can only be used with the
and DELETE statements. SELECT statement.
Data fetching The WHERE clause fetches the The HAVING clause first fetches the
specific data from particular rows complete data. It then separates them
based on the specified condition according to the given condition.
Aggregate The WHERE clause does not allow to The HAVING clause can work with
Functions work with aggregate functions. aggregate functions.
Act as The WHERE clause acts as a pre- The HAVING clause acts as a post-filter.
filter.
Used with We can use the WHERE clause with The HAVING clause can only use with
the SELECT, UPDATE, and DELETE the SELECT statement.
statements.
GROUP BY The GROUP BY clause comes after The GROUP BY clause comes before
the WHERE clause. the HAVING clause.
SQL provides seven (7) aggregate functions, which are given below:
o AVG(): This function is used to returns the average value from specified columns.
o COUNT(): This function is used to returns the number of table rows, including rows with
null values.
o MAX(): This function is used to returns the largest value among the group.
o MIN(): This function is used to returns the smallest value among the group.
o SUM(): This function is used to returns the total summed values(non-null) of the specified
column.
o FIRST(): This function is used to returns the first value of an expression.
o LAST(): This function is used to returns the last value of an expression.
The DENSE_RANK function assigns a unique rank for each row within a partition as per the
specified column value without any gaps. It always specifies ranking in consecutive order. If the
two rows are assigned the same rank, this function will assign it with the same rank, and the next
rank being the next sequential number. For example, if we have 3 records at rank 4, the next rank
listed would be ranked 5.
1) What type of join do you need when you want to include rows with values that don't match?
a. Equi-Join
b. Outer Join
c. Natural Join
d. All of the above.
Hide Answer Workspace
Answer: b
Explanation: Outer Join returns all rows that match the specified condition, including unmatched
rows from one or both tables. Hence, option (B) is the right answer because the outer join is the
only join that can display unmatched records.
Answer: a
Explanation: The CASE expression is a control flow function that evaluates a set of conditions and
displays the output when the first condition is met. It is primarily used to handle conditional
statements, same as IF-THEN-ELSE statements in other programming languages. Hence, option (A)
is the right answer.
Answer: d
Explanation: NUMBER data type is used for defining exact or approximate numeric
values. CLOB stands for Character Large Object used for storing a large amount of textual
data. BLOB stands for Binary Large Object that acts as a reference or pointer to an object such as a
file, image, video, etc. LINT is a SQL dialect linter. It highlights mistakes, explains what's wrong with
them, why they might be wrong, and what you can do as developers to fix them. Hence option (D)
is the right answer.
4) The view is updated immediately if the actual relations used in the view definition change. These
views are referred to as _________.
a. Instant views
b. Instantaneous views
c. Materialized views
d. Materialistic views
Hide Answer Workspace
Answer: c
Explanation: A materialized view is a table stored on the disk containing the data from the result
set of a query. It helps to keep the database up-to-date. Views are called Materialized views when
the actual relations used in the view definition change, and the view is updated immediately.
5) The part of SQL that deals with the SQL support constructs are called _______.
a. Persistent Construct Dealer
b. Persistent Supports Centre
c. Primary Storage Medium
d. Persistent Storage Module
Hide Answer Workspace
Answer: d
Explanation: Persistent Storage Module (SQL/PSM) is a feature that allows users to extend the
basic SQL functionality with their own additions.
Answer: a
Explanation: Correlated subqueries are used for row-by-row processing. It referenced a column in
the outer query and evaluated once for each row processed by the outer query (parent statement)
such as SELECT, UPDATE, or DELETE statement. On the other hand, uncorrelated subqueries
evaluate the subquery first and then determine the processing of the outer query.
Answer: b
Explanation: A trigger is a set of SQL queries that reside in a system catalog. It is a special type of
stored procedure that is invoked automatically in response to an event. Hence, option (B) is correct
because the trigger is a statement that the system executes whenever a database is modified.
Answer: d
Explanation: A transaction has a statement to begin and end both. It starts when one of the
following events takes place CREATE, COMMIT, ROLLBACK, etc. Hence option (D) is correct.
Answer: b
Explanation: A function can use any type of sequential statements, such as an IF, CASE, LOOP,
NEXT, EXIT, or NULL statement. However, it has one exception: it does not allow to work with WAIT
statement because it cannot be used inside a function. The WAIT statement is used to schedule
system work.
Answer: c
Explanation: The SQL TIME data type represents a day's time using a 24-hour clock. The p
indicates the number of digits for the fractional part of the seconds. Its value ranges from 0 to 7. If
we do not specify the p, it will be 7 by default. Hence option (C) is the correct answer.
Answer: d
Explanation: A privilege allows users to perform a set of activities on a particular database object.
Privileges are divided into two categories:
o System Privileges: This indicates that the user has the ability to CREATE, ALTER, or "DROP"
database components.
o Object Privileges: This enables the user to EXECUTE, SELECT, INSERT, or DELETE data from
database objects with privileges.
12) Which of the following indicates another name for referential integrity constraints?
a. Functional dependencies
b. Subset dependencies
c. Superset dependencies
d. Primary dependencies
Hide Answer Workspace
Answer: b
Explanation: Referential integrity specify a relation between two tables. Each table must have a
primary key. It is also called subset dependencies because the set of foreign key values in table1 of
table2 must be a subset of the set of primary key values in table2.
13) Triggers are stored blocks of code that have to be called in order to operate.
a. TRUE
b. FALSE
Hide Answer Workspace
Answer: b
Explanation: Option (B) is correct because the trigger is a set of SQL statements that resides in
system memory with unique names and is executed automatically when a database server event
occurs.
14) Outer join is the same as equi-join, except one of the duplicate columns in the result table is
removed.
a. TRUE
b. FALSE
Hide Answer Workspace
Answer: b
Explanation: An equijoin is a join in which the equal comparison operator is used to match the
keys of both tables. In contrast, outer join is a join where rows in one table that do not have a
matching row in another table are selected with NULL values for the unknown columns.
15) A transaction is a collection of closely related update commands that must all be completed, or
none at all, for the database to be valid.
a. TRUE
b. FALSE
Hide Answer Workspace
Answer: a
1) What is PL/SQL?
PL/SQL stands for procedural language extension to SQL. It supports procedural features of
programming language and SQL both. It was developed by Oracle Corporation in early of 90's to
enhance the capabilities of SQL.
Procedure: A procedure does not have a return type and should not return any value but it can
have a return statement that simply stops its execution and returns to the caller. A procedure is
used to return multiple values otherwise it is generally similar to a function.
Package: A package is schema object which groups logically related PL/SQL types , items and
subprograms. You can also say that it is a group of functions, procedure, variables and record type
statement. It provides modularity, due to this facility it aids application development. It is used to
hide information from unauthorized users.
18) What is the maximum number of triggers, you can apply on a single
table?
12 triggers.
25) what are the two virtual tables available at the time of database
trigger execution?
Table columns are referred as THEN.column_name and NOW.column_name.
29) What is the difference between the implicit and explicit cursors?
Implicit cursor is implicitly declared by Oracle. This is a cursor to all the DDL and DML commands
that return only one row.
34) What are the two different parts of the PL/SQL packages?
PL/SQL packages have the following two parts:
Specification part: It specifies the part where the interface to the application is defined.
Body part: This part specifies where the implementation of the specification is defined.
%FOUND: it checks whether cursor has fetched any row. If yes - TRUE.
39) What is the difference between syntax error and runtime error?
A syntax error can be easily detected by a PL/SQL compiler. For example: incorrect spelling etc.
while, a runtime error is handled with the help of exception-handling section in a PL/SQL block. For
example: SELECT INTO statement, which does not return any rows.
Consider an example: there are two users A and B. A transfers money to B's account. Here the
changes are updated in A's account (debit) but until it will be updated to B's account (credit), till
then other users can't see the debit of A's account. After the debit of A and credit of B, one can see
the updates. That?s consistency.
A cursor contains information on a select statement and the row of data accessed by it. This
temporary work area stores the data retrieved from the database and manipulate this data. A
cursor can hold more than one row, but can process only one row at a time. Cursor are required to
process rows individually for queries.