100% found this document useful (1 vote)
260 views13 pages

SQL Technical INterview PDF

The document contains information about SQL queries, indexes, and database concepts. It provides sample queries to display average item prices by company, find 1970 Nobel Prize winners ordered by subject and name, and describes clustered vs non-clustered indexes. It also defines transaction processing, primary keys vs unique keys, and differences between DELETE and TRUNCATE commands.

Uploaded by

Guru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
260 views13 pages

SQL Technical INterview PDF

The document contains information about SQL queries, indexes, and database concepts. It provides sample queries to display average item prices by company, find 1970 Nobel Prize winners ordered by subject and name, and describes clustered vs non-clustered indexes. It also defines transaction processing, primary keys vs unique keys, and differences between DELETE and TRUNCATE commands.

Uploaded by

Guru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Sandeep Kumar N

Mtech(VLSI & ES)

+91-8553350742

[email protected]

Write a SQL query to display the average price of the items for each
company, showing only the company code.

Sample table : item_mast


Sample Solution :
?

1. SELECT AVG(pro_price), pro_com


2. FROM item_mast
3. GROUP BY pro_com;

Output :

Write a SQL query to find all the details of 1970 winners by the ordered to
subject and winner name; but the list contain the subject Economics and
Chemistry at last.

Sample table : nobel_win


Sample Solution :
view plaincopy to clipboardprint?
1. SELECT *
2. FROM nobel_win
3. WHERE year=1970
4. ORDER BY
5. CASE
6. WHEN subject IN ('Economics','Chemistry') THEN 1
7. ELSE 0
8. END ASC,
9. subject,
10. winner;

Output :

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.

1. 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.

2. What are the different index configurations a table can have?


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

3. What are different types of Collation Sensitivity?

1. Case sensitivity - A and a, B and b, etc.


2. Accent sensitivity
3. Kana Sensitivity - When Japanese kana characters Hiragana and Katakana are treated
differently, it is called Kana sensitive.
4. Width sensitivity - A single-byte character (half-width) and the same character represented as a
double-byte character (full-width) are treated differently than it is width sensitive.

4. What is OLTP (Online Transaction Processing)?

In OLTP - online transaction processing systems relational database design use the discipline of
data modeling and generally follow the Codd rules of data normalization in order to ensure
absolute data integrity. Using these rules complex information is broken down into its most
simple structures (a table) where all of the individual atomic level elements relate to each other
and satisfy the normalization rules.

5. What's the difference between a primary key and a unique key?

Both primary key and unique key enforces uniqueness of the column on which they are defined.
But by default primary key creates a clustered index on the column, where are unique creates a
nonclustered index by default. Another major difference is that, primary key doesn't allow
NULLs, but unique key allows one NULL only.

What is difference between DELETE and TRUNCATE commands?


Delete command removes the rows from a table based on the condition that we provide with a
WHERE clause. Truncate will actually remove all the rows from a table and there will be no data
in the table after we run the truncate command.
1. TRUNCATE:
1. TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
2. TRUNCATE removes the data by deallocating the data pages used to store the table's data, and
only the page deallocations are recorded in the transaction log.
3. TRUNCATE removes all rows from a table, but the table structure, its columns, constraints,
indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for
the column.
4. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
5. TRUNCATE cannot be rolled back.
6. TRUNCATE is DDL Command.
7. TRUNCATE Resets identity of the table
2. DELETE:
1. DELETE removes rows one at a time and records an entry in the transaction log for each deleted
row.
2. If you want to retain the identity counter, use DELETE instead. If you want to remove table
definition and its data, use the DROP TABLE statement.
3. DELETE Can be used with or without a WHERE clause
4. DELETE Activates Triggers.
5. DELETE can be rolled back.
6. DELETE is DML Command.
7. DELETE does not reset identity of the table.
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.

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.

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.

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

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.

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.

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.

13. Which command using Query Analyzer will give you the version of SQL server and
operating system?

SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'),


SERVERPROPERTY ('edition').
14. 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 full- function scheduling engine, which
allows you to schedule your own jobs and scripts.

15. 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.

16. 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 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.

17. 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

18. 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 Transact-SQL
rules for identifiers.

What are the 2 types of Temporary Tables in SQL Server?


1. Local Temporary Tables
2. Global Temporary Tables

What is the difference between Local and Global Temporary Tables?


