SlideShare uma empresa Scribd logo
1 de 3
Baixar para ler offline
SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject

  9,219,840 members and growing!


                                    Email                             Password                  Sign in   Join                              Lost password?




   Home      Articles     Quick Answers        Discussions       Zones      Features     Community               Help!


      » Database » Database » SQL Server
                                                                                                                             Part of The SQL Zone sponsored by

  SQL Server Indexed Views -                                                     Licence
                                                                                 First Posted
                                                                                                CPOL
                                                                                                19 May 2011
  Speed Up Your Select Queries:                                                  Views
                                                                                 Bookmarked
                                                                                                11,349
                                                                                                8 times
                                                                                                                             See Also

  Part 1                                                                                                                        More like this
                                                                                                                                More by this author
  By andrewwasfy | 19 May 2011 | Article
   SQL SQL-Server DBA Dev Beginner

  An introduction to SQL Server Indexed Views.

   Article   Browse Code       Stats    Revisions     Alternatives                                 4.46 (6 votes)        4



   History about views
   Views are a virtual table defining a query against one or more tables. Data isn’t stored in the
   database and the result set is determined while the view is executed.

   What’s an Indexed View?
   An indexed view has a unique clustered index. The clustered index is stored in SQL Server
   and updated like any other clustered index, providing SQL Server with another place to look
   to potentially optimize a query utilizing the indexed view. Queries that don’t specifically use
   the indexed view can even benefit from the existence of the clustered index from the view. In
   the developer and enterprise editions of SQL Server, the optimizer can use the indexes of
   views to optimize queries that do not specify the indexed view. In the other editions of SQL
   Server, however, the query must include the indexed view and specify the hint NOEXPAND to
   get the benefit of the index on the view. If your queries could benefit from having more than
   one index on the view, non-clustered indexes can also be created on the view. This would
   supply the optimizer with more possibilities to speed up the queries referencing the columns
   included in the view.

   Where to use them?
   Indexed views have both a benefit and a cost. The cost of an indexed view is on the
   maintenance of the clustered index (and any non-clustered indexes you may choose to add).
   One must weigh the cost to maintain the index against the benefit of query optimization
   provided by the index. When the underlying tables are subject to significant inserts, updates,
   and deletes, be very careful in selecting the indexes (both table and view) that will provide
   the greatest coverage across your queries for the lowest cost. Typically, environments that
   are best suited for indexed views are data warehouses, data marts, OLAP databases, and the
   like. Transactional environments are less suitable for indexed views. Look for repeating joins
   utilizing the same columns, joins on large tables, aggregations on large tables, and repeating
   queries as potential candidates for indexed views. Be careful of creating indexed views where
   the result set contains more rows than the base tables as this will be counterproductive.

   How to create them?
   A view that is to be indexed has to be created with schema binding. This means that once the
   indexed view is created, the underlying tables cannot be altered in any way that would
   materially affect the indexed view unless the view is first altered or dropped. It also means
   that all the tables referenced in the view must be referenced by their two-part name



