Popular Searches
Popular Course Categories
Popular Courses

Retrieving Data from Views

Retrieving Data from Views

Views and Virtual Tables

Retrieving Data from Views in MySQL

Course: MySQL Training

Topic: Retrieving Data from Views

Course Link: MySQL Training Course

Demo Link: Register for a Course Demo


1. Introduction to Retrieving Data from Views

Retrieving data from views is an important concept in MySQL database management. A view is a named database object defined by a SELECT statement. It presents data from one or more underlying tables in a virtual-table format, allowing users to retrieve information without repeatedly writing the complete query used to produce that information.

Once a view has been created, users can query it using the SELECT statement, much like a regular table. They can retrieve all available columns, select specific columns, filter rows, sort results, perform calculations, and combine a view with other tables or views when the query permits it.

For example, an employee database may contain employee IDs, names, departments, salaries, email addresses, and joining dates. A view called employee_directory_view might display only employee IDs, names, and email addresses. Instead of accessing the entire employees table, an application can retrieve the required information directly from the view.

A standard MySQL view generally stores its query definition rather than a separate copy of the result rows. When users query the view, MySQL evaluates the view definition against the underlying database objects. Consequently, changes to underlying data can be reflected in subsequent queries against the view.

1.1 Learning Objectives

  • Understand how data retrieval from MySQL views works.
  • Learn the basic SELECT syntax for querying a view.
  • Retrieve all columns and selected columns from a view.
  • Filter view records using WHERE conditions.
  • Sort results using ORDER BY.
  • Limit the number of records using LIMIT and OFFSET.
  • Use aggregate functions with views.
  • Retrieve data from views created using joins.
  • Filter grouped view results and perform calculations.
  • Understand NULL values, aliases, and duplicate results.
  • Combine views with tables and other views.
  • Learn how permissions and view definitions affect data retrieval.
  • Troubleshoot common errors and apply best practices.

2. Understanding the SELECT Statement

2.1 What Is SELECT?

SELECT is the SQL statement used to retrieve data from database tables, views, and other valid query sources. It allows users to specify which columns they want to display and which rows should be returned.

The basic syntax for retrieving data from a view is:

SELECT column1, column2, ...
FROM view_name;

In this statement, SELECT identifies the required columns, while FROM identifies the view from which the data will be retrieved.

2.2 Retrieve All Columns

SELECT *
FROM employee_directory_view;

The asterisk (*) represents all columns exposed by the view. This statement returns all available columns and rows from employee_directory_view.

Although SELECT * is convenient for learning and quick inspection, selecting explicit column names is often better in production applications because it makes the required output clearer and less dependent on changes to the view's structure.

2.3 Retrieve Specific Columns

SELECT employee_id, employee_name
FROM employee_directory_view;

This query returns only employee_id and employee_name. The selected columns must be available in the view's output.

2.4 Retrieve Data with a Condition

SELECT employee_id, employee_name
FROM employee_directory_view
WHERE employee_id = 101;

The WHERE clause filters the records returned by the view query. In this example, only the employee whose ID is 101 is requested.

3. Creating Sample Tables and Views

Before practicing data retrieval, create a sample database containing departments and employees. The examples in the following sections use these objects.

3.1 Create a Database

CREATE DATABASE company_db;
USE company_db;

CREATE DATABASE creates the database, and USE selects it for the subsequent SQL statements.

3.2 Create the Departments Table

CREATE TABLE departments (
    department_id INT PRIMARY KEY,
    department_name VARCHAR(100) NOT NULL
);

3.3 Insert Department Data

INSERT INTO departments (department_id, department_name)
VALUES
(1, 'IT'),
(2, 'HR'),
(3, 'Finance'),
(4, 'Marketing');

3.4 Create the Employees Table

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    employee_name VARCHAR(100) NOT NULL,
    department_id INT,
    salary DECIMAL(10,2),
    email VARCHAR(150),
    joining_date DATE,
    FOREIGN KEY (department_id)
        REFERENCES departments(department_id)
);

3.5 Insert Employee Data

INSERT INTO employees
(employee_id, employee_name, department_id, salary, email, joining_date)
VALUES
(101, 'Amit Sharma', 1, 75000, '[email protected]', '2022-01-15'),
(102, 'Priya Verma', 2, 60000, '[email protected]', '2021-03-10'),
(103, 'Rahul Mehta', 1, 90000, '[email protected]', '2020-07-20'),
(104, 'Sneha Patel', 3, 85000, '[email protected]', '2022-11-05'),
(105, 'Vikas Kumar', 2, 65000, '[email protected]', '2023-06-18'),
(106, 'Neha Singh', 1, 80000, '[email protected]', '2023-09-12'),
(107, 'Karan Shah', 3, 70000, '[email protected]', '2021-04-25'),
(108, 'Meera Joshi', 4, 72000, '[email protected]', '2024-02-01');

