views In SQL

 Views:  A view in SQL is essentially a saved SQL query that acts like a virtual table. 

-Unlike physical tables, a view doesn’t store data itself; rather, it retrieves data from one or more tables every time you query it.


How to create a view

CREATE VIEW active_customer AS

SELECT customer_id, name, email from customers

where status = "active"


Views are read-only by default

Deleting a view does not affect the base data.


Why to use it: 

1. Simplify complex queries: 

CREATE VIEW order_summary AS

SELECT c.name, o.order_date, SUM(oi.quantity * oi.unit_price) AS total

FROM customers c

JOIN orders o ON c.customer_id = o.customer_id

JOIN order_items oi ON o.order_id = oi.order_id

GROUP BY c.name, o.order_date;

                Now to use :

SELECT * FROM order_summary;

2. Security: for example, an HR table consists of salary and other things, but needs to show few only 

CREATE VIEW employee_public AS

SELECT employee_id, name, department

FROM employees;

3. Data Abstraction:

CREATE VIEW daily_product_sales AS

SELECT p.product_name, s.sale_date, SUM(s.quantity) AS total_sold

FROM products p

JOIN sales s ON p.product_id = s.product_id

GROUP BY p.product_name, s.sale_date;

NOW :Your sales team needs daily product sales totals, but the calculations require joining and grouping. so we can use below query

SELECT * FROM daily_product_sales WHERE sale_date = '2026-01-12';

4. Reuse: Finance pulls monthly revenue; marketing pulls top products. Both teams can reuse the same monthly_sales view.

CREATE VIEW monthly_sales AS

SELECT DATE_TRUNC('month', sale_date) AS month, product_id, SUM(amount) AS total_revenue

FROM sales

GROUP BY month, product_id;


Used by Finance:

SELECT month, SUM(total_revenue) AS revenue

FROM monthly_sales

GROUP BY month;


Used by Marketing:

SELECT product_id, SUM(total_revenue) AS product_revenue

FROM monthly_sales

GROUP BY product_id

ORDER BY product_revenue DESC

LIMIT 10;







Comments

Popular posts from this blog

Introduction to DBMS

ACID Properties

Understanding First Normal Form (1NF) in Database Design