SQL VIEW Statement

SQL VIEWS

A SQL VIEW is a virtual database table.

You can learn about how to create, update, and delete a sql view by this lessons.



Sql views statement using how to create view in sql server, update view sql server, create table from view, create or replace view, drop view sql server, Add Index View, Alter View or Add Columns, Change View Datatype, Create and View Temp Table, Delete View.

SQL CREATE VIEW Statement

A SQL VIEW can be considered as virtual data table based on the query result of composition of a table in the form of an SQL SELECT or predefined SQL statement.

A SQL VIEW will look like a real database table with all or selected rows and fields. The columns and records in a view are data from one or more real data tables in the database.

You can add any valid SQL SELECT statement like SQL functions, SQL WHERE, and SQL JOINS statements to a view and present the data as if the data were coming from one single data table or multiple data table.

SQL CREATE VIEW Syntax

The basic syntax is:


CREATE VIEW view_name AS
SELECT column_name_list(s)
FROM table_name
[WHERE condition]

Note: A view always display latest information! The database system engine recreates the information, using the view's SQL statement, every time a user queries a view.


SQL CREATE VIEW Example

Following is an example table named "Books" look like this:

BookId BookName BookPrice AuthorName Domain
101 Sql Complete Reference 250.5 Suresh Babu Database
102 Sql Commands 120 Haris Karthik Database
103 Pl / Sql Quick Notes 150 Siva Kumar Programming

Here, we have to create a view from BOOKS table. This view would be used to have bookname, authorname and bookprice from BOOKS table:

We use the following sql statement to create view.


CREATE VIEW My_Book_View AS
SELECT BookName, AuthorName, BookPrice
FROM Books;

We can query the view above as follows:


SELECT * FROM My_Book_View;

After executing above statement, the result will look like this:

BookName AuthorName BookPrice
Sql Complete Reference Suresh Babu 250.5
Sql Commands Haris Karthik 120
Pl / Sql Quick Notes Siva Kumar 150

Another example, The following statement will fetch all records with domain "Database" from "Books" table.


CREATE VIEW Database_Books AS
SELECT * FROM Books
WHERE Domain = 'Database';

We can query the view above as follows:


SELECT * FROM Database_Books;

After executing above statement, the result will look like this:

BookId BookName BookPrice AuthorName Domain
101 Sql Complete Reference 250.5 Suresh Babu Database
102 Sql Commands 120 Haris Karthik Database

SQL Updating a View

We can update a view by using following sql statement:

SQL CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column_name_list(s)
FROM table_name
[WHERE condition]

Now we want to apply a condition which bookprice less than 200 to the "My_Book_View" view. We will update the view with the following SQL:


CREATE VIEW My_Book_View AS
SELECT BookName, AuthorName, BookPrice
FROM Books
WHERE BookPrice < 200;

After executing above statement, the result will look like this:

BookName AuthorName BookPrice
Sql Commands Haris Karthik 120
Pl / Sql Quick Notes Siva Kumar 150

SQL Droping a View

We can delete or remove a view using SQL DROP VIEW statement.

SQL DROP VIEW Syntax

The basic syntax is:


DROP VIEW viewname;

SQL DROP VIEW Example

Now we want to delete the "My_Book_View" view:


DROP VIEW My_Book_View;


Sql server views query using select from view, create view sql server example, updatable view, create view statement, Exec View, Fetch Data from View, Join Views, SQL View Multiple Tables, View vs Table, View with Union.

SQL Add Index View

To make an indexed view, first construct a view with the schema binding option, then add an index to the view.

You may generate indices on views using the Database Engine. Indexed or materialised views are examples of such views. When a view has a unique clustered index, the view is performed, and the result set is saved in the database in the same way as a table with a clustered index is stored. This signifies that data pages are stored in the clustered index's B+- tree's leaf nodes.

Note: The syntax enhancements to the CREATE INDEX and CREATE VIEW statements are used to create indexed views. You describe the requirements of a view rather than a table name in the CREATE INDEX statement.

Creating an indexed view is a two-step process:

  • Use the CREATE VIEW statement with the SCHEMABINDING clause to create the view.
  • Create the clustered index that corresponds.

To create an indexed view, you use the following steps:

  • To begin, create a view with the WITH SCHEMABINDING option, which ties the view to the underlying tables' schema.
  • Second, on the view, construct a single clustered index. This brings the vision to life.
  • Because of the WITH SCHEMABINDING option, you must drop the indexed view first before making any modifications to the underlying tables that influence the indexed view's description.

In particular, SQL Server mandates that all object references in an indexed view use the schema.object two-part naming convention, and that all mentioned objects are in the same database.

The data in the indexed view is automatically updated when the data in the underlying tables changes. The referenced tables experience a write overhead as a result of this. When you write to the underlying table, SQL Server has to write to the view's index as well. As a result, you should only use an indexed view for tables with infrequent data updates.

Example 1: Creating an SQL Server indexed view example

The following statement generates an indexed view using columns from the example database's production.products, production.brands, and production.categories tables:

CREATE VIEW product_master
WITH SCHEMABINDING
AS 
SELECT
    product_id,
    product_name,
    model_year,
    list_price,
    brand_name,
    category_name
FROM
    production.products p
INNER JOIN production.brands b 
    ON b.brand_id = p.brand_id
INNER JOIN production.categories c 
    ON c.category_id = p.category_id;

Example 2: Create an indexed view for above table. First we create a view on Employee table,

CREATE VIEW VW_Employee WITH SCHEMABINDING AS    
SELECT e.Emp_Id,e.EmployeeName,e.EmpSalary,e.StateId,e.CityId    
FROM dbo.Employee e    
WHERE e.EmployeeName LIKE '[A-P]%'    

If we try to create an indexed view without using the schemabinding option, SQL Server will complain that "Cannot construct index on view 'VW Employee' because view is not schema bound."

Example 3: The first step, creating a typical view that can be indexed to improve performance, is demonstrated in this illustration. (Works on is assumed to be a very huge table in this example.)

USE sample;
GO
CREATE VIEW v_enter_month
	WITH SCHEMABINDING
	AS SELECT emp_no, DATEPART(MONTH, enter_date) AS enter_month
	FROM dbo.works_on;

Example 4: Here I am taking “AdventureWorks2012” as a database to demonstrate my example and below is the definition of the view.

CREATE VIEW dbo.viewTestIndexedView
WITH SCHEMABINDING
AS
SELECT
PP.ProductID, PP.Name, PP.Color, SUM(SSO.UnitPrice) AS UnitPriceTotal, SUM(SSO.LineTotal) AS LineTotal,
COUNT_BIG(*) AS CountTotal
FROM Production.Product PP
INNER JOIN Sales.SalesOrderDetail SSO
ON PP.ProductID = SSO.ProductID
GROUP BY PP.ProductID, PP.Name, PP.Color
GO

Now, in order to materialise it, we must establish a unique clustered index on it, as per the requirement.


SQL Alter View or Add Columns

The ALTER VIEW statement in MySQL modifies a view's description. A view is created from the results of a query that include a SELECT statement or a UNION of two or more SELECT statements.

In addition, depending on the operations you're executing, you'll require specific authorization on the underlying objects.

The ALTER VIEW statement regenerates an existing view by adding a scope to a reference type column. The ALTER VIEW statement also allows you to activate or deactivate a view for query efficiency purposes.

Syntax:

ALTER VIEW view-name
    ALTER column column-name ADD SCOPE table-name
    [ENABLE/DISABLE QUERY OPTIMIZATION] 

After changing one of the basis tables, you use the ALTER VIEW command to regenerate an invalid view to guarantee that it remains valid.

Example 1: Modify the view's handling algorithm from UNDEFINED to MERGE with the ALTER VIEW statement, then add the customerNumber field:

ALTER 
    ALGORITHM=MERGE
VIEW salesOrders AS
  SELECT 
   orderNumber, 
   customerNumber,
   productCode,
   quantityOrdered, 
   priceEach, 
   status
 FROM
   orders
 INNER JOIN
  orderDetails USING (orderNumber); 

Example 2: The column specification replaces any prior columns specified for the view.

ALTER VIEW MyView AS SELECT TableCol1 AS ViewCol1,
  TableCol2 AS ViewCol2,
  TableCol3 AS ViewCol3
  FROM MyTable

Example 3: For example, I have created a view that retrieves some selected data from a table.

USE BackupDatabase
GO
CREATE VIEW dbo.SelectView
AS
SELECT [ProductID]
  ,[Name]
  ,[ProductNumber]
  ,[Color]
  ,[StandardCost]
  ,[ListPrice]
  ,[Size]
  ,[Weight]
FROM [BackupDatabase].[SalesLT].[Product]

SQL Change View Datatype

The view to be altered is specified. It has to be a view mentioned in the catalogue.

ALTER COLUMN column-name

The name of the column that has to be changed. The column-name must match one of the view's current columns (SQLSTATE 42703). It is impossible to qualify the name.

Rules if If a view directly or indirectly refers a materialised query table,

  • it cannot be used for query optimization (MQT). An MQT or statistical perspective might refer to another statistical view.
  • A catalogue table is referenced directly or indirectly in the view.
  • The view is typed.

Notes

A view must be considered when optimising a query:

  • An aggregate or distinct operation is not allowed.
  • A union, unless, or intersect operation is not allowed.

Example: Use CAST / CONVERT to that specific column in your VIEW Definition to make the change at the VIEW level.

CREATE VIEW AView
AS
SELECT CAST(title AS char(50))
FROM titles

SQL Create and View Temp Table

SQL Views:

A view is a virtual table that is created from the results of a SQL statement and stored in the database under a specific name.

Each time you retrieve data from the underlying base table, look at the SQL query.

It is not permissible to create views on temporary tables.

SQL temp table:

Tables and displays for temporary data are completely different.

The temp table is a distinct database item. When you insert rows into it, it populates with them.

Temporary tables are an important subject to understand. You can store and process intermediate results with temporary tables utilising the same selection, update, and join capabilities as regular SQL tables.