3.6 Create a Simple View

CREATE VIEW employee_directory_view AS
SELECT employee_id, employee_name, email
FROM employees;

This view exposes three columns from the employees table: employee_id, employee_name, and email. It provides a simple directory-style view of employee information.

3.7 Create a Salary View

CREATE VIEW employee_salary_view AS
SELECT employee_id,
       employee_name,
       department_id,
       salary
FROM employees;

This view is intended for examples involving salary filtering, sorting, and calculations. Access to salary information should be restricted to appropriately authorized users.

3.8 Create a Department View Using JOIN

CREATE VIEW employee_department_view AS
SELECT e.employee_id,
       e.employee_name,
       d.department_name,
       e.salary,
       e.joining_date
FROM employees AS e
INNER JOIN departments AS d
    ON e.department_id = d.department_id;

This view combines employee data with department names. It allows users to retrieve department information without rewriting the join in every query.

4. Retrieving All Data from a View

4.1 Using SELECT *

SELECT *
FROM employee_directory_view;

This statement returns all columns defined in employee_directory_view for all rows that the view query produces.

The output contains employee_id, employee_name, and email. Columns that are present in the underlying employees table but not included in the view will not appear in this result.

4.2 Understanding the Result

employee_id employee_name email
101 Amit Sharma [email protected]
102 Priya Verma [email protected]
103 Rahul Mehta [email protected]
104 Sneha Patel [email protected]
105 Vikas Kumar [email protected]
106 Neha Singh [email protected]
107 Karan Shah [email protected]
108 Meera Joshi [email protected]

The displayed order is illustrative. Unless an outer query specifies ORDER BY, SQL does not guarantee the order of returned rows.

4.3 When Should SELECT * Be Avoided?

  • When an application requires only a small number of columns.
  • When unnecessary columns could expose confidential information.
  • When the query should have a clearly defined output structure.
  • When the view's columns may change over time.
  • When reducing data transfer can improve application efficiency.

5. Retrieving Specific Columns from a View

5.1 Selecting One Column

SELECT employee_name
FROM employee_directory_view;

This query returns only employee names. It does not display employee IDs or email addresses.

5.2 Selecting Multiple Columns

SELECT employee_id, employee_name
FROM employee_directory_view;

Multiple column names are separated by commas. Each column must be available in the view.

5.3 Selecting Columns in a Different Order

SELECT email, employee_name, employee_id
FROM employee_directory_view;

The output follows the column order specified in the outer SELECT statement. This allows a query to present information in a convenient format without changing the view definition.

5.4 Using Column Aliases

SELECT employee_id AS id,
       employee_name AS full_name
FROM employee_directory_view;

Aliases provide alternative names for columns in the query result. Here, employee_id is displayed as id and employee_name as full_name. The aliases in this SELECT statement change the output labels for this query only; they do not modify the stored view.

6. Filtering View Data with WHERE

The WHERE clause restricts which rows are returned by a query. It can filter view data by numbers, text, dates, and other supported expressions.

6.1 Filter by Employee ID

SELECT *
FROM employee_directory_view
WHERE employee_id = 103;

This query returns the record for employee ID 103.

6.2 Filter by Text

SELECT employee_id, employee_name
FROM employee_directory_view
WHERE employee_name = 'Priya Verma';

This query searches for a matching employee name. String comparisons depend on the column's collation, which determines characteristics such as case sensitivity.

6.3 Filter Using LIKE

SELECT employee_id, employee_name
FROM employee_directory_view
WHERE employee_name LIKE 'A%';

The LIKE operator supports pattern matching. The percent sign (%) matches zero or more characters, so this example searches for names beginning with A.

6.4 Filter Using IN

SELECT employee_id, employee_name, department_id, salary
FROM employee_salary_view
WHERE department_id IN (1, 3);

The IN operator checks whether department_id matches one of the specified values. This query returns employees belonging to departments 1 or 3.

6.5 Filter Using BETWEEN

SELECT employee_name, salary
FROM employee_salary_view
WHERE salary BETWEEN 70000 AND 85000;

BETWEEN includes both boundary values. This query retrieves employees whose salary is greater than or equal to 70,000 and less than or equal to 85,000.

6.6 Combine Multiple Conditions

SELECT employee_name, department_id, salary
FROM employee_salary_view
WHERE department_id = 1
  AND salary > 75000;

The AND operator requires both conditions to be true. Only employees in department 1 whose salary exceeds 75,000 are returned.

6.7 Use OR to Match Alternative Conditions

SELECT employee_name, department_id
FROM employee_salary_view
WHERE department_id = 1
   OR department_id = 2;

