Simplifying queries with CREATE VIEW #
If you find yourself writing the same complex query over and over, a view lets you save it under a name and query it like a regular table. A view does not store any data of its own — every time you query it, the database runs the underlying query again behind the scenes.
CREATE VIEW view_name AS
SELECT
column_1,
column_2
FROM
table_name
WHERE
condition;
view_name: The name you will use to query this view, just like a table name.AS SELECT ...: The query the view represents.
Once created, you can query the view exactly like a table:
SELECT
*
FROM
view_name;
Exercise #
Write a command that creates a view called shipped_orders, containing every column of every order from the orders table whose status is Shipped.
Tests #
- A view named
shipped_ordersexists. - Querying
shipped_ordersreturns exactly the orders whosestatusisShipped, and no others.
Solution
CREATE VIEW shipped_orders AS
SELECT
*
FROM
orders
WHERE
status = 'Shipped';
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity