Showing posts with label SQL Server Interview Questions. Show all posts
Showing posts with label SQL Server Interview Questions. Show all posts

Saturday, March 22, 2014

Temp variablesVS Temp tables(SQL Server interview questions)



Temp tables
Temp variables
Big difference
Temp tables are real temporary SQL Server tables , you can create indexes , they can participate in transactions , it will use SQL Server optimization techniques etc.
So if you are operating on large number of records use Temp tables.
As the name says these are variables. So they do not participate in transactions, you can not create indexes directly, they do not use SQL server optimization techniques etc.


Good for small number of records.
Should be used when?
Large number of records.
Less than 100 records.
Scope
Outside procedure
Only Inside the procedure.
Transaction
Yes
No
Indexes
Yes
No (Note: - Indexes get indirectly created if you great a unique primary key.)
Truncate
Yes
No
Alter Table
Yes
No it’s just variable.
Affected by SQL Server optimization
Yes
No
Parallelism
Yes
No.
 
Recently one of our friends was asked this tricky SQL Server interview question: - Can SQL Server views be updated ?. Below is a great video by www.questpond.com which discusses this question in detail.

Friday, April 26, 2013

SQL Server Interview Question and answers:- Triggers, Instead of triggers, after triggers, inserted and deleted tables?

Triggers are special kind of stored procedure which have logic's.These logics can be executed after or before data modification happens on a table.There are two types of triggers “Instead of triggers" and "After triggers".

Instead of triggers logic executes prior to data modification while after trigger logic executes after data modification.




In what scenarios will you use instead of trigger and after trigger?

You will use "INSTEAD trigger" to take alternative actions before the update happens.

Some of the uses of instead of trigger's are:-
•Reject updates which are not valid.
•Take some alternative action if any error occurs.
•To implement cascading deletes.For instance you want to delete a customer record.But in order to delete the customer record you also have to delete address records. So you can create a instead of trigger which will first delete the address table before executing delete on customer table.

While "AFTER trigger" is useful when you want to execute trigger logic after the data has been updated.

Some uses of after triggers are:-

•For recording Audit trail where you want new and old values to be inserted in to audit table.
•Updating values after the update has happened.For instance in a sales table if number of products and per product is inserted, you can create an after trigger which will calculate the total sales amount using these two values.

What are inserted and deleted tables?

During triggers we sometimes need old and new values.Insert and deleted tables are temporary tables created by SQL server itself which have new and old values.Inserted tables have one record for newly added data and deleted table has one record of the old version of the data.

So for instance let's say we add a new record called as "Shiv". The inserted table will have "Shiv" and deleted table will have nulls because the record did not exist.Now let’s say some user updates "Shiv" to "Raju".Then inserted table will have "Raju" and deleted tables will have "Shiv".

Also watch my most asked SQL Server interview question video on:- What is the difference between clustered and non-clustered indexes?

Taken from the best selling SQL Server interview question book,you can see more about the book by clicking on  SQL Server interview questions book.

Monday, October 8, 2012

SQL Server SSIS Interview questions: -What is the difference between “For loop container” and “Foreach loop container”?

The “For Loop Container” executes specified number of times like 10 times, 20 times until the specified condition is met.













The “Foreach Loop Container” runs over an iterator. This iterator can be files from a folder, records from ADO, data from a variable etc.






























In case you are fresher to SSIS, SSAS and SSRS you can start seeing our step by step videos from http://www.youtube.com/watch?v=I_Ae3suaL-U

Regards,

Get more C# training stuffs from author's blog





Thursday, April 5, 2012

11 Important Database designing rules which I follow

Introduction
Before you start reading this article let me confirm that I am not a guru in database designing. The below 11 points which are listed are points which I have learnt via projects, my own experiences and my own reading. I personally think it has helped me a lot when it comes to DB designing. Any criticism welcome.

The reason why I am writing a full blown article is, when developers sit for designing a database they tend to follow the three normal forms like a silver bullet. They tend to think normalization is the only way of designing. Due this mind set they sometimes hit road blocks as the project moves ahead.

In case you are new to normalization, then click and see 3 normal forms in action which explains all three normal forms step by step.

Said and done normalization rules are important guidelines but taking them as a mark on stone is calling for troubles. Below are my own 11 rules which I remember on the top head while doing DB design.


Courtesy: - Image from Motion pictures

Rule 1:- What is the Nature of the application(OLTP or OLAP)?
When you start your database design the first thing to analyze is what is the natureof theapplication you are designing for, is it Transactional or Analytical. You will find many developers by default applying normalization rules without thinking about the nature of the application and then later getting in to performance and customization issues. As said there are 2 kinds of applications transaction based and analytical based,let’s understand what these types are.

