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

SQL Interview questions

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

SQL Interview questions

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

Interview questions

1. What is SQL?
SQL stands for structured query language which is a language
used to communicate with database.

2. What are the applications of SQL?


SQL databases can be used to perform several operations.
This includes:
 Creation of new databases
 Insertion of new data
 Deleting existing data
 Record updates
 Data retrieval
 Dropping and creating tables
 Creation of functions and views
 Conversion of data types

3. What is a database?
A database is a collection of data stored in a computer system
that can be accessed by multiple users.

4. What are the usages of SQL?


SQL is responsible for maintaining the relational data and the
data structures present in the database. Some of the common
usages are given below:

To execute queries against a database


To retrieve data from a database
To inserts records in a database
To updates records in a database
To delete records from a database
To create new databases
To create new tables in a database
To create views in a database
To perform complex operations on the database.

5. What is DBMS?
It is a software which is used to maintain and manage the
database.

6. What is a schema?
A collection of database structural elements such as tables,
stored procedures, indexes, functions, and triggers. It shows
the overall database architecture, specifies the relationships
between various objects of a database, and defines different
access permissions for them.

7. What is RDBMS?
Stands for relational database management system. Rdbms
store the data into the collection of tables. It is a type of dbms
which provides relational operations to manipulate the data
stored into the tables.

8. What are the tables and fields?


Tables Contain all the data in a database, and each table
stores data about a specific subject, such as employees or
products. Tables are uniquely identified by their names.
Fields Contain data about one aspect of the table subject,
such as first name or email address. Fields can contain
different types of data, such as text, numbers, dates, and
hyperlinks. Each row of the database has one value for a field.
Example:
Table: Employee.
Field: EMPID, ENAME, DATE OF BIRTH

9. What is the difference between CHAR and VARCHAR2


datatype in SQL?
Both of these data types are used for characters, but varchar2
is used for character strings of variable length, whereas char
is used for character strings of fixed length. For example, if we
specify the type as char(5) then we will not be allowed to
store a string of any other length in this variable, but if we
specify the type of this variable as varchar2(5) then we will be
allowed to store strings of variable length. We can store a
string of length 3 or 4 or 2 in this variable.

10. What is the primary key?


A Primary Key is one of the candidate keys. One of the
candidate keys is selected as the most important and
becomes the primary key. There cannot be more than one
primary key in a table.

11. What do you mean by foreign key?


A Foreign key is a field that can uniquely identify each row in
another table. And this constraint is used to specify a field as
a Foreign key. That is this field points to the primary key of
another table. This usually creates a kind of link between the
two tables.

12. What is a unique constraint?


A unique key is a single or combination of fields that ensure all
values stores in the column will be unique. It means a column
cannot store duplicate values.

13. What are the different types of database management


systems?

Hierarchical databases (DBMS)


