Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SQLite View

SQLite View (View)

A View is nothing more than a SQLite statement stored in the database under an associated name. A View is actually a combination of tables in the form of a predefined SQLite query.

A View can contain all the rows of a table or selected rows from one or more tables. A View can be created from one or more tables, depending on the SQLite query used to create the view.

A View is a virtual table that allows users to achieve the following:

SQLite Views are read-only, so it may not be possible to execute DELETE, INSERT, or UPDATE statements on a view. However, you can create a trigger on a view that fires when a DELETE, INSERT, or UPDATE is attempted on the view, with the required action defined in the trigger body.

Creating a View

SQLite views are created using the CREATE VIEW statement. SQLite views can be created from a single table, multiple tables, or other views.

The basic syntax of CREATE VIEW is as follows:



CREATE [TEMP | TEMPORARY] VIEW view_name AS

SELECT column1, column2.....

FROM table_name

WHERE [condition];

You can include multiple tables in a SELECT statement, much the same way as in a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is used, the view will be created in a temporary database.

Example

Assume the COMPANY table has the following records:



ID          NAME        AGE         ADDRESS     SALARY

----------  ----------  ----------  ----------  ----------

1           Paul        32          California  20000.0

2           Allen       25          Texas       15000.0

3           Teddy       23          Norway      20000.0

4           Mark        25          Rich-Mond   65000.0

5           David       27          Texas       85000.0

6           Kim         22          South-Hall  45000.0

7           James       24          Houston     10000.0

Now, here is an example of creating a view from the COMPANY table. The view selects only a few columns from the COMPANY table:



sqlite> CREATE VIEW COMPANY_VIEW AS

SELECT ID, NAME, AGE

FROM  COMPANY;

Now you can query COMPANY_VIEW in the same way you would query an actual table. Here is an example:



sqlite> SELECT * FROM COMPANY_VIEW;

This will produce the following result:



ID          NAME        AGE

----------  ----------  ----------

1           Paul        32

2           Allen       25

3           Teddy       23

4           Mark        25

5           David       27

6           Kim         22

7           James       24

Dropping a View

To drop a view, simply use the DROP VIEW statement with view_name the specified view. The basic syntax of DROP VIEW is as follows:



sqlite> DROP VIEW view_name;

The following command will drop the COMPANY_VIEW view we created earlier:



sqlite> DROP VIEW COMPANY_VIEW;