Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Your first view
2. Creating a view
How to use views
Summary

Instruction

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.

Exercise

Create a view named visit_details by joining the tables doctor, patient, and visit as we did in the previous exercise. To save you some typing, we have put the query in the template – you simply need to make it into a view.

Stuck? Here's a hint!

Your query should begin with:

CREATE VIEW visit_details AS