Saturday, March 22, 2014

Views

The SELECT clauses in a view definition cannot include the following:
·         An ORDER BY clause, unless there is also a TOP clause in the select list of the SELECT statement
·         The INTO keyword
·         The OPTION clause
·         A reference to a temporary table or a table variable.

Check option
Forces all data modification statements executed against the view to follow the criteria set within select_statement. When a row is modified through a view, the WITH CHECK OPTION makes sure the data remains visible through the view after the modification is committed. Any updates performed directly to a view's underlying tables are not verified against the view, even if CHECK OPTION is specified.

When schemabinding is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified. When you use SCHEMABINDING, the select_statement must include the two-part names (schema.object) of tables, views, or user-defined functions that are referenced. All referenced objects must be in the same database.

ENCRYPTION          Encrypts the entries in sys.syscomments that contain the text of the CREATE VIEW statement. Using WITH ENCRYPTION prevents the view from being published as part of SQL Server replication.

A view can be created only in the current database. The CREATE VIEW must be the first statement in a query batch. A view can have a maximum of 1,024 columns.

When querying through a view, the Database Engine checks to make sure that all the database objects referenced anywhere in the statement exist and that they are valid in the context of the statement, and that data modification statements do not violate any data integrity rules. A check that fails returns an error message. If a view depends on a table or view that was dropped, the Database Engine produces an error message when anyone tries to use the view. If the new table or view structure changes, the view must be dropped and re-created.

Updatable Views - Conditions

You can modify the data of an underlying base table through a view, as long as the following conditions are true:
·         Any modifications, including UPDATE, INSERT, and DELETE statements, must reference columns from only one base table.
·         The columns being modified in the view must directly reference the underlying data in the table columns. The columns cannot be derived in any other way as through the following:
§  An aggregate function: AVG, COUNT, SUM, MIN, MAX, GROUPING, STDEV, STDEVP, VAR, and VARP.
§  A computation. The column cannot be computed from an expression that uses other columns. Columns that are formed by using the set operators UNION, UNION ALL, CROSSJOIN, EXCEPT, and INTERSECT amount to a computation and are also not updatable.
§  The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses.
§  TOP is not used anywhere in the select_statement of the view together with the WITH CHECK OPTION clause.

Partitioned views



Partitioned views allow the data in a large table to be split into smaller member tables. The data is partitioned between the member tables based on ranges of data values in one of the columns. The data ranges for each member table are defined in a CHECK constraint specified on the partitioning column. A view that uses UNION ALL to combine selects of all the member tables into a single result set is then defined. When SELECT statements referencing the view specify a search condition on the partition column, the query optimizer uses the CHECK constraint definitions to determine which member table contains the rows.

To perform updates on a partitioned view, the partitioning column must be a part of the primary key of the base table. If a view is not updatable, you can create an INSTEAD OF trigger on the view that allows updates. You should design error handling into the trigger to make sure that no duplicate rows are inserted.

CHECK constraints are not needed for the partitioned view to return the correct results. However, if the CHECK constraints have not been defined, the query optimizer must search all the tables instead of only those that cover the search condition on the partitioning column. Without the CHECK constraints, the view operates like any other view with UNION ALL. The query optimizer cannot make any assumptions about the values stored in different tables and it cannot skip searching the tables that participate in the view definition.
If all the member tables referenced by a partitioned view are on the same server, the view is a local partitioned view. If the member tables are on multiple servers, the view is a distributed partitioned view. Distributed partitioned views can be used to spread the database processing load of a system across a group of servers. 
Partitioned views make it easier to maintain the member tables independently. For example, you can do the following at the end of a period:
  • The definition of the partitioned view for current results can be changed to add the newest period and drop the oldest period.
  • The definition of the partitioned view for past results can be changed to add the period just dropped from the current results view. The past results view can also be updated to remove and archive the oldest period it covers.
