当前位置:网站首页>Kingbasees SQL language reference manual of Jincang database (20. SQL statements: merge to values)
Kingbasees SQL language reference manual of Jincang database (20. SQL statements: merge to values)
2022-07-26 20:01:00 【Thousands of sails passed by the side of the sunken boat_】
20. SQL sentence : MERGE To VALUES
This chapter contains the following SQL sentence :
20.1. MERGE
purpose
MERGE -- Insert or modify the target table according to the connection conditions
MERGE During a scan, insert or modify the target table according to the connection conditions .
Use MERGE Syntax can be merged UPDATE and INSERT sentence . adopt MERGE sentence , According to a table ( Or view ) For another table ( Or view ) The query , Execution on connection condition matching UPDATE( May contain DELETE), Unmatched execution INSERT. The data sheet includes : Common watch 、 Partition table .
MERGE Grammar only needs a full table scan to complete all the work , Execution efficiency is higher than INSERT+UPDATE.
MERGE Also a DML sentence , And others DML Statements also need to pass ROLLBACK and COMMIT Statement to end the transaction .
precondition
If MERGE action Specified in UPDATE/INSERT Clause , The user is required to have the UPDATE/INSERT jurisdiction , If in UPDATE Clause specifies DELETE action , You also need to have DELETE jurisdiction .
grammar
MERGE INTO [ schema. ] { target_table } [ [ AS ] target_table_alias ]
USING { [ schema. ] { source_table } [ [ AS ] source_table_alias ]
ON ( condition_expression )
[ merge_update_clause ]
[ merge_insert_clause ];
merge_update_clause:
WHEN MATCHED THEN
UPDATE SET column = { expr | DEFAULT }[, column = { expr | DEFAULT } ]...
[ where_clause ]
[ delete_clause ]
delete_clause:
[DELETE where_clause]
merge_insert_clause:
WHEN NOT MATCHED THEN
INSERT [ ( column [, column ]...) ]
VALUES ({ expr | DEFAULT }[, { expr | DEFAULT } ]...)
[ where_clause ]
where_clause:
WHERE condition
semantics
target_tableMERGE The goal is , It can be a watch 、 Horizontal partition table or updatable view . Cannot be inherited tables or vertically partitioned tables .
target_table_aliasMERGE Alias of the target .
source_tableMERGE Source , It could be a watch 、 View 、SQL/MED、 Subquery 、join table And functions .
source_table_aliasMERGE Alias of the source .
condition_expressionSpecify the join conditions between the target table and the source table . If the condition is true , And it specifies WHEN MATCHED THEN UPDATE Clause , Then update the tuple of the matched target table ; otherwise , If the condition is false and WHEN NOT MATCHED THEN INSERT Clause , Then insert the target table .
merge_update_clauseWhen the target table and the source table ON When the condition is true , Execute the clause , That is, update the target table data . This update operation will trigger the trigger on the target table . The updated column cannot be ON The column referenced in the condition , When updating, you can use WHERE The condition indicates the row to be updated , Conditions can contain columns of the source table , You can also include the columns of the target table , When specified WHERE When the condition is false , Do not update .
delete_clauseDELETE Clause deletes only the target table and the source table ON Condition is true 、 And it is the updated record that meets the deletion conditions ,DELETE Clause does not affect INSERT Line inserted by item . Delete condition is applied to the updated record , It can be related to the source table , It can also be related to the target table , Or both . If ON Condition is true , But it does not meet the update conditions , No updated data , that DELETE No data will be deleted .
merge_insert_clauseWhen the target table and the source table ON When the condition is false , Execute the statement . You can specify the insertion condition , When inserting WHERE Conditions can only refer to columns in the source table .VALUES Only the columns in the source table can be referenced later , Cannot contain columns of the target table .
Optional parameters can be written in any order , Don't follow the order described above .
Example
example 1:
create table test1(a int, b int); insert into test1 values(1, 1); insert into test1 values(2, 2); insert into test1 values(3, 3); create table test2(x int, y int); insert into test2 values(1, 1); insert into test2 values(3, 3); insert into test2 values(5, 5); merge into test2 using test1 on (test1.a = test2.x) when matched then update set y = y * -1 where test1.a > 1 when not matched then insert values(test1.a, test1.b);Execution results : x | y ---+---- 1 | 1 5 | 5 2 | 2 3 | -3 (4 rows)example 2:MERGE Use in DELETE sentence :
create table t1(id int, a int, b int, c varchar(100)); create table t2(id int, a int, b int, c varchar(100)); insert into t1 values(1, 1, 1, '1'); insert into t1 values(2, 2, 2, '2'); insert into t1 values(3, 3, 3, '3'); insert into t1 values(4, 4, 4, '4'); insert into t2 values(2, 22, 22, '2'); insert into t2 values(4, 44, 44, '4'); merge into t2 using t1 on (t1.id = t2.id) when matched then update set t2.a = t2.a * -1, t2.b = t2.b * -1 delete where t1.id = t2.id when not matched then insert values(t1.id, t1.a, t1.b, t1.c); Execution results : id | a | b | c ----+---+---+--- 1 | 1 | 1 | 1 3 | 3 | 3 | 3 (2 rows )
Compatibility
MERGEStatements are not compatible SQL standard .
other
If there are multiple rows in the source table that match a row in the target table , And at the same time, it specifies WHEN MATCHED THEN UPDATE Clause , False report , Because the same tuple cannot be updated repeatedly .
about set_list Come on , Cannot specify ON Columns in the target table used for the join condition in the condition clause .
stay value_list Columns in the target table cannot be referenced in the value expression of .
If there are constraints on the target table or in the definition of the target view WITH CHECK OPTION, Then the update of the target table must meet the constraints on the base table or the verification conditions defined by the view .
You need to have a connection to the source table SELECT jurisdiction , For the target table UPDATE/INSERT jurisdiction , If UPDATE Clauses have DELETE, There needs to be DELETE jurisdiction .
20.2. MOVE
purpose
MOVE — Position a cursor
MOVEMy work is exactly like ``FETCH`` command , But it only locates the cursor and does not return rows . be used forMOVEThe parameters of the command andFETCHThe order is the same , May refer to FETCH .On successful completion ,
MOVEThe form of the command label returned by the command isMOVE count``count`` It's a With the same parameters
FETCHThe number of lines returned by the command ( It could be zero ).
precondition
nothing
grammar
MOVE [ direction [ FROM | IN ] ] cursor_name
among direction It can be empty or one of the following :
NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count
ALL
FORWARD
FORWARD count
FORWARD ALL
BACKWARD
BACKWARD count
BACKWARD ALL
semantics
be used for
MOVEThe parameters of the command andFETCHThe order is the same , May refer to FETCH .
Example
BEGIN WORK; DECLARE liahona CURSOR FOR SELECT * FROM films; -- Skip the former 5 That's ok : MOVE FORWARD 5 IN liahona; MOVE 5 -- From cursor liahona Take the second place 6 That's ok : FETCH 1 FROM liahona; code | title | did | date_prod | kind | len -------+--------+-----+------------+--------+------- P_303 | 48 Hrs | 103 | 1982-10-22 | Action | 01:37 (1 row) -- Close cursor liahona And end the transaction : CLOSE liahona; COMMIT WORK;
Compatibility
stay SQL There is no in the standard
MOVEsentence .
20.3. NOTIFY
purpose
NOTIFY — Generate a notification
NOTIFYThe command sends a notification event and an optional “ load ” String to each client application that is listening , These applications have been executed for the specified channel name in the current database beforeLISTEN channel. Notifications are visible to all users .
NOTIFYTo access the same KingbaseES The process collection of the database provides a simple inter process communication mechanism . A payload string can be sent with the notification , Pass additional data from the notifier to the listener by using tables in the database , You can also build a high-level mechanism for transferring structured data .The information passed to the client by a notification event includes the notification channel name 、 The server process of the notified session PID And load string , If the payload string is not specified, it is an empty string .
The channel names to be used in a given database and other databases are defined by the database designer . Usually , The channel name is the same as the name of a table in the database , And notification of events actually means :“ I changed this watch , Let's see what has been changed ”. however
NOTIFYandLISTENThe command does not force such a connection . for example , A database designer can use several different channel names to mark different kinds of changes on a table . in addition , The payload string can be used in many different situations .When
NOTIFYUsed to mark changes to a specific table , A useful programming technique is to put ``NOTIFY`` Put it in a statement trigger triggered by table update . In this way , Notification will occur automatically whenever the table is changed , And application programmers can't forget to send notifications .
NOTIFYIn some important ways with SQL Transaction interaction . First , If oneNOTIFYExecute within a transaction , Before the transaction is committed , This notification event will not be delivered . This is appropriate , Because if the transaction is aborted , All of these commands will have no effect , IncludeNOTIFY, . But if the notification event is expected to be delivered immediately , Then this behavior will be disturbing . secondly , If a listening session receives a notification signal and it is in a transaction , After the transaction is completed ( Submit or abort ) Before , The notification event will not be delivered to the client it connects . Again , The reason is that if a notification is delivered within a transaction and the transaction is subsequently aborted , We would like the notice to be revoked in some wayBut once the server sends the notification to the client, it cannot “ Take it back ”. Therefore, notification events can only be delivered between transactions . The key point is to put
NOTIFYApplications used as real-time signals should keep their transactions as short as possible .If you send a notification to the same channel name with the same payload string multiple times from the same transaction , The database server can decide to deliver only a single notification . On the other hand , Notifications with different payload strings will always be delivered as different notifications . Similarly , Notifications from different transactions will not be folded into one notification . In addition to discarding the repeated notification instances generated later ,
NOTIFYEnsure that notifications from the same transaction are delivered in the order they are sent . What can also be guaranteed is , Messages from different transactions are delivered in the order in which their transactions are committed .An executive
NOTIFYIt is common for clients to listen to the same notification channel at the same time . under these circumstances , Like all other listening sessions , It will retrieve a notification event . According to the logic of the application , This may lead to useless work , For example, read the same update from a table you just wrote . You can do this by following the server process that sends the notification PID( Provide in the notification event message ) Conversation with yourself PID( It can be downloaded from libkci obtain ) Is it the same to avoid this extra work . When the two are the same , The notification event is sent by the current session itself , So you can ignore that .
precondition
nothing
grammar
NOTIFY channel [ , payload ]
semantics
channelThe name of the notification channel to signal ( Any identifier ).
payloadTo communicate through notification “ load ” character string . This must be a simple string . In the default configuration , The string cannot exceed 8000 byte ( If you need to send binary data or more information , It's best to put it in a database table and send the key of the record ).
Example
from ksql Configure and execute a listener / Notification sequence :
LISTEN virtual; NOTIFY virtual; Asynchronous notification "virtual" received from server process with PID 8448. NOTIFY virtual, 'This is the payload'; Asynchronous notification "virtual" with payload "This is the payload" received from server process with PID 8448. LISTEN foo; SELECT sys_notify('fo' || 'o', 'pay' || 'load'); Asynchronous notification "foo" with payload "payload" received from server process with PID 14728.
Compatibility
stay SQL There is no in the standard
NOTIFYsentence .
other
There is a queue holding notifications that have been sent but have not been processed by all listening sessions . If the queue is full , call
NOTIFYThe transaction of will fail at commit . The queue is very large ( In standard installation 8GB) And it should be enough to cope with almost every use case . however , If a session is executedNOTIFYAnd then enter a transaction for a long time , No cleanup will occur . Once the queue is more than half used , You will see the warning in the log file , It indicates which session prevented cleanup . In this case , You should ensure that this session ends its current transaction , Only in this way can the cleaning go on .function
sys_notification_queue_usageReturns the current proportion of pending notifications in the queue . See System information functions and operators .One has been implemented
NOTIFYThe transaction of cannot be prepared for two-phase commit .To send a notification , You can also use functions
sys_notify(text,text). This function takes the channel name as the first parameter , The load is taken as the second parameter . If you need to use a lot of channel names and loads , The function ratio isNOTIFYCommands are easier to use .
20.4. PREPARE
purpose
PREPARE — Prepare a statement for execution
SELECT INTOCreate a new table and fill it with the data calculated by a query . These data will not be like ordinary ``SELECT`` Then it is returned to the client . The columns of the new table have andSELECTThe name and data type related to the output column of .
PREPARECreate a preliminary statement . A prepared statement is a server-side object , It can be used to optimize performance . WhenPREPAREWhen the statement is executed , The specified statement will be parsed 、 Analyze and rewrite . When the follow-up sends aEXECUTEOn command , The prepared statement will be planned and executed . This division of work avoids repetitive analytical work , However, the execution plan is allowed to depend on the specific parameter values provided .The prepared statement can accept parameters : At execution time, it will be replaced with the value in the statement . When creating the prepared statement , You can reference parameters with positions , Such as
$1、$2etc. . You can also optionally specify a list of parameter data types . When the data type of a parameter is not specified or declaredunknownwhen , Its type will be inferred from the environment in which the parameter is first referenced ( If possible ). When the statement is executed , stayEXECUTEStatement to specify actual values for these parameters . For more information about this, please refer to EXECUTE .The prepared statement only exists during the current database session . When the session ends , The prepared statement will disappear , So it has to be rebuilt before it can be reused . This also means that a prepared statement cannot be used by multiple database clients at the same time . however , Each client can create its own prepared statements to use . Preparatory statements can be used DEALLOCATE Command manual clearing .
When a session is going to execute a large number of similar statements , Prepared statements may have the greatest performance advantage . If the statement is complex ( Difficult to plan or rewrite ), for example , If the query involves the connection of many tables or requires the application of multiple rules , The performance difference will be particularly obvious . If the statement is relatively easy to plan and rewrite , But the execution cost is relatively large , Then the performance advantage of prepared statements is less significant .
precondition
nothing
grammar
PREPARE name [ ( data_type [, ...] ) ] AS statement
semantics
nameGive this particular prepared statement any name . It must be unique in a session and will subsequently be used to execute or clear a previously prepared statement .
data_typePrepare the data type of a parameter of the statement . If the data type of a particular parameter is not specified or specified as
unknown, It will be deduced from the environment in which this parameter is first referenced . To reference parameters in the prepared statement itself , have access to ``$1``、$2etc. .
statementwhatever
SELECT、INSERT、UPDATE、DELETEperhapsVALUESsentence .
Example
For one
INSERTStatement creates a prepared statement , And then execute it :PREPARE fooplan (int, text, bool, numeric) AS INSERT INTO foo VALUES($1, $2, $3, $4); EXECUTE fooplan(1, 'Hunter Valley', 't', 200.00);For one
SELECTStatement creates a prepared statement , And then execute it :PREPARE usrrptplan (int) AS SELECT * FROM users u, logs l WHERE u.usrid=$1 AND u.usrid=l.usrid AND l.date = $2; EXECUTE usrrptplan(1, current_date);In this case , The data type of the second parameter is not specified , therefore , It is from using
$2Inferred from the context of .
Compatibility
SQL The standard includes a
PREPAREsentence , But it is only used for embedded SQL. This version ofPREPAREStatements also use a somewhat different syntax .
other
have access to generic plan or custom plan To execute the prepared statement . The general plan is the same in all implementations , Use the parameter values given in the call to generate a custom plan for a specific execution . Using a generic plan can avoid planning overhead , But in some cases , Customized plans are more effective , Because planners can use the knowledge of parameter values .( Of course , If the prepared statement has no parameters , Then this is meaningless , The general plan is usually used .)
By default ( in other words , When plan_cache_mode Set to
auto), The server will automatically choose whether to use a general plan or a custom plan for a prepared statement with parameters . The current rule is , The first five executions are done using custom plans , And calculate the average estimated cost of these plans . Then create a general plan , And compare its estimated cost with the average customization plan cost . If the cost of a generic plan is not much higher than the cost of an average customized plan , So that repeated rescheduling seems preferable , Then the subsequent implementation will use the general plan .By way of
plan_cache_modeSet toforce_generic_planorforce_custom_plan, This heuristic can be overridden , Force the server to use a general plan or a custom plan . This setting is mainly useful , If the cost estimate of the general plan is poor for some reason , Allow it to be selected , Even if its actual cost is much higher than the cost of customized plan .To check KingbaseES Query plan for a prepared statement , have access to EXPLAIN , for example :
EXPLAIN EXECUTE stmt_name(parameter_values);If you use a general plan , It will contain parameter symbols
$n, A customized plan will replace the provided parameter values .More about query planning and KingbaseES The content of the statistical information collected for this , Please see ANALYZE file .
Although the preparation of statements is mainly to avoid repeated parsing, analysis and planning of statements , However, as long as the database objects used in this statement are defined after the last use of this preliminary statement (DDL) change ,KingbaseES This statement will be forced to be re analyzed and re planned . also , If search_path The value of has changed , The new
search_pathRe parse the statement ( The latter behavior is from KingbaseES V8.2 Start a new behavior ). These rules make the use of prepared statements semantically almost equivalent to repeatedly submitting the same query text , But it can benefit from performance ( If no object definition is changed , Especially if the optimal plan remains unchanged ). An example of this imperfect semantic equivalence is : If the statement references the table with an unqualified name , And then insearch_pathA new table with the same name is created in the schema higher in , Automatic reparse will not occur , Because the object used by this statement has not been changed . however , If some other changes cause reparse , New tables will be referenced in subsequent use .By querying sys_prepared_statements System view to see all available prepared statements in the session .
20.5. PREPARE TRANSACTION
purpose
PREPARE TRANSACTION — Prepare the current transaction for two-phase commit
PREPARE TRANSACTIONPrepare the current transaction for two-phase commit . After this command , The transaction is no longer associated with the current session . contrary , Its state is completely stored on disk , And there is a high probability that it will be submitted successfully ( Even if the database crashes before the request is submitted ).Once ready , Transactions can be used separately later COMMIT PREPARED perhaps ROLLBACK PREPARED Commit or roll back . These commands can be issued from any session, not just the one that performed the original transaction .
From the perspective of the session that issued the command ,
PREPARE TRANSACTIONUnlikeROLLBACKcommand : After executing it , There is no active current transaction , And the effect of this preparatory transaction is no longer visible ( If the transaction is committed , The effect will become visible again ).If for any reason
PREPARE TRANSACTIONCommand fails , It will become aROLLBACK: The current transaction will be canceled .
precondition
PREPARE TRANSACTIONIt is not designed to be used in applications or interactive sessions . Its purpose is to allow an external transaction manager to perform atomic global transactions among multiple databases or other transactional sources . Unless you are writing a transaction manager , Otherwise you may not usePREPARE TRANSACTION.This command must be used in a transaction block . Transaction block is used BEGIN Start .
Currently, we have implemented any temporary table 、 Create a
WITH HOLDCursor or executionLISTEN、UNLISTENorNOTIFYIn the transaction of , Don't allowPREPAREThis transaction . These features are too tightly bound to the current session , So it's useless for a business to be prepared .
grammar
PREPARE TRANSACTION transaction_id
semantics
transaction_idAn arbitrary transaction identifier ,
COMMIT PREPAREDperhapsROLLBACK PREPAREDThis identifier will be used later to identify this transaction . The identifier must be written as a string , And the length must be less than 200 byte . It cannot be the same as the identifier of any currently prepared transaction .
Example
Prepare the current transaction for two-phase commit , Use
foobarAs a transaction identifier :PREPARE TRANSACTION 'foobar';
Compatibility
PREPARE TRANSACTIONIt's a kind of KingbaseES Expand . It is intended for use in external transaction management systems , Some of them have been covered by the standard ( for example X/Open XA), But those systems SQL Aspects are not standardized .
other
If you use
SET( NoLOCALOptions ) Modify any run-time parameters of the transaction , These effects will last untilPREPARE TRANSACTIONafter , And will not be followed by anyCOMMIT PREPAREDor ``ROLLBACK PREPARED`` Affected by . therefore , In this respectPREPARE TRANSACTIONYour behavior is more likeCOMMITinstead ofROLLBACK.All currently available ready transactions are listed in sys_prepared_xacts In the system view .
Caution
It is unwise to keep a transaction ready for too long . This will interfere
VACUUMThe ability to recycle storage , And in extreme cases, it may cause the database to shut down to prevent transactions ID Rewind ( see Prevent transactions ID Rollback failed ). And remember , The transaction will continue to hold the lock it already holds . The design usage of this feature is , As long as an external transaction manager has verified that other databases are ready to commit , A prepared transaction will be normally committed or rolled back .If an external transaction manager is not established to track the prepared transactions and ensure that they are ended quickly , It is best to disable the prepared transaction feature ( Set up max_prepared_transactions zero ). This will prevent accidental creation of ready transactions , Otherwise, the matter may be forgotten and eventually lead to problems .
20.6. PURGE TABLE
purpose
PURGE TABLE It is divided into deleting a table specified in the recycle bin and emptying the recycle bin . When cleaning the recycle bin , Recycle bin view recyclebin And recycle bin system table sys_recyclebin Objects in will be cleared . When deleting a specified table in the recycle bin , The table and its associated objects will be deleted , For example, table index、constraint、trigger、policy、rule etc. . Emptying the recycle bin will delete all tables and associated objects in the recycle bin .
PUGRE RECYCLEBINEmpty the recycle bin , Does not belong to the present schema Your table will also be empty .
precondition
PUGRE TABLEDelete a specified... In the recycle bin table. To execute this command, you must be the owner of the table , If the specified table does not belong to the current search_path, You also need to specify schema.
grammar
Delete a table specified in the recycle bin
PURGE TABLE table_name;Empty all the tables in the recycle bin
PURGE RECYCLEBIN;
semantics
table_nameSpecify the table to delete .
Example
This command will delete the recycle bin named
kindsTable and its associated objects :PURGE TABLE kinds;This command will empty all objects in the recycle bin :
PURGE RECYCLEBIN;
Compatibility
PUGRE TABLEThe statement is a KingbaseES Expand .
other
nothing .
20.7. REASSIGN OWNED
purpose
REASSIGN OWNED — Change the ownership relationship of database objects owned by a database role
REASSIGN OWNEDThe instruction system turns ``old_role People `` The ownership relationship of any database object owned is changed to ``new_role``.
precondition
REASSIGN OWNEDAt the same time, it requires qualifications on the source role and the target role .
grammar
REASSIGN OWNED BY { old_role | CURRENT_USER | SESSION_USER } [, ...]
TO { new_role | CURRENT_USER | SESSION_USER }
semantics
old_roleThe name of a role . What this role has in the current database All objects and all shared objects ( database 、 Table space ) Of Ownership will be given back to ``new_role``.
new_roleThe name of the role that will be the new owner of the affected object .
Example
The way to remove a character who once owned an object is :
REASSIGN OWNED BY doomed_role TO successor_role; DROP OWNED BY doomed_role; -- Repeat the above command in each database in the cluster DROP ROLE doomed_role;
Compatibility
REASSIGN OWNEDCommand is a kind of KingbaseES Expand .
other
REASSIGN OWNEDIt is often used to prepare for the removal of one or more characters . becauseREASSIGN OWNEDDoes not affect objects in other databases , You usually need to execute this command in every database that contains objects owned by the deleted role .DROP OWNED The command can simply delete all database objects owned by one or more roles .
REASSIGN OWNEDThe command does not affect the grant to *old_role People ``* Of any privileges on objects they do not own . Again , It will not affect the use of \ ``ALTER DEFAULT PRIVILEGESDefault privileges created .DROP OWNEDYou can reclaim those privileges .For more discussion, please see Delete the role .
20.8. REFRESH MATERIALIZED VIEW
purpose
REFRESH MATERIALIZED VIEW — Replace the contents of a materialized view
REFRESH MATERIALIZED VIEWCompletely replace the contents of a materialized view . Old content will be discarded . If you specify ``WITH DATA``( Or as the default ), Support queries will be executed to provide new data , And the materialized view will be in a scannable state . If you specify ``WITH NO DATA``, No new data will be generated and the materialized view will be in a non scannable state .
precondition
CONCURRENTLYandWITH NO DATACannot be specified together .
grammar
REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] name
[ WITH [ NO ] DATA ]
semantics
CONCURRENTLYRefreshing the materialized view does not block the concurrent selection on the materialized view . Without this option , A refresh that affects many rows at once will use fewer resources and end faster , But it may block other connections trying to read from the materialized view . This option may be faster if only a few rows are affected .
Only when there is at least one on the materialized view
UNIQUEIndexes ( Use only column names and include all rows ) when , To allow this option . in other words , The index cannot be built on any expression or includeWHEREClause .When the materialized view has not been filled , This option cannot be used .
Even with this option , Only one materialized view can be run at a time ``REFRESH``.
nameThe name of the materialized view to refresh ( Can be defined by patterns ).
Example
This command will use materialized views
order_summaryReplace the contents of the materialized view with the query in the definition , And put it in a scannable state :REFRESH MATERIALIZED VIEW order_summary;This command will release and materialize the view
annual_statistics_basisRelevant storage and make it a non scannable state :REFRESH MATERIALIZED VIEW annual_statistics_basis WITH NO DATA;
Compatibility
REFRESH MATERIALIZED VIEWIt's a kind of KingbaseES Expand
other
Although for the future CLUSTER The default index of the operation will be maintained ,
REFRESH MATERIALIZED VIEWThe resulting rows will not be sorted based on this attribute . If you want the data to be sorted when it is generated , Must be used in support queries ``ORDER BY`` Clause .
20.9. REINDEX
purpose
REINDEX — Rebuild index
REINDEXUse the data stored in the indexed table to rebuild an index , And replace the old copy of the index . There are some scenarios that need to be usedREINDEX:
An index has been corrupted , And no longer contain legal data . Although theoretically this will not happen , In fact, the index will be damaged due to software defects or hardware failure .
REINDEXProvides a recovery method .An index becomes “ Overstaffed ”, It contains many empty or nearly empty pages .KingbaseES Medium B- This may happen to tree indexes in certain unconventional access modes .``REINDEX`` Provides a way to reduce the space consumption of the index , That is to create a new version of the index , There is no death page . See Re index daily .
Modified the storage parameters of an index ( For example, fill factor ), And I hope to ensure that this amendment is fully effective .
If
CONCURRENTLYIndex build of option failed , The index is reserved as “invalid”. Such an index is useless , But it can be easily usedREINDEXTo rebuild them . Be careful , OnlyREINDEX INDEXAbility to perform concurrent builds on invalid indexes .
precondition
nothing
grammar
REINDEX [ ( VERBOSE ) ] { INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } [ CONCURRENTLY ] name
semantics
INDEXRecreate the specified index .
TABLERecreate all indexes of the specified table . If the table has a secondary “TOAST” surface , It will also be re indexed .
SCHEMARebuild all indexes of the specified scheme . If a table in this scheme has secondary “TOAST” surface , It will also be re indexed . The index on the shared system directory will also be processed . In this form
REINDEXCannot execute within a transaction block .
DATABASERecreate all indexes in the current database . The index on the shared system directory will also be Handle . In this form
REINDEXCan't be in one Execute within the transaction block .
SYSTEMRecreate all indexes on the system directory in the current database . Share... On the system directory The index is also included . The index on the user table will not be processed . In this form
REINDEXCannot execute within a transaction block .
nameThe specific index to be reindexed 、 The name of the table or database . Indexes and table names can be Mode qualification . At present ,
REINDEX DATABASEandREINDEX SYSTEMOnly the current database can be re indexed , therefore Their parameters must match the name of the current database .
CONCURRENTLYWhen using this option ,KingbaseES The index will be rebuilt , Without taking any locks to prevent concurrent inserts on the table 、 Update or delete ; The standard index rebuild will lock writes on the table ( Instead of reading ), Until it's finished . There are several considerations when using this option. See At the same time, rebuild the index _ .
VERBOSEPrint a progress report when each index is rebuilt .
Example
Rebuild a single index :
REINDEX INDEX my_index;Rebuild table
my_tableAll indexes on :REINDEX TABLE my_table;Rebuild all indexes in a specific database , It is not assumed that the system index is already available :
$ export KINGBASE_OPTIONS="-P" $ ksql broken_db ... broken_db=> REINDEX DATABASE broken_db; broken_db=> \qRe index the table , Do not block the read and write operations of related relationships in the process of re indexing :
REINDEX TABLE CONCURRENTLY my_broken_table;
Compatibility
stay SQL There is no in the standard
REINDEXcommand .
other
If you suspect that the index on a user table is corrupt , have access to
REINDEX INDEXperhaps ``REINDEX TABLE`` Simply rebuild the index Or all indexes on the table .If you need to recover from index corruption on a system table , It's more difficult . under these circumstances , It is important for the system not to use any suspicious index itself ( actually , In this scenario , You may find that the server process will crash immediately when it starts , This is because of the dependency on corrupt indexes ). To recover safely , The server must use ``-P`` Option to start the , This will prevent it from using indexes for system Directory search .
One way to do this is to shut down the server , And start a single user KingbaseES The server , On its command line It includes
-POptions . then , Can send out ``REINDEX DATABASE``、REINDEX SYSTEM、REINDEX TABLEperhapsREINDEX INDEX, Which command to use depends on how many things you want to refactor . If in doubt , have access to ``REINDEX SYSTEM`` To choose to rebuild all system indexes in the database . Then exit the single user server session and restart the regular server . For more information on how to interact with the single user server interface, see kingbase Reference page .In another way , You can start a regular server session , Include... In its command line options
-P. The method of doing this is related to the client , But in all based on libkci Can be set before starting the clientKINGBASE_OPTIONSThe environment variable is-P. Note that although this approach does not require the exclusion of other clients with locks , It is wiser to prevent other users from connecting to the damaged database before the repair is completed .
REINDEXSimilar to deleting an index and rebuilding it , In which the index content will be built from scratch . however , Locking considerations are quite different .REINDEXCan write with lock exclusion , But it will not exclude the reading on the parent table of the index . It will also get an exclusive lock on the processed index , The lock will block attempts to use the index . contrary ,DROP INDEXWill temporarily obtain an exclusive lock on the schedule , Block write and read . Follow upCREATE INDEXWill reject writing but not reading , Because the index does not exist , So there will be no attempt to read it , This means that there will be no blocking, but read operations may be forced into expensive sequential scans .Re indexing a single index or table requires the user to be the owner of the index or table . The owner of the scheme or database is required to re index the scheme or database . Note that non super users sometimes cannot rebuild indexes on tables owned by other users . however , As a special case , When a non super user sends
REINDEX DATABASE、REINDEX SCHEMAperhapsREINDEX SYSTEMwhen , The index on the shared directory will be skipped , Unless the user owns the directory ( This is not usually the case ). Of course , Super users can always rebuild all indexes .Rebuilding indexes of partitioned tables or partitioned indexes is not supported . However, you can re index each partition separately . Rebuilding the index may interfere with the normal operation of the database . Usually KingbaseES Will lock a table , The index of this table is rebuilt according to the write operation , And the entire index construction can be performed by scanning the table only once . Other transactions can still read the table , But if they try to insert 、 Update or delete rows in the table , They will block these lines , Until the index reconstruction is completed . If the system is a real-time production database , This can have a serious impact . Very large tables can take many hours to index , Even for smaller tables , Rebuilding the index may lock the writer in a long time that the production system cannot accept .
KingbaseES Support re indexing to minimize write locks . This method calls
CONCURRENTLYOfREINDEXOptions . When using this option ,KingbaseES You must perform two table scans for each index that needs to be rebuilt , And wait for the termination of all existing transactions that may use the index . Compared with standard index reconstruction , This method requires more total work , And it takes much longer to complete , Because it needs to wait for unfinished transactions that may modify the index . however , Because it allows normal operation to continue while rebuilding the index , So this method is very useful for rebuilding indexes in the production environment . Of course , Additional regenerated by index CPU、 Memory and I/O The load may slow down other operations .Perform the following steps in concurrent re indexing . Each step runs in a separate transaction . If there are multiple indexes that need to be rebuilt , Then each step iterates through all indexes before entering the next step .
A new temporary index definition is added to the directory
sys_index. This definition will be used to replace the old index . Conversation levelSHARE UPDATE EXCLUSIVEThe lock performs a lock on the index and its associated tables that are being re indexed , To prevent any mode modification during processing .Complete the first iteration of building the index for each new index . Once the index is established , Its logo
sys_index.indisreadySwitched to “true”, To prepare it for insertion , Make it visible to other sessions after executing the built transaction . This step is done in a separate transaction for each index .Then perform a second iteration to add the tuples added at the run time of the first iteration . This step is also done in a separate transaction for each index .
All constraints that reference the index are changed to reference the new index definition , The name of the index has also been changed . here ,
sys_index.indisvalidIt's a turn “true” New index and “false”, Cache invalidation causes all sessions to reference old indexes .The old index consists of
sys_index.indisreadySwitch to “false” To prevent any new tuples from being inserted , After waiting for the query that may reference the old index to complete .The old index is deleted . Index and table
SHARE UPDATE EXCLUSIVEThe session lock is released .If there is a problem rebuilding the index , For example, uniqueness conflicts in unique indexes , be
REINDEXThe command will fail , But one will be left “invalid” The new index of is attached to the existing index . For the purpose of inquiry , This index will be ignored , Because it may be incomplete ; however , It still consumes update overhead .ksql``d`` The command will report such an index :INVALID:kingbase=# \d tab Table "public.tab" Column | Type | Modifiers --------+---------+----------- col | integer | Indexes: "idx" btree (col) "idx_ccnew" btree (col) INVALIDunder these circumstances , The recommended recovery method is to delete invalid indexes , Then try to execute concurrently again
REINDEX CONCURRENTLY. The name of the concurrent index created during processing is suffixedccnew, orccold( If it is an old index definition that we failed to delete ) ending . have access toDROP INDEXDelete invalid index , Include invalid toast Indexes .Regular index building allows other regular index building on the same table to occur at the same time , But only one concurrent index construction can occur on one table at a time . In both cases , It is not allowed to make other types of schema modifications to the table at the same time . Another difference is conventional
REINDEX TABLEorREINDEX INDEXCommands can be executed in a transaction block , howeverREINDEX CONCURRENTLYCannot perform .
REINDEX SYSTEMI won't support it ``CONCURRENTLY``, Because the system directory cannot be re indexed concurrently .Besides , Indexes that exclude constraints cannot be rebuilt concurrently . If you name such an index directly in this command , It will lead to mistakes . If a table or database with an exclusive constraint index is re indexed concurrently , Then these indexes will be skipped .( Can be used without
CONCURRENTLYOption to re index these indexes .)
20.10. RELEASE SAVEPOINT
purpose
RELEASE SAVEPOINT — Destroy a previously defined savepoint
RELEASE SAVEPOINTDestroy a savepoint previously defined in the current transaction .Destroying a savepoint will make it no longer a rollback point , But it has no behavior visible to other users . It will not undo the effect of the command executed after the savepoint is created ( To do this , so ROLLBACK TO SAVEPOINT ). Destroying a savepoint when it is no longer needed allows the system to reclaim some resources before the end of the transaction .
RELEASE SAVEPOINTIt will also destroy all savepoints established after the savepoint is established .
precondition
It is an error to specify a savepoint name that is not previously defined .
Savepoints cannot be released when a transaction is in an aborted state .
If multiple savepoints have the same name , Only the recently defined one will be released .
grammar
RELEASE [ SAVEPOINT ] savepoint_name
semantics
savepoint_nameName of the savepoint to destroy .
Example
Create and destroy a savepoint :
BEGIN; INSERT INTO table1 VALUES (3); SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (4); RELEASE SAVEPOINT my_savepoint; COMMIT; The above transaction will be inserted 3 and 4.
Compatibility
This command conforms to SQL standard . The standard specifies keywords ``SAVEPOINT`` It is mandatory , but KingbaseES It is allowed to omit .
20.11. RESET
purpose
RESET — Restore the value of a run-time parameter to the default value
RESETRestore runtime parameters to their default values .RESETyesSET configuration_parameter TO DEFAULT Another way of writing . See :ref:`SET` .
precondition
nothing
grammar
RESET configuration_parameter RESET ALL
semantics
configuration_parameterA settable runtime parameter name . The available parameters are recorded in Server configuration parameters reference manual as well as SET On the reference page .
ALLReset all settable runtime parameters to default values .
Example
hold
timezoneThe configuration variable is set to the default value :RESET timezone;
Compatibility
RESETIt's a kind of KingbaseES Expand .
other
The default value is defined as if it has not been issued in the current session
SET, The parameter must have a value . The actual source of this value may be an internally compiled default value 、 The configuration file 、 Command line options 、 Or default settings for each database or user . This is different from defining it as “ The value obtained by this parameter at the beginning of the session ” There are subtle differences , Because if the value comes from the configuration file , It will be reset to anything specified in the current configuration file . See Server configuration parameters reference manual .
RESETTransaction behavior andSETidentical : Its effect will be reversed by transaction rollback .
20.12. REVOKE
purpose
REVOKECommand recall from one or more roles before Privileges granted . key wordPUBLICImplicitly defined groups of all roles .See GRANT Description of the order .
Note the privileges that any particular role has, including those granted directly to it 、 From its membership Privileges obtained in the role and granted to
PUBLICThe privilege of . therefore , fromPUBLICTake backSELECTPrivilege does not necessarily mean It means that all characters will lose on this objectSELECTPrivilege : Those who are directly awarded A role given or granted through another role will still have it . Similarly , From a user Take backSELECTafter , IfPUBLICOr another Membership roles still existSELECTright , This user can still useSELECT.If you specify
GRANT OPTION FOR, Only this privilege will be reclaimed Grant options for , Privileges themselves are not recycled . otherwise , Privileges and their granting options are recycled .If a user holds a privilege with the grant option and grants it to other users , Then the privilege held by those other users is called dependency privilege . If the first user holds The privilege or grant option of is being revoked and there are dependent privileges , Appoint
CASCADEYou can reclaim those dependent privileges together , If not specified, it will Cause the recycling action to fail . This recursive recycling only affects the pass traceable to thatREVOKEPrivileges granted by the user chain of the body of the command . therefore , If this privilege is granted to the affected user by another user , Affected users may actually also Reserve this privilege .When reclaiming privileges on a table , It will also automatically recycle the corresponding columns on each column of the table Privilege ( If there is ). per contra , If a role has been granted to a table Privilege , Then reclaiming the same privilege from an individual column will not take effect .
When recycling membership in a role ,
GRANT OPTIONChanged be calledADMIN OPTION, But the behavior is similar . Also pay attention to this Formal commands do not allow noisy wordsGROUP.
precondition
Users can only reclaim the privileges directly granted by it . for example , If the user A A privilege with the grant option has been granted to the user B, And users B Then it is granted to the user C, So users A Not directly from C Withdraw the privilege . Instead, , user A From the user B Withdraw the grant option and use
CASCADEOptions , In this way, the privilege will be From the user C Recycling . For another example , If A and B All grant the same privilege Give it to C,A They can withdraw their own authorization, but not B Authorization of , therefore C In fact, you will still have this privilege .When a non owner of an object tries
REVOKEPrivileges on this object , If the user has no privileges on the object , The command will fail immediately . As long as a privilege is available , This command will continue , But it will only revoke those privileges it has to grant options . If the grant option is not held ,REVOKE ALL PRIVILEGESForm will send a warning , Other forms will warn if they do not hold the grant option of any privileges specifically mentioned in the command ( In principle, , These statements also apply to object owners , But because the owner is always considered to hold all grant options , These things will never happen ).If a super user chooses to send a
GRANTperhaps ``REVOKE`` command , The command is executed as if issued by the owner of the affected object . Because all privileges ultimately come from the object owner ( It may be indirectly through the granting of selected necklaces ), All privileges can be revoked by the super user , But this may require the foregoing ``CASCADE``.
REVOKEIt can also be done by a role that is not the owner of the affected object , But the role should be a member of the role that owns the object or a member with privileges on the objectWITH GRANT OPTIONMembers of the role of . In this case , The command is like being actually owned by the object or privilege ``WITH GRANT OPTION`` The containing role is executed as issued . for example , If the tablet1By the characterg1Have , andu1`` yes \ ``g1A member of , thatu1Can take backt1`` Is recorded as \ ``g1The privileges granted . This will includeu1`` And by the role \ ``g1Grant completed by other members of .If you execute
REVOKEThe role of holds privileges indirectly obtained through more than one role membership path , Which one contains the role that will be used to execute the command is not specified . In this case , Best use ``SET ROLE`` Become what you want to perform as its identity ``REVOKE`` Specific roles . Failure to do this may result in recycling more privileges than you expect , Or you can't recycle anything at all .see jurisdiction Get more information about specific privilege types , And how to check the privileges of objects .
grammar
REVOKE [ GRANT OPTION FOR ]
{ { SELECT | INSERT | UPDATE | DELETE | TRUNCATE | REFERENCES | TRIGGER }
[, ...] | ALL [ PRIVILEGES ] }
ON { [ TABLE ] table_name [, ...]
| ALL TABLES IN SCHEMA schema_name [, ...] }
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ { SELECT | INSERT | UPDATE | REFERENCES } ( column_name [, ...] )
[, ...] | ALL [ PRIVILEGES ] ( column_name [, ...] ) }
ON [ TABLE ] table_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ { USAGE | SELECT | UPDATE }
[, ...] | ALL [ PRIVILEGES ] }
ON { SEQUENCE sequence_name [, ...]
| ALL SEQUENCES IN SCHEMA schema_name [, ...] }
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ { CREATE | CONNECT | TEMPORARY | TEMP } [, ...] | ALL [ PRIVILEGES ] }
ON DATABASE database_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ USAGE | ALL [ PRIVILEGES ] }
ON DOMAIN domain_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ USAGE | ALL [ PRIVILEGES ] }
ON FOREIGN DATA WRAPPER fdw_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ USAGE | ALL [ PRIVILEGES ] }
ON FOREIGN SERVER server_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ EXECUTE | ALL [ PRIVILEGES ] }
ON { { FUNCTION | PROCEDURE | ROUTINE } function_name [ ( [ [ argmode ] [
arg_name ] arg_type [, ...] ] ) ] [, ...]
| ALL { FUNCTIONS | PROCEDURES | ROUTINES } IN SCHEMA schema_name [,
...] }
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ USAGE | ALL [ PRIVILEGES ] }
ON LANGUAGE lang_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ { SELECT | UPDATE } [, ...] | ALL [ PRIVILEGES ] }
ON LARGE OBJECT loid [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ { CREATE | USAGE } [, ...] | ALL [ PRIVILEGES ] }
ON SCHEMA schema_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ CREATE | ALL [ PRIVILEGES ] }
ON TABLESPACE tablespace_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ GRANT OPTION FOR ]
{ USAGE | ALL [ PRIVILEGES ] }
ON TYPE type_name [, ...]
FROM { [ GROUP ] role_name | PUBLIC } [, ...]
[ CASCADE | RESTRICT ]
REVOKE [ ADMIN OPTION FOR ]
role_name [, ...] FROM role_name [, ...]
[ CASCADE | RESTRICT ]
semantics
nothing
Example
from public Withdrawal form
filmsInsert privileges on :REVOKE INSERT ON films FROM PUBLIC;From user
manuelRetract the viewkindsAll privileges on :REVOKE ALL PRIVILEGES ON kinds FROM manuel;Notice that actually means “ Take back all the privileges I have granted ”.
From user
joeTake back the roleadminsMembership in :REVOKE admins FROM joe;
Compatibility
GRANT The compatibility annotation of the command also applies to
REVOKE. According to the standard , key wordRESTRICTorCASCADEbe necessary , however KingbaseES The default assumption isRESTRICT.
20.13. ROLLBACK
purpose
ROLLBACKRollback the current transaction and cause All updates made by the firm were discarded .
precondition
In business
grammar
ROLLBACK [ WORK | TRANSACTION ] [ AND [ NO ] CHAIN ]
semantics
WORKTRANSACTIONOptional keywords , There is no effect .
AND CHAINIf you specify
AND CHAIN, Then immediately start a new transaction with the same transaction characteristics as the transaction just completed ( See SET TRANSACTION ). otherwise , No new transactions will be started .
Example
To rollback all changes :
ROLLBACK;
Compatibility
ROLLBACKThe command conforms to SQL standard .ROLLBACK TRANSACTIONIt's a KingbaseES Expand .
20.14. ROLLBACK PREPARED
purpose
ROLLBACK PREPARED — Cancel a transaction prepared for two-phase commit
ROLLBACK PREPAREDRoll back A transaction in a ready state
precondition
To rollback a prepared transaction , You must be the same user or super user who originally executed the transaction . But you must be in the same session where the transaction is executed .
grammar
ROLLBACK PREPARED transaction_id
semantics
transaction_idTransaction identifier of the transaction to be rolled back .
Example
Use the transaction identifier
foobarRollback the corresponding transaction :ROLLBACK PREPARED 'foobar';
Compatibility
ROLLBACK PREPAREDIt's a kind of KingbaseES Expand . It is intended for use in external transaction management systems , Some of them have been covered by the standard ( for example X/Open XA), But those systems SQL Aspects are not standardized .
other
This command cannot be executed within a transaction block . The prepared transaction will be rolled back immediately .
sys_prepared_xacts All prepared transactions currently available are listed in the system view .
20.15. ROLLBACK TO SAVEPOINT
purpose
ROLLBACK TO SAVEPOINT — Rollback to a savepoint
Rollback all commands executed after the savepoint is established . The savepoint remains valid and can be rolled back to it again later ( if necessary ).
ROLLBACK TO SAVEPOINTImplicitly destroy all savepoints established after the mentioned savepoints .
precondition
Save points need to be established in advance
grammar
ROLLBACK [ WORK | TRANSACTION ] TO [ SAVEPOINT ] savepoint_name
semantics
savepoint_nameThe savepoint to rollback to .
Example
To undo in
my_savepointThe effect of the command executed after establishment :ROLLBACK TO SAVEPOINT my_savepoint;Cursor position is not affected by savepoint rollback :
BEGIN; DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2; SAVEPOINT foo; FETCH 1 FROM foo; ?column? ---------- 1 ROLLBACK TO SAVEPOINT foo; FETCH 1 FROM foo; ?column? ---------- 2 COMMIT;
Compatibility
SQL The standard specifies keywords
SAVEPOINTIt's mandatory , however KingbaseES and Oracle Allow it to be omitted .SQL OnlyWORKinstead ofTRANSACTIONAsROLLBACKAfter the noise words . also ,SQL There is an optional clauseAND [ NO ] CHAIN, At present KingbaseES Does not support . In other ways , This command conforms to SQL standard .
other
Use RELEASE SAVEPOINT The effect of destroying a savepoint without discarding the command that was executed after it was established .
It is an error to specify a savepoint that has not been created .
Relative to savepoint , Cursors have a little non transactional behavior . When the savepoint is rolled back , Any cursor opened within the savepoint will be closed . If a previously opened cursor is ``FETCH`` or
MOVEAffected by the order , The savepoint was later rolled back , Then the cursor will remainFETCHMake it point to the position ( That is to say, byFETCHThe resulting cursor action will not be rolled back ). Rollback cannot undo closing a cursor . however , Other side effects caused by cursor queries ( For example, the side effect of the variable function called by the query ) Can be rolled back , As long as they occur during a savepoint that is later rolled back . If the execution of a cursor causes the transaction to abort , It will be placed in a state that cannot be executed , So when transactions are usedROLLBACK TO SAVEPOINTAfter recovery , The cursor can no longer be used .
20.16. SAVEPOINT
purpose
SAVEPOINTCreate a new savepoint in the current transaction .A savepoint is a special token within a transaction , It allows all commands executed after it is established to be Roll back , Restore the state of the transaction to what it looked like when it was at the savepoint .
precondition
Savepoints can only be created in one transaction block . Multiple savepoints can be defined within a transaction .
grammar
SAVEPOINT savepoint_name
semantics
savepoint_nameGive the name of the new save point .
Example
To create a savepoint and then undo the effect of all commands executed after it is created :
BEGIN; INSERT INTO table1 VALUES (1); SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (2); ROLLBACK TO SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (3); COMMIT;The above transaction will insert values 1 and 3, But it won't insert 2.
To create and later destroy a savepoint :
BEGIN; INSERT INTO table1 VALUES (3); SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (4); RELEASE SAVEPOINT my_savepoint; COMMIT;The above transaction will be inserted 3 and 4.
Compatibility
When creating another savepoint with the same name ,SQL The save point before the standard requirements is automatically destroyed . stay KingbaseES in , Old savepoints will be preserved , But it's going on Only the latest one can be used when rolling back or releasing ( use
RELEASE SAVEPOINTReleasing a newer savepoint will As a result, the older savepoints become available againROLLBACK TO SAVEPOINTandRELEASE SAVEPOINTvisit ). In other ways ,SAVEPOINTIt's completely in line SQL.
other
Use ROLLBACK TO Rollback to a savepoint . Use RELEASE SAVEPOINT Destroy a savepoint , But keep the effect of the command executed after it is established .
20.17. SECURITY LABEL
purpose
SECURITY LABEL — Define or change the security label applied to an object
SECURITY LABELApply a security label to a database object . You can put any number of safety labels ( Each tag provider corresponds to one ) Associate to a given database object . Tag providers use functions ``register_label_provider`` Register your own loadable modules .Be careful
register_label_providerIs not a SQL function , It can only be loaded To the back end C Call in code .
precondition
nothing
grammar
SECURITY LABEL [ FOR provider ] ON
{
TABLE object_name |
COLUMN table_name.column_name |
AGGREGATE aggregate_name ( aggregate_signature ) |
DATABASE object_name |
DOMAIN object_name |
EVENT TRIGGER object_name |
FOREIGN TABLE object_name
FUNCTION function_name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] |
LARGE OBJECT large_object_oid |
MATERIALIZED VIEW object_name |
[ PROCEDURAL ] LANGUAGE object_name |
PUBLICATION object_name |
ROLE object_name |
SCHEMA object_name |
SEQUENCE object_name |
SUBSCRIPTION object_name |
TABLESPACE object_name |
TYPE object_name |
VIEW object_name
} IS 'label'
among aggregate_signature yes :
* |
[ argmode ] [ argname ] argtype [ , ... ] |
[ [ argmode ] [ argname ] argtype [ , ... ] ] ORDER BY [ argmode ] [ argname ]
argtype [ , ... ]
semantics
object_nametable_name.column_nameaggregate_namefunction_nameThe name of the object to be labeled . surface 、 Gather 、 Domain 、 External table 、 function 、 Sequence 、 Type and view The name of can be schema qualified .
providerThe name of the provider associated with this tag . The mentioned provider must have been loaded and must agree with the proposed Label operation . If only one provider happens to be loaded , The name of the provider can be ignored for brevity .
argmodeThe pattern of a function or aggregate parameter :
IN、OUT、INOUTperhapsVARIADIC. If it's ignored , The default value will beIN. Be carefulSECURITY LABELNot really Care forOUTParameters , Because you only need to input parameters when judging the identity of the function . So listIN、INOUTandVARIADICParameters are enough .
argnameThe name of a function or aggregate parameter . Be careful
SECURITY LABELDon't really care about the name of the parameter , Because only the data type of the parameter is needed to judge the identity of the function .
argtypeThe data type of a function or aggregate parameter .
large_object_oidBig object OID.
PROCEDURALThis is a noisy word .
labelWrite a new security label as string text . If written
NULLSaid to delete Original safety labels .
Example
The following example shows how to change the security label of a table .
SECURITY LABEL FOR selinux ON TABLE mytable IS 'system_u:object_r: sekbsql_table_t:s0';
Compatibility
stay SQL There is no in the standard
SECURITY LABELcommand .
other
The tag provider decides whether a given tag is legal and whether it can be assigned to a given object . The meaning of a given tag is also determined by the tag provider .KingbaseES There are no restrictions on whether a label provider must or how to interpret a security label , It just provides a mechanism to store them . actually , This function is to allow mandatory access control with tags (MAC) System integration ( for example SE-Linux). Such systems will be based on object tags rather than traditional autonomous access control (DAC) Concept ( For example, users and groups ) Make all access control decisions .
20.18. SELECT
purpose
SELECT, TABLE, WITH — Retrieve rows from a table or view .
SELECTRetrieve rows from zero or more tables .SELECTThe usual treatment of is as follows :
WITHAll queries in the list will be calculated . These queries are actually Acted as inFROMTemporary tables that can be referenced in the list . stayFROMHas been quoted many times inWITHThe query will only be calculated once . unless specified otherwise withNOT MATERIALIZED.
FROMAll elements in the list will be calculated (FROMEvery element in is a real table or virtual table ). If inFROMMore than one element is specified in the list , They will be Cross connected .If you specify
WHEREClause , All lines that do not meet this condition will Be eliminated from the output .If you specify
GROUP BYClause or if there is an aggregate function , Output Will be grouped into groups consisting of rows that match on one or more values , And calculate the poly The result of the set function . If it doesHAVINGClause , It will eliminate No Groups that meet the given conditions .For each selected row or row group , Will use
SELECTThe output expression evaluates the actual output line .
SELECT DISTINCTEliminate duplicate rows from the results .SELECT DISTINCT ONEliminate matches on all specified expressions Matching line .SELECT ALL( Default ) All candidate rows will be returned , Include duplicate lines .meanwhile KingbaseES Medium SELECT UNIQUEYou can also eliminate duplicate lines from the results .SELECT UNIQUE ONEliminate matches on all specified expressions Matching line .SELECT ALL( Default ) All candidate rows will be returned , Include duplicate lines .By using the operator
UNION、INTERSECTandEXCEPT, More than OneSELECTThe output of statements can be integrated into A result set .UNIONThe operator returns one or two All rows in the result set .INTERSECTThe operator returns simultaneously All rows in both result sets .EXCEPTOperator return Rows in the first result set but not in the second result set . In all three cases , Duplicate lines will be eliminated ( Unless specifiedALL). Can increase noise Phonetic wordsDISTINCTTo explicitly eliminate duplicate rows . Pay attention thoughALLyesSELECTIts own default behavior , But hereDISTINCTIt's the default behavior .If you specify
ORDER BYClause , The returned row will be returned with the specified Order . If there is no givenORDER BY, The system will be able to Quickly generate rows and return them in order (.If you specify
LIMIT( orFETCH FIRST) perhapsOFFSETClause ,SELECTStatement returns only a subset of the result row .If you specify
FOR UPDATE、FOR NO KEY UPDATE、FOR SHAREperhapsFOR KEY SHARE,SELECTStatement will lock the selected row without concurrency Update access them .
precondition
You must have in one
SELECTOn each column used in the commandSELECTPrivilege .FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREperhapsFOR KEY SHAREAlso require ( For each table so selected, at least one column )UPDATEPrivilege .
grammar
[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT | UNIQUE [ ON ( expression [, ...] ) ] ]
[ * | expression [ [ AS ] output_name ] [, ...] ]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY grouping_element [, ...] ]
[ HAVING condition [, ...] ]
[ WINDOW window_name AS ( window_definition ) [, ...] ]
[ { UNION | INTERSECT | EXCEPT | MINUS } [ ALL | DISTINCT ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST |
LAST } ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start [ ROW | ROWS ] ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]
[ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF table_name
[, ...] ]
[ NOWAIT | SKIP LOCKED | WAIT seconds] [...] ]
among from_item It can be one of the following :
[ ONLY ] table_name [ * ] [ @dblink ]
[ PARTITION partition | SUBPARTITION subpartition ]
[ [ AS ] alias [ ( column_alias [, ...] ) ] ]
[ [ AS OF { TIMESTAMP | CSN | SCN } asof_item ] | [ VERSIONS BETWEEN { TIMESTAMP | CSN | SCN } start_item AND end_item ] ]
[ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE
( seed ) ] ]
[ LATERAL ] ( select ) [ AS ] alias [ ( column_alias [, ...] ) ] with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
[ LATERAL ] function_name ( [ argument [, ...] ] )
[ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
[ LATERAL ] function_name ( [ argument [, ...] ] ) [ AS ] alias ( column_definition [, ...] )
[ LATERAL ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
[ LATERAL ] ROWS FROM( function_name ( [ argument [, ...] ] ) [ AS ( column_definition [, ...] ) ] [, ...] )
[ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
from_item [ NATURAL ] join types from_item [ ON join_condition | USING ( join_column [, ...] ) ]
also grouping_element It can be one of the following :
( )
expression
( expression [, ...] )
ROLLUP ( { expression | ( expression [, ...] ) } [, ...] )
CUBE ( { expression | ( expression [, ...] ) } [, ...] )
GROUPING SETS ( grouping_element [, ...] )
also with_query yes :
with_query_name [ ( column_name [, ...] ) ] AS [ [ NOT ] MATERIALIZED ] ( select | values | insert | update | delete )
TABLE [ ONLY ] table_name [ * ]
plsql_declarations
semantics
WITH Clause
WITHClause allows you to specify one or more that can The subquery referenced by its name . During the main query, the sub query actually acts as a temporary table or view Role . Each subquery can be aSELECT、TABLE、VALUES、INSERT、UPDATEperhapsDELETEsentence . stayWITHIn the writing A data modification statement (INSERT、UPDATEperhapsDELETE) when , Usually include aRETURNINGClause . The temporary tables read by the main query areRETURNINGOutput , Not modified by this statement The underlying table . If omittedRETURNING, The statement will still be executed , But it is No output , Therefore, it cannot be referenced from the main query as a table .For each of these
WITHInquire about , Must specify a name ( There is no need to mold Formula limit ). Optionally , You can specify a list of column names . If you omit this list , Will check from this sub Derive column names in query .If you specify
RECURSIVE, Then allow aSELECTSubqueries reference themselves by name . Such a subquery must be in the form ofnon_recursive_term UNION [ ALL | DISTINCT ] recursive_termThe recursive self reference must appear in
UNIONOn the right side of . Every Only one recursive self reference is allowed in the query . Recursive data modification statements are not supported , however You can use a recursion in a data query statementSELECTResult of query . Examples can be seen WITH Inquire about .
RECURSIVEAnother effect of isWITHQueries do not need to be sorted : One query can reference another Queries that are later in the list ( however , Circular reference or mutual recursion is not implemented ). withoutRECURSIVE,WITHQueries can only be referenced inWITHThe brother in front of the listWITHInquire about .Main query and
WITHQuery all ( Theoretically ) At the same time Be performed . This means that you cannot see from any part of the queryWITHThe effect of a data modification statement in , But you can read takeRETURNINGOutput . If two such data modification statements Try to modify the same line , The result will not be certain .
WITHThe key attribute of the query is , Every time the main query is executed , They are usually evaluated only once , Even if the main query references them more than once . especially , The data modification statement is guaranteed to be executed only once , Regardless of whether the main query reads all or any output .however ,
WITHQueries can be markedNOT MATERIALIZEDTo remove this warranty . under these circumstances ,WITHQueries can be folded into main queries , It's like it's in the main queryFROMA simpleSELECT. If the main query references more than onceWITHInquire about , It will lead to double calculation ; however , If each such use only needsWITHThe total output of the query is several rows of data ,NOT MATERIALIZEDYou can provide net savings by allowing queries to be jointly optimized .NOT MATERIALIZEDWill be ignored , If it is recursive or not without side effectsWITHQuery additional ( for example :, It's not an ordinarySELECTIt doesn't contain volatile functions).By default , If in the main query
FROMClause is used only once , Then there are no side effectsWITHThe query will be collapsed into the main query . This allows two query levels to be jointly optimized when semantics are not visible . however , It can be done by puttingWITHThe query is marked asMATERIALIZEDTo prevent this folding . This may be useful , for example , IfWITHQueries are used as an optimization fence , To prevent planners from choosing a bad plan . stay v12 In the previous version ,KingbaseES Never fold like this , So queries written for older versions may rely onWITHTo act as an optimization barrier .For more information, see WITH Inquire about .
FROM Clause
FROMThe clause isSELECTSpecify one or more source tables . If multiple source tables are specified , The result will be... Of all source tables The cartesian product ( Cross connect ). But it usually adds restrictions ( adoptWHERE) To limit the returned row to a subset of the Cartesian product .
FROMClauses can contain the following elements :
table_nameThe name of an existing table or view ( It can be pattern Limited ). If
ONLY, Only this table will be scanned . If not specifiedONLY, This table and all its successors represent ( If there is ) Will be scanned . can Site selection , You can specify*To explicitly indicate that the post representation is included .
@dblinkstay SELECT Of the statement FROM clause , Users can directly add @dblink To specify an object in an external database . Access form :[email protected] Object name : Support qualified names (schema.name Format ) The remote object : It could be a watch 、 View 、 Materialized view , Object types are transparent to local databases . Use dblink You need to configure the corresponding database ODBC data source .
partition
PARTITIONSpecify the primary partition name of the partition or composite partition of a single-layer partition table .
subpartition
SUBPARTITIONSpecify the sub partition name of a composite partition .
aliasAn alias containing
FROMAlternative names for items . Aliases are used for Make writing concise or eliminate confusion in self connection ( The same table will be scanned more than Time ). When providing an alias , The actual name of the table or function will be hidden . example Such as , GivenFROM foo AS f,SELECTThe rest of the must be infinstead offooTo quote thisFROMterm . If you write an alias , You can also write a column Column table to provide alternative names for one or more columns of the table .
asof_item``table_name`` After that ``AS OF`` Clause indicates the function of applying flashback query . Flashback queries can be made by specifying a timestamp (timestamp)、csn There are two ways to query .
asof_itemThat is, by timestamp (timestamp) perhaps csn The expression of a historical snapshot moment when performing a flashback query .For more information, see 《Oracle to KingbaseES V8R6 Migration best practices 》 Flashback technology in .
start_item and end_item``table_name`` After that ``VERSIONS BETWEEN`` Clause indicates the version history query function of applying flashback query , and ``AS OF`` The clause is similar to , You can also use timestamp (timestamp)、csn There are two ways to query . The flashback version query specifies the starting snapshot time, that is :
start_item`` And the ending snapshot moment ``end_item, Return all visible versions during this period .For more information, see 《Oracle to KingbaseES V8R6 Migration best practices 》 Flashback technology in .
TABLESAMPLE sampling_method(argument[, ...] ) [ REPEATABLE (seed) ]``table_name`` After that
TABLESAMPLEClause indicates that the specified ``sampling_method`` To retrieve a subset of rows in a table . This sampling takes precedence over any other filter ( for exampleWHEREClause ). standard KingbaseES Publishing includes two kinds of sampling Method :BERNOULLIandSYSTEM, Other sampling methods can be installed in the database by extension .
BERNOULLIas well asSYSTEMAll sampling methods are accepted One `` Parameters ``, It represents the table to be sampled The scores of , To express as a 0 To 100 Percentage between . This parameter can be arbitraryReal valueexpression ( Other sampling methods may accept more or different Parameters ). Both methods return a randomly selected sample of the table , It contains the designation Table row of percentage .BERNOULLIMethod scans the entire table and Use the specified probability to select or ignore rows .SYSTEMMethod can do Sampling of block layer , Each block has a specific chance to be selected , All rows in the selected block are Will be returned to . When specifying a smaller sampling percentage ,SYSTEMThe way is better thanBERNOULLIIt's a lot faster , But the former may Due to clustering effect, table samples with poor randomness are returned .Optional
REPEATABLEClause specifies a that is used to generate random numbers in the sampling method `` seeds `` Number or expression . The seed value can be any non null floating-point value . If the table is not changed during query , Specify the same seed and ``argument`` Two queries of value will select the same sampling of the table . But different seed values usually produce different samples . If not givenREPEATABLE, Then a new random sample will be selected for each query based on the seed generated by a system . Note that some extended sampling methods are not acceptableREPEATABLE, And will always generate new samples for each use .
selectA dime -
SELECTCan appear inFROMclause . It's like creating its output as a Exist in thisSELECTTemporary table during command . Be careful Son -SELECTMust be surrounded by parentheses , also It must be given an alias . It can also be here Use one VALUES command .
with_query_nameIt can be done by writing a
WITHThe name of the query to reference it , It's like The name of the query is a table name ( actually , TheWITHInquiry meeting Hide any real tables with the same name for the main query . if necessary , You can use Refer to the real table with the same name in a schema qualified way ). Can be like a watch , Provide an alias in the same way .
plsql_declarationsselect Of the statement with clause , Use plsql_declarations Clause declares and defines functions and stored procedures .
Please refer to : For specific definition parameter information, see CREATE FUNCTION、CREATE PROCEDURE etc. .
Usage rule :
1.With The function or stored procedure defined by clause follows the usage rules of ordinary function or stored procedure ;
2.With The life cycle of the function or stored procedure created by clause is current select sentence ;
3. One with Clause can define multiple plsql Function or stored procedure . And it's called ;
4.with Clause when defining a stored procedure , Can't be in select Statements are used directly , But it can be defined in function Call inside .
function_nameFunction calls can appear in
FROMclause ( For returned results Functions of sets are particularly useful , But you can use any function ). It's like putting the The output is created as an existingSELECTCommand period Temporary table of . When adding optionalWITH ORDINALITYWhen clause , In this function Add a new column after the output column of to number each row .You can provide an alias in the same way as a table . If you write an alias , You can also write a Column column table to provide alternative names for one or more attributes of the combined return type of the function , Include
ORDINALITY( If there is ) New columns added .By surrounding multiple function calls
ROWS FROM( ... )You can put them Integrated in a singleFROM- Clause item . The output of such an item is to put each The first line of the function is concatenated , Then the second line of each function , And so on . If there are some Function produces fewer rows than other functions , Then put the value above the missing data , This is returned The total number of rows is always the same as the function that produces the most rows .If the function is defined to return
recorddata type , Then there must be one Alias or keywordAS, The following shape is( column_name``data_type`` [, ... ]) List of column definitions . The column definition list must match the actual... Of the column returned by this function Quantity and type .In the use of
ROWS FROM( ... )Grammatical time , If one of the functions requires a column Definition list , It is best to put the list of column definitions inROWS FROM( ... )Should be After the call of the function . If and only if there is exactly one function and there is noWITH ORDINALITYWhen clause , To put the column definition list inROWS FROM( ... )Behind the structure .To put
ORDINALITYUse with column definition list , You have to useROWS FROM( ... )grammar , And put the column definition list inROWS FROM( ... )Inside .
join types
[ INNER ] JOIN
LEFT [ OUTER ] JOIN
RIGHT [ OUTER ] JOIN
FULL [ OUTER ] JOIN
CROSS JOINabout
INNERandOUTERConnection type , Must specify A connection condition , namelyNATURAL、ON join_conditionperhapsUSING (join_column[, ...]) One of ( There can only be one ). Its meaning is shown below . aboutCROSS JOIN, The above clause cannot appear .One
JOINClause combines twoFROMterm ( For convenience, we call it “ surface ”, Although in fact they can be of any type OfFROMterm ). If necessary, you can use parentheses to determine the nesting order . When there are no parentheses ,JOINWill nest from left to right . In any situation Condition ,JOINThe union of is better than the separationFROM- list The comma of the item is stronger .
CROSS JOINandINNER JOINWill produce a simple Cartesian product , That is, withFROMTwo are listed at the top of The results obtained from the table are the same , But use connection conditions ( If there is ) Constrain the result .CROSS JOINAndINNER JOIN ON (TRUE)equivalent , That is, the condition does not remove any rows . These connection types are just one Convenience on the mark , Because nothing you use is pureFROMandWHEREWhat they can do but they can't do .
LEFT OUTER JOINReturns the restricted Cartesian product All rows in ( That is, all combined lines that pass their connection conditions ), Plus in the left watch There is no corresponding copy of each line of the right-hand line that has passed the connection condition . Through the right hand Insert a null value into the column , This left-hand row will be extended to the full row of the join table . Pay attention to the decision When determining which rows match , Only considerJOINThe condition of the clause itself . after Apply external conditions .contrary ,
RIGHT OUTER JOINReturn all connected lines , Plus every A right-hand row without matching ( Expand with null value at the left end ). It's just for marking Convenience on , Because you can convert it into a by exchanging left and right tablesLEFT OUTER JOIN.
FULL OUTER JOINReturn all connected lines , Plus every A left-hand row without matching ( Expand with null value at the right end ), Plus every one without Match the right hand row on ( Expand with null value at the left end ).
ON join_condition``join_condition`` Is one who will get
booleanExpression of type value ( Similar to aWHEREClause ), It shows which lines in a connection are considered Match .
USING ( join_column[, ...] )form
USING ( a, b, ... )The clause of isON left_table.a = right_table.a AND left_table.b = right_table.b ...Abbreviation . also ,USINGIt means that only one of each pair of equal columns will be Included in the connection output .
NATURAL
NATURALIt's aUSINGShorthand of the list , The list mentions all the columns with matching names in the two tables . If there is no public listing , beNATURALEquivalent toON TRUE.
LATERAL
LATERALKeywords can be placed in a Son -SELECTFROMIn front of . This allows for Son -SELECTquoteFROMIt's in the list BeforeFROMColumns of items ( withoutLATERAL, each Height -SELECTWill be calculated independently and therefore cannot be cross referenced Any otherFROMterm ).
LATERALIt can also be placed in a function callFROMIn front of , But in this case, it's just a noise word , Because in any case, the function expression can refer to theFROMterm .
LATERALItems can appear inFROMlist top floor , Or aJOINin . In the latter case , It can also lead Use it as the right-hand endJOINAny item on the left-hand end .When one
FROMItem containsLATERALCross reference when , The calculation will proceed like this : For providing cross referenced columnsFROMEach of the items One row or multiple of those columnsFROMEach row set of items , Use this The column values of rows or rowsets are calculatedLATERALterm . Result guild and The rows that get them are usually connected . For each row or row of the source table from which columns Set will repeat such steps .The source table of the column must be in
INNERperhapsLEFTTo connect toLATERALterm , Otherwise, it is not used forLATERALTerm calculates the well-defined row set of each row set . Even thoughXRIGHT JOIN LATERAL ``Y`` Such a structure is grammatically legitimate , But in fact, it is not allowed to be used in ``Y`` I quote ``X``.WHERE Clause
Optional
WHEREThe form of clauseWHERE conditionamong ``condition`` Is calculated by any
BooleanExpression of type result . Any dissatisfaction The lines of this condition will be eliminated from the output . If you replace the actual value of one line with After variable reference , The expression returns true , Then the line meets the conditions .GROUP BY Clause
Optional
GROUP BYThe form of clauseGROUP BY grouping_element [, ...]
GROUP BYAll selected rows will share the same grouping expression The rows of values are compressed into one row . One is used in ``grouping_element`` Medium ``expression`` You can enter the column name 、 Output column (SELECTList item ) The name or sequence number of or by the input column Any expression composed of values . In case of ambiguity ,GROUP BYname Will be interpreted as input column names instead of output column names .If anything
GROUPING SETS、ROLLUPperhapsCUBEExists as a grouping element , beGROUP BYClause As a whole, several independent `` Grouping set ``. Its effect is equivalent to that of zaizi Build aUNION ALL, Subqueries have grouped sets as their OfGROUP BYClause .Aggregation function ( If you use ) It will be calculated on all the rows that make up each group , Thus for every A group produces a single value ( If there is an aggregate function but there is no
GROUP BYClause , Then the query will be regarded as composed of all selected rows A single grouping of ). The row set passed to each aggregate function can be called in the aggregate function Use an additionalFILTERClause to further filter , See Aggregate expression . When there is aFILTERWhen clause , Only those rows that match it will be included in the cluster Input of set function .When it exists
GROUP BYClause or any aggregate function ,SELECTList expressions cannot reference non grouped columns ( Unless it Appears in the aggregate function or its function depends on the grouping column ), Because doing so will result in returning There are many possible values when the values of non group columns . If the grouped column is the primary key of a table containing non grouped columns ( Or a subset of the primary key ), There are functional dependencies .Remember that all aggregate functions are in
HAVINGClause orSELECTAny in the list “ Scalar ” The expression was previously evaluated . This means aCASEExpressions cannot be used to skip over an aggregate expression Calculation , see Expression evaluation rules .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHAREUnable to joinGROUP BYDesignate together .HAVING Clause
Optional
HAVINGThe form of clauseHAVING conditionamong ``condition`` And
WHEREThe conditions specified in clause are the same .
HAVINGEliminate grouped rows that do not meet this condition .HAVINGAndWHEREDifferent :WHEREWill be appliedGROUP BYFilter individual rows before , andHAVINGFilter byGROUP BYCreated grouping rows . ``condition`` I quote Each column of the must reference a grouping column unambiguously ( Unless the reference appears in an aggregate Function or the non grouping column function depends on the grouping column .Even without
GROUP BYClause ,HAVINGThe existence of will also transform a query into a group query . This is similar to the query that contains aggregation functions but does notGROUP BYClause is the same . All selected rows are considered a Single grouping , alsoSELECTList andHAVINGClause can only refer to table columns in the aggregate function . If it's time toHAVINGCondition is true , Such a query will issue a single row ; Otherwise, the line is not returned .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHARECannot be associated withHAVINGDesignate together .WINDOW Clause
Optional
WINDOWThe form of clauseWINDOW window_name AS ( window_definition ) [, ...]among ``window_name`` Is one can from
OVERClause or the name referenced in subsequent window definitions . ``window_definition`` yes[ existing_window_name ] [ PARTITION BY expression [, ...] ] [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ] [ frame_clause ]If one is specified ``existing_window_name``, It must quote
WINDOWAn earlier item in the list . The new window will start from Copy its partition clause and sorting clause in this item ( If there is ). under these circumstances , New window Cannot specify its ownPARTITION BYClause , And it can only be copied There is no windowORDER BYSpecify this clause . New windows always use it Own frame clause , The copied window does not need to specify a frame clause .
PARTITION BYThe list elements are explained in GROUP BY The way of elements Conduct , However, they are always simple expressions and must not be the name or number of the output column . Another area In addition, these expressions can contain aggregate function calls , And this is normalGROUP BYClause is not allowed . They are allowed because Windows appear after grouping and aggregation .Similarly ,
ORDER BYThe explanation of list elements is also in ORDER BY Element , However, this expression is always treated as a simple expression and will never be the name or number of the output column .Optional ``frame_clause`` Is a frame dependent window function Definition Window frame ( Not all window functions depend on frames ). Window frame is in query everything ( be called Current row ) Set of related rows of . ``frame_clause`` It can be
{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ] { RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]One of , among ``frame_start`` and ``frame_end`` It can be
UNBOUNDED PRECEDING offset PRECEDING CURRENT ROW offset FOLLOWING UNBOUNDED FOLLOWINGOne of , also ``frame_exclusion`` It can be
EXCLUDE CURRENT ROW EXCLUDE GROUP EXCLUDE TIES EXCLUDE NO OTHERSOne of . If omitted ``frame_end``, It will be defaulted to
CURRENT ROW. The limitation is : ``frame_start`` It can't beUNBOUNDED FOLLOWING, ``frame_end`` It can't beUNBOUNDED PRECEDING, also ``frame_end`` Your choice is above of ``frame_start`` as well as ``frame_end`` The list of options cannot be earlier than ``frame_start`` The choice of — for exampleRANGE BETWEEN CURRENT ROW AND offsetPRECEDING It's not allowed .The default frame option is
RANGE UNBOUNDED PRECEDING, It andRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWidentical . It sets the frame from the partition to the last of the current line Level That's ok ( By the windowORDER BYClause that is equivalent to the current row , withoutORDER BYThen all lines are level ). Usually ,UNBOUNDED PRECEDINGRepresents the frame starting from the first row of the partition , SimilarlyUNBOUNDED FOLLOWINGRepresents the frame that ends with the last line of the partition , Whether inRANGE、ROWSperhapsGROUPSIn the pattern . stayROWSIn the pattern ,CURRENT ROWIndicates the frame starting or ending with the current line . And in theRANGEperhapsGROUPSIn the pattern, it indicates that the current line isORDER BYThe first in the sort Or the frame at the beginning or end of the last horizontal line . ``offset``PRECEDINGand ``offset``FOLLOWINGThe meaning of options will change with the frame mode . stayROWSIn the pattern ,``offset`` It's an integer , Indicates that the frame starts or ends at so many lines before or after the current line . stayGROUPSIn the pattern ,``offset`` It's an integer , It means that it really starts or ends at so many peer groups before or after the peer group of the current line , among Level group Is a group of according to the windowORDER BYClause equivalent row . stayRANGEIn the pattern ,``offset`` The use of options requires exactly one in the window definitionORDER BYColumn . Then the sorting column value of the rows contained in this frame does not exceed ``offset`` And less than ( aboutPRECEDING) Or greater than ( aboutFOLLOWING) The sorting column value of the current row . In these cases ,``offset`` The data type of the expression depends on the data type of the sequence . For digital sequence , It is usually of the same type as the row , But for the datetime Sort column of type it isinterval. In all these cases ,``offset`` The value of must be non empty and non negative . Besides , although ``offset`` It doesn't have to be a simple constant , But it cannot contain variables 、 Aggregate function or window function .``frame_exclusion`` Option allows lines around the current line to be excluded from the frame , Even according to the start option of the frame, they should be included in the frame .
EXCLUDE CURRENT ROWExclude the current line from the frame .EXCLUDE GROUPExclude the current row and its horizontal row in sorting from the frame .EXCLUDE TIESExclude any horizontal rows of the current row from the frame , However, the current row itself is not excluded .EXCLUDE NO OTHERSJust explicitly specify the default behavior that does not exclude the current row or its peers .Be careful , If
ORDER BYSorting cannot uniquely sort rows , beROWSPatterns can produce unpredictable results .RANGEas well asGROUPSThe purpose of the pattern is to ensure thatORDER BYEqual rows in the order are treated the same : All rows in a given peer group are in a frame or excluded from the frame .
WINDOWThe purpose of clause is to specify the SELECT list or ORDER BY Medium Window function act . These functions can be found in theirOVERClause with name referenceWINDOWClause item . however ,WINDOWClause items do not have to be referenced . If it is not used in the query , It will simply be ignored . It can be used without anyWINDOWClause window function , Because window function calls can Directly in itsOVERClause to specify its window definition . however , Dangduo When both window functions need the same window definition ,WINDOWClause can reduce input .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHAREUnable to joinWINDOWDesignated together .The detailed description of the window function is in Advanced features Window function 、 Window function call ` as well as :ref:` Window function processing in .
SELECT list
SELECTlist ( Located in the keywordSELECTandFROMBetween ) Specified compositionSELECTStatement output line expression . These expressions Sure ( And it usually does ) quoteFROMColumn calculated in Clause .As in the table ,
SELECTEach output column of has a name . In a simpleSELECTin , This name is only used to mark to show Columns shown , But whenSELECTIs a sub query of a large query , Large queries This name will be regarded as the column name of the virtual table generated by the sub query . To specify the name of the output column , The expression in this column Write... On the backAS``output_name``( You can omitAS, But only if the expected output name does not match any KingbaseES key word ( see SQL key word ) Omit . In order to avoid conflicts with the future increase of keywords , Recommendations are always writtenASOr use double quotation marks to refer to the output name ). If you do not specify the column name , KingbaseES Will automatically select a name . If the expression of the column Is a simple column reference , Then the selected name is the same as the name of the column . Using function or type names In a more complex situation , The system may generate such as?column?Names like that .The name of an output column can be used in
ORDER BYas well asGROUP BYClause to reference the value of this column , But not forWHEREandHAVINGClause ( In which the You must write an expression ).You can write... In the output list
*Let's take the representative expression , It is selected A shorthand for all columns of a row . You can also writetable_name.*, it Is a short form of all columns from that table only . Cannot be used in these casesASSpecify a new name , The name of the output row will be the same as that of the table column .according to SQL standard , The expression in the output list should be applied
DISTINCT、ORDER BYperhapsLIMITCalculated before . In the use ofDISTINCTObviously, this must be done , Otherwise, we cannot figure out what value we are distinguishing . however , In many cases, if you first calculateORDER BYandLIMITIt will be convenient to calculate the output expression again , Especially if the output list contains any volatile This is especially true for functions or expensive functions . Through this behavior , The order of function calculation is more intuitive and will not be calculated for lines that never appear in the output . As long as the output expression is notDISTINCT、ORDER BYperhapsGROUP BYquote ,KingbaseES The output expression will actually be evaluated after sorting and limiting the number of rows ( As a counterexample ,SELECT f(x) FROM tab ORDER BY 1Obviously, it must be calculated before sortingf(x)). The output expression containing the set return function is actually evaluated after sorting and before limiting the number of rows , suchLIMITTo cut off the output from the set return function .Be careful
V8.2 pre-release KingbaseES Do not execute the output expression 、 Sort 、 The chronological order of limiting the number of lines makes no guarantee , That will depend on the form of the selected query plan .
DISTINCT Clause
If you specify
SELECT DISTINCT, All repeated rows will be removed from the result Centralized removal ( Reserve one row for each set of repeated rows ).SELECT ALLbe Specify the opposite behavior : All lines will be preserved , This is also the default .
SELECT DISTINCT ON ( expression[, ...] ) Only the first row in the set of rows that evaluate equality on a given expression .DISTINCT ONExpressions use andORDER BYThe same rules ( See above ) explain . Be careful , Unless withORDER BYTo ensure that the desired row appears first , Every episode Combined “ first line ” It's unpredictable . for example :SELECT DISTINCT ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;Retrieve the latest weather report for each location . But if we don't use
ORDER BYTo force the time values of each location to be sorted in descending order , The timing of the reports we receive for each location may be unpredictable .
DISTINCT ONThe expression must match the leftmostORDER BYexpression .ORDER BYClauses usually Will contain additional expressions , These additional expressions are used to determine in eachDISTINCT ONGroup the priority of experts .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHAREUnable to joinDISTINCTUse it together .UNIQUE Clause
If you specify
SELECT UNIQUE, All repeated rows will be removed from the result Centralized removal ( Reserve one row for each set of repeated rows ).SELECT ALLbe Specify the opposite behavior : All lines will be preserved , This is also the default .
SELECT UNIQUE ON ( expression[, ...] ) Only the first row in the set of rows that evaluate equality on a given expression .UNIQUE ONExpressions use andORDER BYThe same rules ( See above ) explain . Be careful , Unless withORDER BYTo ensure that the desired row appears first , Every episode Combined “ first line ” It's unpredictable . for example :SELECT UNIQUE ON (location) location, time, report FROM weather_reports ORDER BY location, time DESC;Retrieve the latest weather report for each location . But if we don't use
ORDER BYTo force the time values of each location to be sorted in descending order , The timing of the reports we receive for each location may be unpredictable .
UNIQUE ONThe expression must match the leftmostORDER BYexpression .ORDER BYClauses usually Will contain additional expressions , These additional expressions are used to determine in eachDISTINCT ONGroup the priority of experts .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHAREUnable to joinUNIQUEUse it together .UNION Clause
UNIONClause has the following form :select_statement UNION [ ALL | DISTINCT ] select_statement``select_statement`` Is anything without
ORDER BY、LIMIT、FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHAREClauseSELECTsentence ( If the subexpression is enclosed in parentheses ,ORDER BYandLIMITCan be attached to it . without parentheses , These clauses will be applied toUNIONInstead of the right-hand side On the expression of ).
UNIONOperator calculation involvesSELECTThe union of the rows returned by the statement . If a line Appear in at least one of the two result sets , It will merge . AsUNIONOf two operandsSELECTStatement must produce the same number of columns and The column in the corresponding position must have a compatible data type .
UNIONThe result of will not contain duplicate lines , Unless specifiedALLOptions .ALLWill prevent de duplication ( therefore ,UNION ALLUsually significantly faster thanUNION, Use as much as possibleALL). Can writeDISTINCTCome on Explicitly specify the behavior of eliminating duplicate rows .Unless the order of calculation is specified in parentheses , The same
SELECTMultiple in the statementUNIONThe operator will calculate from left to right .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHARECannot be used forUNIONResult orUNIONAny input from .INTERSECT Clause
INTERSECTClause has the following form :select_statement INTERSECT [ ALL | DISTINCT ] select_statement``select_statement`` Is anything without
ORDER BY,LIMIT、FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREas well asFOR KEY SHAREClauseSELECTsentence .
INTERSECTOperator calculation involvesSELECTStatement returns the intersection of rows . If A row appears in both result sets at the same time , It's in the intersection .
INTERSECTThe result of will not contain duplicate lines , Unless specifiedALLOptions . If there isALL, One has ``m`` Repeat times and in the right table ``n`` Repeated rows will appear in the result min(``m``,``n``) Time .DISTINCTCan writeDISTINCTCome on Explicitly specify the behavior of eliminating duplicate rows .Unless the order of calculation is specified in parentheses , The same
SELECTMultiple in the statementINTERSECTThe operator will calculate from left to right .INTERSECTThe priority ratioUNIONHigher . in other words ,A UNION B INTERSECT CWill be read asA UNION (B INTERSECT C).At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHARECannot be used forINTERSECTResult orINTERSECTAny input from .EXCEPT Clause
EXCEPTClause has the following form :select_statement EXCEPT [ ALL | DISTINCT ] select_statement``select_statement`` Is anything without
ORDER BY、LIMIT、FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREas well asFOR KEY SHAREClauseSELECTsentence .
EXCEPTOperator calculation is on the leftSELECTThe result of the statement is in but not on the rightSELECTThe row set in the statement result .
EXCEPTThe result of will not contain duplicate lines , Unless specifiedALLOptions . If there isALL, One has ``m`` Repeat times and in the right table ``n`` Repeated rows will appear in the result set max(``m``-``n``,0) Time .DISTINCTCan writeDISTINCTCome on Explicitly specify the behavior of eliminating duplicate rows .Unless the order of calculation is specified in parentheses , The same
SELECTMultiple in the statementEXCEPTThe operator will calculate from left to right .EXCEPTWith the priority ofUNIONidentical .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHARECannot be used forEXCEPTResult orEXCEPTAny input from .MINUS Clause
MINUSClause has the following form :select_statement MINUS [ ALL | DISTINCT ] select_statement``select_statement`` Is anything without
ORDER BY、LIMIT、FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREas well asFOR KEY SHAREClauseSELECTsentence .
MINUSOperator calculation is on the leftSELECTThe result of the statement is in but not on the rightSELECTThe row set in the statement result .
MINUSThe result of will not contain duplicate lines , Unless specifiedALLOptions . If there isALL, One has ``m`` Repeat times and in the right table ``n`` Repeated rows will appear in the result set max(``m``-``n``,0) Time .DISTINCTCan writeDISTINCTCome on Explicitly specify the behavior of eliminating duplicate rows .Unless the order of calculation is specified in parentheses , The same
SELECTMultiple in the statementMINUSThe operator will calculate from left to right .MINUSWith the priority ofUNIONidentical .At present ,
FOR NO KEY UPDATE、FOR UPDATE、FOR SHAREandFOR KEY SHARECannot be used forMINUSResult orMINUSAny input from .ORDER BY Clause
Optional
ORDER BYThe form of the clause is as follows :ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...]
ORDER BYClause causes the result row to be sorted according to the specified expression . If the two lines are equal according to the leftmost expression , Then they will be compared according to the next expression , By analogy . If they are equal according to all specified expressions , Then they are returned The order depends on the implementation .every last ``expression`` It can be an output column (
SELECTList item ) Or Serial number , It can also be any expression composed of input column values .Sequence number refers to the order of output columns ( From left to right ) Location . This feature can be unique The name column defines an order . This is not absolutely necessary , Because it can always be used
ASClause gives the output column a name .It can also be in
ORDER BYUse any expression in Clause , Including There are people who appear inSELECTOutput columns in the list . therefore , The following statement is legal :SELECT name FROM distributors ORDER BY code;One limitation of this feature is an application in
UNION、INTERSECTorEXCEPTClause resultORDER BYOnly output column name or sequence number can be specified , But you cannot specify an expression .If one
ORDER BYAn expression is one that matches both the output column name and Enter a simple name for the column name ,ORDER BYIt will be interpreted as the output column name call . This is the same as in the same caseGROUP BYWill make the opposite choice . such Inconsistency is to be consistent with SQL Standard compatible .It can be for
ORDER BYAdd keywords after any expression in the clauseASC( rising )DESC( falling ). If not specified ,ASCAssumed to be the default . perhaps , Can be inUSINGClause to specify a specific sort operator name . A sort operator must be some B- The less than or greater than member of the tree operator family .ASCUsually equivalent toUSING <andDESCUsually equivalent toUSING >( But the creator of a user-defined data type can Define exactly what the default sort order is , And it may correspond to operators with other names ).If specified
NULLS LAST, Null values will rank after non null values ; If specifiedNULLS FIRST, Null values will rank before non null values . If not specified , Specified or impliedASCThe default behavior isNULLS LAST, And specify or implyDESCThe default behavior isNULLS FIRST( therefore , The default behavior is that null values are greater than non null values ). When specifyingUSINGwhen , The default order of null values depends on whether the operator is Less than or greater than operator .Note that the order options only apply to the expressions they follow . for example
ORDER BY x, y DESCandORDER BY x DESC, y DESCIs different .The string data will be sorted according to the collation referenced to the sorted column . According to the need, you can use ``expression`` It includes a
COLLATEClause to override , for exampleORDER BY mycolumn COLLATE "en_US". For more information, see Collation expression and Sort rule .LIMIT Clause
LIMITA clause consists of two independent clauses :LIMIT { count | ALL } OFFSET start``count`` Specify to return The maximum number of lines , and ``start`` Specify the number of rows to skip before returning rows . When both are specified , At the beginning of the calculation to return ``count`` I will skip before going ``start`` That's ok .
If ``count`` Expression evaluation by NULL, It will be treated as
LIMIT ALL, There is no limit . If ``start`` The calculation for the NULL, It will be treated asOFFSET 0.SQL:2008 A different syntax is introduced to achieve the same result , KingbaseES And support it :
OFFSET start { ROW | ROWS } FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLYIn this grammar , Standard requirements ``start`` or ``count`` Is a text constant 、 A parameter or a variable name . And as a kind of KingbaseES An extension of , Other expressions are also allowed , But it usually needs to be enclosed in parentheses to avoid ambiguity . If in a
FETCHOmit... From clause ``count``, Its default value is 1.ROWandROWSas well asFIRSTandNEXTIt's noise , They do not affect The effect of these clauses . According to the standard , If all exist ,OFFSETClause Must appear inFETCHBefore clause . however KingbaseES More relaxed , It allows two orders .In the use of
LIMITwhen , Use oneORDER BYClause handle It is a good idea to restrict the resulting rows to a unique order . Otherwise, you can get the query result line An unpredictable subset — You may ask from the 10 To the first 20 That's ok , But in In what order 10 To the first 20 Well ? Unless specifiedORDER BY, you I don't know the order .When generating a query plan, the query planner will consider
LIMIT, therefore According to what you useLIMITandOFFSET, You are likely to Get different plans ( Get different row order ). therefore , Use differentLIMIT/OFFSETValue to select a query result Different subsets will give inconsistent results , Unless you useORDER BYForce a predictable sequence of results . This is not a defects , It is SQL No commitment in any particular order ( Unless usedORDER BYTo constrain the order ) The fact that a query result is given makes The inevitable consequence of success .If there is no one
ORDER BYTo force the selection of a certain subset , Repeat the sameLIMITThe query may even return a row in the table Different subsets of . Again , This is not a defect , In such a case, it is impossible Ensure the certainty of the results .Lock clause
FOR UPDATE、FOR NO KEY UPDATE、FOR SHAREandFOR KEY SHAREyes Lock clause , They affectSELECTHow to lock rows when getting them from the table .The general form of a locking clause :
FOR lock_strength [ OF table_name [, ...] ] [ NOWAIT | SKIP LOCKED | WAIT seconds ]among ``lock_strength`` It can be
UPDATE NO KEY UPDATE SHARE KEY SHAREOne of .
To prevent this operation from waiting for other transactions to commit , You can use
NOWAITperhapsSKIP LOCKEDperhapsWAIT secondsOptions . UseNOWAITwhen , If the selected row cannot be locked immediately , This statement will report an error instead of waiting . UseSKIP LOCKEDwhen , Any selected row that cannot be locked immediately Will be skipped . Skipping locked rows will provide an inconsistent view of the data , So this is not suitable Work for general purposes , But it can be used to prevent multiple users from accessing a table similar to a queue Lock competition occurs . UseWAIT secondswhen , Before the locked row becomes available , Waiting for the most seconds second , If the wait succeeds, the result set is returned , Otherwise, the error will be returned in case of exceeding . Be carefulNOWAIT,SKIP LOCKEDandWAIT secondsOnly suitable for row lock — RequiredROW SHARETable level locks will still be obtained in the conventional way . If you want a table lock that doesn't wait , You can use the belt firstNOWAITOf LOCK .If a specific table is mentioned in a lock clause , Only from those tables The row will be locked , whatever
SELECTUsed in Other tables are simply read as usual . A locking clause without a table list will affect All tables used in this statement . If a lock clause is applied to a view or Subquery , It will affect all tables used in this view or subquery . however , these Clause does not apply toWITHInquire about . If you wish In aWITHRow locking occurred in the query , It's time toWITHSpecify a locking clause in the query .If it is necessary to specify different locking behaviors for different tables , You can write multiple locking clauses . If the same table is mentioned in more than one locking clause ( Or be affected implicitly ), Then it will be handled according to the strongest locking behavior specified . Similarly , If in any Clauses that affect a table specify
NOWAIT, Will followNOWAITBehavior to handle the table . Otherwise, ifSKIP LOCKEDSpecified in any clause that affects the table , The table will be according toSKIP LOCKEDTo deal with it .If the returned row cannot be clearly consistent with the row in the table , You cannot use the locking clause . For example, locking clauses cannot be used with aggregates .
When a lock clause appears in a
SELECTWhen querying the top level , The locked row is exactly the row returned by the query . In the case of connection query , Be locked The rows of are those that contribute to the returned connection rows . Besides , From the snapshot of the query The row of the query condition is locked , If they are updated after the snapshot and are no longer satisfied Query criteria , They will not be returned . If usedLIMIT, as long as The number of returned rows meets the limit , Locking will stop ( But pay attention to beingOFFSETSkipped rows are locked ). Similarly , If in a cursor The lock clause is used in the query of , Only the rows actually fetched or skipped by the cursor will be lock .When a lock clause appears in a child -
SELECTIn the middle of the day , Be locked Rows are the rows that the subquery returns to the outer query . The number of locked rows may be greater than See less from the perspective of the subquery itself , Because the conditions from the outer query may be used To optimize the execution of subqueries . for example :SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;Will only lock with
col1 = 5The line of ( Although it is not written in the subquery This condition ).Previous releases cannot maintain a lock upgraded by later savepoints . for example , This code :
BEGIN; SELECT * FROM mytable WHERE key = 1 FOR UPDATE; SAVEPOINT s; UPDATE mytable SET ... WHERE key = 1; ROLLBACK TO s;stay
ROLLBACK TOAfter that, it will not be able to maintainFOR UPDATElock . stay 9.3 This problem has been fixed in .Caution
One runs on
READ COMMITTEDTransaction isolation level and useORDER BYAnd lock clauseSELECTThe command may return unordered lines . This is becauseORDER BYWill be applied first . This command sorts the results , But maybe Then block when trying to obtain locks on one or more rows . onceSELECTrelieve Blocking , Some sort column values may have been modified , As a result, those lines become disordered ( Although their roots According to the original column value, it is ordered ). According to need , You can do this by placingFOR UPDATE/SHARETo solve one of the problems , for exampleSELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;Note that this will cause locking
mytableAll of the line , And at the topFOR UPDATEOnly the rows actually returned will be locked . This can lead to significant Performance differences , Especially putORDER BYAndLIMITOr other When limiting combination . Therefore, only when the sorting sequence is updated concurrently and strict sorting results are required It is recommended to use this technology .stay
REPEATABLE READperhapsSERIALIZABLEAt the transaction isolation level, this may cause a serialization failure (SQLSTATEyes'40001'), Therefore, it is impossible to receive unordered lines at these isolation levels .TABLE command
command
TABLE nameEquivalent to
SELECT * FROM nameIt can be used as a top-level command , Or use it in complex queries to save space . Only
WITH、UNION、INTERSECT、EXCEPT、MINUS、ORDER BY、LIMIT、OFFSET、FETCHas well asFORLocking clauses can be used forTABLE. Out of commissionWHEREClause and any form The gathering of .
Example
Keep watch
filmsAnd watchdistributorsConnect :SELECT f.title, f.did, d.name, f.date_prod, f.kind FROM distributors d, films f WHERE f.did = d.did title | did | name | date_prod | kind -------------------+-----+--------------+------------+---------- The Third Man | 101 | British Lion | 1949-12-23 | Drama The African Queen | 101 | British Lion | 1951-08-11 | Romantic ...For all movies
lenColumn sum and usekindGroup the results :SELECT kind, sum(len) AS total FROM films GROUP BY kind; kind | total ----------+------- Action | 07:34 Comedy | 02:58 Drama | 14:28 Musical | 06:42 Romantic | 04:38For all movies
lenSummation 、 According to the results ``kind`` Group and show that the total length is less than 5 Grouping of hours :SELECT kind, sum(len) AS total FROM films GROUP BY kind HAVING sum(len) < interval '5 hours'; kind | total ----------+------- Comedy | 02:58 Romantic | 04:38The following two examples are based on the second column (
name) To sort the results :SELECT * FROM distributors ORDER BY name; SELECT * FROM distributors ORDER BY 2; did | name -----+------------------ 109 | 20th Century Fox 110 | Bavaria Atelier 101 | British Lion 107 | Columbia 102 | Jean Luc Godard 113 | Luso films 104 | Mosfilm 103 | Paramount 106 | Toho 105 | United Artists 111 | Walt Disney 112 | Warner Bros. 108 | WestwardThe following example shows how to get the table
distributorsandactorsUnion , Limit the results to those in each table with Letter W The first line . Want only distinguishable lines , Therefore, the key words are omittedALL.distributors: actors: did | name id | name -----+-------------- ----+---------------- 108 | Westward 1 | Woody Allen 111 | Walt Disney 2 | Warren Beatty 112 | Warner Bros. 3 | Walter Matthau ... ... SELECT distributors.name FROM distributors WHERE distributors.name LIKE 'W%' UNION SELECT actors.name FROM actors WHERE actors.name LIKE 'W%'; name ---------------- Walt Disney Walter Matthau Warner Bros. Warren Beatty Westward Woody AllenThis example shows how to
FROMFunction used in Clause , Define the list with and without columns, respectively :CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$ SELECT * FROM distributors WHERE did = $1; $$ LANGUAGE SQL; SELECT * FROM distributors(111); did | name -----+------------- 111 | Walt Disney CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$ SELECT * FROM distributors WHERE did = $1; $$ LANGUAGE SQL; SELECT * FROM distributors_2(111) AS (f1 int, f2 text); f1 | f2 -----+------------- 111 | Walt DisneyHere is an example of a function with an increasing sequence :
SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY; unnest | ordinality --------+---------- a | 1 b | 2 c | 3 d | 4 e | 5 f | 6 (6 rows)This example shows how to use simple
WITHClause :WITH t AS ( SELECT random() as x FROM generate_series(1, 3) ) SELECT * FROM t UNION ALL SELECT * FROM t x -------------------- 0.534150459803641 0.520092216785997 0.0735620250925422 0.534150459803641 0.520092216785997 0.0735620250925422Pay attention to
WITHThe query is calculated only once , So we get two The set has the same three random values .This example uses
WITH RECURSIVEFrom one display only Look for employees in the list of direct reports Mary All of my subordinates ( Direct or indirect ) And their indirect layers :WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS ( SELECT 1, employee_name, manager_name FROM employee WHERE manager_name = 'Mary' UNION ALL SELECT er.distance + 1, e.employee_name, e.manager_name FROM employee_recursive er, employee e WHERE er.employee_name = e.manager_name ) SELECT distance, employee_name FROM employee_recursive;Note the typical form of this recursive query : An initial condition , Follow behind
UNION, Then there is the recursive part of the query . Make sure The recursive part of the query will eventually return no rows , Otherwise, the query will loop indefinitely ( WITH Inquire about ).This example uses
LATERALbymanufacturersEach row of the table applies a set return functionget_product_names():SELECT m.name AS mname, pname FROM manufacturers m, LATERAL get_product_names(m.id) pname;Currently, manufacturers without any products will not appear in the results , Because this is an internal connection . If we want to include the names of such manufacturers in the results , We can :
SELECT m.name AS mname, pname FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
Compatibility
Of course ,
SELECTStatements are compatible SQL The standard . But there are also some extended and missing features .
Omitted FROM Clause
KingbaseES Allow us to omit
FROMClause . A simple use is to evaluate simple expressions Result :SELECT 2+2; ?column? ---------- 4Some others SQL The database needs to introduce a fake A single row table is placed in this
SELECTOfFROMClause can do this .Be careful , If you don't specify one
FROMClause , This query You cannot reference any database tables . for example , The following query is illegal :SELECT distributors.* WHERE distributors.name = 'Westward';KingbaseES stay 8.1 Previous releases Will accept this form of query , And each table referenced for the query is in
FROMAn item is implicitly added to the clause . It is no longer allowed To do so .empty SELECT list
SELECTThe following output expression list can be empty , This will produce a zero column result table . Yes SQL This is not legal by standard grammar .KingbaseES allow It is to be consistent with the allowed zero list . But in useDISTINCTEmpty list is not allowed .Omit AS key word
stay SQL In the standard , As long as the new column name is a legal column name ( That is to say, it is different from any reserved keywords ), You can omit the optional keywords before the output column name
AS. KingbaseES Be a little stricter : As long as the new column names match Any keyword ( Reserved or non reserved ) NeedAS. The recommended habit is to useASOr output column names with double quotation marks to prevent possible conflicts with future added keywords .stay
FROMItem in , Standards and KingbaseES Are allowed to omit non reserved Keyword alias beforeAS. But due to grammatical ambiguity , This cannot Used to output column names .ONLY And inheritance
Writing
ONLYwhen ,SQL The standard requires parentheses around the table name , for exampleSELECT * FROM ONLY (tab1), ONLY (tab2) WHERE ....KingbaseES Think these parentheses are optional .KingbaseES Allow to write a trailing
*Come on Explicitly specify non -ONLYBehavior . The standard does not allow such .( These points apply equally to all support
ONLYOption SQL command ).TABLESAMPLE Clause limit
Currently, it is only accepted on general tables and materialized views
TABLESAMPLEClause . according to SQL standard , It should be applicable to anyFROMterm .FROM Function call in
KingbaseES Allow a function call to be written directly
FROMA member of the list . stay SQL In the standard , It is necessary to put such a function Call wrapped in a sub -SELECTin . in other words , grammarFROM func(...) ``alias`` Approximately equivalent toFROM LATERAL (SELECT func(...)) ``alias``. Pay attention toLATERALConsidered implicit , This is because the standard is forFROMOne of themUNNEST()RequirementsLATERALsemantics .KingbaseES Will be able toUNNEST()Treat it the same as other collection return functions .GROUP BY and ORDER BY Available namespaces
stay SQL-92 In the standard , One
ORDER BYClause can only use output Column name or sequence number , And oneGROUP BYClauses can only be used based on input The expression of the column name .KingbaseES Expanded These two sub sentences allow them to use other options ( But if there is ambiguity, the standard is still used explain ).KingbaseES Two sub sentences are also allowed Specify any expression . Note that names that appear in an expression will always be treated as input column names Not output column name .SQL:1999 And subsequent standards use a slightly different definition , It is not completely backward compatible SQL-92. however , In most cases , KingbaseES Will be with SQL:1999 same Mode interpretation
ORDER BYorGROUP BYexpression .Function dependency
Only when the primary key of a table is included
GROUP BYIn the list , KingbaseES To recognize functional dependencies ( allow fromGROUP BYOmit the column ).SQL The standard specifies that it should be recognized Additional circumstances .LIMIT and OFFSET
LIMITandOFFSETClause is KingbaseES- Special grammar , stay MySQL It's also used .SQL:2008 Standard already Clauses with the same function are introducedOFFSET ... FETCH {FIRST|NEXT} ...( As mentioned above :ref`LIMIT Clause ` As shown in ). This grammar Also by IBM DB2 Use ( Oracle Written applications often use automatically generatedrownumColumns to achieve the effect of these clauses , This is in KingbaseES None of them ).FOR NO KEY UPDATE、FOR UPDATE 、FOR SHARE 、FOR KEY SHARE
Even though SQL In the standard
FOR UPDATE, But the standard only allows it asDECLARE CURSORAn option for . KingbaseES Allow it to appear in anySELECTQuery and sub -SELECTin , But this is An extension .FOR NO KEY UPDATE、FOR SHAREas well asFOR KEY SHAREVariants andNOWAITandSKIP LOCKEDOptions do not appear in the standard .WITH Data modification statement in
KingbaseES Allow to put
INSERT、UPDATEas well asDELETEUsed as aWITHInquire about . This is in SQL It cannot be found in the standard .Nonstandard clause
DISTINCT ON ( ... )yes SQL Standard extension .
ROWS FROM( ... )yes SQL Standard extension .
WITHOfMATERIALIZEDandNOT MATERIALIZEDThe options are SQL Standard extension .This part is not necessary , If you need to make other instructions, please put them here .
20.19. SELECT INTO
purpose
SELECT INTO — Define a new table from the result of a query
SELECT INTOCreate a new table and fill it with the data calculated by a query . These data will not be like ordinary ``SELECT`` Then it is returned to the client . The columns of the new table have andSELECTThe name and data type related to the output column of .
precondition
nothing
grammar
[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
* | expression [ [ AS ] output_name ] [, ...]
INTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] new_table
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY expression [, ...] ]
[ HAVING condition [, ...] ]
[ WINDOW window_name AS ( window_definition ) [, ...] ]
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST
} ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start [ ROW | ROWS ] ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]
[ FOR { UPDATE | SHARE } [ OF table_name [, ...] ] [ NOWAIT ] [...] ]
semantics
TEMPORARYorTEMPIf specified , This table is created as a temporary table . See CREATE TABLE .
UNLOGGEDIf specified , This table is created as a table without logging . See CREATE TABLE .
new_tableThe name of the table to be created ( It can be pattern Limited ).
All other parameters are in SELECT There is a detailed description of .
Example
Create one only from
filmsThe most recent items of form a new tablefilms_recent:SELECT * INTO films_recent FROM films WHERE date_prod >= '2002-01-01';
Compatibility
SQL Standard use
SELECT INTOIndicates that the value is selected into a scalar variable of the host program , Instead of creating a new table . This is actually ESQL( see ESQL C Embedded in SQL ) and PL/SQL( see PLSQL SQL Process language ) In the middle of the day .KingbaseES Use
SELECT INTOThere are historical reasons for table creation . It is best to use in new codeCREATE TABLE AS.
other
SELECT INTOCreate a new table and fill it with the data calculated by a query . These data will not be like ordinary ``SELECT`` Then it is returned to the client . The columns of the new table have andSELECTThe name and data type related to the output column of .
20.20. SET
purpose
SET — Change a runtime parameter
SETCommand to change run-time configuration parameters . quite a lot Server configuration parameters reference manual The parameters listed in can be used ``SET`` Instant change .
SETOnly the values used in the current session are affected .
precondition
Some parameters require super user privileges to change , And some cannot be changed after the server or session is started
grammar
SET [ SESSION | LOCAL ] configuration_parameter { TO | = } { value | 'value' | DEFAULT }
{ ALTER } SET [ SESSION | LOCAL ] TIME ZONE { TIME_ZONE | time_zone | timezone | LOCAL | DEFAULT }
semantics
SESSIONSpecify that the command is valid for the current session ( This is the default ).
LOCALSpecify that this command is only valid for the current transaction . stay
COMMITperhapsROLLBACKafter , The session level settings will take effect again . Issuing this parameter outside the transaction block will issue a warning and will have no effect .
configuration_parameterThe name of a runtime parameter that can be set . The available parameters are recorded in Server configuration parameters reference manual And below .
valueNew value of parameter . According to specific parameters , Values can be specified as string constants 、 identifier 、 A comma separated list of numbers or more . Write
DEFAULTYou can specify to reset this parameter to its default value ( That is to say, there is no performSETCommand, it has the value ).In addition to the Server configuration parameters reference manual Configuration parameters recorded in , Some parameters can only be used
SETCommand settings Or have special grammar :
SCHEMA
SET SCHEMA 'value' yesSET search_path TO valueAn alias for . Only one pattern can be specified using this syntax .
NAMES
SET NAMES valueyesSET client_encoding TO valueAn alias for .
SEEDRandom number generator ( function
random) Set up An internal seed . The allowable value is -1 and 1 The floating point number between , It will be multiplied 231-1.You can also call the function
setseedTo set the seed :SELECT setseed(value);
TIME ZONE
SET TIME ZONE valueyesSET timezone TO valueA person of name . grammarSET TIME ZONEAllow special... For time zone designation Special grammar . Here is an example of legal value :
'PST8PDT'Time zone in Berkeley, California .
'Europe/Rome'Time zone of Italy .
-7UTC to the west of 7 Hour time zone ( Equivalent to PDT). A positive value is UTC to the east of .
INTERVAL '-08:00' HOUR TO MINUTEUTC to the west of 8 Hour time zone ( Equivalent to PST).
LOCALDEFAULTSet the time zone to your local time zone ( That is to say, the server
timezoneThe default value is ).The time zone setting given in numbers or intervals is internally translated into POSIX Time zone syntax . for example , stay
SET TIME ZONE -7after ,SHOW TIME ZONEWill report<-07>+07.
Example
Set the mode search path :
SET search_path TO my_schema, public;Set the date style to traditional KINGBASE Of “ The day is before the month ” Input habits :
SET datestyle TO kingbase, dmy;Set the time zone to Berkeley, California :
SET TIME ZONE 'PST8PDT';Set the time zone to Italy :
SET TIME ZONE 'Europe/Rome';
Compatibility
SET TIME ZONEExpanded SQL Standard defined syntax . The standard only allows the time zone offset of numbers and KingbaseES Allow more flexible time zone descriptions . All the othersSETThe characteristics are KingbaseES Expand .
other
If issued within a transaction
SET``( Or equivalent \ ``SET SESSION) And the transaction was later suspended , When the transaction is rolled backSETThe effect of the command will disappear . Once the transaction is committed , These effects will last until the end of the session ( Unless by anotherSETCovered with ).
SET LOCALThe effect of only lasts until the end of the current transaction , Whether or not the transaction is committed . A special case is in a transactionSETFollow behind ``SET LOCAL``:SET LOCALThe value will be visible until the end of the transaction , But after that, ( If the transaction is committed )SETThe value will take effect .SETor ``SET LOCAL`` The effect of will also disappear because it is rolled back to a savepoint earlier than them .If used in a function
SET LOCALAnd the function also has aSETOptions ( see CREATE FUNCTION sentence ), On function exit ``SET LOCAL`` The effect of the command will disappear . in other words , The value when this function is called will be restored . This allows you to use ``SET LOCAL`` Change a parameter dynamically or repeatedly within a function , At the same time, it can still be used convenientlySETOption to save and restore the caller's value . however , A regularSETThe command will override any function it is inSETOptions , Unless rollback , Its effect will remain .Be careful
stay KingbaseES V7 In the version , One
SET LOCALThe effect will be caused by releasing earlier savepoints or successfully from a PL/SQL Exit in the exception block and be canceled . This behavior has been changed , Because it is considered not intuitive .
20.21. SET CONSTRAINTS
purpose
SET CONSTRAINTSSet the constraint check in the current transaction act .IMMEDIATEConstraints are checked at the end of each statement .DEFERREDConstraints are not checked until the transaction is committed . Every constraint has Their ownIMMEDIATEorDEFERREDPattern .When creating a , A constraint is given one of three properties :
DEFERRABLE INITIALLY DEFERRED、DEFERRABLE INITIALLY IMMEDIATEperhapsNOT DEFERRABLE. The third kind is alwaysIMMEDIATEAnd will not receiveSET CONSTRAINTSThe impact of the command . The first two categories are in each The transaction starts in the specified mode , But their behavior can be used in a transactionSET CONSTRAINTSchange .With a list of constraint names
SET CONSTRAINTSChange only those constraints ( Must be delayable ) The pattern of . Each constraint name can be Mode Limited . If no schema name is specified , Then the current pattern search path will be used to find The first matching name .SET CONSTRAINTS ALLChange the mode of all deferrable constraints .When
SET CONSTRAINTSChange a constrained pattern fromDEFERREDChange toIMMEDIATEwhen , The new model will have a retrospective effect : Any unresolved data modification ( It would have been at the end of the transaction Checked ) Will turn inSET CONSTRAINTScommand Is checked during the execution of . If any such constraint is violated ,SET CONSTRAINTSWill fail ( And will not change Change the constraint mode ). such ,SET CONSTRAINTSIt can be used to force entry at a specific point in a transaction Row constraint check .At present , Only
UNIQUE、PRIMARY KEY、REFERENCES( Foreign keys ) as well asEXCLUDEConstraints are affected by this setting .NOT NULLas well asCHECKConstraints are always on one line Check immediately when inserted or modified ( Not at the end of the statement ). Not declared asDEFERRABLEThe uniqueness and exclusion constraints of will also be Check immediately .Be declared “ Constraint trigger ” The trigger of is also triggered by this setting The control of — They are triggered while the relevant constraints are checked .
precondition
nothing
grammar
SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }
semantics
nameSpecify constraint name
ALLSpecify all constraints
Example
Set the constraint mode to check at the end
SET CONSTRAINTS my_constraint IMMEDIATE;
Compatibility
This command conforms to SQL The behavior defined in the standard , But there is a limitation : stay KingbaseES in , It will not be applied to
NOT NULLandCHECKConstraints . also , KingbaseES Will immediately check non delayable Unique constraint , Instead of checking at the end of the statement as recommended by the standard .
other
because KingbaseES Constraint names are not required to be in the schema only ( But it is required to be unique in the table ), There may be more than one constraint matching the specified constraint name . In this way Under the circumstances
SET CONSTRAINTSWill operate on all matches . For a non schema qualified name , Once one or more matches are found in a pattern in the search path with , Later patterns in the path will not be searched .This command only modifies the behavior of constraints in the current transaction . Issuing this command outside the transaction block will produce a Warning and will not have any effect .
20.22. SET ROLE
purpose
This command puts the current SQL The current user identifier of the session is set to ``role_name``. The role name can be written as an identifier or a string . stay
SET ROLEafter , Yes SQL When the authority of the command is checked It seems that this role is the same as the original login role .The current session user must be specified role ``role_name`` A member of ( If the session user is a super user , You can choose any role ).
SESSIONandLOCALThe role of modifiers and The conventional SET command .
NONEandRESETForm the current user identifier Reset to the current session user identifier . These forms can be performed by any user .
precondition
You must have this role to use SET ROLE .
grammar
SET [ SESSION | LOCAL ] ROLE role_name SET [ SESSION | LOCAL ] ROLE NONE RESET ROLE
semantics
role_nameThe role name to be set
NONEReset to the current session user identifier
Example
SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- peter | peter SET ROLE 'paul'; SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- peter | paul
Compatibility
KingbaseES Allow identifiers grammar (
"rolename"), and SQL Standard requirements The role name is written as a string .SQL This command is not allowed in transactions , and KingbaseES Don't do this system , Because there is no reason to do this . andRESETgrammar equally ,SESSIONandLOCALModifier is a kind of KingbaseES Expand .
other
Use this command to increase privileges or restrict privileges . If the session user role has
INHERITSattribute , Then it will automatically have its abilitySET ROLEAll privileges of all roles to . under these circumstancesSET ROLEAll features directly assigned to session users will actually be deleted Rights and privileges assigned to session users as members of other roles , Leave only the mentioned Privileges available to roles . let me put it another way , If the session user does notNOINHERITSattribute ,SET ROLEWill delete Get the privileges available to the mentioned role by directly assigning privileges to the session user .Specially , When a super user chooses
SET ROLETo a non Super user role , They will lose their super user privileges .
SET ROLEThe effect is comparable SET SESSION AUTHORIZATION , But the privilege check involved Completely different . also ,SET SESSION AUTHORIZATIONdecision Later,SET ROLEWhat roles can the command use , But useSET ROLEChanging the role does not change the subsequentSET ROLECharacter sets that can be used .
SET ROLEWon't handle roles ALTER ROLE Set the specified session variable . This only happens during login .
SET ROLECan't be in oneSECURITY DEFINERUse in a function .
20.23. SET SESSION AUTHORIZATION
purpose
SET SESSION AUTHORIZATION — Set the session user identifier and current user identifier of the current session
The session user identifier is initially set to that provided by the client ( Possibly certified ) user name . The current user identifier is usually equal to the session user identifier , But maybe in ``SECURITY DEFINER`` Functions and similar mechanisms . It can also be used. SET ROLE Change it . The current user identifier is related to permission check .
The session user identifier can only be used in the initial session user Authenticated user It is changed when you have super user privileges . otherwise , This command will only be accepted if it specifies an authenticated user name .
SESSIONandLOCALThe role of modifiers and conventions SET command .
DEFAULTandRESETForm resets the session user identifier and current user identifier to the initial authenticated user name . These forms can be performed by any user .
precondition
The session user identifier can only be used in the initial session user The authenticated user is changed when he has super user privileges .
grammar
SET [ SESSION | LOCAL ] SESSION AUTHORIZATION user_name SET [ SESSION | LOCAL ] SESSION AUTHORIZATION DEFAULT RESET SESSION AUTHORIZATION
semantics
user_nameThis command puts the current SQL The session user identifier and current user identifier of the session are set to ``user_name``. The user name can be written as an identifier or a string . for example , You can use this command to temporarily become an unprivileged user and later switch back to become a super user .
SESSIONSpecify that the command is valid for the current session ( This is the default ).
LOCALSpecify that this command is only valid for the current transaction . stay
COMMITperhapsROLLBACKafter , The session level settings will take effect again . Issuing this parameter outside the transaction block will issue a warning and will have no effect .
DEFAULT,RESETThe current user identifier is reset to the original authenticated user name . These forms can be performed by any user .
Example
SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- peter | peter SET SESSION AUTHORIZATION 'paul'; SELECT SESSION_USER, CURRENT_USER; session_user | current_user --------------+-------------- paul | paul
Compatibility
SQL The standard allows some other expressions to appear in text *``user_name``* Location , But in fact, these options are not important .KingbaseES Allow to bid Recognizer grammar (
"username"), and SQL The standard does not allow . SQL This command is not allowed in transactions , and KingbaseES This restriction is not made , Because there is no reason to do this . andRESETThe grammar is the same ,SESSIONandLOCALModifier is a kind of KingbaseES Expand .The standard leaves the privileges required to execute this command to the implementation definition .
other
SET SESSION AUTHORIZATIONCan't be in one ``SECURITY DEFINER`` Use in a function .
20.24. SET TRANSACTION
purpose
SET TRANSACTIONCommand sets the current The characteristics of conversation .SET SESSION CHARACTERISTICSSet the default for subsequent transactions of a session Transaction features . It can be used in individual affairsSET TRANSACTIONOverride these defaults .
precondition
nothing
grammar
SET TRANSACTION transaction_mode [, ...]
SET TRANSACTION SNAPSHOT snapshot_id
SET SESSION CHARACTERISTICS AS TRANSACTION transaction_mode [, ...]
among transaction_mode Is one of the following :
ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED }
READ WRITE | READ ONLY
[ NOT ] DEFERRABLE
semantics
The available transaction characteristics are transaction isolation levels 、 Transaction access mode ( read / Write or read only ) as well as Delayable mode . Besides , You can choose a snapshot , However, it can only be used for current transactions, not As the session default .
The isolation level of a transaction determines what data the transaction can see when other transactions run in parallel :
READ COMMITTEDA statement can only see the rows submitted before it starts . This is the default .
REPEATABLE READAll statements of the current transaction can only see the first query or Rows submitted before the data modification statement .
SERIALIZABLEAll statements of the current transaction can only see the first query or Rows submitted before the data modification statement . If the read and write between concurrent serializable transactions Patterns can lead to a serialization of those transactions ( One at a time ) It is impossible to appear The situation of , One of them will be rolled back and get a
serialization_failureerror .SQL The standard defines an additional level :
READ UNCOMMITTED. stay KingbaseES inREAD UNCOMMITTEDBe regarded asREAD COMMITTED.A transaction executes the first query or data modification statement (
SELECT、INSERT、DELETE、UPDATE、FETCHorCOPY) After that, you cannot change the transaction isolation level .The access mode of the transaction determines whether the transaction is read / Write or read only . read / Write is the default . When a transaction is read-only , If SQL command
INSERT、UPDATE、DELETEandCOPY FROMThe table to be written is not a temporary table , Then they are not allowed . Don't allowCREATE、ALTERas well asDROPcommand . Don't allowCOMMENT、GRANT、REVOKE、TRUNCATE. IfEXPLAIN ANALYZEandEXECUTEThe command to be executed is one of the above commands , Then they are not allowed . This is a high-level read-only concept , It can't stop all right Write to disk .Only affairs are
SERIALIZABLEas well asREAD ONLYwhen ,DEFERRABLETransaction attributes are valid . When all three attributes of a transaction are selected , The transaction is in The first time you take a snapshot of it, it may block , After that, it will run withoutSERIALIZABLETransaction overhead without any sacrifice or The risk of being cancelled by a serialization failure . This mode is very suitable for long-running reports or Backup .
SET TRANSACTION SNAPSHOTThe command allows new transactions Use the same as an existing transaction snapshot function . Existing transactions You must have used its snapshotsys_export_snapshotfunction ( see Snapshot synchronization function ) export . This function will return a snapshot identifier ,SET TRANSACTION SNAPSHOTYou need to be given a snapshot identifier to specify the snapshot to import . In this command, the identifier must be written as a string , for example'000003A1-1'.SET TRANSACTION SNAPSHOTOnly in one transaction Start execution , And the first query or data modification statement of the transaction (SELECT、INSERT、DELETE、UPDATE、FETCHorCOPY) Before execution . Besides , The transaction must have been set bySERIALIZABLEperhapsREPEATABLE READIsolation level ( otherwise , This snapshot will be discarded immediately , becauseREAD COMMITTEDMode will take a new snapshot for each command ). If the import transaction usesSERIALIZABLEIsolation level , Then import the snapshot Transactions of must also use this isolation level . also , A non read-only serializable transaction cannot be imported from read-only Snapshot of transactions .
Example
Start a new transaction with the same snapshot of an existing transaction , First of all, from the existing Transaction export snapshot . This will return the snapshot identifier , for example :
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; SELECT sys_export_snapshot(); sys_export_snapshot --------------------- 00000003-0000001B-1 (1 row)Then use the snapshot identifier at the beginning of a newly started transaction in a
SET TRANSACTION SNAPSHOTIn command :BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ; SET TRANSACTION SNAPSHOT '00000003-0000001B-1';
Compatibility
SQL These commands are defined in the standard , however
DEFERRABLETransaction mode andSET TRANSACTION SNAPSHOTExcept in form , These two are KingbaseES Expand .
SERIALIZABLEIt is the default transaction isolation level in the standard . stay KingbaseES The default value in is normalREAD COMMITTED, But you can change it in the above way .stay SQL In the standard , You can use these commands to set up another transaction feature : Diagnostic area The size of the . This concept is related to embedded SQL of , And therefore not in KingbaseES Server implementation .
SQL The standard requires continuous ``transaction_modes`` Comma between , But for historical reasons KingbaseES It is allowed to omit commas .
other
If you execute
SET TRANSACTIONNot beforeSTART TRANSACTIONperhapsBEGIN, It will send a warning and have no effect .It can be done by
BEGINperhapsSTART TRANSACTIONSpecify the desired ``transaction_modes`` To eliminateSET TRANSACTION. But inSET TRANSACTION SNAPSHOTThis option is not available in .The default transaction mode of the session can also be set by setting configuration parameters default_transaction_isolation 、default_transaction_read_only and default_transaction_deferrable To set up ( actually
SET SESSION CHARACTERISTICSJust useSETSet the equivalent of these variables ). This means that you can use the configuration file 、ALTER DATABASEEtc . See Server configuration parameters reference manual .
20.25. SHOW
purpose
SHOW — Display the value of a runtime parameter
SHOWThe current settings of the runtime parameters will be displayed . These variables can be usedSETsentence 、 edit ``kingbase.conf`` Configuration parameters 、 adopt ``KINGBASE_OPTIONS`` environment variable ( Use libkci Or based on libkci Application time ) Or startkingbaseSet the server through the command line flag . See Server configuration parameters reference manual .
precondition
nothing
grammar
SHOW name SHOW ALL
semantics
nameThe name of a runtime parameter . The available parameters are recorded in Server configuration parameters reference manual and SET Reference page . Besides , There are some parameters that can be displayed but cannot be set :
SERVER_VERSIONDisplay the version number of the server .
SERVER_ENCODINGDisplay the character set encoding of the server . At present , This parameter can be displayed But it cannot be set , Because this setting is determined when the database is created .
LC_COLLATEDisplay the collation of the database ( Text order ) Regional settings for . At present , This parameter can be displayed but cannot be set , Because this setting is in Determined when the database is created .
LC_CTYPEDisplay the locale of the character classification of the database . At present , This parameter can be displayed but cannot be set , Because this setting It is decided when the database is created .
IS_SUPERUSERTrue if the current role has super user privileges .
ALLDisplay the values of all configuration parameters , With description .
Example
Display parameters
DateStyleCurrent settings for :SHOW DateStyle; DateStyle ----------- ISO, MDY (1 row)Display parameters
geqoCurrent settings for :SHOW geqo; geqo ------ on (1 row)Show all settings :
SHOW ALL; name |setting | description -------------------------+--------+--------------------------------------------- allow_system_table_mods |off | Allows modifications of the structure of ... . . . xmloption |content| Sets whether XML data in implicit parsing ... zero_damaged_pages |off |Continues processing past damaged page headers. (196 rows)
Compatibility
SHOWCommand is a kind of KingbaseES Expand .
20.26. START TRANSACTION
purpose
START TRANSACTION — Start a transaction block
This command starts a new transaction block . If the isolation level is specified 、 Read write mode or delay mode , The new transaction will have these characteristics , It's like executing SET TRANSACTION equally . This sum BEGIN command .
precondition
nothing
grammar
START TRANSACTION [ transaction_mode [, ...] ]
among transaction_mode Is one of the following :
ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED }
READ WRITE | READ ONLY
[ NOT ] DEFERRABLE
semantics
The meaning of these parameters for this statement can be referred to SET TRANSACTION .
Example
The first isolation level is READ COMMIT Things of
start transaction ISOLATION LEVEL READ COMMITTED;
Compatibility
In the standard , No need to send ``START TRANSACTION`` To start a transaction block : whatever SQL The command implicitly starts a block .
KingbaseES The behavior of can be regarded as Implicitly issue a command after each command that does not follow ``START TRANSACTION``( perhaps
BEGIN) After that ``COMMIT`` And it is often called “ Automatic submission ”. For convenience , Other relational database systems may also provide automatic submission .
DEFERRABLE``transaction_mode`` It's a kind of KingbaseES Language extension .SQL The standard requires continuous ``transaction_modes`` Comma between , But for historical reasons KingbaseES allow Omit commas .
See also SET TRANSACTION Compatibility section .
20.27. TRUNCATE
purpose
TRUNCATEYou can quickly remove all rows from a set of tables . It has and executes unconditionally on each tableDELETESame effect , But it will be faster , Because it has no actual scan table . Besides , It reclaims disk space immediately , Instead of asking for a follow-upVACUUMoperation . On the big watch It's the most useful .
precondition
To truncate a table , You must have the above
TRUNCATEPrivilege .
grammar
TRUNCATE [ TABLE ] [ ONLY ] name [ * ] [, ... ]
[ RESTART IDENTITY | CONTINUE IDENTITY ] [ CASCADE | RESTRICT ]
semantics
nameThe name of the table to truncate ( It can be pattern Limited ). If
ONLY, Only the table will be truncated . If not specifiedONLY, This table and all its successors represent ( If there is ) Will be truncated . Optionally , You can specify*To explicitly include post representatives .
RESTART IDENTITYAutomatically restart the sequence owned by the column of the truncated table .
CONTINUE IDENTITYDo not change the sequence value . This is the default .
CASCADEAutomatically truncate all tables that have foreign key references to any of the mentioned tables and any
CASCADETables added to the Group .
RESTRICTIf any table has foreign key references from tables not listed in the command , Refuse to truncate . This is the default .
Example
Truncation table
bigtableandfattable:TRUNCATE bigtable, fattable;Do the same thing , And also reset any associated sequence generators :
TRUNCATE bigtable, fattable RESTART IDENTITY;Truncation table
othertable, And cascade to cut off any passing Foreign key constraint referenceothertableTable of :TRUNCATE othertable CASCADE;
Compatibility
SQL:2008 The standard includes a
TRUNCATEcommand , Grammar isTRUNCATE TABLE tablename. ClauseCONTINUE IDENTITY/RESTART IDENTITYIt also appears in the standard , But the meaning is somewhat different . Some of the concurrent behavior of this command is standardized Leave it to the implementation to define , Therefore, if necessary, the above annotations should be considered and compared with other implementations .
other
TRUNCATEAsk for one on the table to be operatedACCESS EXCLUSIVElock , This will block all others on the table Concurrent operations . When specifyingRESTART IDENTITYwhen , Anything that needs to be The restarted sequence will also be locked exclusively . If concurrent access on the table is required , that You should useDELETEcommand .
TRUNCATECannot be used on tables referenced by other table foreign keys , Unless those tables are also staged in the same command . The feasibility check in these cases will Require table scanning , And the point is not to do scanning .CASCADEOption can be used to automatically include all dependent tables — But use it very look out , Otherwise you may lose data !
TRUNCATEWill not trigger any... That may exist on the tableON DELETEtrigger . But it will triggerON TRUNCATEtrigger . If in any of these tables It definesON TRUNCATEtrigger , So allBEFORE TRUNCATEThe trigger will be triggered before any truncation occurs Be triggered , And allAFTER TRUNCATEThe trigger will be at the end Triggered after a truncation is completed and all sequences are reset . The trigger will be processed in the order of the table The order is triggered ( First, those listed in the command , Then there is the cascade added ).
TRUNCATENo MVCC Safe . After cutting off , If concurrent transactions use a snapshot taken before truncation occurs , The table will render empty for these concurrent transactions .From the perspective of data in the table ,
TRUNCATEIt's business safety : If the transaction is not committed , The phase will be rolled back safely .In the specified
RESTART IDENTITYwhen , The implicitALTER SEQUENCE RESTARTThe operation will also be transactionally completed . in other words , If the transaction is not committed , They will also be rolled back . This sumALTER SEQUENCE RESTARTYour usual behavior is different . Note that if Additional sequence operations are performed on the restarted sequence before the transaction rollback , The effect of these operations on the sequence Will also be rolled back , But they arecurrval()The effect on will not be rolled back . It's just Is said , After the transaction ,currval()Will continue to reflect the results obtained in the failed transaction The last sequence value , Even if the sequence itself may no longer be consistent with this . This is after the failed transactioncurrval()The usual behavior of is similar .
TRUNCATECurrently, external tables are not supported . This means that if a specified table has any external post representation , This command will fail .
20.28. UNLISTEN
purpose
UNLISTEN — Stop listening for a notification
UNLISTENUsed to remove an existing pairNOTIFYRegistration of events .
UNLISTENCancel any existing and put the current KingbaseES The session is named *``channel``* Registration of listeners of the notification channel . Special wildcards*Cancel the registration of all listeners in the current session .NOTIFY Include relevant
LISTEN`` and \ ``NOTIFYUse more in-depth discussion .
precondition
nothing .
grammar
UNLISTEN { channel | * }
semantics
channelThe name of a notification channel ( Any identifier ).
*All current listening registrations for this session will be cleared .
Example
Do a registration :
LISTEN virtual; NOTIFY virtual; Asynchronous notification "virtual" received from server process with PID 8448.Once implemented
UNLISTEN, furtherNOTIFYMessages will be ignored :UNLISTEN virtual; NOTIFY virtual; -- no NOTIFY event is received
Compatibility
stay SQL There is no in the standard
VACUUMsentence .
other
You can unlisten You have nothing to monitor , There will be no warnings or errors .
At the end of every conversation , Automatically
UNLISTEN *.One has been implemented
UNLISTENThe transaction of cannot be Prepare for two-stage submission .
20.29. UPDATE
purpose
UPDATEChange the specified column in all rows that meet the conditions Value . Only the columns to be modified need to be inSETClause refers to , Columns that have not been explicitly modified retain their previous values .There are two ways to modify a table using information contained in other tables in the database : Use subquery Or in
FROMClause to specify additional tables . This technology is only suitable for Specific environment .Optional
RETURNINGClause results inUPDATECalculate and return the value based on each row that is actually updated . Any column that uses this table andFROMThe expressions of the columns of other tables mentioned in can be evaluated . The new... Of the column of this table will be used for calculation ( After the update ) value .RETURNINGThe syntax of lists andSELECTThe output list of is the same .
precondition
You must have the
UPDATEPrivilege , Or at least have This privilege on the column to be updated . If the value of any column needs to be ``expressions`` perhaps ``condition`` Read , You must also haveSELECTPrivilege .
grammar
[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
SET {[{ column_name = { expression | DEFAULT } |
( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
( column_name [, ...] ) = ( sub-SELECT )
} [, ...]] | [ ROW = record]}
[ FROM from_list ]
[ WHERE condition | WHERE CURRENT OF cursor_name ]
[ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
semantics
with_query
WITHClause allows you to specify one or more inUPDATESubquery referenced by its name in . See WITH Inquire about and SELECT .
table_nameName of the table to be updated ( It can be pattern Limited ). If
ONLY, Only the matching rows in the mentioned table will be updated . If not specifiedONLY, Any matching row in the table inherited from the mentioned table will also Be updated . Optionally , Specify after the table name*You can explicitly indicate to Include the latter representatives .
aliasAn alternative name for the target table . When an alias is provided , It will completely hide the truth of the table name . for example , Given
UPDATE foo AS f,UPDATEThe rest of the statement must usefinstead offooTo reference this table .
column_name``table_name`` The name of a column of the specified table , You can use the table name ( Can be qualified by the schema name ) Make a limit . if necessary , The column name can be a subdomain name ( Subdomain name and table name are required 、 The schema name is qualified with parentheses ) perhaps Array subscript qualification .
expressionAn expression to be assigned to this column . The expression can use this column in the table or Old values of other columns .
DEFAULTSet the column to its default value ( If no default value expression is specified for it , The default value is Will be NULL).
sub-SELECTOne
SELECTSubquery , It is generated and listed in parentheses before it As many output columns . When executed , This subquery must get no more than one row . If it gets a line , Its column value will be assigned to the target column . If it doesn't get ok ,NULL The value will be assigned to Target column . This subquery can reference the old value of the current row in the updated table .
from_listList of table expressions , Allow columns from other tables to appear in
WHEREConditions and update expressions . This is similar to being able toSELECTOf the statement FROM List of tables specified in . Note that the target table cannot appear in ``from_list`` in , Unless you want to do self connection ( In this case, it must Appear as an alias in ``from_list`` in ).
conditionA return
booleanExpression of type value . Let this Expression returntrueThe row of will be updated .
cursor_nameTo be in
WHERE CURRENT OFThe tag name used in the condition . What is to be updated is the most recently fetched row from this cursor . The cursor must be a stayUPDATENon grouped queries on the target table . Be carefulWHERE CURRENT OFCannot be used with a Boolean condition Appoint . About using cursorsWHERE CURRENT OFOf For more information, see DECLARE .
output_expressionAfter each row is updated , To be
UPDATEThe command calculates and returns The expression of . The expression can use ``table_name`` Appoint OrFROMAny column name in the table listed . Write*All columns can be returned .
output_nameName for a returned column .
recordrecord Variable name , The variable type is custom RECORD or %ROWTYPE.UPDATE The statement updates the row data to record A variable's value . For each column of row data ,record The member of must be compatible with the corresponding column type of the table . If the table lists NOT NULL constraint , Corresponding record Members cannot have NULL value .record The number of members must be the same as the previous table Same number of columns for , And the types are compatible . Otherwise, the report will be wrong .
Example
Keep watch
filmsThe column ofkindThe words inDramaChange toDramatic:UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama';In the table
weatherAdjust the temperature item in the row of and reset the sediment to its default value :UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT WHERE city = 'San Francisco' AND date = '2003-07-03';Perform the same operation and return the updated item :
UPDATE weather SET temp_lo = temp_lo+1, temp_hi = temp_lo+15, prcp = DEFAULT WHERE city = 'San Francisco' AND date = '2003-07-03' RETURNING temp_lo, temp_hi, prcp;Use another column list syntax to do the same update :
UPDATE weather SET (temp_lo, temp_hi, prcp) = (temp_lo+1, temp_lo+15, DEFAULT) WHERE city = 'San Francisco' AND date = '2003-07-03';To manage Acme Corporation Account salesperson increases sales , Use
FROMClause Syntax :UPDATE employees SET sales_count = sales_count + 1 FROM accounts WHERE accounts.name = 'Acme Corporation' AND employees.id = accounts.sales_person;Do the same thing , stay
WHEREUse sub selection in Clause :UPDATE employees SET sales_count = sales_count + 1 WHERE id = (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation');to update accounts Contact names in the table to match the currently assigned salesperson :
UPDATE accounts SET (contact_first_name, contact_last_name) = (SELECT first_name, last_name FROM salesmen WHERE salesmen.id = accounts.sales_id);You can use connections to achieve similar results :
UPDATE accounts SET contact_first_name = first_name, contact_last_name = last_name FROM salesmen WHERE salesmen.id = accounts.sales_id;however , If
salesmen.idNot a unique key , The second query may give unexpected results , However, if there are multipleidmatching , The first query guarantees that errors will occur . also , If for a particularaccounts.sales_idItem does not match , The first query will Set the corresponding name field to NULL, The second query does not update the row at all .Update the statistics in a statistical table to match the current data :
UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) = (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d WHERE d.group_id = s.group_id);Try to insert a new inventory item and its inventory . If the item already exists , Then update the inventory of existing items . Do this without letting the whole transaction fail , You can use a savepoint :
BEGIN; -- Other operating SAVEPOINT sp1; INSERT INTO wines VALUES('Chateau Lafite 2003', '24'); -- Assume that the above statement fails because it is not unique , -- So now we issue these orders : ROLLBACK TO sp1; UPDATE wines SET stock = stock + 24 WHERE winename = 'Chateau Lafite 2003'; -- Continue with other operations , And finally COMMIT;Change table
filmsBy cursorc_films`` Positioned row \ ``kindColumn :UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;Change the table data to record A variable's value :
CREATE TABLE t1(id INT, name VARCHAR(20)); DECLARE TYPE myrecord IS RECORD(id INT, name VARCHAR(20)); r1 myrecord; BEGIN r1.id := 1; r1.name := 'new'; UPDATE t1 SET ROW = r1; END; /
Compatibility
This command conforms to SQL standard , however
FROMandRETURNINGClause is KingbaseES Expand , holdWITHbe used forUPDATEIt's also an extension .Some other database systems provide a
FROMOptions , In which, in which target table Can be inFROMIs listed again . but KingbaseES This is not the way to explainFROMOf . Be careful when porting applications that use this extension .According to the standard , The source value of the circle sign sublist of a target column name can be any row value that gets the correct number of columns expression .KingbaseES Only a row constructor or a subquery is allowed for the source value . A column of The updated value can be specified as
DEFAULT, But in This cannot be done in the case of subqueries .
other
Output
On successful completion , One
UPDATEThe command returns in the formUPDATE countCommand label . ``count`` Is the number of rows updated , Include matching lines with unchanged values . Be careful , When updated by a
BEFORE UPDATEWhen the trigger is suppressed , This number may match ``condition`` Less lines . If ``count`` zero , No line should be checked Ask for updates ( It's not a mistake ).If
UPDATEThe command contains aRETURNINGClause , The result will be similar to a containingRETURNINGAs defined in the list Columns and valuesSELECTsentence ( Calculate on the line updated by this command ) Result .explain
When it exists
FROMWhen clause , What actually happened was : The target table is connected to ``from_list`` In the table , And each of the connections Output rows represent an update operation on the target table . In the use ofFROMwhen , You should ensure that the connection produces at most one output line for each line to be modified . in In a word , A target row should not be connected to more than one row from another table . If you send In this case , Then only one connection row is used to update the target row , But what will be used One line is hard to predict .Because of this uncertainty , It is safer to refer to other tables in only one sub selection , But this Statements are usually difficult to write and slower than using connections .
In the case of partitioned tables , Updating a row may cause it to no longer meet the partition constraints of its partition . here , If this row satisfies the partition constraint of some other partition in the partition tree , Then this row will be moved to that partition . If there is no such partition , An error will occur . Backstage , The movement of rows is actually a
DELETEOperation and onceINSERToperation .For moving rows , concurrent
UPDATEorDELETEYou will get a serialization failure error . Suppose the conversation 1 Execute a on a partition keyUPDATE, meanwhile , A concurrent session that can see this line 2 Execute aUPDATEorDELETEoperation . under these circumstances , conversation 2 OfUPDATEorDELETEWill detect row movement and cause serialization failure error ( It always returns a SQLSTATE Code '40001'). If this happens , The application may want to retry the transaction . In general , If the table has no partitions , Or no row movement , conversation 2 The newly updated row will be identified , And execute on this new line versionUPDATE/DELETE.Be careful , Although rows can be moved from local partitions to external table partitions ( Suppose the external data wrapper supports tuple routing ), But they cannot be moved from an external table partition to another partition .
about SET ROW = record sentence , There are the following restrictions :
UPDATE SET ROW = record Only in PLSQL Use in .
Record Variables are only allowed in :
1)UPDATE sentence SET The right side of the clause . 2)RETURNING Clause INTO clause .
ROW Keywords are only allowed in SET Left side , Cannot be used in subqueries ROW.
UPDATE In the sentence , If using ROW, Only one... Is allowed ROW Clause .
If RETURNING INTO Clause contains a record Variable , No other variables or values are allowed .
record The number of members must be in front table Same number of columns , And the types are compatible . Otherwise, the report will be wrong .
I won't support it :
1) Nested record type . 2) return record Function of type . 3)EXECUTE IMMEDIATE Of INSERT, UPDATE Of the statement record
20.30. VACUUM
purpose
VACUUM — Garbage collection and analyze a database as needed
VACUUMReclaim the storage space occupied by dead tuples . In general KingbaseES In operation , Deleted or updated obsolete tuples are not physically removed from their tables , They will exist until onceVACUUMBe performed . Therefore, it is necessary to doVACUUM, Especially on frequently updated tables .In the absence of ``table_and_columns`` List ,
VACUUMIt will process every table and materialized view in the current database that the current user has cleanup permission . If you give a list ,VACUUMYou can only deal with those tables in the list .
VACUUM ANALYZEFor each selected tableANALYZE. This is a convenient combination of the two commands , Can be used for routine maintenance scripts . For details, please refer to ANALYZE .ordinary ``VACUUM``( No
FULL) Simply reclaim space and make it reusable . This form of command can be used in parallel with the normal read-write operation of the table , Because it won't get an exclusive lock . however , The extra space in this form is not returned to the operating system ( in the majority of cases ), It is only kept in the same table for reuse .VACUUM FULLRewrite the entire contents of the table into a new disk file , And no extra space , This allows unused space to be returned to the operating system . This form of command is slower and requires an exclusive lock on each table when it is processed .When the list of options is enclosed in parentheses , Options can be written in any order . If there are no parentheses , The options must be specified strictly in the order shown above . Parenthesized syntax in KingbaseES V8.2 Was added to , The bracketed grammar is abandoned .
precondition
To clean up a table , The operator must usually be the owner of the table or super user . however , Database owners are allowed to clean up all tables in their database except shared directories ( Restrictions on shared directories mean a true database wide
VACUUMCan only be executed by super users ).VACUUMTables that the performer does not have cleanup permissions will be skipped .
grammar
VACUUM [ ( option [, ...] ) ] [ table_and_columns [, ...] ]
VACUUM [ FULL ] [ FREEZE ] [ VERBOSE ] [ ANALYZE ] [ table_and_columns [, ...] ]
among option It can be one of the following :
FULL [ boolean ]
FREEZE [ boolean ]
VERBOSE [ boolean ]
ANALYZE [ boolean ]
DISABLE_PAGE_SKIPPING [ boolean ]
SKIP_LOCKED [ boolean ]
INDEX_CLEANUP [ boolean ]
TRUNCATE [ boolean ]
and table_and_columns yes :
table_name [ ( column_name [, ...] ) ]
semantics
FULLchoice “ Completely ” clear , It can take back more space , And it takes longer and the exclusive lock on the watch . This method also requires additional disk space , Because it will create a new copy of the table , And the old copy will not be released until the operation is completed . Usually, this method is only used when you need to reclaim a large amount of space from the table .
FREEZEChoose radical tuples “ frozen ”. Appoint ``FREEZE`` Equivalent to parameter vacuum_freeze_min_age and vacuum_freeze_table_age Set to 0 Of ``VACUUM``. Aggressive freezing is always performed when the table is rewritten , Therefore, it is specified that
FULLThis option is redundant .
VERBOSEPrint a detailed cleaning activity report for each table .
ANALYZEUpdate the statistics used by the optimizer to determine the most effective way to execute a query .
DISABLE_PAGE_SKIPPINGUsually ,
VACUUMPage will be skipped based on visibility mapping . Pages with all tuples known to be frozen are always skipped , Pages where all tuples are visible to all transactions may be skipped ( Unless it's a radical clean-up ). Besides , Unless in a radical clean-up , Some pages may also be skipped , This avoids waiting for other pages to finish using them . This option disables all page skipping behavior , The intent is to use only when visibility mapping content is suspected , This happens only when the database is damaged due to hardware or software problems .
SKIP_LOCKEDAppoint
VACUUMWhen starting to deal with a relationship , You should not wait for any conflicting locks to be released : If a relationship cannot be locked immediately without waiting , Then skip the relationship . Be careful , Even with this option ,VACUUMIt is still possible to block when opening the index of the relationship . Besides , When from partition 、 When tables inherit sub tables and some types of external tables get sampled rows ,VACUUM ANALYZEIt may still block . Besides , WhenVACUUMUsually, when dealing with all partitions of a specified partition table , If there are conflicting locks on the partition table , This option will result inVACUUMSkip all partitions .
INDEX_CLEANUPAppoint
VACUUMTry deleting index entries that point to dead tuples . It's usually the behavior you need , And by default , Unlessvacuum_index_cleanupOption set to false, In order to cavitate the table . When it is necessary to make vacuum Run as fast as possible , Set this option to false It could be useful , For example, to avoid upcoming transactions ID encapsulation ( see also Prevent transactions ID Rollback failed ). however , If you do not perform index cleanup regularly , Performance may be affected , Because when the table is modified , The index will accumulate dead tuples , The table itself will accumulate dead line pointers , These pointers cannot be deleted until the index cleanup is complete . This option is not valid for tables without indexes , If you useFULLOptions , This option is ignored .
TRUNCATEAppoint
VACUUMYou should try to truncate any empty pages at the end of the table , And allow the truncated page to be returned to the operating system . It's usually the behavior you need , And by default , Unlessvacuum_truncateOption set to false, In order to vacuum the meter . Set this option to false It may help to avoid truncating the required tableACCESS EXCLUSIVElock . If you useFULLOptions , Ignore this option .
booleanSpecify whether the selected option should be turned on or off . You can write
TRUE,ON, or1To enable this option , To writeFALSE,OFF, or0To disable it . You can omit it ``boolean``, Now supposeTRUE.
table_nameName of the table or materialized view to be cleaned up ( Can be decorated with patterns ). If the specified represents a partitioned table , Then all its leaf partitions will also be cleaned up .
column_nameThe name of the specified column to analyze . The default is all columns . If you specify a list of columns , be
ANALYZEMust also be specified .
Example
Clean up a single table
onek, Analyze it for the optimizer and print out a detailed cleanup activity report :VACUUM (VERBOSE, ANALYZE) onek;
Compatibility
stay SQL There is no in the standard
VACUUMsentence .
other
VACUUMCannot be executed within a transaction block .Yes, yes. GIN Index table ,
VACUUM( In any form ) Also by moving the pending index entries to the main GIN In the index structure to complete any pending index insertion .We recommend cleaning up the active production database often ( At least once a night ), To ensure that invalid rows are removed . After adding or deleting a large number of rows , Execute... On the affected tables
VACUUM ANALYZECommand is a good practice . Doing so will update the latest changes to the system directory , And allow KingbaseES The query planner makes better choices when planning user queries .In daily use , Not recommended
FULLOptions , But it can be useful in special situations . An example is when you delete or update most rows in a table , If you want to shrink the table physically to reduce disk space and allow faster table scanning , Then this option is more appropriate .VACUUM FULLIt's usually simpler thanVACUUMShrink the table more .
VACUUMIt can lead to I/O A substantial increase in traffic , This may result in poor performance of other active sessions . therefore , It is sometimes recommended to use the cost based cleanup latency feature . Please refer to Cost based cleanup delay .KingbaseES It includes a “autovacuum” Tools , It can automatically perform routine cleaning and maintenance . For more information about automatic and manual cleaning, see Daily cleaning .
20.31. VALUES
purpose
VALUES -- Calculate a row value or a group of row values specified by a value expression . It is more common to use it to generate “ Often scale ”, But it can also be used alone .
When more than one line is specified , All rows must have the same number of elements . The column data type of the result table is determined by the combination of explicit or derived types of expressions that appear in the column , The rules of decision are the same as
UNIONidentical ( see UNION CASE And related structures ).In large commands , Grammatically allow
VALUESAppear in the ``SELECT`` Wherever it appears . Because grammar regards it as a ``SELECT``, Can be aVALUESCommand to useORDER BY、LIMIT( Or equivalentFETCH FIRST) as well asOFFSETClause .
precondition
nothing .
grammar
VALUES ( expression [, ...] ) [, ...]
[ ORDER BY sort_expression [ ASC | DESC | USING operator ] [, ...] ]
[ LIMIT { count | ALL } ]
[ OFFSET start [ ROW | ROWS ] ]
[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } ONLY ]
semantics
expressionIn the result table ( row set ) A constant or expression calculated and inserted at the specified position in . In a place that appears in
INSERTtop-levelVALUESIn the list , ``expression`` Can beDEFAULTReplace to indicate that the default value of the target column should be inserted . WhenVALUESWhen appearing in other environments , Out of commissionDEFAULT.
sort_expressionAn expression or integer constant that indicates how to sort the result rows . This expression It can be used
column1、column2Wait Quote theVALUESColumns of results . See ``ORDER BY`` Clause :ref:`ORDER BY .
operatorA sort operator . See ```ORDER BY`` Clause :ref:`ORDER BY .
countThe maximum number of rows to return . See ```LIMIT`` Clause :ref:`LIMIT .
startNumber of rows to skip before starting to return rows . See ```LIMIT`` Clause :ref:`LIMIT .
Example
A pure
VALUEScommand :VALUES (1, 'one'), (2, 'two'), (3, 'three');This will return a with two columns 、 A three row table . It is actually equivalent to :
SELECT 1 AS column1, 'one' AS column2 UNION ALL SELECT 2, 'two' UNION ALL SELECT 3, 'three';More commonly ,
VALUESCan be used in a large SQL In command . stayINSERTMost commonly used in :INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama');stay
INSERTIn the environment of , OneVALUESThe items in the list can beDEFAULTTo indicate that the default value of the column should be used instead of specifying a value :INSERT INTO films VALUES ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes'), ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama', DEFAULT);
VALUESIt can also be used to write -SELECT`` The place of , For example, in a \ ``FROMclause :SELECT f.* FROM films f, (VALUES('MGM', 'Horror'), ('UA', 'Sci-Fi')) AS t (studio, kind) WHERE f.studio = t.studio AND f.kind = t.kind; UPDATE employees SET salary = salary * v.increase FROM (VALUES(1, 200000, 1.2), (2, 400000, 1.4)) AS v (depno, target, increase) WHERE employees.depno = v.depno AND employees.sales >= v.target;Pay attention to when
VALUESUsed in aFROMIn a clause , Need to provide aASClause , AndSELECTidentical . It is not necessary to useASClause specifies the name , But that's a good habit ( stay KingbaseES in ,VALUESThe default column name of iscolumn1、column2etc. , But it may be different in other database systems ).When in
INSERTUse inVALUESwhen , Values are automatically forced to the data type of the corresponding target column . When used in other environments , It is necessary to specify the correct data type . If the items are quoted string constants , Forcing the first one is enough to assume the data type for all items :SELECT * FROM machines WHERE ip_address IN (VALUES('192.168.0.1'::inet), ('192.168.0.10'), ('192.168.1.43'));Tips
For simple
INtest , Best useINOf list-of-scalars Instead of writing one like thatVALUESInquire about . Scalar list methods are less written and often more efficient .
Compatibility
VALUESaccord with SQL standard .LIMITandOFFSETyes KingbaseES Expand , See also SELECT .
other
You should avoid
VALUESlist , Otherwise, you may encounter insufficient memory failure or poor performance . Appear in theINSERT`` Medium \ ``VALUESIt's a special case ( Because the desired column type can be fromINSERTThe target table of , And there is no need to scan theVALUESList to derive ), So it can handle larger lists than in other environments .
边栏推荐
- Kingbasees SQL language reference manual of Jincang database (12. SQL statement: alter language to alter subscription)
- DevOps 实践多年,最痛的居然是?
- [shell] Reprint: batch replacement find awk sed xargs
- Kingbases SQL language reference manual of Jincang database (15. SQL statement: create materialized view to create schema)
- Codeforces Round #810 (Div. 2)(A~C)
- 【shell】转载:批量替换 find awk sed xargs
- 【OBS】Dropped Frames And General Connection Issues
- MySQL subquery usage
- Training embedded representation of large categories using triple loss and twin neural networks
- Analysis of interface testing
猜你喜欢

一文看懂中国的金融体系

MySQL 子查询使用方式

2022年下半年(软考高级)信息系统项目管理师报名条件

Decompile jar files (idea environment)

LeetCode每日一练 —— 26. 删除有序数组中的重复项

win11 edge怎么卸载?win11 edge浏览器彻底卸载的方法教程

Leetcode daily practice - 26. Delete duplicates in an ordered array

Leetcode daily practice - 88. Merge two ordered arrays

N圆最密堆积、最小外接正方形的matlab求解(二维、三维等圆Packing 问题)

罗永浩赌上最后一次创业信用
随机推荐
罗永浩赌上最后一次创业信用
计算机网络常见面试题目总结,含答案
Analysis of interface testing
Summary of iPhone development data persistence (final) - Comparison of five data persistence methods
JWT 实现登录认证 + Token 自动续期方案,这才是正确的使用姿势!
福建争抢VC/PE
Overview of canvas
Talk about how to use redis to realize distributed locks?
Kingbases SQL language reference manual of Jincang database (15. SQL statement: create materialized view to create schema)
eadiness probe failed: calico/node is not ready: BIRD is not ready: Error querying BIRD: unable to c
【Pytorch进阶】pytorch模型的保存与使用
【shell】转载:批量替换 find awk sed xargs
Decompile jar files (idea environment)
go+mysql+redis+vue3简单聊室,第5弹:使用消息队列和定时任务同步消息到mysql
DOM case: 10 second countdown - write jump page related knowledge
银行业概览
上半年住户存款增加10.33万亿元,平均每天约571亿存款涌向银行
Implementing DDD based on ABP -- domain logic and application logic
DevOps 实践多年,最痛的居然是?
[internship experience] date verification