Vous êtes sur la page 1sur 26

.

NET Framework
What is the difference between a .NET class, Struct & Enumerations? Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory. Structures are implicitly derived from a class called System.ValueType. The purpose of System.ValueType is to override the virtual methods defined by System.Object. So when the runtime encounters a type derived from System.ValueType, then stack allocation is achieved. When we allocate a structure type, we may also use the new keyword. We may even make a constructor of a structure, but, remember, A Noargument constructor for a structure is not possible. The structure's constructor should always have a parameter. So if we define the following structure struct MyStruct { public int y,z; } and we create a structure type MyStruct st = new MyStruct(); In case of a class, no-argument constructors are possible. Class is defined using the class keyword. A struct cannot have an instance field, whereas a class can. class A { int x = 5; //No error ... } struct { int x = 5; //Syntax Error } A class can inherit from one class (Multiple inheritance not possible). A Structure cannot inherit from a structure. Enum is the keyword used to define an enumeration. An enumeration is a distinct type consisting of a set of named constants called the enumerator list. Every enumeration has an underlying type. The default type is "int". Note: char cant be the underlying data type for enum. First value in enum has value 0, each consequent item is increased by 1. enum colors {red, green, blue, yellow}; Here, red is 0, green is 1, blue is 2 and so on. An explicit casting is required to convert an enum value to its underlying type int x = (int)colors.yellow;

When you choose class or struct? Example Choosing between struct and class Use of structure in following condition is desirable. When you have small data structure Data Structure does not require to extend the functionality. When you want to perform faster operation on data structure. (As structure are stored on stack, operation performed on it are faster.) Use of class in following condition is desirable. When you have complex data structure Data Structure requires to extend functionality. When you want to optimize memory usage. (As class is stored on heap, they are about to be garbage collected when no reference pointing to an object.) Class "A" implements Dispose() method. Instance of class "A" is created in Class "B". In this scenario when will the Dispose method in class "A" get called? If an object A allocates an object B, and object B allocates an object C, then A's Dispose implementation must call Dispose on B, which must in turn call Dispose on C. Objects must also call the Dispose method of their base class if the base class implements IDisposable. Difference between Clsoe() and Dispose()? Close()VsDisposeMethod The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing Do i need to have a static class to define a static method in it? If no, how can I use that method? No. Class Name.Method Name How can we restrict deriving a class? Sealed class Used to restrict the inheritance feature of object oriented programming. In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error.

Why Sealed Classes? We just saw how to create and use a sealed class. The main purpose of a sealed class to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace. The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color. So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries. How can you find out the version information of an assembly? Assembly.GetName().Version How does the Garbage Collector optimize it's operation? When objects are no longer being used by the application, the .NET runtime's garbage collector performs the task of collection, to determine the status of the objects. Necessary operations are performed to relieve the memory, in case the object is no longer in use. This is identified by the GC by examining the metadata of the object. For this, the GC has to know the location of the roots that represent the object. Roots are actually the location of the object on the managed heap. There are two types of memory references, strong & weak. When a root references an object, it is said to be a strong reference as the object is being pointed to by application code. The other type of object, that is not being referenced by the application code is called the weak reference, and this may be collected by the GC. However, this may still be accessed by the application code if required. But for the application to access the weakly referenced object, this has to be converted to a strong reference (and note that this has to be done before the GC collects the weakly referenced object). How many memory locations does the following piece of code create? Object o = new Object(); 2

If i've page load event, on pre render event and a button click event coded. On clicking of the button, which one will get called first Page_Load Reflection can be used to? Reflection is the ability of the .NET framework to gather information (metadata) about assemblies, modules and types at runtime. It allows you also to dynamically create instances of types, invoke methods and access fields, properties and attributes.

Uses: Reflection is primary used by various other components of .NET like .NET Remoting. Reflection can be used to in modular design paradigms ( extension based , add-on based applications) where the functionality of the application is extended by providing new modules for it. In .NET 4.0 this has been upgraded and it has the feature of DLR. What are satellite assemblies? Satellite resource assemblies are used to localize your application, be it a web app, winform, etc. .NET framework uses the hub and spoke model and follows a certain naming convention for the reource files. Depending on the type of application you are writing you will either compile resources into dlls (satellite assemblies) or deploy the resource files themselves. A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language Hub and spoke model requires that you place resources in specific locations so that they can be located and used easily. If you do not compile and name resources as expected, or if you do not place them in the correct locations, the common language runtime will not be able to locate them. As a result, the runtime uses the default resource set.