http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]
SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject

   (schemaname.tablename). Below is an example of the CREATE statement for an indexed
   view, MyView , and its underlying table, MyBigTable. The table is first created, then the view
   that references two of the table’s three columns, and finally the unique clustered index on the
   view making it an indexed view.

    CREATE TABLE OAGTable(
    ID            INT PRIMARY KEY,
    Depart     VARCHAR(3),
    arrival      VARCHAR(3),
    DurationinMin int   )
    GO
    CREATE VIEW MyView WITH SCHEMABINDING AS
    SELECT ID, Duration
    FROM dbo. OAGTable
    WHERE DurationinMin > 300
    GO
    CREATE UNIQUE CLUSTERED INDEX idx_MyView ON MyView(DurationinMin)

   Once this index is created, the result set of this view is stored in the database just like any
   other clustered index. Any query that explicitly uses the view will be able to take advantage
   of the index on the view. Queries that contain a predicate similar to the view and that fall
   into the range defined by the view may also reap the optimization rewards of having that
   index available (assuming the execution cost is non-trivial). Consider the following query:

    SELECT ID
    FROM OAGTable
    WHERE DurationinMin > 400

   Even though the query does not use the indexed view, the optimizer has the option of using
   the clustered index created on the view if it provides better performance than the clustered or
   non-clustered indexes on the base table. If you want the optimizer to always choose the
   indexed view over the base tables when optimizing a query containing an index view, you
   must use the hint NOEXPAND . Conversely, if you’d like to see how a query containing an
   indexed view would perform utilizing the base tables instead, you can specify the option
   EXPAND VIEWS , thus saving you the time substituting the base tables yourself.

   Constraints
   An index cannot be created on just any view. Several constraints exist that a view must meet
   in order for the index creation to be successful. We discussed WITH SCHEMABINDING and
   two-part table names above. Here are some other constraints:

          The view must have been created with certain SET options, such as
          QUOTED_IDENTIFIER and CONCAT_NULL_YIELDS_NULL set to ON .
          The session creating the index must also have the correct SET options.
          Any user-defined function referenced by the view must have been created using WITH
          SCHEMABINDING .
          The view must be deterministic (consistently providing the same result given the same
          input).
          The base tables must have been created with the proper ANSI_NULLS setting.
          The result set of the view is physically stored in the database, thus storage space for
          the clustered index is also a constraint to consider.

   In addition to this, there are constraints on the contents of the view. For instance, the view
   may not contain EXISTS or NOT EXISTS , OUTER JOIN , COUNT(*) , MIN , MAX , subqueries,
   table hints, TOP , UNION , and much more. Check the SQL Server Development Center on
   MSDN for a complete listing.

   References
          http://technet.microsoft.com/en-us/library/cc917715.aspx

   License
   This article, along with any associated source code and files, is licensed under The Code
   Project Open License (CPOL)

   About the Author

    andrewwasfy

    Software Developer



http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]
SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject

    (Senior)
    Majisa
       Egypt

    Member




   Article Top                                               Sign Up to vote    Poor             Excellent    Vote




   Comments and Discussions

   You must Sign In to use this message board.


                                                    Search this forum                                            Go


            Profile popups   Noise   Medium
                                      Medium      Layout    Normal
                                                            Normal                     Per page 25
                                                                                                 25          Update




                                                           Refresh                                    First Prev Next

       My vote of 4                                                  Abed-elfattah Yacoub         0:57 6 Aug '11


       My vote of 2                                                  kornakar                  21:39 19 May '11




http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]

Mais conteúdo relacionado

Mais procurados

Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAConcentrated Technology
 
Moss 2007 Backup Strategies
Moss 2007 Backup StrategiesMoss 2007 Backup Strategies
Moss 2007 Backup StrategiesLiquidHub
 
Introducing Microsoft SQL Server 2012
Introducing Microsoft SQL Server 2012Introducing Microsoft SQL Server 2012
Introducing Microsoft SQL Server 2012Intergen
 
Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1guestd54e35
 
Pre Install Databases
Pre Install DatabasesPre Install Databases
Pre Install DatabasesLiquidHub
 
Advanced SharePoint Server Concepts
Advanced SharePoint Server ConceptsAdvanced SharePoint Server Concepts
Advanced SharePoint Server ConceptsLearning SharePoint
 
Simple Farm Server Deployment
Simple Farm Server DeploymentSimple Farm Server Deployment
Simple Farm Server DeploymentLiquidHub
 
Tech Ed Africa Demystifying Backup Restore In Share Point 2007
Tech Ed Africa Demystifying Backup Restore In Share Point 2007Tech Ed Africa Demystifying Backup Restore In Share Point 2007
Tech Ed Africa Demystifying Backup Restore In Share Point 2007Joel Oleson
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01Niit Care
 
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...SPTechCon
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualDan D'Urso
 
TEC2010 SharePoint 2010 Upgrade
TEC2010 SharePoint 2010 UpgradeTEC2010 SharePoint 2010 Upgrade
TEC2010 SharePoint 2010 UpgradeJoel Oleson
 
Pivotal CRM for iPad
Pivotal CRM for iPadPivotal CRM for iPad
Pivotal CRM for iPadAptean
 
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003LiquidHub
 
Share point 2013 installation step by step
Share point 2013 installation step by stepShare point 2013 installation step by step
Share point 2013 installation step by stepprasslides
 