Transactional: - In this kind of application your end user is more interested in CRUD i.e. Creating, reading, updating and deleting records. The official name for such kind of database is called as OLTP.

Analytical: -In these kinds of applications your end user is more interested in Analysis, reporting, forecasting etc. These kinds of databases have less number of inserts and updates. The main intention here is to fetch and analyze data as fast as possible. The official name for such kind of databases is OLAP.



So in other words if you think insert, updates and deletes are more prominent then go for normalized table design or else create a flat denormalized database structure.

Below is a simple diagram which shows how the names and address in the left hand side is a simple normalized table and by applying denormalized structure how we have created a flat table structure.


Rule 2:- Break your data in to logical pieces, make life simpler
This rule is actually the 1st rule from 1st normal formal. One of the signs of violation of this rule is if your queries are using too many string parsing functions like substring, charindexetc , probably this rule needs to be applied.

For instance you can see the below table which has student names , if you ever want to query student name who is having “Koirala” and not “Harisingh” , you can imagine what kind of query you can end up with.

So the better approach would be to break this field in to further logical pieces so that we can write clean and optimal queries.


Rule 3:- Do not get overdosed with rule 2
Developers are cute creatures. If you tell them this is the way, they keep doing it; well they overdo it leading to unwanted consequences. This also applies to rule 2 which we just talked above. When you think about decomposing, give a pause and ask yourself is it needed. As said the decomposition should be logical.

For instance you can see the phone number field; it’s rare that you will operate on ISD codes of phone number separately(Until your application demands it). So it would be wise decision to just leave it as it can lead to more complications.


Rule 4:- Treat duplicate non-uniform data as your biggest enemy
Focus and refactor duplicate data. My personal worry about duplicate data is not that it takes hard disk space, but the confusion it creates.

For instance in the below diagram you can see “5th Standard” and “Fifth standard” means the same. Now you can say due to bad data entry or poor validation the data has come in to your system. Now if you ever want toderive a report they would show them as different entities which is very confusing from end user point of view.

One of the solutions would be to move the data in to a different master table altogether and refer then via foreign keys. You can see in the below figure how we have created a new master table called as “Standards” and linked the same using a simple foreign key.

Rule 5:- Watch for data separated by separators.
The second rule of 1st normal form says avoid repeating groups. One of the examples of repeating groups is explained in the below diagram. If you see the syllabus field closely, in one field we have too much data stuffed.These kinds of fields are termed as “Repeating groups”. If we have to manipulate this data, the query would be complex and also I doubt performance of the queries.

These kinds of columns which have data stuffed with separator’s need special attention and a better approach would be to move that field to a different table and link the same with keys for better management.

So now let’s apply the second rule of 1st normal form “Avoid repeating groups”. You can see in the above figure I have created a separate syllabus table and then made a many-to-many relationship with the subject table.

With this approach the syllabus field in the main table is no more repeating and having data separators.

Rule 6:- Watch for partial dependencies.

Watch for fields which are depending partially on primary keys. For instance in the above table we can see primary key is created on roll number and standard. Now watch the syllabus field closely. Syllabus field is associated with a standard and not with a student directly (roll number).

Syllabus is associated with the standard in which the student is studying and not directly with the student. So if tomorrow we want to update syllabus we have to update for each student which is pain staking and not logical. It makes more sense to move these fields out and associate them with the standard table.

You can see how we have move the syllabus field and attached the same to standards table.

This rule is nothing but second normal form “All keys should depend on the full primary key and not partially”.

Rule 7:- Choose derived columns preciously

If you are working on OLTP applications must be getting rid of derive columns would be good thought, until there is some pressing reason of performance. In case of OLAP where we do lot of summations, calculations these kinds of fields are necessary to gain performance.

In the above figure you can see how average field is dependent on marks and subject. This is also one of form of redundancy. So for such kind of fields which are derived from other fields give a thought are they really necessary.

This rule is also termed as 3rd normal form “No columns should depend on other non-primary key columns”. My personal thought is do not apply this rule blindly see the situation; it’s not that redundant data is always bad. If the redundant data is calculative data , see the situation and then decide do you want to implement the third normal form.

Rule 8:- Do not be hard on avoidingredundancy, if performance is the key

Do not make it a strict rule that you will always avoid redundancy. If there is a pressing need of performance think about de-normalization. In normalization you need to make joins with many table and in denormalization the joins reduces and thus increasing performance.

Rule 9:- Multidimensional data is a different beast altogether
OLAP projects mostly deal with multidimensional data. For instance you can see the below figure, you would like to get sales as per country, customer and date. In simple words you are looking at sales figure which have 3 intersections of dimension data.


