当前位置:网站首页>Kingbasees SQL language reference manual of Jincang database (9. Common DDL clauses)
Kingbasees SQL language reference manual of Jincang database (9. Common DDL clauses)
2022-07-26 05:44:00 【Thousands of sails passed by the side of the sunken boat_】
9. common DDL Clause
This document describes what appears in SQL Some common data definition clauses in statements . Contains the following sections :
9.1. Constraint clause
purpose
SQL Allows us to define constraints on columns and tables . Constraints allow us to control the data in the table according to our wishes . If a user tries to save data in a column that violates a constraint , An error will be thrown .
Constraint clauses usually appear in the following statements :
CREATE TABLESpecify constraints on table columns when creating tables .
ALTER TABLEAdjustment of existing tables .
CREATE VIEWWhen creating a view .
ALTER VIEWWhen adjusting the view .
Constraint name
CONSTRAINTIs the keyword used when naming constraints , Please use before the constraint name , Put the constraint definition after the name . If the constraint name is not specified in this way , The system will automatically name the constraint .Such as
constraintname:CREATE TABLE distributors ( did integer, name varchar(40), CONSTRAINT constraintname CHECK (did > 100 AND name <> '') );
Common types of constraint clauses are :
NOT NULLThis column is not allowed to contain null values .
NULLThis column is allowed to contain null values . This is the default .
This clause is only provided with non-standard SQL Database compatibility . It is not recommended to use in new applications .
CHECK ( expression) [ NO INHERIT ]
CHECKSpecify an expression that produces a boolean result , If an insert or update operation is to succeed , The new or updated row must satisfy the expression . To calculate the TRUE or UNKNOWN The expression of will succeed . As long as any row of an insert or update operation is generated FALSE result , An error exception will be reported and the insert or update will not modify the database . A check constraint specified as a column constraint should only refer to the value of that column , An expression that appears in a table constraint can reference multiple columns .At present ,
CHECKExpressions cannot contain subqueries , You cannot reference variables other than the columns of the current row . You can reference system columnstableoid, But you cannot reference other system columns .One is marked
NO INHERITThe constraint of will not be propagated to the sub table .When a table has multiple
CHECKWhen restrained , Check outNOT NULLAfter restraint , Each row is checked in alphabetical order of their names ( V8.3 pre-release KingbaseES aboutCHECKThe constraint does not follow any specific firing order ).
UNIQUE( Column constraints )UNIQUE ( column_name[, ... ] ) [ INCLUDE (column_name[, ...]) ] ( Table constraints )
UNIQUEConstraints specify that a group of one or more columns in a table contains unique values . The behavior of a unique table constraint is the same as that of a column constraint , Only table constraints can span multiple columns .For the purpose of a unique constraint , Null values are not considered equal .
Each unique table constraint must name a set of columns , And it is different from the column set named by any other unique or primary key constraint on the table ( Otherwise it will be a constraint that has been enumerated twice ).
When establishing unique constraints for multi-level partition hierarchies , All columns of the partition key of the target partition table must be included in the constraint definition , And the columns of all its descendant partition tables .
Adding a unique constraint will automatically create a unique btree Indexes . Optional clause
INCLUDEAdd to one or more columns of the index , Uniqueness is not enforced on these columns . Be careful , Although constraints are not forced to be included on columns , But it still depends on them . therefore , Some operations on these columns ( for exampleDROP COLUMN) It may cause cascading constraints and index deletion .
PRIMARY KEY( Column constraints )PRIMARY KEY ( column_name[, ... ] ) [ INCLUDE (column_name[, ...]) ] ( Table constraints )
PRIMARY KEYConstraints specify that one or more columns of a table can only contain unique ( No repetition )、 Non empty value . Only one primary key can be specified on a table , It can be used as a column constraint or a table constraint .The column set involved in the primary key constraint should be different from the column set of any unique constraint defined on the same table ( otherwise , This unique constraint is redundant and will be discarded ).
PRIMARY KEYMandatory data constraints can be seen asUNIQUEandNOT NULLThe combination of , However, identifying a group of columns as primary keys also provides metadata for schema design , Because the primary key identifies that other tables can rely on this column set as the unique identifier of rows .
PRIMARY KEYConstraints and placed on the partition tableUNIQUESame constraint .add to
PRIMARY KEYThe constraint will automatically create a unique btree Indexes . OptionalINCLUDEClause allows you to specify a list of columns , These columns will be included in the non key part of the index . Although uniqueness is not enforced for contained columns , But constraints still depend on them . therefore , Some operations on the included columns ( for exampleDROP COLUMN) It may cause cascading constraints and index deletion .
EXCLUDE [ USING index_method] (exclude_elementWITHoperator[, ... ] )index_parameters[ WHERE (predicate) ]
EXCLUDEClause defines an exclusion constraint , It guarantees that if any two rows use the specified operator to compare on the specified column or expression , Not all comparisons will returnTRUE. If all specified operators test for equality , This is equivalent to aUNIQUEconstraint , Although an ordinary unique constraint will be faster . however , Exclusion constraints can specify constraints that are more general than simple equality . for example , You can use&&Operator specifies a constraint , It is required that no two rows in the table contain circles that cover each other ( see Geometric type ).Exclusion constraints are implemented using an index , In this way, each specified operator must be associated with the index access method ``index_method`` An appropriate operator class for ( see Operator classes and operator families ) Related to . Operators are required to be commutative . every last ``exclude_element`` You can optionally specify an operator class or order option , These in CREATE INDEX There is a complete description in .
The access method must support
amgettuple, Now that means GIN Can't use . Despite permission , But use in an exclusion constraint B- A tree or hash index makes no sense , Because it can't do better than an ordinary unique index . So in practice, access methods will always GiST or SP-GiST.``predicate`` Allows you to specify an exclusion constraint on a subset of the table . Internally, this will create a partial index . Note that parentheses around this are necessary .
REFERENCES reftable[ (refcolumn) ] [ MATCHmatchtype] [ ON DELETEreferential_action] [ ON UPDATEreferential_action] ( Column constraints )FOREIGN KEY ( column_name[, ... ] ) REFERENCESreftable[ (refcolumn[, ... ] ) ] [ MATCHmatchtype] [ ON DELETEreferential_action] [ ON UPDATEreferential_action] ( Table constraints )These clauses specify a foreign key constraint , It requires that a column or group of columns in the new table must only contain values that match a row of the referenced table on the referenced column . If ``refcolumn`` The list is ignored , Will use ``reftable`` Primary key of . The referenced column must be a non delayable unique constraint or primary key constraint column in the referenced table . The user must be in the referenced table ( Or the entire table or a specific reference column ) Owned on
REFERENCESjurisdiction . Adding a foreign key constraint requires an exclusive lock on the related table . A value inserted into the reference column will match the value of the referenced table with the given matching type . There are three matching types :MATCH FULL、MATCH PARTIALas well asMATCH SIMPLE( This is the default ).MATCH FULLOne column of a multi column foreign key will not be allowed to be empty , Unless all foreign key columns are empty ; If they are all empty , The row is not required to have a match in the referenced table .MATCH SIMPLEAllow any foreign key column to be empty , If either is empty , The row is not required to have a match in the referenced table .MATCH PARTIALIt has not been realized yet ( Of course ,NOT NULLConstraints can be applied to reference columns to organize these situations ).in addition , When the data in the referenced column is changed , Specific actions can be performed on the data in the columns of this table .
ON DELETESpecify the action to be performed when a referenced row in the referenced table is deleted . Again ,ON UPDATESpecify the action to be performed when a referenced column in the referenced table is updated with a new value . If the row is updated , But the referenced column is not actually changed , Not doing anything . exceptNO ACTIONReference actions outside the check cannot be delayed , Even if the constraint is declared to be delayable . There may be the following actions for each clause :
NO ACTIONGenerating an error indicates that deleting or updating will result in a foreign key constraint violation . If the constraint is delayed , And there are still reference lines , This error will be generated during constraint checking . This is the default action .
RESTRICTGenerating an error indicates that deleting or updating will result in a foreign key constraint violation . This action is similar to
NO ACTIONIt's the same , However, this check is not delayable .
CASCADEDelete any row that references the Deleted Row , Or update the value of the referenced column to the new value of the referenced column .
SET NULLSet the reference column to empty .
SET DEFAULTSet reference columns as their default values ( If the default value is not empty , There must be a row in the referenced table that matches the default value , Otherwise, the operation will fail ).
If the referenced column is changed frequently , It is best to add an index to the reference column , In this way, reference actions related to foreign key constraints can be performed more efficiently .
DEFERRABLENOT DEFERRABLEThis clause controls whether the constraint can be delayed . A non delayable constraint will be checked immediately after each command . The check of deferrable constraints will be deferred until the end of the transaction ( Use SET CONSTRAINTS command ).
NOT DEFERRABLEIs the default value . At present , OnlyUNIQUE、PRIMARY KEY、EXCLUDEas well asREFERENCES( Foreign keys ) The constraint accepts this clause .NOT NULLas well asCHECKConstraints are not delayable . Pay attention to includeON CONFLICT DO UPDATEClauseINSERTIn the sentence , Delayable constraints cannot be used as conflict judges .
INITIALLY IMMEDIATEINITIALLY DEFERREDIf a constraint is delayable , This clause specifies the default time to check the constraint . If the constraint is
INITIALLY IMMEDIATE, It will be checked after each statement . This is the default . If the constraint isINITIALLY DEFERRED, It will only be checked at the end of the transaction . Constraint check time can be used SET CONSTRAINTS Command to change .
ENABLE VALIDATE/NOVALIDATEDISABLE NOVALIDATE/VALIDATEThis clause is used to set or modify the state of the constraint , Include
ENABLE/DISABLEAndVALIDATE/NOVALIDATETwo combinations , There are four states in total . If the constraint isENABLE, Check the constraint rules when inputting or updating data in the database , Data that does not conform to the constraint rules cannot be entered into the database , This is the default . Conversely, if the constraint isDISABLE, Then input or update data will not be checked for constraint rules . OneVALIDATEThe constraint of state indicates that the existing data in the database conforms to the constraint rules . If you set or modify the constraint toENABLEStatus does not specify a validity status ,VALIDATEIs the default value . OneDISABLEVALIDATEState constraints , In order to ensure that the validity state is not destroyed , Will set the database table to read-only , Disable DML operation . If you add for an existing tableVALIDATEState constraints , The constraint rules will be checked for the data in the table . OneNOVALIDATEThe constraint of status indicates that the existing data in the database table has not been checked for constraint rules . Set or modify constraints toDISABLEIn the state of , If no validity status is specified ,NOVALIDATEIs the default value . If you add for an existing tableNOVALIDATEState constraints , There will be no validity check on the existing data (ENABLEThe unique constraint and primary key constraint of the state depend on the index , Creating an index will check the uniqueness of existing data ).Currently, this clause only supports checking constraints 、 Unique constraint 、 Primary key and foreign key constraints .
When creating or modifying constraint state on partition table , The constraint state cascades the constraints applied to the partition . The parent constraint on the partition table and the child constraint on the partition always maintain the same state , You cannot modify the partition table or the inherited constraint state on the partition alone , However, for partitioned tables or independent constraints on partitions, the constraint state can be modified separately .
precondition
You need to have the permissions required by the statement .
Example
Is a table
filmsDefine a unique table constraint . Unique table constraints can be defined on one or more columns of a table :CREATE TABLE films ( code char(5), title varchar(40), did integer, date_prod date, kind varchar(10), len interval hour to minute, CONSTRAINT production UNIQUE(date_prod) );Define a column check constraint :
CREATE TABLE distributors ( did integer CHECK (did > 100), name varchar(40) );Define a table check constraint :
CREATE TABLE distributors ( did integer, name varchar(40), CONSTRAINT con1 CHECK (did > 100 AND name <> '') );Is a table
filmsDefine a primary key table constraint :CREATE TABLE films ( code char(5), title varchar(40), did integer, date_prod date, kind varchar(10), len interval hour to minute, CONSTRAINT code_title PRIMARY KEY(code,title) );Is a table
distributorsDefine a primary key constraint . The following two examples are equivalent , The first one uses table constraint syntax , The second uses column constraint syntax :CREATE TABLE distributors ( did integer, name varchar(40), PRIMARY KEY(did) ); CREATE TABLE distributors ( did integer PRIMARY KEY, name varchar(40) );Column
nameGive a text constant a default value , Arrange columnsdidThe default value of is to select the next value from a sequence object to generate , And letmodtimeThe default value of is the time when the row is inserted :CREATE TABLE distributors ( name varchar(40) DEFAULT 'Luso Films', did integer DEFAULT nextval('distributors_serial'), modtime timestamp DEFAULT current_timestamp );In the table
distributorsDefine twoNOT NULLColumn constraints , One of them is explicitly given a name :CREATE TABLE distributors ( did integer CONSTRAINT no_null NOT NULL, name varchar(40) NOT NULL );by
nameColumn defines a unique constraint :CREATE TABLE distributors ( did integer, name varchar(40) UNIQUE );The same unique constraint is specified with a table constraint :
CREATE TABLE distributors ( did integer, name varchar(40), UNIQUE(name) );Create the same table , Specify the table and its unique index 70% Filling factor of :
CREATE TABLE distributors ( did integer, name varchar(40), UNIQUE(name) WITH (fillfactor=70) ) WITH (fillfactor=70);Create table
circles, With an exclusion constraint to prevent any two circles from overlapping :CREATE TABLE circles ( c circle, EXCLUDE USING gist (c WITH &&) );
9.2. LOG Clause
purpose
LOG Clause allows the database to specify whether operations on the table are recorded to WAL In the log .
LOG Clauses usually appear in the following statements :
CREATE/ALTER TABLEStorage clauses are available when creating or changing tables .
common LOG The types of clauses are :
LOGGEDIf specified , This table is created as a log record (WAL) Table of . The data written to the table recording the log will be written to the pre write log .
UNLOGGEDIf specified , This table is created as a non logged table . The data written to the table without logging will not be written to the pre write log , This makes them much faster than ordinary watches . however , They are not safe when they collapse : A table that does not log will be automatically truncated after a crash or unclean shutdown . The contents of a table that is not logged will not be copied to the backup server . Any index created on a table that is not logged will automatically not be logged .
precondition
You need to have the permissions required by the statement .
Example
establish UNLOGGED surface
CREATE UNLOGGED TABLE test ( id int, name varchar(40));The adjustment table is LOGGED
ALTER TABLE test SET LOGGED;
9.3. Storage clause
purpose
The storage clause allows you to specify that the database stores related parameters , Storage parameters will affect the time required to access the data stored in the database , And the efficiency of database space .
Storage clauses usually appear in the following statements :
CREATE/ALTER TABLEStorage clauses are available when creating or changing tables .
CREATE/ALTER INDEXWhen creating and changing indexes .
CREATE/ALTER MATERIALIZED VIEWWhen creating materialized views .
Common types of storage clauses are :
fillfactor(integer)The fill factor of a table is a 10 To 100 Percentage between .100( Completely fill ) Is the default value . When a smaller fill factor is specified ,
INSERTThe operation will fill the table page only to the specified percentage , The remaining space on each page is reserved for updates on the page . This makesUPDATEHave the opportunity to put the updated version of a line on the same page as its original version , This is more efficient than putting it on a different page . For a table whose entries are never updated , Full filling is the best choice , But on the table with heavy update, a smaller fill factor is more appropriate . This parameter cannot be correct TOAST Table settings .
toast_tuple_target(integer)toast_tuple_target Specifies that you are trying to move the long column value to TOAST The minimum tuple length required before the table , We are also starting toasting Then try to reduce the length to the following target length . This only affects columns marked as external or extended , And only applies to the new element group —— No impact on existing lines . By default , This parameter is set to allow at least 4 Tuples , Its default block size is 2040 byte . The effective value is 128 Byte and ( Block size - head ) Between , The default is 8160 byte . For very short or long lines , Changing this value may not be useful . Be careful , The default settings are usually close to optimal , In some cases , Setting this parameter may have a negative effect . This parameter cannot be used for TOAST surface .
autovacuum_enabled,toast.autovacuum_enabled(boolean)Enable or disable the automatic cleanup daemon for a specific table . If it is true , The automatic cleanup daemon will follow Automatically clean up daemons The rules discussed in execute automatically on this table
VACUUMperhapsANALYZEoperation . If it is false , This table will not be automatically cleaned , But to stop the transaction ID It will still be automatically cleaned up when rewinding . For rollback blocking, see Prevent transactions ID Rollback failed . If autovacuum The parameter is false , The automatic cleanup daemon will not run at all ( Unless to stop the transaction ID Rewind ), Setting independent table storage parameters will not override this setting . So explicitly set this storage parameter totrueRarely of great significance , Only set tofalseIs more useful .
vacuum_index_cleanup,toast.vacuum_index_cleanup(boolean)Run on this table
VACUUMwhen , Enable or disable index cleanup . The default value istrue. Disabling index cleanup can greatly speed upVACUUMSpeed , however , If the table is modified frequently , It may also cause the index to swell seriously .INDEX_CLEANUPParameters of VACUUM , If specified , Then override the value of this option .
vacuum_truncate,toast.vacuum_truncate(boolean)Enable or disable vacuum To try to truncate any empty pages at the end of the table . The default value is
true. Iftrue,VACUUMAnd automatic cleanup will perform truncation , The disk space of the truncated page is returned to the operating system . Be careful , Truncation requiresACCESS EXCLUSIVElock .TRUNCATEParameters of VACUUM , If specified , Then override the value of this option .
autovacuum_vacuum_threshold,toast.autovacuum_vacuum_threshold(integer)autovacuum_vacuum_threshold Parameter values for each table .
autovacuum_vacuum_scale_factor,toast.autovacuum_vacuum_scale_factor(float4)autovacuum_vacuum_scale_factor Parameter values for each table .
autovacuum_analyze_threshold(integer)autovacuum_analyze_threshold Parameter values for each table .
autovacuum_analyze_scale_factor(float4)autovacuum_analyze_scale_factor Parameter values for each table .
autovacuum_vacuum_cost_delay,toast.autovacuum_vacuum_cost_delay(floating point)autovacuum_vacuum_cost_delay Parameter values for each table .
autovacuum_vacuum_cost_limit,toast.autovacuum_vacuum_cost_limit(integer)autovacuum_vacuum_cost_limit Parameter values for each table .
autovacuum_freeze_min_age,toast.autovacuum_freeze_min_age(integer)vacuum_freeze_min_age Parameter values for each table . Note that automatic cleaning will ignore those beyond the scope of the system autovacuum_freeze_max_age Half of the parameters are for each table
autovacuum_freeze_min_ageParameters .
autovacuum_freeze_max_age,toast.autovacuum_freeze_max_age(integer)autovacuum_freeze_max_age Parameter values for each table . Note that automatic cleaning will ignore parameters beyond the system scope ( Can only be set smaller ) Half of them are for each table
autovacuum_freeze_max_ageParameters .
autovacuum_freeze_table_age,toast.autovacuum_freeze_table_age(integer)vacuum_freeze_table_age Parameter values for each table .
autovacuum_multixact_freeze_min_age,toast.autovacuum_multixact_freeze_min_age(integer)vacuum_multixact_freeze_min_age Parameter values for each table . Note that automatic cleaning will ignore those beyond the scope of the system autovacuum_multixact_freeze_max_age Half of the parameters are for each table
autovacuum_multixact_freeze_min_ageParameters .
autovacuum_multixact_freeze_max_age,toast.autovacuum_multixact_freeze_max_age(integer)autovacuum_multixact_freeze_max_age Parameter values for each table . Note that automatic cleaning will ignore parameters beyond the system scope ( Can only be set smaller ) Half of them are for each table
autovacuum_multixact_freeze_max_ageParameters .
autovacuum_multixact_freeze_table_age,toast.autovacuum_multixact_freeze_table_age(integer)vacuum_multixact_freeze_table_age Parameter values for each table .
log_autovacuum_min_duration,toast.log_autovacuum_min_duration(integer)log_autovacuum_min_duration Parameter values for each table .
user_catalog_table(boolean)Declare that this table is an additional catalog table for logical replication purposes . Not right TOAST Table set this parameter .
WITH ( storage_parameter[=value] [, ... ] )This clause specifies optional storage parameters for a table or index . For backward compatibility ,
WITHClauses can containOIDS=FALSETo specify that the rows of the new table should not contain OIDs( Object identifier ),OIDS=TRUENo longer supported .
alloc_space_for_null(boolean)Declare the table as null Pre allocated space table , stay insert Will automatically be null Allocate a fixed size of memory space . The storage mechanism of the database restricts the pre allocation of space for fixed length data types , Variable length data types are allowed on the table , However, variable length data types cannot be followed by fixed length data types . This parameter is only applicable to ordinary tables , I won't support it view、index、 A temporary table , Global temporary table 、 Partition table, etc . Ordinary tables do not support passing alter table Set up alloc_space_for_null Parameters . Tables with pre allocated space can be used for local updates . There are many restrictions on the table with pre allocated space :
Unique constraints are not supported , Foreign key constraints , Exclusive constraints ; Indexes other than primary keys are not supported ; I won't support it dblink; Display of things is not supported ; I won't support it function/procedure; Most... Are not supported alter table operation ; Flashback queries and flashback tables are not supported ; It is not supported to create materialized views based on pre allocated space ; Creating... Is not supported trigger/rule;
template_alloc_space_for_null(boolean)When you declare this table as a template table to create a new table , The new table will be automatically set alloc_space_for_null Parameters , If there is a primary key constraint on the template table , The new table will inherit the primary key constraint of the template table . Only support create table as and select into table Method to create a new table , Template table in sub query 、 This function is not supported when used in compound query and hierarchical query , adopt dblink This function is not supported when creating a new table in . You cannot inherit the primary key constraint in the following cases : a) Multiple base tables are specified , Cannot inherit the primary key constraint ; b) Select The column of does not contain all primary key columns ; c) The base table does not contain a primary key ;
Example
Create table , Specify the table and its unique index 70% Filling factor of .
CREATE TABLE distributors ( did integer, name varchar(40), UNIQUE(name) WITH (fillfactor=70) ) WITH (fillfactor=70);
边栏推荐
- Motor control column summary
- IVR在voip电话系统的应用与价值
- Data warehouse construction -dim floor
- Application of canoe XML in test modules
- High frequency electronic circuit review examination questions and answers
- Processing method of CDC in SDC
- Select sort / insert sort / bubble sort
- 轻量级单片机命令行交互项目,全部开源
- Home VR panoramic display production to improve customer transformation
- Redis publish subscription
猜你喜欢