The OR operator returns rows that satisfy either condition. IN can often express the same requirement more compactly.

7. Retrieving Data with ORDER BY

ORDER BY sorts the rows returned by a query. You can sort by one or more columns in ascending or descending order.

7.1 Sort by Employee Name

SELECT employee_id, employee_name
FROM employee_directory_view
ORDER BY employee_name ASC;

ASC means ascending order and is the default when no direction is specified.

7.2 Sort by Salary from Highest to Lowest

SELECT employee_name, salary
FROM employee_salary_view
ORDER BY salary DESC;

DESC sorts values in descending order. For salaries, this normally places the highest values first.

7.3 Sort by Multiple Columns

SELECT employee_name, department_id, salary
FROM employee_salary_view
ORDER BY department_id ASC, salary DESC;

MySQL sorts first by department_id in ascending order and then sorts salaries in descending order within each department.

7.4 Why Use ORDER BY in the Outer Query?

When retrieving data from a view, specify ORDER BY in the outer SELECT statement whenever the result must follow a particular order. Even if a view definition includes ORDER BY, a query that references the view should not rely on that ordering being preserved. An outer ORDER BY is the appropriate way to request a defined result order.

8. Limiting the Number of Records

The LIMIT clause restricts how many rows are returned. It is useful for previews, reports, dashboards, and pagination.

8.1 Retrieve the First Five Rows

SELECT employee_id, employee_name
FROM employee_directory_view
ORDER BY employee_id
LIMIT 5;

This query returns at most five rows in employee ID order.

8.2 Retrieve the Three Highest Salaries

SELECT employee_name, salary
FROM employee_salary_view
ORDER BY salary DESC
LIMIT 3;

This query returns at most three employees with the highest salary values. If multiple employees have the same salary around the cutoff, LIMIT returns only the number of rows requested. Add a secondary ordering column, such as employee_id, when a stable order among ties is important.

8.3 Use LIMIT with OFFSET

SELECT employee_id, employee_name
FROM employee_directory_view
ORDER BY employee_id
LIMIT 3 OFFSET 3;

This query skips the first three rows in the ordered result and returns the next three rows, if available.

8.4 Alternative LIMIT Syntax

SELECT employee_id, employee_name
FROM employee_directory_view
ORDER BY employee_id
LIMIT 3, 3;

In this syntax, the first number is the offset and the second number is the maximum row count. LIMIT 3 OFFSET 3 is often easier to read because the offset and row count are explicit.

9. Retrieving Data from Views Using Aggregate Functions

Aggregate functions summarize values across a set of rows. They can be used when querying views, provided the selected expressions and grouping rules are valid.

9.1 Count the Records in a View

SELECT COUNT(*) AS total_employees
FROM employee_directory_view;

COUNT(*) returns the number of rows produced by the view. It does not count only the rows with a non-NULL value in a particular column.

9.2 Calculate the Average Salary

SELECT AVG(salary) AS average_salary
FROM employee_salary_view;

AVG calculates the average of non-NULL salary values. If no non-NULL values are available, the result is NULL.

9.3 Find the Highest and Lowest Salaries

SELECT MAX(salary) AS highest_salary,
       MIN(salary) AS lowest_salary
FROM employee_salary_view;

MAX returns the greatest non-NULL value and MIN returns the smallest non-NULL value in the selected set.

9.4 Calculate Total Salary

SELECT SUM(salary) AS total_salary
FROM employee_salary_view;

SUM adds the non-NULL salary values. When no non-NULL values exist, SUM returns NULL rather than zero.

9.5 Count Employees by Department

SELECT department_id,
       COUNT(*) AS employee_count
FROM employee_salary_view
GROUP BY department_id
ORDER BY department_id;

GROUP BY combines rows with the same department ID. COUNT(*) then calculates the number of employees in each group.

10. Retrieving Data from Views with GROUP BY and HAVING

10.1 Understanding GROUP BY

GROUP BY organizes rows into groups based on one or more columns. It is commonly used with aggregate functions to calculate totals, counts, averages, maximums, and minimums for each group.

10.2 Create a Department Summary View

CREATE VIEW department_summary_view AS
SELECT department_id,
       COUNT(*) AS employee_count,
       AVG(salary) AS average_salary,
       MAX(salary) AS highest_salary
FROM employees
GROUP BY department_id;

This view summarizes employees by department. It exposes the department ID, employee count, average salary, and highest salary for each department represented in the employees table.

10.3 Retrieve All Department Summaries

SELECT *
FROM department_summary_view
ORDER BY department_id;

10.4 Filter the Summary Results

SELECT department_id, employee_count, average_salary
FROM department_summary_view
WHERE employee_count > 1;

The outer WHERE clause filters the rows produced by the view. In this example, only department summaries with more than one employee are returned.

