SQLite study notes (five)

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

Outline

This article is structured as follows:

  • INSERT
  • UPDATE
  • DELETE
  • constraint

A, INSERT

INSERT for inserting rows (or added) to the database table. INSERT general form as follows:

INSERT INTO table_name (column_list) VALUES (value_list);

Column_list which part is not necessary. There are three ways to insert the following:

  • Insert complete row;
  • Inserting a portion of the line;
  • Insert the results for some queries.

1. Insert complete row

We are here to insert the Customers table, for example, first check its CREATE statement by .schema command:

sqlite> .schema Customers
CREATE TABLE Customers
(
  cust_id      char(10)  NOT NULL ,
  cust_name    char(50)  NOT NULL ,
  cust_address char(50)  NULL ,
  cust_city    char(50)  NULL ,
  cust_state   char(5)   NULL ,
  cust_zip     char(10)  NULL ,
  cust_country char(50)  NULL ,
  cust_contact char(50)  NULL ,
  cust_email   char(255) NULL ,
  PRIMARY KEY (cust_id)
);

It can be seen that a total of nine fields, where cust_id its primary key. Insert the whole line is as follows:

INSERT INTO Customers 
VALUES ( '1000000006', 
		 'Toy Land', 
		 '123 Any Street',
		 'New York', 
		 'NY', 
		 '11111', 
		 'USA',
		 NULL,
		 NULL);

This statement will insert a new customer to the Customers table. Storing the data in each column of the table given in VALUES clause, you must provide a value for each column. If a column value is not allowed to be empty and then filled to NULL. Each column must be filled in the order they appear in the definition table.

The syntax for this column_list omitted although very simple, but it is not safe, it is highly dependent on the definition of the order of columns in the table, if a schedule change in the structure, then its insertion will fail, we should try to be of the form insert data:

INSERT INTO Customers 
(	cust_id,
	cust_name,
 	cust_address,
  	cust_city,
 	cust_state,
 	cust_zip,
 	cust_country,
  	cust_contact,
 	cust_email)
VALUES ( '1000000006', 
		 'Toy Land', 
		 '123 Any Street',
		 'New York', 
		 'NY', 
		 '11111', 
		 'USA',
		 NULL,
		 NULL);

Although such an approach is cumbersome, but because they do not depend on the definition of the relationship between the order of columns in the table, it will be more secure.

2. Insert row portion

The recommended method is to use INSERT explicitly given column_list, but it also means that we can omit the column, just give the value of some columns, the following example shows:

INSERT INTO Customers 
(	cust_id,
	cust_name,
 	cust_address,
  	cust_city,
 	cust_state,
 	cust_zip,
 	cust_country)
VALUES ( '1000000006', 
		 'Toy Land', 
		 '123 Any Street',
		 'New York', 
		 'NY', 
		 '11111', 
		 'USA');

We have omitted the line cust_contact and cust_email field values, these fields will be filled with the omitted NULL value.

Note: The
premise of the column can be omitted definition table is allowed, can be omitted columns must meet one of the following conditions:

  • The column is defined to allow NULL.
  • The default value is given in the table definition. This means that if the value is not given, the default value.

3. Insert the result of some queries

In addition INSERT insert data line by line, but you can also use the results of a SELECT statement into a table. Examples are as follows:

We create a new table CustNew, as follows:

CREATE TABLE CustNew( 
  cust_id      char(10)  NOT NULL ,
  cust_name    char(50)  NOT NULL ,
  cust_address char(50)  NULL ,
  cust_city    char(50)  NULL ,
  cust_state   char(5)   NULL
 );

At this point we will Customers table data is inserted into the same field in CustNew, as follows:

INSERT INTO CustNew (
	cust_id,
	cust_name,
	cust_address,
	cust_city,
	cust_state) 
SELECT 
cust_id,
cust_name,
cust_address,
cust_city,
cust_state 
FROM Customers;

Of course, we can also filter the data by SELECT we need to add these to see our specific needs.


二、UPDATE

UPDATE used to update the data, its use in two ways:

  • Update a specific row in the table;
  • Update all rows in the table.

UPDATE general form as follows:

UPDATE table_name SET update_list WHERE predicate;

Wherein one or more update_list "field Assignment" list format column_name = value.

Note:
When using UPDATE's WHERE clause must not forget, little attention will be very easy to update all the rows in the table.

Examples are as follows:

UPDATE Customers 
SET cust_email = '[email protected]' 
WHERE cust_id = '1000000005';

This statement indicates that the update for the cust_id 100000005cust_email line is [email protected].

If you want to update multiple columns, then just continue to add the column to be updated after the SET, as follows:

UPDATE Customers 
SET cust_contact = 'Sam Roberts' 
	cust_email = '[email protected]' 
WHERE cust_id = '1000000006';

Three, DELETE

DELETE for deleting data, its use in two ways:

  • Delete specific rows in the table;
  • Delete all the rows in the table.

DELETE and UPDATE using somewhat similar manner, its general form:

DELETE FROM table_name WHERE predicate;

example:

DELETE FROM Customers WHERE cust_id = '1000000006';

The statement is executed, we will be inserted before the data is deleted.

Note:
When using the DELETE WHERE clause must not forget, little attention will be very easy to delete all the rows (delete library on foot) table.


Third, the constraints

Constraint definition part of the table, and fields which may be defined or custom entity table associates. Constraint types are as follows:

  • not null
  • unique
  • primary key
  • foreign key
  • check
  • collate

1. not null

If you do not want to appear above the NULL value of a field, you can use not null constraint, which can ensure that the value of this field is not NULL. INSERT statements can not insert a field to NULL, UPDATE statement can not set the value of the existing field to NULL.

If the field is not null constraint use and the presence of unknown value, then it is recommended to set a default value for the field, such as the following phone field, when the number is unknown, it will be set to the default value UNKNOWN.

CREATE TABLE Contacts
(
	id integer PRIMARY KEY,
	name text not null,
	phone text not null DEFAULT 'UNKNOWN',
	unique(name, phone)
);

INSERT INTO Contacts (name) VALUES('Marck');

When the image shown above INSERT statement to insert data, the value of the phone field will be UNKNOWN, the following results:

sqlite> SELECT * FROM Contacts;
id          name        phone
----------  ----------  ----------
1           Marck      UNKNOWN

2. unique

The only constraint is called unique, it requires the same value or a different set of fields is located. If repeated attempts to insert a value, or a value updated to a value will lead to a constraint of the presence of illegal, and terminates the operation. As follows:

sqlite> INSERT INTO Contacts (name, phone) VALUES ('Marck', 'UNKNOWN');
Error: UNIQUE constraint failed: Contacts.name, Contacts.phone

Uniqueness constraint may be defined in a field or table level. When the table level definition can be applied to a plurality of unique fields, e.g. Contacts only constraint is that the table level:

CREATE TABLE Contacts
(
	id integer PRIMARY KEY,
	name text not null,
	phone text not null DEFAULT 'UNKNOWN',
	unique(name, phone)
);

This uniqueness constraint name and phone fields indicate that a combination of unique constraints.

Note:
defined as a field theoretically unique constraints can be placed in any number of NULL values. Because the NULL value is not equal to any value, including NULL value. This is also the basis for handling SQLite is defined as the unique field to NULL.

3. primary key

In SQLite in the definition of a table always determine a primary key, regardless of whether or not we have our own definition. This field is a 64-bit integer field, or referred rowid rowid or oid. Its default value is automatically generated in accordance with the order of increasing, SQLite primary key field provides automatic growth characteristics.

If the primary key column, SQLite will create a default value for the field is integer primary key, which is the default value to ensure that only an integer value. The fact is, rowid field aliases, they refer to the same value. 9223372036854775807 rowid is maximum.

If you add autoincrement behind the integer primary key, SQLite will prevent recovery of rowid. When creating a table, if the field contains autoincrement constraints, SQLite will record the maximum value of the field in the system table named in sqlite_sequence. Behind the INSERT statement only to use than the current value of the larger, if the maximum value reached behind the INSERT statement will complain. Examples are as follows:

CREATE TABLE Maxed_out
(
	id integer PRIMARY KEY AUTOINCREMENT,
	x text
);

INSERT INTO Maxed_out VALUES(9223372036854775807, 'Marck');

We insert data id field for the maximum allowed, then we look at the system tables sqlite_sequence:

sqlite> SELECT * FROM sqlite_sequence;
name        seq
----------  -------------------
Maxed_out   9223372036854775807

Then insert a data again:

sqlite> INSERT INTO Maxed_out (x) VALUES('Beryl');
Error: database or disk is full

At this point SQLite will error. While preventing rowid autoincrement recovery is reflected in the following example:

DROP TABLE Maxed_out;
CREATE TABLE Maxed_out
(
	id integer PRIMARY KEY AUTOINCREMENT,
	x text
);
INSERT INTO Maxed_out VALUES(100, 'Marck');

First reconstruction of the original table is then deleted, and then inserting a new data, the main key field 100 value. At this time sqlite_sequence follows:

name        seq
----------  ----------
Maxed_out   100

Then delete the row data, and then re-insert a new data:

DELETE FROM Maxed_out WHERE id = 100;
INSERT INTO Maxed_out (x) VALUES('Beryl');

View data:

id          x
----------  ----------
101         Beryl

You can see the newly inserted data from 1 101 rather than from the beginning. Primary key constraint may also be applied to the same and unique on a table, as shown in the following example:

CREATE TABLE pkey
(
	x text, 
	y text, 
	primary key(x, y)
);

Its role is similar and unique, not repeat them here.

4. foreign key

foreign key is also known as a foreign key constraint, it is extremely important to ensure that references to the integrity of the part. It ensures that the key of a table to be referenced from another table. And the data must be physically in another table.

Note:
You must open when using SQLite foreign key constraint, the foreign key constraint is disabled by default:
PRAGMA foreign_keys = on;