ATG - Installing WebLogic Server
ATG - Installing WebLogic ServerATG - Installing WebLogic Server
ATG - Installing WebLogic ServerKeyur Shah
 
Weblogic 12c Graphical Mode installation steps in Windows
Weblogic 12c Graphical Mode installation steps in Windows Weblogic 12c Graphical Mode installation steps in Windows
Weblogic 12c Graphical Mode installation steps in Windows webservicesm
 

Mais procurados (20)

Managing SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBAManaging SQLserver for the reluctant DBA
Managing SQLserver for the reluctant DBA
 
Moss 2007 Backup Strategies
Moss 2007 Backup StrategiesMoss 2007 Backup Strategies
Moss 2007 Backup Strategies
 
Introducing Microsoft SQL Server 2012
Introducing Microsoft SQL Server 2012Introducing Microsoft SQL Server 2012
Introducing Microsoft SQL Server 2012
 
Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1Sql server licensing_guide_partneredn_v1-1
Sql server licensing_guide_partneredn_v1-1
 
Pre Install Databases
Pre Install DatabasesPre Install Databases
Pre Install Databases
 
Advanced SharePoint Server Concepts
Advanced SharePoint Server ConceptsAdvanced SharePoint Server Concepts
Advanced SharePoint Server Concepts
 
Simple Farm Server Deployment
Simple Farm Server DeploymentSimple Farm Server Deployment
Simple Farm Server Deployment
 
Tech Ed Africa Demystifying Backup Restore In Share Point 2007
Tech Ed Africa Demystifying Backup Restore In Share Point 2007Tech Ed Africa Demystifying Backup Restore In Share Point 2007
Tech Ed Africa Demystifying Backup Restore In Share Point 2007
 
01 qmds2005 session01
01 qmds2005 session0101 qmds2005 session01
01 qmds2005 session01
 
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...
Tutorial: SharePoint 2013 Admin in the Hybrid World by Jason Himmelstein - SP...
 
SQL212 Oracle SQL Manual
SQL212 Oracle SQL ManualSQL212 Oracle SQL Manual
SQL212 Oracle SQL Manual
 
TEC2010 SharePoint 2010 Upgrade
TEC2010 SharePoint 2010 UpgradeTEC2010 SharePoint 2010 Upgrade
TEC2010 SharePoint 2010 Upgrade
 
Oracle OSB Tutorial 3
Oracle OSB Tutorial 3Oracle OSB Tutorial 3
Oracle OSB Tutorial 3
 
Pivotal CRM for iPad
Pivotal CRM for iPadPivotal CRM for iPad
Pivotal CRM for iPad
 
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
How To Configure Email Enabled Lists In Moss2007 Rtm Using Exchange 2003
 
Share point 2013 installation step by step
Share point 2013 installation step by stepShare point 2013 installation step by step
Share point 2013 installation step by step
 
JSF2 and JSP
JSF2 and JSPJSF2 and JSP
JSF2 and JSP
 
ATG - Installing WebLogic Server
ATG - Installing WebLogic ServerATG - Installing WebLogic Server
ATG - Installing WebLogic Server
 
Weblogic 12c Graphical Mode installation steps in Windows
Weblogic 12c Graphical Mode installation steps in Windows Weblogic 12c Graphical Mode installation steps in Windows
Weblogic 12c Graphical Mode installation steps in Windows
 
Oracle OSB Tutorial 1
Oracle OSB Tutorial 1Oracle OSB Tutorial 1
Oracle OSB Tutorial 1
 

Destaque

M mc cormack
M mc cormackM mc cormack
M mc cormackmsabala
 
Как маркетплейсы произведут революцию на рынке электронного ОСАГО
Как маркетплейсы произведут революцию на рынке электронного ОСАГОКак маркетплейсы произведут революцию на рынке электронного ОСАГО
Как маркетплейсы произведут революцию на рынке электронного ОСАГОInstitute of development of the Internet
 
Performance Coaching 2009
Performance Coaching  2009Performance Coaching  2009
Performance Coaching 2009dawnlennon
 