What does RCW stand for? RCW Means Runtime Callable Wrappers. The common language runtime(CLR) exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. CCW is the Com Callable Wrapper. This will build a bridge between the Com Component and the .Net Component RCW will build a bridge between .Net Component and Com Component. Converts the .Net data type to Com Data type

What is "weak reference"? Normally whenever you initialize an object in .NET, it creates strong reference which means as long as the object is being referenced, it will not be collected by garbage collection. But we can mark any object as Weak Reference in .NET which allows .NET garbage collection to collect even when the object is being used. This is useful when we are dealing with large object in memory and potentially don't care if we loose. For example, we load large dataset to populate the screen but after we have shown to the screen we may not need that large dataset sitting in the memory; in this scenario, we can mark dataset as weak reference so that it will be collected by garbage collection.

OOPS Questions:
1) What is difference between Interface & Abstract -

2) What is difference between Overloading & Overriding METHOD OVERLOADING class human( { void Hand(two paremeters){ Eating} void Hand(three parameters) { Writing } void Hand(Five parameters) { Fighting } METHOD OVERIDING class father {

void Hand(5 parameters){ Smoking; } } class child extends father{ void Hand(5 parameters){ Drinking} 3) What is difference between Overriding & Shadowing (New keyword) Pre-requisite A parent class object can hold a child class object. Overriding Overriding concept is strictly related with inheritance concept. Which means overriding can happen in child classes if the parent class has a override enabled (virtual) methods only.

internal class A { public virtual string Print() { return "This is class A"; } } internal class B:A { public override string Print() { return "This is class B"; } } and when we use a code as below, A classA = new A(); B classB = new B(); classA = classB; Console.WriteLine(classA.Print()); //This is class B In overriding concept the parent object can see the child object's overridden method and access it.

Shadowing In shadowing concept the child class will recreate a method with the same name as the override enabled method in parent class, and this new method is the available method for next level child classes instead of parent class's method. internal class A { public virtual string Print() { return "This is class A"; } } internal class B:A { public new string Print() { return "This is class B"; } } and when we use a code as below, A classA = new A(); B classB = new B(); classA = classB; Console.WriteLine(classA.Print()); //This is class A The parent class cannot see the newly created method in child class and because of the same name the class will call the method in the parent class. 4) Why Multiple inheritance not supported in .NET C# does not support multiple class inheritance because of the diamond problem that is associated, with multiple class inheritance. Let us understand the diamond problem of multiple class inheritance with an example.

As shown in the image above: 1. I have 2 classes - ClassB and ClassC 2. Both of these classes inherit from ClassA 3. Now, we have another class, ClassD which inherits from both ClassB and ClassC So, if a method in ClassD calls a method defined in ClassA and ClassD has not overriden the invoked method. But both ClassB and ClassC have overridden the same method differently. Now, the ambiguity is, from which class does, ClassD inherit the invoked method: ClassB, or ClassC? 5) What is Value Type & Reference Type Value types Value types inherit from the System.ValueType class, which in turn, inherits from System.Object. However, you can not inherit directly from the System.ValueType class. If you try to inherit explicitly from System.Value, you'll get the C3838 compiler error. Value types have several special properties:

Value types are stored on the stack. (We'll discover that shortly.) Value type objects have two representations: an unboxed form and a boxed form. Value types are accessed directly which means you don't need to use the new operator. Value types are managed types, they are initialised to 0 when they are created. Value type instances are not under the control of the Garbage Collector. Value types are implicitly sealed, which means that no class can derive from them. In C#, structs are always value types and allocated on the stack. //I and J are both of type int I = 20; J = I; int is a value type, which means that the above statements will results in two locations in memory.

Reference types inherit directly from System.Object, they offer many advantages over Value types:

Reference types are stored on the managed heap, thus they are under the control of Garbage Collector. Two or more reference type variables can refer to a single object in the heap, allowing operations on one variable to affect the object referenced by the other variable.

The variable representing the instance contains a pointer to the instance of the class, it is dereferenced first if you want to access any of its members. In C#, Classes are always reference types and created on the managed heap. Vector X, Y; //Object is defined. (No memory is allocated.) X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.) X.value = 30; //Initialising value field in a vector class. Y = X; //Both X and Y points to same memory location. //No memory is created for Y. Console.writeline(Y.value); //displays 30, as both points to same memory Y.value = 50; Console.writeline(X.value); //displays 50. Boxing is a mechanism for converting value types to reference types. Boxing wraps a value type in a box so that it can be used where an object reference is needed.

Unboxing is a mechanism for converting reference types to value types

Framework: 1) What are generics? Generics are the new feature in the c# 2.0. They introduce the concept of Type parameter. When you use generics, you are creating classes or methods that use a generic type, rather than a specific type. For example, rather than creating a type-specific, you could create a reusable List class using generics. Generics aim to promote: o Binary code reuse, o Performance, o Ease of reading, o Type safety. public class GenericClass<T> { void Add(T input) { }

} We create an instance of the generic class like this GenericClass<string> list2 = new GenericClass<string>(); For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting). 2) What is Delegate & Type of Delegates A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. Event is a way to signal something occurred. In ASP.NET this is tied to signal for example when user clicks a button, or makes a selection in DropDownList. Delegate is a function pointer, which is used as "glue" to tie a method to a this event so that method will be called when the event occurs. Basically, when Button is clicked, a corresponding method will be called in response to that, for example a Button_Click method on your page. Delegate Types:

Action<> - this delegate cannot return any value. Func<> - has the capability to return value.Returned value can be of any type,irrespective of the type of input sourc Predicate<> - It doesnt have multiple overloads like the others and it can only return true/false corresponding to each item in the collection.Predicate is used by the following extension methods :Exists, Find, FindAll, FindIndex, FindIndex, FindLast, FindLastIndex, RemoveAll, TrueForAll.

3) What is garbage collection generation Generation 0 - When an object is initialized, its in generation 0. These are new objects that have never been played around with by the GC. As and when more objects get created, the process of Garbage Collection is invoked by the CLR. Generation 1 - The objects that survive the garbage collection process are considered to be in generation 1. These are the old objects. Generation 2 - As more new objects get created and added to the memory, the new objects are added to generation 0, the generation 1 old objects become older, and so are considered to be in generation 2. Generation 2 is the highest level generation in the garbage collection process. Any further garbage collection process occuring causes the level 1 objects promoted to level 2, and the level 2 objects stay in level 2 itself, as this generation level is the highest level. 4) What is Dispose() method To implement Dispose method we need to inherit the interface IDisposable. Use the method to close or release unmanaged resource such as files , streams , and handlers held by an instance of the class that implement this interface.

ASP.NET
1) Page life cycle

- Pre-Init: Dynamic controls , IsPagePostBack - Init: Assign control property


- Preload: ViewState will be loaded - Load: Connection to database, opening file etc (Sequence: Parent Control first and then child control) - Pre-render: Change:Change HTML dynamically ( an Event) - Render: A method - Unload: Child Control unloaded first and then Parent . 2) Difference between Session & Application variables Application variables are the variables which remain common for the whole application for all the users Their value can be used across the whole application by any user And they die only when the application stops or probably when they are killed forcibly The ideal example for these kind of variables are site counter We can find out how many people accessed a particular site since the time it went live via application variables and incrementing the same on ever session start. Session variables are variables which remain common for the whole application but for one particular user. They also can be used across the whole application but each user will have a copy But they die when a particular user session ends or probably when they are killed forcibly The ideal example for this kind of variable are user id You might want to show "Welcome Smile " on every page of your site till Prabha logs off So in session start you set a variable to "Welcome Anu" and kill it on end of session

3) When to use session & Caching If the objects are shareable between user sessions, then use the cache. If the objects are unique to each session -- perhaps because they are governed by permissions -- then store it in the session. Session objects are suitable for user-only-data, on the other hand, Cache objects are more suitable for data shared for the application. Session => A webpage with a step by step interface (an online test for example). Cache => The info displayed in some kind of weather widget (like the one that google has in its igoogle.com page).

4) In which scenario Session_End event occurs Session_End event is supported only in InProc mode.

Reason - Generally Global.aspx related all events are supported IIS activities (directly or indirectly), hence if you use inProc then it will stored ASPnet process (IIS related aspnet process) and if session expired then the relavant event triggered.
But if session store in state server or sql server then that is not related to any of ISS process or memory then that can not picked up by global.asax related events. http://forums.asp.net/t/1665666.aspx

5) How to maintain application hit count without using database table

