0
0
PostgreSQLquery~5 mins

Why views matter in PostgreSQL

Choose your learning style9 modes available
Introduction

Views help you save time by reusing complex queries easily. They make your data look simple and organized.

You want to show only certain columns from a big table to users.
You need to reuse a complicated query many times without rewriting it.
You want to hide the complexity of your database from others.
You want to create a simple report from multiple tables.
You want to control what data users can see without giving full access.
Syntax
PostgreSQL
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
A view acts like a saved query you can use like a table.
You can select from a view just like a normal table.
Examples
This view shows only active customers with their id, name, and email.
PostgreSQL
CREATE VIEW active_customers AS
SELECT id, name, email
FROM customers
WHERE active = true;
This view summarizes total sales per product.
PostgreSQL
CREATE VIEW sales_summary AS
SELECT product_id, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_id;
Sample Program

This example creates a table of employees, inserts some data, then creates a view showing only IT department employees with their names and salaries. Finally, it selects all data from the view.

PostgreSQL
CREATE TABLE employees (
  id SERIAL PRIMARY KEY,
  name TEXT,
  department TEXT,
  salary INT
);

INSERT INTO employees (name, department, salary) VALUES
('Alice', 'HR', 50000),
('Bob', 'IT', 60000),
('Carol', 'IT', 65000),
('Dave', 'HR', 52000);

CREATE VIEW it_employees AS
SELECT name, salary
FROM employees
WHERE department = 'IT';

SELECT * FROM it_employees;
OutputSuccess
Important Notes

Views do not store data themselves; they run the saved query when you use them.

Updating data through views can be limited depending on the view's complexity.

Summary

Views simplify complex queries by saving them as reusable objects.

They help control what data users see without changing the original tables.

Using views makes your database easier to manage and understand.