SQL Interview Questions PDF
SQL Interview Questions PDF
SQL Interview Questions PDF
SQL INTERVIEW
QUESTIONS
&
ANSWERS
1|Page
2|Page
3|Page
4|Page
5|Page
CourseID EnrollNo
1
1000
2
1000
3
1000
1
1002
2
1003
Following is join query that shows names of students enrolled in different courseIDs.
SELECT StudentCourse.CourseID, Student.StudentName
FROM StudentCourse
INNER JOIN Customers
ON StudentCourse.EnrollNo = Student.EnrollNo
ORDER BY StudentCourse.CourseID;
The above query would produce following result.
CourseID StudentName
1
geek1
1
geek2
2
geek1
2
geek3
3
geek1
14.What is Identity?
Ans: Identity (or AutoNumber) is a column that automatically generates numeric values. A
start and increment value can be set, but most DBA leave these at 1. A GUID column also
generates numbers; the value of this cannot be controlled. Identity/GUID columns do not
need to be indexed.
15.What is a view in SQL? How to create one
Ans: A view is a virtual table based on the result-set of an SQL statement. We can create
using create view syntax.
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
16..What are the uses of view?
1. Views can represent a subset of the data contained in a table; consequently, a view can
limit the degree of exposure of the underlying tables to the outer world: a given user may
have permission to query the view, while denied access to the rest of the base table.
6|Page
2. Views can join and simplify multiple tables into a single virtual table
3. Views can act as aggregated tables, where the database engine aggregates data (sum,
average etc.) and presents the calculated results as part of the data
4. Views can hide the complexity of data; for example a view could appear as Sales2000 or
Sales2001, transparently partitioning the actual underlying table.
5. Depending on the SQL engine used, views can provide extra security.
17.What is a Trigger?
Ans: A Trigger is a code that associated with insert, update or delete operations. The code
is executed automatically whenever the associated query is executed on a table. Triggers
can be useful to maintain integrity in database.
18.What is a stored procedure?
Ans: A stored procedure is like a function that contains a set of operations compiled
together. It contains a set of operations that are commonly used in an application to do
some common database tasks.
19.What is the difference between Trigger and Stored Procedure?
Ans: Unlike Stored Procedures, Triggers cannot be called directly. They can only be
associated with queries.
20.What is a transaction? What are ACID properties?
Ans: A Database Transaction is a set of database operations that must be treated as whole,
means either all operations are executed or none of them.
An example can be bank transaction from one account to another account. Either both debit
and credit operations must be executed or none of them.
ACID (Atomicity, Consistency, Isolation, Durability) is a set of properties that guarantee
that database transactions are processed reliably.
21.What are indexes?
Ans: A database index is a data structure that improves the speed of data retrieval
operations on a database table at the cost of additional writes and the use of more storage
space to maintain the extra copy of data.
Data can be stored only in one order on disk. To support faster access according to
different values, faster search like binary search for different values is desired, For this
purpose, indexes are created on tables. These indexes need extra space on disk, but they
allow faster search according to different frequently searched values.
22.What are clustered and non-clustered Indexes?
Ans: Clustered indexes is the index according to which data is physically stored on disk.
Therefore, only one clustered index can be created on a given database table.
Non-clustered indexes dont define physical ordering of data, but logical ordering.
Typically, a tree is created whose leaf point to disk records. B-Tree or B+ tree are used for
this purpose.
7|Page
8|Page
10 | P a g e
12 | P a g e
45.What is Self-Join?
Self-join is query used to join a table to itself. Aliases should be used for the same table
comparison.
46. What is Cross Join?
Cross Join will return all records where each row from the first table is combined with each
row from the second table.
SQL Interview Questions and answers on Database Views
47. What is a view?
Views are virtual tables. Unlike tables that contain data, views simply contain queries that
dynamically retrieve data when used.
48. What is a materialized view?
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.
49. What are the advantages and disadvantages of views in a database?
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 .
SQL Interview Questions and answers on Stored Procedures and Triggers
50. What is a stored procedure?
Stored Procedure is a function which contain collection of SQL Queries. Procedure can take
inputs , process them and send back output.
13 | P a g e
15 | P a g e
16 | P a g e
76. What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about:
Preferring NT authentication, using server, database and application roles to control access
to the data, securing the physical database files using NTFS permissions, using an
unguessable SA password, restricting physical access to the SQL Server, renaming the
Administrator account on the SQL Server computer, disabling the Guest account, enabling
auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL
Server from the web server etc.
77. What is a deadlock and what is a live lock? How will you go about resolving
deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data,
attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the
other to release the lock, unless one of the user processes is terminated. SQL Server detects
deadlocks and terminates one user's process.
A live lock is one, where a request for an exclusive lock is repeatedly denied because a
series of overlapping shared locks keeps interfering. SQL Server detects the situation after
four denials and refuses further shared locks. A live lock also occurs when read
transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
78. What is blocking and how would you troubleshoot it?
Blocking happens when one connection from an application holds a lock and a second
connection requires a conflicting lock type. This forces the second connection to wait,
blocked on the first.
79. Explain CREATE DATABASE syntax
Many of us are used to creating databases from the Enterprise Manager or by just issuing
the command: CREATE DATABAE MyDB. But what if you have to create a database with
two file groups, one on drive C and the other on drive D with log on drive E with an initial
size of 600 MB and with a growth factor of 15%? That's why being a DBA you should be
familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more
information.
80. How to restart SQL Server in single user mode? How to start SQL Server in
minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has
some very important parameters with which a DBA should be familiar with. -m is used for
starting SQL Server in single user mode and -f is used to start the SQL Server in minimal
configuration mode. Check out SQL Server books online for more parameters and their
explanations.
18 | P a g e
81. As a part of your job, what are the DBCC commands that you commonly use for
database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole
load of DBCC commands which are very useful for DBAs. Check out SQL Server books
online for more information.
82. What are statistics, under what circumstances they go out of date, how do you
update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values
then the selectivity of that index is more, as opposed to an index with non-unique values.
Query optimizer uses these indexes in determining whether to choose an index or not
while executing a query.
Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed
(that is, if the distribution of key values has changed), or the table has been truncated using
the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version
83. What are the different ways of moving data/databases between servers and
databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your
requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and
attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO,
creating INSERT scripts to generate data.
84. Explain different types of BACKUPs available in SQL Server? Given a particular
scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Server 7.0+ are Full database backup, differential
database backup, transaction log backup, file group backup. Check out the BACKUP and
RESTORE commands in SQL Server books online. Be prepared to write the commands in
your interview. Books online also has information on detailed backup/restore architecture
and when one should go for a particular kind of backup.
85.What is database replication? What are the different types of replication you can
set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or
different servers. SQL Server supports the following types of replication scenarios:
o Snapshot replication
o Transactional replication (with immediate updating subscribers, with queued updating
subscribers)
o Merge replication
19 | P a g e
86. How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used
to determine the service pack installed. To know more about this process visit
87.What are cursors? Explain different types of cursors. What are the disadvantages
of cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the result sets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more
information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a
network roundtrip, where as a normal SELECT query makes only one rowundtrip, however
large the resultset is. Cursors are also costly because they require more resources and
temporary storage (results in more IO operations). Furthere, there are restrictions on the
SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike
In this situation many developers tend to use a cursor, determine each employee's salary
and update his salary according to the above formula. But the same can be achieved by
multiple update statements or can be combined in a single UPDATE statement as shown
below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
Another situation in which developers tend to use cursors: You need to call a stored
procedure when a column in a particular row meets certain condition. You don't have to
use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key
to identify each row.
88. Write down the general syntax for a SELECT statements covering all the options
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
20 | P a g e
94. There is a trigger defined for INSERT operations on a table, in an OLTP system.
The trigger is written to instantiate a COM object and pass the newly insterted rows
to it for some custom processing. What do you think of this implementation? Can this
be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from
within a trigger, it slows down the data insertion process. Same is the case with sending
emails from triggers. This scenario can be better implemented by logging all the necessary
data into a separate table, and have a job which periodically checks this table and does the
needful.
95. What is a self join? Explain it with an example
Self join is just like any other join, except that two instances of the same table will be joined
in the query. Here is an example: Employees table which contains rows for normal
employees as well as managers. So, to find out the managers of all the employees, you need
a self join.
CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)
INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'
SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid
Here's an advanced query using a LEFT OUTER JOIN that even returns the employees
without managers (super bosses)
SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid
22 | P a g e
23 | P a g e
24 | P a g e
2. 2NF: Eliminate Redundant Data If an attribute depends on only part of a multivalued key, remove it to a separate table.
3. 3NF: Eliminate Columns Not Dependent On Key If attributes do not contribute to
a description of the key, remove them to a separate table. All attributes must be
directly dependent on the primary key.
4. BCNF: Boyce-Codd Normal Form If there are non-trivial dependencies between
candidate key attributes, separate them out into distinct tables.
5. 4NF: Isolate Independent Multiple Relationships No table may contain two or
more 1:n or n:m relationships that are not directly related.
6. 5NF: Isolate Semantically Related Multiple Relationships There may be practical
constrains on information that justify separating logically related many-to-many
relationships.
7. ONF: Optimal Normal Form A model limited to only simple (elemental) facts, as
expressed in Object Role Model notation.
8. DKNF: Domain-Key Normal Form A model free from all modification anomalies is
said to be in DKNF.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it
must first fulfill all the criteria of a 2NF and 1NF database.
116. What is Stored Procedure?
A stored procedure is a named group of SQL statements that have been previously created
and stored in the server database. Stored procedures accept input parameters so that a
single procedure can be used over the network by several clients using different input data.
And when the procedure is modified, all clients automatically get the new version. Stored
procedures reduce network traffic and improve performance. Stored procedures can be
used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.
117. What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or
UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to
maintain the referential integrity of data by changing the data in a systematic fashion. A
trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a
data modification to the associated table. Triggers can be viewed as similar to stored
procedures in that both consist of procedural logic that is stored at the database level.
Stored procedures, however, are not event-drive and are not attached to a specific table as
triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure
while triggers are implicitly executed. In addition, triggers can also execute stored
procedures.
26 | P a g e
28 | P a g e
3. Outer Join A join that includes rows even if they do not have related rows in the
joined table is an Outer Join. You can create three different outer join to specify the
unmatched rows to be included:
1. Left Outer Join: In Left Outer Join all rows in the first-named table i.e. "left"
table, which appears leftmost in the JOIN clause are included. Unmatched
rows in the right table do not appear.
2. Right Outer Join: In Right Outer Join all rows in the second-named table i.e.
"right" table, which appears rightmost in the JOIN clause are included.
Unmatched rows in the left table are not included.
3. Full Outer Join: In Full Outer Join all rows in all joined tables are included,
whether they are matched or not.
4. Self Join This is a particular case when one table joins to itself, with one or two
aliases to avoid confusion. A self join can be of any type, as long as the joined tables
are the same. A self join is rather unique in that it involves a relationship with only
one table. The common example is when company has a hierarchal reporting
structure whereby one member of staff reports to another. Self Join can be Outer
Join or Inner Join.
127. What are primary keys and foreign keys?
Primary keys are the unique identifiers for each row. They must contain unique values and
cannot be null. Due to their importance in relational databases, Primary keys are the most
fundamental of all keys and constraints. A table can have only one Primary key. Foreign
keys are both a method of ensuring data integrity and a manifestation of the relationship
between tables.
128. What is User Defined Functions? What kind of User-Defined Functions can be
created?
User-Defined Functions allow defining its own T-SQL functions that can accept 0 or more
parameters and return a single scalar data value or a table data type.
Different Kinds of User-Defined Functions created are:
1. Scalar User-Defined Function A Scalar user-defined function returns one of the
scalar data types. Text, image and timestamp data types are not supported. These
are the type of user-defined functions that most developers are used to in other
programming languages. You pass in 0 to many parameters and you get a return
value.
2. Inline Table-Value User-Defined Function An Inline Table-Value user-defined
function returns a table data type and is an exceptional alternative to a view as the
user-defined function can pass parameters into a T-SQL select command and in
essence provide us with a parameterized, non-updateable view of the underlying
tables.
3. Multi-statement Table-Value User-Defined Function A Multi-Statement TableValue user-defined function returns a table and is also an exceptional alternative to
a view as the function can support multiple T-SQL statements to build the final
29 | P a g e
result where the view is limited to a single SELECT statement. Also, the ability to
pass parameters into a TSQL select command or a group of them gives us the
capability to in essence create a parameterized, non-updateable view of the data in
the underlying tables. Within the create function command you must define the
table structure that is being returned. After creating this type of user-defined
function, It can be used in the FROM clause of a T-SQL command unlike the behavior
found when using a stored procedure which can also return record sets.
129. What is Identity?
Identity (or AutoNumber) is a column that automatically generates numeric values. A start
and increment value can be set, but most DBA leave these at 1. A GUID column also
generates numbers; the value of this cannot be controlled. Identity/GUID columns do not
need to be indexed.
130. Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP
properties.
131. What are the difference between clustered and a non-clustered index?
1. A clustered index is a special type of index that reorders the way records in the
table are physically stored. Therefore table can have only one clustered index. The
leaf nodes of a clustered index contain the data pages.
2. A non clustered index is a special type of index in which the logical order of the
index does not match the physical stored order of the rows on disk. The leaf node of
a non clustered index does not consist of the data pages. Instead, the leaf nodes
contain index rows.
132. What are the different index configurations a table can have?
A table can have one of the following index configurations:
1.
2.
3.
4.
5.
No indexes
A clustered index
A clustered index and many nonclustered indexes
A non clustered index
Many non clustered indexes
4.
5.
6.
7.
Note: DELETE and TRUNCATE both can be rolled back when surrounded by TRANSACTION
if the current session is not closed. If TRUNCATE is written in Query Editor surrounded by
TRANSACTION and if session is closed, it can not be rolled back but DELETE can be rolled
back.
138. When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large
amount of deletions any modification 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.
139. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
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.
140. What are the properties and different Types of Sub-Queries?
1. Properties of Sub-Query
1. A sub-query must be enclosed in the parenthesis.
2. A sub-query must be put in the right hand of the comparison operator, and
3. A sub-query cannot contain an ORDER-BY clause.
4. A query can contain more than one sub-query.
2. Types of Sub-Query
1. Single-row sub-query, where the sub-query returns only one row.
2. Multiple-row sub-query, where the sub-query returns multiple rows,. and
3. Multiple column sub-query, where the sub-query returns multiple columns
141. What is SQL Profiler?
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.
32 | P a g e
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.
142. What are the authentication modes in SQL Server? How can it be changed?
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.
143. Which command using Query Analyzer will give you the version of SQL server
and operating system?
SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'),
SERVERPROPERTY ('edition').
144. What is SQL Server Agent?
SQL Server agent plays an important role in the day-to-day tasks of a database
administrator (DBA). It is often overlooked as one of the main tools for SQL Server
management. Its purpose is to ease the implementation of tasks for the DBA, with its fullfunction scheduling engine, which allows you to schedule your own jobs and scripts.
145. Can a stored procedure call itself or recursive stored procedure? How much
level SP nesting is possible?
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.
146. What is Log Shipping?
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
33 | P a g e
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.
147. Name 3 ways to get an accurate count of the number of records in a table?
SELECT * FROM table1
SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
148. What does it mean to have QUOTED_IDENTIFIER ON? What are the implications
of having it OFF?
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 TransactSQL rules for identifiers.
149. What is the difference between a Local and a Global temporary table?
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.
150. What is the STUFF function and how does it differ from the REPLACE function?
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.
34 | P a g e
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.
158. What are the advantages of using Stored Procedures?
1. Stored procedure can reduced network traffic and latency, boosting application
performance.
2. Stored procedure execution plans can be reused, staying cached in SQL Server's
memory, reducing server overhead.
3. Stored procedures help promote code reuse.
4. Stored procedures can encapsulate logic. You can change stored procedure code
without affecting clients.
5. Stored procedures provide better security to your data.
159. What is a table called, if it has neither Cluster nor Non-cluster Index? What is it
used for?
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.
160. Can SQL Servers linked to other servers like Oracle?
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.
161. How to implement one-to-one, one-to-many and many-to-many relationships
while designing tables?
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. Manyto-Many relationships are implemented using a junction table with the keys from both the
tables forming the composite primary key of the junction table.
162. What are the basic functions for master, msdb, model, tempdb and resource
databases?
1. The master database holds information for all databases located on the SQL Server
instance and is theglue that holds the engine together. Because SQL Server cannot
start without a functioning masterdatabase, you must administer this database with
care.
36 | P a g e
2. The msdb database stores information regarding database backups, SQL Agent
information, DTS packages, SQL Server jobs, and some replication information such
as for log shipping.
3. The tempdb holds temporary objects such as global and local temporary tables and
stored procedures.
4. The model is essentially a template database used in the creation of any new user
database created in the instance.
5. The resoure Database is a read-only database that contains all the system objects
that are included with SQL Server. SQL Server system objects, such as sys.objects,
are physically persisted in the Resource database, but they logically appear in the
sys schema of every database. The Resource database does not contain user data or
user metadata.
37 | P a g e
3. New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes
related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.
1. DATE: The new DATE type just stores the date itself. It is based on the
Gregorian calendar and handles years from 1 to 9999.
2. TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000
through 23:59:59.9999999. The precision is allowed with this type. TIME
supports seconds down to 100 nanoseconds. The n in TIME (n) defines this
level of fractional second precision, from 0 to 7 digits of precision.
3. The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time-zoneaware version of a datetime datatype. The name will appear less odd when
you consider what it really is: a date + a time + a time-zone offset. The offset
is based on how far behind or ahead you are from Coordinated Universal
Time (UTC) time.
4. The DATETIME2 Type: It is an extension of the datetime type in earlier
versions of SQL Server. This new datatype has a date range covering dates
from January 1 of year 1 through December 31 of year 9999. This is a definite
improvement over the 1753 lower boundary of the datetime datatype.
DATETIME2 not only includes the larger date range, but also has a timestamp
and the same fractional precision that TIME type provides
173. What are the Advantages of using CTE?
1. Using CTE improves the readability and makes maintenance of complex queries
easy.
2. The query can be divided into separate, simple, logical building blocks which can be
then used to build more complex CTEs until final result set is generated.
3. CTE can be defined in functions, stored procedures, triggers or even views.
4. After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT,
UPDATE or DELETE Data.
174. How would you handle error in SQL SERVER 2008?
SQL Server now supports the use of TRY...CATCH con handling. TRY...CATCH lets us
build error handling at the level we need, in the way w to, by setting a region where
if any error occurs, it will break out of the region and head to an error handler.
The basic structure is as follows:
BEGIN TRY
stmts..
END TRY
BEGIN CATCH
stmts..
END CATCH
39 | P a g e
40 | P a g e
187. Explain the differences between structured data and unstructured data.
Structured data are facts concerning objects and events. The most important structured
data are numeric, character, and dates. Structured data are stored in tabular form.
Unstructured data are multimedia data such as documents, photographs, maps, images,
sound, and video clips. Unstructured data are most commonly found on Web servers and
Web-enabled databases.
188.What are dimension tables and definition of Fact tables?
These two questions are most commonly asked database interview questions. Fact tables
are mainly central tables that are an integral part of data warehousing and dimension
tables are used for describing the attributes of the fact tables. Both of these tables are
important and play an important role in maintaining the database management system.
189.What is Data Warehouse?
A data warehouse is a subject-oriented, integrated, time-variant and non-volatile collection
of data in support of management's decision making process.
Subject-Oriented: A data warehouse can be used to analyze a particular subject area. For
example, "sales" can be a particular subject.
Integrated: A data warehouse integrates data from multiple data sources. For example,
source A and source B may have different ways of identifying a product, but in a data
warehouse, there will be only a single way of identifying a product.
Time-Variant: Historical data is kept in a data warehouse. For example, one can retrieve
data from 3 months, 6 months, 12 months, or even older data from a data warehouse. This
contrasts with a transactions system, where often only the most recent data is kept. For
example, a transaction system may hold the most recent address of a customer, where a
data warehouse can hold all addresses associated with a customer.
42 | P a g e
Non-volatile: Once data is in the data warehouse, it will not change. So, historical data in a
data warehouse should never be altered.
190.What is Data Mining?
Data mining is a term from computer science. Sometimes it is also called knowledge
discovery in databases (KDD). Data mining is about finding new information in a lot of
data. The information obtained from data mining is hopefully both new and useful.
MOST FREQUENTLY ASKED SQL QURIES
1.SQL Query to find second highest salary of Employee
Answer : There are many ways to find second highest salary of Employee in SQL, you can
either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :
1. select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from
Employee );
2. SQL Query to find Max Salary from each department.
Answer :
SELECT DeptID, MAX(Salary) FROM Employee GROUP BY DeptID.
3.Write SQL Query to display current date.
Ans:SQL has built in function called GetDate() which returns current timestamp.
SELECT GetDate();
4.Write an SQL Query to check whether date passed to Query is date of given format
or not.
Ans: SQL has IsDate() function which is used to check passed value is date or not of
specified format ,it returns 1(true) or 0(false) accordingly.
SELECT ISDATE('1/08/13') AS "MM/DD/YY";
It will return 0 because passed date is not in correct format.
5. Write a SQL Query to print the name of distinct employee whose DOB is between
01/01/1960 to 31/12/1975.
Ans:
SELECT DISTINCT EmpName FROM Employees WHERE DOB BETWEEN 01/01/1960
AND 31/12/1975;
43 | P a g e
6.Write an SQL Query find number of employees according to gender whose DOB is
between 01/01/1960 to 31/12/1975.
Answer : SELECT COUNT(*), sex from Employees WHERE DOB BETWEEN 01/01/1960 '
AND 31/12/1975 GROUP BY sex;
7.Write an SQL Query to find employee whose Salary is equal or greater than 10000.
Answer : SELECT EmpName FROM Employees WHERE Salary>=10000;
8.Write an SQL Query to find name of employee whose name Start with M
Ans: SELECT * FROM Employees WHERE EmpName like 'M%';
9. find all Employee records containing the word "Joe", regardless of whether it was
stored as JOE, Joe, or joe.
Answer : SELECT * from Employees WHERE upper(EmpName) like upper('joe%');
10. Write a SQL Query to find year from date.
Answer : SELECT YEAR(GETDATE()) as "Year";
11.To fetch ALTERNATE records from a table. (EVEN NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from
emp);
12.To select ALTERNATE records from a table. (ODD NUMBERED)
select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from
emp);
13.Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where
e1.sal <= e2.sal);
14.Find the 3rd MIN salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where
e1.sal >= e2.sal);
15.Select FIRST n records from a table.
select * from emp where rownum <= &n;
16.Select LAST n records from a table
select * from emp minus select * from emp where rownum <= (select count(*) - &n from
emp);
17.List dept no., Dept name for all the departments in which there are no employees
in the department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where
a.deptno = b.deptno);
44 | P a g e
46 | P a g e
40.How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
41. How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
42.Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2
43.Display the names of employees who are working in the company for the past 5
years.
select ename from emp where sysdate-hiredate>5*365;
44.Display the list of employees who have joined the company before 30th June 90 or
after 31st dec 90.
select * from emp where hiredate between 30-jun-1990 and 31-dec-1990;
45.Display the names of employees working in department number 10 or 20 or 40 or
employees working as clerks, salesman or analyst.
select ename from emp where deptno in (10,20,40) or job in
(CLERK,SALESMAN,ANALYST);
47.Display employee names for employees whose name ends with alphabet.
select ename from emp where ename like %S;
47 | P a g e
48 | P a g e