SQL Interview Q N A

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

1. What is DBMS?

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

2. What is RDBMS?

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

Example: SQL Server.

3. What is SQL?

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

4. What is a Database?

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

Example: School Management Database, Bank Management Database.

5. What are tables and Fields?

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

Example:.

Table: Employee.

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

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

6. What is a primary key?

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

7. What is a unique key?

A Unique key constraint uniquely identified each record in the database. This provides uniqueness for
the column or set of columns.
A Primary key constraint has automatic unique constraint defined on it. But not, in the case of Unique
Key.

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

8. What is a foreign key?

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

9. What is a join?

This is a keyword used to query data from more tables based on the relationship between the fields of
the tables. Keys play a major role when JOINs are used.

10. What are the types of join and explain each?

There are various types of join which can be used to retrieve data and it depends on the relationship
between tables.

 Inner Join.

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

 Right Join.

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

 Left Join.

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

 Full Join.

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

11. What is normalization?

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

12. What is Denormalization?

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

The normal forms can be divided into 5 forms, and they are explained below -.

 First Normal Form (1NF):.

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

 Second Normal Form (2NF):.

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

 Third Normal Form (3NF):.

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

 Fourth Normal Form (4NF):.

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

14. What is a View?

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

15. What is an Index?

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

16. What are all the different types of indexes?

There are three types of indexes -.

 Unique Index.

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

 Clustered Index.

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

 NonClustered Index.

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

17. What is a Cursor?


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

18. What is a relationship and what are they?

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

 One to One Relationship.

 One to Many Relationship.

 Many to One Relationship.

 Self-Referencing Relationship.

19. What is a query?

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

20. What is subquery?

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

21. What are the types of subquery?

There are two types of subquery – Correlated and Non-Correlated.

A correlated subquery cannot be considered as independent query, but it can refer the column in a table
listed in the FROM the list of the main query.

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

22. What is a stored procedure?

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

23. What is a trigger?

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

Example: When a new student is added to the student database, new records should be created in the
related tables like Exam, Score and Attendance tables.
24. What is the difference between DELETE and TRUNCATE commands?

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

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

25. What are local and global variables and their differences?

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

Global variables are the variables which can be used or exist throughout the program. Same variable
declared in global cannot be used in functions. Global variables cannot be created whenever that
function is called.

26. What is a constraint?

Constraint can be used to specify the limit on the data type of table. Constraint can be specified while
creating or altering the table statement. Sample of constraint are.

 NOT NULL.

 CHECK.

 DEFAULT.

 UNIQUE.

 PRIMARY KEY.

 FOREIGN KEY.

27. What is data Integrity?

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

28. What is Auto Increment?

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

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

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

Clustered index is used for easy retrieval of data from the database by altering the way that the records
are stored. Database sorts out rows by the column which is set to be clustered index.
A nonclustered index does not alter the way it was stored but creates a complete separate object within
the table. It point back to the original table rows after searching.

30. What is Datawarehouse?

Datawarehouse is a central repository of data from multiple sources of information. Those data are
consolidated, transformed and made available for the mining and online processing. Warehouse data
have a subset of data called Data Marts.

31. What is Self-Join?

Self-join is set to be query used to compare to itself. This is used to compare values in a column with
other values in the same column in the same table. ALIAS ES can be used for the same table comparison.

32. What is Cross-Join?

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

33. What is user defined functions?

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

34. What are all types of user defined functions?

Three types of user defined functions are.

 Scalar Functions.

 Inline Table valued functions.

 Multi statement valued functions.

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

35. What is collation?

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

ASCII value can be used to compare these character data.

36. What are all different types of collation sensitivity?

Following are different types of collation sensitivity -.

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

 Accent Sensitivity.

 Kana Sensitivity – Japanese Kana characters.


 Width Sensitivity – Single byte character and double byte character.

37. Advantages and Disadvantages of Stored Procedure?

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

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

38. What is Online Transaction Processing (OLTP)?

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

Example – Bank Transactions on a daily basis.

39. What is CLAUSE?

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

Example – Query that has WHERE condition

Query that has HAVING condition.

40. What is recursive stored procedure?

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

41. What is Union, minus and Interact commands?

UNION operator is used to combine the results of two tables, and it eliminates duplicate rows from the
tables.

MINUS operator is used to return rows from the first query but not from the second query. Matching
records of first and second query and other rows from the first query will be displayed as a result set.

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

42. What is an ALIAS command?

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

Example-.

Select st.StudentID, Ex.Result from student st, Exam as Ex where st.studentID = Ex. StudentID

Here, st refers to alias name for student table and Ex refers to alias name for exam table.
43. What is the difference between TRUNCATE and DROP statements?

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

44. What are aggregate and scalar functions?

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

Example -.

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

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

45. How can you create an empty table from an existing table?

Example will be -.

Select * into studentcopy from student where 1=2

Here, we are copying student table to another table with the same structure with no rows copied.

46. How to fetch common records from two tables?

Common records result set can be achieved by -.

Select studentID from student INTERSECT Select StudentID from Exam

47. How to fetch alternate records from a table?

Records can be fetched for both Odd and Even row numbers -.

To display even numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0

To display odd numbers-.

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

from (Select rowno, studentId from student) where mod(rowno,2)=1.[/sql]

48. How to select unique records from a table?

Select unique records from a table by using DISTINCT keyword.

Select DISTINCT StudentID, StudentName from Student.

49. What is the command used to fetch first 5 characters of the string?

There are many ways to fetch first 5 characters of the string -.

Select SUBSTRING(StudentName,1,5) as studentname from student


