SQLite Views
A View is nothing more than an SQLite statement stored in the database with an associated name. A View is actually a combination of tables in the form of a predefined SQLite query.
A View can contain all 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 accomplish the following:
Users or user groups can find structured data in a more natural or intuitive way.
Restrict data access, so users can only see limited data rather than the complete table.
Summarize data from various tables to generate reports.
SQLite views are read-only, so you may not be able to execute DELETE, INSERT, or UPDATE statements on a view. However, you can create a trigger on a view, which fires when an attempt is made to DELETE, INSERT, or UPDATE the view, and the actions to be taken are defined in the trigger body.
Create View
SQLite views are created usingCREATE VIEWstatement. 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 the SELECT statement, in a manner very similar to a normal SQL SELECT query. If the optional TEMP or TEMPORARY keyword is used, the view will be created in a temporary database.
Examples
Suppose 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 only selects 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 a similar way to querying an actual table. Below 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
Drop View
To drop a view, simply use theview_nameDROP VIEW statement. The basic syntax of DROP VIEW is as follows:
sqlite> DROP VIEW view_name;
The following command will drop the COMPANY_VIEW view that we created earlier:
sqlite> DROP VIEW COMPANY_VIEW;Other Extensions