When you insert data into the partitioned views, the sp_executesql system stored procedure can be used to create INSERT statements with execution plans that have a significant chance of being reused in systems with many concurrent users.
Limitations
Tables referenced in updateable partitioned views cannot have identity column.
Tables cannot have computed columns if you want to have updateable partitioned view.
The partitioning column has to be defined using equality or inequality operators.

Monday, March 3, 2014

Sparse Column

With the introduction of the new Sparse Column feature in SQL Server 2008, it is now possible to declare a column as Sparse and any time a NULL value is entered in the column it will not use any space. One of the tricks here is to figure out when to determine when a column should be defined as Sparse or not.

So why not just declare all columns as Sparse Columns?
Sparse Columns require four extra bytes of storage for each non NULL fixed-length data type value in the table and zero bytes to store a NULL value; therefore it is very important to have the correct threshold per data type or you will end up using more space instead of gaining it. The fewer bytes a data type uses, the higher the percentage of NULL values are required to save space.

CREATE TABLE CustomerInfo
(CustomerID INT PRIMARY KEY,
Address_Line1 VARCHAR(100) NOT NULL,
Address_Line2 VARCHAR(100) NOT NULL,
Address_Line3 VARCHAR(100) NOT NULL,
Address_Line4 VARCHAR(100) NULL,
Address_Line5 VARCHAR(100) NULL,
Address_Line6 VARCHAR(100) SPARSE NULL,
Address_Line7 VARCHAR(100) SPARSE NULL,
Address_Line8 VARCHAR(100) SPARSE NULL,

)

Filtered Index



A Filtered Index, which is an optimized non-clustered index, allows us to define a filter predicate, a WHERE clause, while creating the index. The B-Tree containing rows from the filtered index will contain only those rows which satisfy the filter criteria used while creating the index. This optimized index offers several benefits over a full table non-clustered index as follows:

  •  The filtered index contains only those rows which satisfy the defined filter criteria. As a result it reduces the storage space requirement for the index. In the example below I will explain it more.
  • The filtered statistics or statistics for a filtered index are more compact and accurate, because they consider only the rows in the filtered index and the smaller size of the filtered index reduces the cost/overhead of updating the statistics.
  • The impact of data modification is less with a filtered index as it is updated only when the data of the index is impacted or a new record is inserted matching the filter criteria.
  • Maintenance costs will be reduced as well since only a subset of rows will be in consideration while re-organizing or rebuilding the index.
  • And most important, as it is an optimized non-clustered index, the query performance will improve if only a subset of data, which is covered by the filtered index criteria, is required.

Filtered Index
Indexed Views
A Filtered Index is created on
column(s) of a particular table.
Index Views can be created on
column(s) from multiple base tables.
A Filtered Index cannot use complex logic in its WHERE clause, for example the LIKE clause is not allowed, only simple comparison operators are allowed.
This limitation does not apply to indexed views and you can design your criteria as complex as you want.
A Filtered Index can be rebuilt online.
Indexed views cannot be rebuilt online.
You can create your Filtered Index as a non-unique index.
Indexed views can only be created as unique index.

Usage Scenario
  •  When you have mostly NULL values (this column can be defined as SPARSE column in SQL Server 2008 to save space required by NULL storage) and you normally pull rows with non-NULL values.
  • When you have several categories of data (multiple domain range) in a single column and often select rows for one or few categories. For example, let's consider the State column in the CustomerAddress table and often you query customers addresses by state. So you can create a filtered index on the State column for StateA, StateB, StateC values. If you execute a query to pull data where State = StateA, the filtered index where State = StateA will be used and so on.
WHAT YOU CAN DO IN A FILTERED INDEX…
  • Use equality or inequality operators, such as =, >=, <, and more in the WHERE clause.
  • Use IN to create an index for a range of values. (This can support a query that does an “OR” –read about “OR” and “IN” with filtered indexes here.)
  • Create multiple filtered indexes on one column. In my order status example, I could have an index WHERE Status = ‘Open’, and I could have another index WHERE Status = ‘Shipping’.
  • Create a filtered index for all NOT NULL values – or all NULL values.