Select LEFT(Studentname,5) as studentname from student

50. Which operator is used in query for pattern matching?

LIKE operator is used for pattern matching, and it can be used as -.

1. % – Matches zero or more characters.

2. _(Underscore) – Matching exactly one character.

Example -.

Select * from Student where studentname like 'a%'

Select * from Student where studentname like 'ami_'

1. What are the properties of the transaction?


Answer: Properties of the transaction are known as ACID properties, such as
Atomicity: Ensures the completeness of all transactions performed. Checks whether every transaction is
completed successfully if not then transaction is aborted at the failure point and the previous
transaction is rolled back to its initial state as changes undone
Consistency: Ensures that all changes made through successful transaction are reflected properly on
database
Isolation: Ensures that all transactions are performed independently and changes made by one
transaction are not reflected on other
Durability: Ensures that the changes made in the database with committed transactions persist as it is
even after a system failure.

2. Explain SQL Data Types?


Answer: In SQL Server, each column in a database table has a name and a data type. We need to decide
what type of data to store inside each and every column of a table while creating a SQL table.

3. Explain the working of SQL Privileges?


Answer: SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user
environments. The administrator of the database can grant or revoke privileges to or from users of
database object like SELECT, INSERT, UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to user apart from an
administrator.
Syntax: GRANT privilege_name
ON object_name
TO {user_name|PUBLIC|role_name}
In the above syntax WITH GRANT, OPTIONS 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};
4. Difference between TRUNCATE, DELETE and DROP commands?
Answer: DELETE removes some or all rows from a table based on the condition. It can be rolled back.
TRUNCATE removes ALL rows from a table by de-allocating the memory pages. The operation cannot be
rolled back
DROP command removes a table from the database completely.

5. What is Referential Integrity?


Answer: Set of rules that restrict the values of one or more columns of the tables based on the values of
the primary key or unique key of the referenced table.

6. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?
Answer: BETWEEN operator is used to displaying rows based on a range of values in a row whereas the
IN condition operator is used to check for values contained in a specific set of values.
Example of BETWEEN:
SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;
Example of IN:
SELECT * FROM students where ROLL_NO IN (8,15,25);

7. Why are SQL functions used?


Answer: SQL functions are used for the following purposes:
To perform some calculations on the data
To modify individual data items
To manipulate the output
To format dates and numbers
To convert the data types

8. What do you mean by recursive stored procedure?


Answer: Recursive stored procedure refers to a stored procedure which calls by itself until it reaches
some boundary condition. This recursive function or procedure helps the programmers to use the same
set of code n number of times.

9. What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?


Answer: HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY clause
and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is applied to
each row before they are a part of the GROUP BY function in a query.

10. List some case manipulation functions in SQL?


Answer:
There are three case manipulation functions in SQL, namely:
LOWER: This function returns the string in lowercase. It takes a string as an argument and returns it by
converting it into lower case. Syntax:
LOWER(‘string’)
UPPER: This function returns the string in uppercase. It takes a string as an argument and returns it by
converting it into uppercase. Syntax:
UPPER(‘string’)
INITCAP: This function returns the string with the first letter in uppercase and the rest of the letters in
lowercase. Syntax:
INITCAP(‘string’)
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this
technology, you can opt for a structured training from SVR! Click below to know more.

11. What is an ALIAS command?


Answer: ALIAS name can be given to any table or a column. This alias name can be referred in WHERE
clause to identify a particular table or a column.
For example-
Select emp.empID, dept.Result from employee emp, department as dept where
emp.empID=dept.empID
In the above example, emp refers to alias name for employee table and dept refers to alias name for
department table.

12. What are the aggregate and scalar functions?


Answer: Aggregate functions are used to evaluate mathematical calculation and return a single value.
These calculations are done from the columns in a table. For example- max(),count() are calculated with
respect to numeric.
Scalar functions return a single value based on the input value. For example – UCASE(), NOW() is
calculated with respect to a string.

13. What is a Stored Procedure?


Answer: A Stored Procedure is a function which consists of many SQL statements to access the database
system. Several SQL statements are consolidated into a stored procedure and execute them whenever
and wherever required which saves time and avoid writing code again and again.

14. List some advantages and disadvantages of Stored Procedure?


Answer:
Advantages:
A Stored Procedure can be used as modular programming which means create once, store and call for
several times whenever it is required. This supports faster execution. It also reduces network traffic and
provides better security to the data.
Disadvantage:
The only disadvantage of Stored Procedure is that it can be executed only in the database and utilizes
more memory in the database server.

15. List all the types of user-defined functions?


Answer:

There are three types of user-defined functions, namely:

 Scalar Functions

 Inline Table-valued functions

 Multi-statement valued functions

 Scalar returns the unit, variant defined the return clause. Other two types of defined functions
return table.
16. What do you mean by Collation?
Answer: Collation is defined as a set of rules that determine how data can be sorted as well as
compared. Character data is sorted using the rules that define the correct character sequence along
with options for specifying case-sensitivity, character width, etc.

17. What are the different types of Collation Sensitivity?


Answer:
Following are the different types of collation sensitivity:

Case Sensitivity: A and a and B and b.

Kana Sensitivity: Japanese Kana characters.

Width Sensitivity: Single byte character and double-byte character.


Accent Sensitivity.

Apart from this SQL Interview Questions Blog, if you want to get trained from professionals on this
technology, you can opt for structured training from SVR

