SELECT
customer_type,
COUNT(*) AS customer_count
FROM customer_classification
GROUP BY customer_type;
This helps keep business definitions consistent.
1️⃣4️⃣ Views for BI and Reporting
Views are very common in reporting environments.
Imagine Power BI needs:
Customer, Order, Product, Region, Revenue, Profit, Order Date
Instead of exposing many raw tables, a database team may create a reporting View:
CREATE VIEW sales_reporting AS
SELECT
o.order_id,
o.order_date,
c.customer_id,
c.customer_name,
p.product_name,
o.region,
o.sales_amount,
o.profit
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
JOIN products p
ON o.product_id = p.product_id;
The BI tool can then consume:
SELECT *
FROM sales_reporting;
This can simplify the data model and centralize transformation logic.
1️⃣5️⃣ Views and Query Performance
A very important point:
A normal View does not automatically make a query faster.
For example:
CREATE VIEW customer_orders AS
SELECT ...
FROM customers
JOIN orders ...;
Then:
SELECT *
FROM customer_orders;
The database generally still needs to execute the underlying query.
A View is primarily an abstraction and reuse mechanism.
Performance depends on factors such as:
• Indexes
• Query structure
• Join conditions
• Filtering
• Data volume
• Database optimizer
• Statistics
• Execution plan
Some database systems also support materialized views, which are different.
1️⃣6️⃣ Materialized View
A Materialized View stores the result of a query physically.
Conceptually:
Normal View → Stores query definition
Materialized View → Stores query result
Example concept:
CREATE MATERIALIZED VIEW monthly_sales AS
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(order_amount) AS total_sales
FROM orders
GROUP BY DATE_TRUNC('month', order_date);
The exact syntax and refresh behavior depend heavily on the database.
Materialized Views can be useful when:
• Queries are expensive
• Data is large
• Aggregations are repeatedly requested
• Near-real-time data isn't required
But the stored result needs to be refreshed according to the database's configuration.
1️⃣7️⃣ View with CTE
You can also create a View using a CTE.
CREATE VIEW customer_summary AS
WITH customer_orders AS (
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(order_amount) AS total_sales
FROM orders
GROUP BY customer_id
)
SELECT
c.customer_id,
c.customer_name,
co.order_count,
co.total_sales
FROM customers c
JOIN customer_orders co
ON c.customer_id = co.customer_id;
Now the complex logic is reusable:
SELECT *
FROM customer_summary;