Sei sulla pagina 1di 16

SQL Queries Interview Questions for Freshers (Starters)

How to find second highest value of a column in a table?


.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier
New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre
{ margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color:
#0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt
{ background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color:
#606060; }
-- Option 1
SELECT max(SAL) FROM EMP

WHERE SAL < ( SELECT max(SAL) FROM EMP);

-- Option 2
SELECT max( SAL) FROM EMP WHERE SAL NOT IN( SELECT max(SAL) FROM EMP );

-- Option 3
SELECT max(value1) FROM ( SELECT value1 FROM val EXCEPT SELECT max(value1) FROM val );

-- Option 4
SELECT * FROM EMP
WHERE SAL IN (SELECT MAX(SAL) FROM EMP
WHERE SAL <> (SELECT MAX(SAL) FROM EMP))

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier
New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre
{ margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color:
#0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt

{ background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color:


#606060; }
What is the difference between DDL and DML commands? Can you name some examples of
each?
DDL Statements are data definition language commands. Examples are CREATE,
ALTER and DROP. where as DML Statements are data manipulation language commands.
Examples are INSERT, UPDATE and DELETE.
What are the advantages of using Views ?

Views restrict access to the data because the view can display selective
columns from the table.

Views provide data independence for ad hoc users and application programs.
One view can be used to retrieve data from several tables.

Views provide groups of users access to data according to their particular


criteria.

Views provides an additional level of table security, by restricting access to a


predetermined set of rows and columns of a table.

Hide data complexity.

Simplify commands for the user.

Present the data in a different perpecetive from that of the base table.

Store complex queries.

What is query optimization?


Query optimization is the part of the query process in which the database system compares
different query strategies and chooses the one with the least expected cost
What are the main components of Database management systems software.
The database management system software includes components for storage management,
concurrency control, transaction processing, database manipulation interface, database
definition interface, and database control interface.
What is transaction?

A transaction is a collection of applications code and database manipulation code bound into
an indivisible unit of execution. it consists from: BEGIN-TRANSACTION Name Code END
TRANSACTION Name
What is schema?
A schema is collection of database objects of a Use.
How to find structure of an existing table ?
What is difference between alias and synonym ?
Alias is a temporary used with in a query but Synonyms are permanent in a database.
Are Views automatically updated, when we insert / update the base table ?
YES, Views always displays the updated data and there is no need to manually update them.
Views doesnt store any data they refer base table for data.
What is the difference between a "where" clause and a "having" clause?
"Where" is a kind of restiriction statement. You use where clause to restrict all the data from
DB.Where clause is using before result retrieving. But Having clause is using after retrieving
the data.Having clause is a kind of filtering command.
Can you name some other alternatives to SQL Server ?
Informix, Oracle, DB2, MySQL
What is the basic form of a SQL statement to read data out of a table?
The basic form to read data out of table is SELECT * FROM table_name; An answer:
SELECT * FROM table_name WHERE xyz= whatever; cannot be called basic form because
of WHERE clause.
What structure can you implement for the database to speed up table reads?
Follow the rules of DB tuning we have to: 1] properly use indexes ( different types of
indexes) 2] properly locate different DB objects across different tablespaces, files and so
on.3] create a special space (tablespace) to locate some of the data with special datatype
( for example CLOB, LOB and )
What are the tradeoffs with having indexes?
1. Faster selects, slower updates. 2. Extra storage space to store indexes. Updates are
slower because in addition to updating the table you have to update the index.
What is a "join"?

Join used to connect two or more tables logically with or without common field.
What is normalization? "Denormalization"? Why do we sometimes want to
denormalize?
Normalizing data means eliminating redundant information from a table and organizing the
data so that future changes to the table are easier. Denormalization means allowing
redundancy in a table. The main benefit of denormalization is improved performance with
simplified data retrieval and manipulation. This is done by reduction in the number of joins
needed for data processing.
What is a "constraint"?
A constraint allows you to apply simple referential integrity checks to a table. There are four
primary types of constraints that are currently supported by SQL Server: PRIMARY/UNIQUE
enforces uniqueness of a particular table column. DEFAULT specifies a default value for a
column in case an insert operation does not provide one. FOREIGN KEY validates that
every value in a column exists in a column of another table. CHECK checks that every
value stored in a column is in some specified list. Each type of constraint performs a specific
type of action. Default is not a constraint. NOT NULL is one more constraint which does not
allow values in the specific column to be null. And also it the only constraint which is not a
table level constraint.
What types of index data structures can you have?
An index helps to faster search values in tables. The three most commonly used index-types
are: B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value.
Needs a lot of space and is the default index type for most databases. Bitmap: string of
bits for each possible value of the column. Each bit string has one bit for each row. Needs
only few space and is very fast.(however, domain of value cannot be large, e.g. SEX(m,f);
degree(BS,MS,PHD) Hash: A hashing algorithm is used to assign a set of characters to
represent a text string such as a composite of keys or partial keys, and compresses the
underlying data. Takes longer to build and is supported by relatively few databases.
What is a "primary key"?
A PRIMARY INDEX or PRIMARY KEY is something which comes mainly from
database theory. From its behavior is almost the same as an UNIQUE INDEX, i.e. there may
only be one of each value in this column. If you call such an INDEX PRIMARY instead of
UNIQUE, you say something about
your table design, which I am not able to explain in few words. Primary Key is a type of a
constraint enforcing uniqueness and data integrity for each row of a table. All columns
participating in a primary key constraint must possess the NOT NULL property.
What is a "functional dependency"? How does it relate to database table design?

Functional dependency relates to how one object depends upon the other in the database.
for example, procedure/function sp2 may be called by procedure sp1. Then we say that sp1
has functional dependency on sp2.
What is a "trigger"?
Triggers are stored procedures created in order to enforce integrity rules in a database. A
trigger is executed every time a data-modification operation occurs (i.e., insert, update or
delete). Triggers are executed automatically on occurance of one of the data-modification
operations. A trigger is a database object directly associated with a particular table. It fires
whenever a specific statement/type of statement is issued against that table. The types of
statements are insert,update,delete and query statements. Basically, trigger is a set of SQL
statements A trigger is a solution to the restrictions of a constraint. For instance: 1.A
database column cannot carry PSEUDO columns as criteria where a trigger can. 2. A
database constraint cannot refer old and new values for a row where a trigger can.
What is "index covering" of a query?
Index covering means that "Data can be found only using indexes, without touching the
tables"
What types of join algorithms can you have?
What is a SQL view?
An output of a query can be stored as a view. View acts like small table which meets our
criterion. View is a precomplied SQL query which is used to select data from one or more
tables. A view is like a table but it doesnt physically take any space. View is a good way to
present data in a particular format if you use that query quite often. View can also be used
to restrict users from accessing the tables directly.
How do you 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. Many-toMany relationships are implemented using a junction table with the keys from both the
tables forming the composite primary key of the junction table. It will be a good idea to read
up a database designing fundamentals text book.
Whats the difference between a primary key and a unique key?
Both primary key and unique enforce 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 non-clustered index by default. Another major difference is that, primary key does
not allow NULLs, but unique key allows one NULL only.

What is bit data type and whats the information that can be stored inside a bit
column?
Bit data type is used to store Boolean information like 1 or 0 (true or false). Until SQL Server
6.5 bit data type could hold either a 1 or 0 and there was no support for NULL. But from SQL
Server 7.0 onwards, bit data type can represent a third state, which is NULL
Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate
key becomes the primary key of the table. If the table has more than one candidate key, one
of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
What are defaults? Is there a column to which a default cannot be bound?
A default is a value that will be used by a column, if no value is supplied to that column
while inserting data.IDENTITY columns and timestamp columns cant have defaults bound to
them. See CREATE DEFAULT in books online.
What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none.
ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a
transaction. For more information and explanation of these properties, see SQL Server books
online or any RDBMS fundamentals text book.
Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent
transactions. The default SQL Server isolation level is Read Committed. Here are the other
isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed,
Repeatable Read, Serializable. See SQL Server books online for an explanation of the
isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you
customize the isolation level at the connection level.
CREATE INDEX myIndex ON myTable (myColumn)
What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on
the primary key, unless specified otherwise.
What is the maximum size of a row?

8060 bytes. Do not be surprised with questions like What is the maximum number of
columns per table. Check out SQL Server books online for the page titled: "Maximum
Capacity Specifications".
What are constraints? Explain different types of constraints.
Constraints enable the RDBMS enforce the integrity of the database automatically, without
needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY
For an explanation of these constraints see books online for the pages titled: "Constraints"
and "CREATE TABLE", "ALTER TABLE"
What is an index? What are the types of indexes? How many clustered indexes
can be created on a table? I create a separate index on each column of a table.
what are the advantages and disadvantages of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the
data quicker.
Indexes are of two types. Clustered indexes and non-clustered indexes. When you create
a clustered index on a table, all the rows in the table are stored in the order of the clustered
index key. So, there can be only one clustered index per table. Non-clustered indexes have
their own storage separate from the table data storage. Non-clustered indexes are stored as
B-tree structures (so do clustered indexes), with the leaf level nodes having the index key
and its row locater. The row located could be the RID or the Clustered index key, depending
up on the absence or presence of clustered index on the table.
If you create an index on each column of a table, it improves the query performance, as the
query optimizer can choose from all the existing indexes to come up with an efficient
execution plan. At the same time, data modification operations (such as INSERT, UPDATE,
DELETE) will become slow, as every time data changes in the table, all the indexes need to
be updated. Another disadvantage is that, indexes need disk space, the more indexes you
have, more disk space is used.
What are triggers? How many triggers you can have on a table? How to invoke a
trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an
INSERT, UPDATE or DELETEoperation takes place on a table.
In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE
and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could
create multiple triggers per each action. But in 7.0 theres no way to control the order in
which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires
last using sp_settriggerorder

Triggers cannot be invoked on demand. They get triggered only when an associated action
(INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used
to extend the referential integrity checks, but wherever possible, use constraints for this
purpose, instead of triggers, as constraints are much faster.
Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a
way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also.
Search SQL Server 2000 books online forINSTEAD OF triggers.
Also check out books online for inserted table, deleted table and COLUMNS_UPDATED()
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 inserted rows to it for some custom
processing.
What is the difference between oracle, sql and sql server ?

Oracle is based on RDBMS.

SQL is Structured Query Language.

SQL Server is another tool for RDBMS provided by MicroSoft.

Difference between Stored Procedure and Trigger?

we can call stored procedure explicitly.

but trigger is automatically invoked when the action defined in trigger is


done.
ex: create trigger after Insert on

this trigger invoked after we insert something on that table.

Stored procedure cant be inactive but trigger can be Inactive.

Triggers are used to initiate a particular activity after fulfilling certain


condition.It need to define and can be enable and disable according to need.

What is the advantage to use trigger in your PL?


A trigger is a database object directly associated with a particular table. It fires whenever a
specific statement/type of statement is issued against that table. The types of statements
are insert,update,delete and query statements. Basically, trigger is a set of SQL statements
A trigger is a solution to the restrictions of a constraint. For instance: 1.A database column

cannot carry PSEUDO columns as criteria where a trigger can. 2. A database constraint
cannot refer old and new values for a row where a trigger can.
Triggers are fired implicitly on the tables/views on which they are created. There are various
advantages of using a trigger. Some of them are:

Suppose we need to validate a DML statement(insert/Update/Delete) that


modifies a table then we can write a trigger on the table that gets fired
implicitly whenever DML statement is executed on that table.

Another reason of using triggers can be for automatic updation of one or more
tables whenever a DML/DDL statement is executed for the table on which the
trigger is created.

Triggers can be used to enforce constraints. For eg : Any insert/update/ Delete


statements should not be allowed on a particular table after office hours. For
enforcing this constraint Triggers should be used.

Triggers can be used to publish information about database events to


subscribers. Database event can be a system event like Database startup or
shutdown or it can be a user even like User loggin in or user logoff.

What is a SQL view?


An output of a query can be stored as a view. View acts like small table which meets our
criterion. View is a pre-complied SQL query which is used to select data from one or more
tables. A view is like a table but it doesnt physically take any space. View is a good way to
present data in a particular format if you use that query quite often. View can also be used
to restrict users from accessing the tables directly.
What is GROUP BY?
The GROUP BY keywords has been added to SQL because aggregate functions (like SUM)
return the aggregate of all column values every time they are called. Without the GROUP BY
functionality, finding the sum for each individual group of column values was not possible.
What are defaults? Is there a column to which a default cant be bound?
A default is a value that will be used by a column, if no value is supplied to that column
while inserting data. IDENTITY columns and timestamp columns cant have defaults bound
to them.
What does COMMIT do?
Saving all changes made by DML statements
List all the possible values that can be stored in a BOOLEAN data field.

There are only two values that can be stored in a BOOLEAN data field: -1(true) and 0(false).
What is the highest value that can be stored in a BYTE data field?
The highest value that can be stored in a BYTE field is 255. or from -128 to 127.
Explain SQL SELECT example:
select j.FILE_NUM
from DB_name.job j, DB_name.address a
where j.JOB_TYPE ='C'
AND j.COMPANY_NAME = 'TEST6'
AND j.OFFICE_ID = '101'
AND j.ACTIVE_IND = 'Y'
AND a.ADDRESS_STATUS_ID = 'H'
AND a.OFFICE_ID = '101'
AND a.FILE_NUM = j.FILE_NUM order by j.FILE_NUM;

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier
New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre
{ margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color:
#0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt
{ background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color:
#606060; }
J and A are aliases for table names. this is outer join select statement from two tables.
Describe some Group Functions that you know

The COUNT function tells you how many rows were in the result set. SELECT
COUNT(*) FROM Employees

The AVG function tells you the average value of a numeric column. SELECT
MAX(SALARY) FROM Employees

The MAX and MIN functions tell you the maximum and minimum value of a
numeric column. SELECT MIN(SALARY) FROM Employees

The SUM function tells you the sum value of a numeric column. SELECT
SUM(SALARY) FROM Employees

What does DML stand for?


DML is Data Manipulation Language statements. (SELECT)
What does DDL stand for?
DDL is Data Definition Language statements. (CREATE)
What does DCL stand for?
DCL is Data Control Language statements. (COMMIT)
What is SQL comments and how to inser comments in SQL statements?
SQL comments are introduced by two consecutive hyphens () and ended by the end of the
line.

What is the difference between a return parameter and an OUTPUT


parameter?
A return parameter is always returned by a stored procedure,and it is meant to indicate the
success or failure of the stored procedure. The return parameter is always an INT data type.
An OUTPUT parameter is designated specifically by the developer, and it can return other
types of data, such as characters and numeric values.
You can use multiple OUTPUT parameters in a stored procedure,whereas you can only use
one return parameter.
What is the minimum number of tables required to perform a SQL join?
One, you can join a table as a self join too, consider an example of employee table which
has a column EMPID, NAME and Mgr ID and we need to display EMPID, name of the
employee and MGRID of that employee,
How can present Summarizing Data in SQL Server?
CUBE or ROLLUP operators to generate summary reports. Both are part of the GROUP BY
Clause
What is Service Broker

Its a message queuing technology in SQL to helps developer to develop fully ditributed
applications.Its helps to send asynchronous, transactional message.Its also helps to send
message to another database.
What is SQL Profiler
SQL Profiler is a graphical tool thats helps administrator to capture events in instance of
Microsoft Sql Server. We can get all the events that done on file or on SQL Table.We can filter
the events that we need for us.We can also get the subset of event that we need.
Why not to use prefix sp in store procedure
Thses prefix is used by master database so SQL server first searches in the master database
and then in the current session database. So its time taken is much higher master database
causes extra overhead and also get wrong result in case of same name in master database.
What is the advantage of SET NOCOUNT ON
When we use SELECT and DML statement in SQL .SQL server return a message which specify
the number of rows effected by these statements. This information helps coder when they
are debugging the code other wise this is not useful we can disable this by typing SET
NOCOUNT ON. It is very helpful when we are doing on store procedure contains lots of
statements,loops its also increase in performance and boost network traffic.
Why to use SQL Sequence and its drawbacks
In SQL Sequences are used for creating sequence numbers without any overhead of locking
but one drawback is that when any of transaction is rolled back the sequence number is lost.
What are the different ways of moving data from database
There are different methods of moving data

BACKUP and RESTORE

detach and attach

Attaching databases

Replication

DTS

BCP

logshipping

INSERTSELECT

SELECTINTO

SQL Server 2012 HADR

creating INSERT scripts to generate data.

How to get top two records without Top keyword


set rowcount 2
select column,column1 from tblEmployeeMaster
What do you mean by KEYSET Cursor
KEYSET Cursor uses the set of keys that are primary key or we can saw uniquely identify the
cursors rows. SQL Server uses a table in tempdb to store keyset. The KEYSET cursor helps to
updates non key values from being made through this cursor, but when inserts made by
other users are not visible. Updates nonkey values made by other users are visible as the
owner scrolls around the cursor, but updates key values made by other users are not visible.
Difference between Set and Select

Set is a ANSI standard for variable assignment.

Select is a Non-ANSI standard when assigning variables.

Set We can assign only one variable at a time

Select We can assign multiple variable at a time

When assigning from a query that returns more than one value, SET will fail with
an error.
When assigning from a query that returns more than one value, SELECT will assign the last
value returned by the query and hide the fact that the query returned
What is Network Packet Size in SQL
NPS(Network Packet Size) is the size of the TDS (tabular data stream) packets used to
communicate between your applications and your relational database engine and default
packet size is 4 kilobytes and its manily depends on network packet size configuration
option.
What are Sparse Columns in Sql Server2008

Sparse column is a tool that helps to reduce amount of physical storage used in a database.
These are ordinary columns that have an optimized storage for all null values.SPARSE
column are better at managing NULL and ZERO values in SQL Server. It does not take any
space in database at all.
Can we create non primary key as cluster index
Yes we can do this on non-primary key column but that column must be unique and the
primary key column of that table must have non-clustered index because there is one cluster
index in table. By default primary key column contains clustered index so its recommended
to create such non-primary key clustered index column first and then should create primary
key column so in such case the primary key on that column will be with non-clustered. But
its highly recommended to create primary key column as a clustered indexed column.
Could you please give some Optimization Tips in writing SQL Queries ?

Always try to use views and stored procedures instead of doing work with
heavy queries.

Make a habit to use constraints instead of triggers whenever it is possible.

When you need n number of row from database try to use top keyword or SET
ROWCOUNT statement

Always use table variables in place of temporary tables.

Avoid Union and try to use UNION ALL statement.

Always avoid using the DISTINCT clause, whenever possible.

Always try to avoid using SQL Server cursors.

Always try to avoid the HAVING clause.

Do not use select count(*) to get number of rows

Try to include SET NOCOUNT ON statement into your stored procedures to


stop the message indicating the number of rows affected by a T-SQL
statement.

Always use file system to store large binary objects and use the file path in
database.

Sometimes we may have to apply more than one sub queries in our main
query. Try to minimize the number of sub query block in your query.

Try to use column name instead of *

Why Group BY and Order By clause are so expensive


These both of these requires Temporary table to process the result of query so these are
expensive
What is the default value of int datatype
The default value of all datatype is NULL
Is it possible to create foreign key without primary key
Yes we can do this by the help of Unique Key constraint . Means table must have atleast
Primary key or Unique key.
Does SQL Server supports Merge statement ?
YES, This is newly introduced feature in SQL Server 2008
What is Trace frag in SQL
The Trace Tags is used to set temporary setting of specific server characteristics. DBCC
TRACEON is the command to set the trace flags. Once activated, trace flag will be in effect
until the server is restarted. Trace frags are frequently used for diagnosing performance
issues.For example, the trace flag 3205 is used for disabling hard compression for tape
drives, when an instance of SQL Server starts.
What is Pivot and Unpivot
We can sort, count, and total the data stored in one table or spreadsheet and create a
second table displaying the summarized data with the Pivot tables. The PIVOT operator turns
the values of a specified column into column names, effectively rotating a table.
UNPIVOT table is reverse of PIVOT Table.
Can we call a Trigger in store procedure
A Trigger is also a special kind of Stored Procedure which will fire automatically on the
happening of an event like before or after insert, update or delete. We cannot call a trigger
explicitly from a Stored Procedure.
Why we use SET ROWCOUNT in Sql
This syntax is used in SQL Server to stop processing the query after the specified number of
rows are returned.
Why we use Unicode In Sql server
Unicode data is stored using the nchar, nvarchar,and ntext data types in SQL Server. Use

these data types for columns that store characters from more than one character set. The
SQL Server Unicode data types are based on the National Character data types in the SQL92 standard.
What is SQL Cache Dependency in ASP.NET 2.0
SQL cache dependencies is new technique in ASP.NET 2.0 which can automatically invalidate
a cached data object just like a Dataset. when the related data is modified in the database.
So for instance if you have a dataset which is tied up to a database tables any changes in
the database table will invalidate the cached data object which can be a dataset or a data
source.To enable this we need a syntax that

Potrebbero piacerti anche