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 ASSELECT column1, column2FROM table_nameWHERE condition;The examples use the tables from the example database.
Creating and using a view
Section titled “Creating and using a view”The accounts team asks for unpaid invoices every day. A view saves writing the query each time:
CREATE VIEW UnpaidInvoices ASSELECT InvoiceID, Supplier, AmountFROM InvoicesWHERE 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.
Hiding a complicated query
Section titled “Hiding a complicated query”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 ASSELECT Productions.Title, COUNT(Invoices.InvoiceID) AS Invoices, COALESCE(SUM(Invoices.Amount), 0) AS SpentFROM ProductionsLEFT JOIN Invoices ON Invoices.ProductionID = Productions.ProductionIDGROUP BY Productions.ProductionID, Productions.Title;Anyone can now ask a simple question of it, without knowing about the join:
SELECT * FROM ProductionSpendWHERE Spent > 0ORDER 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.
Changing and removing a view
Section titled “Changing and removing a view”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.