Answer: Creating Views
Explore how to create SQL views to simplify complex data queries and improve data access. Learn the use of CREATE VIEW, JOINs, aliases, and subqueries to display combined data from multiple tables effectively.
Solution
The solution is given below:
Code explanation
The explanation of the solution code is given below:
Line 4: The
CREATE VIEWstatement creates a view namedSalesTransactionsByCategory.Lines 5–9: The columns of the view are
Sales ID,Employee Name,Category,Sales Amount, andMonth.Line 10: The data is retrieved from the
Salestable.Line 11: The
JOINis performed withSalesandProductCategorieson the columnsCategoryIDin both the tables.Line 12: The result of the previous
JOINis joined withEmployeestable usingEIDcolumns.Line 14: The
SELECTstatement displays the content of the created viewSalesTransactionsByCategory.
Recalling relevant concepts
We have covered the following concepts in this question:
Creating a view
Using
JOINSelective columns
Aliases
Let’s discuss the concepts used in the solution:
We use
CREATE VIEWto create a view. Unlike traditional tables, it doesn’t store data physically but displays data from one or more tables in a specific format. Views simplify complex queries, limit data access for security purposes, and improve efficiency. Following are the examples of creating views:
/* Create a view */CREATE VIEW ExampleView ASSELECT ColumnNameFROM TableNameWHERE condition;/* Retrieve data through view */SELECT * FROM ExampleView;/* Create a view using WITH*/CREATE VIEW ExampleAnotherView ASWITH SomeName AS (SELECT ColumnNameFROM TableNameWHERE condition)SELECT * FROM SomeName;/* Retrieve data through view */SELECT * FROM ExampleAnotherView;
JOIN(short forINNER JOIN) combines rows from two or more tables based on their related columns.JOINorINNER JOINreturns records that have matching values in both tables.
SELECT a.ColumnNameFROM TableName1 AS aJOIN TableName2 AS bON a.CommonColumn = b.CommonColumn;
JOINcan also be applied by specifying columns in theUSINGclause, as shown below:
SELECT a.ColumnNameFROM TableName1 AS aJOIN TableName2 AS bUSING (CommonColumn);
We specify the columns to retrieve in the
SELECTquery; it retrieves the records based on specified conditions. TheFROMclause is used to specify the table from which we want to retrieve the data.
SELECT Column1, Column2, ColumnnFROM TableName;
Aliases are used to give a temporary name to tables or columns. An alias only exists for the duration of the query. Usually, the
ASkeyword is used for specifying an alias. However, it can also be omitted. Examples are as follows:
/* Column alias */SELECT ColumnName AS ColAliasFROM TableName;/* Column alias with space */SELECT ColumnName AS "Col Alias"FROM TableName;/* Table alias */SELECT t.ColumnNameFROM TableName AS t;/* Table alias without using as */SELECT t.ColumnNameFROM TableName t;
Alternate solutions
Let’s discuss the alternate solutions for the same problem in this section:
Using Common Table Expression (CTE)
We can use the common table expression (CTE) to find the desired output. The CTE defined within a view will get the records based on the requirements. Within the view definition, after defining a CTE, the records are retrieved using the SELECT query. The data of view can be viewed using the SELECT query. Let’s take a look at the following query:
Using subqueries
We can use the subqueries to find the desired output without creating a view. The subquery will retrieve the data from the columns in the SELECT statement. Initially, these columns are not part of the same table and we need to fetch the data from different tables. Let’s take a look at the following query:
Similar interview questions
Let’s discuss the variations of the questions in this section:
View for employee responsibility by product
Create a view, EmployeeProductResponsibility, that lists each employee being responsible for each product. The view should show Employee Name, Category, and Product Name.
If you’re unsure how to do this, click the “Show Solution” button.
View of products and their categories
Attempt the following quiz to test your understanding of views.
(Select all that apply.) Select the correct options to create a view showing products and their categories. Multi-select
CREATE VIEW ProductCategoryList AS
SELECT P.PName AS 'Product Name', PC.CategoryName AS Category
FROM Products P
JOIN ProductCategories PC ON P.CategoryID = PC.CategoryID;
CREATE VIEW ProductCategoryList AS
SELECT PName AS 'Product Name', CategoryID AS Category
FROM Products;
SELECT * FROM ProductCategoryList;
CREATE VIEW ProductCategoryList AS
SELECT P.PName AS 'Product Name',
(SELECT CategoryName
FROM ProductCategories
WHERE CategoryID = P.CategoryID) AS Category
FROM Products P;
CREATE VIEW ProductCategoryList AS
WITH ProductWithCategory AS (
SELECT P.PName AS 'Product Name', PC.CategoryName AS Category
FROM Products P
JOIN ProductCategories PC ON P.CategoryID = PC.CategoryID
)
SELECT * FROM ProductWithCategory;
Brain teaser
Solve the following puzzle to create a view to show each Employee along with the product category they manage.
If you’re unsure how to do this, click the “Show Solution” button.
Key terms
We have covered the following key terms in the lesson:
|
|
|
|
|
|
|
|
|