18. What are the different authentication modes in SQL Server? How can it be changed?
Answer: Windows mode and Mixed Mode – SQL and Windows. You can go to the below steps to change
authentication mode in SQL Server:
Click Start> Programs> Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise
Manager from the Microsoft SQL Server program group.
Then select the server from the Tools menu.
Select SQL Server Configuration Properties, and choose the Security page.

19. What is a Data warehouse?


Answer: Datawarehouse refers to a central repository of data where the data is assembled from
multiple sources of information. Those data are consolidated, transformed and made available for the
mining as well as online processing. Warehouse data also have a subset of data called Data Marts.

20. What are Local and Global variables?


Answer:
Local variables:
These variables can be used or exist only inside the function. These variables are not used or referred by
any other function.
Global variables:
These variables are the variables which can be accessed throughout the program. Global variables
cannot be created whenever that function is called.

21. How can you fetch alternate records from a table?


Answer: You can fetch alternate records i.e both odd and even row numbers. For example- To display
even numbers, use the following command:
A select student from (Select row, students from student) where mod(row,2)=0
Now, to display odd numbers:
Select student from (Select row, a student from student) where mod(row,2)=1
22. When are we going to use truncate and delete?
Answer: TRUNCATE is a DDL command, whereas DELETE is a DML command.
We can’t execute a trigger in case of TRUNCATE whilst with DELETE, we can accomplish a trigger.
TRUNCATE is quicker than DELETE, for the reason that when we use DELETE to delete the data, at that
time it stores the whole statistics in the rollback gap on or after where we can get the data back after
removal. In the case of TRUNCATE, it will not store data in rollback gap and will unswervingly rub it out.
TRUNCATE do not recover the deleted data.
We can use any condition in WHERE clause using DELETE but it is not possible with TRUNCATE.5.If a
table is referenced by any foreign key constraints, then TRUNCATE won’t work.
Go through this SQL tutorial to learn more about SQL commands.

23. What is the SQL CASE statement used for? Explain with an example?
Answer:
It allows you to embed an if-else like a clause in the SELECT clause.
SELECT Employee_Name, CASE Location
WHEN ‘Alex’ THEN Bonus * 2
WHEN ‘robin’ THEN Bonus *, 5
ELSE Bonus
END
“New Bonus”
FROM Intellipaat_employee;
Read this blog to learn why SQL Optimization has always been an important aspect of database
management.

24. How do you maintain database integrity where deletions from one table will automatically cause
deletions in another table?
Answer:
You can create a trigger that will automatically delete elements in the second table when elements from
the first table are removed.

25. How to find the second highest salary of an Employee?