Network databases (IDMS)
Relational databases (RDBMS
Object-oriented databases
Document databases (Document DB)
Graph databases
ER model databases
NoSQL databases

14. What are SQL comments?


Comments are explanations or annotations in SQL queries that
are readable by programmers. It's used to make SQL
statements easier to understand for humans. During the
parsing of SQL code, it will be ignored. Comments can be
written on a single line or across several lines.
Single Line Comments: It starts with two consecutive hyphens
(--).
Multi-line Comments: It starts with /* and ends with */.

15. What is a Constraint?


Constraints are the rules that we can apply to the type of data
in a table. That is, we can specify the limit on the type of data
that can be stored in a particular column in a table using
constraints.

16. What is a query?


An SQL query is used to retrieve the required data from the
database. However, there may be multiple SQL queries that
yield the same results but with different levels of efficiency. An
inefficient query can drain the database resources, reduce the
database speed or result in a loss of service for other users. So
it is very important to optimize the query to obtain the best
database performance.

17. What is the difference between primary key and unique


constraints?
The primary key cannot have NULL values; the unique
constraints can have NULL values. There is only one primary key
in a table, but there can be multiple unique constraints. The
primary key creates the clustered index automatically but the
unique key does not.

18. Is a blank space or zero the same as a NULL value?


A NULL value is a value, which is 'unavailable, unassigned,
unknown or not applicable.' It would be used in the absence
of any value. We can perform arithmetic operations on it. On
the other hand, zero is a number, and a blank space is treated
as a character.
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 TABLE_NAME;

20. 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.
21. What is an ALIAS command?
Aliases are the temporary names given to a table or column
for the purpose of a particular SQL query. It is used when the
name of a column or table is used other than its original name,
but the modified name is only temporary.
22. What is DISTINCT?
The SQL DISTINCT keyword is used in conjunction with the
SELECT statement to fetch unique records from a table.
We use DISTINCT keyword with the SELECT statement when
there is a need to avoid duplicate values present in any specific
columns/tables. When we use DISTINCT keyword, SELECT
statement returns only the unique records available in the
table.

23. What types of SQL commands (or SQL subsets) do you know?
Data Definition Language (DDL) – to define and modify the
structure of a database.
Data Manipulation Language (DML) – to access, manipulate,
and modify data in a database.
Data Control Language (DCL) – to control user access to the
data in the database and give or revoke privileges to a specific
user or a group of users.
Transaction Control Language (TCL) – to control transactions
in a database.
Data Query Language (DQL) – to perform queries on the data
in a database to retrieve the necessary information from it.

24. What is a clause?


A condition imposed on a SQL query to filter the data to obtain
the desired result. Some examples are WHERE, LIMIT, HAVING,
LIKE, AND, OR, ORDER BY, etc.
25. What types of SQL operators do you know?
Arithmetic (+, -, *, /,)
Comparison (=,!=, <>)
Concatenation (||)
Logical (AND, OR, NOT)
Relational (<, >, >=, <=)
Special operators (IN, NOT IN, BETWEEN, NOT BETWEEN, IS, IS
NOT, LIKE, NOT LIKE)
Subquery operators (ALL, ANY, EXISTS, NOT EXISTS)

26. Name the operator which is used in the query for appending
two strings?
In SQL for appending two strings, the” Concatenation
operator” is used and its symbol is” || “.

27. Define BETWEEN statements in SQL?


The SQL BETWEEN condition allows you to easily test if an
expression is within a range of values (inclusive). The values
can be text, date, or numbers. It can be used in a SELECT,
INSERT, UPDATE, or DELETE statement. The SQL BETWEEN
Condition will return the records where the expression is
within the range of value1 and value2.

28. What is the use of WHERE clause?


The WHERE clause is used to filter records. It is used to extract
only those records that fulfil a specified condition.
29. What is LIKE operator?
The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.

30. What is GROUP BY clause?


The GROUP BY statement groups rows that have the same
values into summary rows, like "find the number of customers
in each country".
The GROUP BY statement is often used with aggregate
functions (COUNT (), MAX (), MIN (), SUM (), AVG ()) to group
the result-set by one or more columns.

31. What is having clause?


It is use to filter the groups. The HAVING clause was added to
SQL because the WHERE keyword cannot be used with
aggregate functions.

32. What is the meaning of function and what are the types of
functions.?
SQL functions are simple code snippets that are frequently
used and re-used in database systems for data processing and
manipulation. Functions are the measured values. It always
performs a specific task.

SQL categories the functions into two types:

User-Defined Function: Functions created by a user based on


their needs are termed user-defined functions.
System Defined Function: Functions whose definition is
defined by the system are termed system-defined functions.
They are built-in database functions.

33. What is aggregate function and what are the types of


aggregate functions?
An aggregate function in SQL is a function that calculates a
single value from a set of values, usually from a column or
group of columns in a table. Aggregate functions are often
used with the GROUP BY clause in a SELECT statement.
1. MAX ()
2. MIN ()
3. AVG ()
4.SUM ()
5.COUNT ()

34. Define SQL Order by the statement?


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

By default, ORDER BY sorts the data in ascending order.


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

35. What is a subquery?


In SQL, a Subquery can be simply defined as a query within
another query. In other words, we can say that a Subquery is a
query that is embedded in the WHERE clause of another SQL
query.
36. What are Union, minus, and Intersection commands?
Set Operations in SQL eliminate duplicate tuples and can be
applied only to the relations which are union compatible. Set
Operations available in SQL are:
Set Union
Set Intersection
Set Difference

37. What is a join in SQL? What are the types of joins?


An SQL Join statement is used to combine data or rows from
two or more tables based on a common field between them.
Different types of Joins are:
1.CARTESIAN JOIN/CROSS JOIN
2.INNER JOIN/EQUI JOIN
3.OUTER JOIN
 LEFT OUTER JOIN
 RIGHT OUTER JOIN
 FULL OUTER JOIN
4. NATURAL JOIN
5. SELF JOIN

38. What is correlated subquery in SQL?


A correlated subquery in SQL is a subquery that uses values
from the outer query. It's also known as a repeating or
synchronized subquery.

39. What do you mean by data definition language?


Data definition language or DDL allows to execution of
queries like CREATE, DROP, and ALTER. That is those queries
that define the data.

40. What do you mean by data manipulation language?


Data manipulation Language or DML is used to access or
manipulate data in the database. It allows us to perform the
below-listed functions:
Insert data or rows in a database
Delete data from the database
Update data in a database.

41. What is the view in SQL?


Views in SQL are a kind of virtual table. A view also has rows
and columns as they are on a real table in the database. We
can create a view by selecting fields from one or more tables
present in the database. A View can either have all the rows
of a table or specific rows based on certain conditions.

42. What is normalization?


It is a process of analysing the given relation schemas based
on their functional dependencies and primary keys to achieve
the following desirable properties:
Minimizing Redundancy
Minimizing the Insertion, Deletion, And Update Anomalies
Relation schemas that do not meet the properties are
decomposed into smaller relation schemas that could meet
desirable properties.

43. What is Denormalization?


Denormalization is a database optimization technique in
which we add redundant data to one or more tables. This
can help us avoid costly joins in a relational database. Note
that denormalization does not mean not doing
normalization. It is an optimization technique that is applied
after normalization.
In a traditional normalized database, we store data in
separate logical tables and attempt to minimize redundant
data. We may strive to have only one copy of each piece of
data in the database.

44. What is Data Integrity?


Data integrity is defined as the data contained in the
database being both correct and consistent. For this
purpose, the data stored in the database must satisfy certain
types of procedures (rules). The data in a database must be
correct and consistent. So, data stored in the database must
satisfy certain types of procedures (rules).
45. What is a stored procedure?
Stored Procedures are created to perform one or more DML
operations on databases. It is nothing but a group of SQL
statements that accepts some input in the form of
parameters and performs some task and may or may not
return a value.

46. What is SQL injection?


SQL injection is a technique used to exploit user data
through web page inputs by injecting SQL commands as
statements. Basically, these statements can be used to
manipulate the application’s web server by malicious users.
SQL injection is a code injection technique that might
destroy your database. SQL injection is one of the most
common web hacking techniques. SQL injection is the
placement of malicious code in SQL statements, via web
page input.

47. What is an index?


A database index is a data structure that improves the speed
of data retrieval operations on a database table at the cost
of additional writes and the use of more storage space to
maintain the extra copy of data. Data can be stored only in
one order on a disk. To support faster access according to
different values, a faster search like a binary search for
different values is desired. For this purpose, indexes are
created on tables. These indexes need extra space on the
disk, but they allow faster search according to different
frequently searched values.

48. Explain WITH clause in SQL?


The WITH clause provides a way relationship of defining a
temporary relationship whose definition is available only to
the query in which the with clause occurs. SQL applies
predicates in the WITH clause after groups have been
formed, so aggregate functions may be used.

49. What is a Cursor?


The cursor is a Temporary Memory or Temporary Work
Station. It is Allocated by Database Server at the Time of
Performing DML operations on the Table by the User.
Cursors are used to store Database Tables.

50. What is a trigger?


The trigger is a statement that a system executes
automatically when there is any modification to the
database. In a trigger, we first specify when the trigger is to
be executed and then the action to be performed when the
trigger executes. Triggers are used to specify certain
integrity constraints and referential constraints that cannot
be specified using the constraint mechanism of SQL.

51. What is the difference between SQL DELETE and SQL


TRUNCATE commands?
SQL DELETE SQL TRUNCATE

The DELETE statement removes TRUNCATE TABLE removes the data by


rows one at a time and records an deallocating the data pages used to store the
entry in the transaction log for table data and records only the page
each deleted row. deallocations in the transaction log.

DELETE command is slower than While the TRUNCATE command is faster than
the identity TRUNCATE command. the DELETE command.

To use Delete you need DELETE To use Truncate on a table we need at least
permission on the table. ALTER permission on the table.

The identity of the column retains


The identity of the column is reset to its seed
the identity after using DELETE
value if the table contains an identity column.
Statement on the table.

The delete can be used with


Truncate cannot be used with indexed views.
indexed views.

52. What is the difference between TRUNCATE and DROP


statements?
SQL DROP TRUNCATE

Whereas the TRUNCATE command is


The DROP command is used to remove
used to delete all the rows from the
the table definition and its contents.
table.

In the DROP command, table space is While the TRUNCATE command does not
freed from memory. free the table space from memory.

Whereas the TRUNCATE is also a


DROP is a DDL(Data Definition
DDL(Data Definition Language)
Language) command.
command.
SQL DROP TRUNCATE

In the DROP command, a view of the While in this command, a view of the
table does not exist. table exists.

In the DROP command, integrity While in this command, integrity


constraints will be removed. constraints will not be removed.

In the DROP command, undo space is While in this command, undo space is
not used. used but less than DELETE.

53. Why do we use commit and rollback commands?


COMMIT ROLLBACK

COMMIT permanently saves the changes ROLLBACK undo the changes made
made by the current transaction. by the current transaction.

The transaction cannot undo changes after Transaction reaches its previous
COMMIT execution. state after ROLLBACK.

When the transaction is successful, When the transaction is aborted,


COMMIT is applied. ROLLBACK occurs.

54. What is ETL in SQL?


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

SQL is a query execution or commanding PL/SQL is a complete programming


language language

SQL is a data-oriented language. PL/SQL is a procedural language

SQL is very declarative in nature. PL/SQL has a procedural nature.

It is used for manipulating data. It is used for creating applications.

We can execute one statement at a time We can execute blocks of statements


in SQL in PL/SQL

SQL tells databases, what to do? PL/SQL tells databases how to do.

We can embed SQL in PL/SQL We cannot embed PL/SQL in SQL

56. Write down various types of relationships in SQL?


There are various relationships, namely:
One-to-One Relationship.
One to Many Relationships.
Many to One Relationship.
Self-Referencing Relationship.

57. What is the primary use of Normalization?


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

58. What are the different types of indexes in SQL?


SQL indexes are nothing more than a technique of minimizing
the query's cost. The higher the query's cost, the worse the
query's performance. The following are the different types of
Indexes supported in SQL:

Unique Index
Clustered Index
Non-Clustered Index
Bit-Map Index
Normal Index
Composite Index
B-Tree Index

59. What is self-join and what is the requirement of self-join?


A SELF JOIN is used to join a table with itself. This join can be
performed using table aliases, which allow us to avoid
repeating the same table name in a single sentence. It will
throw an error if we use the same table name more than
once in a single query without using table aliases.
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.
60. What is meant by case manipulation functions? Explains its
different types in SQL.?
Case manipulation functions are part of the character
functions. It converts the data from the state in which it is
already stored in the table to upper, lower, or mixed case.
The conversion performed by this function can be used to
format the output. We can use it in almost every part of the
SQL statement. Case manipulation functions are mostly used
when you need to search for data, and you don't have any
idea that the data you are looking for is in lower case or upper
case.
There are three case manipulation functions in SQL:
LOWER: This function is used to converts a given character
into lowercase.
UPPER: This function is used to converts a given character
into uppercase.
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.

61. What is the usage of the NVL () function?


The NVL () function is used to convert the NULL value to the
other value. The function returns the value of the second
parameter if the first parameter is NULL. If the first parameter
is anything other than NULL, it is left unchanged. This function
is used in Oracle, not in SQL and MySQL. Instead of NVL ()
function, MySQL have IFNULL () and SQL Server have ISNULL
() function.

62. What is the difference between the WHERE and HAVING


clauses?
WHERE HAVING

This clause is implemented in row This clause is implemented in column


operations. operations.

It does not allow to work with aggregate


It can work with aggregate functions.
functions.

This clause can be used with the SELECT, This clause can only be used with the
UPDATE, and DELETE statements. SELECT statement.

63. What is the difference between the RANK () and


DENSE_RANK () functions?
The RANK function determines the rank for each row within
your ordered partition in the result set. If the two rows are
assigned the same rank, then the next number in the ranking
will be its previous rank plus a number of duplicate numbers.
For example, if we have three records at rank 4, the next rank
listed would be ranked 7.
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.

64. What are SQL dialects? Give some examples.


The various versions of SQL, both free and paid, are also called
SQL dialects. All the flavours of SQL have a very similar syntax
and vary insignificantly only in additional functionality. Some
examples are Microsoft SQL Server, PostgreSQL, MySQL,
SQLite, T-SQL, Oracle, and MongoDB.

65. How to create a table?


Using the CREATE TABLE statement. For example, to create a
table with three columns of predefined datatypes, we apply
the following syntax:
CREATE TABLE table name (
col_1 datatype constraints,
col_2 datatype constraints,
col_3 datatype constraints
);
66. What is the difference between nested and correlated
subqueries?
A correlated subquery is an inner query nested in a bigger
(outer) query that refers to the values from the outer query
for its execution, meaning that a correlated subquery
depends on its outer query. Instead, a non-correlated
subquery doesn't rely on the data from the outer query and
can be run independently of it.

67. What is the difference between clustered and non-clustered


indexes?
While a clustered index defines the physical order of records
of a table and performs data searching based on the key
values, a non-clustered index keeps the order of records that
do not match the physical order of the actual data on the
disk. A table can have only one clustered index but many
non-clustered ones.

68. What is the CASE () function?


The way to implement the if-then-else logic in SQL. This
function sequentially checks the provided conditions in the
WHEN clauses and returns the value from the corresponding
THEN clause when the first condition is satisfied. If none of
the conditions is satisfied, the function returns the value from
the ELSE clause in case it's provided, otherwise, it returns
NULL. The syntax is:
CASE
WHEN condition_1 THEN value_1
WHEN condition_2 THEN value_2
WHEN condition_3 THEN value_3
...
ELSE value
END;
69. How can you optimize a slow-running query?
here are several techniques, including:
 Using appropriate indexes.
 Avoiding unnecessary joins and subqueries.
 Using efficient functions and operators.
 Analysing execution plans to identify bottlenecks.

70. Describe the purpose of window functions in SQL.


Window functions perform calculations on a set of rows
within a query partition. Examples include ranking,
calculating moving averages, and finding percentiles.

71. What is collation in SQL.?


In SQL, "collation" refers to a set of rules that define how
character data is sorted and compared within a database,
including factors like case sensitivity, accent sensitivity, and
the specific character set used, essentially dictating how text
data is ordered when performing operations like sorting or
filtering in queries.

72. What is sharding in SQL.?


Sharding involves splitting and distributing one logical data
set across multiple databases that share nothing and can be
deployed across multiple servers. To achieve sharding, the
rows or columns of a larger database table are split into
multiple smaller tables.

You might also like