Featured Post

What is the purpose of the php.ini file?

  The PHP configuration file,   php.ini , is the final and most immediate way to affect PHP's functionality. The php.ini file is read ea...

SQL Interview Questions with Answers on De-normalization, Identity, properties of the Relational tables

What is De-normalization?

De-normalization is the process of attempting to optimize the performance of a database by adding
redundant data. It is sometimes necessary because current DBMSs implement the relational model
poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while
providing physical storage of data that is tuned for high performance. De-normalization is a technique
to move from higher to lower normal forms of database modeling in order to speed up database access.

How to get @@error and @@rowcount at the same time?

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. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR


SQL Interview Questions with Answers on Index, BCP, Scheduled Tasks,Scheduled Jobs

What is a table called, if it does not have 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 than do bulk of inserts and to restore those indexes after that.


SQL Interview Questions with Answers

How do you load large data to the SQL server database?
BulkCopy is a tool used to copy huge amount of data from tables. BULK INSERT command helps to
Imports a data file into a database table or view in a user-specified format.
Can we rewrite subqueries into simple select statements or with joins?
Subqueries can often be re-written to use a standard outer join, resulting in faster performance. As we
may know, an outer join uses the plus sign (+) operator to tell the database to return all non-matching
rows with NULL values. Hence we combine the outer join with a NULL test in the WHERE clause to
reproduce the result set without using a sub-query.


SQL Interview Questions with Answers on Procedure,trigger

List few advantages of Stored Procedure.

· Stored procedure can reduced network traffic and latency, boosting application performance.
· Stored procedure execution plans can be reused, staying cached in SQL Server's memory,
reducing server overhead.
· Stored procedures help promote code reuse.
· Stored procedures can encapsulate logic. You can change stored procedure code without
affecting clients.
· Stored procedures provide better security to your data.


SQL Interview Questions with Answers on DataWarehousing,OLTP, SQL server 2000 and XML

What is DataWarehousing?
· Subject-oriented, meaning that the data in the database is organized so that all the data
elements relating to the same real-world event or object are linked together;
· Time-variant, meaning that the changes to the data in the database are tracked and recorded
so that reports can be produced showing changes over time;
· Non-volatile, meaning that data in the database is never over-written or deleted, once
committed, the data is static, read-only, but retained for future reporting;
· Integrated, meaning that the database contains data from most or all of an organization's
operational applications, and that this data is made consistent.

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.


SQL Interview Questions with Answers on sp_configure commands, set commands, replication

What command do we use to rename a db?
sp_renamedb ‘oldname’ , ‘newname’
If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using
sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user
mode.

What is sp_configure commands and set commands?
Use sp_configure to display or change server-level settings. To change database-level settings, use
ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.


SQL Interview Questions with Answers on @@ERROR, Raiseerror, log shipping,

What is @@ERROR?
The @@ERROR automatic variable returns the error code of the last Transact-SQL statement. If there
was no error, @@ERROR returns zero. Because @@ERROR is reset after each Transact-SQL statement,
it must be saved to a variable if it is needed to process it further after checking it.
What is Raiseerror?
Stored procedures report errors to client applications via the RAISERROR command. RAISERROR
doesn't change the flow of a procedure; it merely displays an error message, sets the @@ERROR
automatic variable, and optionally writes the message to the SQL Server error log and the NT
application event log.


SQL Interview Questions with Answers on SQL server agent, SP nesting possible

Where are SQL server users names and passwords are stored in sql server?
They get stored in master db in the sysxlogins table.

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

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

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.


SQL Interview Questions with Answers on TCP,SQL Server run on

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.

Multi-statement Table-Value User-Defined Function
A Multi-Statement Table-Value 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 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.


SQL Interview Questions with Answers on Defined Functions

What is User Defined Functions?
User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters
and return a single scalar data value or a table data type.

What kind of User-Defined Functions can be created?
There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-
Valued and Multi-statement Table-valued.


