SlideShare a Scribd company logo
1 of 23
Download to read offline
CHAPTER
th
SQL
NIGHT
Designing and
Implementing Views
Sotiris Karras
Fivi Panopoulou
Oct 10, 2015
26
• Introduction to Views
• View options
• Updatable Views
• Indexed Views
Agenda
Views
A view is a virtual table whose contents
are defined by a query
CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ]
[ WITH <view_attribute> [ ,...n ] ]
AS select_statement
[ WITH CHECK OPTION ]
[ ; ]
<view_attribute> ::=
{
[ ENCRYPTION ]
[ SCHEMABINDING ]
[ VIEW_METADATA ]
}
Views
• Query is eventually applied to the underlying object
• Views can be used for
• Simplification and customization
• Security
• Backward compatibility
• The select statement cannot include
• ORDER BY clause, unless it is used with TOP or OFFSET
• Reference to temporary table or variable
• INTO and OPTION keywords
CHAPTER
View Options
CHAPTER
• CHECK OPTION
• The CHECK OPTION in the SELECT statement of a
CREATE VIEW statement allows the user to specify rules
that any modifications against the view must be
compliant with.
• Any modifications that happen in the underlying tables
that violate the rules within the CHECK OPTION are not
visible in the view.
CHAPTER
• SCHEMABINDING
• The SCHEMABINDING option, binds the view to the
schema of the underlying tables.
• The SCHEMABINDING option can be used only with
objects within the same database and in the SELECT
statement the participating objects must be referenced
as (schema.object).
• Other views or tables cannot be altered or dropped if
they are participating in schemabinded views.
CHAPTER
• ENCRYPTION and VIEW_METADATA
• 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.
CHAPTER
DEMO
Views
CHAPTER
Updatable Views
• Views through which the data of the underlying tables
can be modified.
• Managing security privileges across multiple tables
easier.
• User can modify underlying table through the view, f he haw the
corresponding permission on the view.
Updatable Views
• The modifications in an UPDATE, DELETE or INSERT statement can only
reference one underlying table at a time.
• The underlying columns to be modified, must be directly referenced by the
columns of the view. Cannot update columns that are derived by aggregate
functions or other computations.
• TOP clause is not present in the SELECT statement of the view.
• The columns being modified are not affected by GROUP BY, HAVING, or
DISTINCT clauses.
• Rule of thumb: The Database engine must be able to UNAMBIGUOUSLY trace
modifications from the view to the underlying table.
Restrictions
• The above restrictions can be avoided by creating an INSTEAD OF trigger on
the view.
• The trigger, explicitly specifies the actions to be taken if a data modification
statement is to be made on the view.
• By using an INSTEAD OF trigger, every view can be made updatable.
Bypassing the restrictions
CREATE TRIGGER <trigger_name>
ON <view>
INSTEAD OF
{INSERT, UPDATE, DELETE}
AS <SQL_code_here>;
CHAPTER
DEMO
Updatable Views
CHAPTER
Indexed Views
• Indexed View: a view with a unique clustered index on it
• Indexed views are used for performance tuning
• An indexed view can be updatable
• Query optimizer can use the index to speed up queries
• Additional non-clustered indexes can be created
• Indexed views affect insert and update operations on
base tables
Indexed Views
• Verify SET options for session and underlying tables
• Check that the view definition is deterministic
• Create the view with SCHEMABINDING
• Create a unique clustered index on the view
Creating an Indexed View
SET OPTIONS REQUIRED VALUE
ANSI_NULLS ON
ANSI_PADDING ON
ANSI_WARNINGS ON
ARITHABORT ON
CONCAT_NULL_YIEDS_NULL ON
NUMERIC_ROUNDABORT OFF
QUOTED IDENTIFIER ON
• All expressions in the select list, the WHERE and the
GROUP BY clause must be deterministic
• Deterministic expression: returns the same result every
time evaluated on the same input
• Precise expression: do not contain float expressions
• Float expression can only be non-key columns
• Only precise deterministic expressions can participate in
key columns.
Deterministic Views and Precise Columns
• If GROUP BY is present
• the definition must contain COUNT_BIG(*)
• must not contain HAVING
• the key can reference only columns specified in the GROUP BY
clause
• CLR functions can appear in the select list, but cannot
be part of the key
• The view cannot reference objects in other databases
Restrictions
• The statement must not contain the following elements
Restrictions
COUNT DISTINCT * MIN, MAX
ORDER BY TOP OFFSET STDEV, STDEVP, VAR, VARP, AVG
OUTER joins Self-joins UNION,EXCEPT,INTERSECT CUBE, ROLLUP, GROUPING SETS
Subquery CTE Derived table table-valued functions
CLR user-defined aggregate
function
PIVOT, UNPIVOT APPLY text, ntext, image, XML, filestream
columns
Full-text predicates TABLESAMPLE Table variables ROWSET functions
SUM function on nullable
expression
Sparse column
sets
CHECKSUM_AGG OVER clause, which includes ranking
or aggregate window functions
… and some more restrictions and requirements
https://msdn.microsoft.com/en-us/library/ms191432.aspx#Restrictions
CHAPTER
DEMO
Indexed Views
help@sqlschool.gr
SELECT
KNOWLEDGE
FROM
SQL SERVER
http://www.sqlschool.gr
Copyright © 2015 SQL School Greece

More Related Content

Similar to Implementing and Using Views in SQL Server

Similar to Implementing and Using Views in SQL Server (20)

SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data   SQL Inteoduction to SQL manipulating of data
SQL Inteoduction to SQL manipulating of data
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Oracle view
Oracle viewOracle view
Oracle view
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
View, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - ThaiptView, Store Procedure & Function and Trigger in MySQL - Thaipt
View, Store Procedure & Function and Trigger in MySQL - Thaipt
 
