100 SQL Interview Questions and Answers
100 SQL Interview Questions and Answers
com
hirist
.com
TOP 100
SQL
hirist
.com
QUESTION 1
QUESTION
What is DBMS?
ANSWER
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.
hirist
.com
QUESTION 2
QUESTION
What is RDBMS?
ANSWER
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.
hirist
.com
QUESTION 3
QUESTION
What is SQL?
ANSWER
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.
hirist
.com
QUESTION 4
QUESTION
What is a Database?
ANSWER
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.
hirist
.com
QUESTION 5
QUESTION
What are tables and Fields?
ANSWER
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.
hirist
.com
QUESTION 6
QUESTION
What is a primary key?
ANSWER
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.
hirist
.com
QUESTION 7
QUESTION
What is a unique key?
ANSWER
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.
hirist
.com
QUESTION 8
QUESTION
What is a foreign key?
ANSWER
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.
hirist
.com
QUESTION 9
QUESTION
What are the types of join and explain each?
ANSWER
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.
10
hirist
.com
QUESTION 10
QUESTION
Explain an outer join?
ANSWER
An outer join includes rows from tables when there are no matching values in the tables.
11
hirist
.com
QUESTION 11
QUESTION
What is normalization?
ANSWER
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
hirist
.com
QUESTION 12
QUESTION
What is Denormalization?
ANSWER
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
hirist
.com
QUESTION 13
QUESTION
What are all the different normalizations?
ANSWER
The normal forms can be divided into 4 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 multivalued dependencies.
14
hirist
.com
QUESTION 14
QUESTION
What is an Index? What are all the different types of indexes?
ANSWER
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.
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.
Non Clustered Index: Non Clustered Index does not alter the physical order of the table and maintains logical
order of data. Each table can have 999 non clustered indexes.
15
hirist
.com
QUESTION 15
QUESTION
What is a relationship and what are they?
ANSWER
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.
16
hirist
.com
QUESTION 16
QUESTION
What is a query?
ANSWER
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.
17
hirist
.com
QUESTION 17
QUESTION
What is subquery? What are the types of subquery?
ANSWER
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.
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.
18
hirist
.com
QUESTION 18
QUESTION
What is a trigger?
ANSWER
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.
19
hirist
.com
QUESTION 19
QUESTION
What are the types of Triggers?
ANSWER
There are four types of triggers and they are:
Insert
Delete
Update
Instead of
20
hirist
.com
QUESTION 20
QUESTION
What is the difference between DELETE TRUNCATE and DROP commands?
ANSWER
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.
Drop command is used to drop the table or keys like primary, foreign from a table.
21
hirist
.com
QUESTION 21
QUESTION
What is data Integrity?
ANSWER
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.
22
hirist
.com
QUESTION 22
QUESTION
What is collation?
ANSWER
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.
23
hirist
.com
QUESTION 23
QUESTION
Advantages and Disadvantages of Stored Procedure?
ANSWER
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.
24
hirist
.com
QUESTION 24
QUESTION
What is SQL Injection ?
ANSWER
SQL Injection is one of the techniques uses by hackers to hack a website by injecting SQL commands in data fields.
25
hirist
.com
QUESTION 25
QUESTION
What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
ANSWER
They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only
with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used,
HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a
query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.
26
hirist
.com
QUESTION 26
QUESTION
How would apply date range filter?
ANSWER
a. You can use simple condition >= and <= or similar or use between/and but the trick is to know your exact data
type.
b. Sometimes date fields contain time and that is where the query can go wrong so it is recommended to use some
date related functions to remove the time issue. In SQL Server common function to do that is datediff function.
c. You also have to be aware of different time zones and server time zone.
d. To increase query performance you may still want to use between however you should be aware of proper format
you should use if not it might misbehave during filtering.
27
hirist
.com
QUESTION 27
QUESTION
What is the difference between JOIN and UNION?
ANSWER
SQL JOIN allows us to lookup records on other table based on the given conditions between two tables. For
example, if we have the department ID of each employee, then we can use this department ID of the employee
table to join with the department ID of department table to lookup department names.
UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the
source data sets. Union does not require any condition for joining. For example, if you have 2 employee tables
with same structure, you can UNION them to create one result set that will contain all the employees from both of
the tables.
SELECT * FROM EMP1
UNION
SELECT * FROM EMP2;
28
hirist
.com
QUESTION 28
QUESTION
What is the difference among UNION, MINUS and INTERSECT?
ANSWER
UNION combines the results from 2 tables and eliminates duplicate records from the result set.
MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which are
present in the second table.
INTERSECT operator returns us only the matching or common rows between 2 result sets.
29
hirist
.com
QUESTION 29
QUESTION
What is Self Join and why is it required?
ANSWER
Self Join is the act of joining one table with itself. Self Join is often very useful to convert a hierarchical structure into
a flat structure
30
hirist
.com
QUESTION 30
QUESTION
How can we transpose a table using SQL (changing rows to column or vice-versa)?
ANSWER
The usual way to do it in SQL is to use CASE statement or DECODE statement.
31
hirist
.com
QUESTION 31
QUESTION
What are the differences among ROWNUM, RANK and DENSE_RANK?
ANSWER
ROW_NUMBER assigns contiguous, unique numbers from 1.. N to a result set.
RANK does not assign unique numbersnor does it assign contiguous numbers. If two records tie for second
place, no record will be assigned the 3rd rank as no one came in third, according to RANK.
DENSE_RANK, like RANK, does not assign unique numbers, but it does assign contiguous numbers. Even though
two records tied for second place, there is a third-place record.
32
hirist
.com
QUESTION 32
QUESTION
What is a database transaction?
ANSWER
Database transaction take database from one consistent state to another. At the end of the transaction the system
must be in the prior state if transaction fails or the status of the system should reflect the successful completion if
the transaction goes through.
33
hirist
.com
QUESTION 33
QUESTION
What are properties of a transaction?
ANSWER
Properties of the transaction can be summarized as ACID Properties.
1. Atomicity: A transaction consists of many steps. When all the steps in a transaction gets completed, it will get
reflected in DB or if any step fails, all the transactions are rolled back.
2. Consistency: The database will move from one consistent state to another, if the transaction succeeds and
remain in the original state, if the transaction fails.
3. Isolation: Every transaction should operate as if it is the only transaction in the system
4. Durability: Once a transaction has completed successfully, the updated rows/records must be available for all
other transactions on a permanent basis
34
hirist
.com
QUESTION 34
QUESTION
What is a Database Lock? What are the type of locks?
ANSWER
Database lock tell a transaction, if the data item in questions is currently being used by other transactions.
1. Shared Lock: When a shared lock is applied on data item, other transactions can only read the item, but can't
write into it.
2. Exclusive Lock: When a exclusive lock is applied on data item, other transactions can't read or write into the data
item.
35
hirist
.com
QUESTION 35
QUESTION
What is a Composite Key?
ANSWER
A Composite primary key is a type of candidate key, which represents a set of columns whose values uniquely
identify every row in a table.
For example - if "Employee_ID" and "Employee Name" in a table is combined to uniquely identifies a row its called
a Composite Key.
36
hirist
.com
QUESTION 36
QUESTION
What is a Composite Primary Key?
ANSWER
A Composite primary key is a set of columns whose values uniquely identify every row in a table. What it means is
that, table which contains composite primary key will be indexed based on columns specified in the primary key.
This key will be referred in Foreign Key tables.
For example - if combined effect of columns, "Employee_ID" and "Employee Name" in a table is required to uniquely
identifies a row, its called a Composite Primary Key. In this case, both the columns will be represented as primary
key.
37
hirist
.com
QUESTION 37
QUESTION
Define SQL Insert Statement?
ANSWER
SQL INSERT statement is used to add rows to a table. For a full row insert, SQL Query should start with insert into
statement followed by table name and values command, followed by the values that need to be inserted into the
table. Insert can be used in several ways:
1. To insert a single complete row
2. To insert a single partial row
38
hirist
.com
QUESTION 38
QUESTION
Define SQL Update Statement?
ANSWER
SQL Update is used to update data in a row or set of rows specified in the filter condition.
The basic format of an SQL UPDATE statement is ,Update command followed by table to be updated and SET
command followed by column names and their new values followed by filter condition that determines which rows
should be updated.
39
hirist
.com
QUESTION 39
QUESTION
What are wild cards used in database for Pattern Matching?
ANSWER
SQL Like operator is user for pattern matching. SQL 'Like' command takes more time to process. So before using
like operator, consider suggestions given below on when and where to use wild card search.
1) Don't overuse wild cards. If another search operator will do, use it instead.
2) When you do use wild cards, try not to use them at the beginning of the search pattern, unless absolutely
necessary. Search patterns that begin with wild cards are the slowest to process.
3) Pay careful attention to the placement of the wild card symbols. If they are misplaced, you might not return the
data you intended
40
hirist
.com
QUESTION 40
QUESTION
What is Cross Join?
ANSWER
Cross Join will return all records where each row from the first table is combined with each row from the second
table.
41
hirist
.com
QUESTION 41
QUESTION
What is a view?
ANSWER
Views are virtual tables. Unlike tables that contain data, views simply contain queries that dynamically retrieve data
when used.
42
hirist
.com
QUESTION 42
QUESTION
What is a materialized view?
ANSWER
Materialized views is also a view but are disk based. Materialized views get updated on specific duration, base upon
the interval specified in the query definition. We can index materialized view.
43
hirist
.com
QUESTION 43
QUESTION
What are the advantages and disadvantages of views in a database?
ANSWER
Advantages:
1. Views doesn't store data in a physical location.
2. View can be use to hide some of the columns from the table
3. Views can provide Access Restriction, since data insertion, update and deletion is not possible on the view.
Disadvantages:
1. When a table is dropped, associated view become irrelevant.
2. Since view are created when a query requesting data from view is triggered, its bit slow
3. When views are created for large tables, it occupy more memory.
44
hirist
.com
QUESTION 44
QUESTION
When do you use UPDATE_STATISTICS command?
ANSWER
This command is used when a large processing of data has occurred. If any large amount of deletions, any
modifications, or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into
account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
45
hirist
.com
QUESTION 45
QUESTION
What is an IDENTITY column in insert statements?
ANSWER
IDENTITY column is used in table columns to make that column as Auto incremental number or a surrogate key.
46
hirist
.com
QUESTION 46
QUESTION
How will I retrieve all records of employment 1 those should not be present n
employment 2?
ANSWER
(Select * from employment 2)-(Select * from employment 1).
47
hirist
.com
QUESTION 47
QUESTION
Which TCP/IP port does SQL Server run on? How can it be changed?
ANSWER
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties.
48
hirist
.com
QUESTION 48
QUESTION
What is SQL Server Agent?
ANSWER
SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). Its purpose is
to ease the implementation of tasks for the DBA, with its full- function scheduling engine, which allows you to
schedule your own jobs and scripts.
49
hirist
.com
QUESTION 49
QUESTION
Which command using Query Analyzer will give you the version of SQL server and
operating system?
ANSWER
SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel') and SERVERPROPERTY
('edition')
50
hirist
.com
QUESTION 51
QUESTION
How to create recursive query in SQL Server?
ANSWER
Recursive query can be create in SQL using stored procedure but you can also use CTE (Common table
expression). It might be also worth asking about performance as CTE is not always very fast.
51
hirist
.com
QUESTION 51
QUESTION
What is a constraint?
ANSWER
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.
52
hirist
.com
QUESTION 52
QUESTION
What is Auto Increment?
ANSWER
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.
53
hirist
.com
QUESTION 53
QUESTION
What is Datawarehouse?
ANSWER
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.
54
hirist
.com
QUESTION 54
QUESTION
What is user defined functions?
ANSWER
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.
55
hirist
.com
QUESTION 55
QUESTION
What are all types of user defined functions?
ANSWER
Three types of user defined functions are.
a. Scalar Functions.
b. Inline Table valued functions.
c. Multi statement valued functions.
56
hirist
.com
QUESTION 56
QUESTION
What are all different types of collation sensitivity?
ANSWER
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.
57
hirist
.com
QUESTION 57
QUESTION
What is Online Transaction Processing (OLTP)?
ANSWER
Online Transaction Processing or OLTP manages transaction based applications which can be used for data entry
and easy retrieval processing of data. This processing makes like easier on simplicity and efficiency. It is faster,
more accurate results and expenses with respect to OTLP.
Example Bank Transactions on a daily basis.
58
hirist
.com
QUESTION 58
QUESTION
What is an ALIAS command?
ANSWER
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.
59
hirist
.com
QUESTION 59
QUESTION
What are aggregate and scalar functions?
ANSWER
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.
60
hirist
.com
QUESTION 60
QUESTION
How can you create an empty table from an existing table?
ANSWER
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.
61
hirist
.com
QUESTION 61
QUESTION
How to fetch common records from two tables?
ANSWER
Common records result set can be achieved by -.
Select studentID from student. <strong>INTERSECT </strong> Select StudentID from Exam
62
hirist
.com
QUESTION 62
QUESTION
How to select unique records from a table?
ANSWER
Select unique records from a table by using DISTINCT keyword.
Select DISTINCT StudentID, StudentName from Student.
63
hirist
.com
QUESTION 63
QUESTION
What are the different index configurations a table can have?
ANSWER
A table can have one of the following index configurations:
1. No indexes
2. A clustered index
3. A clustered index and many nonclustered indexes
4. A nonclustered index
5. Many nonclustered indexes
64
hirist
.com
QUESTION 64
QUESTION
What are the properties and different Types of Sub-Queries?
ANSWER
Properties of Sub-Query
a. A sub-query must be enclosed in the parenthesis.
b. A sub-query must be put in the right hand of the comparison operator, and
c. A sub-query cannot contain an ORDER-BY clause.
d. A query can contain more than one sub-query.
Types of Sub-Query
e. Single-row sub-query, where the sub-query returns only one row.
f. Multiple-row sub-query, where the sub-query returns multiple rows,. and
g. Multiple column sub-query, where the sub-query returns multiple columns
65
hirist
.com
QUESTION 65
QUESTION
What is SQL Profiler?
ANSWER
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL
Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For
example, you can monitor a production environment to see which stored procedures are hampering performances
by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can
filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too
many events adds overhead to the server and the monitoring process and can cause the trace file or trace table
to grow very large, especially when the monitoring process takes place over a long period of time.
66
hirist
.com
QUESTION 66
QUESTION
What are the authentication modes in SQL Server? How can it be changed?
ANSWER
Windows mode and Mixed Mode - SQL and Windows. 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. Select the server then from the Tools menu select SQL Server
Configuration Properties, and choose the Security page.
67
hirist
.com
QUESTION 67
QUESTION
Can a stored procedure call itself or recursive stored procedure? How much level
SP nesting is possible?
ANSWER
Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion
can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to
subsets of the problem. A common application of recursive logic is to perform numeric computations that lend
themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored
procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can
nest stored procedures and managed code references up to 32 levels.
68
hirist
.com
QUESTION 68
QUESTION
What is Log Shipping?
ANSWER
Log shipping is the process of automating the backup of database and transaction log files on a production SQL
server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log
shipping the transactional log file from one server is automatically updated into the backup database on the other
server. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery
plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and
automatically restore them on the standby server at defined interval.
69
hirist
.com
QUESTION 69
QUESTION
Name 3 ways to get an accurate count of the number of records in a table?
ANSWER
SELECT * FROM table1
SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
70
hirist
.com
QUESTION 70
QUESTION
What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of
having it OFF?
ANSWER
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must
be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted
and must follow all Transact-SQL rules for identifiers.
71
hirist
.com
QUESTION 71
QUESTION
What is the difference between a Local and a Global temporary table?
ANSWER
1. A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for
the duration of the compound statement.
2. A global temporary table remains in the database permanently, but the rows exist only within a given connection.
When connection is closed, the data in the global temporary table disappears. However, the table definition
remains with the database for access when database is opened next time.
72
hirist
.com
QUESTION 72
QUESTION
How Global temporary tables are represented and its scope?
ANSWER
Global temporary tables are represented with ## before the table name. Scope will be the outside the session
whereas local temporary tables are inside the session. Session ID can be found using @@SPID.
73
hirist
.com
QUESTION 73
QUESTION
What is the STUFF function and how does it differ from the REPLACE function?
ANSWER
STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length,
replacement_characters), string_expression is the string that will have characters substituted, start is the starting
position, length is the number of characters in the string that are substituted, and replacement_characters are the
new characters interjected into the string. REPLACE function to replace existing characters of all occurrences.
Using the syntax REPLACE (string_expression, search_string, replacement_string), where every incidence of
search_string found in the string_expression will be replaced with replacement_string.
74
hirist
.com
QUESTION 74
QUESTION
What is CHECK Constraint?
ANSWER
A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to
enforce domain integrity.
75
hirist
.com
QUESTION 75
QUESTION
What is the difference between UNION and UNION ALL?
ANSWER
UNION statement is mainly used to combine the tables including the duplicate rows and UNION ALL combine but
does not look for duplicate rows. With this, UNION ALL will be very faster than UNION statements.
76
hirist
.com
QUESTION 76
QUESTION
What is NOT NULL Constraint?
ANSWER
A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to
enforce domain integrity, as the check constraints.
77
hirist
.com
QUESTION 77
QUESTION
How to get @@ERROR and @@ROWCOUNT at the same time?
ANSWER
If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it
would have been reset. And if @@Recordcount is checked before the error-checking statement then @@Error
would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them
in local variable.
78
hirist
.com
QUESTION 78
QUESTION
What is a Scheduled Jobs or What is a Scheduled Tasks?
ANSWER
Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule
administrative tasks, such as cube processing, to run during times of slow business activity. User can also
determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up
database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user can
configure SQL Server Agent to continue to run the remaining tasks or to stop execution.
79
hirist
.com
QUESTION 79
QUESTION
What is a table called, if it has neither Cluster nor Non-cluster Index? What is it
used for?
ANSWER
Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A heap is a table that
does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only
structures that link the pages in a table together. Unindexed tables are good for fast storing of data. Many times it
is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that.
80
hirist
.com
QUESTION 80
QUESTION
Can SQL Servers linked to other servers like Oracle?
ANSWER
SQL Server can be linked to any server provided it has OLE-DB provider from Microsoft to allow a link. E.g. Oracle
has an OLE-DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group.
81
hirist
.com
QUESTION 81
QUESTION
What is BCP? When does it used?
ANSWER
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures
same as source to destination. BULK INSERT command helps to import a data file into a database table or view
in a user-specified format.
82
hirist
.com
QUESTION 82
QUESTION
How to implement one-to-one, one-to-many and many-to-many relationships while
designing tables?
ANSWER
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key
relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key
and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys
from both the tables forming the composite primary key of the junction table.
83
hirist
.com
QUESTION 83
QUESTION
What is an execution plan? When would you use it? How would you view the
execution plan?
ANSWER
An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by
the SQL Server query optimizer for a stored procedure or ad- hoc query and is a very useful tool for a developer
to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL
Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an
option called "Show Execution Plan" (located on the Query drop-down menu). If this option is turned on it will
display query execution plan in separate window when query is ran again.
84
hirist
.com
QUESTION 84
QUESTION
What are the two authentication modes in SQL Server?
ANSWER
There are two authentication modes
Windows Mode
Mixed Mode
Modes can be changed by selecting the tools menu of SQL Server configuration properties and choose security
page.
85
hirist
.com
QUESTION 85
QUESTION
What is COALESCE in SQL Server?
ANSWER
COALESCE is used to return first non-null expression within the arguments. This function is used to return a nonnull from more than one column in the arguments.
Example
Select COALESCE(empno, empname, salary) from employee;
86
hirist
.com
QUESTION 86
QUESTION
How exceptions can be handled in SQL Server Programming?
ANSWER
Exceptions are handled using TRY-CATCH constructs and it is handles by writing scripts inside the TRY block
and error handling in the CATCH block.
87
hirist
.com
QUESTION 87
QUESTION
What is the purpose of FLOOR function?
ANSWER
FLOOR function is used to round up a non-integer value to the previous least integer. Example is given FLOOR(6.7)
Returns 6.
88
hirist
.com
QUESTION 88
QUESTION
Can we check locks in database? If so, how can we do this lock check?
ANSWER
Yes, we can check locks in the database. It can be achieved by using in-built stored procedure called sp_lock.
89
hirist
.com
QUESTION 89
QUESTION
What is the use of SIGN function?
ANSWER
SIGN function is used to determine whether the number specified is Positive, Negative and Zero. This will return
+1,-1 or 0.
Example: SIGN(-35) returns -1
90
hirist
.com
QUESTION 90
QUESTION
How is the SUBSTR keyword used in SQL?
ANSWER
SUBSTR is used for string manipulation with column name, first position and string length used as arguments. E.g.
SUBSTR (NAME, 1 3) refers to the first three characters in the column NAME.
91
hirist
.com
QUESTION 91
QUESTION
What is a NULL value? What are the pros and cons of using NULLS?
ANSWER
A NULL value takes up one byte of storage and indicates that a value is not present as opposed to a space or zero
value. It's the DB2 equivalent of TBD on an organizational chart and often correctly portrays a business situation.
Unfortunately, it requires extra coding for an application program to handle this situation.
92
hirist
.com
QUESTION 92
QUESTION
What is a synonym? How is it used?
ANSWER
A synonym is used to reference a table or view by another name. The other name can then be written in the
application code pointing to test tables in the development stage and to production entities when the code is
migrated. The synonym is linked to the AUTHID that created it.
93
hirist
.com
QUESTION 93
QUESTION
What is a Cartesian product?
ANSWER
A Cartesian product results from a faulty query. It is a row in the results for every combination in the join tables.
94
hirist
.com
QUESTION 94
QUESTION
What is a tuple?
ANSWER
Static SQL is compiled and optimized prior to its execution; dynamic is compiled and optimized during execution.
95
hirist
.com
QUESTION 95
QUESTION
What is referential integrity?
ANSWER
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every
foreign key value must have a corresponding primary key value.
96
hirist
.com
QUESTION 96
QUESTION
Whats the maximum size of a row?
ANSWER
8060 bytes.
97
hirist
.com
QUESTION 97
QUESTION
How to change Database name in SQL server?
ANSWER
Use the following code:
Supported in SQL server 2000 and 2005
Exec sp_renamedb test, test1
Supported in SQL Server 2005 and later version
ALTER Database test1 Modify Name = test
98
hirist
.com
QUESTION 98
QUESTION
What is a Cursor?
ANSWER
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.
99
hirist
.com
QUESTION 99
QUESTION
What are Magic Tables in SQL Server?
ANSWER
Insert and Delete tables are created when the trigger is fired for any DML command. Those tables are called Magic
Tables in SQL Server. These magic tables are used inside the triggers for data transaction.
100
hirist
.com
QUESTION 100
QUESTION
What is ISNULL() operator?
ANSWER
ISNULL function is used to check whether value given is NULL or not NULL in sql server. This function also provides
to replace a value with the NULL.
101
hirist
.com
Resources
http://www.itechaleart.com/2013/05/top-50-sql-question-answers_11.html
https://www.katieandemil.com/sql-interview-questions-andanswers?tab=article#Question 4
http://www.dwbiconcepts.com/tutorial/24-interview-questions/190-top-20-sqlinterview-questions-with-answers.html
http://a4academics.com/interview-questions/53-database-and-sql/411-sqlinterview-questions-and-answers-database
http://narendra86.blogspot.com/2013/10/top-80-sql-query-interviewquestions.html
http://crackaninterview.com/sql-queries-interview-questions-answers/
http://career.guru99.com/top-50-sql-question-answers/
http://www.indiabix.com/technical/sql-server-common-questions/
http://career.guru99.com/top-50-sql-server-questions-answers/
http://www.ittestpapers.com/sql-interview-questions(25-50).html
http://www.dotnetfunda.com/interviews/cat/8/sql-server
http://www.careerride.com/SQLServer-Interview-Questions.aspx
102
www.hirist.com
TOP 100
SQL