View use:

  1. Reduce redundancy in query authoring by reusing some SQL query logic.
  2. Improve performance for complex calculations and joins by making outcomes simple and hiding sophisticated logic.
  3. Giving team members and non-developers simple access to query logic.
  4. You want to add/remove fields without having to change the underlying schema (Table schema).

Temporary table use:

  • Use a temp table if the structure or SQL query logic will not be reused frequently.
  • If there is logic that requires data manipulation that cannot be accomplished in a single query, the output of one query / interim results can be placed in a temporary table, which subsequently participates in additional manipulation via joins and other methods to reach the desired result.

Example :

create table #foo(id int)
go
create view vfoo 
as
select * from #foo

Result:

Msg 4508, Level 16, State 1, Procedure vfoo, Line 4 [Batch Start Line 9]
Views or functions are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.


SQL Delete View

Delete rows from a view in the same way that you delete rows from a table. To remove rows from a view, we can use the SQL DELETE statement. We must first understand the requisite rights to delete a view before we can delete a row from it. Second, we must comprehend the drawbacks of eliminating a view.

A user must have authorization to delete a view in SQL Server.

  • Either user must have ALTER permission on the schema that contains the view.
  • A user must have CONTROL permission on the item as an alternative.
  • When we delete a view in SQL Server, the definition of the view, as well as any related metadata, is deleted from the system catalogue. In particular, any rights associated with that view are erased.

A view is the result set of a stored data query.

A SQL view is a table that does not exist physically. It's just a fictitious table.

A SQL VIEW is built by joining one or more tables in a SQL query.

Syntax:

DELETE FROM view_name
WHERE condition;

view_name: Name of view from where we want to delete rows

condition: Condition to select rows

Example 1: In this example, we'll delete the last row from the DetailsView view, which we just added in the inserting rows illustration above.

DELETE FROM DetailsView
WHERE NAME="Suresh";

Example 2: To delete a view in SQL Server using a query is quite simple. And for this task, we can use the following syntax.

USE databse_name;  
GO  
IF OBJECT_ID ('view_name', 'V') IS NOT NULL  
DROP VIEW view_name;  
GO

Example 3: First, we'll specify the database where the view exists in the example above. The "IF OBJECT ID " statement is then used to check for the existence of the view. Finally, we destroy the view from SQL Server with the DROP VIEW query.

CREATE VIEW IBM_Billings
 AS
 SELECT BillingNumber, BillingDate, BillingTotal
 FROM Billings
 WHERE BankerID = (SELECT BankerID FROM Bankers WHERE BankerName = 'IBM')
 GO

 INSERT INTO IBM_Billings (BillingNumber, BillingDate, BillingTotal)
 VALUES ('8', '2002-07-31', 417)
 GO

 DELETE FROM IBM_Billings
 WHERE BillingNumber = '3'
 GO

SQL Drop View

To entirely remove a view from the database, use the DROP VIEW statement.

The ANSI/ISO standard for SQL has been extended with this statement.

Syntax:

The following illustrates the syntax of the DROP VIEW statement:

DROP VIEW [IF EXISTS] view_name
[CASCADE | RESTRICT]

After the DROP VIEW keywords, type the name of the view.

Second, only drop a view if it already exists using the IF EXISTS option. PostgreSQL will throw an error if you don't utilise the IF EXISTS option and drop a view that doesn't exist. If you use the IF EXISTS option, PostgreSQL instead issues a notification.

Third, if any objects are dependent on the view, use the RESTRICT option to prevent it from being removed. The default setting is RESTRICT. When the CASCADE option is used, the DROP VIEW command drops all objects that are dependent on view, as well as any objects that are dependent on those objects.

Example 1: The following statement drops the view that is named cust1:

DROP VIEW cust1

Example 2: The following example shows how to drop the sales.daily_sales view from the sample database:

DROP VIEW IF EXISTS sales.daily_sales;

Example 3: This example uses the DROP VIEW statement to drop the customerPayments view:

DROP VIEW IF EXISTS customerPayments;

Example 4: The following statement uses the DROP VIEW statement to drop the film_master view:

DROP VIEW film_master;

PostgreSQL issued an error:

ERROR: cannot drop view film_master because other objects depend on it
DETAIL: view horror_film depends on view film_master
HINT: Use DROP ... CASCADE to drop the dependent objects too.
SQL state: 2BP01


SQL Exec View

The query-specification is evaluated by the EXEC SQL CREATE VIEW command, which produces a viewed table named viewed-table-name.

Syntax :

EXEC SQL [DBID dbid] CREATE VIEW viewed-table-name
[(column-identifier [, column-identifier] ... )]
AS query-specification [WITH CHECK OPTION];

Example 1:

EXEC SQL CREATE VIEW example
EXEC SQL CREATE VIEW ViewedTableName
AS SELECT Age FROM Persons WHERE Age = 19;

Example 2: SQL Executing Views

select quotename(table_schema) +'.' + quotename(table_name) as ViewNAme,
 identity(int,1,1) as ID
  into #test
  from information_schema.tables
 where table_type = 'view'

