0% found this document useful (0 votes)
339 views15 pages

Understanding SQL Views with Examples

Views

Uploaded by

Samina Khalid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
339 views15 pages

Understanding SQL Views with Examples

Views

Uploaded by

Samina Khalid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

24/11/2024, 15:11 SQL Views

SQL Views
Last Updated : 11 Nov, 2024

Views in SQL are a type of virtual table that simplifies how users interact with
data across one or more tables. Unlike traditional tables, a view in SQL does
not store data on disk; instead, it dynamically retrieves data based on a pre-
defined query each time it’s accessed.

SQL views are particularly useful for managing complex queries, enhancing
security, and presenting data in a simplified format. In this guide, we will cover
the SQL create view statement, updating and deleting views, and using the
WITH CHECK OPTION clause.

Demo SQL Database


We will be using these two SQL tables for examples.

StudentDetails

StudentMarks

[Link] 1/15
24/11/2024, 15:11 SQL Views

You can create these tables on your system by writing the following SQL
query:

MySQL

1 -- Create StudentDetails table


2 CREATE TABLE StudentDetails (
3 S_ID INT PRIMARY KEY,
4 NAME VARCHAR(255),
5 ADDRESS VARCHAR(255)
6 );
7
8 INSERT INTO StudentDetails (S_ID, NAME, ADDRESS)
9 VALUES
10 (1, 'Harsh', 'Kolkata'),
11 (2, 'Ashish', 'Durgapur'),
12 (3, 'Pratik', 'Delhi'),
13 (4, 'Dhanraj', 'Bihar'),
14 (5, 'Ram', 'Rajasthan');
15
16 -- Create StudentMarks table
17 CREATE TABLE StudentMarks (
18 ID INT PRIMARY KEY,
19 NAME VARCHAR(255),
20 Marks INT,
21 Age INT
22 );
23
24 INSERT INTO StudentMarks (ID, NAME, Marks, Age)
25 VALUES
26 (1, 'Harsh', 90, 19),
27 (2, 'Suresh', 50, 20),
28 (3, 'Pratik', 80, 19),
29 (4, 'Dhanraj', 95, 21),
30 (5, 'Ram', 85, 18);

[Link] 2/15
24/11/2024, 15:11 SQL Views

CREATE VIEWS in SQL


We can create a view using CREATE VIEW statement. A View can be created
from a single table or multiple tables.

Syntax

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

Parameters:

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows

SQL CREATE VIEW Statement Examples


Let’s look at some examples of CREATE VIEW Statement in SQL to get a better
understanding of how to create views in SQL.

Example 1: Creating View from a single table

In this example, we will create a View named DetailsView from the table
StudentDetails. Query:

CREATE VIEW DetailsView AS


SELECT NAME, ADDRESS

[Link] 3/15
24/11/2024, 15:11 SQL Views

FROM StudentDetails
WHERE S_ID < 5;

To see the data in the View, we can query the view in the same manner as we
query a table.

SELECT * FROM DetailsView;

Output:

Example 2: Create View From Table

In this example, we will create a view named StudentNames from the table
StudentDetails. Query:

CREATE VIEW StudentNames AS


SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

If we now query the view as,

SELECT * FROM StudentNames;

Output:

[Link] 4/15
24/11/2024, 15:11 SQL Views

Example 3: Creating View from multiple tables

In this example we will create a View named MarksView from two tables
StudentDetails and StudentMarks. To create a View from multiple tables we
can simply include multiple tables in the SELECT statement. Query:

CREATE VIEW MarksView AS


SELECT [Link], [Link], [Link]
FROM StudentDetails, StudentMarks
WHERE [Link] = [Link];

To display data of View MarksView:

SELECT * FROM MarksView;

Output:

LISTING ALL VIEWS IN A DATABASE


We can list View using the SHOW FULL TABLES statement or using the
information_schema table. A View can be created from a single table or
multiple tables.

Syntax

USE "database_name";
SHOW FULL TABLES WHERE table_type LIKE "%VIEW";

Using information_schema

[Link] 5/15
24/11/2024, 15:11 SQL Views

SELECT table_name
FROM information_schema.views
WHERE table_schema = 'database_name';

OR

SELECT table_schema, table_name, view_definition


FROM information_schema.views
WHERE table_schema = 'database_name';

DELETE VIEWS in SQL


