Views are the results you get from the SQL queries that you can reuse for other queries. An exemplary and practical application of views is retrieving data from a view that is modified by multiple functions, has created arbitrary columns, and has omitted other columns.
Views are primarily made of results from the SQL queries. Query results are added to a view to prepare it for occasional reuse.
CREATE VIEW view_name AS
sql_query;
Where view_name is the name of the particular view and sql_query is the SQL query.
Here is an example of creating a view and using it:
CREATE VIEW young_users AS
SELECT * FROM users
WHERE age < 18; // create
SELECT * FROM young_users; // selecting everything from the view
Note: If you are using functions on columns, you must provide an alias for the expression containing those. For example:
CREATE VIEW young_users AS
SELECT name, LENGTH(name) AS length FROM users;
It would be necessary to replace a view whenever the particular view will be used for other situations.
CREATE OR REPLACE VIEW view_name AS
sql_query;
This statement will alter the view regardless of the previous structure defined in the view.
If the view previously contains two columns, it can be replaced with a view with one column. The statement below is additionally served as an example of replacing a view:
CREATE OR REPLACE VIEW length_average AS
SELECT AVG(LENGTH(name)) AS average
FROM users;
Here, the results of a query are stored in a view, also replacing the previous results with new ones. The query only returns one row and one column. It determines the average of lengths of all names and stores it in a view.
If there is no other need to use the view, deleting or dropping it will help. The syntax is similar to dropping a table:
DROP VIEW view_name;