10.5 Use HAVING in the Outer Query

SELECT department_id,
       COUNT(*) AS employee_count
FROM employee_salary_view
GROUP BY department_id
HAVING COUNT(*) > 1;

HAVING filters groups after GROUP BY has formed them. WHERE filters individual rows before grouping. Both clauses are useful, but they operate at different stages of query processing.

11. Retrieving Data from Views Created with JOINs

11.1 Query a Joined View

SELECT *
FROM employee_department_view;

This query returns the columns exposed by employee_department_view, including employee IDs, names, department names, salaries, and joining dates.

11.2 Retrieve Specific Department Records

SELECT employee_name, department_name
FROM employee_department_view
WHERE department_name = 'IT';

This query returns employee names and department names for employees whose department is IT.

11.3 Sort the Joined Results

SELECT employee_name, department_name, salary
FROM employee_department_view
ORDER BY department_name ASC, salary DESC;

The query groups the displayed order by department name and sorts salaries from highest to lowest within each department.

11.4 Retrieve Data from a LEFT JOIN View

A view defined with LEFT JOIN can include every row from its left-side table, even when no matching row exists on the right side. In such cases, the right-side columns are NULL.

CREATE VIEW employee_department_all_view AS
SELECT e.employee_id,
       e.employee_name,
       d.department_name
FROM employees AS e
LEFT JOIN departments AS d
    ON e.department_id = d.department_id;

SELECT employee_id, employee_name, department_name
FROM employee_department_all_view
ORDER BY employee_id;

Because the sample employees table has a foreign key referencing departments, an employee cannot normally contain a non-NULL department ID without a matching department. However, department_id is nullable, so an employee may have no department assigned; the LEFT JOIN preserves that employee and returns NULL for department_name.

12. Retrieving Data from Views with Calculated Columns

12.1 Create a Calculated View

CREATE VIEW employee_annual_salary_view AS
SELECT employee_id,
       employee_name,
       salary,
       salary * 12 AS annual_salary
FROM employees;

This view calculates annual_salary by multiplying salary by 12. This calculation assumes that the salary column stores a monthly amount.

12.2 Retrieve Calculated Values

SELECT employee_name, salary, annual_salary
FROM employee_annual_salary_view
ORDER BY annual_salary DESC;

The query retrieves the stored view columns and sorts employees by the calculated annual salary. The calculated value is produced by the view's SELECT expression.

12.3 Filter Using a Calculated Column

SELECT employee_name, annual_salary
FROM employee_annual_salary_view
WHERE annual_salary > 900000;

This query returns employees whose calculated annual salary exceeds 900,000, assuming the monthly-salary interpretation used in the view definition.

12.4 Apply a New Calculation in the Outer Query

SELECT employee_name,
       salary,
       salary * 0.10 AS estimated_bonus
FROM employee_salary_view
ORDER BY estimated_bonus DESC;

A query that reads from a view can include additional calculations. In this example, the estimated bonus is calculated by the outer query rather than being defined inside the view.

13. Working with NULL Values in Views

13.1 What Is NULL?

NULL represents a missing, unknown, or unavailable value. It is not the same as zero, an empty string, or a regular text value.

13.2 Find Records with NULL Values

SELECT employee_id, employee_name, department_id
FROM employee_salary_view
WHERE department_id IS NULL;

Use IS NULL to find records where a column has no value. Comparing a column with = NULL does not correctly test for NULL values.

13.3 Find Records Without NULL Values

SELECT employee_id, employee_name, department_id
FROM employee_salary_view
WHERE department_id IS NOT NULL;

IS NOT NULL returns rows where department_id has a non-NULL value.

13.4 Replace NULL in Displayed Results

SELECT employee_name,
       COALESCE(department_id, 0) AS displayed_department_id
FROM employee_salary_view;

COALESCE returns the first non-NULL expression in its argument list. Here, a missing department ID is displayed as 0. This is only a display substitution; it does not change the underlying data, and 0 should not be mistaken for a real department ID unless the database design defines it that way.

14. Retrieving Distinct Values from Views

14.1 What Does DISTINCT Do?

DISTINCT removes duplicate combinations of the selected columns from the result set. It is useful when a view contains repeated values and the query needs unique values only.

14.2 Retrieve Unique Department IDs

SELECT DISTINCT department_id
FROM employee_salary_view
ORDER BY department_id;

This query returns each distinct department ID present in the view. If multiple employees belong to the same department, the department ID appears only once in the result.

14.3 Retrieve Unique Combinations

SELECT DISTINCT department_id, salary
FROM employee_salary_view
ORDER BY department_id, salary;

When DISTINCT is used with multiple columns, MySQL removes duplicate combinations of all selected columns, not duplicates in each column independently.

15. Searching View Data with LIKE and Other Operators

15.1 Search Names Beginning with a Letter

SELECT employee_id, employee_name
FROM employee_directory_view
WHERE employee_name LIKE 'S%';

The percent sign matches zero or more characters after S.

15.2 Search Names Containing Text

SELECT employee_id, employee_name
FROM employee_directory_view
WHERE employee_name LIKE '%sh%';

The pattern %sh% searches for the sequence sh anywhere in the employee name. Case sensitivity depends on the collation used by the relevant column.

15.3 Search for a Range of Dates

CREATE VIEW employee_joining_view AS
SELECT employee_id, employee_name, joining_date
FROM employees;

SELECT employee_id, employee_name, joining_date
FROM employee_joining_view
WHERE joining_date BETWEEN '2022-01-01' AND '2023-12-31'
ORDER BY joining_date;

This query retrieves employees whose joining dates fall between January 1, 2022, and December 31, 2023, including both dates.

15.4 Use Comparison Operators

SELECT employee_name, salary
FROM employee_salary_view
WHERE salary >= 80000;

Comparison operators such as =, <>, >, <, >=, and <= help retrieve records that meet numerical or other comparable conditions.

16. Retrieving Data from One View Using Another View

MySQL allows a view definition to reference another view. This can be useful when building reusable layers of query logic. The view hierarchy should remain understandable and manageable.

16.1 Create a Base View

CREATE VIEW employee_basic_view AS
SELECT employee_id, employee_name, department_id, salary
FROM employees;

16.2 Create a Second View Based on the First View

CREATE VIEW high_salary_employee_view AS
SELECT employee_id, employee_name, department_id, salary
FROM employee_basic_view
WHERE salary > 75000;

16.3 Retrieve Data from the Second View

SELECT employee_name, salary
FROM high_salary_employee_view
ORDER BY salary DESC;

The query reads from high_salary_employee_view, which references employee_basic_view, which in turn reads from employees. MySQL resolves the view definitions to produce the requested result.

16.4 Best Practices for Nested Views

  • Use meaningful names that explain each view's purpose.
  • Avoid excessive nesting that makes query behavior difficult to follow.
  • Document dependencies between views and base tables.
  • Test dependent views after changing a source view's definition.
  • Use EXPLAIN to investigate query performance when necessary.

17. Joining a View with a Table

A view can be used as a source in a JOIN just like a table, provided the query is valid. This allows users to combine a reusable view with additional data sources.

17.1 Join a View with the Departments Table

SELECT ev.employee_name,
       d.department_name
FROM employee_salary_view AS ev
INNER JOIN departments AS d
    ON ev.department_id = d.department_id
ORDER BY d.department_name, ev.employee_name;

This query joins employee_salary_view with departments to display employee names and department names. The view provides employee data, while the departments table provides the department labels.

17.2 Join Two Views

SELECT es.employee_name,
       ed.department_name,
       es.salary
FROM employee_salary_view AS es
INNER JOIN employee_department_view AS ed
    ON es.employee_id = ed.employee_id
ORDER BY es.salary DESC;

This example joins two views using employee_id. Because both views contain employee records, matching IDs connect their rows. The join is included for demonstration; if the same output can be produced more simply from one view, prefer the simpler query.

18. Retrieving Data from Views with Subqueries

Subqueries are queries nested inside another SQL statement. A view can be used inside a subquery when the query structure supports it.

18.1 Find Employees Earning More Than the Average Salary

SELECT employee_name, salary
FROM employee_salary_view
WHERE salary > (
    SELECT AVG(salary)
    FROM employee_salary_view
)
ORDER BY salary DESC;

The inner query calculates the average salary from the view. The outer query returns employees whose salary exceeds that average.

18.2 Find Employees in Departments with Multiple Employees

SELECT employee_name, department_id
FROM employee_salary_view
WHERE department_id IN (
    SELECT department_id
    FROM employee_salary_view
    GROUP BY department_id
    HAVING COUNT(*) > 1
)
ORDER BY department_id, employee_name;

The subquery identifies departments containing more than one employee. The outer query returns employees belonging to those departments.

19. Retrieving Data with UNION

UNION combines the results of two or more compatible SELECT statements into one result set. By default, UNION removes duplicate rows. UNION ALL retains duplicates.

19.1 Combine Results from Two Views

CREATE VIEW it_employee_names_view AS
SELECT employee_id, employee_name
FROM employees
WHERE department_id = 1;

CREATE VIEW hr_employee_names_view AS
SELECT employee_id, employee_name
FROM employees
WHERE department_id = 2;

SELECT employee_id, employee_name
FROM it_employee_names_view
UNION
SELECT employee_id, employee_name
FROM hr_employee_names_view
ORDER BY employee_name;