For such kind of situations a dimension and fact design is a better approach. In simple words you can create a simple central sales fact table which has the sales amount field and he makes a connection with all dimension tables using a foreign key relationship.


Rule 10:- Centralize name value table design
Many times I have come across name value tables. Name and value tables means it has key and some data associated with the key. For instance in the below figure you can see we have currency table and country table. If you watch the data closely they actually only have Key and value.

For such kind of table creating one central table and differentiating the data by using a type field makes more sense.

Rule 11:- For unlimited hierarchical data self-reference PK and FK
Many times we come across data with unlimited parent child hierarchy. For instance consider a Multi-level marketing scenario where one sales person can have multiple sales people below them. For such kind of scenarios using a self-referencing primary key and foreign key will help to achieve the same.


This article is not meant to say that do not follow normal forms , but do not follow them blindly , look at your project nature and type of data you are dealing with.

Out of full respect, below is a video which explains 3 normal forms step by step using a simple school table.



You can also visit my site for step by step videos on Design Patterns, UML, SharePoint 2010, .NET Fundamentals, VSTS, UML, SQL Server, MVC and lot more.

Visit for more authors blog on .NET Interview questions

Monday, February 20, 2012

SQL Server interview question:- What do you mean by SSIS, SSAS and SSRS?

All these 3 things are related to Business intelligence. Business intelligence is all about making meaning of your data, forecasting using that data, making more business sense from the data.

In order to do the same we first need to collect data, analyze it and then display it to the stake holders.
The collection of data is done by using SSIS.

The data analyzation part is done by SSAS.

The displaying of data is done by using SSRS or reporting services.

Below is a simple video in 2 parts which explains the same in more detail and with full demonstration.

Part 1:


Please click to see the Part 2 of what are SSIS, SSAS and SSRS video.

Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Monday, February 13, 2012

SQL Server interview questions: - Elaborate the essential components of SQL Server Service broker?

An SQL Server interview questions asked in the interview. So do read the following answer before going for an interview.

Following are the essential components of SQL Server:-
  • End-Points
The endpoints can be two applications running on different servers or instances, or they can be two applications running on the same server.
  • Message
A message is an entity that is exchanged between Server Brokers. A message must have a name and data type. Optionally, a message can have a validation on that type of data. A message is part of a conversation and it has a unique identifier as well as a unique sequence number to enforce message ordering.
  • Dialog
Dialog ensure messages to be read in the same order as they where put in to queue between endpoints. In short, it ensures proper ordered sequence of events at both ends for a message.
  • Conversation Group
Conversation Group is a logical grouping of Dialog. To complete a task you can need one or more dialog. For instance an online payment gateway can have two Dialog’s first is the “Address Check” and second is the “Credit Card Number” validation, these both dialog form your complete “Payment process”. So you can group both the dialogs in one Conversation Group.
  • Message Transport
Message transport defines how the messages will be send across networks. Message transport is based on TCP/IP and FTP. There are two basic protocols “Binary Adjacent Broker Protocol” which is like TCP/IP and “Dialog Protocol” which like FTP.

See the following video on calling a stored procedure using LINQ: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Sunday, February 5, 2012

SQL Server interview questions: - Explain architecture of Notification Services?

This is the SQL Server interview questions which more of Database administrator (DBA) oriented. Have a look before going for interview. So one can start answering this question as follows.

Detail sections in SQL notification services:-

Notification Service application: - It’s a simple user application which will be used to add subscription to the subscription database.

Event providers: - All events reside in Event providers. There are two event providers which are provided by default “File System watcher” and “SQL Server event provider”. “File System watcher” detects changes in operating system files. “SQL Server event provider” watches for SQL Server or analysis service database for change. You can also plug in custom event providers. When event providers find any change in database, they send the event in “Event” table.

Generator: - Generator checks the event database, when it finds any event it tries to match with the subscription and sends it to the notification database. So generator in short is the decision maker between the subscribers and the events.

Distributor: - Distributor continuously pools the “Notification” database for any “Notification’s” to be processed. If the distributor finds any entry, it retrieves it and formats it so that it can be delivered to the end recipient. Formatting is normally done using “XML” and “XSLT” for rendering purpose.

After the formatting is done, it is then pushed to the “distribution providers”. They are nothing but medium of delivery. There are three built-in providers:-
  • SMTP provider
  • File provider
  • HTTP provider
Figure: - Detail architecture of SQL notification services.

See the following video on calling a stored procedure using LINQ: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Wednesday, February 1, 2012