declare @Loopid int,@MaxID int

select @LoopID =1,@MaxID =MAX(id) 
from #test

declare @ViewName varchar(100)

while @LoopID <= @MaxID
begin

select @ViewName = ViewNAme 
from #test
where id = @LoopID

exec ('select top 1 * from ' + @ViewName)
set @LoopID = @LoopID + 1
end

drop table #test

Execute a view in SQL Server:

Using a SQL query, call a view in SQL Server. Now we'll see how to use SQL Server Management Studio to run a view. The steps for implementing this are as follows.

  • To begin, open SQL Server Management Studio and connect to the database instance you need.
  • Expand the necessary Databases directory in the Object Explorer next.
  • Then, beneath the database, expand the Views directory. And the Views directory will list all of the views in that database.
  • Finally, in SQL Server, right-click the required view and select "SELECT TOP 1000 Rows."

SQL Fetch Data from View

Example 1: view named EMP_DETAILS which looks like:

CREATE OR REPLACE FORCE VIEW "ABC"."EMP_DETAILS" ("NAME",  "COUNTRY") AS 

SELECT 
b.NAME,c.COUNTRY
FROM 
ABC.Emp a ,ABC.Emp_Bom b ,ABC.Emp_info c 
where a.E_ID=b.ID and a.R_ID=c.NR order by 1 asc;

I simply wish to fetch a row from this view and the query for the same looks like,

Select * from EMP_DETAILS where NAME = 'xxx' and COUNTRY = 'xxx';

Example 2:

SELECT * INTO ATable FROM AView

Because the view is nothing more than a saved query, you can't script data from it. So you can script its definition, but it's pointless to mention the view's data because the data the view exposes is in some tables, not the view. The RESULTS of the view are saved as data in a table.


SQL Join Views

In the CREATE VIEW statement, a join view is one that is based on many basis tables that are linked together to form a view. Any insert, update, or delete statement on a view can only update one of the view's base tables. If the main and unique keys are unique on the views result set, a table is called a key maintained in a join view.

Example 1: JOIN views with tables. You can use views just like tables in SELECTs.

SELECT * FROM view1 INNER JOIN view2 ON view1.id = view2. ref; 

Example 2: The joins for find out views:

create view t1_view as select a.empno, a.ename, a.deptno, b.dname
 from emp a, dept b
 where a.deptno = b.deptno;

desc t1_view;
Name	Null?	    Type
EMPNO	NOT NULL	NUMBER(4)
ENAME	
VARCHAR2(10)
DEPTPNO	
NUMBER(2)
DNAME	
VARCHAR2(14)
select * from t1_view;
EMPNO	ENAME	DEPTNO	DNAME
7369	SMITH	20	RESEARCH
7499	ALLEN	30	SALES
7521	WARD	30	SALES
7566	JONES	20	RESEARCH
7654	MARTIN	30	SALES

Because the primary key of the emp is also unique in the view, the key of the table emp is kept in the aforementioned view. Because the primary key deptno is duplicated multiple times, the dept table is not key saved.

Example 3:

Sample table: orders

Sample table: customer

Sample table: agents

To create a view 'ordersview' by three tables 'orders', 'customer' and ' agents' with following conditions:

'a' and 'b' and 'c' are the aliases of 'orders' and 'customer' and 'agents' table, 'cust_code' of 'orders' and 'customer' table must be same, 'agent_code' of 'orders' and 'agents' table must be same, the following SQL statement can be used:

CREATE VIEW ordersview
AS SELECT ord_num, ord_amount, a.agent_code,
agent_name, cust_name
FROM orders a, customer b, agents c
WHERE a.cust_code=b.cust_code
AND a.agent_code=c.agent_code;

SQL Update Views

The SQL UPDATE VIEW command can be used to change a view's data.

Not all views can be changed. As a result, the UPDATE command does not apply to all views. An updatable view helps in performing a UPDATE command on it without impacting any other tables.

SQL views can only be updated using the UPDATE statement if they are a direct subset of table data with no aggregation or alteration.

Using the UPDATE statement, you can update the underlying data of a SQL view. The real table data will be updated, not the view's SQL query.

Syntax:

UPDATE < view_name > SET<column1>=<value1>,<column2>=<value2>,.....
WHERE <condition>;

Example 1: This statement bellow creates a updatable view 'orderindate':

CREATE VIEW orderindate
AS SELECT agent_code,ord_num,cust_code,advance_amount
FROM orders
WHERE ord_date IN ('15-APR-08','15-Aug-08');

SQL statement can be used:

UPDATE orderindate SET advance_amount=2000
WHERE advance_amount=1500;

Example 2:

update order_view
  set quantity=50
  where order_date>'2020-05-03';

select * from order_view;

Output:

+------------+----------+
| order_date | quantity |
+------------+----------+
| 2020-05-01 |       23 |
| 2020-05-01 |       35 |
| 2020-05-02 |       45 |
| 2020-05-02 |       23 |
| 2020-05-03 |       19 |
| 2020-05-03 |       15 |
| 2020-05-04 |       50 |
| 2020-05-04 |       50 |
+------------+----------+

