Create a View for Products in Stock with Supplier Name
Create a View for Products in Stock with Supplier Name
Products Table:
Suppliers Table:
Query Explanation:
-
CREATE VIEW ProductsInStock AS: A new view is being created called
ProductsInStock
. -
SELECT p.ProductID, p.ProductName, p.UnitsInStock, s.SupplierName: Selects the
ProductID
,ProductName
,UnitsInStock
from theProducts
table and theSupplierName
from theSuppliers
table. -
FROM Products p JOIN Suppliers s: Joins the
Products
table with theSuppliers
table. -
ON p.SupplierID = s.SupplierID: The join condition is based on matching the
SupplierID
between the two tables. -
WHERE p.UnitsInStock > 0: Filters to include only products that are in stock (where
UnitsInStock
is greater than 0).
This view will return a list of products that are in stock, along with their supplier names.
SQL Query:
-- Step 1: Create a view for products in stock with the supplier name
CREATE VIEW productsinstock AS
SELECT
products.ProductID, -- Product ID from Products table
products.ProductName, -- Product Name from Products table
products.UnitsInStock, -- Units in stock from Products table
Suppliers.SupplierName -- Supplier Name from Suppliers table
FROM
products -- From the Products table
JOIN
suppliers -- Join with Suppliers table to get the supplier name
ON suppliers.SupplierID = products.SupplierID -- Matching SupplierID in both tables
WHERE
UnitsInStock > 0; -- Only include products that are in stock (UnitsInStock > 0)
-- Step 2: View the data from the productsinstock view
SELECT * FROM productsinstock;
Output: