Skip to content

SQL Views

A view is a saved query with a name. You query it as if it were a table, but it holds no data of its own: each time you use it, the database runs the saved query against the tables underneath, so a view is always up to date.

CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;

The examples use the tables from the example database.

The accounts team asks for unpaid invoices every day. A view saves writing the query each time:

CREATE VIEW UnpaidInvoices AS
SELECT InvoiceID, Supplier, Amount
FROM Invoices
WHERE PaidDate IS NULL;

Query it like a table:

SELECT * FROM UnpaidInvoices;
InvoiceID Supplier Amount
1003 Ashby Camera Hire 41,250.00
1004 Kestrel Catering 2,940.00

When invoice 1003 is paid, the view changes with no further work, since it is read afresh each time:

InvoiceID Supplier Amount
1004 Kestrel Catering 2,940.00

That is the difference from a copy made with SELECT INTO, which stays as it was when it was made.

A view can wrap a join, a grouping, or anything else, and present the result as one simple table. Each production’s spending:

CREATE VIEW ProductionSpend AS
SELECT Productions.Title,
COUNT(Invoices.InvoiceID) AS Invoices,
COALESCE(SUM(Invoices.Amount), 0) AS Spent
FROM Productions
LEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.ProductionID, Productions.Title;

Anyone can now ask a simple question of it, without knowing about the join:

SELECT * FROM ProductionSpend
WHERE Spent > 0
ORDER BY Spent DESC;
Title Invoices Spent
The Lantern Keepers 2 65,850.00
Quarry Lane 1 3,180.00
Six Bells 1 2,940.00

Views also help with permissions: a person can be allowed to read a view without being allowed to read the tables behind it, so they see only the columns and rows the view exposes.

To change a view’s query, replace it:

Database Statement
PostgreSQL, MySQL, Oracle CREATE OR REPLACE VIEW UnpaidInvoices AS …
SQL Server CREATE OR ALTER VIEW UnpaidInvoices AS …
SQLite DROP VIEW UnpaidInvoices;, then CREATE VIEW again

To remove it, run DROP VIEW UnpaidInvoices;. Dropping a view deletes only the saved query; the tables and their data are untouched.