DEV Community

Harry Douglas
Harry Douglas

Posted on

What is a database view?

In database terminology, a view is a virtual table based on the result set of an SQL query.

Unlike a standard database table, a view does not store data on disk by default. Instead, it acts as a saved window or lens looking into one or more underlying base tables. Every time you query a view, the database runs the view's underlying SQL query behind the scenes and returns the fresh, real-time data.


How It Works

Think of a view as a saved bookmark of a query.

If you have a complex query that joins five tables together and performs calculations, you can package that logic into a view. Once created, you can treat that view just like a regular table in your SELECT statements.

+-------------------+      +-------------------+
|  orders Table     |      |  customers Table  |
+-------------------+      +-------------------+
          \                      /
           \                    /
            v                  v
       +----------------------------+
       |   VIEW: customer_orders    |  <-- Virtual Table (No data stored)
       +----------------------------+
                     |
                     v
           SELECT * FROM customer_orders;

Enter fullscreen mode Exit fullscreen mode

Why Use Views?

Views are one of the most useful tools in database design. Here are the main reasons to use them:

  • Simplification: They hide complex JOINs, GROUP BY aggregations, and messy conditional logic behind a simple SELECT * FROM view_name.
  • Security & Access Control: You can grant a user access to a view without giving them access to the underlying tables. For example, you can create a view that exposes a user's name and email while stripping out their password_hash and ssn.
  • Data Consistency: Rather than every developer writing their own query to calculate "Monthly Active Users," you write the logic once in a view so everyone uses the exact same definition.
  • Backward Compatibility: If you refactor or split a database table, you can create a view with the old table's structure so legacy applications won't break while transitioning.

Top comments (0)