SQL Server interview questions: - What is the stateless and stateful load balancing?

Following way you can answer this SQL Server interview questions.

Stateless load balancer
Stateless load balancer uses the hashing algorithm. It takes packet from the client and selects fields from the packet to be hashed. For instance from each client it can take IP address and port number and hash them in to an integer between 1 to number of servers. You can see from the figure we have four servers. So the load balancer takes the IP address and port and hashes them with a number between 1 to 4. Depending on the number the client is directed to the server. For instance client A is directed to server 2, client b to server 1 and so on. Once the client is connected to a server it is always redirected to the same server.


Figure: - Stateless load balancing

Advantage of stateless load balancing is that it’s simple. The biggest disadvantage is that it treats all clients equally and connects one client to one server always. That is if client A is connects to server 2 it will always connect to server 2. This is irrespective of how many times client A sends request. So if client A sends 100 request and client B sends 10 requests even then client will be sent to server 2 for all the 100 request and client B to server 1 for all requests.

Stateful load balancer
In stateful balancing the load balancer looks at each session and assigns it to the appropriate server based on load. In order that the load balancer can track each session it needs to know when the session starts and when it ends.


Figure: - Stateful load balancing

You can see from the figure for every session the load balancer redirects the request to different servers.

See the following video on Data Access layer used in Enterprise Application Block as follows: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Wednesday, January 25, 2012

SQL Server interview questions: - What do you mean about Fragmentation in SQL Server?

This is the SQL Server interview questions which are asked during the interview not so frequent. But still go through it once before going for the interview.

Speed issues occur because of two major things
  • Fragmentation.
  • Splits.
Splits have been covered in the first questions. But one other big issue is fragmentation. When database grows it will lead to splits, but what happens when you delete something from the database…HeHeHe life has lot of turns right. Ok let’s say you have two extents and each have two pages with some data. Below is a graphical representation. Well actually that’s now how things are inside but for sake of clarity lot of things have been removed.


Figure: - Data Distribution in Initial Stages

Now over a period of time some Extent and Pages data undergo some delete. Here is the modified database scenario. Now one observation you can see is that some page’s are not removed even when they do not have data. Second If SQL server wants to fetch all “Females” it has to span across to two extent and multiple pages within them. This is called as “Fragmentation” i.e. to fetch data you span across lot of pages and extents. This is also termed as “Scattered Data”.


Figure: - Data Distribution after Deletes

What if the fragmentation is removed, you only have to search in two extent and two pages. Definitely, this will be faster as we are spanning across less entities


Figure: - Fragmentation removed

See the following video on calling a stored procedure using LINQ: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Thursday, January 19, 2012

SQL Server interview questions: - Explain two types of indexes?

This is the SQL Server interview questions most asked during the interview so do revise before you go for the interview.
There are basically two types of indexes:-
  • Clustered Indexes.
  • Non-Clustered Indexes.
Every thing is same for both the indexes i.e. it uses “B-TREE” for searching data. However, the main difference is the way it stores physical data
In clustered index, the non-leaf level actually points to the actual data.



Figure: - Clustered Index Architecture

In Non-Clustered index the leaf nodes point to pointers (they are rowid’s) which then point to actual data.


Figure: - Non-Clustered Index has pointers

So here is what the main difference is in clustered and non-clustered, in clustered when we reach the leaf nodes we are on the actual data. In non-clustered indexes, we get a pointer, which then points to the actual data.

Therefore, after the above fundamentals following are the basic differences between them:-
  • indexes as we have pointers, which is logical arrangement we do need this compulsion. Also, note in clustered index actual data as to be sorted in same way as the clustered indexes are. While in non-clustered
  • So we can have only one clustered index on a table as we can have only one physical order while we can have more than one non-clustered indexes.
Also see the following video calling a stored procedure using LINQ: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Saturday, December 24, 2011

SQL Server interview questions: - State publisher, distributor and subscriber in “Replication”?

This is the most expected asked SQL Server interview questions during the interview by the interviewer.

Publisher is the one who owns the database and is the main source for data. Publisher identifies what data should be distributed across.

Distributor is a bridge between publisher and subscriber. Distributor gathers all the published data and holds it until it sends it across to all subscriber. So as it is a bridge who sits in between publisher and subscriber, it supports multiple publisher and subscriber concept.

Subscriber is the end source or the final destination to which data has to be transmitted.


                      Figure: - Publisher, Distributor and Subscriber in action

View video on Query Plan, Logical/Physical operators in SQL Server as follows: -



Click for more SQL Server interview questions

Regards,

Visit for more author’s blog on SQL Server interview questions

Thursday, December 22, 2011

