Views and Subqueries
Views and Subqueries
Views and Subqueries
Views
• A view is nothing more than a SQL statement
that is stored in the database with an
associated name. A view is actually a
composition of a table in the form of a
predefined SQL query.
• A view can contain all rows of a table or select
rows from a table. A view can be created from
one or many tables which depends on the
written SQL query to create a view.
Creating Views
• Database views are created using the CREATE
VIEW statement. Views can be created from a
single table, multiple tables or another view.
• Rename view
• RENAME original_view_name TO
new_view_name;
Subquery
• A Subquery or Inner query or a Nested query is
a query within another SQL query and
embedded within the WHERE clause.
• A subquery is used to return data that will be
used in the main query as a condition to further
restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT,
UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must
follow −
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause,
unless multiple columns are in the main query for the
subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery,
although the main query can use an ORDER BY. The GROUP
BY command can be used to perform the same function as
the ORDER BY in a subquery.
• Subqueries that return more than one row can only be used
with multiple value operators such as the IN operator.
• The BETWEEN operator cannot be used with a subquery.
However, the BETWEEN operator can be used within the
subquery.
Subqueries with the SELECT Statement