SQL-Server

Truncate & Delete

1.Truncate a table means data will be lost, but structure of the table will be present in the database.

Syntax: Truncate table <table name>;

2.If you drop a table then the structure of the table also goes along with the data.
Syntax: drop table <table name>;

3.You can’t delete a table; you can delete the data in a record wise manner.

SYNTAX: DELETE FROM <TABLE NAME> WHERE <CONDITION>


4.The difference between the truncate and delete is you can delete the data at a stretch buy using the truncate, by using the delete you can delete only one record at a time.

5.When you have truncated the table then all the records will lose. Then immediately if you add a record to that table the row number will be ‘1’ only.

Index:


1.            If you have a clustered index on a column, then also you can assign a primary key to that column?

2.            You are having rowid already then why you are going for the index?

3.            How many non-clustered indexes can be allowed in a table?

Syntax:
Create index <index name>

On

<Table name (<col1>, <col2>, -------)>;

Syntax:
Drop index <index name>

Rules

9.Rules will maintain the domain integrity.

10.Is it possible to create a rule at the time of creating a table?
No.

11.Is it possible to drop a rule?
Yes.

12.What is the difference between the rule and check constraint?
If a check constraint is applied to a table it will enforce the constraint to previously existing data also. If that data violates the constraint then constraint statement gives an error message.

If a rule is applied on a table it will not apply to the already existing data in the table. The rule will be imposed from now on the updation and insertion of data.

SYNTAX

Create rule <rule name> as <condition>
Sp_bindrule <rule name>, <object name>
Drop rule <rule name>

24.What are the types of replication?

Types of the replications:
·                     Snapshot Replication
Option: Snapshot, with immediate-updating Subscribers
·                     Transactional Replication
Option: Transactional, with immediate-updating Subscribers
·                     Merge Replication
Which type of replication you choose for your application depends on your requirements for data consistency, site autonomy, and network resources.
25.Differences between the SQL-server 2000 and SQL-Server 7.0.

26.What is the sql using by the SQL-Server and oracle?

SQL-Server: Transact-SQL
Oracle: ANSI-SQL

28.Is it possible to create a view with out a base table?

Actually the answer is NO.
But this is possible by using the “FORCED VIEWS”
Syntax:
Create force view XYZ
As
Select * from ZZZ;

29.Index is the only second object, which holds data in the database.

30. “MODIFY” is a keyword only it is not a clause.
31.What will happen if you add a not null constraint on to a column if that column is already having the null values and what is the status of those null values, which are already present?

An error is given stating that null values are found.

32.I am doing a transaction, I am having four activities in those four fourth activity got some problem, then will be the transaction committed or roll backed?

Automatically it will rollback, because a transaction is said to be committed when all the activities of that transaction is perfectly executed.

Joins

33.What is a join?

34.How many types of joins are there?

35.What is the difference between the outer join and left outer join?