Answer: There are many ways to find the second highest salary of Employees in SQ. You can either use
SQL Join or Subquery to solve this problem.
Here is SQL query using Subquery :
Select MAX(Salary) from Intellipaat_emplyee WHERE Salary NOT IN ( select MAX.

26. When is the Explicit Cursor Used?


Answer: If the developer needs to perform the row by row operations for the result set containing more
than one row, then he unambiguously declares a pointer with a name. They are managed by OPEN,
FETCH and CLOSE.%FOUND, %NOFOUND, %ROWCOUNT, and %ISOPEN characteristics are used in all
types of pointers.

27. Explain correlated query work?


Answer: It’s most important to be attentive to the arrange of operations in an interrelated subquery.
First, a row is processed in the outer doubt.
Then, for that exacting row, the subquery is executed – as a result for each row processed by the outer
query, the subquery will also be processed. In a correlated subquery, each time a line is worked for
Emp1, the subquery will also make a decision on the exacting row’s value for Emp1. Salary and run. And
the outer query will move on to the next row, and the subquery will execute for that row’s value of
Emp1.Salary.
It will persist in anticipation of the “WHERE (1) = (… )” state is pleased.

28. When is the UPDATE_STATISTICS command used?


Answer: This command is used, ones the processing of large data is done.
When we delete a large number of files, alteration or reproduction takes place in the tables, to be
concerned about these changes we need to restructure the indexes This is done UPDATE_STATISTICS.

29. What is a Subquery?


Answer: A Subquery is a SQL query within another query. It is a subset of a Select statement whose
return values are used in filtering the conditions of the main query.

30. What are SQL constraints?


Answer: SQL constraints are the set of rules that impose some restriction while insertion, deletion or
updation of data in the databases. In SQL we have both column level as well as table
level constraints which are applied at columns and tables respectively. Some of constraints in SQL are –
Primary Key, Foreign Key, Unique Key, Not NULL, DEFAULT, CHECK and Index constraint.

31. What are the different DCL commands in SQL?


Answer: DCL commands are used to create roles, grant permission and control access to the database
objects.
GRANT: To provide user access
DENY: To deny permissions to users
REVOKE: To remove user access

32. What is a Primary Key?


Answer: A primary key is a column or a combination of columns which uniquely identifies a record in the
database. A primary key can only have unique and not NULL values and there can be only one primary
key in a table.

33. How to add code to the existing article (Using Improve Article)?
Answer: Recursive Practice Problems with Solutions
Run Levels in Linux 

34. Explain Boyce and Codd Normal Form(BCNF)?


Answer: BCNF is the advanced or stricter version of 3NF.
For each functional dependency X -> Y-
X should be the super key

35. Explain the First Normal Form(1NF)?


Answer: According to First Normal Form, a column cannot have multiple values, each value in the
columns must be atomic.

36. What are scalar functions in SQL?


Answer: Scalar functions are the functions that return a single value by processing a single value in SQL.
Some of the widely used SQL functions are-
UCASE() – USed to convert a string to upper case
LCASE() – Used to convert a string to lower case
ROUND() – Used to round a number to the decimal places specified
NOW() – Used to fetch current system date and time
LEN() – Used to find the length of a string
SUBSTRING() or MID() – MID and SUBSTRING are synonyms in SQL. They are used to extract a substring
from a string by specifying the start and end index. Syntax –
SUBSTRING(ColumnName,startIndex,endIndex).
LOCATE() – Used to find the index of the character in a string. Syntax – LOCATE(character,ColumnName)
LTRIM() – Used to trim spaces from left
RTRIM() – Used to trim spaces from right

37. What is a coalesce function?


Answer: Coalesce function is used to return the first, not NULL value out of the multiple values or
expressions passed to the coalesce function as parameters.Example-
COALESCE(NULL, NULL, 5, ‘ArtOfTesting’) will return the value 5.
COALESCE(NULL, NULL, NULL) will return NULL value as no not NULL value is encountered in the
parameters list.

38. What are the different types of joins?


Answer:
Types of Joins are as follows:

 INNER JOIN

 LEFT JOIN

 RIGHT JOIN

 OUTER JOIN

 View Complete Post

39. What do you mean by Subquery?


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

40. What is a Unique key?


Answer: Uniquely identifies a single row in the table.
Multiple values allowed per table.
Null values allowed.
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this
technology, you can opt for a structured training from SVR! 

41. What do you mean by data integrity?


Answer: Data Integrity defines accuracy as well as the consistency of the data stored in a database. It
also defines integrity constraints to enforce business rules on the data when it is entered into an
application or a database.
42. Write a SQL query to display the current date?
Answer: In SQL, there is a built-in function called GetDate() which helps to return the current
timestamp/date.

43. What is DBMS?


Answer: Database Management System is a collection of programs that enables a user to store, retrieve,
update and delete information from a database.

44. What are the different DDL commands in SQL?


Answer: DDL commands are used to define or alter the structure of the database.
CREATE: To create databases and database objects
ALTER: To alter existing database objects
DROP: To drop databases and databases objects
TRUNCATE: To remove all records from a table but not its database structure
RENAME: To rename database objects

45. What are Constraints?


Answer: Constraints are used to specify the limit on the data type of the table. It can be specified while
creating or altering the table statement.

The sample of constraints are:

 NOT NULL

 CHECK

 DEFAULT

 UNIQUE

 PRIMARY KEY

 FOREIGN KEY

46. Explain different types of index?


Answer:
There are three types of index namely:
Unique Index:
This index does not allow the field to have duplicate values if the column is unique indexed. If a primary
key is defined, a unique index can be applied automatically.
Clustered Index:
This index reorders the physical order of the table and searches based on the basis of key values. Each
table can only have one clustered index.
Non-Clustered Index:
Non-Clustered Index does not alter the physical order of the table and maintains a logical order of the
data. Each table can have many nonclustered indexes.

47. Explain different types of Normalization?


Answer: There are many successive levels of normalization. These are called normal forms. Each
consecutive normal form depends on the previous one.
The first three normal forms are usually adequate.
First Normal Form (1NF) – No repeating groups within rows
Second Normal Form (2NF) – Every non-key (supporting) column value is dependent on the whole
primary key.
Third Normal Form (3NF) – Dependent solely on the primary key and no other non-key (supporting)
column value.

48. What is ACID property in a database?


Answer: ACID stands for Atomicity, Consistency, Isolation, Durability. It is used to ensure that the data
transactions are processed reliably in a database system.
Atomicity: Atomicity refers to the transactions that are completely done or failed where transaction
refers to a single logical operation of a data. It means if one part of any transaction fails, the entire
transaction fails and the database state is left unchanged.
Consistency: Consistency ensures that the data must meet all the validation rules. In simple words, you
can say that your transaction never leaves the database without completing its state.
Isolation: The main goal of isolation is concurrency control.
Durability: Durability means that if a transaction has been committed, it will occur whatever may come
in between such as power loss, crash or any sort of error.

49. What do you mean by “Trigger” in SQL?


Answer: Trigger in SQL is are a special type of stored procedures that are defined to execute
automatically in place or after data modifications. It allows you to execute a batch of code when an
insert, update or any other query is executed against a specific table.

50. What are the different operators available in SQL?


Answer: There are three operators available in SQL, namely:
Arithmetic Operators
Logical Operators
Comparison Operators
Apart from this SQL Interview Questions blog, if you want to get trained from professionals on this
technology, you can opt for a structured training from SVR! 

Note: Browse latest SQL Interview Questions and SQL Tutorial Videos. Here you can check SQL
Training details and SQL Training Videos for self learning. Contact +91 988 502 2027 for more
information.

Post navigation

Q #1) What is SQL?


Answer: Structured Query Language SQL is a database tool that is used to create and
access the database to support software applications.
Q #2) What are tables in SQL?
Answer: The table is a collection of record and its information at a single view.
Q #3) What are the different types of statements supported by SQL?
Answer:
There are 3 types of SQL statements:
a) DDL (Data Definition Language): It is used to define the database structure such as
tables. It includes three statements such as CREATE, ALTER, and DROP.
Also read =>> MySQL Create Table Tutorial
Some of the DDL Commands are listed below:
CREATE: It is used for creating the table.
CREATE TABLE table_name

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size),

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

 ADD column_name datatype

OR

ALTER TABLE table_name

DROP COLUMN column_name

b) DML (Data Manipulation Language): These statements are used to manipulate the


data in records. Commonly used DML statements are INSERT, UPDATE, and DELETE.
The SELECT statement is used as a partial DML statement, used to select all or relevant
records in the table.

