A view in SQL is a virtual table that is based on the result of a SELECT statement. Views provide a way to encapsulate complex queries and reuse them throughout an application, without having to repeat the underlying SQL code.
Here’s an example of how to create a view that returns information about cars with a particular manufacturer:
1 2 3 4 5 |
CREATE VIEW cars_by_manufacturer AS SELECT manufacturer, model, year, price FROM cars WHERE manufacturer = 'Toyota'; |
In this example, we’re creating a view named cars_by_manufacturer
that returns information about cars made by the manufacturer ‘Toyota’. The view is based on the SELECT statement that returns the columns manufacturer
, model
, year
, and price
from the cars
table.
To query the view, you can use the view name in a SELECT statement, just like you would with a table:
1 2 |
SELECT * FROM cars_by_manufacturer; |
This will return the information about all cars made by the manufacturer ‘Toyota’ that are stored in the view.