SQL allows us to delete an existing View. We can delete or drop View using
the DROP statement.
Databases SQL MySQL PostgreSQL PL/SQL MongoDB SQL Cheat Sheet SQL Interview Questions MyS
Syntax

DROP VIEW view_name;

Example

In this example, we are deleting the View MarksView.

DROP VIEW MarksView;

UPDATE VIEW in SQL


If you want to update the existing data within the view, use the UPDATE
statement.

Syntax

UPDATE view_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

Note: Not all views can be updated using the UPDATE statement.

[Link] 6/15
24/11/2024, 15:11 SQL Views

If you want to update the view definition without affecting the data, use the
CREATE OR REPLACE VIEW statement. you can use this syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;

Rules to Update Views in SQL:

Certain conditions need to be satisfied to update a view. If any of these


conditions are not met, the view can not be updated.

1. The SELECT statement which is used to create the view should not include
GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
5. The view should be created from a single table. If the view is created using
multiple tables then we will not be allowed to update the view.

Examples

Let’s look at different use cases for updating a view in SQL. We will cover
these use cases with examples to get a better understanding.

Example 1: Update View to Add or Replace a View Field

We can use the CREATE OR REPLACE VIEW statement to add or replace


fields from a view.

If we want to update the view MarksView and add the field AGE to this View
from StudentMarks Table, we can do this by:

CREATE OR REPLACE VIEW MarksView AS


SELECT [Link], [Link], [Link],
[Link]

[Link] 7/15
24/11/2024, 15:11 SQL Views

FROM StudentDetails, StudentMarks


WHERE [Link] = [Link];

If we fetch all the data from MarksView now as:

SELECT * FROM MarksView;

Output:

Example 2: Update View to Insert a row in a view

We can insert a row in a View in the same way as we do in a table. We can use
the INSERT INTO statement of SQL to insert a row in a View.

In the below example, we will insert a new row in the View DetailsView which
we have created above in the example of “creating views from a single table”.

INSERT INTO DetailsView(NAME, ADDRESS)


VALUES("Suresh","Gurgaon");

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:

Example 3: Deleting a row from a View

[Link] 8/15
24/11/2024, 15:11 SQL Views

Deleting rows from a view is also as simple as deleting rows from a table. We
can use the DELETE statement of SQL to delete rows from a view. Also
deleting a row from a view first deletes the row from the actual table and the
change is then reflected in the view.

In this example, we will delete the last row from the view DetailsView which
we just added in the above example of inserting rows.

DELETE FROM DetailsView


WHERE NAME="Suresh";

If we fetch all the data from DetailsView now as,

SELECT * FROM DetailsView;

Output:

WITH CHECK OPTION Clause

The WITH CHECK OPTION clause in SQL is a very useful clause for views. It
applies to an updatable view.

The WITH CHECK OPTION clause is used to prevent data modification (using
INSERT or UPDATE) if the condition in the WHERE clause in the CREATE VIEW
statement is not satisfied.

If we have used the WITH CHECK OPTION clause in the CREATE VIEW
statement, and if the UPDATE or INSERT clause does not satisfy the conditions
then they will return an error.

WITH CHECK OPTION Clause Example:

In the below example, we are creating a View SampleView from the


StudentDetails Table with a WITH CHECK OPTION clause.
[Link] 9/15
24/11/2024, 15:11 SQL Views

CREATE VIEW SampleView AS


SELECT S_ID, NAME
FROM StudentDetails
WHERE NAME IS NOT NULL
WITH CHECK OPTION;

In this view, if we now try to insert a new row with a null value in the NAME
column then it will give an error because the view is created with the condition
for the NAME column as NOT NULL. For example, though the View is
updatable then also the below query for this View is not valid:

INSERT INTO SampleView(S_ID)


VALUES(6);

NOTE: The default value of NAME column is null.

Uses of a View
A good database should contain views for the given reasons:

1. Restricting data access – Views provide an additional level of table security


by restricting access to a predetermined set of rows and columns of a table.
2. Hiding data complexity – A view can hide the complexity that exists in
multiple joined tables.
3. Simplify commands for the user – Views allow the user to select
information from multiple tables without requiring the users to actually
know how to perform a join.
4. Store complex queries – Views can be used to store complex queries.
5. Rename Columns – Views can also be used to rename the columns without
affecting the base tables provided the number of columns in view must
match the number of columns specified in a select statement. Thus,
renaming helps to hide the names of the columns of the base tables.
6. Multiple view facility – Different views can be created on the same table for
different users.