SQL Interview Questions with Answers on Properties of Sub-Query,SQL Profiler,

Properties of Sub-Query
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator, and
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.

What are types of sub-queries?
Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.


SQL Interview Questions with Answers on HAVING CLAUSE , WHERE CLAUSE, ub-query,

What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Specifies a search condition for a group or an aggregate. 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. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

What is sub-query? Explain properties of sub-query.


SQL Interview Questions with Answers on Stored Procedure, Function , UPDATE_STATISTICS, INNER JOINs, OUTER JOINs, CROSS JOINs,RIGHT OUTER JOINS and FULL OUTER JOINS

Difference between Function and Stored Procedure?
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as
Stored procedures cannot be.
UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
Inline UDF's can be though of as views that take parameters and can be used in JOINs and other
Rowset operations.


SQL Interview Questions with Answers on NOLOCK, TRUNCATE, DELETE

What is a NOLOCK?

Using the NOLOCK query optimiser hint is generally considered good practice in order to improve
concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are
taken when data is read. The result is a Dirty Read, which means that another process could be
updating the data at the exact time you are reading it. There are no guarantees that your query will
retrieve the most recent data. The advantage to performance is that your reading of data will not block
updates from taking place, and updates will not block your reading of data. SELECT statements take
Shared (Read) locks. This means that multiple SELECT statements are allowed simultaneous access, but
other processes are blocked from modifying the data. The updates will queue until all the reads have
completed, and reads requested after the update will wait for the updates to complete. The result to
your system is delay(blocking).
What is difference between DELETE & 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.

SQL Interview Questions with Answers on DBCC ,Linked Server,Collation

What is the use of DBCC commands?
DBCC stands for database consistency checker. We use these commands to check the consistency of
the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.
DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query
both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy
to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.
Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is
sorted using rules that define the correct character sequence, with options for specifying casesensitivity,
accent marks, kana character types and character width.


SQL Interview Questions with Answers on Index, clustered , non-clustered index

What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table
to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of
a table, and each index is given a name. The users cannot see the indexes, they are just used to speed
up queries. Effective indexes are one of the best ways to improve performance in a database
application. A table scan happens when there is no index available to help a query. In a table scan SQL
Server examines every row in the table to satisfy the query results. Table scans are sometimes
unavoidable, but on large tables, scans have a terrific impact on performance.
Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this
reason, each database table may have only one clustered index.
Non-clustered indexes are created outside of the database table and contain a sorted list of references
to the table itself.


SQL Interview Questions with Answers on Procedure, Trigger,

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.

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;
the 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.


SQL Interview Questions with Answers on RDBMS,1NF,

What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain
data records and indices in tables. Relationships may be created and maintained across and among the
data and tables. In a relational database, relationships between data items are expressed by means of
tables. Interdependencies among these tables are expressed by data values rather than by pointers.
This allows a high degree of data independence. An RDBMS has the capability to recombine the data
items from different files, providing powerful tools for data usage.
What is normalization?
Database normalization is a data design and organization process applied to data structures based on
rules that help build relational databases. In relational database design, the process of organizing data
to minimize redundancy. Normalization usually involves dividing a database into two or more tables and
defining relationships between the tables. The objective is to isolate data so that additions, deletions,
and modifications of a field can be made in just one table and then propagated through the rest of the
database via the defined relationships.
What are different normalization forms?


Sql Queries

List the emps who are either ‘CLERK’ or ‘ANALYST’ in the Desc order.
A) select * from emp where job = ‘CLERK’ or job = ‘ANALYST’ order by job desc;
List the emps who joined on 1-MAY-81,3-DEC-81,17-DEC-81,19-JAN-80 in asc order of seniority.
A) select * from emp where hiredate in (’01-may-81’,’03-dec-81’,’17-dec-81’,’19-jan-80’) order by hiredate asc;

List the emps along with their Exp and Daily Sal is more than Rs.100.


A) select * from emp where (sal/30) >100;

