SQLite study notes (six)

Disclaimer: This article is a blogger original article, please indicate the source: https://blog.csdn.net/qq_38182125/article/details/89453107

Outline

The structure of this article is as follows:

  • View (View)
  • Index (Index)
  • Trigger (Trigger)
  • Transaction (Transaction)

A view

View (View) or virtual table, also called a derived table, its contents are derived from the results of other tables. Although the view looks like a basic table, but it is not a base table, because the content of the base table is long-lasting, and the content view is that when using dynamically generated. Create view syntax is as follows:

CREATE VIEW name AS select-stmt;

Name of the view specified by name, which is defined by the defined select-stmt. The final generated view looks like the name of the base table name. We tend to use view on the following grounds:

  • Reuse SQL statements.
  • Simplify complex SQL operations. After writing queries, you can easily reuse it without knowing its basic query details.
  • Part instead of the entire table using a table.
  • Protect data. You can grant permissions for access to a specific part of the table, rather than access to the entire table.
  • Change the data format and presentation. May return a different view of the table represents the underlying data and format.

The following examples look at a retrieval of data:

SELECT cust_name, cust_contact 
FROM Customers, Orders, OrderItems 
WHERE Customers.cust_id = Orders.cust_id 
AND OrderItems.order_num = Orders.order_num 
AND prod_id = 'RGAN01';

This example join the three tables, and retrieve customer information prod_id as "RGAN01" of. And if we need to retrieve prod_id as "DLL01" of customer information, on top of a long list of command had to re-enter it again, this time, we can consider with a view to possible use of reusable parts together. As follows:

CREATE VIEW ProductCustomers AS 
SELECT cust_name, cust_contact, prod_id  
FROM Customers, Orders, OrderItems 
WHERE Customers.cust_id = Orders.cust_id 
AND OrderItems.order_num = Orders.order_num;

After you create the view, we can use this view as follows:

Input:

SELECT cust_name, cust_contact 
FROM ProductCustomers 
WHERE prod_id = 'RGAN01';

Output:

cust_name   cust_contact
----------  ------------------
Fun4All     Denise L. Stephens
The Toy St  Kim Howard

By view, we can omit some SQL statements, and improve its reusability, if we want to query customers prod_id as "DLL01", you do not need as much input as before the SQL statement.

Note:
SQLite updatable view is not supported, in other words only SQLite use a view in the search.
Should try to create a view when considering their reusability, create a view is not bound to specific data is often a good choice.

If you need to remove a view, simply execute the following command:

DROP VIEW ProductsCustomers;

Second, the index

Index (Index) is a structure under certain conditions used to speed up queries. Existing retrieval follows:

SELECT cust_name, cust_contact 
FROM Customers 
WHERE cust_id = '100000002';

Under normal circumstances, the database sequential scans, all the rows one by one in the search table, the compliance cust_id '1000000002' = output statement. But if the Customers table is very large, then this way of retrieving data will become very inefficient, then we can consider ways to accelerate the use of the index retrieval speed, SQLite underlying the use of B-tree indexing.

Create index command as follows:

CREATE INDEX [UNIQUE] index_name ON table_name (columns);

Index_name is the name of the index variables, including the field where table_name is the name of the index table, the variable columns is a field or fields in a comma-separated.

If you use keyword UNIQUE, will add constraints on the index, all values ​​in the index must be unique. This applies not only to the index, also applies to the field where the index. Examples are as follows:

sqlite> CREATE TABLE Foo(a text, b text);
sqlite> CREATE UNIQUE INDEX Foo_idx ON Foo(a,b);
sqlite> INSERT INTO Foo VALUES('unique', 'value');
sqlite> INSERT INTO Foo VALUES('unique', 'value1');
sqlite> INSERT INTO Foo VALUES('unique', 'value');
Error: UNIQUE constraint failed: Foo.a, Foo.b

We can see from the error message, when the joint field value duplication, it will error. If you want to remove the index, use the DROP INDEX command:

DROP INDEX Foo_idx;

note:

  • Although indexes can speed up our search speed, but the index data may have to take up a lot of storage space, especially if all the fields in a multi-table indexes are created, the size of the table may double.
  • Another issue to consider is the index maintenance. When insert, update and delete operations, in addition to modify the table, the database need to be modified corresponding to the index, the index may be reduced if it is insert, update and the like of the operation speed.
  • Finally, when defining multiple columns in the index (for example, states and cities). This index is only useful when sorting order to the state plus cities. If you want to sort by city, this index is not useful.

1. Use Index

SQLite has some specific conditions to determine whether to use the index. The following expressions will appear in the WHERE clause. SQLite will use a single index field.

column { = | > | >= | <= | < } expression
expression { = | > | >= | <= | < } column
column IN (expression-list)
column IN (subquery)

The following few examples illustrate, assume that the table is defined as follows:

CREATE TABLE foo (a,b,c,d);

At this point the index to create more of the following fields:

create index foo_idx on foo(a,b,c,d);

Now follows Search:

SELECT * FROM foo WHERE a=1 AND b=2 AND d=3;

Only the first and second conditions will use the index. Reason not to use third condition is no condition to use c to narrow the gap d. SQLite left to right use when using multiple-field indexes intelligently field, which began from the left side of the field, use the query field, then move to the second field, and so on, until the WHERE clause can not find effective conditions.

SELECT * FROM foo WHERE a>1 AND b=2 AND c=3 AND d=4;

SQLite index scan will be carried out on the field a, the expression a> 1 index field called the far right, because it uses inequality . Similarly, the following statement will stop at b> 2:

SELECT * FROM foo WHERE a=1 AND b>2 AND c=3 AND d=4;

All in all, create an index must have a good reason to ensure improved performance can be achieved, otherwise there may be negative optimization.


Third, the flip-flop

Trigger (Trigger) executed automatically when a specific database activity occurs. It may trigger on a specific table INSERT, UPDATE, and the DELETE (or combination) associated operations. General to create a trigger command as follows:

CREATE [TEMP|TEMPORARY] TRIGGER trigger_name 
[BEFORE|AFTER] [INSERT|DELETE|UPDATE|UPDATE OF columns] ON table_name 
BEGIN 
	-- trigger logic goes here...
END;

Triggers are by name, behavior and table definitions. Conduct a series of SQL commands which, when certain events occur, the trigger is responsible for initiating these commands. You can also specify these keyword before or after the operation is performed after or before the occurrence of the incident. Wherein creating UPDATE trigger on the table can be a column or more designated fields.

Here are some common uses of triggers:

  • Ensure data consistency. For example in the INSERT or UPDATE operation State all converted to uppercase.
  • Based on changes in a table on the implementation of activities in other tables. For example, whenever a row to update or delete audit trail records written to a log table.
  • Additional data needed to verify and rollback. For example, to ensure that a customer does not exceed the limit of available funds, if you have exceeded the blocking insert.
  • Update timestamp value or computed column.

The following is a simple example of trigger:

CREATE TABLE Company
(
	id      integer PRIMARY KEY,
	name    text NOT NULL,
	address text NOT NULL
);

CREATE TABLE log(
	emp_id integer, 
	emp_date text
);

Create two tables, a table base and table Company log for a recording operation. Next, create a trigger:

CREATE TRIGGER log_trigger AFTER INSERT ON Company 
BEGIN 
	INSERT INTO log VALUES(new.id, datetime('now'));
END;

After we tried to create a trigger effect next few insert data validation:

INSERT INTO Company VALUES(null, 'Baidu', 'Beijing');
INSERT INTO Company VALUES(null, 'Alibaba', 'HangZhou');
INSERT INTO Company VALUES(null, 'Tencent', 'ShenZhen');

SELECT * FROM log;

emp_id      emp_date
----------  -------------------
1           2019-04-23 01:18:30
2           2019-04-23 01:18:45
3           2019-04-23 01:18:47

Can be seen, we can record time via the trigger insert operation to save the log information to the corresponding table.

Note:
In other DBMS can support for each row trigger that is also supported for each statement trigger. But only SQLite support for each row trigger, that is, operating statements for each affected row when he triggered once.

If you want to list the trigger, you can help sqlite_master:

SELECT name FROM sqlite_master WHERE type = 'trigger';

name
-----------
log_trigger

Delete trigger equally simple:

DROP TRIGGER log_trigger;

Fourth, the transaction

SQLite support services operation, support transactional operations means that the database must support the four properties ACID transactions.

characteristic description
Atomicity (Atomicity) Atomicity refers to all operations in the transaction included either all succeed, or all fail to roll back, that is, if the operation succeed, they must complete the application transaction to the database, otherwise it can not have any impact on the database
Consistency (Consustency) Consistency refers to the transaction must transform the database from one consistent state to another consistent state, that is, before and after a transaction execution and implementation must be in a consistent state
Isolation (Isolation) Isolation when a plurality of users concurrent access to the database, such as operating with a table, a database for each user transaction open, the other can not be firm interference, to isolation between a plurality of concurrent transactions
Persistent (Durability) Persistence means that once a transaction is committed, then changes to the data in the database are permanent, even in the case of failure of the database system was not operating loss of committed transactions

1. Command affairs

Affairs are controlled by three commands: begin, commit and rollback. begin open a transaction, all operations can begin after the cancellation, it did not issue a commit if the connection is terminated before will be canceled. commit the transaction began committing all operations performed. The rollback is to restore operations after all begin. E.g:

sqlite> begin;
sqlite> DELETE FROM Products;
sqlite> rollback;
sqlite> SELECT count(*) FROM Products;

