Back to all posts

SQL Views Explained with Practical Examples

For SQL users who write SELECT queries and have not created a view yet.

On this page

A view is a SELECT query saved in the database under a name, and you query a view like a table. For example, several reports can read the salary total of each department from one view, instead of each repeating the query.

A view can also let a database user read the employees' names and not their salaries.

Every view is created with the same statement:

CREATE VIEW view_name AS
SELECT columns
FROM table_name
WHERE condition;
  • view_name names the view. Later queries read it with SELECT ... FROM view_name.
  • AS is followed by the query that the view stores. The query can join tables and use GROUP BY.
  • SELECT columns gives the view its columns and their names.
  • WHERE condition limits the rows that the view shows. The WHERE is optional.

Create one table of five employees:

CREATE TABLE employees (
  id     int PRIMARY KEY,
  name   text,
  dept   text,
  salary int
);

INSERT INTO employees VALUES
  (1, 'Anna',  'Sales', 4000),
  (2, 'Ben',   'Sales', 3500),
  (3, 'Chloe', 'IT',    5000),
  (4, 'David', 'IT',    4500),
  (5, 'Emma',  'HR',    3800);

Run the statements in order. Later UPDATE and ALTER TABLE statements change the employees table.

Every result below comes from PostgreSQL 18.6. SQLite 3.50 returns the same rows for the first two views. Each later SQLite difference is named under its result.

CREATE VIEW

CREATE VIEW stores a query under a name. For example, you can store a list of the employees without their salaries.

CREATE VIEW employee_directory AS
SELECT id, name, dept
FROM employees;

SELECT * FROM employee_directory;
idnamedept
1AnnaSales
2BenSales
3ChloeIT
4DavidIT
5EmmaHR

The view returns all five employees. It has no salary column, because its SELECT does not list salary.

The view holds no copy of these rows. The PostgreSQL documentation says "the query is run every time the view is referenced in a query". A change to the employees table shows up the next time you read the view.

The employees table stores five rows with four columns; the view employee_directory stores only its query, SELECT id, name, dept FROM employees; reading the view runs that query and returns the five rows without the salary column

GROUP BY in a view

A view can store a SELECT with GROUP BY. For example, a view can count the employees of each department and add up their salaries.

CREATE VIEW dept_payroll AS
SELECT dept, count(*) AS headcount, sum(salary) AS total_salary
FROM employees
GROUP BY dept;

SELECT * FROM dept_payroll ORDER BY dept;
deptheadcounttotal_salary
HR13800
IT29500
Sales27500

Each department became one row. Sales and IT have two employees, and HR has Emma alone. The aliases headcount and total_salary became the names of the view's columns.

Give every calculated column a name with AS. Without a name, PostgreSQL calls the columns count and sum, and SQLite calls them count(*) and sum(salary).

CREATE OR REPLACE VIEW

CREATE OR REPLACE VIEW changes the query that an existing view stores. For example, you can add the highest salary of each department to dept_payroll.

CREATE OR REPLACE VIEW dept_payroll AS
SELECT dept, count(*) AS headcount, sum(salary) AS total_salary,
       max(salary) AS top_salary
FROM employees
GROUP BY dept;

SELECT * FROM dept_payroll ORDER BY dept;
deptheadcounttotal_salarytop_salary
HR138003800
IT295005000
Sales275004000

The first three columns kept their names and their order, and top_salary came last. IT's top salary is Chloe's 5000.

PostgreSQL accepts a new column only after the existing ones. If the new query leaves out an old column, PostgreSQL stops with "cannot drop columns from view". In that case, run DROP VIEW dept_payroll and create the view again.

On SQLite, always drop the view and create it again. SQLite has no CREATE OR REPLACE VIEW.

Updatable views

An UPDATE, INSERT or DELETE on a simple view changes the table that the view reads. For example, you can move Emma to Sales through employee_directory. PostgreSQL calls such a view automatically updatable.

UPDATE employee_directory SET dept = 'Sales' WHERE name = 'Emma';

SELECT * FROM employees ORDER BY id;
idnamedeptsalary
1AnnaSales4000
2BenSales3500
3ChloeIT5000
4DavidIT4500
5EmmaSales3800

Emma's row in employees now says Sales, and her salary of 3800 is unchanged. employee_directory reads one table and has no GROUP BY, DISTINCT or aggregate function such as sum. The view meets PostgreSQL's list of conditions, so each row of the view is one row of the table.

dept_payroll fails these conditions. An UPDATE on dept_payroll stops with "cannot update view "dept_payroll"", and PostgreSQL adds the detail "Views containing GROUP BY are not automatically updatable."

SQLite views are read-only. On SQLite, the same UPDATE of Emma fails with "cannot modify employee_directory because it is a view".

WITH CHECK OPTION

WITH CHECK OPTION makes a view reject an INSERT or UPDATE whose row does not match the view's WHERE. For example, a view of the Sales team can refuse to move an employee to HR.

CREATE VIEW sales_team AS
SELECT id, name, dept
FROM employees
WHERE dept = 'Sales'
WITH CHECK OPTION;

UPDATE sales_team SET dept = 'HR' WHERE name = 'Emma';

PostgreSQL refuses the update:

ERROR: new row violates check option for view "sales_team"
DETAIL: Failing row contains (5, Emma, HR, 3800).

