MySQL Views (or Virtual Tables)

MySQL Views (or Virtual Tables)

A View is essentially a table in MySQL consisting of rows and columns, just like a regular table. However, the difference is that a View, or Virtual Table, does not physically store data.

Key Points to Learn About Views

Let's go through the key points. First, let's see how to create a View. It's a simple process:

1. Creating a View

Use the following query to create a View easily:

CREATE VIEW VIEWNAME;        

2. Working with Views

Once a View is created, you can use SQL commands like SELECT, DELETE, UPDATE, and INSERT on it just like on a normal table.

3. Advantages of Using Views

Before we dive into an example, let's explore the benefits of using Views:

  1. Security Mechanism: Views allow you to expose only the required data, reducing complexity and securing sensitive information.
  2. Data Abstraction: You can display specific data to the user as needed while keeping the underlying table structure hidden.
  3. Convenience: Views make queries more readable and easier to execute by simplifying complex operations into a single command.

Step 1: Creating a Normal Table

First, create a table named Accounts.

CREATE TABLE Accounts (
    Account_ID INT,
    Company VARCHAR(50),
    Amount DECIMAL(10, 2)
);
        


Image1


Step 2: Adding Data to the Table

Now, add a few rows of data to the table.

INSERT INTO Accounts (Account_ID, Company, Amount) VALUES
(1, 'ABC', 450.00),
(2, 'aXYZ', 15000.00),
(3, 'QRT', 5000.00);
        


Image2

Step 3: Viewing the Table

Once the data is added, you can view the Accounts table. This is a standard table with the data stored physically.

SELECT * FROM Accounts;        


Image3

Step 4: Creating a View

Now, let’s create a View to include all the data from the Accounts table.

CREATE VIEW Debit AS 
SELECT * FROM Accounts;
        
Image4

Step 5: Viewing a View

SELECT *FROM Debit;        


Image 5

You can check the View in your database tool, such as phpMyAdmin, just like you check any physical table. The View, however, does not store data physically; it retrieves it dynamically from the base table whenever accessed.


Image 6


Image 7

Advanced Examples

Creating a View with Specific Columns and Where Concept

You can create a View that includes only specific columns:

CREATE VIEW DebitGreater1000 AS 
SELECT Account_ID, Amount FROM Accounts WHERE Amount >1000;        


Image 8


Image 9

Summary

  • A View is a virtual table that helps you simplify and secure data access.
  • You can include specific columns or filter data using conditions while creating Views.
  • Views improve query readability, reduce complexity, and enhance data security.



Homini Udani

Sabaragamuwa University of Sri Lanka

3 个月

Very informative

回复
SHANIKA DILRUKSHI

Business Analyst | MERN Stack Developer | Aspiring Machine Learning Engineer | Researcher

3 个月

This is very useful.

要查看或添加评论,请登录

Kavindu Praneeth的更多文章

社区洞察

其他会员也浏览了