You can use the UPDATE statement on views if the SELECT statement for the view is as follows:

DISTINCT, GROUP BY, HAVING, AGGREGATIONS, SET functions and operators are not available.

There are no references to several tables.

There are no computed columns.

Example 3: You can update a VIEW without dropping it by using the following Example:

CREATE or REPLACE VIEW myView AS
    SELECT first_name, last_name
    FROM employee;

select * from myView;

Output:

FIRST_NAME LAST_NAME
---------- ----------
Jason      Martin
Alison     Mathews
James      Smith
Celia      Rice
Robert     Black
Linda      Green
David      Larry
James      Cat

SQL View

Views are database objects that are similar to virtual tables in that they contain columns and rows from the table being referenced. It holds data from one or several tables but has no actual storage.  A view, like a true table in the database, has rows and columns.

A View can contain either all of a table's rows or only certain rows based on a condition. When we update, insert, or perform any other operation on a view, it is applied to the table(s) on which the view was constructed.

A SQL Server view does not keep a set of values in a database unless it is specified as indexed. When you run the SELECT Statement against a SQL view, the records will come from the table that was linked when the view was created.

Construct VIEW is used to create a View. A single table or numerous tables can be used to construct a View.

A logical subset of data from one or more tables is referred to as a VIEW in SQL. View is a data access restriction tool.

Types Of Views:

  • System View
  • User Define View

Because User Defined Views are so crucial, I will only discuss them. There are two kinds of them:

Simple View

A Simple View is defined as a View that is generated on a single Table. On a Simple View, we can do any operation that we can on a table.

Complex view

Complex Views are views that are constructed from multiple tables. A Complex View is unable to conduct all table operations.

Syntax for creating a View :

CREATE or REPLACE VIEW view_name 
    AS
    SELECT column_name(s)
    FROM table_name
    WHERE condition

Example 1: This example shows how to create View in SQL Server using the Create Statement:

CREATE VIEW EmployeesViewbyQuery
AS
SELECT  [FirstName] + ' ' + [LastName] AS Name
	,[Occupation]
	,[Education]
	,dept.DepartmentName AS Department
	,[YearlyIncome] AS Income
	,[Sales]
FROM [MyEmployees Table]
   INNER JOIN 
 	 Department AS dept ON
	    Dept.[id] = [MyEmployees Table].DeptID
GO

Example 2: Consider following Sale table,

oid	order_name	previous_balance	customer
11	ord1		2000	    		Alex
12	ord2		1000	    		Adam
13	ord3		2000	    		Abhi
14	ord4		1000	    		Adam
15	ord5		2000		    	Alex

SQL Query to Create a View from the above table will be,

CREATE or REPLACE VIEW sale_view 
AS 
SELECT * FROM Sale WHERE customer = 'Alex';

The results of the SELECT operation will be saved in a new object called sale_view. We can use CREATE and REPLACE separately, but combining the two is preferable because if a view with the supplied name already exists, this query will replace it with new data.


SQL View Benifits

Advantages of views

Security

Users can access views through a narrow collection of views that include the precise data the user is authorised to see, limiting the user's access to stored data.

This is due to the fact that each user can now only access and edit a certain quantity of data.

Query Simplicity

A view can combine data from multiple tables into a single table, effectively reducing multi-table searches to single-table queries against the view.

Structural simplicity

Views can provide a user with a "personalized" view of the database structure, presenting it as a set of virtual tables that sound right to that user.

Consistency

Views give a stable, unmodified depiction of the database structure, even if the underlying source tables are divided, restructured, or renamed, without requiring schema modifications.

Data Integrity

When data is accessed and entered via a view, the DBMS can examine the data to ensure that it complies with the given integrity constraints.

Logical data independence

To some extent, View can make the application and database tables distinct. If no view is available, the application must be built on a table. The program can be set up in view of the above, to view the program with a database table divided.

Performance:

Because the database stores the specification of the SQL query rather than the actual data, views are quicker.

Easy and Reusable:

Multiple tables can be combined and simplified into a single virtual table using views.

View Hide complex queries for a cleaner look and the ability to reuse sophisticated query code.

Aggregated data:

Views can be used as aggregated tables, in which the database engine aggregates data (sum, average, etc.) and displays the generated results beside the data.

Data independence

The view is an abstraction of the table structure that is unrelated to the real table data.

The view logic is separate from the underlying database table structure and data.

Simplicity:

A view can take data from multiple tables and present it in a straightforward, easy-to-understand fashion.

Advantages:

  1. Data is not stored in a physical location by views.
  2. You can use the view to conceal parts of the table's columns.
  3. Because data insertion, update, and deletion are not feasible with views, they can give Access Restriction.

SQL View Constraints

When it comes to sanitising data, CHECK restrictions are already rather useful. However, CHECK constraints have significant drawbacks, such as the fact that they are applied to the table itself, which is inconvenient when you wish to express constraints that only occur in specific circumstances. The SQL standard WITH CHECK OPTION clause, which is enabled by at least Oracle and SQL Server, can be used to accomplish this.