36.How to make a copy of a table (if you have a table with some name X, is it possible to create a table with a name Y by using the table X?

Explanation:

SQL server

SELECT <COLUMNS> INTO <NEW TABLE> FROM <OLD TABLE>

Oracle
Create table <table name> as select * from <table name>

Write a query to display the details of employees whose salary is more than the ‘BLAKE’ salary.

Sql> select B. * from EMP A, EMP B
Where A.ename=’BLAKE’
1.            Sal < B.sal;
It is also called aliasing.
It is a self-joining concept.

SQL Interview Questions And Answers Module -1

  1. What is an Entity?

The basic data item stored in database is called entity. An entity can be any object, item, place, person, concept, or activity about which data is stored.

  1. What is an attribute?

An attribute is a property of an entity. It describes a part of an entity. Entity could have one or more attributes.

  1. What is ER diagram?

An Entity Relationship Diagram is diagrammatic representation of the logical structure of a database system.

  1. Describe the concept of keys.

Candidate key
An attribute that uniquely identifies a row is called candidate key. It is also called das surrogate key.
Primary key
A candidate key that you choose to identify rows uniquely is called a primary key.
Alternate key
If there are multiple candidate keys in a table, the candidate keys that are chosen as primary key are called the alternate keys.
Composite key
When the key that uniquely identifies the rows of a table is made up of more than one attribute, it is called as a composite key.

Foreign key
Two tables can be related using a common attribute. When a primary key of one table is also available as an attribute in another related table it is called a foreign key.
  1. What are joins?

Sometimes, data from multiple tables is to be displayed using select statement. For this purpose, the tables in use must have a column that is equated. This is termed as simple join or multiple join.

Sometimes, you might want to display all records from one table and some from another. This type of join is called an outer join. An outer join is only possible between two tables.

There are two types of outer join, namely left and right. In a left outer join, all the rows of the first table named in the FROM clause are displayed. In a right outer join all the rows from the second table mentioned in the FROM clause are displayed. In either case, all the matching rows from other table are displayed.

  1. What is a sub query?

Sometimes the results of one query are dependant on the results of another query. For this purpose one query is nested inside another query, this is called as sub query.

  1. What are the types of constraints?

You can enforce data integrity by using constraints. Constraints are divided in to five categories.

Primary key constraint

A primary key constraint is defined on a column are a set of columns whose values uniquely identify the rows in a table. It cannot contain null values.

Unique constraint

Unique constraints are used to enforce uniqueness on non-primary key columns. It allows null values but only one row can have a null value.
Multiple unique constraints can be created on a table.

Foreign Key constraint

You can use the foreign key constraint to remove the inconsistency in two tables when the data in the one table is dependant on the other table.
Check constraint

It enforces domain integrity by restricting the values to be inserted in a column. It is possible to define multiple check constraints on a single column. These are evaluated in the order in which they are defined.
Default Constraint

A default constraint can be use to assign a constant value to a column and the user need not insert values in to that column.

  1. What is a rule?

The required integrity can be enforced by specifying a check constraint or by defining a rule. But check constraint modifies the table structure. The constraint can there fore be implemented using rules with out changing the table structure. This rule is applied before an insert or update statement .
A rule must be bound to a column or a user-define d data type. This is done using stored procedure sp_bindrule. Rules do not apply to data that has already been inserted in the table. The existing values in tables do not have to meet the criteria specified by the rule.
  1. What are indexes?

To speed up data retrieval indexes are used. Indexes also enforce the uniqueness of rows.

Advantages

  1. Improves the speed of execution.

  2. Enforces uniqueness of data.

  3. Speeds up joins between tables.

Disadvantages

1.Takes disk space to store.

2.Data modification takes longer.

3.Takes time to create index.

Types of indexes

Clustered index

1.The data is physically sorted

2.One clustered index can be created per table, so you should build it on attributes that have a high percentage of unique values and that are not modified often.

Nonclustered index

1.The physical order of the rows is not the same as the index order.

2.There can be as many as 249 nonclustered indexes per column.

  1. What are views?

A view is a virtual table, which gives access to a subset of columns from one or more tables. It is a query stored as an object in the database. Hence a view is an object that derives it data from one or more tables.

Advantages

1.A view serves as a security mechanism.

2.A view simplifies the usage of complex queries.

SQL Interview Questions And Answers Module -2

  1. What are store procedures and its advantages?
A stored procedure is collection or batch of Transact-SQL statements and control flow language that is stored under one name, and executed as single unit. It helps in improving the performance of a query. It is a precompiled object. As it is ready to execute no time is needed for parsing and compiling the procedure.
Advantages
Improved performance – Applications do not have to compile the procedure over and over again.
Reduction in network congestion – applications need not submit multiple SQL statements to server for the purpose of processing.
Enhanced accuracy – SQL statements included in a procedure are designed by experienced programmers and are therefore more efficient, error free, and tested.
Better security mechanism – users can be granted permission to execute a stored procedure even if they do not own it.
Types of stored procedures
1.User-defined
2.System defined
These are prefixed with sp_. These are for administrative purpose and are stored in the database and are accessible to all users.
3.Temporary
These are prefixed with #, stored in tempdb and are automatically dropped when connection terminates.
4.Remote
These are created and stored in remote servers and can accessed by users with appropriate permissions.
5.Extended
These are dlls that are executed outside SQL Server. They are prefixed by xp_.
  1. Explain about BCP and DTS.

BCP

The transfer data from an external source to SQL Server is performed using Bulk Copy Program utility. The external source is a flat file. Data transfer from external source to SQL Server in BCP IN. The transfer of data from SQL Server to external source is BCP OUT.

DTS

Data transformation services can be used to import and export data between heterogeneous data sources and SQL Server. The external data sources include Visual FoxPro, MS Excel, Paradox, MS Access, Dbase, and text files.

  1. What are transactions and their properties?

A transaction is a sequence of operations performed together as a single unit of logical work. It has four properties.

Atomicity – it states that either all the data modifications are performed or none are performed.

Consistency - it states that all the data is in a consistent state after a successful completion of transaction.

Isolation – it states any data modification made my concurrent transactions must be isolated from the modifications made by other concurrent transaction.

Durability – it states that ay change made by a completed transaction remains permanently in the system.

  1. Locking mechanism.

SQL Server uses the concept of locking to ensure transactional integrity and database consistency. Locking, by functionally prevents users from accessing information being changed by other users. In a multi-user environment, Locking prevents users from changing the same data at the same time. In SQL Server locking is implemented automatically.

SQL Server implements multi-granular locking, which allows transactions to lock different types of resources at different levels. SQL Server can lock the following resources.

RID – is a row identifier that individually locks a row in a table.
Key – is a rowlock with in an index.
Page – is an 8k page or an index page.
Extent – is a contiguous group of 8k data pages or index pages.
Table – is the entire table, including all data and indexes.
Database – is the complete database.
Shared Locks

It is used for operations that do not change or update the data. This allows concurrent transactions to read a resource and no other transaction can modify the data on that resource.
Update Locks

This lock is implemented when a transaction modify a row. Only one update lock is allowed on a resource at a time.

Exclusive locks

Intent locks

Schema Locks
  1. What is deadlock?

A dead lock is a situation in which two users (or transactions) have locks on separate objects, and each user is waiting for a lock on the other’s object. It usually occurs in a multi-user environment.

  1. What are triggers?

A trigger is a block of code that constitutes with a set of T-SQL statements that are activated in response to certain actions. A trigger can also be interpreted as a special kind of stored procedure that is executed whenever an action, such as data modification, takes place.
A trigger is always defined on a table, and is said to have fired whenever the data in the underlying table is affected by any of the Data Manipulation Language (DML) statements-INSERT, UPDATE, or DELETE. A trigger fires in response to an event like insertion, updation, and deletion of data.
Triggers help in maintaining consistent, reliable, and correct data in tables. They enable the performance of complex actions and cascade these actions to other dependant tables.
Characteristics of a trigger:

    • It can be associated with tables.
    • It cannot be defined on temporary tables or views. However, it can reference temporary tables and views.
    • Whenever any data modification statement is issued then SQL Server fires it automatically.
    • It cannot be explicitly invoked or executed, as in the case of stored procedures.
    • Triggers can be nested up to 16 levels. The nesting of triggers occurs when a trigger performs an action that initiates another trigger.
    • It prevents incorrect, unauthorized, and inconsistent changes in data.
    • It cannot return data to the user.

There are three types of triggers
1) INSERT
2) DELETE
3) UPDATE
  1. What is Normalization? Explain three normal forms?