Key Takeaways About SQL Views

[Link] 10/15
24/11/2024, 15:11 SQL Views

Views in SQL are a kind of virtual table.


The fields in a view can be from one or multiple tables.
We can create a view using the CREATE VIEW statement and delete a
view using the DROP VIEW statement.
We can update a view using the CREATE OR REPLACE VIEW
statement.
WITH CHECK OPTION clause is used to prevent inserting new rows
that do not satisfy the view’s filtering condition.

"This course is very well structured and easy to learn. Anyone with zero
experience of data science, python or ML can learn from this. This course
makes things so easy that anybody can learn on their own. It's helping me a lot.
Thanks for creating such a great course."- Ayushi Jain | Placed at Microsoft

Now's your chance to unlock high-earning job opportunities as a Data Scientist!


Join our Complete Machine Learning & Data Science Program and get a 360-
degree learning experience mentored by industry experts.

Get hands on practice with 40+ Industry Projects, regular doubt solving
sessions, and much more. Register for the Program today!

[Link] 11/15
24/11/2024, 15:11 SQL Views

Views in DBMS Visit Course

H Harsh Agarwal 230

Previous Article Next Article


SQL RTRIM() Function SQL Views

Similar Reads
Difference Between Views and Materialized Views in PL/SQL
In PL/SQL views play an important role in data accessibility, data manipulation,
and query optimization. Views help restrict the user's data, which is not suppose…
5 min read

SQL | Views
In SQL, a view is a virtual table based on the result-set of an SQL statement. A
view also has rows and columns as they are in a real table in the database. We…
3 min read

Delete Views in SQL Server


In the area of relational databases, SQL Server is one of the most powerful and
popular systems. It is flexible to make possible the development of complex dat…
4 min read

How to use INFORMATION_SCHEMA Views in SQL Server


In SQL Server, INFORMATION_SCHEMA Views are a set of views provided by the
INFORMATION_SCHEMA database in the SQL server that stores the metadata …
4 min read

Difference between Structured Query Language (SQL) and Transact-SQL (T-…


Structured Query Language (SQL): Structured Query Language (SQL) has a
specific design motive for defining, accessing and changement of data. It is…
2 min read

[Link] 12/15
24/11/2024, 15:11 SQL Views

Configure SQL Jobs in SQL Server using T-SQL


In this article, we will learn how to configure SQL jobs in SQL Server using T-
SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-S…
7 min read

MongoDB Views
In MongoDB, there are two primary types of views such as Standard Views and
On-demand Materialized Views. These views offer different ways of managing…
7 min read

SQL SERVER – Input and Output Parameter For Dynamic SQL


An Input Parameter can influence the subset of rows it returns from a select
statement within it. A calling script can get the value of an output parameter. An…
3 min read

Difference between T-SQL and PL-SQL


1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query
Language. It is a product by Microsoft and is an extension of SQL Language whi…
3 min read

SQL - SELECT from Multiple Tables with MS SQL Server


In SQL we can retrieve data from multiple tables also by using SELECT with
multiple tables which actually results in CROSS JOIN of all the tables. The…
3 min read

Article Tags : Databases SQL

Corporate & Communications Address:-


A-143, 9th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305) | Registered Address:- K 061,
[Link] 13/15
24/11/2024, 15:11 SQL Views
Tower K, Gulshan Vivante Apartment,
Sector 137, Noida, Gautam Buddh
Nagar, Uttar Pradesh, 201305

Company Languages
About Us Python
Legal Java
In Media C++
Contact Us PHP
Advertise with us GoLang
GFG Corporate Solution SQL
Placement Training Program R Language
GeeksforGeeks Community Android Tutorial
Tutorials Archive

DSA Data Science & ML


Data Structures Data Science With Python
Algorithms Data Science For Beginner
DSA for Beginners Machine Learning
Basic DSA Problems ML Maths
DSA Roadmap Data Visualisation
Top 100 DSA Interview Problems Pandas
DSA Roadmap by Sandeep Jain NumPy
All Cheat Sheets NLP
Deep Learning

Web Technologies Python Tutorial


HTML Python Programming Examples
CSS Python Projects
JavaScript Python Tkinter
TypeScript Web Scraping
ReactJS OpenCV Tutorial
NextJS Python Interview Question
Bootstrap Django
Web Design

Computer Science DevOps


