SQL Views and SQL Subqueries Lab
SQL Views and SQL Subqueries Lab
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the
data, using the view's SQL statement, every time a user queries a view.
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2,…
FROM table_name
WHERE condition;
Example
Now we want to add the "Category" column to the "Current Product List" view.
We will update the view with the following SQL:
CREATE OR REPLACE VIEW [Current Product List] AS
SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;
SQL Subqueries
A subquery is a SQL statement that has another SQL query
embedded in the Where or the having clause
A subquery is a SQL query within a query.
Subqueries are nested queries that provide data to the enclosing
query.
Subqueries can return individual values or a list of records
Subqueries must be enclosed with parenthesis
Syntax
The syntax for a subquery when the embedded SQL statement is part of
the WHERE condition is as follows:
SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");
[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It
can also be a text operator such as "LIKE". The portion in red is considered
as the "inner query," while the portion in Green is considered as the "outer
query."
Examples
We use the following tables for our examples.
Student
Example 1: Simple subquery
To use a subquery to find the data of youngest student
Result:
Course Enrollment
Now we want to show those students who have enrolled course with 3 credit
hours