This query combines the IT and HR employee results. The SELECT statements must return the same number of compatible columns.

19.2 UNION vs. UNION ALL

Feature UNION UNION ALL
Duplicate rows Removes duplicate result rows. Retains duplicate result rows.
Typical use When unique combined results are required. When all rows should be retained.
Performance May require additional work to eliminate duplicates. Can avoid duplicate-elimination work.

20. Retrieving Data from Views with Date Functions

Views that expose date columns can be queried using MySQL date functions. This is useful for reports based on joining dates, order dates, delivery dates, or other time-related information.

20.1 Retrieve the Year of Joining

SELECT employee_name,
       YEAR(joining_date) AS joining_year
FROM employee_joining_view
ORDER BY joining_year, employee_name;

YEAR() extracts the year component from a date value.

20.2 Retrieve Employees Who Joined in a Particular Year

SELECT employee_name, joining_date
FROM employee_joining_view
WHERE joining_date >= '2023-01-01'
  AND joining_date < '2024-01-01'
ORDER BY joining_date;

This date-range pattern retrieves records from the year 2023. For a DATE column, the upper bound excludes January 1, 2024, and everything after it.

20.3 Calculate Time Since Joining

SELECT employee_name,
       joining_date,
       TIMESTAMPDIFF(YEAR, joining_date, CURDATE()) AS completed_years
FROM employee_joining_view
ORDER BY completed_years DESC;

TIMESTAMPDIFF calculates the number of completed year intervals between joining_date and the current date. The result changes as the current date changes.

21. Retrieving Data from Views with Conditional Logic

21.1 Use CASE to Categorize Employees

CREATE VIEW employee_salary_category_view AS
SELECT employee_id,
       employee_name,
       salary,
       CASE
           WHEN salary >= 85000 THEN 'High'
           WHEN salary >= 70000 THEN 'Medium'
           ELSE 'Standard'
       END AS salary_category
FROM employees;

21.2 Retrieve a Particular Salary Category

SELECT employee_name, salary, salary_category
FROM employee_salary_category_view
WHERE salary_category = 'High'
ORDER BY salary DESC;

This query returns employees classified as High by the CASE expression in the view. The category thresholds are illustrative and should match the actual business rules in a real application.

22. Retrieving Data from Views and Understanding Updates

A standard view generally retrieves current data from its underlying tables when queried. If a row in a base table is changed, a subsequent query against a view that references that row can reflect the change.

22.1 Retrieve a Record Before an Update

SELECT employee_id, employee_name, email
FROM employee_directory_view
WHERE employee_id = 101;

22.2 Update the Underlying Table

UPDATE employees
SET email = '[email protected]'
WHERE employee_id = 101;

22.3 Retrieve the Record Again

SELECT employee_id, employee_name, email
FROM employee_directory_view
WHERE employee_id = 101;

The new email address appears in the view result because the view reads from the employees table. This example updates a sample record; verify the WHERE condition and intended row before performing data changes in a real database.

22.4 Important Difference Between a View and a Snapshot

A standard view is not the same as a saved report or exported file. A saved report may contain values captured at an earlier time, while a standard view normally queries its underlying data when it is accessed. Applications may cache results separately, so application-level caching can affect what a user sees.

23. View Permissions and Data Retrieval

23.1 Why Permissions Matter

Users must have appropriate privileges to query a view. MySQL also checks privileges for the underlying objects according to the view's security context.

A view can expose a limited set of columns, but this is only an effective access-control approach when database privileges are configured so that unauthorized users cannot bypass the view and query sensitive underlying tables directly.

23.2 Grant SELECT Permission on a View

GRANT SELECT
ON company_db.employee_directory_view
TO 'report_user'@'localhost';

This example grants SELECT permission on the specified view to an example account. The account must exist, and the administrator executing the GRANT statement must have the required privileges.

23.3 Query the View as an Authorized User

SELECT employee_id, employee_name, email
FROM company_db.employee_directory_view;

The query can run only when the current account has sufficient privileges under the view's configured security context.

23.4 Security Best Practices

  • Grant only the privileges needed for the user's responsibilities.
  • Avoid exposing confidential columns unnecessarily.
  • Review the view's DEFINER and SQL SECURITY configuration.
  • Do not assume that view access automatically blocks direct access to source tables.
  • Test access using an account with the same permissions as the intended user.

24. Inspecting a View Before Retrieving Data

24.1 List Views in the Current Database

SHOW FULL TABLES
WHERE Table_type = 'VIEW';

This statement lists views in the current database, helping you confirm the name of a view before querying it.

24.2 Display a View's Definition

SHOW CREATE VIEW employee_directory_view;