chap 9 dbms.ppt
chap 9 dbms.pptchap 9 dbms.ppt
chap 9 dbms.ppt
 
6232 b 04
6232 b 046232 b 04
6232 b 04
 
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn vbds
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn  vbdsfoodmunch 2.pptx hdshid hdbfhdbfhkd vcn  vbds
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn vbds
 
MySQL Views
MySQL ViewsMySQL Views
MySQL Views
 
Session 14 - Working with table view and search bar
Session 14 - Working with table view and search barSession 14 - Working with table view and search bar
Session 14 - Working with table view and search bar
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Part1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the OptimizerPart1 of SQL Tuning Workshop - Understanding the Optimizer
Part1 of SQL Tuning Workshop - Understanding the Optimizer
 
Les10
Les10Les10
Les10
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
View
ViewView
View
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Implementing and Using Views in SQL Server

  • 1. CHAPTER th SQL NIGHT Designing and Implementing Views Sotiris Karras Fivi Panopoulou Oct 10, 2015 26
  • 2. • Introduction to Views • View options • Updatable Views • Indexed Views Agenda
  • 3. Views A view is a virtual table whose contents are defined by a query CREATE VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ] <view_attribute> ::= { [ ENCRYPTION ] [ SCHEMABINDING ] [ VIEW_METADATA ] }
  • 4. Views • Query is eventually applied to the underlying object • Views can be used for • Simplification and customization • Security • Backward compatibility • The select statement cannot include • ORDER BY clause, unless it is used with TOP or OFFSET • Reference to temporary table or variable • INTO and OPTION keywords
  • 6. CHAPTER • CHECK OPTION • The CHECK OPTION in the SELECT statement of a CREATE VIEW statement allows the user to specify rules that any modifications against the view must be compliant with. • Any modifications that happen in the underlying tables that violate the rules within the CHECK OPTION are not visible in the view.
  • 7. CHAPTER • SCHEMABINDING • The SCHEMABINDING option, binds the view to the schema of the underlying tables. • The SCHEMABINDING option can be used only with objects within the same database and in the SELECT statement the participating objects must be referenced as (schema.object). • Other views or tables cannot be altered or dropped if they are participating in schemabinded views.
  • 8. CHAPTER • ENCRYPTION and VIEW_METADATA • 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.
  • 11. • Views through which the data of the underlying tables can be modified. • Managing security privileges across multiple tables easier. • User can modify underlying table through the view, f he haw the corresponding permission on the view. Updatable Views
  • 12. • The modifications in an UPDATE, DELETE or INSERT statement can only reference one underlying table at a time. • The underlying columns to be modified, must be directly referenced by the columns of the view. Cannot update columns that are derived by aggregate functions or other computations. • TOP clause is not present in the SELECT statement of the view. • The columns being modified are not affected by GROUP BY, HAVING, or DISTINCT clauses. • Rule of thumb: The Database engine must be able to UNAMBIGUOUSLY trace modifications from the view to the underlying table. Restrictions
  • 13. • The above restrictions can be avoided by creating an INSTEAD OF trigger on the view. • The trigger, explicitly specifies the actions to be taken if a data modification statement is to be made on the view. • By using an INSTEAD OF trigger, every view can be made updatable. Bypassing the restrictions CREATE TRIGGER <trigger_name> ON <view> INSTEAD OF {INSERT, UPDATE, DELETE} AS <SQL_code_here>;
  • 16. • Indexed View: a view with a unique clustered index on it • Indexed views are used for performance tuning • An indexed view can be updatable • Query optimizer can use the index to speed up queries • Additional non-clustered indexes can be created • Indexed views affect insert and update operations on base tables Indexed Views
  • 17. • Verify SET options for session and underlying tables • Check that the view definition is deterministic • Create the view with SCHEMABINDING • Create a unique clustered index on the view Creating an Indexed View SET OPTIONS REQUIRED VALUE ANSI_NULLS ON ANSI_PADDING ON ANSI_WARNINGS ON ARITHABORT ON CONCAT_NULL_YIEDS_NULL ON NUMERIC_ROUNDABORT OFF QUOTED IDENTIFIER ON
  • 18. • All expressions in the select list, the WHERE and the GROUP BY clause must be deterministic • Deterministic expression: returns the same result every time evaluated on the same input • Precise expression: do not contain float expressions • Float expression can only be non-key columns • Only precise deterministic expressions can participate in key columns. Deterministic Views and Precise Columns
  • 19. • If GROUP BY is present • the definition must contain COUNT_BIG(*) • must not contain HAVING • the key can reference only columns specified in the GROUP BY clause • CLR functions can appear in the select list, but cannot be part of the key • The view cannot reference objects in other databases Restrictions
  • 20. • The statement must not contain the following elements Restrictions COUNT DISTINCT * MIN, MAX ORDER BY TOP OFFSET STDEV, STDEVP, VAR, VARP, AVG OUTER joins Self-joins UNION,EXCEPT,INTERSECT CUBE, ROLLUP, GROUPING SETS Subquery CTE Derived table table-valued functions CLR user-defined aggregate function PIVOT, UNPIVOT APPLY text, ntext, image, XML, filestream columns Full-text predicates TABLESAMPLE Table variables ROWSET functions SUM function on nullable expression Sparse column sets CHECKSUM_AGG OVER clause, which includes ranking or aggregate window functions … and some more restrictions and requirements https://msdn.microsoft.com/en-us/library/ms191432.aspx#Restrictions