Operating Systems Git
Computer Network Linux
Database Management System AWS
Software Engineering Docker
Digital Logic Design Kubernetes
[Link] 14/15
24/11/2024, 15:11 SQL Views
Engineering Maths Azure
Software Development GCP
Software Testing DevOps Roadmap

System Design Inteview Preparation


High Level Design Competitive Programming
Low Level Design Top DS or Algo for CP
UML Diagrams Company-Wise Recruitment Process
Interview Guide Company-Wise Preparation
Design Patterns Aptitude Preparation
OOAD Puzzles
System Design Bootcamp
Interview Questions

School Subjects GeeksforGeeks Videos


Mathematics DSA
Physics Python
Chemistry Java
Biology C++
Social Science Web Development
English Grammar Data Science
Commerce CS Subjects
World GK

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

[Link] 15/15

Common questions

Powered by AI

The key differences between SQL views and materialized views lie in their data storage and refresh mechanisms. An SQL view does not store any data itself but dynamically retrieves data from the underlying tables whenever accessed. In contrast, a materialized view stores actual data on disk and requires explicit refreshes to stay updated with the source data. These differences influence database design in that SQL views are suitable for scenarios requiring real-time data without additional storage, while materialized views are optimal for performance improvement in read-heavy databases where real-time data is not as critical .

SQL views enhance database security by restricting user access to predefined subsets of data. By using views, administrators can limit exposure to sensitive data, ensuring users only see or interact with required data segments without permitting access to the entire table. Views serve as an additional layer of security, complementing user permissions and protecting underlying table structures from direct manipulation .

SQL views offer the benefit of encapsulating complex queries, making them reusable and easier to manage than repeatedly writing intricate SQL statements. They simplify database interactions for end users who do not need to understand the underlying complexity, thus improving usability and security by abstracting business logic. However, limitations include performance overhead due to dynamically retrieving data each time the view is accessed, which can be slower compared to direct query execution or using materialized views that store pre-calculated results .

Maintaining up-to-date metadata about SQL views using INFORMATION_SCHEMA is crucial for managing database environments as it provides detailed information about existing view definitions, helping in auditing, documentation, and understanding the database structure. Such metadata facilitates efficient querying for view details, ensuring administrators can track structural changes and dependencies within the database ecosystem. Accurate metadata assists in performance tuning and prepares databases for maintenance and development tasks .

SQL views provide several advantages over traditional tables, such as enhancing security by restricting access to a specific set of rows and columns, simplifying query execution for the user by managing complex queries internally, and allowing easier manipulation and presentation of data by hiding the complexity inherent in joined tables . Views also allow renaming of columns without altering the base tables and facilitate different user requirements by enabling multiple views on the same table .

The CREATE OR REPLACE VIEW statement allows the modification of an existing SQL view without changing its name or requiring the view to be dropped first. It enables adding, removing, or altering columns in the view’s query definition. This is particularly useful when a view needs to be updated with new columns or adjusted to reflect changes in the business logic or underlying database schema without interrupting the existing dependencies on the view .

The WITH CHECK OPTION clause in SQL views ensures that any data modification through INSERT or UPDATE respects the WHERE clause condition specified in the view's definition. This clause prevents invalid data from being inserted or updated by enforcing the view's constraints at all times. If a data modification operation violates these constraints, it results in an error . This mechanism is particularly important for maintaining data integrity and enforcing business rules at the database level .

Updating an SQL view using the UPDATE statement may be inappropriate when the view includes a SELECT statement with GROUP BY, ORDER BY, or DISTINCT clauses. It is also unsuitable if the view is based on multiple tables, contains NOT NULL values that cannot be satisfied, or is defined using nested or complex queries, as these constraints prevent direct updates of view data .

Views aid in the reusability and maintainability of SQL queries by encapsulating complex query logic in a single, reusable object. This abstraction allows developers to make changes in the view definition without affecting other queries built on top of the view. Consequently, it reduces redundancy in query logic across applications, facilitating easier updates, consistency in data presentation, and reducing errors. Views ensure that improvements or changes in logic only need updating in one location, promoting maintainability .

Deleting a view in SQL using the DROP VIEW statement permanently removes the view schema from the database, which can lead to the loss of pre-written query abstractions that simplify interaction with underlying tables. The deletion of a view does not affect the data in the underlying tables but may impact applications and users that rely on the view for data retrieval and presentation .

You might also like