Les journées de Chipo - Jour 276 - 02
Les journées de Chipo - Jour 276 - 02Les journées de Chipo - Jour 276 - 02
Les journées de Chipo - Jour 276 - 02Figaronron Figaronron
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Kode etik guru indonesia
Kode etik guru indonesiaKode etik guru indonesia
Kode etik guru indonesiaRadite Suandana
 
Rab komputer pc dak bk kb n juknis 2016
Rab komputer pc dak bk kb n juknis 2016Rab komputer pc dak bk kb n juknis 2016
Rab komputer pc dak bk kb n juknis 2016Redis Manik
 

Destaque (9)

M mc cormack
M mc cormackM mc cormack
M mc cormack
 
Как маркетплейсы произведут революцию на рынке электронного ОСАГО
Как маркетплейсы произведут революцию на рынке электронного ОСАГОКак маркетплейсы произведут революцию на рынке электронного ОСАГО
Как маркетплейсы произведут революцию на рынке электронного ОСАГО
 
Norton Paint System - Broschyr
Norton Paint System - BroschyrNorton Paint System - Broschyr
Norton Paint System - Broschyr
 
S4 trabajo 4 minas
S4 trabajo 4 minasS4 trabajo 4 minas
S4 trabajo 4 minas
 
Performance Coaching 2009
Performance Coaching  2009Performance Coaching  2009
Performance Coaching 2009
 
Les journées de Chipo - Jour 276 - 02
Les journées de Chipo - Jour 276 - 02Les journées de Chipo - Jour 276 - 02
Les journées de Chipo - Jour 276 - 02
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Kode etik guru indonesia
Kode etik guru indonesiaKode etik guru indonesia
Kode etik guru indonesia
 
Rab komputer pc dak bk kb n juknis 2016
Rab komputer pc dak bk kb n juknis 2016Rab komputer pc dak bk kb n juknis 2016
Rab komputer pc dak bk kb n juknis 2016
 

Semelhante a Sql server indexed views speed up your select queries part 1 - code-projec

Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005rainynovember12
 
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersKoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersTobias Koprowski
 
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersKoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersTobias Koprowski
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part isqlserver.co.il
 
Access tips access and sql part 1 setting the sql scene
Access tips  access and sql part 1  setting the sql sceneAccess tips  access and sql part 1  setting the sql scene
Access tips access and sql part 1 setting the sql scenequest2900
 
4) databases
4) databases4) databases
4) databasestechbed
 
Sage 300 ERP: Technical Tour of Diagnostic Tools
Sage 300 ERP: Technical Tour of Diagnostic ToolsSage 300 ERP: Technical Tour of Diagnostic Tools
Sage 300 ERP: Technical Tour of Diagnostic ToolsSage 300 ERP CS
 
SAP BO and Teradata best practices
SAP BO and Teradata best practicesSAP BO and Teradata best practices
SAP BO and Teradata best practicesDmitry Anoshin
 
Tech-Spark: Azure SQL Databases
Tech-Spark: Azure SQL DatabasesTech-Spark: Azure SQL Databases
Tech-Spark: Azure SQL DatabasesRalph Attard
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
Making ultra fast ultra scalable solutions with sitecore 8
Making ultra fast ultra scalable solutions with sitecore 8Making ultra fast ultra scalable solutions with sitecore 8
Making ultra fast ultra scalable solutions with sitecore 8Mark van Aalst
 
Apex basics-for Beginners
Apex basics-for BeginnersApex basics-for Beginners
Apex basics-for Beginnershrakhra
 
Obiee11g working with partitions
Obiee11g working with partitionsObiee11g working with partitions
Obiee11g working with partitionsAmit Sharma
 
Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Aaron Shilo
 
Toad for Sybase Datasheet
Toad for Sybase DatasheetToad for Sybase Datasheet
Toad for Sybase DatasheetToad4Sybase
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL ServerRajesh Gunasundaram
 

Semelhante a Sql server indexed views speed up your select queries part 1 - code-projec (20)

Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005Optimizing Data Accessin Sq Lserver2005
Optimizing Data Accessin Sq Lserver2005
 
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginnersKoprowskiT_SQLSat409_MaintenancePlansForBeginners
KoprowskiT_SQLSat409_MaintenancePlansForBeginners
 
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginnersKoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
KoprowskiT_SQLSaturday409_MaintenancePlansForBeginners
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part i
 
