Beruflich Dokumente
Kultur Dokumente
The IHttpHandler interface is implemented by all the handlers. The interface consists of one property
called IsReusable. The IsReusable property gets a value indicating whether another request can use the
IHttpHandler instance. The method ProcessRequest() allows you to process the current request. This is
the core place where all your code goes. This method receives a parameter of type HttpContext using
which you can access the intrinsic objects such as Request and Response. The IHttpHandlerFactory
interface consists of two methods - GetHandler and ReleaseHandler. The GetHandler() method
instantiates the required HTTP handler based on some condition and returns it back to ASP.NET. The
ReleaseHandler() method allows the factory to reuse an existing handler.
Does .NET CLR and SQL SERVER run in different process?
Dot Net CLR and all .net realtes application and Sql Server run in same process or we can say that that
on the same address because there is no issue of speed because if these two process are run in different
process then there may be a speed issue created one process goes fast and other slow may create the
problem.
What do you mean by three-tier architecture?
The three-tier architecture was comes into existence to improve management of code and contents and
to improve the performance of the web based applications. There are mainly three layers in three-tier
architecture. the are define as follows
(1)Presentation
(2)Business Logic
(3)Database
(1)First layer Presentation contains mainly the interface code, and this is shown to user. This code could
contain any technology that can be used on the client side like HTML, JavaScript or VBScript etc.
(2)Second layer is Business Logic which contains all the code of the server-side .This layer have code to
interact with database and to query, manipulate, pass data to user interface and handle any input from
the UI as well.
(3)Third layer Data represents the data store like MS Access, SQL Server, an XML file, an Excel file or
even a text file containing data also some additional database are also added to that layers.
• When the software being designed would not change with time.
• When the requirements of the source code of the application are unique.
If any of the above applies in the current software design, there is no need to apply design patterns in the
current design and increase unnecessary complexity in the design.
Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init
events but you will see that view state is not fully loaded during this event.5
(B) How can we identify that the Page is Post Back?
Page object has an “IsPostBack” property, which can be checked to know that is the page posted back.
Server controls like Data grid, Data List, and Repeater can have other child controls inside them. Example
Data Grid can have combo box inside data grid. These child control do not raise there events by
themselves, rather they pass the event to the container parent (which can be a data grid, data list,
repeater), which passed to the page as “ItemCommand” event. As the child control send events to parent
it is termed as event bubbling.
@Register directive informs the compiler of any custom server control added to the page.
It’s a feature provided by ASP. NET to prevent flickering and redrawing when the page is posted back.
Note:- This is only supported for IE browser. Project is who have browser compatibility as requirements
have to think some other ways of avoiding flickering.
Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-
defined values. Example below defined is “Connection String” section, which will be used through out the
project for database connection.
<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>
User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in
order that the ASCX can be used in project:.
• Register the ASCX control in page using the <percentage@ Register directive.Example
• Now to use the above accounting footer in page you can use the below directive.
RequiredFieldValidator
It checks whether the control have any value. It is used when you want the control should not be empty.
RangeValidator
It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not
be more than eight lengths.
CompareValidator
It checks that the value in controls should match some specific value. Example Textbox TxtPie should be
equal to 3.14.
RegularExpressionValidator
When we want the control, value should match with a specific regular expression.
CustomValidator
Note: - It is rare that some one will ask step by step all the validation controls. Rather they will ask for
what type of validation which validator will be used. Example in one of the interviews i was asked how will
you display summary of all errors in the validation control...just uttered one word Validation summary.
(B) Can you explain “AutoPostBack”?
If we want the control to automatically post back in case of any event, we will need to check this attribute
as true. Example on a Combo Box change we need to send the event immediately to the server side then
set the “AutoPostBack” attribute to true.
Following are the points to be done in order to enable paging in Data grid:-
• Set the “Allow Paging” to true.
• In PageIndexChanged event set the current page index clicked.
Note: - The answers are very short, if you have implemented practically its just a revision. If you are
fresher, just make sample code using Datagrid and try to implement this functionality.
It allows to execute ASP.NET application level events and setting application-level variables.
“Web.config” files apply settings to each web application, while “Machine.config” file apply settings to all
ASP.NET applications.
Session object store information between HTTP requests for a particular user, while application object are
global across users.
Page.Validate
(B) How can we check if all the validation control are valid and proper?
Using the Page.IsValid () property you can check whether all the validation are done.
(A) If client side validation is enabled in your Web page, does that mean server side code is not run.
When client side validation is enabled server emit’s JavaScript code for the custom validators. However,
note that does not mean that server side checks on custom validators do not execute. It does this
redundant check two times, as some of the validators do not support client side scripting.
(A)Which JavaScript file is referenced for validating the validators at the client side?
WebUIValidation.js JavaScript file installed at “aspnet_client” root IIS directory is used to validate the
validation controls at the client side
(A)How can I show the entire validation error message in a message box on the client side?
(B)You find that one of your validations is very complicated and does not fit in any of the validators, what
will you do?
Best is to go for CustomValidators. Below is a sample code for a custom validator, which checks that a
textbox should not have zero value
<asp:CustomValidator id="CustomValidator1" runat="server"
ErrorMessage="Number not divisible by Zero"
ControlToValidate="txtNumber"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckZero" /><br>
Input:
<asp:TextBox id="txtNumber" runat="server" />
<script language="javascript">
<!--function CheckZero(source, args) {
int val = parseInt(args.Value, 10);
if (value==0) {
args.
IsValid = false;
}
}
// -->
</script>
Note: - Here the interviewer is expecting complete flow of how an ASPX page is processed with respect
to IIS and ASP.NET engine.
Following are the steps which occur when we request a ASPX page :-
The browser sends the request to the webserver. Let us assume that the webserver at the other end is
IIS.
Once IIS receives the request he looks on which engine can serve this request.When we mean engine
means the DLL who can parse this page or compile and send a response back to browser. Which request
to map to is decided by file extension of the page requested.
Depending on file extension following are some mapping
• .aspx, for ASP.NET Web pages,
• .asmx, for ASP.NET Web services,
• .config, for ASP.NET configuration files,
• .ashx, for custom ASP.NET HTTP handlers,
• .rem, for remoting resources
You can also configure the extension mapping to which engine can route by using the IIS engine.
Example an ASP page will be sent to old classic ASP.DLL to compile. While .ASPX pages will be routed
to ASP.NET engine for compilation.
• As this book mainly will target ASP.NET we will look in to how ASP.NET pages that is ASPX pages
generation sequence occurs. Once IIS passes the request to ASP.NET engine page has to go through
two section HTTP module section and HTTP handler section. Both these section have there own work to
be done in order that the page is properly compiled and sent to the IIS. HTTP modules inspect the
incoming request and depending on that, they can change the internal workflow of the request. HTTP
handler actually compiles the page and generates output. If you see your machine.config file you will see
following section of HTTP modules
<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
<add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
<add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" />
<add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
<add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
<add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule,
System.Web.Mobile, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</httpModules>
The above mapping will show which Namespace handles which functionality. Example
FormsAthuentication is handled by “System. Web.
Security.FormsAuthenticationModule”. If you look at the web.config, section HTTP module is where
authentication and authorization happens.
Ok now the HTTP handler is where the actual compilation takes place and the output is generated.
Following is a paste from HTTP handler section of WEB.CONFIG file.
<httpHandlers>
<add verb="*" path="*.vjsproj" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.java" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="*.jsl" type="System.Web.HttpForbiddenHandler" />
<add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler" />
<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" />
...
</httpHandlers>
• Depending on the File extension handler decides which Namespace will generate the output. Example
all .ASPX extension files will be compiled by System.Web.UI.PageHandlerFactory
• Once the file is compiled it will be send back again to the HTTP modules and from there to IIS and then
to the browser.
Figure: - 7.2 IIS flow from various sections.
Session abandon
I will leave this to the readers … Just a hint we have to use System.Web.HttpPostedFile class.
Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process.
Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is
running and in process2, we have all Web application running
High (Isolated):-In high isolated scenario every process is running is there own process. In below figure
there are five processes and every one handling individual application. This consumes heavy memory but
has highest reliability.
(A)ASP used STA threading model, what is the threading model used for ASP.NET.
ASP.NET uses MTA threading model.
This attribute works like a compatibility option. As mentioned before ASP worked in STA model and
ASP.NET works in MTA model, but what if your ASP.NET application is using a VB COM component. In
order that VB COM runs properly in ASP.NET threading model, we have to set attribute. After defining the
ASPCOMPAT directive attribute ASP.NET pages runs in STA model thus building the compatibility
between ASP.NET and old COM components that does not support MTA model.
Server side code is executed at the server side on IIS in ASP.NET framework, while client side code is
executed on the browser.
In old ASP if you where said to create a login page and do authentication you have to do hell lot of
custom coding. Now in ASP.NET that has made easy by introducing Forms authentication. So let us see
in detail what form authentication is.
Forms authentication uses a ticket cookie to see that user is authenticated or not. That means when user
is authenticated first time a cookie is set to tell that this user is authenticated. If the cookies expire then
Forms authentication mechanism sends the user to the login page.
Following are the steps, which defines steps for Forms authentication:-
• Configure Web.config file with forms authentication. As shown below in the config file you can see we
have give the cookie name and loginurl page.
<configuration>
<system.web>
<!-- Other settings omitted. -->
<authentication mode="Forms">
<forms name="logincookies"
loginUrl="login.aspx"
protection="All"
timeout="30"
path="/" />
</authentication>
</system.web>
</configuration>
• Remove anonymous access to the IIS web application, following are changes done to web.config file.
<configuration>
<system.web>
<!-- Other settings omitted. -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
• Create the login page, which will accept user information. You will have create your login page that is
the Login.aspx, which will actually take the user data.
• Finally a small coding in the login button.
Let us assume that the login page has two textboxes TX name and txtapssword.
Also, import System.Web.Security and put the following code in login button of the page.
If Page.IsValid Then
If FormsAuthentication.Authenticate(txtName.Text, txtPassword.Text) Then
FormsAuthentication.RedirectFromLoginPage(txtName.Text, False)
Else
lblStatus.Text = "Error not proper user"
End If
End If
FormsAuthentication.Signout ()
(A)If cookies are not enabled at browser end does form Authentication work?
Twist: - How can I track event in checkbox, which is one of the columns of a data grid?
Note: - This is normally asked when the interviewer want to see that have you really worked practically on
a project.
<ItemTemplate>
<asp:CheckBox id="CheckBox1" runat="server" AutoPostBack="True"
OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>
If you look at the Item template, we have “OnCheckChanged” event. This “OnCheckChanged” event has
“Check Clicked” subroutine is actually in behind code. Note this method, which is in behind code, should
either be “protected” or “public”
Following below is the subroutine, which defines the method
Protected Sub Check Clicked (By Val sender As Object, By Val e As EventArgs)
‘Do something
End Sub
The above steps should be defined in short to the interviewer, which will give a quick feeling of your
practical experience with ASP.NET’
Windows Services are long-running executable applications that run in its own Windows session, which
then has the ability to start automatically when the computer boots and also can be manually paused,
stopped or even restarted.
Following are the steps to create a service:-
Create a project of type “Windows Service”.
Now to install the service you need to do run the install util exe.
(A) What is the difference between “Web farms” and “Web garden”?
“Web farms” are used to have some redundancy to minimize failures. It consists of two or more web
server of the same configuration and they stream the same kind of contents. When any request comes
there is switching / routing logic, which decides which web server from the farm, handles the request. For
instance, we have two servers “Server1” and “Server2” which have the same configuration and content.
Therefore, there is a special switch, which stands in between these two servers and the users and routes
the request accordingly.
Above figure explains in detail how web farm work. You can see there is a router in between which takes
a request and sees which one of the server is least loaded and forwards the request to that server.
Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3
and final request4 is routed to server4. So you can see because we have web farm at place server1 and
server2 are loaded with two request each rather than one server loading to full. One more advantage of
using this kind of architecture is if one of the servers goes down we can still run with the other server thus
having 24x7 uptime.
The routing logic can be a number of different options:-
• Round robin: Each node gets a request sent to it “in turn”. Therefore, server1 gets a request, then
server2 again, then server1, then server2 again. As shown in the above figure.
• Least Active: Whichever node show to have the lowest number of current connects gets new connects
sent to it. This is good to help keep the load balanced between the server nodes.
• Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good
option - especially if there are nodes that might not be “equal” in performance. If one performs better than
the other, then send more requests there rather than which is moving slowly?
Before we try to understand what a web garden is let’s try to understand how IIS handles processes. All
requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e.
with out web garden, we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all
requests. This one instance of worker process uses the CPU processor as directed by the operating
system.
However, when we enable web garden for a web server it creates different instances of the worker
process and each of these worker process runs on different CPU. You can see in the below diagram we
have different worker process instances created which run on different CPU’s.
In short, we can define a model in which multiple processes run on multiple CPUs in a single server
machine are termed as Web garden.
“Web garden” can be configured by using process model settings in “machine.config” or “Web.config” file.
The configuration section is named <process Model> and is shown in
The following example. The process model is enabled by default (enable=”true”). Below is the snippet
from config file.
<process Model
enable=”true”
timeout=”infinite”
idle Timeout=”infinite”
shutdown Timeout=”0:00:05"
requestLimit=”infinite”
requestQueueLimit=”5000"
memoryLimit=”80"
webGarden=”false”
cpuMask=”12"
userName=””
password=””
logLevel=”errors”
clientConnectedCheck=”0:00:05"
/>
From the above process model section for web garden, we are concerned with only two attributes “web
garden” and “cpuMask”.
Web Garden: - Controls CPU affinity. True indicates that processes should be affinities to the
corresponding CPU. The default is False.
CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET
processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET
threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false,
cpuMask is ignored and only one worker process will run regardless of the number of processors in the
machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that
corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff.
Below are detail steps of how to implement web garden
• Click Start and then click Run.
• Type calc.exe and then click OK.
• Go to View menu, click Scientific.
• Go to View menu, click Binary.
• Use zero and one to specify the processors ASP.NET can or cannot use.
Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not
want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-
processor computer, type 1100.
• On the View menu, click Decimal. Note the decimal number.
• Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is
located in the folder where the application is saved.
• In the Web.config file, add the process Model configuration element under the System. Web element.
Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition
attribute in the <process Model> section of the Web.config file is set to everywhere.
• Add and then set the web Garden attribute of the process Model element to True.
• Add and then set the cpuMask attribute of the process Model element to the result that is determined in
your calculation.
Do not preface the number with zerox because the result of the calculation is a decimal number. The
following example demonstrates the process Model element that is configured to enable only the first two
processors of a four-processor computer.
<processModel
enable=”true”
webGarden=”true”
cpuMask=”12" />
Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified
processors.
(B) What is the main difference between Grid layout and Flow Layout?
Grid Layout provides absolute positioning for controls placed on the page. Developers that have their
roots in rich-client development environments like Visual Basic will find it easier to develop their pages
using absolute positioning, because they can place items exactly where they want them. On the other
hand, Flow Layout positions items down the page like traditional HTML. Experienced Web developers
favor this approach because it results in pages that are compatible with a wider range of browsers.
If you look in to the HTML code created by absolute positioning you can notice lot of DIV tags. While in
Flow layout, you can see more of using HTML table to position elements, which is compatible with wide
range of browsers.
Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In
Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the
part of the executable they run on the same thread where the code runs and they do not given you the
exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will
see a debug file also as shown in figure ‘Debug Mode’.
Figure 7.10 : - Debug mode
Trace works in both debug as well as release mode. The main advantage of using trace over debug is to
do performance analysis which can not be done by debug. Trace runs on a different thread thus it does
not impact the main code thread.
Note: - There is also a fundamental difference in thinking when we want to use trace and when want to
debug. Tracing is a process about getting information regarding program's execution. On the other hand
debugging is about finding errors in the code.
To enable tracing on an ASP.NET page we need to put the ‘trace’ attribute to true on the page attribute as
shown in figure ‘Tracing in Action’ ( Its numbered as 1 in the figure). In the behind code we can use the
trace object to put tracing like one we have shown on the page load numbered as (4). We have used the
‘trace.write’ to display our tracing. You can also see the trace data which is circled. 2 and 3 show the
actual data. You can see how trace shows in details the tracing information for a page with events and
time period for execution. If you make the ‘trace’ as false you will only see the actual display i.e. ‘This is
the actual data’. So you can enable and disable trace with out actually compiling and uploading new
DLL’s on production environment.
The above sample enables tracing only at page level. To enable tracing on application level we need to
modify the ‘web.config’ file and put the ‘trace’ tag with ‘enabled=true’.
‘Tracelistener’ are objects that get tracing information from the trace class and they output the data to
some medium. For instance you can see from the figure ‘TraceListener’ how it listens to the trace object
and outputs the same to UI, File or a windows event log. There are three different types of ‘tracelistener’
first is the ‘defaulttracelistener’ (this outputs the data to UI), second is ‘textwritertracelistener’ (this outputs
to a file) and the final one is ‘Eventlogtracelistener’ which outputs the same to a windows event log.
Trace switches helps us to control and govern the tracing behavior of a project. There are two types of
trace switches ‘BooleanSwitch’ and ‘TraceSwitch’. BooleanSwitch, as the name says, is a kind of on/off
switch which can be either enabled (true) or disabled (false).
‘TraceSwitch’ on the other hand offers more options rather than simple true/false like ‘BooleanSwitch’.
Tracing is enabled for a TraceSwitch object using the Level property. When we set the Level property of a
switch to a particular level, it includes all levels from the indicated level down. For example, if you set a
TraceSwitch's Level property to TraceLevel.Info, then all the lower levels, from TraceLevel.Error to
TraceLevel.Warning, will be taken in to account. Below are the various levels in ‘TraceSwitch’ object.
Off a Outputs no messages to Trace Listeners
Error a Outputs only error messages to Trace Listeners
Warning a Outputs error and warning messages to Trace Listeners
Info a Outputs informational, warning and error messages to Trace Listeners
Verbose a Outputs all messages to Trace Listeners
Web.config file is the configuration file for the Asp.net web application. There is one web.config file for
one asp.net application which configures the particular application. Web.config file is written in XML with
specific tags having specific meanings.It includes databa which includes connections,Session
States,Error Handling,Security etc. For example :
< configuration >
< appSettings >
< add key="ConnectionString"
value="server=localhost;uid=sa;pwd=;database=MyDB" / >
< /appSettings >
< /configuration >
ASP.NET Questions – 01
August 5, 2006
Explain the .NET architecture.
How many languages .NET is supporting now? – When .NET was introduced it came with several
languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are
supported.
How is .NET able to support multiple languages? – a language should comply with the Common
Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft
Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in
.NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a
function written in another language.
How ASP .NET different from ASP? – Scripting is separated from the HTML, Code is compiled as a DLL,
these DLLs can be executed on the server.
Resource Files: How to use the resource files, how to know which language to use?
What is smart navigation? – The cursor position is maintained when the page gets refreshed due to the
server side validation and the page gets refreshed.
What is view state? – The web is stateless. But in ASP.NET, the state of a page is maintained in the in
the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done
automatically by the ASP.NET. This can be switched off / on for a single control
Explain the life cycle of an ASP .NET page.
How do you validate the controls in an ASP .NET page? – Using special validation controls that are
meant for this. We have Range Validator, Email Validator.
Can the validation be done in the server side? Or this can be done only in the Client side? – Client side is
done by default. Server side validation is also possible. We can switch off the client side and server side
can be done.
How to manage pagination in a page? – Using pagination option in DataGrid control. We have to set the
number of records for a page, then it takes care of pagination by itself.
What is ADO .NET and what is difference between ADO and ADO.NET? – ADO.NET is stateless
mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships
between the tables and select insert and updates to the database. I can update the actual database as a
batch.
Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.
Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.
Questions are categorized under the following sections, for your convenience:
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-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype 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.
Back to top
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 are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.
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"
Whar 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 craete 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 it's 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 t ime, 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.
Back to top
What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.
Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.
Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com
What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.
Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices
What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.
Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.
How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.
As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.
What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.
Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats
What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database
backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in
SQL Server books online. Be prepared to write the commands in your interview. Books online also has
information on detailed backup/restore architecture and when one should go for a particular kind of
backup.
What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:
Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.
Back to top
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:
Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.
Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".
What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.
What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
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 DELETE operation 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 there's 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 can't 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 for INSTEAD 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 insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.
Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)
Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.
Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.
What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.
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.
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
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.
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433
(Note: the first comment, "<--" hides the content of the script from browsers that don't understand javascript. The "// -->" finishes the
comment. The "//" tells javascript that this is a comment so javascript doesn't try to interpret the "-->". If your audience has much
older browsers, you should put this comments inside your javascript. If most of your audience has newer browsers, the comments
can be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.tx
24. In a pop-up browser window, how do you refer to the main browser window that opened it?
Use window.opener to refer to the main window from pop-ups
.
26. Methods GET and POST in HTML forms - what's the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about
2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST.
However, there are limits on the maximum amount of data that can be transferred in one name/value pair.
37. What are the ways to emit client-side JavaScript from server-side code in ASP.NET?
The Page object in ASP.NET has two methods that allow emitting of client-side JavaScript:
RegisterClientScriptBlock and RegisterStartupScript.
43. How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script src="abc.js"></script>How to access an external javascript file that is stored externally and not embedded? where abc.js is
the external javscript file to be accessed.
<script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html code </NOSCRIPT>
73. How to find the selected radio button immediately using the 'this' variable?
<script>
function favAnimal(button) {
alert('You like '+button.value+'s.');
}.....<input type="radio" name="marsupial" value="Tasmanian Tiger"
onchange="favAnimal(this)">Tasmanian Tiger
84. How to open a window with no toolbar, but with the location object.
window.open("http://www.mysite.org/Misc/Pennies","Pennies","resizable=yes,
status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400"
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
103. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified seperator between them.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
108. eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during exection.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
2. But some browsers taking CSS as case sensitive, where there may be the use of XML document and
XHTML doctypes.
3. It is better practice to avoid CSS classes with same name, where the only difference is case.
4.Parts that are not under control of CSS like font family names and URLs can be case sensitive -
IMAGE.gif and image.gif is not the same file.
In HTML attributes, CSS properties which one take precedence over another?
Posted by: Peermohamedmydeen
CSS properties always take precedence over HTML attributes. If both are specified, HTML attributes will
be displayed in browsers without CSS support, but won't have any effect in browsers with CSS support.
P:first-line
H1:first-letter
First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:
<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>
First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:
<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>
The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.
The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1
Any element with CLASS footnote will be red but only if it occurs in the context of P
Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P
What is ID selector?
Posted by: Chikul
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.
<P ID=abc123>This and only this element can be identified as abc123 </P>
Embedded CSS codes are placed within the HEAD area of the page code. That is anywhere after the
<HEAD> tag and before the </HEAD> tag. NOT in the HEAD tag itself.
Now, whenever any of those elements are used within the body of the document, they will be formatted
as instructed in the above style sheet.
Web.config file is the configuration file for the Asp.net web application. There is one web.config file for
one asp.net application which configures the particular application. Web.config file is written in XML with
specific tags having specific meanings.It includes databa which includes connections,Session
States,Error Handling,Security etc. For example :
< configuration >
< appSettings >
< add key="ConnectionString"
value="server=localhost;uid=sa;pwd=;database=MyDB" / >
< /appSettings >
< /configuration >
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for
responding to application-level and session-level events raised by ASP.NET or by HTTPModule.If you
remember it's same as global.asa in ASP. The Global.asax file resides in the root directory of an
ASP.NET application. At run time, Global.asax is parsed and compiled into a dynamically generated .NET
Framework class derived from the HttpApplication base class. ASP.NET is configured so that any direct
URL request for the Global.asax file is automatically rejected.
The HTTPApplication class exposes the following events for you to handle.
AcquireRequestState
AuthenticateRequest
AuthorizeRequest
BeginRequest
EndRequest
Error
PostRequestHandlerExecute
PreRequestHandlerExecute
PreSendRequestContent
PreSendRequestHeaders
ReleaseRequestState
ResolveRequestCache
UpdateRequestCache
(Note: the first comment, "<--" hides the content of the script from browsers that don't understand
javascript. The "// -->" finishes the comment. The "//" tells javascript that this is a comment so javascript
doesn't try to interpret the "-->". If your audience has much older browsers, you should put this comments
inside your javascript. If most of your audience has newer browsers, the comments can be omitted. For
brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely username@website.txt.
c:\Windows\Cookies\username@Website.tx
24. In a pop-up browser window, how do you refer to the main browser window that opened it?
Use window.opener to refer to the main window from pop-ups
.
26. Methods GET and POST in HTML forms - what's the difference?.
GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET
method is limited to about 2kb.
POST: Parameters are passed in the request body. There is no limit to the amount of data that can be
transferred using POST. However, there are limits on the maximum amount of data that can be
transferred in one name/value pair.
43. How to access an external javascript file that is stored externally and not embedded?
This can be achieved by using the following tag between head tags or between body tags.
<script src="abc.js"></script>How to access an external javascript file that is stored externally and not
embedded? where abc.js is the external javscript file to be accessed.
<script language=javascript> <!-- javascript code goes here // --> or Use the <NOSCRIPT>some html
code </NOSCRIPT>
73. How to find the selected radio button immediately using the 'this' variable?
<script>
function favAnimal(button) {
alert('You like '+button.value+'s.');
}.....<input type="radio" name="marsupial" value="Tasmanian Tiger"
onchange="favAnimal(this)">Tasmanian Tiger
84. How to open a window with no toolbar, but with the location object.
window.open("http://www.mysite.org/Misc/Pennies","Pennies","resizable=yes,
status=yes,toolbar=yes,location=yes,menubar=yes,scrollbars=yes,width=800,height=400"
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
103. How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified seperator between them.
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
108. eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code during exection.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
AppDomain: An AppDomain is a light-weight process which separates one application in .NET with
another. CLR creates an AppDomain when an application is loaded. Each application will have an
AppDomain associated. Each AppDomain can have different threads running in it. Each app domain will
have its associated code, data and configuration. Hence when one application crashes, it does not affect
other.
Thread: Each process can have multiple threads. Multiple threads can share same execution code and
resources. A multi-threaded process can perform several tasks concurrently.
.NET framework supports different type of applications like Web, windows, console etc,. Each type of
application needs a runtime host to start it. This runtime host loads the runtime into a process, creates the
application with in the process and loads the application code into the process.
ASP.NET: It loads the runtime that can handle a web request into the process. ASP.NET also creates an
application domain for each Web application that will run on a Web server.
Shell executables: When ever a runtime executable is launched from the shell, this executable invokes
the corresponding runtime host.
Code which targets the .NET framework CLR is manageable meaning CLR can provide its services like
type safety, memory management, exceptional handling etc to this type of code. Managed code is always
compiled into MSIL. When a .NET application is run this compiled MSIL is compiled to native code using
JIT (Just In Time compiler). This JIT generates the native code as per the hardware specification on the
system. Since all this process happens under the control of a managed environment CLR, CLR provides
all its rich functionality. Managed code provides platform independence since the code is converted to
MSIL and then converted to native code depending on the system architecture.
The code that does not target CLR is unmanageable. It cannot run under CLR. This code directly runs
under OS control. Applications written in traditional applications like C++, VB, C generate unmanaged
code. This targets the computer architecture. Unmanaged code is always compiled to target a specific
architecture and will only run on the intended platform. This means that if you want to run the same code
on different architecture then you will have to recompile the code using that particular architecture.
Unmanaged code is always compiled directly to the native code which is architecture specific. This code
cannot be executed on other platforms that are different than the one on which the code was compiled. All
the features provided by CLR are unavailable and are to be taken care by the code. Hence this causes
memory leaks in traditional applications.
Value types: Value types inherit from the System.ValueType class, which in turn, inherits from
System.Object. Value types are stored on stack. They are implicitly sealed. Structs and Enumerations are
value types and they are always stored on stack. A value type cannot contain a null value. Variables that
are value types store data.
Reference types: Variables to reference types referred to as object, store reference to actual data. Actual
data is stored on the heap and reference is stored on the stack. This allows the garbage collector to track
outstanding references to a particular instance and free the instance when no references remain.
Integral types : sbyte, byte, char, short, ushort, int, uint, long, ulong
Floating Point types: float, double
Decimal types: decimal
Objects created are stored on heap. Since the memory (here heap) is exhaustible, .NET identifies a
mechanism to collect the unused memory(heap). GC does an automatic sweep of heap once it is full. GC
can only destroy managed objects.
GC will finalize all the objects in the memory that are not being used anymore and thereby freeing the
memory allocated to them.
.NET uses a three-generation approach to collecting memory. Newly allocated memory tends to be freed
more frequently than older allocations, which tend to be more permanent. Gen 0 (Zero) is the youngest
generation and, after a garbage collection, any survivors go on to Gen 1. Likewise, any survivors of a Gen
1 collection go on to Gen 2. Usually garbage collection will occur only on Gen 0, and only if after it has
reached some limit. Until memory is exhausted, the cost of allocating each new object is that of
incrementing a pointer--which is close to the performance of advancing the stack pointer.
CLR calls the GC when there is a high memory pressure and it is not able to find any exact place to
allocate a new object or the applied threshold is reached.
In applications with significant memory requirements, you can force garbage collection by invoking the
GC.Collect method from the program.
What is CLR?
CLS: Common Language specification is a set of rules that are to be followed by a language in order to
be .NET complaint. This facilitates cross-language integration. Programs written in one .NET language
can interoperate with programs written in another .NET language.
CTS: Common Type System Common Type System (CTS) describes how types are declared, used and
managed. CTS facilitates cross-language integration, type safety, and high performance code execution.
Actually during just-in-time (JIT) compilation, an optional verification process examines the metadata and
Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify
that they are type safe. This process is skipped if the code has permission to bypass verification. For
example, the runtime cannot prevent unmanaged code from calling into native (unmanaged) code and
performing malicious operations. When code is type safe, the runtime's security enforcement mechanism
ensures that it does not access native code unless it has permission to do so. All code that is not type
safe must have been granted Security Permission with the passed enum member SkipVerification to run.
What is an assembly?
An assembly is a basic building block for an application. It can be a DLL or EXE. An assembly contains
IL. It consists of metadata about the types inside the assembly.
(You have to install the Microsoft .NET Framework Version 1.1 Redistributable Package before installing
the .NET SDK.)
Explain Namespace.
Namespaces are logical groupings of names used within a program. There may be multiple namespaces
in a single application code, grouped based on the identifiers’ use. The name of any given identifier must
appear only once in its namespace.
What is CLI?
The CLI is a set of specifications for a runtime environment, including a common type system, base class
library, and a machine-independent intermediate code known as the Common Intermediate Language
(CIL). (Source: Wikipedia.)
What is Postback?
When an action occurs (like button click), the page containing all the controls within the <FORM... > tag
performs an HTTP POST, while having itself as the target URL. This is called Postback.
more +
It is very difficult in today's job market to find well-qualified database developers. As a colleague of mine
once said, "SQL development is a language that is easy to learn, but very difficult to master."
When I interview SQL Server database developer candidates, I use a standard set of baseline technical
questions. The following questions are ones that I find can really help weed out less-qualified candidates.
They are listed in order from easiest to more difficult. When you get to the question about primary and
foreign keys, it starts to get challenging because the answers can be more difficult to explain and
articulate, especially in an interview setting.
Can you give me an overview of some of the database objects available for use in SQL Server 2000?
You are looking for objects such as: tables, views, user-defined functions, and stored procedures; it's
even better if they mention additional objects such as triggers. It's not a good sign if an applicant cannot
answer this basic question.
What is an index? What types of indexes are available in SQL Server 2000?
Any experienced database developer should be able to answer this question with ease. Some of the less-
experienced developers will be able to answer it, but with a little less clarity.
The value NULL is a very tricky subject in the database world, so don't be surprised if several applicants
trip up on this question.
The value NULL means UNKNOWN; it does not mean '' (empty string). Assuming ANSI_NULLS are on in
your SQL Server database, which they are by default, any comparison to the value NULL will yield the
value NULL. You cannot compare any value with an UNKNOWN value and logically expect to get an
answer. You must use the IS NULL operator instead.
A primary key is the field(s) in a table that uniquely defines the row in the table; the values in the primary
key are always unique. A foreign key is a constraint that establishes a relationship between two tables.
This relationship typically involves the primary key field(s) from one table with an adjoining set of field(s)
in another table (although it could be the same table). The adjoining field(s) is the foreign key.
What are triggers? What are the different types of triggers in SQL Server 2000?
It's very beneficial for a potential database developer to know the types of triggers available, and how to
implement them.
A trigger is a specialized type of stored procedure that is bound to a table or view in SQL Server 2000. In
SQL Server 2000, there are INSTEAD-OF triggers and AFTER triggers. INSTEAD-OF triggers are
procedures that execute in place of a Data Manipulation Language (DML) statement on a table. For
example, if I have an INSTEAD-OF-UPDATE trigger on TableA, and I execute an update statement on
that table, the code in the INSTEAD-OF-UPDATE trigger will execute instead of the update statement that
I executed.
An AFTER trigger executes after a DML statement has taken place in the database. These types of
triggers are very handy for auditing data changes that have occurred in your database tables.
How can you ensure that a table named TableB with a field named Fld1 will only have those values in the
Fld1 field that are also in the table named TableA with a field named Fld1?
This relationship related question has two potential answers. The first answer (and the one that you want
to hear) is the use of foreign key constraints. A foreign key constraint is used to maintain referential
integrity. It is used to ensure that a field in a table will only hold values that are already defined in another
field in a different (or the same) table. That field is the candidate key (usually a primary key of the other
table).
The other option is the use of triggers. Triggers can be used to ensure the same effect of constraints in a
roundabout way, but it is much more difficult to set up and maintain, and the performance is typically
worse. Because of this, Microsoft recommends that developers use foreign key constraints instead of
triggers for maintaining referential integrity.
What is a performance consideration of having too many indexes on a production online transaction
processing (OLTP) table?
You are looking for the applicant to make some reference regarding data manipulations. The more
indexes on a table, the more time it takes for the database engine to update, insert, or delete data, as the
indexes all have to be maintained as the data manipulation occurs.
What can be used to ensure that a field in a table only accepts a certain range of values?
This question can be answered a couple of different ways, but only one answer is a "good" one. The
answer you want to hear is a Check constraint, which is defined on a database table that limits the values
entered into that column. These constraints are relatively easy to create, and they are the recommended
type for enforcing domain integrity in SQL Server.
Triggers can also be used to restrict the values accepted in a field in a database table, but this solution
requires the trigger to be defined on the table, which can hinder performance in certain situations. For this
reason, Microsoft recommends Check constraints over all other methods for restricting domain integrity.
If the applicant is able to answer this question correctly, the odds are good that they have some
experience working with stored procedures.
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. (There are some limitations on the data types that can be used
as output parameters.) You can use multiple OUTPUT parameters in a stored procedure, whereas you
can only use one return parameter.
The more seasoned developer will be able to accurately describe this type of query.
A correlated sub-query is a special type of query containing a sub-query. The sub-query contained in the
query actually requests values from the outside query, creating a situation similar to a loop. You can find
a more detailed description as to how these special types of queries work in this article.
Here are some SQL Server DBA/Developer interview questions I faced myself personally and/or heard
from people. I will try to answer these questions briefly here, but be advised that these answers may not
be complete and it will be better for you to go through text books, books online and other resources on the
net. At the end of this article, I listed some useful books for aspiring DBAs and developers.
Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.
Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.
Questions are categorized under the following sections, for your convenience:
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-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype can represent a third state, which is NULL.
A key formed by combining at least two or more columns is called composite key.
Back to top
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's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log,
which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion
of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of
course, TRUNCATE TABLE can be rolled back.
What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.
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"
Whar 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 craete 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 it's 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 t ime, 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.
Back to top
What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.
Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.
Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com
What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.
Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices
What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.
Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.
How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.
As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.
What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.
Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats
What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database
backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in
SQL Server books online. Be prepared to write the commands in your interview. Books online also has
information on detailed backup/restore architecture and when one should go for a particular kind of
backup.
What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:
Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.
Back to top
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:
Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.
Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".
What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.
What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
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 DELETE operation 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 there's 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 can't 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 for INSTEAD 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 insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.
Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)
Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.
Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.
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.
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
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.
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433
Here are some SQL Server DBA/Developer interview questions I faced myself personally and/or heard
from people. I will try to answer these questions briefly here, but be advised that these answers may not
be complete and it will be better for you to go through text books, books online and other resources on the
net. At the end of this article, I listed some useful books for aspiring DBAs and developers.
Before you go for the interview, be prepared to explain the database design of one of your latest projects.
Don't be surprised if the interviewer asks you to draw ER diagrams.
Well, here are some questions for you. Hope this helps you prepare for your interview. Wish you all the
best in your job hunt! Feel free to email me 'interview questions' that you've faced.
Questions are categorized under the following sections, for your convenience:
Database design (8 questions)
SQL Server architecture(12 questions)
Database administration(13 questions)
Database programming (10 questions)
Database design (top)
What is normalization? Explain different levels of normalization?
Check out the article Q100139 from Microsoft knowledge base and of course, there's much more
information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book,
especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.
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-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name,
and format to the database. Take for example, in your database, there is a column called Flight_Num
which appears in many tables. In all these tables it should be varchar(8). In this case you could create a
user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit
datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards,
bit datatype can represent a third state, which is NULL.
A key formed by combining at least two or more columns is called composite key.
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's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log,
which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion
of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of
course, TRUNCATE TABLE can be rolled back.
What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time
of your interview)? What changed between the previous version of SQL Server and the current version?
This question is generally asked to see how current is your knowledge. Generally there is a section in the
beginning of the books online titled "What's New", which has all such information. Of course, reading just
that is not enough, you should have tried those things to better answer the questions. Also check out the
section titled "Backward Compatibility" in books online which talks about the changes that have taken
place in the new version.
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"
Whar 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 craete 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 it's 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 t ime, 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.
Back to top
Database administration(top)
What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database
servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance.
MSDN has some information about RAID levels and for detailed information, check out the RAID advisory
board's homepage
What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a
query. But some general issues that you could talk about would be: No indexes, table scans, missing or
out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers
without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.
Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL
ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000
Performance monitor, Graphical execution plan in Query Analyzer.
Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to
check out sql-server-performance.com
What are the steps you will take, if you are tasked with securing an SQL Server?
Again this is another open ended question. Here are some things you could talk about: Preferring NT
authentication, using server, databse and application roles to control access to the data, securing the
physical database files using NTFS permissions, using an unguessable SA password, restricting physical
access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling
the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls,
isolating SQL Server from the web server etc.
Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server
security best practices
What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire
a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless
one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's
process.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of
overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and
refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page,
forcing a write transaction to wait indefinitely.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also
check out the article Q169960 from Microsoft knowledge base.
Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding
efficient transactions.
How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very
important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in
single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL
Server books online for more parameters and their explanations.
As a part of your job, what are the DBCC commands that you commonly use for database maintenance?
DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC
SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of
DBCC commands which are very useful for DBAs. Check out SQL Server books online for more
information.
What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the
selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses
these indexes in determining whether to choose an index or not while executing a query.
Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the
distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE
statement and then repopulated
3) Database is upgraded from a previous version
Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE,
DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats,
sp_updatestats
What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements.
Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication,
DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
Explian different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would
you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database
backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in
SQL Server books online. Be prepared to write the commands in your interview. Books online also has
information on detailed backup/restore architecture and when one should go for a particular kind of
backup.
What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers.
SQL Server supports the following types of replication scenarios:
Snapshot replication
Transactional replication (with immediate updating subscribers, with queued updating subscribers)
Merge replication
See SQL Server books online for indepth coverage on replication. Be prepared to explain how different
replication agents function, what are the main system tables used in replication etc.
Back to top
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike
In this situation many developers tend to use a cursor, determine each employee's salary and update his
salary according to the above formula. But the same can be achieved by multiple update statements or
can be combined in a single UPDATE statement as shown below:
Another situation in which developers tend to use cursors: You need to call a stored procedure when a
column in a particular row meets certain condition. You don't have to use cursors for this. This can be
achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using
WHILE loop for row by row processing, check out the 'My code library' section of my site or search for
WHILE.
Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".
What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++
using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored
procedures using the EXEC statement. See books online to learn how to create extended stored
procedures and how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using
sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-
SQL, see 'My code library' section of this site.
What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER,
SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().
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 DELETE operation 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 there's 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 can't 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 for INSTEAD 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 insterted rows to it for some custom processing. What do
you think of this implementation? Can this be implemented better?
Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it
slows down the data insertion process. Same is the case with sending emails from triggers. This scenario
can be better implemented by logging all the necessary data into a separate table, and have a job which
periodically checks this table and does the needful.
Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without
managers (super bosses)
Given an employee table, how would you find out the second highest salary?
For a solution see the 'My code library' section of this site.
Begin Transaction
Update names_table set employee_name = "Ramesh" where employee_name = "Mahesh"
Save Transaction SAVE_POINT
Update salaries set salary=salary + 900 where employee_job = "Engineer"
Rollback transaction
Commit transaction
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE)
occurs.
What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as
updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the
view was created with.
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.
How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and
foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and
foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables
forming the composite primary key of the junction table.
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.
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433
Which of these is a CSS pseudo class? A) .abc { color:green; } B) a:visited { color:green; } C) h1 h2
{ color:green; }
Posted by: Ddd
NOTE: This is objective type question, Please click question title for correct answer.
2. But some browsers taking CSS as case sensitive, where there may be the use of XML document and
XHTML doctypes.
3. It is better practice to avoid CSS classes with same name, where the only difference is case.
4.Parts that are not under control of CSS like font family names and URLs can be case sensitive -
IMAGE.gif and image.gif is not the same file.
In HTML attributes, CSS properties which one take precedence over another?
Posted by: Peermohamedmydeen
CSS properties always take precedence over HTML attributes. If both are specified, HTML attributes will
be displayed in browsers without CSS support, but won't have any effect in browsers with CSS support.
P:first-line
H1:first-letter
P.initial:first-line
First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:
First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:
<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>
The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.
The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1
Any element with CLASS footnote will be red but only if it occurs in the context of P
Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P
What is ID selector?
Posted by: Chikul
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.
<P ID=abc123>This and only this element can be identified as abc123 </P>
Embedded CSS codes are placed within the HEAD area of the page code. That is anywhere after the
<HEAD> tag and before the </HEAD> tag. NOT in the HEAD tag itself.
Now, whenever any of those elements are used within the body of the document, they will be formatted
as instructed in the above style sheet.
'Fixed' Background?
There is the possibility to use the HTML tag bgproperties="fixed", but that is IE proprietary, and
dependent upon the 'background' attribute (deprecated in HTML4).
BODY {
font-family : "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
background-image: url(images/yourimage.gif);
background-repeat: no-repeat; /*no-tiling background*/
background-position: center;
background-attachment: fixed;
background-color: #hexcolor;
color : #hexcolor;
margin: 10px;
}
that shows a background-image in the center of the <BODY> element, non-scrolling and non-repeating -
in IE or NN6. NN 4.xx gets the non-repeat-part right, but stuffs the picture in the upper left corner and
scrolls ...
<HEAD>
<STYLE TYPE="text/css">
<!--
P {text-indent: 10pt}
-->
</STYLE>
</HEAD>
Note: The styling rules are written as a HTML comment, that is, between <!-- and --> to hide the content
in browsers without CSS support which would otherwise be displayed.
What is ID selector?
ID selector is an individually identified (named) selector to which a specific style is declared. Using the ID
attribute the declared style can then be associated with one and only one HTML element per document
as to differentiate it from all other elements. ID selectors are created by a character # followed by the
selector's name. The name can contain characters a-z, A-Z, digits 0-9, period, hyphen, escaped
characters, Unicode characters 161-255, as well as any Unicode character as a numeric code, however,
they cannot start with a dash or a digit.
<P ID=abc123>This and only this element can be identified as abc123 </P>
The element CODE will be displayed in red but only if it occurs in the context of the element P which must
occur in the context of the element TD.
The element CODE will be displayed in red as described above AND the element EM will also be red but
only if it occurs in the context of H1
Any element with CLASS footnote will be red but only if it occurs in the context of P
Any element with attribute LANG will be red but only if it is classed as "footnote" and occurs in the context
of P
The digits and letters after the backslash (\) are a hexadecimal number. Hexadecimal numbers are made
from ordinary digits and the letters A to F (or a to f). Unicode numbers consist of four such digits.
If the number starts with a 0, you may omit it. The above could also be written as:
Disadvantages
* Classes can be created for use on multiple tag types in the document
* Selector and grouping methods can be used to apply styles under complex contexts
* No additional downloads necessary to receive style information
Disadvantages
* This method can not control styles for multiple documents at once
Inline Styles
Advantages
Disadvantages
* Does not distance style information from content (a main goal of SGML/HTML)
* Can not control styles for multiple documents at once
* Author can not create or control classes of elements to control multiple element types within the
document
* Selector grouping methods can not be used to create complex element addressing scenarios
* fonts
* colors
* layout
* positioning
* imagery
* accessibility
Style sheets give you a lot of power to define how your pages will look. And another great thing about
them is that style sheets make it really easy to update your pages when you want to make a new design.
Simply load in a new style sheet onto your pages and you're done.
Preferred style is a default style that applies automatically and is declared by setting the TITLE attribute to
the LINK element. There can only be one preferred style, e.g.:
Alternate style gives an user the choice of selecting an alternative style - a very convenient way of
specifying a media dependent style. Note: Each group of alternate styles must have unique TITLE, e.g.:
As the property is non-standard, it won't validate with the W3C validator, so if we put it in the head like
this (above) - in an IE conditional comment - the validator will ignore it and the page will get a clean bill of
health.
If instead you're interested in those browsers which are known to do a credible job of bug-free and mostly
completel support for CSS1, then the list narrows somewhat dramatically:
3. CSS is a language that adds style (colors, images, borders, margins?) to your site. It?s really that
simple. CSS is not used to put any content on your site, it?s just there to take the content you have and
make it pretty. First thing you do is link a CSS-file to your HTML document. Do this by adding this line:
The line should be placed in between your <head> and </head> tags. If you have several pages you
could add the exact same line to all of them and they will all use the same stylesheet, but more about that
later. Let?s look inside the file ?style.css? we just linked to.
h1 {
font-size: 40px;
height: 200px;
}
.warning {
color: Red;
font-weight: bold;
}
#footer {
background-color: Gray;
}
4. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g. fonts, colors, spacing) to
Web documents. This is also where information meets the artistic abilities of a web-designer. CSS helps
you spice up your web-page and make it look neat in wide variety of aspects.
1. By setting the properties margin-left and margin-right to auto and width to some explicit value:
In this case, the left and right margins will each be four ems wide, since they equally split up the eight
ems left over from (30em - 22em). Note that it was not necessary to set an explicit width for the BODY
element; it was done here to keep the math clean.
Another example:
If background and color should always be set together, why do they exist as separate properties?
There are several reasons for this. First, style sheets become more legible -- both for humans and
machines. The background property is already the most complex property in CSS1 and combining it with
color would make it even more complex. Second, color inherits, but background doesn't and this would be
a source of confusion.
What is class?
Class is a group of 1) instances of the same element to which an unique style can be attached or 2)
instances of different elements to which the same style can be attached.
1) The rule P {color: red} will display red text in all paragraphs. By classifying the selector P different style
can be attached to each class allowing the display of some paragraphs in one style and some other
paragraphs in another style.
2) A class can also be specified without associating a specific element to it and then attached to any
element which is to be styled in accordance with it's declaration. All elements to which a specific class is
attached will have the same style.
To classify an element add a period to the selector followed by an unique name. The name can contain
characters a-z, A-Z, digits 0-9, period, hyphen, escaped characters, Unicode characters 161-255, as well
as any Unicode character as a numeric code, however, they cannot start with a dash or a digit. (Note: in
HTML the value of the CLASS attribute can contain more characters). (Note: text between /* and */ are
my comments).
CSS
P.name1 {color: red} /* one class of P selector */
P.name2 {color: blue} /* another class of P selector */
.name3 {color: green} /* can be attached to any element */
HTML
<P class=name1>This paragraph will be red</P>
<P class=name2>This paragraph will be blue</P>
<P class=name3>This paragraph will be green</P>
<LI class=name3>This list item will be green</LI>
It is a good practice to name classes according to their function than their appearance; e.g. P.fotnote and
not P.green. In CSS1 only one class can be attached to a selector. CSS2 allows attaching more classes,
e.g.:
P.name1.name2.name3 {declaration} <P class="name1 name2 name2">This paragraph has three
classes attached</P>
What is grouping ?
Grouping is gathering (1) into a comma separated list two or more selectors that share the same style or
(2) into a semicolon separated list two or more declarations that are attached to the same selector (2).
1. The selectors LI, P with class name .first and class .footnote share the same style, e.g.:
LI {font-style: italic}
P.first {font-style: italic}
.footnote {font-style: italic}
To reduce the size of style sheets and also save some typing time they can all be grouped in one list.
LI, P.first, .footnote {font-style: italic}
2. The declarations {font-style: italic} and {color: red} can be attached to one selector, e.g.:
H2 {font-style: italic}
H2 {color: red}
and can also be grouped into one list:
H2 {font-style: italic; color: red}
It is a good idea to avoid naming classes where the only difference is the case, for example:
div.myclass { ...}
div.myClass { ... }
If the DOCTYPE or XML declaration is ever removed from your pages, even by mistake, the last instance
of the style will be used, regardless of case.
The way the code goes into your Web-page is through a variety of ways. The way CSS works is that is
the code is set between the<head></head> tags. You can put the CSS code after </title> which is
what most people do. Now, here are the following ways of making your webpage with CSS enabled
features:
1.) Writing your CSS code within your HTML source code. This is how it would look like:
2.) Linking to your CSS file. This tells the webpage to find the .css file and use it as the CSS code.
Here is the code that would allow you to do:
<html><head><title>CSS</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head><body /></html>
As you can see from the code above, the <link> tag is pretty helpful. What it does is that it links to
the style.css file which has all the css code. Just like embedding an image throught he <img> tag.
Now to explain a bit from the first example. CSS code isn't very hard to understand.Take for example
the body { ..} part. What it does is that it formats how the <body> tag in HTML would work. That is a
very simple way of formatting the body tag with the CSS. To help you understand better, here is a
simple syntax for CSS:
The "selector" sort of relates to the html tags used for outputting etc...
We all know that <a> is a tag used for links. You will see in the example about a:hover and a itself.
<br>What a does it just sets the characteristics of the format. You can set how you want a link to
appear using the font size, weight etc..
Then comes the "a:hover". What does is also pretty self explanatory. It acts on when a person moves
the mouse cursor over the links.
<style type="text/css">
<!--
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// -->
</style>
<style type="text/css">
<!--
BODY {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
TEXTAREA {
scrollbar-arrow-color: green;
scrollbar-face-color: #FFFFFF;
scrollbar-track-color: rgb(12,35,244);
}
// -->
</style>
That above code, has some similarities. The textbox area is treated with the same function statements
as for the scrollbar. The scrollbar statements goes in the BODY selector.
Why does my content shift to the left on some pages (in FF)?
That'll be the pages with more content? The ones that have a vertical scrollbar? If you look in IE
there's probably a white space on the right where there would be a scrollbar if there were enough
content to require one. In Firefox, the scrollbar appears when it's needed and the viewport becomes
about 20px smaller, so the content seems to shift to the left when you move from a page with little
content to one with lots of content. It's not a bug or something that needs to be fixed, but it does
confuse and irritate some developers.
If, for some reason, you'd like Firefox to always have scrollbars - whether they're needed or not - you
can do this :
CSS html {
height:100.1%;
}
How do I combine multiple sheets into one?
To combine multiple/partial style sheets into one set the TITLE attribute taking one and the same
value to the LINK element. The combined style will apply as a preferred style, e.g.:
body {
background: white url(example.gif) ;
color: black ;
}
If you specify a background image, you should also specify text, link, and background colors since the
reader's default colors may not provide adequate contrast against your background image. The
background color may be used by those not using your background image. Authors should not rely on
the specified background image since browsers allow their users to disable image loading or to
override document-specified backgrounds.
How do I have a fixed (non-scrolling) background image?
With CSS, you can use the background-attachment property. The background attachment can be
included in the shorthand background property, as in this example:
body {
background: white url(example.gif) fixed ;
color: black ;
}
Note that this CSS is supported by Internet Explorer, Mozilla, Firefox Opera, Safari, and other
browsers. In contrast, Microsoft's proprietary BGPROPERTIES attribute is supported only by Internet
Explorer.
What are inline, block, parent, children, replaced and floating elements?
Inline
elements which do not have line breaks. Can occur in block elements or other inline elements, cannot
contain block elements.
Inline elements in HTML 3.2; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, TT, I, B, U, STRIKE,
BIG, SMALL, SUB, SUP, A, IMG, APPLET, FONT, BASEFONT, BR, SCRIPT, MAP, INPUT, SELECT,
TEXTAREA.
Inline elements in HTML 4.0; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR, ACRONYM, TT,
I, B, BIG, SMALL, SUB, SUP, A, IMG, OBJECT, BR, SCRIPT, MAP, Q, SPAN, BDO, INPUT, SELECT,
TEXTAREA, LABEL, BUTTON, (INS, DEL).
Inline elements in HTML 4.0 Transitional; EM, STRONG, DFN, CODE, SAMP, KBD, VAR, CITE, ABBR,
ACRONYM, TT, I, B, U, S, STRIKE, BIG, SMALL, SUB, SUP, A, IMG, APPLET, OBJECT, FONT,
BASEFONT, BR, SCRIPT, MAP, Q, SPAN, BDO, IFRAME, INPUT, SELECT, TEXTAREA, LABEL, BUTTON,
(INS, DEL).
Block
elements which do have line breaks. May occur in other block elements, cannot occur in inline
elements, may contain both block and inline elements.
Block elements in HTML 3.2; H1, H2, H3, H4, H5, H6, ADDRESS, P, DL, DT, DD, UL, OL, DIR, MENU,
LI, DIV, CENTER, BLOCKQUOTE, PRE, HR, ISINDEX, TABLE, FORM.
Block elements in HTML 4.0; P, H1, H2, H3, H4, H5, H6, UL, OL, PRE, DL, DIV, NOSCRIPT,
BLOCKQUOTE, FORM, HR, TABLE, FIELDSET, ADDRESS, (INS, DEL).
Block elements in HTML 4.0 Transitional; P, H1, H2, H3, H4, H5, H6, UL, OL, DIR, MENU, PRE, DL,
DIV, CENTER, NOSCRIPT, NOFRAMES, BLOCKQUOTE, FORM, ISINDEX, HR, TABLE, FIELDSET,
ADDRESS, (INS, DEL).
In CSS you just add the nifty <link>-tag I?ve told you about to the head of your HTML document and
you have created a link to your design. In the HTML document you put content only, and that link of
yours makes sure it looks right. You can also use the exact same link on many of your pages, giving
them all of them the same design. You want to add content? Just write a plain HTML document and
think about marking things up like ?header? instead of ?big blue header? and use CSS to make all
headers look the way you want!
Some examples of good and bad coding. What?s wrong with this?
<font size="3">Welcome to my page</font>
Comment: The font-tag is design and design shouldn?t be in the HTML document. All design should be
in the CSS-file! Instead do this:
In the HTML:
<h1>Welcome to my page</h1>
In the CSS:
h1 { font-size: 2em; }
This looks right doesn?t it? But if you look up what <b> stands for you quickly find bold. But bold is
certainly design, so it still doesn?t belong in the HTML document. A better choice is <em> that stands
for emphasis or simply ?this piece of text is important?. So instead of saying ?this text looks like this?
you are saying ?this text is important? and you let the looks be decided by the CSS. Seems like a
minor change, but it illustrates how to select your tags. Use this instead:
In the HTML:
<em>An error occured</em>
In the CSS:
em {
font-weight: bold;
color: Red;
}
<table>
<tr><td><a href="">first link</a></td></tr>
<tr><td><a href="">second link</a></td></tr>
...
</table>
Can CSS be used with other than HTML documents?
Yes. CSS can be used with any ny structured document format. e.g. XML, however, the method of
linking CSS with other document types has not been decided yet.
Can Style Sheets and HTML stylistic elements be used in the same document?
Yes. Style Sheets will be ignored in browsers without CSS-support and HTML stylistic elements used.
What are pseudo-classes?
Pseudo-classes are fictional element types that do not exist in HTML. In CSS1 there is only one
element type which can be classed this way, namely the A element (anchor). By creating three
fictional types of the A element individual style can be attached to each class. These three fictional
element types are: A as unvisited link, A as active link and A as visited link. Pseudo-classes are
created by a colon followed by pseudo-class's name. They can also be combined with normal classes,
e.g.:
<A HREF....>This anchor (or rather these anchors) will be displayed as declared above</A>
<A CLASS=foot HREF....>This anchor and all other anchors with CLASS foot will be displayed as
declared above</A>
How do I design for backward compatibility using Style Sheets?
Existing HTML style methods (such as <font SIZE> and <b>) may be easily combined with style sheet
specification methods. Browsers that do not understand style sheets will use the older HTML
formatting methods, and style sheets specifications can control the appearance of these elements in
browsers that support CSS1.
As a reader, how can I make my browser recognize my own style sheet?
Netscape
It is not possible to do this in Netscape yet (as of version 4.0.)
Internet Explorer 3.0 (Win95/NT)
[It is possible to do this at least in Windows95/NT, but no user interface is provided. Unknown how
this might be accomplished on other operating systems.]
CSS
img {display:block;}
One problem that this can cause is when you want to have a few images next to each other - if they
are block-level, they won't be next to each other. To get around that, you can use float:left. Of
course, this might present another problem - maybe you don't want the image to float left. In this
case, you can use an unordered list like this :
CSS
ul, li {
list-style-type:none;
padding:0;
margin:0 auto;
}
ul {
width:150px;
}
li {
float:left;
}
HTML
<ul>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
</ul>
Why use Style Sheets?
Style sheets allow a much greater degree of layout and display control than has ever been possible
thus far in HTML. The amount of format coding necessary to control display characteristics can be
greatly reduced through the use of external style sheets which can be used by a group of documents.
Also, multiple style sheets can be integrated from different sources to form a cohesive tapestry of
styles for a document. Style sheets are also backward compatible - They can be mixed with HTML
styling elements and attributes so that older browsers can view content as intended.
What does the "Cascading" in "Cascading Style Sheets" mean?
Style Sheets allow style information to be specified from many locations. Multiple (partial) external
style sheets can be referenced to reduce redundancy, and both authors as well as readers can specify
style preferences. In addition, three main methods can be employed by an author to add style
information to HTML documents, and multiple approaches for style control are available in each of
these methods. In the end, style can be specified for a single element using any, or all, of these
methods. What style is to be used when there is a direct conflict between style specifications for an
element?
Cascading comes to the rescue. A document can have styles specified using all of these methods, but
all the information will be reduced to a single, cohesive "virtual" Style Sheet. Conflict resolution is
based on each style rule having an assigned weight according to its importance in the scheme of
things. A rule with a higher overall importance will carry a higher weight. This will be used in place of
a competing style rule with a lower weight/importance. A hierarchy of competing styles is thus formed
creating a "cascade" of styles according to their assigned weights. The algorithm used to determine
this cascading weight scale is fairly complex.
What is CSS rule 'at-rule'?
There are two types of CSS rules: ruleset and at-rule. At-rule is a rule that applies to the whole style
sheet and not to a specific selector only (like in ruleset). They all begin with the @ symbol followed by
a keyword made up of letters a-z, A-Z, digits 0-9, dashes and escaped characters, e.g. @import or
@font-face.
What is selector?
CSS selector is equivalent of HTML element(s). It is a string identifying to which element(s) the
corresponding declaration(s) will apply and as such the link between the HTML document and the style
sheet.
For example in P {text-indent: 10pt} the selector is P and is called type selector as it matches all
instances of this element type in the document.
in P, UL {text-indent: 10pt} the selector is P and UL (see grouping); in .class {text-indent: 10pt} the
selector is .class (see class selector).
What is CLASS selector?
Class selector is a "stand alone" class to which a specific style is declared. Using the CLASS attribute
the declared style can then be associated with any HTML element. The class selectors are created by a
period followed by the class's name. The name can contain characters a-z, A-Z, digits 0-9, period,
hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as a
numeric code, however, they cannot start with a dash or a digit. (Note: in HTML the value of the
CLASS attribute can contain more characters).It is a good practice to name classes according to their
function than their appearance.
In the example above the background property has increased weight while the color property has
normal.
What is cascade?
Cascade is a method of defining the weight (importance) of individual styling rules thus allowing
conflicting rules to be sorted out should such rules apply to the same selector.
Declarations with increased weight take precedence over declaration with normal weight:
Here, the #wrap div goes around your whole page - it's like a sub-body.
You need to use 'min-height' rather than 'height' for Firefox because otherwise it will set it to 100% of
the viewport and no more. Internet Explorer, being well... crap, treats 'height' as it should be treating
'min-height' which it doesn't recognise. (You can target IE by preceding your code with ' * html ').
To make floated divs within this #wrap div 100% of the #wrap div... well that's more difficult. I think
the best way is to use the 'faux columns' technique which basically means that you put the
background in your body rather than your columns. If the body has columns and your floats don't then
it looks like your floated content is in a column that stretches to the bottom of the page. I've used this
technique in my layout demos.
The problem is often not that the columns aren't 100% height, but that they're not equal lengths.
Columns usually don't start from the top of the page and end at the bottom - there's often a header
and a footer or sometimes, more interesting designs don't have a recognisable columnar layout, but
do require div boxes to be equal heights. This can be done with the aid of a couple of images and
some css or with some javascript.
What is property?
Property is a stylistic parameter (attribute) that can be influenced through CSS, e.g. FONT or WIDTH.
There must always be a corresponing value or values set to each property, e.g. font: bold or font:
bold san-serif.
How do I write my style sheet so that it gracefully cascades with user's personal sheet ?
You can help with this by setting properties in recommended places. Style rules that apply to the
whole document should be set in the BODY element -- and only there. In this way, the user can easily
modify document-wide style settings.
What are pseudo-elements?
Pseudo-elements are fictional elements that do not exist in HTML. They address the element's sub-
part (non-existent in HTML) and not the element itself. In CSS1 there are two pseudo-elements: 'first-
line pseudo-element' and 'first-letter pseudo-element'. They can be attached to block-level elements
(e.g. paragraphs or headings) to allow typographical styling of their sub-parts. Pseudo-element is
created by a colon followed by pseudo-element's name, e.g:
P:first-line
H1:first-letter
P.initial:first-line
First-line pseudo-element allows sub-parting the element's first line and attaching specific style
exclusively to this sub-part; e.g.:
<P class=initial>The first line of this paragraph will be displayed in uppercase letters</P>
First-letter pseudo-element allows sub-parting the element's first letter and attaching specific style
exclusively to this sub-part; e.g.:
<P class=initial>The first letter of this paragraph will be displayed in red and twice as large as the
remaining letters</P>
As a developer who works with CSS every day, I find one complication that continues to
bother me in my daily work. Support for CSS has always been good on the horizontal scope,
but vertical positioning has always been quite complicated. Alone the procedure to affix a
footer to the bottom of a screen in dependance of the amount of content is unnecessarily
difficult. The old table method provided much easier methods for this. What are your
thoughts on this and do you see improvement following in future CSS revisions?
Indeed, the CSS formatting model allows more control horizontally than vertically. This is due to
(typically) having a known width, but an unknown height. As such, the height is harder to deal with.
However, CSS2 fixed positioning allows you to place content relative to the viewport (which is CSS-
speak for window) instead of the document. For example, by setting position: fixed; bottom: 0 on an
element, it will stick to the bottom. This works in Opera, Safari and Mozilla-based browsers. IE6
doesn't support it, however. It remains to be seen if IE7 will support it.
How can I make a page look the same in e.g. NS and MSIE ?
The simple answer is, you can't, and you shouldn't waste your time trying to make it exactly the
same. Web browsers are allowed, per definition, to interpret a page as they like, subject to the
general rules set down in the HTML and CSS specifications. As a web author you can not have a prior
knowledge of the exact situation and/or medium that will be used to render your page, and it's almost
always rather counterproductive to try to control that process. There is no necessity for a well-written
page to look the same in different browsers. You may want to strive to ensure that it looks good in
more than one browser, even if the actual display (in the case of graphical browsers) comes out a bit
different. "Looking good" can be achieved by adopting sensible design and guidelines, such as not
fixing the size or face of your fonts, not fixing the width of tables, etc? Don't fight the medium; most
web users only use one browser and will never know, or bother to find out, that your page looks
different, or even "better", in any other browser.
Is there anything that CAN'T be replaced by Style Sheets?
Quite a bit actually. Style sheets only specify information that controls display and rendering
information. Virtual style elements that convey the NATURE of the content can not be replaced by
style sheets, and hyperlinking and multimedia object insertion is not a part of style sheet functionality
at all (although controlling how those objects appear IS part of style sheets functionality.) The CSS1
specification has gone out of its way to absorb ALL of the HTML functionality used in controlling display
and layout characteristics. For more information on the possible properties in CSS, see the Index DOT
Css Property Index.
Rule of Thumb: if an HTML element or attribute gives cues as to how its contents should be displayed,
then some or all of its functionality has been absorbed by style sheets.
Can I include comments in my Style Sheet?
Yes. Comments can be written anywhere where whitespace is allowed and are treated as white space
themselves. Anything written between /* and */ is treated as a comment (white space). NOTE:
Comments cannot be nested.
What is the difference between ID and CLASS?
ID identifies and sets style to one and only one occurrence of an element while class can be attached
to any number of elements. By singling out one occurrence of an element the unique value can be
declared to said element.
CSS
#eva1 {background: red; color: white}
.eva2 {background: red; color: white}
HTML - ID
<P ID=eva1>Paragraph 1 - ONLY THIS occurrence of the element P (or single occurrence of some
other element) can be identified as eva1</P>
<P ID=eva1>Paragraph 2 - This occurrence of the element P CANNOT be identified as eva1</P>
HTML - CLASS
<P class=eva2>Paragraph 1 - This occurrence of the element P can be classified as eva2</P>
<P class=eva2>Paragraph 2 - And so can this, as well as occurrences of any other element, </P>
How to make text-links without underline?
a:link, a:visited {text-decoration: none}
or
...will show the links without underlining. However, suppressing the underlining of links isn't a very
smart idea as most people are used to having them underlined. Also, such links are not spotted unless
someone coincidentally runs a mouse over them. If, for whatever reason, links without underline are
required background and foreground colors can be instead declared to them so that they can be
distinguished from other text, e.g.;
a:link, a:visited {text-decoration: none; background: red; color: blue}
or
Both background and foreground colors should be specified as the property that is not specified can be
overridden by user's own settings.
How do you make a tool tip that appears on hover?
The most simple way is to use the 'title' attribute like this...
HTML
<span title="Example of the title attribute in use">like this</span>
CSS
a.tooltip {
position:relative;
cursor:help;
}
a.tooltip span {
display: none;
position:absolute;
top:1.5em;
left:0;
width:15em;
padding:0 2px;
}
a.tooltip:hover {
display:inline;
}
a.tooltip:hover span {
display:block;
border:1px solid gray;
background-color:white;
}
HTML
The "#n" in the link is to prevent the page from jumping to the top if the link is clicked. The "href"
part is necessary as it won't work in IE without it.
Which characters can CSS-names contain?
The CSS-names; names of selectors, classes and IDs can contain characters a-z, A-Z, digits 0-9,
period, hyphen, escaped characters, Unicode characters 161-255, as well as any Unicode character as
a numeric code. The names cannot start with a dash or a digit. (Note: in HTML the value of the CLASS
attribute can contain more characters).
What browsers support style sheets? To what extent?
Microsoft's Internet Explorer version 3.0 Beta 2 and above supports CSS, as does Netscape
Communicator 4.0 Beta 2 and above and Opera 3.5 and above. Take note that the early
implementations in these browsers did not support ALL of the properties and syntax described in the
full CSS1 specification and beyond. Later versions have been getting much closer to full CSS1
compliance, but then comes the next hurdle - CSS2...it was such a big leap over CSS1 that it has
taken the browsers years to come close to supporting a majority of CSS2's features. Mozilla and
Opera's current versions both offer excellent CSS standards compliance. The Macintosh version of
Internet Explorer is said to be very impressive in its CSS capabilities as well, but PC IE lags behind
these implementations. Quite a few other implementations of CSS now exist in browsers that are not
as widely-used (such as Amaya, Arena and Emacs-W3), but coverage of features in these documents
currently only covers Internet Explorer, NCSA Mosaic, Netscape and Opera browsers.
What is cascading order?
Cascading order is a sorting system consisting of rules by which declarations are sorted out so that
there are not conflicts as to which declaration is to influence the presentation. The sorting begins with
rule no 1. If a match is found the search is over. If there is no match under rule no 1 the search
continues under rule no 2 and so on.
1. Find all declarations that apply to a specific selector/property and Declare the specified style if the
selector matches the element if there isn't any Let the element inherit its parent property if there isn't
any Use initial value
2. Sort by weight (! important) Increased weight take precedence over normal weight
3. Sort by origin Rules with normal weight declared in author's style sheet will override rules with
normal weight declared in user's personal style sheets Rules with increased weight declared in user's
personal style sheet will override rules with normal weight declared in author's style sheet Rules with
increased weight declared in author's style sheet will override rules with increased weight declared in
user's personal style sheets Author's and user's rules will override UA's default style sheet.
4. Sort by selector's specificity More specific selector will override less specific one: ID-selector (most
specific), followed by Classified contextual selectors (TABLE P EM.fot) Class selectors (EM.fot)
Contextual selectors - the "lower down" the more weight, (TABLE P EM), (TABLE P EM STRONG) -
STRONG has more weight than EM.
5. Sort by order specified If two rules have the same weight, the latter specified overrides ones
specified earlier. Style sheets are sorted out as follows: The STYLE attribute (inline style) overrides all
other styles The Style element (embedded style) overrides linked and imported sheets The LINK
element (external style) overrides imported style The @import statement - imported style sheets also
cascade with each other in the same order as they are imported
Why shouldn't I use fixed sized fonts ?
Only in very rare situations we will find users that have a "calibrated" rendering device that shows
fixed font sizes correct. This tells us that we can never know the real size of a font when it's rendered
on the user end. Other people may find your choice of font size uncomfortable. A surprisingly large
number of people have vision problems and require larger text than the average. Other people have
good eyesight and prefer the advantage of more text on the screen that a smaller font size allows.
What is comfortable to you on your system may be uncomfortable to someone else. Browsers have a
default size for fonts. If a user finds this inappropriate, they can change it to something they prefer.
You can never assume that your choice is better for them. So, leave the font size alone for the
majority of your text. If you wish to change it in specific places (say smaller text for a copyright notice
at the bottom of page), use relative units so that the size will stay in relationship to what the user
may have selected already. Remember, if people find your text uncomfortable, they will not bother
struggling with your web site. Very few (if any) web sites are important enough to the average user to
justify fighting with the author's idea of what is best.
How do you make a whole div into a link?
You can't put 'a' tags around a div, but you can do this with javascript :
HTML
<div onclick="javascript:location='http://bonrouge.com'" id="mydiv">
... stuff goes here ...
</div>
If you want to use an empty div with a background image as a link instead of putting your image into
the html, you can do something like this:
CSS
#empty {
background-image:url(wine.jpg);
width:50px;
height:50px;
margin:auto;
}
#empty a {
display:block;
height:50px;
}
* html #empty a {
display:inline-block;
}
HTML
<div id="empty"><a href="#n"></a></div>
How do I have links of different colors on the same page?
Recommending people to use classes in their 'a' tags like this :
CSS
a.red {
color:red;
}
a.blue {
color:blue;
}
HTML
<a href="#" class="red">A red link</a>
<a href="#" class="blue">A blue link</a>
This is a valid way to do it, but usually, this isn't what a page looks like - two links next to each other
with different colours - it's usually something like a menu with one kind of link and main body text or
another menu with different links. In this (normal) situation, To go higher up the cascade to style the
links. Something like this :
CSS
a{
color:red;
}
#menu a {
color:blue;
}
HTML
<ul id="menu">
<li><a href="#">A red link</a></li>
<li><a href="#">A red link</a></li>
</ul>
<div id="content">
<p>There's <a href="#">a blue link</a> here.</p>
</div>
What is shorthand property?
Shorthand property is a property made up of individual properties that have a common "addressee".
For example properties: font-weight, font-style, font-variant, font-size, font-family, refer to the font.
To reduce the size of style sheets and also save some keystrokes as well as bandwidth they can all be
specified as one shorthand property font, e.g.:
H1 {font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-size: 160%;
font-family: serif}
Note: To make things even simpler the line-height property can be specified together with the font-
size property:
HTML document split up in four parts all with different meaning, use the
-tag. Div is short for ?division? and isn?t header, navigation and so on ...
<div id="header">
<h1>The name of this page</h1>
</div>
<div id="navigation">
<h2>Navigation</h2>
<ul>
<li><a href="first.html">First</a></li>
<li><a href="second.html">Second</a></li>
<li><a href="third.html">Third</a></li>
</ul>
</div>
<div id="content">
<h2>Content</h2>
<p>Some sample content, add your own here</p>
</div>
<div id="footer">
<p>This page is written by [Your name] and builds
n a <a href="http://friendlybit.com">
Friendlybit template</a>.</p>
</div>
</body>
</html>
body {
background-color: Green;
}
div {
border: 3px solid Black;
padding: 7px;
width: 600px;
}
h1, h2, h3, h4, h5, h6 {
margin: 0;
}
#navigation {
float: left;
width: 150px;
}
#content {
float: left;
width: 430px;
}
#footer {
clear: both;
}
How do I get my footer to sit at the bottom...?
Need a div which makes space at the bottom of the main page (inside the #wrap div). Then, the
footer (being inside #wrap) can be placed in that space by using absolute positioning. Like this :
HTML
<div id="wrap">
...content goes here...
<div id="clearfooter"></div>
<div id="footer">Footer</div>
</div>
Can I attach more than one declaration to a selector?
Yes. If more than one declaration is attached to a selector they must appear in a semi colon separated
list, e.g.;
Selector {declaration1; declaration2}
P {background: white; color: black}
Border around a table?
Try the following:
.tblboda {
border-width: 1px;
border-style: solid;
border-color: #CCCCCC;
}
/*color, thickness and style can be altered*/
<style type="text/css">
(here you can place your styles)
</style>
<div class="tblboda">
<table yaddayadda>
<tr>
<td>Content text and more content</td>
</tr>
</table>
</div>
That should give you a grey thin border around this table.
If you want the border to 'shrink wrap' around the table, then you have to use the <span> tag instead
the
tag. But that is not quite proper CSS or HTML, because a is for inline elements. A table is not an inline
element, therefore the correct tag is a <div>. If you play around with it a bit then you have a good
chance to achieve what you want and still have correct HTML/CSS.
The other way would be that you apply the class .tblboda directly to the table (for IE and other
contemporary browsers), like <table ... class="tableboda"> and you define another class for each
stylesheet: .tblboda2
In the NN4.xx stylesheet, you use the same properties as above, and in the IE and other
contemporary browsers you carefully set all those properties to default, like {border-style: none;}
Then you wrap the table in the <div> with the class .tblboda2 (NN4.xx does that) (IE a.o.c.b. don't do
anything, because the border-style is set to "none" = no border at all).
This way you have a table that is wrapped in a nice little border: .tblboda2 for NN4.xx, .tblboda for IE
and other modern browsers.
How do you target a certain browser?
IE can be targetted by preceding your properties with '* html'. For example...
#nav {
position:fixed;
}
* html #nav { /* this will target IE */
position:absolute;
}
Another way to target IE is with conditional comments. Put this (below) in the head - just before the
closing tag - and put anything you want to be directed only at IE in another stylesheet.
<!--[if IE]>
<link href="ieonly.css" rel="stylesheet" type="text/css">
<![endif]-->
#wrap {
width:760px; /* for IE5x */
w\idth:780px; /* for all other major browsers */
}