Normalization is a scientific method of breaking down complex table structures in to simple table structures by using certain rules. Hence reduce redundancy in a table and eliminate inconsistency problems and disk space usage.

First Normal Form

A table is said to be in 1NF when each cell of the table contains precisely one value.

Functional dependency

If you have two attribute A and B, A is said to be functionally dependant on B, if for each value of B, there is exactly one value of A.

Second Normal Form

Identify the functionally dependent keys and place them in a different table.

Third Normal Form

A relation is said to be 3NF when every non-key attribute is functionally dependant only on the primary key.

  1. What are Cursors and types of cursors?

A cursor is a work area called private SQL area, which executes SQL statements and stores the results.

CURSOR TYPES

So you can specify the four-cursor types for Transact-SQL cursors. These cursors vary in their ability to detect changes to the result set and in the resources, such as memory and space in tempdb, they consume. The four API server cursor types supported by SQL Server are:
  • Static cursors
  • Dynamic cursors
  • Forward-only cursors
  • Key set-driven cursors
Static cursors detect few or no changes but consume relatively few resources while scrolling, although they store the entire cursor in tempdb.
Dynamic cursors detect all changes but consume more resources while scrolling, although they make the lightest use of tempdb.
Key set-driven cursors lie in between, detecting most changes but at less expense than dynamic cursors.
Although the database API cursor models consider a forward-only cursor to be a distinct type of cursor, SQL Server does not. SQL Server considers both Forward only and scroll to be options that can be applied to static, key set-driven, and dynamic cursors.
  1. What is Encryption option in SQL Server?