c) DCL (Data Control Language): These statements are used to set privileges such as
GRANT and REVOKE database access permission to the specific user.
Q #4) How do we use the DISTINCT statement? What is its use?
Answer: The DISTINCT statement is used with the SELECT statement. If the record
contains duplicate values then the DISTINCT statement is used to select different values
among duplicate records.
Syntax:
SELECT DISTINCT column_name(s)

 FROM table_name;

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


Answer:
WHERE Clause: This clause is used to define the condition, extract and display only those
records which fulfill the given condition.
Syntax:
SELECT column_name(s)

 FROM table_name

 WHERE condition;

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

 FROM table_name

 GROUP BY column_name;

HAVING clause: This clause is used in association with the GROUP BY clause. It is


applied to each group of results or the entire result as a single group. It is much similar as
WHERE clause but the only difference is you cannot use it without GROUP BY clause
Syntax:
SELECT column_name(s)

 FROM table_name

 GROUP BY column_name

 HAVING condition;

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

 FROM table_name

 WHERE condition

 ORDER BY column_name ASC|DESC;

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

 FROM table_name

 JOIN table_name

 USING (column_name);

Q #6) Why do we use SQL constraints? Which constraints we can use while creating
a database in SQL?
Answer: Constraints are used to set the rules for all records in the table. If any constraints
get violated then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.

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


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

4 major types of Joins are used while working on multiple tables in SQL databases:
INNER JOIN: It is also known as SIMPLE JOIN which returns all rows from BOTH tables
when it has at least one matching column.
Syntax:
SELECT column_name(s)

 FROM table_name1 

 INNER JOIN table_name2

 ON column_name1=column_name2;

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

The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date

  FROM Employee

  INNER JOIN Joining

  ON Employee.Emp_id = Joining.Emp_id

  ORDER BY Employee.Emp_id;

There will be 4 records selected. Results are:

Employee and Orders tables have a matching customer_id value.


LEFT JOIN (LEFT OUTER JOIN): This join returns all rows from the LEFT table and its
matched rows from a RIGHT table.
Syntax:
SELECT column_name(s)
 FROM table_name1

 LEFT JOIN table_name2

 ON column_name1=column_name2;

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

The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

LEFT OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

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

RIGHT JOIN (RIGHT OUTER JOIN): This joins returns all rows from the RIGHT table and
its matched rows from the LEFT table.
Syntax:
SELECT column_name(s)
FROM table_name1

RIGHT JOIN table_name2

ON column_name1=column_name2;

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

The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date FROM Employee

RIGHT JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

Output:
Emp_id Joining_Date

E0012 2016/04/18

E0013 2016/04/19

E0014 2016/05/01

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

 FULL OUTER JOIN table_name2

 ON column_name1=column_name2;

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

The second table’s name is Joining.

Enter the following SQL statement:


SELECT Employee.Emp_id, Joining.Joining_Date

FROM Employee

FULL OUTER JOIN Joining

ON Employee.Emp_id = Joining.Emp_id

ORDER BY Employee.Emp_id;

There will be 8 records selected. These are the results that you should see.
Also Read =>  MySQL Join Tutorial
Q #8) What are transactions and their controls?
Answer: A transaction can be defined as the sequence task that is performed on databases
in a logical manner to gain certain results. Operations like Creating, updating, deleting
records performed in the database come from transactions.
In simple words, we can say that a transaction means a group of SQL queries executed on
database records.

There are 4 transaction controls such as


 COMMIT: It is used to save all changes made through the transaction.
 ROLLBACK: It is used to roll back the transaction. All changes made by the
transaction are reverted back and the database remains as before.
 SET TRANSACTION: Set the name of the transaction.
 SAVEPOINT: It is used to set the point where the transaction is to be rolled back.
Q #9) What are the properties of the transaction?
Answer: Properties of the transaction are known as ACID properties. These are:
 Atomicity: Ensures the completeness of all transactions performed. Checks whether
every transaction is completed successfully or not. If not, then the transaction is
aborted at the failure point and the previous transaction is rolled back to its initial
state as changes are undone.
 Consistency: Ensures that all changes made through successful transactions are
reflected properly on the database.
 Isolation: Ensures that all transactions are performed independently and changes
made by one transaction are not reflected on others.
 Durability: Ensures that the changes made in the database with committed
transactions persist as it is even after a system failure.
Q #10) How many Aggregate functions are available in SQL?
Answer: SQL Aggregate functions determine and calculate values from multiple columns in
a table and return a single value.
There are 7 aggregate functions in SQL:
 AVG(): Returns the average value from specified columns.
 COUNT(): Returns number of table rows.
 MAX(): Returns the largest value among the records.
 MIN(): Returns smallest value among the records.
 SUM(): Returns the sum of specified column values.
 FIRST(): Returns the first value.
 LAST(): Returns last value.
Q #11) What are Scalar functions in SQL?
Answer: Scalar functions are used to return a single value based on the input values.
Scalar Functions are as follows:
 UCASE(): Converts the specified field in the upper case.
 LCASE(): Converts the specified field in lower case.
 MID(): Extracts and returns character from the text field.
 FORMAT(): Specifies the display format.
 LEN(): Specifies the length of the text field.
 ROUND(): Rounds up the decimal field value to a number.
Q #12) What are triggers?
Answer: Triggers in SQL is kind of stored procedures used to create a response to a
specific action performed on the table such as INSERT, UPDATE or DELETE. You can
invoke triggers explicitly on the table in the database.
Action and Event are two main components of SQL triggers. When certain actions are
performed, the event occurs in response to that action.

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