The constraints must be specified with the DISABLE NOVALIDATE clause because they are not validated. Traditional views have the drawback of being unable to define referential integrity requirements against any view.

ALTER VIEW Emp_view
ADD CONSTRAINT emp_view_unq
UNIQUE (first_name) DISABLE NOVALIDATE;

Views are used to hide the internal table join processes in a complex query. Declarative primary key, unique key, and foreign key constraints against views can now be specified as seen below.

Constraints on views:

  1. NOT NULL: It cannot be specified explicitly because it is always inherited straight from the view's base tables.
  2. Unique constraints: Oracle allows you to specify unique constraints on any column in the view.
  3. Primary key: Today we can get primary key constraints defined directly upon the view.

Example 1:

CREATE TABLE books (
  id    NUMBER(10)         NOT NULL,
  title VARCHAR2(100 CHAR) NOT NULL,
  price NUMBER(10, 2)      NOT NULL,
   
  CONSTRAINT pk_book PRIMARY KEY (id)
);
/
 
CREATE VIEW expensive_books
AS
SELECT id, title, price
FROM books
WHERE price > 100
WITH CHECK OPTION;
/
 
INSERT INTO books 
VALUES (1, '1984', 35.90);
 
INSERT INTO books 
VALUES (
  2, 
  'The Answer to Life, the Universe, and Everything',
  999.90
);

Example 2:

CREATE VIEW Emp_view
(id PRIMARY KEY DISABLE NOVALIDATE, firstname)
AS SELECT employee_id, first_name
FROM employees
WHERE department_id = 10;

SQL View Insert

Data is inserted into a view in the same manner that data is inserted into a table. To insert a row into a View, use the SQL INSERT INTO statement.

If a view fails to match any of the criteria for updating, it cannot be used for inserting. It must also meet the following conditions:

  • The view includes all base table columns with no default values.
  • There are no view column names that are duplicated.
  • All of the view columns are simple columns that haven't been generated in any way.

Syntax:

INSERT INTO view_name(column1, column2 , column3,..) 
VALUES(value1, value2, value3..);

view_name: Name of the View

Example 1: The following are examples of derived columns

column_name + 25
LOWER(column_name)
(subquery)
9.5
column1 / column2

Because view_check2 only tests the insert against view check2, and the WHERE clause evaluates to true (150 is >10), this insert passes.

INSERT INTO view_check2 VALUES (150);

This insert fails, as view_check3 checks the insert against both view_check3 and the underlying views. The WHERE clause for view_check1 evaluates as false (150 is >10, but 150 is not <100), so the insert fails.

INSERT INTO view_check3 VALUES (150);

Result:

ERROR 1369 (HY000): CHECK OPTION failed 'test.view_check3'

Example 2: to insert data into the emp_details view:

INSERT INTO emp_details (emp_id, last_name)
VALUES (11, ‘Grover’);

This will insert another value into the employee table, and will show up in the emp_details view.

SELECT emp_id, last_name
FROM emp_details;

Results:

emp_id	last_name
1   	Jones
2   	Smith
3   	King
4   	Johnson
5   	Archer
6   	McDonald
7	Ferrier
8	Reacher
9	Clarkson
10	Simpson
11	Grover

Example 3: In the example below, we'll add a new row to the View DetailsView that we made before in the "building views from a single table" section.

INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");

Example 4:

create View V as (select id, value from A) UNION ALL (select id, value from B)

And now you can successfuly insert directly into the view (no trigger required):

insert into v (id, value) select 1,'B' 

SQL View in Where

To save records in the view based on specified circumstances, use the WHERE clause in conjunction with the VIEW command.

The criteria for row selection is defined by the word "WHERE."

Syntax:

The Construct VIEW statement is used to create a PostgreSQL view. This statement's syntax is as follows:

CREATE [OR REPLACE] VIEW view-name AS
  SELECT column(s)
  FROM table(s)
  [WHERE condition(s)];

The WHERE condition(s) are optional, and every record added to the view must satisfy them.

Example 1:

Sample table: agents

The following SQL query may be used to construct a view 'agentview' as the table 'agents' with the requirement 'working area' must be 'Bangalore':

CREATE VIEW agentview
AS SELECT * 
FROM agents
WHERE working_area=’Bangalore’;

Example 2: create a view from the above table:

CREATE VIEW Price_View AS
  SELECT id, price
  FROM Price
  WHERE price > 200;

Example 3: Create a view called "CourseView" from the table "ScalerCourses" (i.e. Table 1) to query certain specific course details for students with a budget of less than Rs 2000 to display on the website.

CREATE VIEW CourseView AS
SELECT Name, Duration
FROM ScalerCourses
WHERE Cost < 2000;

SQL View Multiple Tables

To join data from various tables, a view can be constructed using a SELECT command. SQL Server will throw an error if you try to put data into a view that refers to numerous tabes. Data normalisation into numerous tables is a typical approach. Then, with the help of a view, de-normalize them into a single output.

