Академический Документы
Профессиональный Документы
Культура Документы
In this part of the SQLite tutorial, we will mention views, triggers and transactions.
Views
A view is a specific look on data in from one or more tables. It can arrange data in some specific order,
higlight or hide some data. A view consists of a stored query accessible as a virtual table composed of
the result set of a query. Unlike ordinary tables a view does not form part of the physical schema. It is a
Id Name Cost
1 Audi 52642
2 Mercedes 57127
3 Skoda 9000
4 Volvo 29000
5 Bentley 350000
6 Citroen 21000
7 Hummer 41400
8 Volkswagen 21600
sqlite> CREATE VIEW CheapCars AS SELECT Name FROM Cars WHERE Cost < 30000;
Name
----------
Skoda
Volvo
Citroen
Volkswagen
sqlite> .tables
sqlite> .tables
Technically a view is a virtual table. So we can list all views with a .tables command. To remove a
Triggers
Triggers are database operations that are automatically performed when a specified database event
occurs.
In the following example, we will use the Friends table and create a new Log table.
CREATE TABLE Log(Id integer PRIMARY KEY, OldName text, NewName text, Date text);
We will create 2 new tables for the next example with triggers.
BEGIN
END;
We create a trigger called mytrigger with the CREATE TRIGGER statement. This trigger will launch a
INSERT statement whenever we update the name column of the Friends table. The INSERT statement
will insert the old name, the new name and the time stamp into the Log table.
sqlite> SELECT * FROM Friends;
Id Name Sex
1 Jane F
2 Thomas M
3 Franklin M
4 Elisabeth F
5 Mary F
6 Lucy F
7 Jack M
We check the Log table. This log confirms the update operation we performed.
Transactions
A transaction is an atomic unit of database operations against the data in one or more databases. The
effects of all the SQL statements in a transaction can be either all committed to the database or all
rolled back.
In SQLite, any command other than the SELECT will start an implicit transaction. Manual transactions
are started with the BEGIN TRANSACTION statement and finished with the COMMIT OR ROLLBACK
statements.
BEGIN TRANSACTION;
COMMIT;
Here we have a sample transaction. A transaction begins with BEGIN TRANSACTION and ends with
COMMIT.
We have a NOT NULL constraint set on the Id column. Thus, the fourth insert will not succeed. SQLite
does transactions specifically. For some errors, it reverts all changes. For others, it reverts only the last
statement and leaves other changes intact. In our case, the table is created and the first three inserts
Say, we already had an empty table named Test. Executing the above transaction would fail
completely. No changes would be written. If we changed the CREATE TABLE statement into CREATE
BEGIN TRANSACTION;
ROLLBACK;
A transaction can end with a COMMIT or a ROLLBACK statement. The ROLLBACK reverts all changes.
In this part of the SQLite tutorial, we have worked with views, triggers and transactions in SQLite.