Foreign key general form as follows:

CREATE TABLE table_name
(
	column_definition REFERENCES foreign_table(column_name) 
	ON {DELETE | UPDATE} integrity_action 
	[not] deferrable [initially {deferred | immediate},  
);

Next comes the respective roles of these keywords:

  • REFERENCES Represents a reference, the latter foreign_table (column_name) represents the table and field references.
  • ON {DELETE | UPDATE} integrity_action Expressed strategy when deleting or updating, integrity_action values ​​as follows:
    • null SET : if the parent value is deleted or does not exist, the remaining sub-values to null.
    • default the SET : value is deleted or if the parent does not exist, the remaining sub-value to the default value.
    • Cascade : When updating the parent values, update the value of all the sub-predict match. When you delete a parent values, remove all child values.
    • the restrict : update or delete the parent values may appear isolated sub-value, thereby preventing the transaction.
    • NO Action : non-interference in the operation to perform, observe the only change. Throughout the end of the sentence report an error.
  • deferrable Control clause defined constraints enforced immediately or delayed until the end of the entire transaction.

Foreign key to help prevent accidental deletion
After defining the foreign key, DBMS can not delete rows associated with a row in another table. For example, you can not delete customer-related orders. The only way to remove the customer is to first delete the associated orders. Due to the need to delete a series, and thus the use of foreign key can prevent accidental deletion of data.

Here is a simple example of a foreign key constraint:

CREATE TABLE Orders2
(
	order_num  integer  NOT NULL PRIMARY KEY,
	order_date DATETIME NOT NULL,
	cust_id    CHAR(10) NOT NULL REFERENCES Customers(cust_id)
);

Then check what Orders2 inside the data:

order_num   order_date  cust_id
----------  ----------  ----------
20005       2012-05-01  1000000001
20006       2012-01-12  1000000003
20007       2012-01-30  1000000004
20008       2012-02-03  1000000005
20009       2012-02-08  1000000001

There can be seen a total of five pieces of data, cust_id values ​​are derived from the value of the cust_id field of Customers. The next attempt to delete the value in Customers cust_id 100000001 as follows:

sqlite> DELETE FROM Customers WHERE cust_id = '1000000001';
Error: FOREIGN KEY constraint failed

It can be seen deleted failed to verify the above conclusion. Next, look at a more complex example foreign keys:

CREATE TABLE Orders3 
(
	order_num  integer  NOT NULL PRIMARY KEY,
	order_date DATETIME NOT NULL,
	cust_id    CHAR(10) NOT NULL REFERENCES Customers(cust_id)
	on delete restrict 
	deferrable initially deferred
);

According to the previous description we can see that:

  • Customers cited the cust_id field cust_id;
  • If you will have time to delete orphaned child the value of the transaction is terminated;
  • This clause defines the constraints delayed until the end of the entire transaction is executed.

5. check

defined check constraint allows expression to test field values ​​to be inserted or updated. If not set the standard expression, it will be given, as shown in the following example:

CREATE TABLE Contacts 
(
	id integer PRIMARY KEY,
	name text NOT NULL,
	phone text NOT NULL DEFAULT 'UNKNOWN',
	unique(name, phone),
	check(length(phone) >= 7)
); 

sqlite> INSERT INTO contacts VALUES(1, 'Marck', '10086');
Error: CHECK constraint failed: Contatcts

Since the phone can be seen that the length of the data field value of less than 7 is inserted, the insertion fails. check constraint all fields are evaluated before the modification occurs, you want to change the value of success, constraint expression must be determined to be true.

6. collate

Collation key collate custom fields. There are three built-in SQLite collation:

  • binary: the binary collation, which is the default collation, using the C function memcmp () byte for byte comparison text values.
  • nocase: non-case-sensitive sorting algorithm.
  • In contrast to the binary sort algorithm: reverse.

We now redefine once Contacts, and insert a piece of data, as follows:

CREATE TABLE Contacts 
(
	id integer PRIMARY KEY,
	name text NOT NULL collate nocase,
	phone text NOT NULL DEFAULT 'UNKNOWN',
	unique(name, phone)
);
INSERT INTO Contacts VALUES(1, 'Marck', '10086');

At this point we have a Contacts table data, as shown below:

id          name        phone
----------  ----------  ----------
1           Marck       10086

At this point we insert a piece of data:

sqlite> INSERT INTO Contacts VALUES (2, 'MARCK', '10086');
Error: UNIQUE constraint failed: Contacts.name, Contacts.phone

We can see the error occurred. The reason is based on the collation name field, the name is case insensitive, so "MARCK" and "Marck" is the same value already exists in the table, so the data violates the insert uniqueness constraint.


reference

"SQLite Definitive Guide"

  • Chapter 4 sqlite Advanced sql

"SQL must know will be"

  • Lesson 15 insert data
  • Lesson 16 update and delete data
  • Lesson 22 Advanced SQL Features

Guess you like

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