Local Temporary Tables:
1. Prefixed with a single pound sign (#).
2. Local temporary tables are visible to that session of SQL Server which has created it.
3. Local temporary tables are automatically dropped, when the session that created the temporary
tables is closed.

Global Temporary Tables:


1. Prefixed with two pound signs (##).
2. Global temporary tables are visible to all the SQL server sessions.
3. Global temporary tables are also automatically dropped, when the session that created the
temporary tables is closed.

Can you create foreign key constraints on temporary tables?


No

Do you have to manually delete temporary tables?


No, temporary tables are automatically dropped, when the session that created the temporary tables is
closed. But if you maintain a persistent connection or if connection pooling is enabled, then it is better
to explicitly drop the temporary tables you have created.
However, It is generally considered a good coding practice to explicitly drop every temporary table
you create.
In which database, the temporary tables get created?
TEMPDB database.

What are the disadvantages of an Index?


There are 2 disadvantages of an Index
1. Increased Disk Space
2. Insert, Update and Delete statements could be slow. In short, all DML statements could be slow.

Disk Space: Indexes are stored on the disk, and the amount of space required will depend on the size
of the table, and the number and types of columns used in the index. Disk space is generally cheap
enough to trade for application performance, particularly when a database serves a large number of
users.

Insert, Update and Delete statements could be slow: Another downside to using an index is the
performance implication on data modification statements. Any time a query modifies the data in a
table (INSERT, UPDATE, or DELETE), the database needs to update all of the indexes where data
has changed. Indexing can help the database during data modification statements by allowing the
database to quickly locate the records to modify, however, providing too many indexes to update can
actually hurt the performance of data modifications. This leads to a delicate balancing act when tuning
the database for performance.

What are the 2 types of Indexes in SQL Server?


1. Clustered Index
2. Non Clustered Index

How many Clustered and Non Clustered Indexes can you have per table?
Clustered Index - Only one Clustered Index per table. A clustered index contains all of the data for a
table in the index, sorted by the index key. Phone Book is an example for Clustered Index.
Non Clustered Index - You can have multiple Non Clustered Indexes per table. Index at the back of
a book is an example for Non Clustered Index.
Which Index is faster, Clustered or Non Clustered Index?
Clustered Index is slightly faster than Non Clustered Index. This is because, when a Non Clustered
Index is used there is an extra look up from the Non Clustered Index to the table, to fetch the actual
rows.

When is it usually better to create a unique nonclustered index on the primary key column?
Sometimes it is better to use a unique nonclustered index on the primary key column, and place the
clustered index on a column used by more queries. For example, if the majority of searches are for the
price of a product instead of the primary key of a product, the clustered index could be more effective
if used on the price field.

What is a Composite Index in SQL Server?


or
What is the advantage of using a Composite Index in SQL Server?
or
What is Covering Query?
A composite index is an index on two or more columns. Both clustered and nonclustered indexes can
be composite indexes.
If all of the information for a query can be retrieved from an Index. A clustered index, if selected for
use by the query optimizer, always covers a query, since it contains all of the data in a table.

By creating a composite indexes, we can have covering queries.


What is a Trigger in SQL Server?
A Trigger is a database object that is attached to a table. In many aspects it is similar to a stored
procedure. As a matter of fact, triggers are often referred to as a "special kind of stored
procedure." The main difference between a trigger and a stored procedure is that the former is
attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs.

What are the two types of Triggers in SQL Server?


1. After Triggers : Fired after Insert, Update and Delete operations on a table.
2. Instead of Triggers: Fired instead of Insert, Update and Delete operations on a table.

What are the special tables used by Triggers in SQL Server?


Triggers make use of two special tables called inserted and deleted. The inserted table contains the
data referenced in an INSERT before it is actually committed to the database. The deleted table
contains the data in the underlying table referenced in a DELETE before it is actually removed
from the database. When an UPDATE is issued both tables are used. More specifically, the new
data referenced in the UPDATE statement is contained in inserted table and the data that is
being updated is contained in deleted table.

What is the difference between a User Defined Function (UDF) and


a Stored Procedure (SP) in SQL Server

1. Stored Procedure support deffered name resolution where as functions do not support deffered
name resolution.

2. User Defined Function can be used in a select statement where as you cannot use a stored
procedure in a select statement.

3. UDF's cannot return Image, Text where as a StoredProcedure can return any datatype.
4. In general User Defined Functions are used for computations where as Stored Procedures are
used for performing business logic.

5. UDF should return a value where as Stored Procedure need not.

6. User Defined Functions accept lesser number of input parameters than Stored Procedures.
UDF can have upto 1023 input parameters where as a Stored Procedure can have upto 21000 input
parameters.

7. Temporary Tables can not be used in a UDF where as a StoredProcedure can use Temporary
Tables.

8. UDF can not Execute Dynamic SQL where as a Stored Procedure can execute Dynamic SQL.

Can you create a view based on other views?


Yes, you can create a view based on other views. Usually we create views based on tables, but it also
possible to create views based on views.

Can you update views?


Yes, views can be updated. However, updating a view that is based on multiple tables, may not update
the underlying tables correctly. To correctly update a view that is based on multiple tables you can
make use INSTEAD OF triggers in SQL Server. Click here for a real time example, that we have
already discussed in SQL Server Interview Questions on triggers article.

What are the limitations of a View?


1. You cannot pass parameters to a view.

2. Rules and Defaults cannot be associated with views.

3. The ORDER BY clause is invalid in views unless TOP or FOR XML is also specified.
4. Views cannot be based on temporary tables.

What are the different types of joins available in sql server?


There are 3 different types of joins available in sql server, and they are
1. Cross Join
2. Inner Join or Join
3. Outer Join

Outer Join is again divided into 3 types as shown below.


1. Left Outer Join or Left Join
2. Right Outer Join or Right Join
3. Full Outer Join or Full Join

You might have heard about self join, but self join is not a different type of join. A self join means
joining a table with itself. We can have an inner self join or outer self join. Read this sql server
interview question, to understand self join in a greater detail.

SQL Server interview questions on string manipulation functions

The following 2 SQL Server Interview questions were asked when I attended an interview for SQL
Server Developer role.

Can you list a few useful string manipulation functions in SQL Server?
LEN(), SUBSTRING(), CHARINDEX(), LEFT(), RIGHT() etc.

Then he asked me, Can you give me one example of where you have used these functions in your
experience?
The following is one simple real time example, where we can use LEN(),
CHARINDEX() and SUBSTRING() functions. Let us assume we have table as shown below.
I want you to write a query to find out total number of emails, by domain. The result of the query
should be as shown below.

We can use LEN(), CHARINDEX() and SUBSTRING() functions to produce the desired results.
Please refer to the query below.

Select SUBSTRING(Email,CHARINDEX('@',Email)+1,(LEN(Email) -
CHARINDEX('@',Email))) as EmailDomain, Count(*) as Total
From TableName
Group By SUBSTRING(Email,CHARINDEX('@',Email)+1,(LEN(Email) -
CHARINDEX('@',Email)))
Order by Count(*) Desc

There could be even better ways of producing the same result. If you feel you have a better way of
producing the same output, please share using the form below.

You might also like