That would be a lot of typing, wouldn't it? What if we needed such a query over and over? Would we have to write it from scratch every time?
This is where views come in handy.
A view is an SQL statement which we "save" under a specific name and which we can later treat as a table in other SQL queries. Views are often called virtual tables because we can query them just like a regular table.
Now, look again at the doctor
table from the previous exercise:
CREATE TABLE doctor (
id integer PRIMARY KEY,
full_name varchar(128),
type varchar(32),
city varchar(128),
rating decimal(2, 1),
price_per_visit decimal(5, 2)
);
And here you can see an example of a very simple view:
CREATE VIEW cardiologist AS
SELECT *
FROM doctor
WHERE type = 'cardiologist';
The code above starts with CREATE VIEW
. This is followed by the view name, i.e., cardiologist
. Then we have the AS
keyword. After that, we simply use a regular SQL query to select doctors who specialize in cardiology.