count(*)
----------
9

This example opens a transaction carried out in a rollback deletes all the data in the Products then, so the query again when the data still exists Products.

By default, SQLite in each SQL statement from the transaction to (Auto Commit mode). In other words, SQLite default each individual SQL statements have begin ... commit / rollback of the transaction, in which case, all successful command will automatically be submitted, failing command is rolled back, this mode of operation is also known as automatic commit mode.

2. Use the reserved spot

SQLite support savepoint and release orders, the work comprises multiple statements can be set savepoint, roll back can return to a savepoint. Create a savepoint command is as follows:

savepoint savepoint_name;

If aware of the need to fall back to somewhere, do not roll back the entire transaction, rollback can use the following command:

rollback [transaction] to savepoint_name;

An example to show under its use, first of all let's take a look at the Customers table information for subsequent comparison:

sqlite> select cust_id, cust_name from Customers;
cust_id     cust_name
----------  ------------
1000000001  Village Toys
1000000002  Kids Place
1000000003  Fun4All
1000000004  Fun4All
1000000005  The Toy Stor

Then we execute transactions contain retention points:

begin;
INSERT INTO Customers(cust_id, cust_name) VALUES('1000000010', 'Toys Emporium');
savepoint one;
INSERT INTO  Customers(cust_id, cust_name) VALUES('1000000008', 'Toys Moyu');
INSERT INTO  Customers(cust_id, cust_name) VALUES('1000000007', 'Toys JKLove');
rollback to one;
commit;

Theoretically after the implementation of the transaction is rolled back to one point this reservation, which is actually only cust_id inserted into this data 1000000010, let's see whether such a query by:

sqlite> select cust_id, cust_name from Customers;
cust_id     cust_name
----------  ------------
1000000001  Village Toys
1000000002  Kids Place
1000000003  Fun4All
1000000004  Fun4All
1000000005  The Toy Stor
1000000010  Toys Emporiu

You can really only see the newly inserted a sentence, which is roughly the savepoint usage.

release command for releasing the retention point, release needs to be performed in the savepoint will not be used to determine when, for example, the following transactions will generate an error:

begin;
INSERT INTO Customers(cust_id, cust_name) VALUES('1000000010', 'Toys Emporium');
savepoint one;
INSERT INTO  Customers(cust_id, cust_name) VALUES('1000000008', 'Toys Moyu');
INSERT INTO  Customers(cust_id, cust_name) VALUES('1000000007', 'Toys JKLove');
release one;
rollback to one;
commit;

Error: no such savepoint: one

In the latter case will be reserved to the use of one point one of the first to be release, it will cause the following rollback statement can not be found in one case.

3. Conflict Resolution

When a constraint violation will result in termination of the transaction. In addition to the termination of the consequences of simply modified before the abolition of all (which is handling most of the database), SQLIte provides the following options:

Tactics description
replace When a unique constraint violation, SQLite will result in a violation of this record deleted to insert a new record or modifications alternative, SQLite continue; if the violation is not null constraints and the field is no default, SQLite application abort strategy
ignore When a constraint violation occurs, SQLite allows the command to continue execution, constraint violations remain the same, but before and after it will continue to modify records
fail When a constraint violation occurs, SQLite termination command, but does not recover before the constraint violation has been modified records
abort When a constraint violation occurs, SQLite command to restore all changes made and terminating command. SQLite is the default abort all operations solutions
rollback When a constraint violation occurs, SQLite performs a rollback - terminate the current command and the entire transaction

Conflict resolution syntax is as follows:

INSERT OR resolution INTO table_name (column_list) VALUES (value_list);
UPDATE OR resolution table_name SET (value_list) WHERE predicate;

Following through an example to do an exemplary use of it, we have assumed the following table:

CREATE TABLE test(id integer PRIMARY KEY);
SELECT count(*) FROM test;

count(*)
----------
412

It contains a total of 412 rows of data, data 1 to 412. Now do the following update:

UPDATE test SET id=800-id;
Error: UNIQUE constraint failed: test.id

We can see it violates the uniqueness constraint, because when the UPDATE statement to update the first 388 records, it will view id updated to 800-388 = 412, but the 412 already present in the test, so the command is terminated. According to the previous analysis, we know that it is the default execution abort strategy, that is to say in front of 377 successful update records will be canceled.

If we wish to retain 377 the previous record can be updated successfully, we can enter the following command:

UPDATE OR FAIL test SET id=800-id;

By setting policies fail, you can change the front of the 377 records preserved.


reference

"SQLite Definitive Guide"

  • Chapter 4 sqlite Advanced sql

"SQL must know will be"

  • Lesson 18 Using Views
  • Lesson 20 Transaction Management
  • Lesson 22 Advanced SQL Features

I hope this article to help you ~

Guess you like

Origin blog.csdn.net/qq_38182125/article/details/89453107