SQL View A complete introduction and walk through

SQL View A complete introduction and walk through

SQL View - A complete introduction and walk-through

SQLShack

SQL Server training Español

SQL View – A complete introduction and walk-through

July 1, 2019 by Rajendra Gupta In relational databases, data is structured using various database objects like tables, stored procedure, views, clusters etc. This article aims to walk you through ‘SQL VIEW’ – one of the widely-used database objects in SQL Server. It is a good practice to organize tables in a database to reduce redundancy and dependency in SQL database. Normalization is a database process for organizing the data in the database by splitting large tables into smaller tables. These multiple tables are linked using the relationships. Developers write queries to retrieve data from multiple tables and columns. In the query, we might use multiple joins and queries could become complicated and overwhelming to understand. Users should also require permissions on individual objects to fetch the data. Let’s go ahead and see how SQL VIEW help to resolve these issues in SQL Server.

Introduction

A VIEW in SQL Server is like a virtual table that contains data from one or multiple tables. It does not hold any data and does not exist physically in the database. Similar to a SQL table, the view name should be unique in a database. It contains a set of predefined SQL queries to fetch data from the database. It can contain database tables from single or multiple databases as well. In the following image, you can see the VIEW contains a query to join three relational tables and fetch the data in a virtual table. A VIEW does not require any storage in a database because it does not exist physically. In a VIEW, we can also control user security for accessing the data from the database tables. We can allow users to get the data from the VIEW, and the user does not require permission for each table or column to fetch data. Let’s explore user-defined VIEW in SQL Server. Note: In this article, I am going to use sample database AdventureWorks for all examples.

Create a SQL VIEW

The syntax to create a VIEW is as follows: 123 CREATE VIEW Name AS Select column1, Column2...Column N From tables Where conditions;

Example 1 SQL VIEW to fetch all records of a table

It is the simplest form of a VIEW. Usually, we do not use a VIEW in SQL Server to fetch all records from a single table. 1234 CREATE VIEW EmployeeRecordsAS SELECT * FROM [HumanResources].[Employee]; Once a VIEW is created, you can access it like a SQL table.

Example 2 SQL VIEW to fetch a few columns of a table

We might not be interested in all columns of a table. We can specify required column names in the select statement to fetch those fields only from the table. 1234 CREATE VIEW EmployeeRecordsAS SELECT NationalIDNumber,LoginID,JobTitle FROM [HumanResources].[Employee];

Example 3 SQL VIEW to fetch a few columns of a table and filter results using WHERE clause

We can filter the results using a Where clause condition in a Select statement. Suppose we want to get EmployeeRecords with Martial status ‘M’. 12345678 CREATE VIEW EmployeeRecordsAS SELECT NationalIDNumber, LoginID, JobTitle, MaritalStatus FROM [HumanResources].[Employee] WHERE MaritalStatus = 'M';

Example 4 SQL VIEW to fetch records from multiple tables

We can use VIEW to have a select statement with Join condition between multiple tables. It is one of the frequent uses of a VIEW in SQL Server. In the following query, we use INNER JOIN and LEFT OUTER JOIN between multiple tables to fetch a few columns as per our requirement. 1234567891011121314151617181920 CREATE VIEW [Sales].[vStoreWithContacts]AS SELECT s.[BusinessEntityID], s.[Name], ct.[Name] AS [ContactType], p.[Title], p.[FirstName], p.[MiddleName], p.[LastName], p.[Suffix], pp.[PhoneNumber], ea.[EmailAddress], p.[EmailPromotion] FROM [Sales].[Store] s INNER JOIN [Person].[BusinessEntityContact] bec ON bec.[BusinessEntityID] = s.[BusinessEntityID] INNER JOIN [Person].[ContactType] ct ON ct.[ContactTypeID] = bec.[ContactTypeID] INNER JOIN [Person].[Person] p ON p.[BusinessEntityID] = bec.[PersonID] LEFT OUTER JOIN [Person].[EmailAddress] ea ON ea.[BusinessEntityID] = p.[BusinessEntityID] LEFT OUTER JOIN [Person].[PersonPhone] pp ON pp.[BusinessEntityID] = p.[BusinessEntityID];GO Suppose you need to execute this query very frequently. Using a VIEW, we can simply get the data with a single line of code. 1 select * from [Sales].[vStoreWithContacts]

Example 5 SQL VIEW to fetch specific column

In the previous example, we created a VIEW with multiple tables and a few column from those tables. Once we have a view, it is not required to fetch all columns from the view. We can select few columns as well from a VIEW in SQL Server similar to a relational table. In the following query, we want to get only two columns name and contract type from the view. 123 SELECT Name, ContactTypeFROM [Sales].[vStoreWithContacts];

Example 6 Use Sp_helptext to retrieve VIEW definition

We can use sp_helptext system stored procedure to get VIEW definition. It returns the complete definition of a SQL VIEW. For example, let’s check the view definition for EmployeeRecords VIEW. We can use SSMS as well to generate the script for a VIEW. Expand database -> Views -> Right click and go to Script view as -> Create To -> New Query Editor Window.

Example 7 sp_refreshview to update the Metadata of a SQL VIEW

Suppose we have a VIEW on a table that specifies select * statement to get all columns of that table. 1234 CREATE VIEW DemoViewAS SELECT * FROM [AdventureWorks2017].[dbo].[MyTable]; Once we call the VIEW DemoView, it gives the following output. Let’s add a new column in the table using the Alter table statement. 1 Alter Table [AdventureWorks2017].[dbo].[MyTable] Add City nvarchar(50) Rerun the select statement to get records from VIEW. It should display the new column as well in the output. We still get the same output, and it does not contain the newly added column. By Default, SQL Server does not modify the schema and metadata for the VIEW. We can use the system stored procedure sp_refreshview to refresh the metadata of any view. 1 Exec sp_refreshview DemoView Rerun the select statement to get records from VIEW. We can see the City column in the output.