Encryption is a method for keeping sensitive information confidential by changing data into an unreadable form. Encryption ensures that data remains secure by keeping the information hidden from everyone, even if the encrypted data is viewed directly. Decryption is the process of changing encrypted data back into its original form and so authorized users can view it.
  1. What are time-stamped data types?
It is a database-wide unique number. The storage size is 8 bytes. A table can have only one timestamp column. The value in the timestamp column is updated every time a row containing a timestampcolumn is inserted or updated. This property makes a timestamp column a poor candidate for keys, especially primary keys. Any update made to the row changes the timestamp value, thereby changing the key value. If the column is in a primary key, the old key value is no longer valid, and foreign keys referencing the old value are no longer valid. If the table is referenced in a dynamic cursor, all updates change the position of the rows in the cursor. If the column is in an index key, all updates to the data row also generate updates of the index.

MVC Interview Questions and Module -5

Explain Repository Pattern in ASP.NET MVC?
In simple terms, a repository basically works as a mediator between our business logic layer and our data access layer of the application. Sometimes, it would be troublesome to expose the data access mechanism directly to business logic layer, it may result in redundant code for accessing data for similar entities or it may result in a code that is hard to test or understand. To overcome these kinds of issues, and to write an Interface driven and test driven code to access data, we use Repository Pattern. The repository makes queries to the data source for the data, thereafter maps the data from the data source to a business entity/domain object, finally and persists the changes in the business entity to the data source. According to MSDN, a repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
·                     It centralizes the data logic or Web service access logic.
·                     It provides a substitution point for the unit tests.
·                     It provides a flexible architecture that can be adapted as the overall design of the application evolves.

In Repository, we write our whole business logic of CRUD operations with the help of Entity Framework classes, that will not only result in meaningful test driven code but will also reduce our controller code of accessing data.

How can you call a javascript function/method on the change of Dropdown List in MVC?
Create a java-script method:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Invoke the method:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>

Explain Routing in MVC?
A route is a URL pattern that is mapped to a handler. The handler can be a physical
file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.
Routing within the ASP.NET MVC framework serves two main purposes:

·                           It matches incoming requests that would not otherwise match a file on the file system and maps the requests to a controller action.
·                      
·                           It constructs outgoing URLs that correspond to controller actions.

How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method in global.asax is called. This method, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table for MVC application.

What are Layouts in ASP.NET MVC Razor?
Layouts in Razor help maintain a consistent look and feel across multiple views within our application.As compared to Web Forms Web Forms, layouts serve the same purpose as master pages, but offer both a simpler syntax and greater flexibility.
We can use a layout to define a common template for your site (or just part of it). This template contains one or more placeholders that the other views in your application provide content for. In some ways, it’s like an abstract base class for your views.
e.g. declared at the top of view as,
 @{
       Layout = "~/Views/Shared/SiteLayout.cshtml";
}