SHOW CREATE VIEW displays the SQL definition of the view. It helps you determine which tables, columns, conditions, and expressions are used to produce the result.

24.3 Inspect View Metadata

SELECT TABLE_SCHEMA,
       TABLE_NAME,
       IS_UPDATABLE,
       SECURITY_TYPE
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_SCHEMA = 'company_db';

INFORMATION_SCHEMA.VIEWS provides metadata about views visible to the current account. Available information and visibility depend on MySQL privileges.

24.4 Check the Underlying Query Performance

EXPLAIN
SELECT employee_name, salary
FROM employee_salary_view
WHERE salary > 75000
ORDER BY salary DESC;

EXPLAIN displays information about the query execution plan. It can help identify table scans, index usage, joins, and other operations that may affect performance.

25. Common Errors When Retrieving Data from Views

Error or Problem Possible Cause Solution
Table or view does not exist. The view name is incorrect or the wrong database is selected. Check the database using SELECT DATABASE() and list available views.
Unknown column. The requested column is not exposed by the view or its name is incorrect. Use SHOW CREATE VIEW to inspect the view definition and output columns.
Access denied. The current account lacks required privileges. Review SELECT permissions and the view's security context.
Empty result set. The WHERE condition does not match any rows, or the underlying data contains no qualifying records. Check the condition, verify the source data, and test the view without filters.
Unexpected duplicate rows. The view uses joins that produce multiple matches, or the source data contains duplicates. Inspect join conditions and use DISTINCT only when duplicate removal matches the intended result.
Incorrect row order. The query does not specify ORDER BY. Add ORDER BY to the outer SELECT statement.
NULL values appear. The source columns contain NULL or an outer join has no matching row. Use IS NULL for filtering and COALESCE for appropriate display substitutions.
View query is slow. The underlying query uses expensive joins, scans, or sorting operations. Use EXPLAIN, review indexes on source tables, and simplify the query where possible.
View definition is invalid. A source table or column was dropped or renamed. Inspect the definition and update the view to match the current schema.
New source-table columns do not appear. The view definition was created before the source schema changed. Update the view definition to include the required columns.

26. Best Practices for Retrieving Data from Views

  • Use explicit column names when the query needs a known set of fields.
  • Use WHERE to reduce the number of rows returned when filtering is appropriate.
  • Use ORDER BY whenever the output must follow a specific order.
  • Use LIMIT for previews and pagination, together with a deterministic ORDER BY.
  • Check the view definition if a requested column is missing or unexpected.
  • Understand whether joins can create duplicate rows.
  • Use aggregate functions only when their summary behavior matches the reporting requirement.
  • Use IS NULL and IS NOT NULL for NULL comparisons.
  • Choose DISTINCT carefully because it removes duplicate combinations of selected columns.
  • Restrict access to views and underlying tables based on user responsibilities.
  • Use EXPLAIN to investigate performance instead of assuming that a view makes a query faster.
  • Test view queries after changes to underlying tables or other views.
  • Avoid relying on an implicit row order.
  • Document complicated views and their business logic.
  • Use realistic test data to verify filters, joins, NULL handling, and aggregate results.

27. Practical Exercise: Retrieving Employee Information

Use the company_db database and the views created in these notes to complete the following exercises.

Exercise 1: Retrieve All Employee Directory Records

SELECT *
FROM employee_directory_view;

Expected task: Display every row and every column exposed by the employee directory view.

Exercise 2: Retrieve Only Names and Emails

SELECT employee_name, email
FROM employee_directory_view
ORDER BY employee_name;

Expected task: Display employee names and email addresses in alphabetical order.

Exercise 3: Find Employees Earning More Than 75,000

SELECT employee_name, salary
FROM employee_salary_view
WHERE salary > 75000
ORDER BY salary DESC;

Expected task: Return employees whose salary exceeds 75,000, with the highest salaries first.

Exercise 4: Retrieve Employees from IT

SELECT employee_name, department_name
FROM employee_department_view
WHERE department_name = 'IT';

Expected task: Display employees belonging to the IT department.

Exercise 5: Find the Average Salary

SELECT AVG(salary) AS average_salary
FROM employee_salary_view;

Expected task: Calculate the average of the non-NULL salary values exposed by the view.

Exercise 6: Retrieve the Three Highest-Paid Employees

SELECT employee_name, salary
FROM employee_salary_view
ORDER BY salary DESC, employee_id ASC
LIMIT 3;

Expected task: Return three rows ordered by salary from highest to lowest. The employee ID provides a stable tie-breaker.

Exercise 7: Count Employees in Each Department

SELECT department_id, COUNT(*) AS employee_count
FROM employee_salary_view
GROUP BY department_id
ORDER BY department_id;

Expected task: Display the number of employee records associated with each department ID.

