SQL Views โ Creating Reusable Virtual Tables
A SQL View is a saved SQL query that behaves like a virtual table.
Instead of writing the same complex query repeatedly, you can create a View once and query it like a table.
This is especially useful in:
โข Data analytics
โข Reporting
โข Business Intelligence
โข Power BI datasets
โข Data warehouses
โข Reusable business logic
โข Data security
1๏ธโฃ What Is a View?
Suppose you frequently need this query:
SELECT
customer_id,
customer_name,
country,
total_sales
FROM customers
WHERE country = 'India'
AND total_sales > 100000;
Instead of writing it every time, you can create a View:
CREATE VIEW high_value_indian_customers AS
SELECT
customer_id,
customer_name,
country,
total_sales
FROM customers
WHERE country = 'India'
AND total_sales > 100000;
Now you can simply write:
SELECT *
FROM high_value_indian_customers;
The View behaves like a table from the user's perspective.
2๏ธโฃ Why Do We Need Views?
Imagine your reporting query contains:
โข 4 JOINs
โข 3 CASE statements
โข Multiple filters
โข Several calculated columns
โข Aggregations
You don't want every analyst or report to rewrite that logic.
A View allows you to centralize the logic.
3๏ธโฃ Basic CREATE VIEW Syntax
The general syntax is:
CREATE VIEW view_name AS
SELECT
column1,
column2,
column3
FROM table_name
WHERE condition;
Example:
CREATE VIEW active_customers AS
SELECT
customer_id,
customer_name,
country
FROM customers
WHERE status = 'Active';
Query the View:
SELECT *
FROM active_customers;
4๏ธโฃ A View Can Contain JOINs
Views aren't limited to simple SELECT statements.
For example:
CREATE VIEW customer_orders AS
SELECT
c.customer_id,
c.customer_name,
o.order_id,
o.order_date,
o.order_amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id;
Now:
SELECT *
FROM customer_orders;
returns the result of that JOIN.
You don't need to repeatedly write the JOIN.
5๏ธโฃ Views with Aggregation
You can also create aggregated Views.
Suppose management regularly needs regional sales:
CREATE VIEW regional_sales AS
SELECT
region,
SUM(order_amount) AS total_sales,
COUNT(*) AS total_orders
FROM orders
GROUP BY region;
Now:
SELECT *
FROM regional_sales;
Example result:
region total_sales total_orders
North 450000 1250
South 620000 1580
West 510000 1390
East 380000 980
You can further analyze the View:
SELECT *
FROM regional_sales
WHERE total_sales > 500000;
6๏ธโฃ Views with CASE Statements
Views are useful for standardizing business logic.
For example:
CREATE VIEW customer_segments AS
SELECT
customer_id,
customer_name,
total_sales,
CASE
WHEN total_sales >= 100000 THEN 'High Value'
WHEN total_sales >= 50000 THEN 'Medium Value'
ELSE 'Low Value'
END AS customer_segment
FROM customers;
Now every report can use the same segmentation logic:
SELECT
customer_segment,
COUNT(*) AS customers
FROM customer_segments
GROUP BY customer_segment;