Without using database table - http://www.codeproject.com/KB/customcontrols/fastcustomhitcounter.aspx Using Database table - http://imar.spaanjaars.com/238/howto-create-a-hit-counter-using-a-database-inaspnet-1x-with-c-sharp

6) What is HTTP module, HTTP Handlers

HttpHandler help us to inject pre-processing logic based on the extension of the file name requested. So when a page is requested, HttpHandler executes on the base of extension file names and on the base of verbs. HttpModule is an event based methodology to inject pre-processing logic before any resource is requested. When any client sends a request for a resource, the request pipeline emits a lot of events: o BeginRequest: Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event. o AuthenticateRequest: If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user in a way that you want to. o AuthorizeRequest: This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so. o PreRequestHandlerExecute: This event occurs before the HTTP handler is executed. o PostRequestHandlerExecute: This event occurs after the HTTP handler is executed. o EndRequest: Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page. http://www.codeproject.com/KB/aspnet/HttpModuleandHttpHandle.aspx

7) When to use cookies, View state:

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips. The ControlState property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState property. ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page. A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent. A query string is information that is appended to the end of a page URL. http://www.contoso.com/listwidgets.aspx?category=basic&price=100 http://www.codeproject.com/KB/aspnet/Beginners_Cookies.aspx http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

SQL

Difference between Unique Key, Foreign Key & Primary key PRIMARY KEY: A table can contain only one PRIMARY KEY. It doesnt allow null values; it is used as Foreign Key in another Table (like Reference Key). UNIQUE KEY: A Table may contain one or more UNIQUE constraints. Its allowing only one null value. Use this key we maintain unique vales in the table. FOREIGN KEY: A key used in one table to represent the value of a primary key in a related table. While primary keys must contain unique values, foreign keys may have duplicates. For instance, if we use student ID as the primary key in a Students table (each student has a unique ID), we could use student ID as a foreign key in a Courses table: as each student may do more than one course, the student ID field in the Courses table (often shortened to Courses. student ID) Will hold duplicate values.

Difference between Stored Procedure & Functions Function - A function performs an operation and returns a value. A function consists of the function name, followed by a set of parenthesis that contains any parameter or arguments required by the function. If a function requires two or more arguments you can separate them with commas. Stored Procedure - If a repetitive T-SQL task has to be executed within an application, then the best repository for it is a program called a stored procedure, stored in SQL Server. Storing the code inside the SQL Server object gives us many advantages, like: o Security due to encryption o Performance gains due to compilation o Being able to hold the code in a central repository: o Altering the code in SQL Server without replicating in several different programs o Being able to keep statistics on the code to keep it optimized o Reduction in the amount of data passed over a network by keeping the code on the server o Hiding the raw data by allowing only stored procedures to gain access to the data

Code reusability

Although both functions and sp's are prcomiled sql statements there exists some differences between them. 1. Functions must return a value(scalar,inline table or multi statement table) whereas stored proc may or may not retun a value. 2.Functions can return a table whereas stored procs can create a table but can't return table. 3. Stored procs can be called independently using exec keyword whereas function are called using select statements. 4. Stored procs can be used to change server configuration(in terms of security-i.e. setting granular permissions of user rights) whereas function can't be used for this 5. XML and output parameters can't be passed to functions whereas it can be with sp's. 6.transaction related statement can be handled in sp whereas it can't be in function. 7. stored procedures can call a funtion or another sstored proc similarly a function can call another function and a stored proc.The catch with function is that no user defined stored proc can be called.Only extended/system defined procs can be called. What is a Trigger A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You cant explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to.
Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them. Basically, triggers are classified into two main types:(i) After Triggers (For Triggers) (ii) Instead Of Triggers

Why SELECT * throws an error but SELECT COUNT(*) does not.


Count (*) is about counting rows, not a particular column. It doesnt even look to see what columns are available, itll just count the rows, which in the case of a missing FROM clause, is 1. Select * is designed to return columns, and therefore barfs if there are none available.

What Command do we Use to Rename a db, a Table and a Column?


To Rename db sp_renamedb oldname , newname If someone is using db it will not accept sp_renmaedb. In that case, first bring db to single user mode using sp_dboptions. Use sp_renamedb to rename the database. Use sp_dboptions to bring the database to multiuser mode. e.g.