Access tips access and sql part 1 setting the sql scene
Access tips  access and sql part 1  setting the sql sceneAccess tips  access and sql part 1  setting the sql scene
Access tips access and sql part 1 setting the sql scene
 
4) databases
4) databases4) databases
4) databases
 
Sage 300 ERP: Technical Tour of Diagnostic Tools
Sage 300 ERP: Technical Tour of Diagnostic ToolsSage 300 ERP: Technical Tour of Diagnostic Tools
Sage 300 ERP: Technical Tour of Diagnostic Tools
 
Ebook11
Ebook11Ebook11
Ebook11
 
SAP BO and Teradata best practices
SAP BO and Teradata best practicesSAP BO and Teradata best practices
SAP BO and Teradata best practices
 
Tech-Spark: Azure SQL Databases
Tech-Spark: Azure SQL DatabasesTech-Spark: Azure SQL Databases
Tech-Spark: Azure SQL Databases
 
Managing SQLserver
Managing SQLserverManaging SQLserver
Managing SQLserver
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
Making ultra fast ultra scalable solutions with sitecore 8
Making ultra fast ultra scalable solutions with sitecore 8Making ultra fast ultra scalable solutions with sitecore 8
Making ultra fast ultra scalable solutions with sitecore 8
 
Apex basics-for Beginners
Apex basics-for BeginnersApex basics-for Beginners
Apex basics-for Beginners
 
Obiee11g working with partitions
Obiee11g working with partitionsObiee11g working with partitions
Obiee11g working with partitions
 
Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…Getting to know oracle database objects iot, mviews, clusters and more…
Getting to know oracle database objects iot, mviews, clusters and more…
 
CDS Views.pptx
CDS Views.pptxCDS Views.pptx
CDS Views.pptx
 
Toad for Sybase Datasheet
Toad for Sybase DatasheetToad for Sybase Datasheet
Toad for Sybase Datasheet
 
Query Optimization in SQL Server
Query Optimization in SQL ServerQuery Optimization in SQL Server
Query Optimization in SQL Server
 
Oracle query optimizer
Oracle query optimizerOracle query optimizer
Oracle query optimizer
 

Mais de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republicKaing Menglieng
 
Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republicKaing Menglieng
 
Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republicKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republicKaing Menglieng
 

Mais de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republic
 
Using object dependencies in sql server 2008 tech republic
Using object dependencies in sql server 2008   tech republicUsing object dependencies in sql server 2008   tech republic
Using object dependencies in sql server 2008 tech republic
 
Using hash fields in sql server tech republic
Using hash fields in sql server   tech republicUsing hash fields in sql server   tech republic
Using hash fields in sql server tech republic
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republic
 