What is ViewStart?
For group of views that all use the same layout, this can get a bit redundant and harder to maintain.
The _ViewStart.cshtml page can be used to remove this redundancy. The code within this file
is executed before the code in any view placed in the same directory. This fi le is also recursively applied to any view within a subdirectory.
When we create a default ASP.NET MVC project, we find there is already a _ViewStart
.cshtml fi le in the Views directory. It specifi es a default layout:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Because this code runs before any view, a view can override the Layout property and choose a different one. If a set of views shares common settings, the _ViewStart.cshtml file is a useful place to consolidate these common view settings. If any view needs to override any of the common settings, the view can set those values to another value.

Note: Some of the content has been taken from various books/articles.

What are HTML Helpers?
HTML helpers are methods we can invoke on the Html property of a view. We also have
access to URL helpers (via the Url property), and AJAX helpers (via the Ajax property). All
these helpers have the same goal: to make views easy to author. The URL helper is also available from within the controller.
Most of the helpers, particularly the HTML helpers, output HTML markup. For example, the
BeginForm helper is a helper we can use to build a robust form tag for our search
form, but without using lines and lines of code:
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<input type="text" name="q" />
<input type="submit" value="Search" />
}

What is Html.ValidationSummary?
The ValidationSummary helper displays an unordered list of all validation errors in the ModelState dictionary. The Boolean parameter you are using (with a value of true) is telling the helper to exclude property-level errors. In other words, you are telling the summary to display only the errors in ModelState associated with the model itself, and exclude any errors associated with a specific model property. We will be displaying property-level errors separately.Assume you have the following code somewhere in the controller action rendering the edit view:
ModelState.AddModelError("", "This is all wrong!");
ModelState.AddModelError("Title", "What a terrible name!");
The first error is a model-level error, because you didn’t provide a key (or provided an empty key) to associate the error with a specifi c property. The second error you associated with the Title property, so in your view it will not display in the validation summary area (unless you remove the parameter to the helper method, or change the value to false). In this scenario, the helper renders the following HTML:

<div class="validation-summary-errors">
<ul>
<li>This is all wrong!</li>
</ul>
</div>

Other overloads of the ValidationSummary helper enable you to provide header text and set specific HTML attributes.
NOTE By convention, the ValidationSummary helper renders the CSS class validation-summary-errors along with any specifi c CSS classes you provide.The default MVC project template includes some styling to display these items in red, which you can change in styles.css.

What are Validation Annotations?
Data annotations are attributes you can find in System.ComponentModel.DataAnnotations
namespace.These attributes provide server-side validation, and the framework also supports client-side validation when you use one of the attributes on a model property. You can use four attributes in the DataAnnotations namespace to cover common validation scenarios,
Required, String Length, Regular Expression, Range.

What is Html.Partial?
The Partial helper renders a partial view into a string. Typically, a partial view contains reusable markup you want to render from inside multiple different views. Partial has four overloads:

public void Partial(string partialViewName);
public void Partial(string partialViewName, object model);
public void Partial(string partialViewName, ViewDataDictionary viewData);
public void Partial(string partialViewName, object model,
ViewDataDictionary viewData);

What is Html.RenderPartial?
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the response output stream instead of returning a string. For this reason, you must place RenderPartial inside a code block instead of a code expression. To illustrate, the following two lines of code render the same output to the output stream:
@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")

If they are same then which one to use?
In general, you should prefer Partial to RenderPartial because Partial is more convenient (you don’t have to wrap the call in a code block with curly braces). However, RenderPartial may result in better performance because it writes directly to the response stream, although it would require a lot of use (either high site traffic or repeated calls in a loop) before the difference would be noticeable.

How do you return a partial view from controller?
return PartialView(options); //options could be Model or View name

What are different ways of returning a View?
There are different ways for returning/rendering a view in MVC Razor.E.g. return View(), return RedirectToAction(), return Redirect() and return RedirectToRoute().