ON table_name [FOR [EACH] {ROW|STATEMENT}]

EXECUTE PROCEDURE functionname {arguments}

Q #13) What is View in SQL?


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

SELECT column_name(s)

FROM table_name

WHERE condition

Q #14) How we can update the view?


Answer: SQL CREATE and REPLACE can be used for updating the view.
Execute the below query to update the created view.

Syntax:
CREATE OR REPLACE VIEW view_name AS

 SELECT column_name(s)
 FROM table_name

 WHERE condition

Q #15) Explain the working of SQL Privileges?


Answer: SQL GRANT and REVOKE commands are used to implement privileges in SQL
multiple user environments. The administrator of the database can grant or revoke
privileges to or from users of database objects by using commands like SELECT, INSERT,
UPDATE, DELETE, ALL, etc.
GRANT Command: This command is used to provide database access to users other than
the administrator.
Syntax:
GRANT privilege_name

 ON object_name

 TO {user_name|PUBLIC|role_name}

 [WITH GRANT OPTION];

In the above syntax, the GRANT option indicates that the user can grant access to another
user too.

REVOKE command: This command is used to provide database deny or remove access to
database objects.
Syntax:
REVOKE privilege_name

 ON object_name

 FROM {user_name|PUBLIC|role_name};

Q #16) How many types of Privileges are available in SQL?


Answer: There are two types of privileges used in SQL, such as
 System privilege: System privilege deals with the object of a particular type and
provides users the right to perform one or more actions on it. These actions include
performing administrative tasks, ALTER ANY INDEX, ALTER ANY CACHE GROUP
CREATE/ALTER/DELETE TABLE, CREATE/ALTER/DELETE VIEW etc.
 Object privilege: This allows to perform actions on an object or object of another
user(s) viz. table, view, indexes etc. Some of the object privileges are EXECUTE,
INSERT, UPDATE, DELETE, SELECT, FLUSH, LOAD, INDEX, REFERENCES etc.
Q #17) What is SQL Injection?
Answer: SQL Injection is a type of database attack technique where malicious SQL
statements are inserted into an entry field of database in a way that once it is executed, the
database is exposed to an attacker for the attack. This technique is usually used for
attacking data-driven applications to have access to sensitive data and perform
administrative tasks on databases.
For Example,
SELECT column_name(s) FROM table_name WHERE condition;

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


Answer: SQL Sandbox is a safe place in the SQL server environment where untrusted
scripts are executed. There are 3 types of SQL sandbox:
 Safe Access Sandbox: Here a user can perform SQL operations such as creating
stored procedures, triggers etc. but cannot have access to the memory as well as
cannot create files.
 External Access Sandbox: Users can access files without having the right to
manipulate the memory allocation.
 Unsafe Access Sandbox: This contains untrusted codes where a user can have
access to memory.
Q #19) What is the difference between SQL and PL/SQL?
Answer: SQL is a Structured Query Language to create and access databases whereas
PL/SQL comes with procedural concepts of programming languages.
Q #20) What is the difference between SQL and MySQL?
Answer: SQL is a Structured Query Language that is used for manipulating and accessing
the relational database. On the other hand, MySQL itself is a relational database that uses
SQL as the standard database language.
Q #21) What is the use of the NVL function?
Answer: NVL function is used to convert the null value to its actual value.
Q #22) What is the Cartesian product of the table?
Answer: The output of Cross Join is called a Cartesian product. It returns rows combining
each row from the first table with each row of the second table. For Example, if we join two
tables having 15 and 20 columns the Cartesian product of two tables will be 15×20=300
rows.
Q #23) What do you mean by Subquery?
Answer: Query within another query is called as Subquery. A subquery is called inner
query which returns output that is to be used by another query.
Q #24) How many row comparison operators are used while working with a
subquery?
Answer: There are 3-row comparison operators that are used in subqueries such as IN,
ANY and ALL.
Q #25) What is the difference between clustered and non-clustered indexes?
Answer: The differences between the two are as follows:
 One table can have only one clustered index but multiple non-clustered indexes.
 Clustered indexes can be read rapidly rather than non-clustered indexes.
 Clustered indexes store data physically in the table or view whereas, non-clustered
indexes do not store data in the table as it has separate structure from the data row.
Q #26) What is the difference between DELETE and TRUNCATE?
Answer: The differences are:
 The basic difference in both is DELETE command is DML command and the
TRUNCATE command is DDL.
 DELETE command is used to delete a specific row from the table whereas the
TRUNCATE command is used to remove all rows from the table.
 We can use the DELETE command with WHERE clause but cannot use the
TRUNCATE command with it.
Q #27) What is the difference between DROP and TRUNCATE?
Answer: TRUNCATE removes all rows from the table which cannot be retrieved back,
DROP removes the entire table from the database and it also cannot be retrieved back.
Q #28) How to write a query to show the details of a student from Students table
whose
name start with K?
Answer: Query:
SELECT * FROM Student WHERE Student_Name like ‘K%’;

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

Q #29) What is the difference between Nested Subquery and Correlated Subquery?
Answer: Subquery within another subquery is called Nested Subquery.  If the output of a
subquery depends on column values of the parent query table then the query is called
Correlated Subquery.
SELECT adminid(SELEC Firstname+' '+Lastname  FROM Employee WHERE

 empid=emp. adminid)AS EmpAdminId FROM Employee;

The result of the query is the details of an employee from the Employee table.

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


Answer: Normalization is used to organize the data in such a manner that data redundancy
will never occur in the database and avoid insert, update and delete anomalies.
There are 5 forms of Normalization:
 First Normal Form (1NF): It removes all duplicate columns from the table. It creates