Example 8 Schema Binding a SQL VIEW

In the previous example, we modify the SQL table to add a new column. Suppose in the production instance, and you have a view in the application. You are not aware of the changes in the table design for the new column. We do not want any changes to be made in the tables being used in the VIEW. We can use SCHEMABINDING option to lock all tables used in the VIEW and deny any alter table statement against those tables. Let’s execute the following query with an option SCHEMABINDING. 12345 CREATE VIEW DemoViewWITH SCHEMABINDINGAS SELECT * FROM [AdventureWorks2017].[dbo].[MyTable]; It gives an error message. Msg 1054, Level 15, State 6, Procedure DemoView, Line 4 [Batch Start Line 2]
Syntax ‘*’ is not allowed in schema-bound objects. We cannot call all columns (Select *) in a VIEW with SCHEMABINDING option. Let’s specify the columns in the following query and execute it again. 12345 CREATE VIEW DemoViewWITH SCHEMABINDINGAS SELECT TableID, ForeignID ,Value, CodeOne FROM [AdventureWorks2017].[dbo].[MyTable]; We again get the following error message. Msg 4512, Level 16, State 3, Procedure DemoView, Line 5 [Batch Start Line 1]
Cannot schema bind VIEW ‘DemoView’ because of the name ‘AdventureWorks2017.dbo.MyTable’ is invalid for schema binding.
Names must be in a two-part format, and an object cannot reference itself. In my query, I used a three-part object name in the format [DBName.Schema.Object]. We cannot use this format with SCHEMABINDING option in a VIEW. We can use the two-part name as per the following query. 12345 CREATE VIEW DemoViewWITH SCHEMABINDINGAS SELECT TableID, ForeignID ,Value, CodeOne FROM [dbo].[MyTable]; Once you have created a VIEW with SCHEMABINDING option, try to add a modify a column data type using Alter table command. 1 ALTER TABLE dbo.MyTable ALTER COLUMN ForeignID BIGINT; We need to drop the VIEW definition itself along with other dependencies on that table before making a change to the existing table schema.

Example 8 SQL VIEW ENCRYPTION

We can encrypt the VIEW using the WITH ENCRYPTION clause. Previously, we checked users can see the view definition using the sp_helptext command. If we do not want users to view the definition, we can encrypt it. 12345 CREATE VIEW DemoViewWITH ENCRYPTIONAS SELECT TableID, ForeignID ,Value, CodeOne FROM [dbo].[MyTable]; Now if you run the sp_helptext command to view the definition, you get the following error message. 1 Exec sp_helptext DemoView The text for the object ‘DemoView’ is encrypted.

Example 9 SQL VIEW for DML Update Delete and Insert queries

We can use SQL VIEW to insert, update and delete data in a single SQL table. We need to note the following things regarding this. We can use DML operation on a single table only VIEW should not contain Group By, Having, Distinct clauses We cannot use a subquery in a VIEW in SQL Server We cannot use Set operators in a SQL VIEW Use the following queries to perform DML operation using VIEW in SQL Server. Insert DML 1 Insert into DemoView values(4,'CC','KK','RR') Delete DML 1 Delete from DemoView where TableID=7 Update DML 1 Update DemoView set value='Raj' where TableID=5

Example 10 SQL VIEW and Check Option

We can use WITH CHECK option to check the conditions in VIEW are inline with the DML statements. It prevents to insert rows in the table where the condition in the Where clause is not satisfied If the condition does not satisfy, we get an error message in the insert or update statement In the following query, we use the CHECK option, and we want only values starting with letter F in the [Codeone] column. 123456 CREATE VIEW DemoViewAS SELECT * FROM [dbo].[MyTable] WHERE [Codeone] LIKE 'F%'WITH CHECK OPTION; If we try to insert a value that does not match the condition, we get the following error message. 1 Insert into DemoView values (5,'CC','Raj','Raj')

Example 11 Drop SQL VIEW

We can drop a VIEW using the DROP VIEW statement. In the following query, we want to drop the VIEW demoview in SQL Server. 1 DROP VIEW demoview;

Example 12 Alter a SQL VIEW

We can change the SQL statement in a VIEW using the following alter VIEW command. Suppose we want to change the condition in the where clause of a VIEW. Execute the following query. 123456 Alter VIEW DemoViewAS SELECT * FROM [dbo].[MyTable] WHERE [Codeone] LIKE 'C%'WITH CHECK OPTION; Starting from SQL Server 2016 SP1, we can use the CREATE or ALTER statement to create a SQL VIEW or modify it if already exists. Prior to SQL Server 2016 SP1, we cannot use both CREATE or Alter together. 12345 CREATE OR ALTER VIEW DemoViewAS SELECT * FROM [dbo].[MyTable] WHERE [Codeone] LIKE 'C%'WITH CHECK OPTION;

Conclusion

In this article, we explored SQL View with various examples. You should be familiar with the view in SQL Server as a developer or DBA as well. Further, you can learn more on how to create view in SQL Server and SQL Server indexed view. If you have any comments or questions, feel free to leave them in the comments below. Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Top SQL Server Books Introduction to pagination in SQL Server The benefits, costs, and documentation of database constraints Term Extraction Transformation in SSIS What is causing database slowdowns? 175,565 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!