sales_team shows only the Sales rows. After the update, Emma's row would say HR, so PostgreSQL rejected the update and changed nothing. An INSERT of an IT employee through sales_team fails with the same error.

Without WITH CHECK OPTION, the same update succeeds, and Emma no longer appears in sales_team. SQLite has no WITH CHECK OPTION and rejects it as a syntax error.

GRANT SELECT on a view

GRANT SELECT on a view lets a user read the view without any permission on its table. For example, an intern can read the employee list and not the salaries.

CREATE ROLE intern;
GRANT SELECT ON employee_directory TO intern;

SET ROLE intern;
SELECT * FROM employee_directory WHERE dept = 'IT';
RESET ROLE;

CREATE ROLE creates the role intern, and SET ROLE runs the following queries as that role until RESET ROLE. The WHERE filters the view like a table:

idnamedept
3ChloeIT
4DavidIT

The same role gets "permission denied for table employees" from SELECT * FROM employees. The view can still read employees, because PostgreSQL checks the permissions of the view's owner, the user who created it, not the intern's. SQLite has no users, so it has no GRANT.

CREATE MATERIALIZED VIEW

A materialized view stores the rows of its query, like a table. For example, you can store each department's salary total.

CREATE MATERIALIZED VIEW payroll_snapshot AS
SELECT dept, sum(salary) AS total_salary
FROM employees
GROUP BY dept;

UPDATE employees SET salary = 4400 WHERE name = 'Anna';

SELECT * FROM payroll_snapshot ORDER BY dept;
depttotal_salary
IT9500
Sales11300

Sales totals 11300: Anna's old 4000, Ben's 3500 and Emma's 3800. Reading payroll_snapshot does not run its query, so Anna's raise is not there. HR has no row, because the earlier UPDATE moved Emma to Sales.

REFRESH MATERIALIZED VIEW runs the query again and replaces the stored rows:

REFRESH MATERIALIZED VIEW payroll_snapshot;

SELECT * FROM payroll_snapshot ORDER BY dept;
depttotal_salary
IT9500
Sales11700

Sales now counts Anna's 4400. If a query is slow and rows from the last refresh are good enough, use a materialized view. SQLite has no materialized views.

What goes wrong

SELECT * keeps the columns of the day it ran

CREATE VIEW all_employees AS
SELECT * FROM employees;

ALTER TABLE employees ADD COLUMN email text;

SELECT * FROM all_employees ORDER BY id;
idnamedeptsalary
1AnnaSales4400
2BenSales3500
3ChloeIT5000
4DavidIT4500
5EmmaSales3800

When the view was created, PostgreSQL replaced * with the four columns that employees had then, so email is missing. On SQLite, the same view returns email.

List the columns by name in the view's SELECT. The view then returns the same columns on both engines.

A view blocks DROP COLUMN

ALTER TABLE employees DROP COLUMN dept;

PostgreSQL refuses, and lists every view that depends on the column:

ERROR: cannot drop column dept of table employees because other objects depend on it
DETAIL: view employee_directory depends on column dept of table employees
view dept_payroll depends on column dept of table employees
view sales_team depends on column dept of table employees
materialized view payroll_snapshot depends on column dept of table employees
view all_employees depends on column dept of table employees
HINT: Use DROP ... CASCADE to drop the dependent objects too.

Change or drop each view first, then drop the column. DROP COLUMN with CASCADE would drop all five views together with the column. SQLite refuses too, with "error in view employee_directory after drop column: no such column: dept".

A view is no faster than its query

EXPLAIN (COSTS OFF)
SELECT * FROM dept_payroll;
HashAggregate
  Group Key: employees.dept
  ->  Seq Scan on employees

EXPLAIN shows the steps that PostgreSQL runs. Seq Scan reads all of employees, and HashAggregate groups the rows by dept.

A view saves you from writing the query again, not from running it. If the query is too slow, use a materialized view.

Views in DbSchema

The SQL Editor in DbSchema runs CREATE VIEW and shows a view's rows in a grid under the editor. Press Editor in the toolbar, choose SQL Editor, paste the statement, and press Run.

The query SELECT * FROM employee_directory in the DbSchema SQL Editor, with the five employees and their id, name and dept in the result grid

After CREATE VIEW, DbSchema lists the view in the tree on the left, beside the tables. To edit the view, right-click it, and DbSchema opens the Edit View dialog with the view's name and definition:

The DbSchema Edit View dialog of the view monthly_totals, whose definition starts with CREATE OR REPLACE VIEW and a placeholder for the view's name

DbSchema writes a placeholder for the view's name in the definition, and fills in the name when it creates the view. To rename the view, change its Name and keep the definition as it is. DbSchema then runs CREATE OR REPLACE VIEW under the new name in the connected database, and drops the old view.

Download DbSchema at https://dbschema.com/download.html and connect it to PostgreSQL or SQLite. Paste the CREATE TABLE and INSERT statements into the SQL Editor, then create each view and query it. These statements need only a connection and the SQL Editor, and both are part of the free Community Edition.

DbSchema ER diagram designer DbSchema ER diagram designer

Design and visualize
your database schema

Edit referenced records
in related tables

Query your data
visually too

Reuse the SQL
generated

Free Download