Exercise 8: Find Employees Who Joined During 2023

SELECT employee_id, employee_name, joining_date
FROM employee_joining_view
WHERE joining_date >= '2023-01-01'
  AND joining_date < '2024-01-01'
ORDER BY joining_date;

Expected task: Return employees whose joining dates fall within the calendar year 2023.

Exercise 9: Find Employees with Missing Department Assignments

SELECT employee_id, employee_name, department_id
FROM employee_salary_view
WHERE department_id IS NULL;

Expected task: Return employees whose department ID has not been assigned.

Exercise 10: Retrieve Department Salary Summaries

SELECT department_id,
       employee_count,
       average_salary,
       highest_salary
FROM department_summary_view
ORDER BY average_salary DESC;

Expected task: Display department-level summary data ordered by average salary. If a department's average salary is NULL, its placement depends on the sort direction and MySQL's NULL ordering rules.

28. Interview Questions and Answers

Q1. How do you retrieve data from a MySQL view?

Use SELECT with the view name in the FROM clause, just as you would when retrieving data from a table.

SELECT *
FROM view_name;

Q2. Can we retrieve selected columns from a view?

Yes. Specify the required column names in the SELECT clause, provided those columns are exposed by the view.

Q3. Can we use WHERE with a view?

Yes. WHERE filters rows produced by the view query.

Q4. Can we sort the data retrieved from a view?

Yes. Use ORDER BY in the outer SELECT statement to define the required result order.

Q5. Can we use LIMIT with a view?

Yes. LIMIT restricts the number of rows returned by the outer query. ORDER BY is recommended when the selected rows must be predictable.

Q6. Can we use aggregate functions with views?

Yes. Functions such as COUNT(), SUM(), AVG(), MIN(), and MAX() can be used when querying a view, subject to valid SQL grouping rules.

Q7. Does a view store a separate copy of the data?

A standard MySQL view generally stores its query definition rather than a separate copy of its result rows.

Q8. Will changes to a base table appear in a view?

Subsequent queries against a standard view generally reflect changes to the underlying data, provided the view definition remains valid and the changed rows satisfy its query conditions.

Q9. What is the difference between WHERE and HAVING?

WHERE filters rows before grouping. HAVING filters groups after GROUP BY has formed them.

Q10. How do you retrieve unique values from a view?

Use SELECT DISTINCT followed by the required column or columns.

Q11. Can a view be joined with a table?

Yes. A view can be used as a source in a JOIN, just like a table, provided the query is valid.

Q12. How do you inspect a view definition?

SHOW CREATE VIEW view_name;

Q13. Why might a view query return no rows?

The view may produce no qualifying records, or the outer WHERE condition may filter out every row. Check the view without the additional filter and inspect the underlying data.

Q14. Why should ORDER BY be used when retrieving view data?

SQL does not guarantee row order unless the outer query specifies ORDER BY.

Q15. Does querying a view automatically improve performance?

No. A standard view provides query abstraction and reuse, but performance depends on the underlying query, indexes, data distribution, and execution plan.

29. Quick Revision Checklist

  • SELECT: Retrieves data from a view.
  • FROM: Identifies the view being queried.
  • SELECT *: Returns all columns exposed by the view.
  • Specific columns: Return only the fields required by the query.
  • WHERE: Filters individual rows.
  • ORDER BY: Defines the result order.
  • LIMIT: Restricts the number of returned rows.
  • OFFSET: Skips a specified number of rows before returning results.
  • DISTINCT: Removes duplicate combinations of selected values.
  • GROUP BY: Creates groups for aggregate calculations.
  • HAVING: Filters grouped results.
  • JOIN: Combines data from views, tables, or both.
  • Subquery: Allows a query to use the result of another query.
  • NULL: Test using IS NULL or IS NOT NULL.
  • SHOW CREATE VIEW: Displays the view definition.
  • EXPLAIN: Helps analyze query execution plans.
  • Permissions: Control who can retrieve data through a view and access underlying objects.

30. Conclusion

Retrieving data from views is a fundamental MySQL skill that makes it easier to access reusable query results. By using SELECT with views, users can retrieve all or selected columns, filter rows, sort results, limit output, calculate summaries, and combine information from related tables.

Understanding WHERE, ORDER BY, LIMIT, DISTINCT, GROUP BY, HAVING, joins, subqueries, and aggregate functions makes it possible to retrieve data from views for a wide variety of reporting and application requirements. It is also important to understand view definitions, NULL behavior, permissions, and query performance.

For reliable results, select only the columns you need, define ordering explicitly, test filters carefully, review permissions, and use EXPLAIN when a query performs poorly. With regular practice, retrieving data from MySQL views becomes a useful part of database querying, reporting, and application development.

31. Additional Learning Resources

whatsapp