Example 1: Let's look at an example of this implementation. And to do so, we'll use the query below to create a view.

USE [sqlserverguides]
GO

CREATE VIEW [dbo].[USCityView]
AS
SELECT City, Country FROM dbo.City_1
WHERE Country = 'United States'
UNION
SELECT City, Country FROM dbo.City_2
WHERE Country = 'United States';
GO

We've generated a view called USCityView in the query above. We also use two SELECT queries in the definition to get the city and country columns from their respective tables.

Example 2: We'll make a MarksView View out of two tables, StudentDetails and StudentMarks, in this example. We may simply add numerous tables in the SELECT statement to generate a View from multiple tables.

CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

Example 3:

Create View dbo.vwGetCustomerOrders
AS
 SELECT C.FirstName,O.OrderId
 FROM dbo.Customers C 
   INNER JOIN dbo.Orders O
    ON C.CustomerId = O.CustomerId
GO

Select * from dbo.vwGetCustomerOrders

SQL View Orderby

Server SQL Unless TOP, OFFSET, or FOR XML is also given, the ORDER BY clause is incorrect in views, inline functions, derived tables, subqueries, and common table expressions. When a database developer attempts to utilize the Order By clause in the definition of a SQL view, an error occurs.

Rows available through a view do not appear with any default sorting, just like rows in a base table do not. A view is a relational table, and a table is defined as a collection of rows in the relational model. Because sets aren't ordered by definition, neither are the rows in a view. As a result, an ORDER BY clause in the view definition has no effect. In a CREATE VIEW statement, an ORDER BY clause in a subselect is not allowed, just as it is not allowed in a CREATE TABLE statement. Sorted data, on the other hand, can be accessed from a view using the same query language as any other table. However, some DBMS allow you to create a view using an ORDER BY clause in a subquery, which changes how data is shown.

A VIEW in SQL Server is similar to a virtual table that stores data from one or more tables. A view is a collection of SQL queries that retrieve data from a database.

The ORDER BY clause in SQL Server, on the other hand, allows you to sort the resultset data in ascending or descending order. It also enables you to sort the resultset by the column list you provide and limit the number of rows returned to a defined range.

The ORDER BY clause is not supported in SQL Server views, as previously stated. Furthermore, even if you try to use it, SQL Server will give you an error.

Example 1: Lets say you try to create a View using Order By Clause as show in the example below

CREATE VIEW SCHEMA_NAME/VIEW_NAME as (                              
  SELECT  PRODUCTS.COMPANY, PRODUCTS.ITEMNO, PRODUCTS.DESC1, 
   PRODUCTS.DESC2, PRODUCTS.PRICE, PRODUCTS.WEIGHT,       
   PRODUCTS.CATEGORY, CTGTABLE.CATNAME,                   
   PRODUCTS.MFG, MFGTABLE.MFGNAME                         
  FROM PRODUCTS left outer join CTGTABLE on                 
    PRODUCTS.COMPANY  = CTGTABLE.COMPANY  and             
    PRODUCTS.CATEGORY = CTGTABLE.CATEGORY                  
  left outer join MFGTABLE on                               
    PRODUCTS.COMPANY  = MFGTABLE.COMPANY  and             
    PRODUCTS.MFG      = MFGTABLE.MFG                       
  ORDER by PRODUCTS.COMPANY, PRODUCTS.ITEMNO                 
)

The following error message will appear.

The keyword ORDER was unexpected in this context. At the keyword ORDER, a syntactic issue was discovered. UNION EXCEPT is a partial list of valid tokens. The statement is assumed to be correct until the unexpected keyword. Although the issue may occur earlier in the statement, the syntax appears to be correct up to this point.

Example 2: Let's take a look at the scenario using a SQL Server example. For this, we'll develop a view that defines the ORDER BY clause.

USE [sqlserverguides]
GO

CREATE VIEW [dbo].[USA_CustomerView]
AS
SELECT customer_name, city, country
FROM Customers
WHERE country = 'United States'
ORDER BY customer_name
GO

Example 3: For Transact-SQL programmers and SQL Server database administrators, this SQL article demonstrates how to create SQL views with the Order By clause utilizing TOP 100 Percent or Offset 0 Rows.

create view Department_View
as
select Name from [HumanResources].[Department] order by Name

SQL Engine will display the following error message

Msg 1033, Level 15, State 1, Procedure Department_View, Line 4

Unless TOP, OFFSET, or FOR XML are also given, the ORDER BY clause is incorrect in views, inline functions, derived tables, subqueries, and common table expressions.

Example 4:

The concept is that a view should not be ordered by default. Like any other question. If you want the data from a view to be ordered, use the ORDER BY clause in the query. In reality, putting an ORDER BY in a view will result in an error:

Msg 1033, Level 15, State 1, Procedure MyView, Line 4 [Batch Start Line 2]

Unless TOP, OFFSET, or FOR XML are also given, the ORDER BY clause is incorrect in views, inline functions, derived tables, subqueries, and common table expressions.