SQL Server interview questions: - Different types of relationship existing in database designing?

This is one of the most favorite SQL Server interview questions asked by the interviewer during the interview.

We have tried to keep answer as simple as we can. So starts the answer as, basically there are three major relationship models: -
  • One-to-one

                      Figure: - One-to-One relationship ER diagram
  • One-to-many
In this many records in one table corresponds to the one record in other table. Example: - Every one customer can have multiple sales. So there exist one-to-many relationships between customer and sales table.

One “Asset” can have multiple “Maintenance”. So “Asset” entity has one-to-many relationship between them as the ER model shows below.


                     Figure: - One-to-Many Relationship ER diagram
  • Many-to-many
In this, one record in one table corresponds to many rows in other table and also vice-versa. For instance :- In a company one employee can have many skills like java , c# etc and also one skill can belong to many employees.

Given below is a sample of many-to-many relationship. One employee can have knowledge of multiple “Technology”. So in order to implement this we have one more table “Employee Technology” which is linked to the primary key of “Employee” and “Technology” table.


                  Figure: - Many-to-Many Relationship ER diagram
Also see the following video on differences between unique key and primary key in SQL Server as follows:-



Visit for more SQL Server interview questions

Regards,

Get more from author’s blog for SQL Server interview questions

Saturday, November 12, 2011

SQL Server Interview Question - How do we connect to SQL SERVER, which namespace do we use?

This SQL Server interview questions is more of practical oriented. Below is the code to connect SQL Server, then we will try to understand the same in a more detailed manner.

Private Sub LoadData()
‘ note :- with and end with makes your code more readable
Dim strConnectionString As String
Dim objConnection As New SqlConnection
Dim objCommand As New SqlCommand
Dim objReader As SqlDataReader
Try
‘ this gets the connectionstring from the app.config file.
‘ note if this gives error see where the MDB file is stored 
  in your pc and point to thastrConnectionString = AppSettings.Item
(“ConnectionString”)
‘ take the connectiostring and initialize the connection object
With objConnection
.ConnectionString = strConnectionString
.Open()
End With
objCommand = New SqlCommand(“Select FirstName from Employees”)
With objCommand
.Connection = objConnection
objReader = .ExecuteReader()
End With
‘ looping through the reader to fill the list box
Do While objReader.Read()
lstData.Items.Add(objReader.Item(“FirstName”))
Loop
Catch ex As Exception
Throw ex
Finally
objConnection.Close()
End Try
<appSettings>
<add key=”Connectionstring” value=”Server=ERMBOM1-IT2;User ID=sa;Database=Employees”/>
</appSettings>
 
Note:- Comments in the code do explain a lot but we will again iterate through the 
whole code later. “LoadData” is the main method which loads the data from SQL SERVER. 
Before running this code you have to install SQL SERVER in your machine. As we are dealing 
with SQLCLIENT we need to setup database in SQL SERVER. Depending on computer you will 
also have to change the connectionstring in Web.config file.
 
For setting up the sample SQL table, we can use the DTS import wizard to import the table. See the below figure which is using data source as Microsoft Access. While importing the database author had, give the database name as “Employees”.

Figure: - Loading “Nwind.mdb” in SQL SERVER
 



Figure: - Load only the Employee table.

To make it simple we will only import the employee table as that is the only thing needed in our sample code.

 












Figure: - View of loaded Employee table

Now from interview point of view definitely you are not going to say the whole source code, which is given in the book. Interviewer expects only the broader answer of what are the steps needed to connect to SQL SERVER. For fundamental sake author has explained the whole source code. In short, you have to explain the “Load Data” method in broader way. Following are the steps to connect to SQL SERVER:-

• First imports the namespace “System.Data.SqlClient”.
• Create a connection object as shown in “Load Data” method.

With objConnection
.Connection String = strConnectionString
.Open ()
End With
• Create the command object with the SQL. Also, assign the created connection object to command object and execute the reader.

ObjCommand = New SqlCommand (“Select First Name from Employees”)
With objCommand
.Connection = objConnection
Breeder = .Execute Reader ()
End With
• Finally loop through the reader and fill the list box. If old VB programmers are expecting the move next command it is replaced by Read () which returns true if there is any data to be read. If the .Read () return is false that means that it’s end of data reader and there is no more data to be read.

Do while objReader.Read ()
lstData.Items.Add (objReader.Item (“First Name”))
Loop
• Do not forget to close the connection object.

See the following video on use of SQL Server in SharePoint and use of virtual path provider














More stuffs on SQL Server interview questions for interview preparation.

Regards,

Go to author’s blog for typical other  SQL Server interview questions