USE MASTER; GO EXEC sp_dboption AdventureWorks, 'Single User', True GO EXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New' GO EXEC sp_dboption AdventureWorks, 'Single User', False GO To Rename Table We can change the table name using sp_rename as follows: sp_rename 'oldTableName' 'newTableName' e.g. sp_RENAME 'Table_First', 'Table_Last' GO To rename Column The script for renaming any column is as follows: sp_rename 'TableName.[OldcolumnName]', 'NewColumnName', 'Column' e.g. sp_RENAME 'Table_First.Name', 'NameChange' , 'COLUMN' GO

What is Difference between Commit and Rollback when Used in Transactions?


The usual structure of the TRANSACTION is as follows: BEGIN TRANSACTION Operations COMMIT TRANSACTION or ROLLBACK TRANSACTION When Commit is executed, every statement between BEGIN and COMMIT becomes persistent to database. When Rollback is executed, every statement between BEGIN and ROLLBACK are reverted to the state when BEGIN was executed.

Joins in SQL

Inner join or Equi join o Self Join Outer Join o Left Outer Join o Right Outer Join o Full Outer Join Cross join Inner join or Equi join: used to select only those rows that have common values in the column on which join is based.

Self-Join - join a table to itself

Outer Join : o Left Outer Join: is used to select the rows from the left hand side table regardless of whether the table on the right hand side has common values or not.

Right Outer join: used to select rows from the table on the right hand side regardless of whether the table on the left hand side has common values or not.

Full Outer Join:

The Cross joins: used to get rows from all the possible combinations of rows and columns from both the table.

Indexes?

There is currently no index on the Product table to help this query, so the database engine performs a scan and examines each record to see if UnitPrice falls between 12.5 and 14. In the diagram below, the database search touches a total of 77 records to find just three matches.

Now imagine if we created an index, just like a book index, on the data in the UnitPrice column. Each index entry would contain a copy of the UnitPrice value for a row, and a reference (just like a page number) to the row where the value originated. SQL will sort these index entries into ascending order. The index will allow the database to quickly narrow in on the three rows to satisfy the query, and avoid scanning every row in the table. How It Works The database takes the columns specified in a CREATE INDEX command and sorts the values into a special data structure known as a B-tree. A B-tree structure supports fast searches with a minimum amount of disk reads, allowing the database engine to quickly find the starting and stopping points for the query we are using. Conceptually, we may think of an index as shown in the diagram below. On the left, each index entry contains the index key (UnitPrice). Each entry also includes a reference (which points) to the table rows which share that particular value and from which we can retrieve the required information.

Much like the index in the back of a book helps us to find keywords quickly, so the database is able to quickly narrow the number of records it must examine to a minimum by using the sorted list of UnitPrice values stored in the index. We have avoided a table scan to fetch the query results.
Create Index query - CREATE INDEX [IDX_UnitPrice] ON Products (UnitPrice) Clustered index is comprised of the actual rows sorted in order of the cluster key.
CREATE CLUSTERED INDEX IDX_SupplierID ON Products(SupplierID)

A non-clustered index is comprised of the key columns plus a pointer to the actual rows. Inserting a new row into the table will not require all the rows after the inserted row to be moved on the disk, instead the row will have to be inserted into the correct data page, and this might require a page split if there is not enough room on the page for the new row. A printed phone directory is a great example of a clustered index: o The cluster key in the phone directory is a combination of last name and first name. o Using the last name plus first name to find the number is called a clustered index seek. o If u wanted to locate everyone with the first name of "Jeff" in the book, you would have to look at every entry in the entire book because the first name is the second column in our cluster key. This is called a clustered index scan. A non-clustered index has the indexed columns and a pointer or bookmark pointing to the actual row, used to retrieve part of the required information from the rows in the table. When all of the required columns are part of the index, it is called a "covering index". An index key can contain up to 16 columns and can be up to 900 bytes wide. Indexes that surpass these limits called "included columns". Indexes take up disk space and require resources to keep updated. If a table has four non-clustered indexes, every write to that table requires four additional writes to keep the indexes up to date.

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

Indexes and Data Modification Another downside to using an index is the performance implication on data modification statements. Any time a query modifies the data in a table (INSERT, UPDATE, or DELETE), the database needs to update all of the indexes where data has changed. As we discussed earlier, indexing can help the database during data modification statements by allowing the database to quickly locate the records to modify, however, we now caveat the discussion with the understanding that providing too many indexes to update can actually hurt the performance of data modifications. This leads to a delicate balancing act when tuning the database for performance. A Disadvantage to Clustered Indexes If we update a record and change the value of an indexed column in a clustered index, the database might need to move the entire row into a new position to keep the rows in sorted order. This behavior essentially turns an update query into a DELETE followed by an INSERT, with an obvious decrease in performance. A table's clustered index can often be found on the primary key or a foreign key column, because key values generally do not change once a record is inserted into the database.
SQL Constraints