CREATE VIEW [dbo].[MyView] AS
SELECT TOP 100 percent *
FROM [dbo].[table1]
ORDER BY id;
GO

And the view is built successfully. ORDER BY, on the other hand, is entirely ignored.


SQL View vs Table

Main Article :- Sql difference between VIEW and (TEMP) TABLE

In SQL Server or any other relational database, the words table and view are commonly used. Tables and views in SQL Server are comparable, but they are not the identical.

The main difference is that a table is a collection of rows and columns. And it's primarily used to store and retrieve data as needed by the user.

The view, on the other hand, is a virtual table that is created from the result set of a SQL statement and is lost when the current session ends.

Table View
A table is a database object that contains data for applications and analyses. A view is a database object that functions as a table and can connect to other tables.
Tables are physical entities in SQL Server that are stored in a database and used to organise data into rows and columns and display it in a structured way. It allows humans to grasp the information that has been saved. Views are viewed as a logical/virtual table that can be used to see or manipulate table elements. It's a database object with the same rows and columns as actual tables.
A table's primary role is to maintain information in a row-column structure. A view's principal purpose is to extract data and hide complexity.
Tables provide quick results because they are physical objects. Because the view renders the information from the table every time we query it, it produces a sluggish result.
A table allows you to execute actions such as adding, updating, and deleting data. Any data in a view cannot be added, updated, or deleted. We must update the data in the source tables if we wish to make any modifications to a view.
The table is a self-contained data object. Unless it's a relational table, that is. The table determines the number of views. As a result, we can't design a view without tables.
DML procedures DML actions on tables are possible in SQL Server. On view, we additionally execute some DML activities. However, the modifications are finally made to the underlying table.
Because the table is a physical item in the RDBMS memory, you can only construct or drop it; you can't replace it directly. Because the view is only an alias for the query that is running behind, you can easily recreate it with the replace choice.
It takes up space on the systems. It takes up no space on the systems.

SQL View with Union

In a SQL Server VIEW, using the UNION operator is straightforward. In SQL Server, a basic view typically consists of a single select statement. However, we can combine the results of many SELECT operations into a single view using the UNION operator.

Because there is no single way to map a change to just one row in one of the underlying tables, VIEWs based on a UNION or UNION ALL operation are read-only. Duplicate rows will be removed from the results using the UNION operator. The UNION and UNION ALL procedures both hide the table from which the rows came. Because the columns in a UNION [ALL] have no names of their own, such VIEWs must utilise a. A UNION of two disjoint tables, neither of which contains duplicate rows, should theoretically be updatable.

Example 1: Let's look at an example to better understand the implementation. We'll utilise the identical tables that we used in the last section for this example.

USE [sqlserverguides]
GO

CREATE VIEW US_CityView
AS
SELECT City, Country FROM dbo.Customers_1
WHERE Country = 'United States'
UNION
SELECT City, Country FROM dbo.Customers_2
WHERE Country = 'United States';
GO

In the preceding example, we created a view called US CityView. We also use two SELECT queries in the definition to get the city and country columns from their respective tables.

Furthermore, each SELECT query includes a WHERE clause that fetches data where the country is the United States.

As a result, the view will return the unique city names from both tables beneath United States.

Example 2:

CREATE VIEW DepTally2 (emp_nbr, dependent_cnt)
AS (SELECT emp_nbr, COUNT(*)
  FROM Dependents
  GROUP BY emp_nbr)
UNION
  (SELECT emp_nbr, 0
  FROM Personnel AS P2
  WHERE NOT EXISTS 
  (SELECT *
  FROM Dependents AS D2
  WHERE D2.emp_nbr = P2.emp_nbr));

Example 3:

CREATE VIEW myView AS
 SELECT * FROM employee where id = 1
 UNION SELECT * FROM employee where id = 2
 UNION SELECT * FROM employee where id = 3;

 --Fetch the record
select * from myView;

Output:

+------+------------+-----------+------------+------------+---------+-----------+-------------+
| id   | first_name | last_name | start_date | end_date   | salary  | city      | description |
+------+------------+-----------+------------+------------+---------+-----------+-------------+
|    1 | Jason      | Martin    | 1996-07-25 | 2006-07-25 | 1234.56 | Toronto   | Programmer  |
|    2 | Alison     | Mathews   | 1976-03-21 | 1986-02-21 | 6661.78 | Vancouver | Tester      |
|    3 | James      | Smith     | 1978-12-12 | 1990-03-15 | 6544.78 | Vancouver | Tester      |
+------+------------+-----------+------------+------------+---------+-----------+-------------+

Example 4:

CREATE VIEW v AS
    SELECT maker, model, price FROM product NATURAL JOIN laptop
    UNION
    SELECT maker, model, price FROM product NATURAL JOIN pc
    UNION
    SELECT maker, model, price FROM product NATURAL JOIN printer

Because UNION DISTINCT will almost probably be significantly slower, especially if the tables are large, you may wish to try UNION ALL instead of UNION (aka UNION DISTINCT). On the other hand, if you desire to avoid duplication, UNION is the correct option.