Views and Subqueries Views Cheat Sheet

 Views

Database: The database stores the sample data of an e-commerce aplication. Here, the database consists of

user
,
order_details
and
product
tables that store the information of products, orders placed, and the products on the platform.

Refer the tables in the code playground for a better understanding of the database.

View

A view can simply be considered as a name to a SQL Query

Create View

To create a view in the database, use the

CREATE VIEW
statement.

Example

Create

user_base_details
view with id, name, age, gender and pincode.

CREATE VIEW user_base_details AS
SELECT id, name, age, gender, pincode
FROM user;
SQL
Note

In general, views are read only.

We cannot perform write operations like updating, deleting & inserting rows in the base tables through views.

Try it Yourself!

Create

order_with_products
view with order_id, product_id, no_of_units, name, price_per_unit, rating, category, brand.

Querying Using View

We can use its name instead of writing the original query to get the data.

SELECT *
FROM user_base_details;
SQL
Output
idnameagegenderpincode
1Sai40Male400068
2Boult20Male30154
3Sri20Female700009
...............

We can use same operations which are used on tables like WHERE clause, Ordering results, etc.

If we try to retrive data which is not defined in the view it raises an

error
.

Example

SELECT name, address
FROM user_base_details
WHERE gender = "Male";
ORDER BY age ASC;
SQL
Output
Error: no such column:address
SQL

Try it Yourself!

From the

order_with_products
view created above, get the name and no_of_units ordered in order_id = 802.

Expected Output
nameno_of_units
Oneplus 8 Pro1
Gorilla Glass1

List All Available Views

In SQLite, to list all the available views, we use the folowing query.

SELECT
name
FROM
sqlite_master
WHERE
TYPE = 'view';
SQL
Output
name
order_with_products
user_base_details

Delete View

To remove a view from a database, use the

DROP VIEW
statement.

Syntax

DROP VIEW view_name;
SQL

Example

Delete

user_base_details
view from the database.

DROP VIEW user_base_details;
SQL

Advantages

  • Views are used to write complex queries that involves multiple joinsgroup by, etc., and can be used whenever needed.
  • Restrict access to the data such that a user can only see limited data instead of a complete table.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form