WHAT YOU CAN’T DO IN A FILTERED INDEX…

  • Create filtered indexes in SQL Server 2005.
  • Use certain expressions, such as BETWEEN, NOT IN, or a CASE statement.
  • Use date functions such as DATEADD for a rolling date range – the value in WHERE clause must be exact.
  • The query optimizer won’t consider filtered indexes if you’re using local variables or parameterized SQL for the predicate that matches the filter.
CREATE NONCLUSTERED INDEX FI_Employee_DOJ
ON Employee(DOJ)
WHERE DOJ IS NOT NULL

Friday, February 21, 2014

Constraints

Constraints let you define the way the Database Engine automatically enforces the integrity of a database. Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity.

1.       NOT NULL specifies that the column does not accept NULL values.
2.       CHECK constraints enforce domain integrity by limiting the values that can be put in a column.
3.       UNIQUE constraints enforce the uniqueness of the values in a set of columns.
4.       PRIMARY KEY constraints identify the column or set of columns that have values that uniquely identify         a row in a table.
5.       FOREIGN KEY constraints identify and enforce the relationships between tables.

 The ON DELETE clause controls what actions are taken when you try to delete a row to which existing foreign keys point. The ON DELETE clause has the following options:
·         NO ACTION specifies that the deletion fails with an error.
·         CASCADE specifies that all the rows with foreign keys pointing to the deleted row are also deleted.
·         SET NULL specifies that all rows with foreign keys pointing to the deleted row are set to NULL.

·         SET DEFAULT specifies that all rows with foreign keys pointing to the deleted row are set to their default value.

Schema

A schema is a collection of database objects that are owned by a single principal and form a single namespace. Schemas own objects and principals own schemas. A schema can be owned by either a primary or secondary principal, with the term “principal” meaning any SQL Server entity that can access securable objects.

Users can now have a default schema assigned using the DEFAULT_SCHEMA option of CREATE USER and ALTER USER commands. If no default schema is supplied for a user then DBO will be used as the default schema.
            The primary purpose of SQL schema was -is- to facilitate security management: define who [which principals] can access what [which database objects]. This was made particularly easier starting with SQL 2005 when the schema stopped being directly tied to the owner. 

Another use of schema is to serve as a namespace that is preventing name clashes between objects from different schemas.

       The original use of this was to allow multiple [interactive, i.e. ad-hoc like] users of a given database to create their own tables or stored procedures (or other objects), without having to worry about the existence of similarly named objects possibly introduced by other users. The Namespace-like nature of schema can also be put to use in a planned database setting, i.e. one when a single architect designs the database structure in a way which provides distinct type of access, and indeed different behaviors, for distinct user groups.


Schemas provide the opportunity to simplify administration of security, backup and restore, and database management by allowing database objects, or entities, to be logically grouped together. This is especially advantageous in situations where those objects are often utilized as a unit by applications. For example, a hotel-management system may be broken down into the following logical entities or modules: Rooms, Bar/Restaurant, and Kitchen Supplies. These entities can be stored as three separate physical databases. Using schemas however, they can be combined as three logical entities in one physical database. This reduces the administrative complexity of managing three separate databases.

CREATE LOGIN [User1] WITH PASSWORD=N'User1'

CREATE USER [User1] FOR LOGIN [User1] WITH DEFAULT_SCHEMA=[Pract]

CREATE ROLE [Pract_Role] AUTHORIZATION [dbo]

CREATE SCHEMA [Pract_Sch] AUTHORIZATION [User1]

GRANT DELETE,SELECT,INSERT,UPDATE,ALTER ON SCHEMA::[Pract_Sch] TO [Pract_Role]

EXEC sp_addrolemember N'Pract_Role', N'User1'
GO

GRANT CREATE TABLE TO [Pract_Role]

1.       We have created a login called User1
2.       Created a user with same name
3.       Created a role
4.       Created a schema under User1
5.       Granted permissions on schema to the role
6.       Added the role to the user
7.       Granted create table to the role

Here, we can observer that we have to grant permissions on table/schema to the role.