You are on page 1of 6

Views

iews are virtual tables that are is based on a query that runs on one or more database tables.
Database views are saved in the database as named queries and can be used to save frequently
used, complex queries. Views can be used to simplify queries, restrict access to sensitive data,
and provide a consistent interface to the database

Why Use a View?


So if a view is just an SQL statement with a name, why would you use one?
There are several reasons to use views in SQL. This applies to any SQL variation you use
(Oracle, SQL Server, MySQL, etc).
Simplify Queries

The main advantage to using views is that they simplify your queries.

As we learned above, views are just stored SQL statements. These statements can include, for
example:
• Selecting of different columns
• Joins to other tables
• Functions, including aggregate functions
• WHERE clauses
• GROUP BY and HAVING
So, if you have a complicated query or logic that’s used in many places, you can use a view to
hold that logic. You can then query from that view whenever you need that data.

For example, you can create a view that counts the number of orders and totals the order
volume for all orders for each month. You can then query this view and limit by month to find
the data you need for a specific month.

Security

Another benefit of using views is increased security. You can create a view that only selects
certain columns from a table. Then, certain users, or applications, can be given access to this
view rather than the entire table.

For example, you may have an employee table with salary information. You might not want all
applications or users to see this salary information.
So, you can create a view that selects all columns except for the salary columns, and then give
access to that view to other users (and don’t give them access to the employee table).

This means when they query the employee view, they won’t see the salary information.

How to Create a View in SQL


To create a view in SQL, follow this syntax:
CREATE [OR REPLACE] VIEW viewname AS
SELECT select_query;
This is specifically for Oracle SQL but it should be similar for all other databases.
It includes several components:
• CREATE VIEW: specifiess that we are creating a view.
• OR REPLACE: this optional query lets you replace a view that already exists with the same
name, which means you don’t have to drop it first.
• viewname: the name of the view to create. This will be used in queries in the future to
refer to this view.
• AS SELECT: specifies that the view translates to the following SELECT query.
• select_query: the SELECT query to be stored and used for the view. Selecting from the
view will run this query.
Create a Simple View

We’ll create a view that shows the emp_id and last_name columns from the employee table.

CREATE VIEW emp_details AS


SELECT
emp_id,
last_name
FROM employee;
Once this view is created, we can SELECT from it as though it is a table.

SELECT emp_id, last_name


FROM emp_details;
View with Joins

We’ll create a view that shows all employee and department information in the one view.

CREATE VIEW empdept AS


SELECT
e.emp_id,
e.last_name,
e.salary,
d.dept_id,
d.dept_name
FROM employee e
INNER JOIN department d ON e.dept_id = d.dept_id;

View with Aggregate Functions

Now let’s take a look at a view that uses aggregate functions. Let’s say we wanted to find the
department ID and name, the number of employees, and the total salary in each department.

CREATE VIEW dept_stats AS


SELECT
d.dept_id,
d.dept_name,
COUNT(e.*) AS emp_count,
SUM(e.salary) AS total_salary
FROM department d
INNER JOIN employee e ON d.dept_id = e.dept_id
GROUP BY d.dept_id, d.dept_name;

Inserting or Updating Data in a View


You can insert or update data in a view if the view does not:
• Have any DISTINCT keywords, aggregate functions, or window functions in the SELECT
clause
• Use set operators (e.g. UNION)
• Use subqueries in the SELECT clause or marked as read-only
• Use the GROUP BY, HAVING, ORDER BY, MODEL, CONNECT BY, or START WITH clause
• Contain pseudocolumns or expressions
The view must also include all NOT NULL columns for an INSERT to be possible.
When updating or inserting, the data being inserted or updated must be targeted at a key-
preserved table. A key-preserved table is where every primary key and unique key in the
underlying table exists in the view. Without the keys being in the view, the data in the underlying
table can’t be inserted or updated.
How to Insert Data with a View
Inserting data with a view is done the same way as inserting data into a table.
For example, to insert data into the emp_details view:
INSERT INTO emp_details (emp_id, last_name)
VALUES (11, ‘Grover’);
How to Update Data with a View
Updating data with a view is also done the same way as you would do it with a table.
UPDATE employee_rst
SET dept_id = 3
WHERE emp_id = 6;

Aggregation Functions in Databases


Aggregation functions are mathematical operations applied to sets of data to summarize or
transform information. In the context of databases, these functions operate on columns of data
and return a single value, often providing a condensed representation of the dataset.

Types of Aggregation Functions:


1. SUM:
- Calculates the total of numerical values within a column.
2. AVG (Average):
- Computes the average of numerical values in a column.
3. COUNT:
- Counts the number of rows in a dataset, often used to determine the size of a subset.
4. MIN and MAX:
- Identify the smallest and largest values in a column, respectively.

Use Cases:
1. Financial Analysis:
- SUM can be used to calculate the total revenue or expenses.
- AVG assists in determining the average transaction value.
2. Inventory Management:
- COUNT helps track the number of items in stock.
- MIN and MAX identify the oldest and newest items.
3. Data Quality Assurance:
- COUNT is employed to check for missing or duplicate records.
- AVG can be used to identify abnormal values.
Integration with GROUP BY:
Aggregation functions are often paired with the GROUP BY clause to perform operations on
subsets of data. This is particularly useful when analyzing data at a more granular level, such as
by category or time period.
Challenges:
1. Handling NULL Values:
- Aggregation functions may behave unexpectedly when dealing with NULL values.
Understanding how each function handles these cases is crucial.
2. Performance Considerations:
- Aggregation on large datasets can impact database performance. Indexing and proper query
optimization are essential to mitigate this.
Aggregation functions are indispensable tools for extracting meaningful information from
databases. Whether in financial analysis, inventory management, or quality assurance, these
functions empower users to derive insights that drive informed decision-making. Understanding
their types, use cases, and challenges is fundamental for effective database management and
analysis.

You might also like