You are on page 1of 8

SQL Server views: What they are and how to create them

This is the first of two parts on SQL Server views. This first tip introduces the concept of SQL
Server views and shows you how to create them. Part 2 examines how to index and update base
data on views.

One of the objects you can create in a SQL Server database is a view, a virtual table that
retrieves data from one or more tables (or other views), similar to how
a SELECT statementreturns a data set. SQL Server views abstract the underlying table schema
while presenting data in rows and columns like a regular table. As a result, users and
applications can query a view as they would a table, but the view defines what data they can
see and how that data is referenced.
You can think of SQL Server views as filters that simplify and control data access. They are
essentially named queries that provide a snapshot of the data returned by that query. Not only
do SQL Server views let you focus and customize how you present the data, but they also
provide an extra layer of security by abstracting the underlying data structure. You can grant
access to a view without granting access to the tables on which the view is based.
SQL Server views can also abstract schema changes to the underlying tables. For example, if an
application retrieves data through a view and the view's structure (returned columns) remains
unchanged, the view's query can be modified to accommodate changes to the underlying tables
without impacting view access. A view can also be used to providebackward compatibility to
emulate a table that has significantly changed or no longer exists.
In this article, I introduce you to SQL Server views and give examples that demonstrate how
they work. The examples are based on two tables I created in
the AdventureWorks2012 database on a local instance of SQL Server 2012. The following code
shows the T-SQL I used to create the tables:

As you can see, I used two SELECTINTO statements to define and populate
the CurrentEmployee and EmployeeInfo tables. If you want to try out the exercises, you need
only run the T-SQL and you'll be ready to go. If you're running a different version of
the AdventureWorks database, you might have to tweak the code and examples to make them
work on your system.
The CREATE VIEW syntax
To create a view in SQL Server, use the CREATE VIEW statement, which is shown in the
following syntax:

Not surprisingly, you begin with the CREATE VIEW clause, providing the name and, optionally,
the schema where you want to define the view. If you don't specify a schema name, the default
schema is used.
Next, you can specify one or more column names, enclosed in parentheses and separated with
commas. These are the columns that users see when querying the view. If you don't include
column names, the view uses the names returned by the SELECT statement. If you want to use
different names -- or you're creating computed columns -- you can include the column names
here, after the CREATE VIEWclause, or specify column aliases within your query's SELECT list.
After the column names, you can include a WITH clause, which takes one or more of the
following three arguments:
ENCRYPTION: Encrypts the CREATE VIEW statement text and prevents SQL Server
replication from publishing the view.
SCHEMABINDING: Binds the view to the tables referenced within the SELECT statement so
the tables can't be modified in any way that would impact the view.
VIEW_METADATA: Returns the view's metadata information instead of information about
the base tables. This applies when the view is queried through the DB-Library, ODBC or OLE
DB API and when browse-mode metadata is being requested for the query.
After the optional WITH clause, you specify the AS keyword, followed by the query that
accesses the underlying data. The query is a standard SELECT statement that retrieves data
from one or more tables or views. You can also retrieve partitioned data by using
the UNION operator to join SELECT statements. However, you cannot include
an ORDER BY clause, unless the SELECT list includes a TOP clause. In addition, you cannot use
the INTO keyword or the OPTION clause, and you cannot reference a temporary table or table
variable.
The last optional element of the CREATE VIEW definition is WITH CHECK OPTION, which forces
all data modification statements executed against the view to conform to the
view's SELECT statement. In other words, WITH CHECK OPTION prevents data from being
updated if it will impact the data returned by the view in a way that the view can no longer
return that data. To better understand this option, as well as the other options related to the
view definition, see the topic "CREATE VIEW (Transact-SQL)" in SQL Server Books Online.
Creating a view in SQL Server
Once you have a basic understanding of the CREATE VIEW syntax, you're ready to build your
own view. The following example includes a CREATE VIEW statement that defines
the vEmployees view:

First, we use an IF statement to check for the existence of the view and then drop it if it does
exist. Then we run our CREATE VIEW statement. Not surprisingly, we start the statement with
the CREATEVIEW clause and then specify the column names to use for the returned data.
Again, you do not need to specify the column names here; you can instead use those returned
by the SELECT statement.
After the column names, the statement specifies the WITH SCHEMABINDING clause to ensure
the tables cannot be updated if they impact the view. Next comes the AS keyword and then the
actual query.
The SELECT statement joins the CurrentEmployee and EmployeeInfo tables and returns
the BusinessEntityID, FirstName and LastName columns from the CurrentEmployee table and
the JobTitle andHireDate columns from the EmployeeInfo table. Notice that the view definition
changes the column name BusinessEntityID to EmployeeID and
changes HireDate to DateHired.
Once you've created your view, you can call it within a query as you would a table. For example,
the following SELECT statement retrieves several columns of data from the vEmployees view:

Notice that we reference the column names based on how they're defined in the view. In this
case, we're using EmployeeID rather than BusinessEntityID. We've also concatenated
the FirstName andLastName columns and named the results FullName. We can even qualify
our queries as we would with a table, as shown in the following example:

This time around, we've added a WHERE clause specifying that the year must be greater than
2002. Again, we reference the column name (DateHired) in the view, rather than the table's
column name.
You can, of course, create queries that are far more complex than our two examples, but what
we've shown here should give you a good idea of how a view works.
See part two on indexing and adding data to views.
About the author:
Robert Sheldon is a technical consultant and the author of numerous books, articles and training
material related to Microsoft Windows, various relational database management systems, and
business intelligence design and implementation.
SQL Server views: Creating indexes and adding base data
This is the second of two parts on SQL Server views. This tip examines how to index and update
base data. The first introduced the concept of SQL Server views and showed how to create them.

You can create indexes on SQL Server views as long as you meet a number of conditions. For
example, you must ensure that your SET options are configured correctly on all tables that
participate in the view. In addition, the view's query must be deterministic; that is, the query
must return the same results when the input values are repeated. You cannot, for example, use
the getdate() function in the query because the value returned is always different. In addition,
you must always include the WITH SCHEMABINDING clause in your view definition.
These are only some of the considerations to take into account if you want to create an index
on a view. For more details about the requirements, refer to the TechNet article "Create
Indexed Views."
The first index you create on a view must be a unique clustered index. After that index has been
added, you can create nonclustered indexes. Keep in mind, however, that you might want to
avoid indexing a view if the underlying data is updated frequently because the index itself will
have to be constantly updated, which can impact the performance of other operations. But if
the source data is relatively stable, indexed views can significantly improve query performance.
For example, suppose we generated an execution plan when we ran the SELECT statement as in
the example in part 1. Figure 1 shows what that execution plan might look like.

Figure 1: A nonindexed view accesses the base tables when querying the view.
Not surprisingly, this is a fairly basic query. Neither source table is indexed so the database
engine performs table scans to retrieve the data. But even if the tables were indexed, the
database engine must query two tables and then join the data together. Now let's create an
index on the table. The following statement defines a unique clustered index on the
view's EmployeeID column:

As you can see, creating an index on a view is like creating an index on a table. If, after creating
the index, we rerun the same query, we'll see a very different execution plan, as shown in
Figure 2.

Figure 2: An indexed view does not access the base tables when the view is queried.
Even in this simple scenario, the execution is cleaner. Only the clustered index needs to be
accessed in order to return the data. Of course, measuring performance is a much more
complex issue than what's demonstrated here. Deciding to index a view depends on how you
query and modify data and the complexity of those queries, but in certain situations, an
indexed view can represent a significant boost in performance.
Using a view to update base data
In some cases, you can use a view to modify data in the tables referenced by the view.
However, as with indexed views, there are many rules governing your ability to update data.
For example, you can modify data in only one table at a time, regardless of how many tables
are referenced by the view. In addition, you can modify data through a view only if the
database engine can unambiguously track the column in the view definition to the underlying
base table. For example, you can't update data that has been grouped and aggregated. (For
more details about the rules that govern your ability to update data through a view, refer once
again to the topic CREATE VIEW (Transact-SQL) in SQL Server Books Online.)
Assuming you meet all the criteria for updating data through a view, the process itself is fairly
straightforward and is similar to modifying data directly in a table. For example, the
following UPDATEstatement updates an employee's job title:

As you can see, we reference the view in the UPDATE clause as we would a table. Then we use
the SET clause to provide the updated value and the WHERE clause to specify which row to
update. Notice that we can use the FirstName and LastName values from
the CurrentEmployee table to update the JobTitle column in the EmployeeInfo table. Because
the two tables are joined within the view, we do not have to join those tables when we update
the data.
We can also use the view to insert data. For example, the following INSERT INTO statement
uses the vEmployees view to add a new employee:

As you'll recall from the view definition, the view's EmployeeID column directly maps to
the BusinessEntityID column in the CurrentEmployee table, the same table that contains
the FirstName andLastName columns. We can perform this update because all three columns
are in the same table. Had we also tried to add a job title and hire date, our statement would
have failed.
Working with SQL Server views
Views provide a valuable tool for exposing SQL Server data to users and their applications. They
simplify the underlying data structure and provide an extra layer of security. They can be
indexed to improve performance and can even be used to modify data. Plus, view definitions
port easily from one version of SQL Server to the next. In fact, the basic CREATE VIEW syntax
has not changed since SQL Server 2000. Clearly, you have much to gain by implementing views
in your SQL Server database. They're simple to create and easy to use. If you can write
a SELECT statement, you can define a view.
See part one on defining and creating views.

You might also like