a table for related data and identifies unique column values.
 First Normal Form (2NF): Follows 1NF and creates and places data subsets in an
individual table and defines the relationship between tables using the primary key.
 Third Normal Form (3NF): Follows 2NF and removes those columns which are not
related through the primary key.
 Fourth Normal Form (4NF): Follows 3NF and does not define multi-valued
dependencies. 4NF is also known as BCNF.
Q #31) What is a Relationship? How many types of Relationships are there?
Answer: The relationship can be defined as the connection between more than one table in
the database.
There are 4 types of relationships:
 One to One Relationship
 Many to One Relationship
 Many to Many Relationship
 One to Many Relationship
Q #32) What do you mean by Stored Procedures? How do we use it?
Answer: A stored procedure is a collection of SQL statements that can be used as a
function to access the database. We can create these stored procedures earlier before
using it and can execute them wherever required by applying some conditional logic to it.
Stored procedures are also used to reduce network traffic and improve performance.
Syntax:
CREATE Procedure Procedure_Name

 (

 //Parameters

 )

 AS
 BEGIN

 SQL statements in stored procedures to update/retrieve records

 END

Q #33) State some properties of Relational databases?


Answer: Properties are as follows:
 In relational databases, each column should have a unique name.
 The sequence of rows and columns in relational databases is insignificant.
 All values are atomic and each row is unique.
Q #34) What are Nested Triggers?
Answer: Triggers may implement data modification logic by using INSERT, UPDATE, and
DELETE statements. These triggers that contain data modification logic and find other
triggers for data modification are called Nested Triggers.
Q #35) What is a Cursor?
Answer: A cursor is a database object which is used to manipulate data in a row-to-row
manner.
Cursor follows steps as given below:
 Declare Cursor
 Open Cursor
 Retrieve row from the Cursor
 Process the row
 Close Cursor
 Deallocate Cursor
Q #36) What is Collation?
Answer: Collation is a set of rules that check how the data is sorted by comparing it. Such
as character data is stored using correct character sequence along with case sensitivity,
type, and accent.
Q #37) What do we need to check in Database Testing?
Answer: In Database testing, the following thing is required to be tested:
 Database connectivity
 Constraint check
 Required application field and its size
 Data Retrieval and processing with DML operations
 Stored Procedures
 Functional flow
Q #38) What is Database White Box Testing?
Answer: Database White Box testing involves:
 Database Consistency and ACID properties
 Database triggers and logical views
 Decision Coverage, Condition Coverage, and Statement Coverage
 Database Tables, Data Model, and Database Schema
 Referential integrity rules
Q #39) What is Database Black Box Testing?
Answer: Database Black Box testing involves:
 Data Mapping
 Data stored and retrieved
 Use of Black Box testing techniques such as Equivalence Partitioning and Boundary
Value Analysis (BVA)
Q #40) What are Indexes in SQL?
Answer: The index can be defined as the way to retrieve the data more quickly. We can
define indexes using CREATE statements.
Syntax:
CREATE INDEX index_name

 ON table_name (column_name)

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

CREATE UNIQUE INDEX index_name

 ON table_name (column_name)

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


Q #41) What does SQL stand for?
Answer: SQL stands for Structured Query Language.
Q #42) How to select all records from the table?
Answer: To select all the records from the table we need to use the following syntax:
Select * from table_name;

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


Answer: Join keyword is used to fetch data from two or more related tables. It returns rows
where there is at least one match in both the tables included in the join. Read more here.
Type of joins are:
1. Right join
2. Outer join
3. Full join
4. Cross join
5. Self join.
Q #44) What is the syntax to add a record to a table?
Answer: To add a record in a table INSERT syntax is used.
For Example,
INSERT into table_name VALUES (value1, value2..);

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


Answer: To add another column in the table, use the following command:
ALTER TABLE table_name ADD (column_name);

Recommended reading =>> How to add a column to a table in MySQL


Q #46) Define the SQL DELETE statement.
Answer: DELETE is used to delete a row or rows from a table based on the specified
condition.
The basic syntax is as follows:
DELETE FROM table_name
WHERE <Condition>

Q #47) Define COMMIT?


Answer: COMMIT saves all changes made by DML statements.
Q #48) What is the Primary key?
Answer: A Primary key is a column whose values uniquely identify every row in a table.
Primary key values can never be reused.
Q #49) What are Foreign keys?
Answer: When a table’s primary key field is added to related tables in order to create the
common field which relates the two tables, it called a foreign key in other tables. Foreign
key constraints enforce referential integrity.
Q #50) What is CHECK Constraint?
Answer: A CHECK constraint is used to limit the values or type of data that can be stored
in a column. They are used to enforce domain integrity.
Q #51) Is it possible for a table to have more than one foreign key?
Answer: Yes, a table can have many foreign keys but only one primary key.
Q #52) What are the possible values for the BOOLEAN data field?
Answer: For a BOOLEAN data field, two values are possible: -1(true) and 0(false).
Q #53) What is a stored procedure?
Answer: A stored procedure is a set of SQL queries that can take input and send back
output.
Q #54) What is identity in SQL?
Answer: An identity column in where SQL automatically generates numeric values. We can
define a start and increment value of the identity column.
Q #55) What is Normalization?
Answer: The process of table design to minimize the data redundancy is called
normalization. We need to divide a database into two or more table and define the
relationship between them.
Q #56) What is a Trigger?
Answer: The Trigger allows us to execute a batch of SQL code when table event occurs
(INSERT, UPDATE or DELETE commands are executed against a specific table).
Q #57) How to select random rows from a table?
Answer: Using a SAMPLE clause we can select random rows.
For Example,
SELECT * FROM table_name SAMPLE(10);

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


