SQL CREATE VIEW: save a query and use it like a table

A view is a query with a name. You write it once, say revenue per customer across three tables, and from then on you just select from the view as if it were a table. The result always reflects the data as it is right now.

In short: CREATE VIEW name AS SELECT … saves a query under a name. SELECT * FROM name runs it. DROP VIEW name removes only the saved query, never the data behind it.

What you should know first: joining tables with JOIN and grouping with GROUP BY. For the first exercise, SELECT with WHERE is enough.

Try it now

In this lesson you create views. After your statement runs, the check deliberately changes some data and reads your view again. What you see is what the view returns at that point.

Task Sales asks every day which products can ship right away. Create the view in_stock for them: name, category and price of every product with stock above 0. It has to be a view, not a table: after your statement, the check changes one product's stock and reads your view again.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

How CREATE VIEW works

Take a finished SELECT query and put CREATE VIEW name AS in front of it. The database doesn't run the query at that moment and doesn't store a result. It stores the query itself. Only when someone selects from the view does the query run, and it runs fresh every time.

An example from the practice shop: an order's value lives in order_items and has to be summed every time you need it. The view order_totals does that for you:

CREATE VIEW order_totals AS
SELECT o.order_id, o.order_date, o.status,
       SUM(oi.quantity * oi.unit_price) AS total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.order_date, o.status;

Now you query order_totals like any table, with WHERE, ORDER BY and everything else you know. Which valid orders were over 1,000?

SELECT order_id, order_date, total
FROM order_totals
WHERE status <> 'cancelled' AND total > 1000
ORDER BY total DESC;
order_idorder_datetotal
10042026-02-031344
10092026-03-301284.4
10142026-06-021236
10082026-03-171067.45

The view's column names come from its SELECT, so every calculated column needs an alias. Without AS it would be called SUM(oi.quantity * oi.unit_price).

A view always shows current data

Change a line item and the view reflects it immediately. Raise the monitors in order 1009 from 2 to 5, and order_totals reports 2121.4 instead of 1284.4 for that order without you doing anything else. That's the difference from CREATE TABLE … AS SELECT, which makes a copy as of the moment you run it and goes stale with the first change.

Why views earn their keep

  • Write long queries once: two joins and a GROUP BY live in the view, and everyone else writes SELECT * FROM customer_revenue.
  • One definition for everybody: when "revenue excluding cancelled orders" sits in a view, sales and finance report the same number.
  • Show only what's needed: a view can leave out columns such as salary. Microsoft lists exactly this as a purpose of views in SQL Server: people read data through the view without being granted access to the tables behind it.

Another exercise: a view with a join and a sum

This time a real report goes into the view. Build the query first, check it with Run, and only then put CREATE VIEW in front.

Task Management wants revenue per customer on demand, without joining three tables every time. Create the view customer_revenue with the columns customer (the customer's name) and revenue (sum of quantity times unit_price). Cancelled orders don't count, and customers without revenue don't need to appear. Afterwards the check cancels one order and queries the view just like a table: SELECT customer, revenue FROM customer_revenue.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Changing a view: DROP VIEW

SQLite has no CREATE OR REPLACE VIEW. To change what a view returns, drop it with DROP VIEW name and create it again. That only touches the saved query; no rows are lost. DROP VIEW IF EXISTS name doesn't raise an error when the view isn't there.

Task The view open_orders already exists (shown above the editor), but customer service needs more from it now. Replace it with a new view of the same name: order_id, order_date, status and customer (the customer's name) of every order with status open or shipped. Afterwards the check changes one status and reads your view.

open_orders 3 rows, 2 columns
order_idorder_date
10162026-06-12
10172026-06-13
10182026-06-14
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

CREATE TABLE instead of CREATE VIEW

CREATE TABLE in_stock AS SELECT … makes a copy. As soon as the check changes a stock level, a row is missing from it and the exercise says "After your changes: The check shows 10 rows, expected: 11 rows". Use CREATE VIEW.

Forgetting AS before SELECT

CREATE VIEW in_stock SELECT … gives a syntax error near "SELECT". AS goes between the name and the query.

The view already exists

A second CREATE VIEW with the same name fails with a message that the name already exists. The suggested IF NOT EXISTS only helps if the old view should stay as it is. To replace it, put DROP VIEW first.

CREATE OR REPLACE or DROP TABLE

CREATE OR REPLACE VIEW gives a syntax error near "OR" in these exercises, because SQLite doesn't have that form. DROP TABLE on a view is refused by SQLite, and the exercise tells you to use DROP VIEW.

Views in MySQL, PostgreSQL, SQL Server and SQLite

DatabaseReplace a viewChange data through a view
MySQLCREATE OR REPLACE VIEWwhen each view row matches exactly one table row (no aggregates, DISTINCT or GROUP BY)
PostgreSQLCREATE OR REPLACE VIEW, only with the same columns in the same order; new columns go at the endautomatic for simple views (one table, no GROUP BY, DISTINCT or LIMIT)
SQL ServerCREATE OR ALTER VIEW (SQL Server 2016 SP1 and later)when the change touches columns of one table only
SQLite (these exercises)DROP VIEW, then create it againno, views are read-only

Materialized views: with CREATE MATERIALIZED VIEW, PostgreSQL stores the result much like a table. That makes it quick to query, but it's no longer live: it only catches up when you run REFRESH MATERIALIZED VIEW name. SQL Server's counterpart is the indexed view. You create the view WITH SCHEMABINDING and add a unique clustered index, after which its result is stored in the database. Unlike PostgreSQL, SQL Server keeps that stored result up to date on every INSERT, UPDATE and DELETE against the tables, which can slow those changes down.

ORDER BY inside a view: SQL Server only allows it together with TOP (or OFFSET), and even then the order isn't guaranteed when you query the view. MySQL ignores a view's ORDER BY when the query on the view has its own. Sort in the query that reads the view.

Sources: MySQL Reference Manual (CREATE VIEW Statement, Updatable and Insertable Views), PostgreSQL documentation (CREATE VIEW, CREATE MATERIALIZED VIEW), Microsoft Learn (CREATE VIEW, Create Indexed Views), sqlite.org (CREATE VIEW).

Frequently asked questions

Is a view slower than a table?

A regular view is just a name for a query, so it runs exactly as fast as that query. If the query behind it is heavy, so is every SELECT on the view.

Can a view use another view?

Yes. A view can read from tables and from other views, for example a monthly summary built on order_totals. Keep the chains short, or it gets hard to trace where a number comes from.

What happens to the view when I change the table?

New rows and changed values show up right away, because the view reads the table on every query. Changing the table's structure depends on the database. SQL Server, for instance, recommends running sp_refreshview on affected views afterwards, and won't let you change a table referenced by a view WITH SCHEMABINDING in a way that breaks the view.

How do I list the views in a database?

In SQLite they're in the sqlite_master table with type = 'view'. MySQL, PostgreSQL and SQL Server list them in information_schema.views. In the exercises they appear above the editor.

Learn this next: transactions

Moving stock between two warehouses takes two changes that only make sense together. BEGIN, COMMIT and ROLLBACK turn them into a single unit that happens completely or not at all.

Practice transactions

Write to us

Choose language

Select your preferred language