Constraints are used to limit the type of data that can go into a table. Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).

NOT NULL - The NOT NULL constraint enforces a column to NOT accept NULL values.

The NOT NULL constraint enforces a field to always contain a value. This means that you cannot insert a new record, or update a record without adding a value to this field. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

UNIQUE - The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. CREATE TABLE Persons (

P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), UNIQUE (P_Id) )

PRIMARY KEY - The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values. A primary key column cannot contain NULL values. Each table should have a primary key, and each table can have only ONE primary key.

FOREIGN KEY - A FOREIGN KEY in one table points to a PRIMARY KEY in another table. CHECK - The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) )

DEFAULT - The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' )

Normalization?

It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization. Benefits of Normalizing your database include:
o o o o

Avoiding repetitive entries Reducing required storage space Preventing the need to restructure existing tables to accommodate new data Increased speed and flexibility of queries, sorts, and summaries

The three normal forms as follows: First Normal Form For a table to be in first normal form, data must be broken up into the smallest units possible. In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields.

Figure 1.8: Repeating groups example In the above example, city1 and city2 are repeating. In order for these tables to be in First normal form, you have to modify the table structure as follows. Also note that the Customer Name is now broken down to first name and last name (First normal form data should be broken down to the smallest unit).

Figure 1.9: Customer table normalized to first normal form Second Normal Form

The second normal form states that each field in a multiple field primary key table must be directly related to the entire primary key. In other words, each non-key field should be a fact about all the fields in the primary key. In the above table of customer, city is not linked to any primary field.

Figure 1.10: Normalized customer table.

Figure 1.11: City is now shifted to a different master table. That takes our database to a second normal form. Third Normal Form A non-key field should not depend on another Non-key field. The field Total is dependent on Unit price and qty.

Figure 1.12: Fill third normal form So now the Total field is removed and is the multiplication of Unit price * Qty. In fourth normal form, it should not contain two or more independent multi-valued facts about an entity and it should satisfy Third Normal form.

So let us try to see what multi-valued facts are. If there are two or more many-to-many relationship in one entity and they tend to come to one place, it is termed as multi-valued facts.

Figure 1.13: Multi-valued facts In the above table, you can see that there are two many-to-many relationships between Supplier / Product and Supplier / Location (or in short multi-valued facts). In order for the above example to satisfy the fourth normal form, both the many-to-many relationships should go in different tables.

Figure 1.14: Normalized to Fourth Normal form. Fifth normal form deals with reconstructing information from smaller pieces of information. These smaller pieces of information can be maintained with less redundancy. Example: Dealers sell Product which can be manufactured by various Companies. Dealers in order to sell the Product should be registered with the Company. So these three entities have a mutual relationship within them.

Figure 1.15: Not in Fifth Normal Form. The above table shows some sample data. If you observe closely, a single record is created using lot of small information. For instance: JM Associate can sell sweets under the following two conditions: JM Associate should be an authorized dealer of Cadbury Sweets should be manufactured by Cadbury company

These two smaller bits of information form one record of the above given table. So in order for the above information to be Fifth Normal Form all the smaller information should be in three different places. Below is the complete fifth normal form of the database.

Figure 1.16: Complete Fifth Normal Form Denormalization is the process of putting one fact in numerous places (it is vice-versa of normalization). Only one valid reason exists for denormalizing a relational design - to enhance performance. The sacrifice to performance is that you increase redundancy in a database. Difference between 4th and 5th NF: There is a huge similarity between Fourth and Fifth normal form, i.e. they address the problem of Multi-Valued facts Fifth normal form multi-valued facts are interlinked and Fourth normal form values are independent. For instance in the above two questions Supplier/Product and Supplier/Location are not linked. While in fifth form, the Dealer/Product/Companies are completely linked. Sixth normal form - If you want a relational system in conjunction with time, you use sixth normal form. At this moment SQL Server does not support it directly.
http://www.codeproject.com/KB/database/SQLInterviewQuestions.aspx

Vous aimerez peut-être aussi