Answer: By default SQL Server runs on port 1433.
Q #59) Write a SQL SELECT query that only returns each name only once from a
table?
Answer: To get the result as each name only once, we need to use the DISTINCT
keyword.
SELECT DISTINCT name FROM table_name;

Q #60) Explain DML and DDL?


Answer: DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE 
are DML statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL
statements.

Q #61) Can we rename a column in the output of the SQL query?


Answer: Yes, using the following syntax we can do this.
SELECT column_name AS new_name FROM table_name;

Q #62) Give the order of SQL SELECT?


Answer: Order of SQL SELECT clauses is: SELECT, FROM, WHERE, GROUP BY,
HAVING, ORDER BY. Only the SELECT and FROM clauses are mandatory.
Q #63) Suppose a Student column has two columns, Name and Marks. How to get
names and marks of the top three students.
Answer: SELECT Name, Marks FROM Student s1 where 3 <= (SELECT COUNT(*) FROM
Students s2 WHERE s1.marks = s2.marks)
Q #64) What is SQL comments?
Answer: SQL comments can be inserted by adding two consecutive hyphens (–).
Q #65) Difference between TRUNCATE, DELETE and DROP commands?
Answer:
 DELETE removes some or all rows from a table based on the condition. It can be
rolled back.
 TRUNCATE removes ALL rows from a table by de-allocating the memory pages.
The operation cannot be rolled back
 DROP command removes a table from the database completely.
Q #66) What are the properties of a transaction?
Answer: Generally, these properties are referred to as ACID properties. They are:
1. Atomicity
2. Consistency
3. Isolation
4. Durability.
Q #67) What do you mean by ROWID?
Answer: It’s an 18 character long pseudo column attached with each row of a table.
Q #68) Define UNION, MINUS, UNION ALL, INTERSECT?
Answer:
 MINUS – returns all distinct rows selected by the first query but not by the second.
 UNION – returns all distinct rows selected by either query
 UNION ALL – returns all rows selected by either query, including all duplicates.
 INTERSECT – returns all distinct rows selected by both queries.
Q #69) What is a transaction?
Answer: A transaction is a sequence of code that runs against a database. It takes the
database from one consistent state to another.
Q #70) What is the difference between UNIQUE and PRIMARY KEY constraints?
Answer: The differences are as follows:
 A table can have only one PRIMARY KEY whereas there can be any number of
UNIQUE keys.
 The primary key cannot contain Null values whereas the Unique key can contain Null
values.
Q #71) What is a composite primary key?
Answer: The primary key created on more than one column is called composite primary
key.
Q #72) What is an Index?
Answer: An Index is a special structure associated with a table to speed up the
performance of queries. The index can be created on one or more columns of a table.
Q #73) What is the Subquery?
Answer: A Subquery is a subset of select statements whose return values are used in
filtering conditions of the main query.
Q #74) What do you mean by query optimization?
Answer: Query optimization is a process in which a database system compares different
query strategies and select the query with the least cost.
Q #75) What is Collation?
Answer: Set of rules that define how data is stored, how case-sensitivity and Kana
character can be treated etc.
Q #76) What is Referential Integrity?
Answer: Set of rules that restrict the values of one or more columns of the tables based on
the values of the primary key or unique key of the referenced table.
Q #77) What is the Case function?
Answer: Case facilitates if-then-else type of logic in SQL. It evaluates a list of conditions
and returns one of the multiple possible result expressions.
Q #78) Define a temp table?
Answer: A temp table is a temporary storage structure to store the data temporarily.
Q #79) How can we avoid duplicating records in a query?
Answer: By using the DISTINCT keyword, duplication of records in a query can be avoided.
Q #80) Explain the difference between Rename and Alias?
Answer: Rename is a permanent name given to a table or column whereas Alias is a
temporary name given to a table or column.
Q #81) What is a View?
Answer: A view is a virtual table that contains data from one or more tables. Views restrict
data access of the table by selecting only required values and make complex queries easy.
Q #82) What are the advantages of Views?
Answer: Advantages of Views are:
 Views restrict access to the data because the view can display selective columns
from the table.
 Views can be used to make simple queries to retrieve the results of complicated
queries. For Example, views can be used to query information from multiple tables
without the user knowing.
Q #83) List the various privileges that a user can grant to another user?
Answer:  SELECT, CONNECT, RESOURCES.
Q #84) What is schema?
Answer: A schema is a collection of database objects of a User.
Q #85) What is a Table?
Answer: A table is the basic unit of data storage in the database management system.
Table data is stored in rows and columns.
Q #86) Does View contain Data?
Answer: No, Views are virtual structures.
Q #87) Can a View based on another View?
Answer: Yes, A View is based on another View.
Q #88) What is the difference between the HAVING clause and WHERE clause?
Answer: Both specify a search condition but Having clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaved like WHERE clause only.
Q #89) What is the difference between Local and Global temporary tables?
Answer: If defined inside a compound statement a local temporary table exists only for the
duration of that statement but a global temporary table exists permanently in the DB but its
rows disappear when the connection is closed.
Q #90) What is CTE?
Answer: A CTE or common table expression is an expression that contains temporary
result set which is defined in a SQL statement.
Conclusion
SQL is an essential component of the database system. Having well-versed knowledge of
database along with SQL concepts will definitely be beneficial to crack the interview for the
concerned profile.

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

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

You might also like