Sql server indexed views speed up your select queries part 1 - code-projec

  • 1. SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject 9,219,840 members and growing! Email Password Sign in Join Lost password? Home Articles Quick Answers Discussions Zones Features Community Help! » Database » Database » SQL Server Part of The SQL Zone sponsored by SQL Server Indexed Views - Licence First Posted CPOL 19 May 2011 Speed Up Your Select Queries: Views Bookmarked 11,349 8 times See Also Part 1 More like this More by this author By andrewwasfy | 19 May 2011 | Article SQL SQL-Server DBA Dev Beginner An introduction to SQL Server Indexed Views. Article Browse Code Stats Revisions Alternatives 4.46 (6 votes) 4 History about views Views are a virtual table defining a query against one or more tables. Data isn’t stored in the database and the result set is determined while the view is executed. What’s an Indexed View? An indexed view has a unique clustered index. The clustered index is stored in SQL Server and updated like any other clustered index, providing SQL Server with another place to look to potentially optimize a query utilizing the indexed view. Queries that don’t specifically use the indexed view can even benefit from the existence of the clustered index from the view. In the developer and enterprise editions of SQL Server, the optimizer can use the indexes of views to optimize queries that do not specify the indexed view. In the other editions of SQL Server, however, the query must include the indexed view and specify the hint NOEXPAND to get the benefit of the index on the view. If your queries could benefit from having more than one index on the view, non-clustered indexes can also be created on the view. This would supply the optimizer with more possibilities to speed up the queries referencing the columns included in the view. Where to use them? Indexed views have both a benefit and a cost. The cost of an indexed view is on the maintenance of the clustered index (and any non-clustered indexes you may choose to add). One must weigh the cost to maintain the index against the benefit of query optimization provided by the index. When the underlying tables are subject to significant inserts, updates, and deletes, be very careful in selecting the indexes (both table and view) that will provide the greatest coverage across your queries for the lowest cost. Typically, environments that are best suited for indexed views are data warehouses, data marts, OLAP databases, and the like. Transactional environments are less suitable for indexed views. Look for repeating joins utilizing the same columns, joins on large tables, aggregations on large tables, and repeating queries as potential candidates for indexed views. Be careful of creating indexed views where the result set contains more rows than the base tables as this will be counterproductive. How to create them? A view that is to be indexed has to be created with schema binding. This means that once the indexed view is created, the underlying tables cannot be altered in any way that would materially affect the indexed view unless the view is first altered or dropped. It also means that all the tables referenced in the view must be referenced by their two-part name http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]
  • 2. SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject (schemaname.tablename). Below is an example of the CREATE statement for an indexed view, MyView , and its underlying table, MyBigTable. The table is first created, then the view that references two of the table’s three columns, and finally the unique clustered index on the view making it an indexed view. CREATE TABLE OAGTable( ID INT PRIMARY KEY, Depart VARCHAR(3), arrival VARCHAR(3), DurationinMin int ) GO CREATE VIEW MyView WITH SCHEMABINDING AS SELECT ID, Duration FROM dbo. OAGTable WHERE DurationinMin > 300 GO CREATE UNIQUE CLUSTERED INDEX idx_MyView ON MyView(DurationinMin) Once this index is created, the result set of this view is stored in the database just like any other clustered index. Any query that explicitly uses the view will be able to take advantage of the index on the view. Queries that contain a predicate similar to the view and that fall into the range defined by the view may also reap the optimization rewards of having that index available (assuming the execution cost is non-trivial). Consider the following query: SELECT ID FROM OAGTable WHERE DurationinMin > 400 Even though the query does not use the indexed view, the optimizer has the option of using the clustered index created on the view if it provides better performance than the clustered or non-clustered indexes on the base table. If you want the optimizer to always choose the indexed view over the base tables when optimizing a query containing an index view, you must use the hint NOEXPAND . Conversely, if you’d like to see how a query containing an indexed view would perform utilizing the base tables instead, you can specify the option EXPAND VIEWS , thus saving you the time substituting the base tables yourself. Constraints An index cannot be created on just any view. Several constraints exist that a view must meet in order for the index creation to be successful. We discussed WITH SCHEMABINDING and two-part table names above. Here are some other constraints: The view must have been created with certain SET options, such as QUOTED_IDENTIFIER and CONCAT_NULL_YIELDS_NULL set to ON . The session creating the index must also have the correct SET options. Any user-defined function referenced by the view must have been created using WITH SCHEMABINDING . The view must be deterministic (consistently providing the same result given the same input). The base tables must have been created with the proper ANSI_NULLS setting. The result set of the view is physically stored in the database, thus storage space for the clustered index is also a constraint to consider. In addition to this, there are constraints on the contents of the view. For instance, the view may not contain EXISTS or NOT EXISTS , OUTER JOIN , COUNT(*) , MIN , MAX , subqueries, table hints, TOP , UNION , and much more. Check the SQL Server Development Center on MSDN for a complete listing. References http://technet.microsoft.com/en-us/library/cc917715.aspx License This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) About the Author andrewwasfy Software Developer http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]
  • 3. SQL Server Indexed Views - Speed Up Your Select Queries: Part 1 - CodeProject (Senior) Majisa Egypt Member Article Top Sign Up to vote Poor Excellent Vote Comments and Discussions You must Sign In to use this message board. Search this forum Go Profile popups Noise Medium Medium Layout Normal Normal Per page 25 25 Update Refresh First Prev Next My vote of 4 Abed-elfattah Yacoub 0:57 6 Aug '11 My vote of 2 kornakar 21:39 19 May '11 http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer[08/29/2012 4:20:35 PM]