嵌入式通用学习路线整理

Motor control column summary

解决Vagrant报错b:48:in `join‘: incompatible character encodings: GBK and UTF-8 (Encoding::Compatib

520 for what? DIY is a high-value RGB clock that girls want to watch

How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects

【个人总结】2022.7.24周结

Benji Banas launched the second season of earn while playing bonus activities, supporting the use of multiple Benji passes!

Redis official visualization tool, with high appearance value and powerful functions!

SIP账号注册的SIP软电话的使用和常见问题

Mongondb API usage
随机推荐
How to view the container name in pod
DOM operation -- operation node
517. Super washing machine
中文文本纠错任务简介
Using easyexcel to import tables to realize batch insertion of xlsx files ----- MySQL of Linux
柠檬班自动化学习毕竟
Home VR panoramic display production to improve customer transformation
Motor control column summary
解决Vagrant报错b:48:in `join‘: incompatible character encodings: GBK and UTF-8 (Encoding::Compatib
Hack The Box - Web Requests Module详细讲解中文教程
【个人总结】2022.7.24周结
Redis persistence AOF
TZC 1283: simple sort - Comparative sort
Why can't lpddr completely replace DDR?
Redis发布订阅
又一开源神器,值得收藏学习!
二叉树的性质 ~
[cloud native] record of feign custom configuration of microservices
Hack The Box - Introduction to Networking Module详细讲解中文教程
Is it really hopeless to choose electronic engineering and be discouraged?