List the emps in the asc order of Designations of those joined after the second half of 1981.

Answer:

select * from emp where hiredate > (’30-jun-81’) and to_char(hiredate,’YYYY’) = 1981 order by job asc;

Display all the details of the emps whose Comm. Is more than their Sal.

Answer:

List the Empno, Ename, Sal, Exp of all emps working for Mgr 7369.

Answer:

Display the Empno, Ename, job, Hiredate, Exp of all Mgrs

Answer:

List the Empno, Ename, Sal, Daily sal of all emps in the asc order of Annsal.

Answer:

List the emps who joined before 1981.

Answer:

select * from emp where hiredate < (’01-jan-81’);

Display all the details of all Mgrs

Answer:

Display all the unique job groups in the descending order?

Answer:

List the details of the emps in asc order of the Dptnos and desc of Jobs?

Answer:

List the emps in the asc order of their Salaries?

Answer:

Display unique Jobs from EMP table?

Answer:

Display all the information of the EMP table?

Query for selecting all data from table write below select sql query

Using REPLACE in an UPDATE statement

This article covers using the REPLACE function to selectively replace text inside a string in SQL Server. The REPLACE function is easy to use and very handy with an UPDATE statment.
Replace searches for certain characters in a string and replaces them with other characters. So this statement:
SELECT Replace('SQLTeam.com Rocks!', 'Rocks', 'Rolls')
will return
SQLTeam.com Rolls!
REPLACE searches the the first string for any occurance of the the second string and replaces it with the third string. You can also do replacements of different sizes. For example,
SELECT Replace('SQLTeam.com Rocks!', 'Rocks', 'is cool')
gives us
SQLTeam.com is cool!
I replaced a five character string with a seven character string with no problem. If the string isn't found, no changes will be made.
SELECT Replace('SQLTeam.com Rocks!', 'Yak', 'Tibetan bison')
returns exactly what we started with which is
SQLTeam.com Rocks!
If it doesn't find anything to change it just returns the string unchanged. You can use REPLACE in an UPDATE statement. Using the pubs database we could write:
Update dbo.authors
Set    city = replace(city, 'Salt', 'Olympic');
There were two authors that had "Salt Lake City" in the CITY field. Now that field holds "Olympic Lake City" for those two authors. The CITY field is unchanged for all the other authors.
A more common approach is to use this in conjuntion with a WHERE clause like this:
UPDATE dbo.authors
SET    city = replace(city, 'Salt', 'Olympic')
WHERE  city LIKE 'Salt%';
This only affects the rows that start with 'Salt'.

Trapping Errors in Stored Procedures


A TRY CATCH block can catch errors in stored procedures called by other stored procedures.  An example is:
BEGIN TRY
    EXEC ParentError
END TRY
BEGIN CATCH
    SELECT Error_Line = ERROR_LINE(),
           Error_Proc = ERROR_PROCEDURE()
END CATCH
Assuming that the ParentError stored procedure calls the ChildError stored procedure which generates an error you'd see output like this:
Error_Line  Error_Proc
----------- -------------
5           ChildError

Handling SQL Server Errors

This article covers the basics of TRY CATCH error handling in T-SQL introduced in SQL Server 2005. It includes the usage of common functions to return information about the error and using the TRY CATCH block in stored procedures and transactions.
SQL Server uses the following syntax to capture errors in Transact-SQL statements:
BEGIN TRY
    SELECT [First] = 1
    SELECT [Second] = 1/0
    SELECT [Third] = 3
END TRY
BEGIN CATCH
    PRINT 'An error occurred'
END CATCH
This returns the following output:
First
-----------
1

(1 row(s) affected)

Second
-----------

(0 row(s) affected)

An error occurred
A key difference from SQL Server 2000 is that execution is halted when SQL Server encounters an error.  At that point execution transfers to the CATCH block.  This error isn't returned to the client application or calling program.  The TRY CATCH block consumes the error.

Popular Posts