diff --git a/3rd_src/pom.xml b/3rd_src/pom.xml
new file mode 100644
index 0000000000000000000000000000000000000000..022739ae66eaa407d8d6ed72d9d902922efa9689
--- /dev/null
+++ b/3rd_src/pom.xml
@@ -0,0 +1,426 @@
+
通过操作列表,您只需要知道自己要“做什么”,就可以快速找到所需命令,而不需要事先知道命令名称。
+通过操作列表,您只需要知道自己要“做什么”,就可以快速找到所需命令,而不需要事先知道命令名称。
+任务 | +命令 | +说明 | +
---|
在中间窗口中,选中SQL语句,SQL助手会显示对应的说明信息。
+In the middle window, if you choose the related SQL, the SQL assistant will show the related information.
任务 | 命令 | 说明 |
---|
Suggestion
" + tempSubSuggestion + "Suggestion
" + tempSubSuggestion + "Suggestion
" + tempSubSuggestion + "Suggestion
" + tempSubSuggestion + ""; + $.each(tempValues, function(n, v) { + if (v.alias.indexOf('|') > -1) { + tempSuggestion = tempSuggestion + "· " + v.id + "\r\n"; + } else { + tempSuggestion = tempSuggestion + "· " + v.alias + "\r\n"; + } + }); + tempSuggestion = tempSuggestion + ""; + return tempSuggestion; +} + +function hideKeyWord(needHide) { + if (needHide) { + $('#keywordInfo').hide(); + $("#listStatus").removeClass("hideList").addClass("showList"); + } else { + $('#keywordInfo').show(); + $("#listStatus").removeClass("showList").addClass("hideList"); + } +} + +function hideOrShowKeyWord() { + if ($("#keywordInfo").is(':visible')) { + hideKeyWord(true); + } else { + hideKeyWord(false); + } +} + +function hideKeyWordList(str) { + $('#keyword').val(str); + hideKeyWord(true); +} + +function getSQLHtmlForList(tempValues, recordPath) { + var tempSuggestion = ""; + $.each(tempValues, function(n, v) { + if (v.alias.indexOf('|') > -1) { + tempSuggestion = tempSuggestion + "
性能优化建议
" + tempSubSuggestion + "性能优化建议
" + tempSubSuggestion + "" + errorCode + "
Descrition
" + err.description + "
SQLSTATE
" + err.sqlstate + "
Possible Causes
" + err.cause + "
Solution
" + err.solution + "
"; + $('#divSuggestion').html(tempHtml); + if (isNotSingle) myCallDBAssistant('show'); + } +} + +function processSelection1() { + if (oTextSelection != "") { + myCallDBAssistantProcessSelection(oTextSelection); + } +} + +function processSelection2() { + if (oTextSelection != "") { + myCallDBAssistantProcessSelection2(oTextSelection); + } +} + +function displayVersionNote(curVersion) { + var divVersionNote = $(''); + var p1 = $('请从华为Support上下载FusionInsight LibrA对应版本的知识库。
'); + divVersionNote.append(p1); + $('body').append(divVersionNote); +} + +function disableNote(disable) { + if (disable) { + if (divDefault != "") { + divDefault.remove(); + divDefault = ""; + } + } else { + divDefault = $('在中间窗口中,选中SQL语句或错误码,SQL助手会显示对应的说明信息。
'); + var p2 = $('我知道了
'); + divDefault.append(p1); + divDefault.append(p2); + $('body').append(divDefault); + } +} + +function setCurrentSQL(sql) { + currentSQL = sql; +} + +function setCookie(name, value) { + var Days = 30; + var exp = new Date(); + exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); + document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); +} + +function loadSuggestion(docRealPath) { + commands = new Commands(); + var xml = new ActiveXObject("Microsoft.XMLDOM"); + xml.async = false; + xml.load(docRealPath + "/suggestion.xml"); + commands.load(xml); + var valueStr = JSON.stringify(commands); + getSQLHtmlForList(commands.cmds, docRealPath); + +} + +function loadErrorcode(docRealPath) { + errorcodes = new ErrorCodes(); + //var xml = new ActiveXObject("Microsoft.XMLDOM"); + //xml.async = false; + //xml.load(docRealPath+"/errorcode.xml"); + //errorcodes.load(xml); + processInput(currentSQL); + myCallDBAssistant('show'); +} + +function isHidden(oDiv) { + var vDiv = oDiv.nextSibling; + while (vDiv.nodeType == 3) { + vDiv = vDiv.nextSibling; + } + vDiv.style.display = (vDiv.style.display == 'none') ? 'block' : 'none'; + var pngs = oDiv.getElementsByTagName("img"); + switch (pngs[1].style.display) { + case 'none': + pngs[0].style.display = 'none'; + pngs[1].style.display = 'inline'; + break; + case 'inline': + pngs[0].style.display = 'inline'; + pngs[1].style.display = 'none'; + break; + } +} + +function goBack(display) { + if (display == "none") { + divGoBack.remove ? divGoBack.remove() : divGoBack.removeNode(true); + divGoBack = ""; + processInput(backString); + } else { + divGoBack = $(''); + var img1 = $('"+realStr.replace(/ , /g,",").replace(/' /g,"'").replace(/ ';/g,"';").replace(/ ; /g,";")+""; +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/js/suggestionParser.js b/code/datastudio/db_assistant/js/suggestionParser.js new file mode 100644 index 0000000000000000000000000000000000000000..93edc6f868329cec6c9a3b09123703da8b4a36be --- /dev/null +++ b/code/datastudio/db_assistant/js/suggestionParser.js @@ -0,0 +1,203 @@ +function Commands() +{ + this.cmds=[]; + this.add=add; + this.find=find; + this.findInArray=findInArray; + this.getOneFromArray=getOneFromArray; + this.load=load; + var __that__=this; + function add(cmd) + { + this.cmds[this.cmds.length]=cmd; + } + function find(cmdId,cur_pos) + { + var tmpCmds=[]; + $(this.cmds).each(function(i,cmd) + { + if(cmd.id.split(' ')[cur_pos]==cmdId) + { + tmpCmds[tmpCmds.length]=cmd; + } + }); + return tmpCmds; + } + function findInArray(array,cmdId,cur_pos) + { + var tmpCmds=[]; + $(array).each(function(i,cmd) + { + /*$(cmd.subs).each(function(j,sub){ + if(sub.id==cmdId) + { + sub.show=true; + return array; + } + });*/ + if(cmd.id.split(' ')[cur_pos]==cmdId) + { + tmpCmds[tmpCmds.length]=cmd; + } + }); + if(tmpCmds.length==0) + { + tmpCmds=array; + } + return tmpCmds; + } + function getOneFromArrayCnt(array,cur_pos) + { + var cc=0; + $(array).each(function(i,cmd) + { + if(cmd.id.split(' ').length==cur_pos) + { + cc++; + } + }); + return cc; + } + function getOneFromArray(array,cur_pos) + { + var rtnCmd=""; + var tempCnt=getOneFromArrayCnt(array,cur_pos); + $(array).each(function(i,cmd) + { + if(cmd.id.split(' ').length==cur_pos&&(tempCnt==1||tempCnt>2||(tempCnt==2 &&(cmd.alias.replace(/\s+/g,"") ==selectedCmdAlias.replace(/\s+/g,""))))) + { + rtnCmd=cmd; + } + }); + return rtnCmd; + } + function load(xml) + { + __that__.cmds.length=0; + $(xml).find("command").each(function(i,cmdXml) + { + var cmd=new Command(cmdXml.getAttribute("id"),cmdXml.getAttribute("alias"),cmdXml.childNodes[0].text); + $(cmdXml).children("sub").each(function(j,subXml) + { + var sub=new Sub($(subXml).attr("id"),$(subXml).children("suggestion").text()); + //fillSub(sub,subXml); + cmd.addSub(sub); + }); + __that__.add(cmd); + }); + } +} + +function fillSub(sub,subXml) +{ + $(subXml).children("option").each(function(i,optionXml) + { + var option=new Option($(optionXml).attr("id"),$(optionXml).children("suggestion").text()); + sub.addOption(option); + }); + $(subXml).children("sub").each(function(i,subXmlTemp) + { + var subTemp=new Sub($(subXmlTemp).attr("id"),$(subXmlTemp).children("suggestion").text()); + fillSub(subTemp,subXmlTemp); + sub.addSub(subTemp); + }); +} +function Command(id,alias,suggestion) +{ + this.id=id; + this.alias=alias; + this.suggestion=suggestion; + this.options=[]; + this.subs=[]; + this.addOption=addOption; + this.findOption=findOption; + this.addSub=addSub; + this.findSub=findSub; + + function addOption(option) + { + this.options[this.options.length]=option; + } + function findOption(optionId) + { + var tmpOption=""; + $(this.options).each(function(i,option) + { + if(optionId==option.id) + { + tmpOption=option; + } + }); + return tmpOption; + } + + function addSub(sub) + { + this.subs[this.subs.length]=sub; + } + function findSub(subId) + { + var tmpSub=""; + $(this.subs).each(function(i,sub) + { + if(subId==sub.id) + { + tmpSub=sub; + } + }); + return tmpSub; + } +} + +function Option(id,suggestion) +{ + this.id=id; + this.suggestion=suggestion; +} + +function Sub(id,suggestion) +{ + this.id=id; + this.suggestion=suggestion; + //this.show=false; + this.options=[]; + this.subs=[]; + this.addOption=addOption; + this.findOption=findOption; + this.addSub=addSub; + this.findSub=findSub; + + function addOption(option) + { + this.options[this.options.length]=option; + } + function findOption(optionId) + { + var tmpOption=""; + $(this.options).each(function(i,option) + { + if(optionId==option.id) + { + tmpOption=option; + } + }); + return tmpOption; + } + + function addSub(sub) + { + this.subs[this.subs.length]=sub; + } + function findSub(subId) + { + var tmpSub=""; + $(this.subs).each(function(i,sub) + { + if(subId==sub.id) + { + tmpSub=sub; + } + }); + return tmpSub; + } +} \ No newline at end of file diff --git a/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml b/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml new file mode 100644 index 0000000000000000000000000000000000000000..9e60313e72f0d5738845ce45ea81d2a891b7fb15 --- /dev/null +++ b/code/datastudio/db_assistant/openGauss 1.0.0/en/errorcode.xml @@ -0,0 +1,28969 @@ + +
ALTER DATABASE modifies a database, including its name, owner, connection limitation, and object isolation.
+-- Set the maximum number of connections to database music to 10: +postgres=# ALTER DATABASE music CONNECTION LIMIT= 10 ; + +-- Rename database music to music4: +postgres=# ALTER DATABASE music RENAME TO music4 ; + +-- Change the owner of database music2 to user tom: +postgres=# ALTER DATABASE music2 OWNER TO tom ; + +-- Set the tablespace of database music3 to PG_DEFAULT: +postgres=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT ; + +-- Disable the default index scan on database music3. +postgres=# ALTER DATABASE music3 SET enable_indexscan TO off ; + +-- Reset the enable_indexscan parameter. +postgres=# ALTER DATABASE music3 RESET enable_indexscan ; +Delete the databases: +postgres=# DROP DATABASE music2 ; +postgres=# DROP DATABASE music3 ; +postgres=# DROP DATABASE music4 ; +
ALTER DATA SOURCE modifies the attributes and content of the data source.
+The attributes include the name and owner. The content includes the type, version, and connection options.
+-- Rename the data source. +postgres=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; + +-- Change the owner. +postgres=# CREATE USER user_test1 IDENTIFIED BY ' Gs@123456 ' ; +postgres=# ALTER USER user_test1 WITH SYSADMIN ; +postgres=# ALTER DATA SOURCE ds_test OWNER TO user_test1 ; + +-- Modify TYPE and VERSION. +postgres=# ALTER DATA SOURCE ds_test TYPE ' MPPDB_TYPE ' VERSION ' XXX ' ; + +-- Add a column. +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( add dsn ' gaussdb ' , username ' test_user ' ) ; + +-- Modify a column. +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( set dsn ' unknown ' ) ; + +-- Delete a column. +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( drop username ) ; +
ALTER DEFAULT PRIVILEGES allows you to set the permissions that will be applied to objects created in the future. (It does not affect permissions granted to existing objects.)
+Only the permissions for tables (including views), functions, and types (including domains) can be altered.
+ALTER DIRECTORY modifies a directory.
+-- Change the owner of the directory. +postgres=# ALTER DIRECTORY dir OWNER TO system ; +
ALTER FUNCTION modifies the attributes of a customized function.
+Only the owner of the function or a system administrator has the permission to run this statement. If a function involves operations on temporary tables, ALTER FUNCTION cannot be used.
+-- Alter the execution rule of function add to IMMUTABLE ( that is, the same result is returned if the parameter remains unchanged ) . +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) IMMUTABLE ; + +-- Alter the name of function add to add_two_number. +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) RENAME TO add_two_number ; + +-- Change the owner of function add to omm. +postgres=# ALTER FUNCTION add_two_number ( INTEGER , INTEGER ) OWNER TO omm ; +
ALTER GROUP modifies the attributes of a user group.
+ALTER GROUP is an alias for ALTER ROLE, and it is not a standard SQL syntax and not recommended. Users can use ALTER ROLE directly.
+ALTER INDEX modifies the definition of an existing index.
+It has the following forms:
+Sends a notice instead of an error if the specified index does not exist.
+Changes only the name of the index. The stored data is not affected.
+This option changes the index tablespace to the specified tablespace and moves index-related data files to the new tablespace.
+Changes one or more index-method-specific storage parameters of an index. Note that the index content will not be modified immediately by this statement. You may need to use REINDEX to recreate the index based on different parameters to achieve the expected effect.
+Resets one or more index-method-specific storage parameters of an index to the default value. Similar to the SET statement, REINDEX may be used to completely update the index.
+Sets the indexes on a table or index partition to be unavailable.
+Rebuilds indexes on a table or an index partition.
+Renames an index partition.
+Modifies the tablespace to which an index partition belongs.
+Only the index owner or a system administrator can run this statement.
+-- Rename an existing index. +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5 ; + +-- Set the index as unusable. +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE ; + +-- Rebuild an index. +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD ; + +-- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index2 to example1. +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1 ; + +-- Change the tablespace of the partitioned table index CA_ADDRESS_SK_index3 to example2. +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2 ; + +-- Rename a partitioned table index. +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4 ; +
ALTER LARGE OBJECT changes the owner of a large object.
+Only a system administrator or the owner of the to-be-modified large object can run ALTER LARGE OBJECT.
+ALTER ROLE modifies role attributes.
+ALTER ROW LEVEL SECURITY POLICY modifies an existing row-level access control policy, including the policy name and the users and expressions affected by the policy.
+Only the table owner or a system administrator can perform this operation.
+-- Change the name of the all_data_rls policy. +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls ; + +-- Change the users affected by the row-level access control policy. +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice , bob ; +postgres=# \d+ all_data +Table "public.all_data" +Column | Type | Modifiers | Storage | Stats target | Description +--------+------------------------+-----------+----------+--------------+------------- +id | integer | | plain | | +role | character varying ( 100 ) | | extended | | +data | character varying ( 100 ) | | extended | | +Row Level Security Policies: +POLICY "all_data_new_rls" +TO alice , bob +USING ( ( ( role ) ::name = "current_user" ( ) ) ) +Has OIDs: no +Location Nodes: ALL DATANODES +Options: orientation=row , compression=no , enable_rowsecurity=true + +-- Modify the expression defined for the access control policy. +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING ( id > 100 AND role = current_user ) ; +postgres=# \d+ all_data +Table "public.all_data" +Column | Type | Modifiers | Storage | Stats target | Description +--------+------------------------+-----------+----------+--------------+------------- +id | integer | | plain | | +role | character varying ( 100 ) | | extended | | +data | character varying ( 100 ) | | extended | | +Row Level Security Policies: +POLICY "all_data_new_rls" +TO alice , bob +USING ( ( ( id > 100 ) AND ( ( role ) ::name = "current_user" ( ) ) ) ) +Has OIDs: no +Location Nodes: ALL DATANODES +Options: orientation=row , compression=no , enable_rowsecurity=true +
ALTER SCHEMA modifies schema properties.
+Only the owner of a schema or a system administrator has the permission to run the ALTER SCHEMA statement.
+-- Rename the current schema ds to ds_new. +postgres=# ALTER SCHEMA ds RENAME TO ds_new ; + +-- Change the owner of ds_new to jack. +postgres=# ALTER SCHEMA ds_new OWNER TO jack ; +
ALTER SEQUENCE modifies the parameters of an existing sequence.
+-- Change the owning column of serial to T1.C1. +postgres=# ALTER SEQUENCE serial OWNED BY T1.C1 ; +
ALTER SESSION defines or modifies the conditions or parameters that affect the current session. Modified session parameters are kept until the current session is disconnected.
+-- Set the character code of the current session to UTF8. +postgres=# ALTER SESSION SET NAMES ' UTF8 ' ; + +-- Set the current schema. +postgres=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds ; + +-- Set XML OPTION to DOCUMENT. +postgres=# ALTER SESSION SET XML OPTION DOCUMENT ; + +-- Create the role joe and set it as the session role. +postgres=# CREATE ROLE joe WITH PASSWORD ' Bigdata@123 ' ; +postgres=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD ' Bigdata@123 ' ; + +-- Switch to the default user. +postgres=> ALTER SESSION SET SESSION AUTHORIZATION default; +
ALTER SYNONYM modifies the attributes of the SYNONYM object.
+-- Change the owner of synonym t1 to u1. +postgres=# ALTER SYNONYM t1 OWNER TO u1 ; +
ALTER SYSTEM KILL SESSION ends a session.
+ALTER TABLE modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level access control, and adding or updating multiple columns.
+ALTER TABLE PARTITION modifies table partition, including adding, deleting, splitting, merging partitions, and modifying partition attributes.
+ALTER TABLESPACE modifies the attributes of a tablespace.
+If new_owner is the same as old_owner, the current user will not be verified. A message indicating successful ALTER execution is displayed.
+-- Rename the ds_location1 tablespace to ds_location3. +postgres=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 ; + +-- Change the owner of the ds_location2 tablespace. +postgres=# ALTER TABLESPACE ds_location2 OWNER TO jay ; +
ALTER TEXT SEARCH CONFIGURATION modifies the definition of a text search configuration. You can modify its mappings from token types to dictionaries, change the configuration's name or owner, or modify the parameters.
+The ADD MAPPING FOR form installs a list of dictionaries to be consulted for the specified token types; an error will be generated if there is already a mapping for any of the token types.
+The ALTER MAPPING FOR form removes existing mapping for those token types and then adds specified mappings.
+ALTER MAPPING REPLACE ... WITH ... and ALTER MAPPING FOR... REPLACE ... WITH ... options replace old_dictionary with new_dictionary. Note that only when pg_ts_config_map has tuples corresponding to maptokentype and old_dictionary, the update will succeed. If the update fails, no messages are returned.
+The DROP MAPPING FOR form deletes all dictionaries for the specified token types in the text search configuration. If IF EXISTS is not specified and the string type mapping specified by DROP MAPPING FOR does not exist in text search configuration, an error will occur in the database.
+-- Add text search configuration string mapping. +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple , english_stem ; +ALTER TEXT SEARCH CONFIGURATION + +-- Add text search configuration string mapping. +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem , french_stem ; +ALTER TEXT SEARCH CONFIGURATION + +-- Add text search configuration string mapping. +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem ; +ALTER TEXT SEARCH CONFIGURATION +
ALTER TEXT SEARCH DICTIONARY modifies the definition of a full-text search dictionary, including its parameters, name, owner, and schema.
+-- Modify the definition of stop words in Snowball dictionaries. Retain the values of other parameters. +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian , FilePath = ' file:///home/dicts ' ) ; + +-- Modify the Language parameter in Snowball dictionaries and delete the definition of stop words. +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch , StopWords ) ; + +-- Update the dictionary definition and do not change any other content. +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ) ; +
ALTER TRIGGER modifies the definition of a trigger.
+Only the owner of a table where the trigger is created and a system administrator can run the ALTER TRIGGER statement.
+-- Modify a trigger. +postgres=# ALTER TRIGGER delete_trigger ON test_trigger_src_tbl RENAME TO delete_trigger_renamed ; + +-- Disable insert_trigger. +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER insert_trigger ; + +-- Disable all triggers on the current table. +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER ALL ; +
ALTER TYPE modifies the definition of a type.
+ALTER USER modifies the attributes of a database user.
+Session parameters modified by ALTER USER apply to a specified user and take effect in the next session.
+ALTER VIEW modifies all auxiliary attributes of a view. (To modify the query definition of a view, use CREATE OR REPLACE VIEW.)
+-- Rename a view. +postgres=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2 ; + +-- Change the schema of a view. +postgres=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public ; +
ANALYZE collects statistics about ordinary tables in a database, and stores the results in the PG_STATISTIC system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan.
+If no parameter is specified, ANALYZE analyzes each table and partitioned table in the current database. You can also specify the table_name, column, and partition_name parameters to restrict the analysis to a specific table, column, or partitioned table.
+ANALYZE | ANALYSE VERIFY is used to check whether data files of common tables (row-store and column-store tables) in a database are damaged.
+Non-temporary tables cannot be analyzed in an anonymous block, transaction block, function, or stored procedure. Temporary tables in a stored procedure can be analyzed but their statistics updates cannot be rolled back.
+The ANALYZE VERIFY operation is used to detect abnormal scenarios. The RELEASE version is required. In the ANALYZE VERIFY scenario, remote read is not triggered. Therefore, the remote read parameter does not take effect. If the system detects that a page is damaged due to an error in a key system table, the system directly reports an error and does not continue the detection.
+postgres=# CREATE TABLE customer_info + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) + ; + +-- Create a partitioned table. +postgres=# CREATE TABLE customer_par + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2452275 ) , +PARTITION P2 VALUES LESS THAN ( 2452640 ) , +PARTITION P3 VALUES LESS THAN ( 2453000 ) , +PARTITION P4 VALUES LESS THAN ( MAXVALUE ) + ) +ENABLE ROW MOVEMENT ; + +-- Run ANALYZE to update statistics. +postgres=# ANALYZE customer ; + +-- Run ANALYZE VERBOSE statement to update statistics and display table information. +postgres=# ANALYZE VERBOSE customer_info ; +INFO: analyzing "cstore.pg_delta_3394584009" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" inheritance tree ( cn_5002 pid=53078 ) +ANALYZE +If any environment-related fault occurs , check the logs of the primary node of the database. + +-- Delete the table. +postgres=# DROP TABLE customer ; +postgres=# DROP TABLE customer_par ; +
ANALYZE collects statistics about ordinary tables in a database, and stores the results in the PG_STATISTIC system catalog. The execution plan generator uses these statistics to determine which one is the most effective execution plan.
+If no parameter is specified, ANALYZE analyzes each table and partitioned table in the current database. You can also specify the table_name, column, and partition_name parameters to restrict the analysis to a specific table, column, or partitioned table.
+ANALYZE | ANALYSE VERIFY is used to check whether data files of common tables (row-store and column-store tables) in a database are damaged.
+Non-temporary tables cannot be analyzed in an anonymous block, transaction block, function, or stored procedure. Temporary tables in a stored procedure can be analyzed but their statistics updates cannot be rolled back.
+The ANALYZE VERIFY operation is used to detect abnormal scenarios. The RELEASE version is required. In the ANALYZE VERIFY scenario, remote read is not triggered. Therefore, the remote read parameter does not take effect. If the system detects that a page is damaged due to an error in a key system table, the system directly reports an error and does not continue the detection.
+postgres=# CREATE TABLE customer_info + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) + ; + +-- Create a partitioned table. +postgres=# CREATE TABLE customer_par + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2452275 ) , +PARTITION P2 VALUES LESS THAN ( 2452640 ) , +PARTITION P3 VALUES LESS THAN ( 2453000 ) , +PARTITION P4 VALUES LESS THAN ( MAXVALUE ) + ) +ENABLE ROW MOVEMENT ; + +-- Run ANALYZE to update statistics. +postgres=# ANALYZE customer ; + +-- Run ANALYZE VERBOSE statement to update statistics and display table information. +postgres=# ANALYZE VERBOSE customer_info ; +INFO: analyzing "cstore.pg_delta_3394584009" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" inheritance tree ( cn_5002 pid=53078 ) +ANALYZE +If any environment-related fault occurs , check the logs of the primary node of the database. + +-- Delete the table. +postgres=# DROP TABLE customer ; +postgres=# DROP TABLE customer_par ; +
BEGIN may be used to initiate an anonymous block or a single transaction. This section describes the syntax of BEGIN used to initiate an anonymous block. For details about the BEGIN syntax that initiates transactions, see START TRANSACTION.
+An anonymous block is a structure that can dynamically create and execute stored procedure code instead of permanently storing code as a database object in the database.
+CALL can be used to call defined functions and stored procedures.
+-- Transfer by parameter value. +postgres=# CALL func_add_sql ( 1 , 3 ) ; + +-- Transfer by naming tag method. +postgres=# CALL func_add_sql ( num1 => 1 , num2 => 3 ) ; +postgres=# CALL func_add_sql ( num2 := 2 , num1 := 3 ) ; + +-- Transfer a constant as an output parameter. +postgres=# CALL func_increment_sql ( 1 , 2 , 1 ) ; + +-- Call the function. +postgres=# call package_func_overload ( 1 , ' test ' ) ; +postgres=# call package_func_overload ( 1 , 1 ) ; +
A checkpoint is a point in the transaction log sequence at which all data files have been updated to reflect the information in the log. All data files will be flushed to a disk.
+CHECKPOINT forces a transaction log checkpoint. By default, WALs periodically specify checkpoints in a transaction log. You may use gs_guc to specify run-time parameters checkpoint_segments and checkpoint_timeout to adjust the atomized checkpoint intervals.
+-- Set a checkpoint. +postgres=# CHECKPOINT ; +
CLOSE frees the resources associated with an open cursor.
+-- Close the cursor and commit the transaction. +postgres=# CLOSE cursor1 ; + +-- Close the cursor and commit the transaction. +postgres=# CLOSE cursor2 ; + +-- Close the cursor. +postgres=# CLOSE cursor1 ; +
CLUSTER is used to cluster a table based on an index.
+CLUSTER instructs openGauss to cluster the table specified by table_name based on the index specified by index_name. The index must have been defined by table_name.
+When a table is clustered, it is physically reordered based on the index information. Clustering is a one-time operation. When the table is subsequently updated, the changes are not clustered. That is, no attempt is made to store new or updated rows according to their index order.
+When a table is clustered, openGauss records which index the table was clustered by. The form CLUSTER table_name reclusters the table using the same index as before. You can also use the CLUSTER or SET WITHOUT CLUSTER form of ALTER TABLE to set the index to be used for future cluster operations, or to clear any previous settings.
+CLUSTER without any parameter reclusters all the previously-clustered tables in the current database that the calling user owns, or all such tables if called by an administrator.
+When a table is being clustered, an ACCESS EXCLUSIVE lock is acquired on it. This prevents any other database operations (both read and write) from being performed on the table until the CLUSTER is finished.
+Only row-store B-tree indexes support CLUSTER.
+In the case where you are accessing single rows randomly within a table, the actual order of the data in the table is unimportant. However, if you tend to access some data more than others, and there is an index that groups them together, it is helpful by using CLUSTER. If you are requesting a range of indexed values from a table, or a single indexed value that has multiple rows that match, CLUSTER will help because once the index identifies the table page for the first row that matches, all other rows that match are probably already on the same table page, and so you save disk accesses and speed up the query.
+When an index scan is used, a temporary copy of the table is created that contains the table data in the index order. Temporary copies of each index on the table are created as well. Therefore, you need free space on disk at least equal to the sum of the table size and the total index size.
+Because CLUSTER remembers which indexes are clustered, one can cluster the tables manually the first time, then set up a time like VACUUM without any parameters, so that the desired tables are periodically reclustered.
+Because the optimizer records statistics about the ordering of tables, it is advisable to run ANALYZE on the newly clustered table. Otherwise, the optimizer might make poor choices of query plans.
+CLUSTER cannot be executed in transactions.
+-- Cluster the tpcds.inventory_p1 table. +postgres=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1 ; + +-- Cluster the p3 partition. +postgres=# CLUSTER tpcds.inventory_p1 PARTITION ( p3 ) USING ds_inventory_p1_index1 ; + +-- Cluster the tables that can be clustered in the database. +postgres=# CLUSTER ; +
COMMENT defines or changes the comment of an object.
+-- Comment out the tpcds.customer_demographics_t2.cd_demo_sk column. +postgres=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS ' Primary key of customer demographics table. ' ; + +-- Comment out the tpcds.customer_details_view_v2 view. +postgres=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS ' View of customer detail ' ; +
COMMIT or END commits all operations of a transaction.
+Only the creator of a transaction or a system administrator can run the COMMIT command. The creation and commit operations must be in different sessions.
+-- Create a table. +postgres=# CREATE TABLE tpcds.customer_demographics_t2 + ( +CD_DEMO_SK INTEGER NOT NULL , +CD_GENDER CHAR ( 1 ) , +CD_MARITAL_STATUS CHAR ( 1 ) , +CD_EDUCATION_STATUS CHAR ( 20 ) , +CD_PURCHASE_ESTIMATE INTEGER , +CD_CREDIT_RATING CHAR ( 10 ) , +CD_DEP_COUNT INTEGER , +CD_DEP_EMPLOYED_COUNT INTEGER , +CD_DEP_COLLEGE_COUNT INTEGER + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) + ; + +-- Start a transaction. +postgres=# START TRANSACTION ; + +-- Insert data. +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; + +-- Commit the transaction to make all changes permanent. +postgres=# COMMIT ; + +-- Query data. +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; + +-- Delete the tpcds.customer_demographics_t2 table. +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; +
COMMIT or END commits all operations of a transaction.
+Only the creator of a transaction or a system administrator can run the COMMIT command. The creation and commit operations must be in different sessions.
+-- Create a table. +postgres=# CREATE TABLE tpcds.customer_demographics_t2 + ( +CD_DEMO_SK INTEGER NOT NULL , +CD_GENDER CHAR ( 1 ) , +CD_MARITAL_STATUS CHAR ( 1 ) , +CD_EDUCATION_STATUS CHAR ( 20 ) , +CD_PURCHASE_ESTIMATE INTEGER , +CD_CREDIT_RATING CHAR ( 10 ) , +CD_DEP_COUNT INTEGER , +CD_DEP_EMPLOYED_COUNT INTEGER , +CD_DEP_COLLEGE_COUNT INTEGER + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) + ; + +-- Start a transaction. +postgres=# START TRANSACTION ; + +-- Insert data. +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; + +-- Commit the transaction to make all changes permanent. +postgres=# COMMIT ; + +-- Query data. +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; + +-- Delete the tpcds.customer_demographics_t2 table. +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; +
COMMIT PREPARED commits a prepared two-phase transaction.
+COPY copies data between tables and files.
+COPY FROM copies data from a file to a table, and COPY TO copies data from a table to a file.
+-- Copy data from the tpcds.ship_mode file to the /home/omm/ds_ship_mode.dat file: +postgres=# COPY tpcds.ship_mode TO ' /home/omm/ds_ship_mode.dat ' ; + +-- Output tpcds.ship_mode to stdout. +postgres=# COPY tpcds.ship_mode TO stdout; + +-- Copy data from stdin to the tpcds.ship_mode_t1 table. +postgres=# COPY tpcds.ship_mode_t1 FROM stdin ; + +-- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table. +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' ; + +-- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to TEXT ( format 'text' ) , the delimiter set to \t' ( delimiter E'\t' ) , excessive columns ignored ( ignore_extra_data 'true' ) , and characters not escaped ( noescaping 'true' ) . +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' WITH ( format ' text ' , delimiter E ' \t ' , ignore_extra_data ' true ' , noescaping ' true ' ) ; + +-- Copy data from the /home/omm/ds_ship_mode.dat file to the tpcds.ship_mode_t1 table, with the import format set to FIXED, fixed-length format specified ( FORMATTER ( SM_SHIP_MODE_SK ( 0, 2 ) , SM_SHIP_MODE_ID ( 2,16 ) , SM_TYPE ( 18,30 ) , SM_CODE ( 50,10 ) , SM_CARRIER ( 61,20 ) , SM_CONTRACT ( 82,20 ) ) ) , excessive columns ignored ( ignore_extra_data ) , and headers included ( header ) . +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' FIXED FORMATTER ( SM_SHIP_MODE_SK ( 0 , 2 ) , SM_SHIP_MODE_ID ( 2 , 16 ) , SM_TYPE ( 18 , 30 ) , SM_CODE ( 50 , 10 ) , SM_CARRIER ( 61 , 20 ) , SM_CONTRACT ( 82 , 20 ) ) header ignore_extra_data ; +
Create a database. By default, a new database is created by copying the standard system database template0. Only template0 can be used to create a new database.
+-- Create database music using GBK ( the local encoding type is also GBK ) : +postgres=# CREATE DATABASE music ENCODING ' GBK ' template = template0 ; + +-- Create database music2 and specify user jim as its owner: +postgres=# CREATE DATABASE music2 OWNER jim ; + +-- Create database music3 using template template0 and specify user jim as its owner: +postgres=# CREATE DATABASE music3 OWNER jim TEMPLATE template0 ; + +-- Create a database compatible with the TD format. +postgres=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY ' C ' ; + +-- Create a database compatible with the ORA format. +postgres=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY ' A ' ; +
CREATE DATA SOURCE creates an external data source, which defines the information about the database that openGauss will connect to.
+-- Create an empty data source that does not contain any information. +postgres=# CREATE DATA SOURCE ds_test1 ; + +-- Create a data source with TYPE information and VERSION being null. +postgres=# CREATE DATA SOURCE ds_test2 TYPE ' MPPDB ' VERSION NULL ; + +-- Create a data source that contains only OPTIONS. +postgres=# CREATE DATA SOURCE ds_test3 OPTIONS ( dsn ' openGauss ' , encoding ' utf8 ' ) ; + +-- Create a data source that contains TYPE, VERSION, and OPTIONS. +postgres=# CREATE DATA SOURCE ds_test4 TYPE ' unknown ' VERSION ' 11.2.3 ' OPTIONS ( dsn ' openGauss ' , username ' userid ' , password ' pwd@123456 ' , encoding ' ' ) ; +
CREATE DIRECTORY creates a directory. The directory defines an alias for a path in the server file system and is used to store data files used by users.
+-- Create a directory. +postgres=# CREATE OR REPLACE DIRECTORY dir as ' /tmp/ ' ; +
CREATE FUNCTION creates a function.
+-- Define a function as SQL query. +postgres=# CREATE FUNCTION func_add_sql ( integer , integer ) RETURNS integer +AS ' select $1 + $2 ; ' +LANGUAGE SQL +IMMUTABLE +RETURNS NULL ON NULL INPUT ; + +-- Add an integer by parameter name using PL/pgSQL. +postgres=# CREATE OR REPLACE FUNCTION func_increment_plsql ( i integer ) RETURNS integer AS $$ +BEGIN +RETURN i + 1 ; +END ; +$$ LANGUAGE plpgsql ; + +-- Return the RECORD type. +CREATE OR REPLACE FUNCTION compute ( i int , out result_1 bigint , out result_2 bigint ) +returns SETOF RECORD +as $$ +begin +result_1 = i + 1 ; +result_2 = i * 10 ; +return next; +end ; +$$language plpgsql ; + +-- Return a record containing multiple output parameters. +postgres=# CREATE FUNCTION func_dup_sql ( in int , out f1 int , out f2 text ) +AS $$ SELECT $1 , CAST ( $1 AS text ) || ' is text ' $$ +LANGUAGE SQL ; +postgres=# SELECT * FROM func_dup_sql ( 42 ) ; + +-- Compute the sum of two integers and return the result ( if the input is null, the returned result is null ) . +postgres=# CREATE FUNCTION func_add_sql2 ( num1 integer , num2 integer ) RETURN integer +AS +BEGIN +RETURN num1 + num2 ; +END ; +/ +
CREATE GROUP creates a user group.
+CREATE GROUP is an alias for CREATE ROLE, and it is not a standard SQL syntax and not recommended. Users can use CREATE ROLE directly.
+CREATE INDEX creates an index in a specified table.
+Indexes are primarily used to enhance database performance (though inappropriate use can result in database performance deterioration). You are advised to create indexes on:
+Partitioned tables do not support concurrent index creation, partial index creation, and NULL FIRST.
+-- Create a common index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) ; + +-- Create a B-tree index on the SM_SHIP_MODE_SK column in the tpcds.ship_mode_t1 table. +postgres=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree ( SM_SHIP_MODE_SK ) ; + +-- Create an expression index on the SM_CODE column in the tpcds.ship_mode_t1 table: +postgres=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1 ( SUBSTR ( SM_CODE , 1 , 4 ) ) ; + +-- Create a partial index on the SM_SHIP_MODE_SK column where SM_SHIP_MODE_SK is greater than 10 in the tpcds.ship_mode_t1 table. +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) WHERE SM_SHIP_MODE_SK>10 ; + +-- Create the partitioned table index ds_customer_address_p1_index1 without specifying the index partition name. +postgres=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1 ( CA_ADDRESS_SK ) LOCAL ; + +-- Create the partitioned table index ds_customer_address_p1_index2 with the name of the index partition specified. +postgres=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1 ( CA_ADDRESS_SK ) LOCAL + ( +PARTITION CA_ADDRESS_SK_index1 , +PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3 , +PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 + ) +TABLESPACE example2 ; + +-- Create a column-store table and its GIN index: +postgres=# create table cgin_create_test ( a int , b text ) with ( orientation = column ) ; +CREATE TABLE +postgres=# create index cgin_test on cgin_create_test using gin ( to_tsvector ( ' ngram ' , b ) ) ; +CREATE INDEX +
CREATE ROW LEVEL SECURITY POLICY creates a row-level access control policy for a table.
+The policy takes effect only after row-level access control is enabled (by running ALTER TABLE... ENABLE ROW LEVEL SECURITY). Otherwise, this statement does not take effect.
+Currently, row-level access control affects the read (SELECT, UPDATE, DELETE) of data tables and does not affect the write (INSERT and MERGE INTO) of data tables. The table owner or system administrators can create an expression in the USING clause. When the client reads the data table, the database server combines the expressions that meet the condition and applies it to the execution plan in the statement rewriting phase of a query. For each tuple in a data table, if the expression returns TRUE, the tuple is visible to the current user; if the expression returns FALSE or NULL, the tuple is invisible to the current user.
+A row-level access control policy name is specific to a table. A data table cannot have row-level access control policies with the same name. Different data tables can have the same row-level access control policy.
+Row-level access control policies can be applied to specified operations (SELECT, UPDATE, DELETE, and ALL). ALL indicates that SELECT, UPDATE, and DELETE will be affected. For a new row-level access control policy, the default value ALL will be used if you do not specify the operations that will be affected.
+Row-level access control policies can be applied to a specified user (role) or to all users (PUBLIC). For a new row-level access control policy, the default value PUBLIC will be used if you do not specify the user that will be affected.
+CREATE PROCEDURE creates a stored procedure.
+CREATE ROLE is used to create a role.
+A role is an entity that owns database objects and permissions. In different environments, a role can be considered a user, a group, or both.
+CREATE SCHEMA creates a schema.
+Named objects are accessed either by "qualifying" their names with the schema name as a prefix, or by setting a search path that includes the desired schema. When creating named objects, you can also use the schema name as a prefix.
+Optionally, CREATE SCHEMA can include sub-commands to create objects within the new schema. The sub-commands are treated essentially the same as separate commands issued after creating the schema. If the AUTHORIZATION clause is used, all the created objects are owned by this user.
+-- Create a schema named role1 for the role1 role. The owner of the films and winners tables created by the clause is role1. +postgres=# CREATE SCHEMA AUTHORIZATION role1 +CREATE TABLE films ( title text , release date , awards text[] ) +CREATE VIEW winners AS +SELECT title , release FROM films WHERE awards IS NOT NULL ; +
CREATE SEQUENCE adds a sequence to the current database. The owner of a sequence is the user who creates the sequence.
+postgres=# CREATE SEQUENCE serial +START 101 +CACHE 20 ; +Select the next number from the sequence. +postgres=# SELECT nextval ( ' serial ' ) ; +nextval + +-- +102 +Create a sequence associated with the table. +postgres=# CREATE TABLE customer_address + ( +ca_address_sk integer not null , +ca_address_id char ( 16 ) not null , +ca_street_number char ( 10 ) , +ca_street_name varchar ( 60 ) , +ca_street_type char ( 15 ) , +ca_suite_number char ( 10 ) , +ca_city varchar ( 60 ) , +ca_county varchar ( 30 ) , +ca_state char ( 2 ) , +ca_zip char ( 10 ) , +ca_country varchar ( 20 ) , +ca_gmt_offset decimal ( 5 , 2 ) , +ca_location_type char ( 20 ) + ) ; +postgres=# CREATE SEQUENCE serial1 +START 101 +CACHE 20 +OWNED BY customer_address.ca_address_sk ; +
CREATE SYNONYM creates a synonym object. A synonym is an alias of a database object and is used to record the mapping between database object names. You can use synonyms to access associated database objects.
+CREATE TABLE is used to create an initially empty table in the current database. The table will be owned by the creator.
+CREATE TABLE AS creates a table from the results of a query.
+It creates a table and fills it with data obtained using SELECT. The table columns have the names and data types associated with the output columns of SELECT (except that you can override the SELECT output column names by giving an explicit list of new column names).
+CREATE TABLE AS queries a source table once and writes the data in a new table. The result in the query view changes with the source table. In contrast, the view re-computes and defines its SELECT statement at each query.
+CREATE TABLE PARTITION creates a partitioned table. A partitioned table is a logical table that is divided into several physical partitions for storage based on a specific plan. Data is stored in physical partitions not the logical table.
+The common forms of partitioning include range partitioning, hash partitioning, list partitioning, and value partitioning. Currently, the system supports only range partitioning for row-store and column-store tables.
+In range partitioning, a table is partitioned based on ranges defined by values in one or more columns, with no overlap between the ranges of values assigned to different partitions. Each range has a dedicated partition for data storage.
+The range partitioning policy refers to how data is inserted into partitions. Currently, range partitioning only allows the use of the range partitioning policy.
+In range partitioning, a table is partitioned based on partition key values. If a record can be mapped to a partition, it is inserted into the partition; if it cannot, an error message is returned. Range partitioning is the most commonly used partitioning policy.
+Partitioning can provide several benefits:
+A partitioned table supports unique and primary key constraints. The constraint keys of these constraints must contain all partition keys.
+-- Create a range-partitioned table tpcds.web_returns_p1. +postgres=# CREATE TABLE tpcds.web_returns_p1 + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER , +WR_REFUNDED_CDEMO_SK INTEGER , +WR_REFUNDED_HDEMO_SK INTEGER , +WR_REFUNDED_ADDR_SK INTEGER , +WR_RETURNING_CUSTOMER_SK INTEGER , +WR_RETURNING_CDEMO_SK INTEGER , +WR_RETURNING_HDEMO_SK INTEGER , +WR_RETURNING_ADDR_SK INTEGER , +WR_WEB_PAGE_SK INTEGER , +WR_REASON_SK INTEGER , +WR_ORDER_NUMBER BIGINT NOT NULL , +WR_RETURN_QUANTITY INTEGER , +WR_RETURN_AMT DECIMAL ( 7 , 2 ) , +WR_RETURN_TAX DECIMAL ( 7 , 2 ) , +WR_RETURN_AMT_INC_TAX DECIMAL ( 7 , 2 ) , +WR_FEE DECIMAL ( 7 , 2 ) , +WR_RETURN_SHIP_COST DECIMAL ( 7 , 2 ) , +WR_REFUNDED_CASH DECIMAL ( 7 , 2 ) , +WR_REVERSED_CHARGE DECIMAL ( 7 , 2 ) , +WR_ACCOUNT_CREDIT DECIMAL ( 7 , 2 ) , +WR_NET_LOSS DECIMAL ( 7 , 2 ) + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2450815 ) , +PARTITION P2 VALUES LESS THAN ( 2451179 ) , +PARTITION P3 VALUES LESS THAN ( 2451544 ) , +PARTITION P4 VALUES LESS THAN ( 2451910 ) , +PARTITION P5 VALUES LESS THAN ( 2452275 ) , +PARTITION P6 VALUES LESS THAN ( 2452640 ) , +PARTITION P7 VALUES LESS THAN ( 2453005 ) , +PARTITION P8 VALUES LESS THAN ( MAXVALUE ) + ) ; + +-- Query the number of rows in the P1 partition. +postgres=# SELECT COUNT ( * ) FROM tpcds.web_returns_p1 PARTITION FOR ( 2450815 ) ; +count +-------- +0 + ( 1 row ) +Example 2: Create a range-partitioned table tpcds.web_returns_p2. The table has eight partitions and their partition keys are of the integer type. The upper limit of the eighth partition is MAXVALUE.The ranges of the partitions are: wr_returned_date_sk < 2450815 , 2450815 鈮?wr_returned_date_sk < 2451179 , 2451179 鈮?wr_returned_date_sk < 2451544 , 2451544 鈮?wr_returned_date_sk < 2451910 , 2451910 鈮?wr_returned_date_sk < 2452275 , 2452275 鈮?wr_returned_date_sk < 2452640 , 2452640 鈮?wr_returned_date_sk < 2453005 , and wr_returned_date_sk 鈮?2453005. +The tablespace of the tpcds.web_returns_p2 partitioned table is example1. Partitions P1 to P7 have no specified tablespaces , and use the example1 tablespace of the tpcds.web_returns_p2 partitioned table. The tablespace of the P8 partitioned table is example2. +Assume that the following data directories of the database nodes are empty directories for which user dwsadmin has the read and write permissions: /pg_location/mount1/path1 , /pg_location/mount2/path2 , /pg_location/mount3/path3 , and /pg_location/mount4/path4. +postgres=# CREATE TABLESPACE example1 RELATIVE LOCATION ' tablespace1/tablespace_1 ' ; +postgres=# CREATE TABLESPACE example2 RELATIVE LOCATION ' tablespace2/tablespace_2 ' ; +postgres=# CREATE TABLESPACE example3 RELATIVE LOCATION ' tablespace3/tablespace_3 ' ; +postgres=# CREATE TABLESPACE example4 RELATIVE LOCATION ' tablespace4/tablespace_4 ' ; +postgres=# CREATE TABLE tpcds.web_returns_p2 + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER , +WR_REFUNDED_CDEMO_SK INTEGER , +WR_REFUNDED_HDEMO_SK INTEGER , +WR_REFUNDED_ADDR_SK INTEGER , +WR_RETURNING_CUSTOMER_SK INTEGER , +WR_RETURNING_CDEMO_SK INTEGER , +WR_RETURNING_HDEMO_SK INTEGER , +WR_RETURNING_ADDR_SK INTEGER , +WR_WEB_PAGE_SK INTEGER , +WR_REASON_SK INTEGER , +WR_ORDER_NUMBER BIGINT NOT NULL , +WR_RETURN_QUANTITY INTEGER , +WR_RETURN_AMT DECIMAL ( 7 , 2 ) , +WR_RETURN_TAX DECIMAL ( 7 , 2 ) , +WR_RETURN_AMT_INC_TAX DECIMAL ( 7 , 2 ) , +WR_FEE DECIMAL ( 7 , 2 ) , +WR_RETURN_SHIP_COST DECIMAL ( 7 , 2 ) , +WR_REFUNDED_CASH DECIMAL ( 7 , 2 ) , +WR_REVERSED_CHARGE DECIMAL ( 7 , 2 ) , +WR_ACCOUNT_CREDIT DECIMAL ( 7 , 2 ) , +WR_NET_LOSS DECIMAL ( 7 , 2 ) + ) +TABLESPACE example1 +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2450815 ) , +PARTITION P2 VALUES LESS THAN ( 2451179 ) , +PARTITION P3 VALUES LESS THAN ( 2451544 ) , +PARTITION P4 VALUES LESS THAN ( 2451910 ) , +PARTITION P5 VALUES LESS THAN ( 2452275 ) , +PARTITION P6 VALUES LESS THAN ( 2452640 ) , +PARTITION P7 VALUES LESS THAN ( 2453005 ) , +PARTITION P8 VALUES LESS THAN ( MAXVALUE ) TABLESPACE example2 + ) +ENABLE ROW MOVEMENT ; + +-- Create a partitioned table using LIKE. +postgres=# CREATE TABLE tpcds.web_returns_p3 ( LIKE tpcds.web_returns_p2 INCLUDING PARTITION ) ; +
CREATE TABLESPACE creates a tablespace in a database.
+-- Create a tablespace. +postgres=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; + +-- Create a tablespace and set its owner to user joe. +postgres=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +
CREATE TEXT SEARCH CONFIGURATION creates a text search configuration. A text search configuration specifies a text search parser that can divide a string into tokens, plus dictionaries that can be used to determine which tokens are of interest for searching.
+-- Create a text search configuration. +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram2 ( parser=ngram ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; + +-- Create a text search configuration. +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram3 ( copy=ngram2 ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; +
CREATE TEXT SEARCH DICTIONARY creates a full-text retrieval dictionary. A dictionary is used to identify and process particular words during full-text retrieval.
+Dictionaries are created by using predefined templates (defined in the PG_TS_TEMPLATE system catalog). Five types of dictionaries can be created, Simple, Ispell, Synonym, Thesaurus, and Snowball. These dictionaries are used to handle different types of tasks.
+CREATE TRIGGER creates a trigger. The trigger will be associated with the specified table or view, and will execute the specified function operations are performed.
+-- Create a source table and a destination table. +postgres=# CREATE TABLE test_trigger_src_tbl ( id1 INT , id2 INT , id3 INT ) ; +postgres=# CREATE TABLE test_trigger_des_tbl ( id1 INT , id2 INT , id3 INT ) ; + +-- Create a trigger function. +postgres=# CREATE OR REPLACE FUNCTION tri_insert_func ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +INSERT INTO test_trigger_des_tbl VALUES ( NEW.id1 , NEW.id2 , NEW.id3 ) ; +RETURN NEW ; +END +$$ LANGUAGE PLPGSQL ; +postgres=# CREATE OR REPLACE FUNCTION tri_update_func ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +UPDATE test_trigger_des_tbl SET id3 = NEW.id3 WHERE id1=OLD.id1 ; +RETURN OLD ; +END +$$ LANGUAGE PLPGSQL ; +postgres=# CREATE OR REPLACE FUNCTION TRI_DELETE_FUNC ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +DELETE FROM test_trigger_des_tbl WHERE id1=OLD.id1 ; +RETURN OLD ; +END +$$ LANGUAGE PLPGSQL ; + +-- Create an INSERT trigger. +postgres=# CREATE TRIGGER insert_trigger +BEFORE INSERT ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_insert_func ( ) ; + +-- Create an UPDATE trigger. +postgres=# CREATE TRIGGER update_trigger +AFTER UPDATE ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_update_func ( ) ; + +-- Create a DELETE trigger. +postgres=# CREATE TRIGGER delete_trigger +BEFORE DELETE ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_delete_func ( ) ; +
CREATE TYPE registers a new data type for use in the current database. The user who defines a type becomes its owner. Types are designed only for row-store tables.
+The following data types can be created: composite type, base type, shell type, and enumerated type.
+A composite type is specified by a list of attribute names and data types. If the data type of an attribute is collatable, the attribute's collation rule can also be specified. This is essentially the same as the row type of a table, but using CREATE TYPE avoids the need to create an actual table when all that is wanted is to define a type. A stand-alone composite type is useful as the parameter or return type of a function.
+To create a composite type, you must have the USAGE permission on all of its attribute types.
+You can create a base type (scalar type). Generally, these functions must be written in the underlying language.
+A shell type is simply a placeholder for a type to be defined later; it is created by issuing CREATE TYPE with no parameters except for the type name. Shell types are needed as forward references when base types are created.
+An enumerated type is a list of one or more quoted labels, each of which must be 1 to 64 bytes long.
+If a schema name is given then the type is created in the specified schema. Otherwise, it is created in the current schema. The type name must be distinct from the name of any existing type or domain in the same schema. (Because tables have associated data types, the type name must also be distinct from the name of any existing table in the same schema.)
+-- Create a composite type, create a table, insert data, and make a query. +postgres=# CREATE TYPE compfoo AS ( f1 int , f2 text ) ; +postgres=# CREATE TABLE t1_compfoo ( a int , b compfoo ) ; +postgres=# CREATE TABLE t2_compfoo ( a int , b compfoo ) ; +postgres=# INSERT INTO t1_compfoo values ( 1 , ( 1 , ' demo ' ) ) ; +postgres=# INSERT INTO t2_compfoo select * from t1_typ5 ; +postgres=# SELECT ( b ) .f1 FROM t1_compfoo ; +postgres=# SELECT * FROM t1_compfoo t1 join t2_compfoo t2 on ( t1.b ) .f1= ( t1.b ) .f1 ; + +-- Change the owner of the user-defined type compfoo1 to usr1. +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; + +-- Create an enumerated type. +postgres=# CREATE TYPE bugstatus AS ENUM ( ' create ' , ' modify ' , ' closed ' ) ; +
CREATE USER creates a user.
+CREATE VIEW creates a view. A view is a virtual table, not a base table. Only view definition is stored in the database and view data is not. The data is stored in a base table. If data in the base table changes, the data in the view changes accordingly. In this sense, a view is like a window through which users can know their interested data and data changes in the database.
+-- Create a view consisting of columns whose spcname is pg_default. +postgres=# CREATE VIEW myView AS +SELECT * FROM pg_tablespace WHERE spcname = ' pg_default ' ; +
CURSOR defines a cursor to retrieve a small number of rows at a time out of a larger query.
+To process SQL statements, the stored procedure process assigns a memory segment to store context association. Cursors are handles or pointers pointing to context regions. With cursors, stored procedures can control alterations in context regions.
+-- Set up cursor1. +postgres=# CURSOR cursor1 FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; + +-- Fetch the first three rows in cursor1. +postgres=# FETCH FORWARD 3 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 3 rows ) + +-- Close the cursor and commit the transaction. +postgres=# CLOSE cursor1 ; + +-- Set up cursor2. +postgres=# CURSOR cursor2 FOR VALUES ( 1 , 2 ) , ( 0 , 3 ) ORDER BY 1 ; + +-- Fetch the first two rows in cursor2. +postgres=# FETCH FORWARD 2 FROM cursor2 ; +column1 | column2 +---------+--------- +0 | 3 +1 | 2 + ( 2 rows ) + +-- Close the cursor and commit the transaction. +postgres=# CLOSE cursor2 ; + +-- Set up a WITH HOLD cursor. +postgres=# DECLARE cursor1 CURSOR WITH HOLD FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; + +-- Fetch the first two rows in cursor1. +postgres=# FETCH FORWARD 2 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo + ( 2 rows ) + +-- Fetch the next row in cursor1. +postgres=# FETCH FORWARD 1 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 1 row ) + +-- Close the cursor. +postgres=# CLOSE cursor1 ; +
DEALLOCATE deallocates a previously prepared statement. If you do not explicitly deallocate a prepared statement, it is deallocated when the session ends.
+The PREPARE keyword is always ignored.
+DECLARE defines a cursor to retrieve a small number of rows at a time out of a larger query and can be the start of an anonymous block.
+This section describes usage of cursors. The usage of anonymous blocks is available in BEGIN.
+To process SQL statements, the stored procedure process assigns a memory segment to store context association. Cursors are handles or pointers pointing to context regions. With cursors, stored procedures can control alterations in context regions.
+Generally, CURSOR and SELECT both have text returns. Since data is stored in binary format in the system, the system needs to convert the data from the binary format to the text format. If data is returned in text format, client applications need to convert the data back to the binary format for processing. FETCH implements conversion between binary data and text data.
+DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. The result is a valid, but an empty table.
+-- Delete employees whose ca_address_sk is smaller than 14888 from the tpcds.customer_address_bak table. +postgres=# DELETE FROM tpcds.customer_address_bak WHERE ca_address_sk < 14888 ; + +-- Delete all data from the tpcds.customer_address_bak table. +postgres=# DELETE FROM tpcds.customer_address_bak ; +Delete the tpcds.customer_address_bak table. +postgres=# DROP TABLE tpcds.customer_address_bak ; +
DO executes an anonymous code block.
+The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.
+DROP DATABASE deletes a database.
+DROP DATABASE cannot be undone.
+-- Reset the enable_indexscan parameter. +postgres=# ALTER DATABASE music3 RESET enable_indexscan ;
DROP DATA SOURCE deletes a data source.
+-- Delete the data source. +postgres=# DROP DATA SOURCE ds_tst1 CASCADE ;
DROP Directory deletes a synonym.
+By default, only the initial user can perform the drop operation. When enable_access_server_directory (enable_access_server_directory), users with the sysadmin permission can also perform the drop operation.
+DROP FUNCTION deletes a function.
+If a function involves operations on temporary tables, DROP FUNCTION cannot be used.
+DROP GROUP deletes a user group.
+DROP GROUP is an alias for DROP ROLE.
+DROP GROUP is an internal interface of the openGauss management tool. You are not advised to use this interface, because doing so affects openGauss.
+DROP INDEX deletes an index.
+Only the owner of an index or a system administrator has the DROP INDEX permission.
+-- Delete an existing index. +postgres=# DROP INDEX tpcds.ds_ship_mode_t1_index2 ;
DROP OWNED deletes the database objects owned by a database role.
+DROP ROW LEVEL SECURITY POLICY deletes a row-level access control policy from a table.
+Only the owner of a table or a system administrator has the DROP ROW LEVEL SECURITY POLICY permission.
+-- Delete a row-level access control policy. +postgres=# DROP ROW LEVEL SECURITY POLICY all_data_rls ON all_data ;
DROP PROCEDURE deletes a stored procedure.
+DROP ROLE deletes a role.
+DROP SCHEMA deletes a schema from the current database.
+Only the owner of a schema or a system administrator has the DROP SCHEMA permission.
+-- Delete the schema. +postgres=# DROP SCHEMA role1 CASCADE ;
DROP SEQUENCE deletes a sequence from the current database.
+Only the owner of a schema or a system administrator has the DROP SEQUENCE permission.
+-- Delete a sequence. +postgres=# DROP SEQUENCE serial ;
DROP SYNONYM deletes a synonym.
+Only the owner of a synonym or a system administrator has the DROP SYNONYM permission.
+DROP TABLE deletes a table.
+DROP TABLE forcibly deletes the specified table and the indexes depending on the table. After the table is deleted, the functions and stored procedures that need to use this table cannot be executed. Deleting a partitioned table also deletes all partitions in the table.
+DROP TABLESPACE deletes a tablespace.
+-- Delete the tablespace. +postgres=# DROP TABLESPACE ds_location2 ;
DROP TEXT SEARCH CONFIGURATION deletes a text search configuration.
+Only the owner of a text search configuration has the DROP TEXT SEARCH CONFIGURATION permission.
+-- Delete the text search configuration. +postgres=# DROP TEXT SEARCH CONFIGURATION joe.ngram_2 ;
DROP TEXT SEARCH DICTIONARY deletes a full-text retrieval dictionary.
+-- Delete the english dictionary. +DROP TEXT SEARCH DICTIONARY english ;
DROP TRIGGER deletes a trigger.
+Only the owner of a trigger or a system administrator has the DROP TRIGGER permission.
+DROP TYPE deletes a user-defined data type. Only the owner of a type has the DROP TYPE permission.
+DROP USER deletes a user and the schema with the same name as the user.
+DROP VIEW forcibly deletes a view from the database.
+Only the owner of a view or a system administrator has the DROP VIEW permission.
+-- Delete the view. +postgres=# DROP VIEW myView ;
EXECUTE executes a prepared statement. Because a prepared statement exists only in the lifetime of the session, the prepared statement must be created earlier in the current session by using the PREPARE statement.
+If the PREPARE statement creating the prepared statement declares some parameters, the parameter set passed to the EXECUTE statement must be compatible. Otherwise, an error will occur.
+-- Create a prepared statement for an INSERT statement and execute the prepared statement. +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; +
EXPLAIN shows the execution plan of an SQL statement.
+The execution plan shows how the tables referenced by the statement will be scanned - by plain sequential scan, index scan, etc. - and if multiple tables are referenced, what join algorithms will be used to bring together the required rows from each input table.
+The most critical part of the display is the estimated statement execution cost, which is the planner's guess at how long it will take to run the statement.
+The ANALYZE option causes the statement to be actually executed, not only planned. The total elapsed time expended within each plan node (in milliseconds) and total number of rows it actually returned are added to the display. This is useful for seeing whether the planner's estimates are close to reality.
+The statement is actually executed when the ANALYZE option is used. If you wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE, CREATE TABLE AS, or EXECUTE statement without letting the statement affect your data, use this approach:
+START TRANSACTION; +EXPLAIN ANALYZE ...; +ROLLBACK;+
-- Change the value of explain_perf_mode to normal. +postgres=# SET explain_perf_mode=normal ; + +-- Display an execution plan for simple queries in the table. +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 ; +QUERY PLAN +-------------------------------------------------- +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) +Node/s: All dbnodes + ( 2 rows ) + +-- Generate an execution plan in JSON format ( with explain_perf_mode being normal ) . +postgres=# EXPLAIN ( FORMAT JSON ) SELECT * FROM tpcds.customer_address_p1 ; +QUERY PLAN +-------------------------------------- +[ + +{ + +"Plan": { + +"Node Type": "Data Node Scan" , + +"Startup Cost": 0.00 , + +"Total Cost": 0.00 , + +"Plan Rows": 0 , + +"Plan Width": 0 , + +"Node/s": "All dbnodes" + +} + +} + +] + ( 1 row ) + +-- If there is an index and we use a query with an indexable WHERE condition, EXPLAIN might show a different plan. +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +-------------------------------------------------- +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) +Node/s: dn_6005_6006 + ( 2 rows ) + +-- Generate an execution plan in YAML format ( with explain_perf_mode being normal ) . +postgres=# EXPLAIN ( FORMAT YAML ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +--------------------------------- +- Plan: + +Node Type: "Data Node Scan"+ +Startup Cost: 0.00 + +Total Cost: 0.00 + +Plan Rows: 0 + +Plan Width: 0 + +Node/s: "dn_6005_6006" + ( 1 row ) + +-- Here is an example of a query plan with cost estimates suppressed: +postgres=# EXPLAIN ( COSTS FALSE ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +------------------------ +Data Node Scan +Node/s: dn_6005_6006 + ( 2 rows ) + +-- Here is an example of a query plan for a query using an aggregate function: +postgres=# EXPLAIN SELECT SUM ( ca_address_sk ) FROM tpcds.customer_address_p1 WHERE ca_address_sk<10000 ; +QUERY PLAN +--------------------------------------------------------------------------------------- +Aggregate ( cost=18.19..14.32 rows=1 width=4 ) +-> Streaming ( type: GATHER ) ( cost=18.19..14.32 rows=3 width=4 ) +Node/s: All dbnodes +-> Aggregate ( cost=14.19..14.20 rows=3 width=4 ) +-> Seq Scan on customer_address_p1 ( cost=0.00..14.18 rows=10 width=4 ) +Filter: ( ca_address_sk < 10000 ) + ( 6 rows ) +
EXPLAIN PLAN saves information about an execution plan into the PLAN_TABLE table. Different from the EXPLAIN statement, EXPLAIN PLAN only saves plan information and does not print information on the screen.
+FETCH retrieves rows using a previously created cursor.
+A cursor has an associated position, which is used by FETCH. The cursor position can be before the first row of the query result, on any particular row of the result, or after the last row of the result.
+-- Fetch the first three rows in cursor1. +postgres=# FETCH FORWARD 3 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 3 rows ) + +-- Fetch the first two rows in cursor2. +postgres=# FETCH FORWARD 2 FROM cursor2 ; +column1 | column2 +---------+--------- +0 | 3 +1 | 2 + ( 2 rows ) + +-- Fetch the first two rows in cursor1. +postgres=# FETCH FORWARD 2 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo + ( 2 rows ) + +-- Fetch the next row in cursor1. +postgres=# FETCH FORWARD 1 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 1 row ) +
GRANT is used to grant permissions to roles and users.
+GRANT is used in the following scenarios:
+System permissions are also called user properties, including SYSADMIN, CREATEDB, CREATEROLE, AUDITADMIN, and LOGIN.
+They can be specified only by the CREATE ROLE or ALTER ROLE statement. The SYSADMIN permissions can be granted and revoked using GRANT ALL PRIVILEGE and REVOKE ALL PRIVILEGE, respectively. System permissions cannot be inherited by a user from a role, and cannot be granted using PUBLIC.
+Grant permissions related to database objects (tables, views, specified columns, databases, functions, schemas, and tablespaces) to specified roles or users.
+GRANT gives specific permissions on a database object to one or more roles. These permissions are added to those already granted, if any.
+The keyword PUBLIC indicates that the permissions are to be granted to all roles, including those that might be created later. PUBLIC can be thought of as an implicitly defined group that always includes all roles. Any particular role will have the sum of permissions granted directly to it, permissions granted to any role it is presently a member of, and permissions granted to PUBLIC.
+If WITH GRANT OPTION is specified, the recipient of the permission can in turn grant it to others. Without a grant option, the recipient cannot do that. GRANT options cannot be granted to PUBLIC. Only openGauss supports this operation.
+openGauss grants the permissions for objects of certain types to PUBLIC. By default, permissions on tables, columns, sequences, foreign data sources, foreign servers, schemas, and tablespaces are not granted to PUBLIC, but the following permissions are granted to PUBLIC: CONNECT and CREATE TEMP TABLE permissions on databases, EXECUTE permission on functions, and USAGE permission on languages and data types (including domains). An object owner can revoke the default permissions granted to PUBLIC and grant permissions to other users as needed. For security purposes, you are advised to create an object and set its permissions in the same transaction so that other users do not have time windows to use the object. In addition, you can run the ALTER DEFAULT PRIVILEGES statement to modify the default permissions.
+Grant a role's or user's permissions to one or more roles or users. In this case, every role or user can be regarded as a set of one or more database permissions.
+If WITH ADMIN OPTION is specified, the recipients can in turn grant the permissions to other roles or users or revoke the permissions they have granted to other roles or users. If recipients' permissions are changed or revoked later, the grantees' permissions will also change.
+Database administrators can grant or revoke permissions for any roles or users. Roles with the CREATEROLE permission can grant or revoke permissions for non-admin roles.
+postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT ALL PRIVILEGES TO joe ; +Afterward , user joe has the sysadmin permissions. +Example 2: Granting object permissions to a user or role +Revoke the sysadmin permission from the joe user. Grant the usage permission of the tpcds schema and all permissions on the tpcds.reason table to joe.postgres=# REVOKE ALL PRIVILEGES FROM joe ; +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; +Then joe has all permissions on the tpcds.reason table , including create , retrieve , update , and delete. +Grant the retrieve permission of r_reason_sk , r_reason_id , and r_reason_desc columns and the update permission of the r_reason_desc column in the tpcds.reason table to joe.postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; +Then joe has the retrieve permission of r_reason_sk and r_reason_id columns in the tpcds.reason table. To enable user joe to grant these permissions to other users , execute the following statement: +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; +Grant the postgres database connection permission and schema creation permission to user joe , and enable this user to grant these permissions to other users. +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; +Create role tpcds_manager , grant the tpcds schema access permission and object creation permission to this role , but do not enable this role to grant these permissions to others. +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; +Grant all the permissions on the tpcds_tbspc tablespace to user joe but do not enable this user to grant these permissions to others. +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; +Example 3: Granting the permissions of one user or role to others +Create role manager , grant user joe ' s permissions to the created role , and enable this role to grant its permissions to others.postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; +Create role senior_manager and grant manager ' s permissions to senior_manager.postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT manager TO senior_manager ; +Revoke permissions granted to senior_manager and manager and delete manager.postgres=# REVOKE manager FROM joe ; +postgres=# REVOKE senior_manager FROM manager ; +postgres=# DROP USER manager ; +Example 4: Revoking permissions and deleting roles and users +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; +postgres=# DROP TABLESPACE tpcds_tbspc ; +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; +postgres=# DROP ROLE tpcds_manager ; +postgres=# DROP ROLE senior_manager ; +postgres=# DROP USER joe CASCADE ; +
INSERT inserts new rows into a table.
+If inserting multi-byte character data (such as Chinese characters) to database with the character set byte encoding (SQL_ASCII, LATIN1), and the character data crosses the truncation position, the string is truncated based on its bytes instead of characters. Unexpected result will occur in tail after the truncation. If you want correct truncation result, you are advised to adopt encoding set such as UTF8, which has no character data crossing the truncation position.
+-- Insert a record into a table. +postgres=# INSERT INTO tpcds.reason_t2 ( r_reason_sk , r_reason_id , r_reason_desc ) VALUES ( 1 , ' AAAAAAAABAAAAAAA ' , ' reason1 ' ) ; + +-- Insert a record into the table, which is equivalent to the previous syntax. +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 2 , ' AAAAAAAABAAAAAAA ' , ' reason2 ' ) ; + +-- Insert multiple records into the table. +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 3 , ' AAAAAAAACAAAAAAA ' , ' reason3 ' ) , ( 4 , ' AAAAAAAADAAAAAAA ' , ' reason4 ' ) , ( 5 , ' AAAAAAAAEAAAAAAA ' , ' reason5 ' ) ; + +-- Insert records whose r_reason_sk in the tpcds.tpcds.reason table is less than 5. +postgres=# INSERT INTO tpcds.reason_t2 SELECT * FROM tpcds.reason WHERE r_reason_sk <5 ; + +-- Insert multiple records into the table. If the records conflict, update the r_reason_id field in the conflicting row to 'BBBBBBBBCAAAAAAA'. +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 5 , ' BBBBBBBBCAAAAAAA ' , ' reason5 ' ) , ( 6 , ' AAAAAAAADAAAAAAA ' , ' reason6 ' ) ON DUPLICATE KEY UPDATE r_reason_id = ' BBBBBBBBCAAAAAAA ' ; +
LOCK TABLE obtains a table-level lock.
+openGauss always tries to select the lock mode with minimum constraints when automatically requesting a lock for a statement referenced by a table. Use LOCK if users need a more strict lock mode. For example, suppose an application runs a transaction at the Read Committed isolation level and needs to ensure that data in a table remains stable in the duration of the transaction. To achieve this, you could obtain SHARE lock mode over the table before the query. This will prevent concurrent data changes and ensure subsequent reads of the table see a stable view of committed data. It is because the SHARE lock mode conflicts with the ROW EXCLUSIVE lock acquired by writers, and your LOCK TABLE name IN SHARE MODE statement will wait until any concurrent holders of ROW EXCLUSIVE mode locks commit or roll back. Therefore, once you obtain the lock, there are no uncommitted writes outstanding; furthermore none can begin until you release the lock.
+MOVE repositions a cursor without retrieving any data. MOVE works exactly like the FETCH statement, except it only repositions the cursor and does not return rows.
+-- Skip the first three rows of cursor1. +postgres=# MOVE FORWARD 3 FROM cursor1 ; +
MERGE INTO conditionally matches data in a target table with that in a source table. If data matches, UPDATE is executed on the target table; if data does not match, INSERT is executed. You can use this syntax to run UPDATE and INSERT at a time for convenience
+-- Run MERGE INTO. +postgres=# MERGE INTO products p +USING newproducts np +ON ( p.product_id = np.product_id ) +WHEN MATCHED THEN +UPDATE SET p.product_name = np.product_name , p.category = np.category WHERE p.product_name != ' play gym ' +WHEN NOT MATCHED THEN +INSERT VALUES ( np.product_id , np.product_name , np.category ) WHERE np.category = ' books ' ; +MERGE 4 +
PREPARE creates a prepared statement.
+A prepared statement is a performance optimizing object on the server. When the PREPARE statement is executed, the specified query is parsed, analyzed, and rewritten. When EXECUTE is executed, the prepared statement is planned and executed. This avoids repetitive parsing and analysis. After the PREPARE statement is created, it exists throughout the database session. Once it is created (even if in a transaction block), it will not be deleted when a transaction is rolled back. It can only be deleted by explicitly invoking DEALLOCATE or automatically deleted when the session ends.
+-- Create a prepared statement for an INSERT statement and execute the prepared statement. +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; +
PREPARE TRANSACTION prepares the current transaction for two-phase commit.
+After this statement, the transaction is no longer associated with the current session; instead, its state is fully stored on disk, and there is a high probability that it can be committed successfully, even if a database crash occurs before the commit is requested.
+Once prepared, a transaction can later be committed or rolled back with COMMIT PREPARED or ROLLBACK PREPARED, respectively. Those statements can be issued from any session, not only the one that executed the original transaction.
+From the point of view of the issuing session, PREPARE TRANSACTION is not unlike a ROLLBACK statement: after executing it, there is no active current transaction, and the effects of the prepared transaction are no longer visible. (The effects will become visible again if the transaction is committed.)
+If the PREPARE TRANSACTION statement fails for any reason, it becomes a ROLLBACK and the current transaction is canceled.
+REASSIGN OWNED changes the owner of the database object.
+REASSIGN OWNED requires that the system change owners of all the database objects owned by old_roles to new_role.
+REINDEX rebuilds an index using the data stored in the index's table, replacing the old copy of the index.
+There are several scenarios in which REINDEX can be used:
+An index build with the CONCURRENTLY option failed, leaving an "invalid" index.
+REINDEX DATABASE and REINDEX SYSTEM type cannot be performed in transaction blocks.
+-- Rebuild a single index. +postgres=# REINDEX INDEX tpcds.tpcds_customer_index1 ; + +-- Rebuild all indexes in the tpcds.customer_t1 table: +postgres=# REINDEX TABLE tpcds.customer_t1 ; +Delete the tpcds.customer_t1 table. +postgres=# DROP TABLE tpcds.customer_t1 ; +
RELEASE SAVEPOINT destroys a savepoint previously defined in the current transaction.
+Destroying a savepoint makes it unavailable as a rollback point, but it has no other user visible behavior. It does not undo the effects of statements executed after the savepoint was established. To do that, use ROLLBACK TO SAVEPOINT. Destroying a savepoint when it is no longer needed allows the system to reclaim some resources earlier than transaction end.
+RELEASE SAVEPOINT also destroys all savepoints that were established after the named savepoint was established.
+-- Delete the savepoint. +postgres=# RELEASE SAVEPOINT my_savepoint; +
RESET restores run-time parameters to their default values. The default values are parameter default values complied in the postgresql.conf configuration file.
+RESET is an alternative spelling for:
+SET configuration_parameter TO DEFAULT
+RESET and SET have the same transaction behavior. Their impact will be rolled back.
+-- Reset timezone to the default value. +postgres=# RESET timezone ; + +-- Set all parameters to their default values. +postgres=# RESET ALL ; +
REVOKE revokes permissions from one or more roles.
+If a non-owner user of an object attempts to REVOKE permission on the object, the statement is executed based on the following rules:
+postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT ALL PRIVILEGES TO joe ; +Afterward , user joe has the sysadmin permissions. +Example 2: Granting object permissions to a user or role +Revoke the sysadmin permission from the joe user. Grant the usage permission of the tpcds schema and all permissions on the tpcds.reason table to joe.postgres=# REVOKE ALL PRIVILEGES FROM joe ; +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; +Then joe has all permissions on the tpcds.reason table , including create , retrieve , update , and delete. +Grant the retrieve permission of r_reason_sk , r_reason_id , and r_reason_desc columns and the update permission of the r_reason_desc column in the tpcds.reason table to joe.postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; +Then joe has the retrieve permission of r_reason_sk and r_reason_id columns in the tpcds.reason table. To enable user joe to grant these permissions to other users , execute the following statement: +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; +Grant the postgres database connection permission and schema creation permission to user joe , and enable this user to grant these permissions to other users. +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; +Create role tpcds_manager , grant the tpcds schema access permission and object creation permission to this role , but do not enable this role to grant these permissions to others. +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; +Grant all the permissions on the tpcds_tbspc tablespace to user joe but do not enable this user to grant these permissions to others. +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; +Example 3: Granting the permissions of one user or role to others +Create role manager , grant user joe ' s permissions to the created role , and enable this role to grant its permissions to others.postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; +Create role senior_manager and grant manager ' s permissions to senior_manager.postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT manager TO senior_manager ; +Revoke permissions granted to senior_manager and manager and delete manager.postgres=# REVOKE manager FROM joe ; +postgres=# REVOKE senior_manager FROM manager ; +postgres=# DROP USER manager ; +Example 4: Revoking permissions and deleting roles and users +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; +postgres=# DROP TABLESPACE tpcds_tbspc ; +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; +postgres=# DROP ROLE tpcds_manager ; +postgres=# DROP ROLE senior_manager ; +postgres=# DROP USER joe CASCADE ; +
ROLLBACK rolls back the current transaction and backs out all updates in the transaction.
+ROLLBACK backs out of all changes that a transaction makes to a database if the transaction fails to be executed due to a fault.
+If a ROLLBACK statement is executed out of a transaction, no error occurs, but a notice is displayed.
+ROLLBACK PREPARED cancels a transaction ready for two-phase committing.
+ROLLBACK TO SAVEPOINT rolls back to a savepoint. It implicitly destroys all savepoints that were established after the named savepoint.
+Rolls back all statements that were executed after the savepoint was established. The savepoint remains valid and can be rolled back to again later, if needed.
+-- Undo the effects of the statements executed after my_savepoint was established: +postgres=# START TRANSACTION ; +postgres=# SAVEPOINT my_savepoint; +postgres=# ROLLBACK TO SAVEPOINT my_savepoint; + +-- Cursor positions are not affected by savepoint rollback. +postgres=# DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2 ; +postgres=# SAVEPOINT foo ; +postgres=# FETCH 1 FROM foo ; +?column? +---------- +1 +postgres=# ROLLBACK TO SAVEPOINT foo ; +postgres=# FETCH 1 FROM foo ; +?column? +---------- +2 +postgres=# RELEASE SAVEPOINT my_savepoint; +postgres=# COMMIT ; +
SAVEPOINT establishes a new savepoint within the current transaction.
+A savepoint is a special mark inside a transaction. It allows all statements executed following its establishment to be rolled back, restoring the transaction state to what it was at the time of the savepoint.
+-- Create a savepoint. +postgres=# SAVEPOINT my_savepoint; + +-- Roll back a savepoint. +postgres=# ROLLBACK TO SAVEPOINT my_savepoint; + +-- Create a savepoint. +postgres=# SAVEPOINT my_savepoint; + +-- Roll back a savepoint. +postgres=# RELEASE SAVEPOINT my_savepoint; +
SELECT retrieves data from a table or view.
+Serving as an overlaid filter for a database table, SELECT filters required data from the table using SQL keywords.
+-- Obtain the temp_t temporary table by a subquery and query all records in this table. +postgres=# WITH temp_t ( name , isdba ) AS ( SELECT usename , usesuper FROM pg_user ) SELECT * FROM temp_t; + +-- Query all r_reason_sk records in the tpcds.reason table and delete duplicate records. +postgres=# SELECT DISTINCT ( r_reason_sk ) FROM tpcds.reason ; + +-- Example of a LIMIT clause: Obtain a record from the table. +postgres=# SELECT * FROM tpcds.reason LIMIT 1 ; + +-- Query all records and sort them in alphabetic order. +postgres=# SELECT r_reason_desc FROM tpcds.reason ORDER BY r_reason_desc ; + +-- Use table aliases to obtain data from the pg_user and pg_user_status tables: +postgres=# SELECT a.usename , b.locktime FROM pg_user a , pg_user_status b WHERE a.usesysid=b.roloid ; + +-- Example of the FULL JOIN clause: Join data in the pg_user and pg_user_status tables. +postgres=# SELECT a.usename , b.locktime , a.usesuper FROM pg_user a FULL JOIN pg_user_status b on a.usesysid=b.roloid ; + +-- Example of the GROUP BY clause: Filter data based on query conditions, and group the results. +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY r_reason_id HAVING AVG ( r_reason_sk ) > 25 ; + +-- Example of the GROUP BY CUBE clause: Filter data based on query conditions, and group the results. +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk ) ; + +-- Example of the GROUP BY GROUPING SETS clause: Filter data based on query conditions, and group the results. +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_sk ) ; + +-- Example of the UNION clause: Merge the names started with W and N in the r_reason_desc column in the tpcds.reason table. +postgres=# SELECT r_reason_sk , tpcds.reason.r_reason_desc +FROM tpcds.reason +WHERE tpcds.reason.r_reason_desc LIKE ' W% ' +UNION +SELECT r_reason_sk , tpcds.reason.r_reason_desc +FROM tpcds.reason +WHERE tpcds.reason.r_reason_desc LIKE ' N% ' ; + +-- Example of the NLS_SORT clause: Sort by Chinese Pinyin. +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = SCHINESE_PINYIN_M ' ) ; + +-- Case-insensitive order: +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = generic_m_ci ' ) ; + +-- Example of the PARTITION clause: Obtain data from the P_05_BEFORE partition in the tpcds.reason_p table. +postgres=# SELECT * FROM tpcds.reason_p PARTITION ( P_05_BEFORE ) ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +4 | AAAAAAAABAAAAAAA | reason 3 +3 | AAAAAAAABAAAAAAA | reason 1 + ( 2 rows ) + +-- Example of the GROUP BY clause: Group records in the tpcds.reason_p table by r_reason_id, and count the number of records in each group. +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id ; +count | r_reason_id +-------+------------------ +2 | AAAAAAAACAAAAAAA +5 | AAAAAAAABAAAAAAA + ( 2 rows ) + +-- Example of the GROUP BY CUBE clause: Filter data based on query conditions, and group the results. +postgres=# SELECT * FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk , r_reason_desc ) ; + +-- Example of the GROUP BY GROUPING SETS clause: Filter data based on query conditions, and group the results. +postgres=# SELECT * FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_desc ) ; + +-- Example of the HAVING clause: Group records in the tpcds.reason_p table by r_reason_id, count the number of records in each group, and display only values whose number of r_reason_id is greater than 2. +postgres=# SELECT COUNT ( * ) c , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING c>2 ; +c | r_reason_id + +-- Example of the IN clause: Group records in the tpcds.reason_p table by r_reason_id, count the number of records in each group, and display only the numbers of records whose r_reason_id is AAAAAAAABAAAAAAA or AAAAAAAADAAAAAAA. +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING r_reason_id IN ( ' AAAAAAAABAAAAAAA ' , ' AAAAAAAADAAAAAAA ' ) ; +count | r_reason_id +-------+------------------ +5 | AAAAAAAABAAAAAAA + ( 1 row ) + +-- Example of the INTERSECT clause: Query records whose r_reason_id is AAAAAAAABAAAAAAA and whose r_reason_sk is smaller than 5. +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' INTERSECT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<5 ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +4 | AAAAAAAABAAAAAAA | reason 3 +3 | AAAAAAAABAAAAAAA | reason 1 + ( 2 rows ) + +-- Example of the EXCEPT clause: Query records whose r_reason_id is AAAAAAAABAAAAAAA and whose r_reason_sk is greater than or equal to 4. +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' EXCEPT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<4 ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +10 | AAAAAAAABAAAAAAA | reason 2 +10 | AAAAAAAABAAAAAAA | reason 5 +10 | AAAAAAAABAAAAAAA | reason 4 +4 | AAAAAAAABAAAAAAA | reason 3 + ( 4 rows ) + +-- Specify the operator ( + ) in the WHERE clause to indicate a left join. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) +order by 1 desc limit 1 ; +sr_item_sk | c_customer_id +------------+--------------- +18000 | + ( 1 row ) + +-- Specify the operator ( + ) in the WHERE clause to indicate a right join. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk +order by 1 desc limit 1 ; +sr_item_sk | c_customer_id +------------+------------------ +| AAAAAAAAJNGEBAAA + ( 1 row ) + +-- Specify the operator ( + ) in the WHERE clause to indicate a left join and add a join condition. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 order by 1 limit 1 ; +sr_item_sk | c_customer_id +------------+--------------- +1 | + ( 1 row ) + +-- If the operator ( + ) is specified in the WHERE clause, do not use expressions connected through AND/OR. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where not ( t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 ) ; +ERROR: Operator " ( + ) " can not be used in nesting expression. +LINE 1: ...tomer_id from store_returns t1 , customer t2 where not ( t1.sr_... +^ + +-- If the operator ( + ) is specified in the WHERE clause which does not support expression macros, an error will be reported. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where ( t1.sr_customer_sk = t2.c_customer_sk ( + ) ) ::bool ; +ERROR: Operator " ( + ) " can only be used in common expression. + +-- If the operator ( + ) is specified on both sides of an expression in the WHERE clause, an error will be reported. +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk ( + ) ; +ERROR: Operator " ( + ) " can ' t be specified on more than one relation in one join condition +HINT: "t1" , "t2"...are specified Operator " ( + ) " in one condition. +
SELECT INTO defines a new table based on a query result and inserts data obtained by query to the new table.
+Different from SELECT, data found by SELECT INTO is not returned to the client. The table columns have the same names and data types as the output columns of the SELECT.
+CREATE TABLE AS provides functions similar to SELECT INTO in functions and provides a superset of functions provided by SELECT INTO. You are advised to use CREATE TABLE AS, because SELECT INTO cannot be used in a stored procedure.
+-- Add the values that are less than 5 in the r_reason_sk field in the tpcds.reason table to the new table. +postgres=# SELECT * INTO tpcds.reason_t1 FROM tpcds.reason WHERE r_reason_sk < 5 ; +INSERT 0 6 +
SET modifies a run-time parameter.
+Most run-time parameters can be modified by executing SET. Some parameters cannot be modified after a server or session starts.
+-- Set the search path of a schema. +postgres=# SET search_path TO tpcds , public ; + +-- Set the date style to the traditional POSTGRES style ( date placed before month ) . +postgres=# SET datestyle TO postgres ; +
SET CONSTRAINTS sets the behavior of constraint checking within the current transaction.
+IMMEDIATE constraints are checked at the end of each statement. DEFERRED constraints are not checked until transaction commit. Each constraint has its own IMMEDIATE or DEFERRED mode.
+Upon creation, a constraint is given one of three characteristics DEFERRABLE INITIALLY DEFERRED, DEFERRABLE INITIALLY IMMEDIATE, or NOT DEFERRABLE. The third class is always IMMEDIATE and is not affected by the SET CONSTRAINTS statement. The first two classes start every transaction in specified modes, but its behaviors can be changed within a transaction by SET CONSTRAINTS.
+SET CONSTRAINTS with a list of constraint names changes the mode of just those constraints (which must all be deferrable). If multiple constraints match a name, the name is affected by all of these constraints. SET CONSTRAINTS ALL changes the modes of all deferrable constraints.
+When SET CONSTRAINTS changes the mode of a constraint from DEFERRED to IMMEDIATE, the new mode takes effect retroactively: any outstanding data modifications that would have been checked at the end of the transaction are instead checked during the execution of the SET CONSTRAINTS statement. If any such constraint is violated, the SET CONSTRAINTS fails (and does not change the constraint mode). Therefore, SET CONSTRAINTS can be used to force checking of constraints to occur at a specific point in a transaction.
+Check and unique constraints are always checked immediately when a row is inserted or modified.
+SET CONSTRAINTS sets the behavior of constraint checking only within the current transaction. Therefore, if you execute this statement outside of a transaction block (START TRANSACTION/COMMIT pair), it will not appear to have any effect.
+SET ROLE sets the current user identifier of the current session.
+-- Set the current user to paul. +postgres=# SET ROLE paul PASSWORD ' Bigdata@123 ' ; + +-- Reset the current user. +postgres=# RESET role ; +
SET SESSION AUTHORIZATION sets the session user identifier and the current user identifier of the current SQL session to a specified user.
+The session identifier can be changed only when the initial session user has the system administrator rights. Otherwise, the system supports the statement only when the authenticated user name is specified.
+-- Set the current user to paul. +postgres=# SET SESSION AUTHORIZATION paul password ' Bigdata@123 ' ; + +-- Reset the current user. +postgres=# RESET SESSION AUTHORIZATION ; +
SET TRANSACTION sets the characteristics of the current transaction. It has no effect on any subsequent transactions. Available transaction characteristics include the transaction isolation level and transaction access mode (read/write or read only).
+-- Start a transaction and set its isolation level to READ COMMITTED and access mode to READ ONLY. +postgres=# START TRANSACTION ; +postgres=# SET LOCAL TRANSACTION ISOLATION LEVEL READ COMMITTED READ ONLY ; +postgres=# COMMIT ; +
SHOW shows the current value of a run-time parameter.
+-- Show the value of timezone. +postgres=# SHOW timezone ; + +-- Show all parameters. +postgres=# SHOW ALL ; +
START TRANSACTION starts a transaction. If the isolation level or read/write mode is specified, a new transaction will have those characteristics. You can also specify them using SET TRANSACTION.
+-- Start a transaction in default mode. +postgres=# START TRANSACTION ; +postgres=# SELECT * FROM tpcds.reason ; +postgres=# END ; + +-- Start a transaction with the isolation level being READ COMMITTED and the access mode being READ WRITE: +postgres=# START TRANSACTION ISOLATION LEVEL READ COMMITTED READ WRITE ; +postgres=# SELECT * FROM tpcds.reason ; +postgres=# COMMIT ; +
TRUNCATE quickly removes all rows from a database table.
+It has the same effect as an unqualified DELETE on each table, but it is faster since it does not actually scan the tables. This is most useful on large tables.
+UPDATE updates data in a table. UPDATE changes the values of the specified columns in all rows that satisfy the condition. The WHERE clause clarifies conditions. The columns to be modified need to be mentioned in the SET clause; columns not explicitly modified retain their previous values.
+-- Update the values of all records. +postgres=# UPDATE student1 SET classno = classno*2 ; +
修改数据库的属性,包括它的名称、所有者、连接数限制、对象隔离属性等。
+--设置music数据库的连接数为10。 +postgres=# ALTER DATABASE music CONNECTION LIMIT= 10 ; + +--将music名称改为music4。 +postgres=# ALTER DATABASE music RENAME TO music4 ; + +--将数据库music2的所属者改为tom。 +postgres=# ALTER DATABASE music2 OWNER TO tom ; + +--设置music3的表空间为PG_DEFAULT。 +postgres=# ALTER DATABASE music3 SET TABLESPACE PG_DEFAULT ; + +--关闭在数据库music3上缺省的索引扫描。 +postgres=# ALTER DATABASE music3 SET enable_indexscan TO off ; + +--重置enable_indexscan参数。 +postgres=# ALTER DATABASE music3 RESET enable_indexscan ; +
修改Data Source对象的属性和内容。
+属性有:名称和属主;内容有:类型、版本和连接选项。
+--修改名称。 +postgres=# ALTER DATA SOURCE ds_test1 RENAME TO ds_test; + +--修改属主。 +postgres=# CREATE USER user_test1 IDENTIFIED BY ' Gs@123456 ' ; +postgres=# ALTER USER user_test1 WITH SYSADMIN ; +postgres=# ALTER DATA SOURCE ds_test OWNER TO user_test1 ; + +--修改TYPE和VERSION。 +postgres=# ALTER DATA SOURCE ds_test TYPE ' MPPDB_TYPE ' VERSION ' XXX ' ; + +--添加字段。 +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( add dsn ' gaussdb ' , username ' test_user ' ) ; + +--修改字段。 +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( set dsn ' unknown ' ) ; + +--删除字段。 +postgres=# ALTER DATA SOURCE ds_test OPTIONS ( drop username ) ; +
设置应用于将来创建的对象的权限(这不会影响分配到已有对象中的权限)。
+目前只支持表(包括视图)、 函数和类型(包括域)的权限更改。
+--将创建在模式tpcds里的所有表(和视图)的SELECT权限授予每一个用户。 +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT SELECT ON TABLES TO PUBLIC ; + +--将tpcds下的所有表的插入权限授予用户jack。 +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds GRANT INSERT ON TABLES TO jack ; + +--撤销上述权限。 +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE SELECT ON TABLES FROM PUBLIC ; +postgres=# ALTER DEFAULT PRIVILEGES IN SCHEMA tpcds REVOKE INSERT ON TABLES FROM jack ; +
对directory属性进行修改。
+--修改目录的owner。 +postgres=# ALTER DIRECTORY dir OWNER TO system ; +
修改自定义函数的属性。
+只有该函数的所有者,才有权限执行该命令,系统管理员默认拥有该权限。如果函数中涉及对临时表相关的操作,则无法使用ALTER FUNCTION。
+--修改函数add的执行规则为IMMUTABLE,即参数不变时返回相同结果。 +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) IMMUTABLE ; + +--将函数add的名称修改为add_two_number。 +postgres=# ALTER FUNCTION func_add_sql2 ( INTEGER , INTEGER ) RENAME TO add_two_number ; + +--将函数add的属者改为omm。 +postgres=# ALTER FUNCTION add_two_number ( INTEGER , INTEGER ) OWNER TO omm ; +
修改一个用户组的属性。
+ALTER GROUP是ALTER ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用ALTER ROLE替代。
+--向用户组中添加用户。 +postgres=# ALTER GROUP super_users ADD USER lche , jim ; + +--从用户组中删除用户。 +postgres=# ALTER GROUP super_users DROP USER jim ; + +--修改用户组的名称。 +postgres=# ALTER GROUP super_users RENAME TO normal_users ; +
ALTER INDEX用于修改现有索引的定义。
+它有几种子形式:
+如果指定的索引不存在,则发出一个notice而不是error。
+只改变索引的名称。对存储的数据没有影响。
+这个选项会改变索引的表空间为指定表空间,并且把索引相关的数据文件移动到新的表空间里。
+改变索引的一个或多个索引方法特定的存储参数。 需要注意的是索引内容不会被这个命令立即修改,根据参数的不同,可能需要使用REINDEX重建索引来获得期望的效果。
+重置索引的一个或多个索引方法特定的存储参数为缺省值。与SET一样,可能需要使用REINDEX来完全更新索引。
+用于设置表或者索引分区上的索引不可用。
+用于重建表或者索引分区上的索引。
+用于重命名索引分区
+用于修改索引分区的所属表空间。
+只有索引的所有者有权限执行此命令,系统管理员默认拥有此权限。
+--重命名一个现有的索引。 +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index1 RENAME TO ds_ship_mode_t1_index5 ; + +--设置索引不可用。 +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 UNUSABLE ; + +--重建索引。 +postgres=# ALTER INDEX tpcds.ds_ship_mode_t1_index2 REBUILD ; + +--修改分区表索引CA_ADDRESS_SK_index2的表空间为example1。 +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index2 TABLESPACE example1 ; + +--修改分区表索引CA_ADDRESS_SK_index3的表空间为example2。 +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 MOVE PARTITION CA_ADDRESS_SK_index3 TABLESPACE example2 ; + +--重命名分区表索引。 +postgres=# ALTER INDEX tpcds.ds_customer_address_p1_index2 RENAME PARTITION CA_ADDRESS_SK_index1 TO CA_ADDRESS_SK_index4 ; +
ALTER LARGE OBJECT用于更改一个large object的定义。它的唯一的功能是分配一个新的所有者。
+使用ALTER LARGE OBJECT必须是系统管理员或者是其所有者。
+修改角色属性。
+--修改角色manager的密码为abcd@123。 +postgres=# ALTER ROLE manager IDENTIFIED BY ' abcd@123 ' REPLACE ' Bigdata@123 ' ; + +--修改角色manager为系统管理员。 +postgres=# ALTER ROLE manager SYSADMIN ; +
对已存在的行访问控制策略(包括行访问控制策略的名称,行访问控制指定的用户,行访问控制的策略表达式)进行修改。
+表的所有者或管理员用户才能进行此操作。
+--修改行访问控制all_data_rls的名称 +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_rls ON all_data RENAME TO all_data_new_rls ; + +--修改行访问控制策略影响的用户 +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data TO alice , bob ; +postgres=# \d+ all_data +Table "public.all_data" +Column | Type | Modifiers | Storage | Stats target | Description +--------+------------------------+-----------+----------+--------------+------------- +id | integer | | plain | | +role | character varying ( 100 ) | | extended | | +data | character varying ( 100 ) | | extended | | +Row Level Security Policies: +POLICY "all_data_new_rls" +TO alice , bob +USING ( ( ( role ) ::name = "current_user" ( ) ) ) +Has OIDs: no +Location Nodes: ALL DATANODES +Options: orientation=row , compression=no , enable_rowsecurity=true + +--修改行访问控制策略表达式 +postgres=# ALTER ROW LEVEL SECURITY POLICY all_data_new_rls ON all_data USING ( id > 100 AND role = current_user ) ; +postgres=# \d+ all_data +Table "public.all_data" +Column | Type | Modifiers | Storage | Stats target | Description +--------+------------------------+-----------+----------+--------------+------------- +id | integer | | plain | | +role | character varying ( 100 ) | | extended | | +data | character varying ( 100 ) | | extended | | +Row Level Security Policies: +POLICY "all_data_new_rls" +TO alice , bob +USING ( ( ( id > 100 ) AND ( ( role ) ::name = "current_user" ( ) ) ) ) +Has OIDs: no +Location Nodes: ALL DATANODES +Options: orientation=row , compression=no , enable_rowsecurity=true +
修改模式属性。
+只有模式的所有者有权限执行ALTER SCHEMA命令,系统管理员默认拥有此权限。
+--将当前模式ds更名为ds_new。 +postgres=# ALTER SCHEMA ds RENAME TO ds_new ; + +--将DS_NEW的所有者修改为jack。 +postgres=# ALTER SCHEMA ds_new OWNER TO jack ; +
修改一个现有的序列的参数。
+--将序列serial的归属列变为T1.C1。 +postgres=# ALTER SEQUENCE serial OWNED BY T1.C1 ; +
ALTER SESSION命令用于定义或修改那些对当前会话有影响的条件或参数。修改后的会话参数会一直保持,直到断开当前会话。
+--设置当前会话的字符编码为UTF8。 +postgres=# ALTER SESSION SET NAMES ' UTF8 ' ; + +--设置当前模式。 +postgres=# ALTER SESSION SET CURRENT_SCHEMA TO tpcds ; + +--设置XML OPTION为DOCUMENT。 +postgres=# ALTER SESSION SET XML OPTION DOCUMENT ; + +--创建角色joe,并设置会话的角色为joe。 +postgres=# CREATE ROLE joe WITH PASSWORD ' Bigdata@123 ' ; +postgres=# ALTER SESSION SET SESSION AUTHORIZATION joe PASSWORD ' Bigdata@123 ' ; + +--切换到默认用户。 +postgres=> ALTER SESSION SET SESSION AUTHORIZATION default; +
修改SYNONYM对象的属性。
+--修改同义词t1的owner为u1。 +postgres=# ALTER SYNONYM t1 OWNER TO u1 ; +
ALTER SYSTEM KILL SESSION命令用于结束一个会话。
+--结束SID为140131075880720的会话。 +postgres=# ALTER SYSTEM KILL SESSION ' 140131075880720 , 0 ' IMMEDIATE ; +
修改表,包括修改表的定义、重命名表、重命名表中指定的列、重命名表的约束、设置表的所属模式、添加/更新多个列、打开/关闭行访问控制开关。
+--向tpcds.warehouse_t19表中增加一个varchar列。 +postgres=# ALTER TABLE tpcds.warehouse_t19 ADD W_GOODS_CATEGORY varchar ( 30 ) ; + +--给tpcds.warehouse_t19表增加一个检查约束。 +postgres=# ALTER TABLE tpcds.warehouse_t19 ADD CONSTRAINT W_CONSTR_KEY4 CHECK ( W_STATE IS NOT NULL ) ; + +--在一个操作中改变两个现存字段的类型。 +postgres=# ALTER TABLE tpcds.warehouse_t19 +ALTER COLUMN W_GOODS_CATEGORY TYPE varchar ( 80 ) , +ALTER COLUMN W_STREET_NAME TYPE varchar ( 100 ) ; + +--此语句与上面语句等效。 +postgres=# ALTER TABLE tpcds.warehouse_t19 MODIFY ( W_GOODS_CATEGORY varchar ( 30 ) , W_STREET_NAME varchar ( 60 ) ) ; + +--给一个已存在字段添加非空约束。 +postgres=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY SET NOT NULL ; + +--移除已存在字段的非空约束。 +postgres=# ALTER TABLE tpcds.warehouse_t19 ALTER COLUMN W_GOODS_CATEGORY DROP NOT NULL ; + +--如果列存表中还未指定局部聚簇,向在一个列存表中添加局部聚簇列。 +postgres=# ALTER TABLE tpcds.warehouse_t17 ADD PARTIAL CLUSTER KEY ( W_WAREHOUSE_SK ) ; + +--查看约束的名称,并删除一个列存表中的局部聚簇列。 +postgres=# \d+ tpcds.warehouse_t17 +Table "tpcds.warehouse_t17" +Column | Type | Modifiers | Storage | Stats target | Description +-------------------+-----------------------+-----------+----------+--------------+------------- +w_warehouse_sk | integer | not null | plain | | +w_warehouse_id | character ( 16 ) | not null | extended | | +w_warehouse_name | character varying ( 20 ) | | extended | | +w_warehouse_sq_ft | integer | | plain | | +w_street_number | character ( 10 ) | | extended | | +w_street_name | character varying ( 60 ) | | extended | | +w_street_type | character ( 15 ) | | extended | | +w_suite_number | character ( 10 ) | | extended | | +w_city | character varying ( 60 ) | | extended | | +w_county | character varying ( 30 ) | | extended | | +w_state | character ( 2 ) | | extended | | +w_zip | character ( 10 ) | | extended | | +w_country | character varying ( 20 ) | | extended | | +w_gmt_offset | numeric ( 5 , 2 ) | | main | | +Partial Cluster : +"warehouse_t17_cluster" PARTIAL CLUSTER KEY ( w_warehouse_sk ) +Has OIDs: no +Location Nodes: ALL DATANODES +Options: compression=no , version=0.12 +postgres=# ALTER TABLE tpcds.warehouse_t17 DROP CONSTRAINT warehouse_t17_cluster ; + +--将表移动到另一个表空间。 +postgres=# ALTER TABLE tpcds.warehouse_t19 SET TABLESPACE PG_DEFAULT ; + +--将表移动到另一个模式中。 +postgres=# ALTER TABLE tpcds.warehouse_t19 SET SCHEMA joe ; + +--重命名已存在的表。 +postgres=# ALTER TABLE joe.warehouse_t19 RENAME TO warehouse_t23 ; + +--从warehouse_t23表中删除一个字段。 +postgres=# ALTER TABLE joe.warehouse_t23 DROP COLUMN W_STREET_NAME ; +
修改表分区,包括增删分区、切割分区、合成分区,以及修改分区属性等。
+--删除分区P8。 +postgres=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION P8 ; + +--增加分区WR_RETURNED_DATE_SK介于2453005和2453105之间。 +postgres=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P8 VALUES LESS THAN ( 2453105 ) ; + +--增加分区WR_RETURNED_DATE_SK介于2453105和MAXVALUE之间。 +postgres=# ALTER TABLE tpcds.web_returns_p1 ADD PARTITION P9 VALUES LESS THAN ( MAXVALUE ) ; + +--删除分区P8。 +postgres=# ALTER TABLE tpcds.web_returns_p1 DROP PARTITION FOR ( 2453005 ) ; + +--分区P7重命名为P10。 +postgres=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION P7 TO P10 ; + +--分区P6重命名为P11。 +postgres=# ALTER TABLE tpcds.web_returns_p1 RENAME PARTITION FOR ( 2452639 ) TO P11 ; + +--修改分区P1的表空间为example2。 +postgres=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P1 TABLESPACE example2 ; + +--修改分区P2的表空间为example3。 +postgres=# ALTER TABLE tpcds.web_returns_p2 MOVE PARTITION P2 TABLESPACE example3 ; + +--以2453010为分割点切分P8。 +postgres=# ALTER TABLE tpcds.web_returns_p2 SPLIT PARTITION P8 AT ( 2453010 ) INTO + ( +PARTITION P9 , +PARTITION P10 + ) ; + +--将P6,P7合并为一个分区。 +postgres=# ALTER TABLE tpcds.web_returns_p2 MERGE PARTITIONS P6 , P7 INTO PARTITION P8 ; +
修改表空间的属性。
+如果new_owner与old_owner一致,此处不再校验当前执行操作的用户是否具有修改权限,而直接显示ALTER成功。
+--把表空间ds_location1重命名为ds_location3。 +postgres=# ALTER TABLESPACE ds_location1 RENAME TO ds_location3 ; + +--改变表空间ds_location2的所有者。 +postgres=# ALTER TABLESPACE ds_location2 OWNER TO jay ; +
更改文本搜索配置的定义。用户可以将映射从字串类型调整为字典,或者改变配置的名称或者所有者,或者修改搜索配置的配置参数。
+ADD MAPPING FOR选项为文本搜索配置增加字串类型映射;如果ADD MAPPING FOR后面任何一个字串类型的映射已经存在于此文本搜索配置中,那么系统将会报错。
+ALTER MAPPING FOR选项会首先清除已有的字串类型映射,然后添加指定的字串类型映射。
+ALTER MAPPING REPLACE ... WITH ... 与ALTER MAPPING FOR ... REPLACE ... WITH ...选项会直接使用new_dictionary替换old_dictionary。需要注意的是,只有pg_ts_config_map系统表中存在maptokentype与old_dictionary对应关系的元组时,才能更新成功,否则不会成功,也不会有任何提示信息返回。
+DROP MAPPING FOR选项会删除当前文本搜索配置中指定的字串类型映射。 如果没有指定IF EXISTS选项,当DROP MAPPING FOR选项指定的字串类型映射在文本搜索配置中不存在时,数据库会报错。
+--增加文本搜索配置字串类型映射语法。 +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR word WITH simple , english_stem ; +ALTER TEXT SEARCH CONFIGURATION + +--增加文本搜索配置字串类型映射语法。 +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ADD MAPPING FOR email WITH english_stem , french_stem ; +ALTER TEXT SEARCH CONFIGURATION + +--增加文本搜索配置字串类型映射语法。 +postgres=# ALTER TEXT SEARCH CONFIGURATION english_1 ALTER MAPPING REPLACE french_stem with german_stem ; +ALTER TEXT SEARCH CONFIGURATION +
修改全文检索词典的相关定义,包括参数、名称、所有者、以及模式等。
+--更改Snowball类型字典的停用词定义,其他参数保持不变。 +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( StopWords = newrussian , FilePath = ' file:///home/dicts ' ) ; + +--更改Snowball类型字典的Language参数,并删除停用词定义。 +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( Language = dutch, StopWords ) ; + +--更新词典定义,不实际更改任何内容。 +postgres=# ALTER TEXT SEARCH DICTIONARY my_dict ( dummy ) ; +
修改触发器定义。
+只有触发器所在表的所有者可以执行ALTER TRIGGER操作,系统管理员默认拥有此权限。
+--修改触发器 +postgres=# ALTER TRIGGER delete_trigger ON test_trigger_src_tbl RENAME TO delete_trigger_renamed ; + +--禁用insert_trigger触发器 +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER insert_trigger ; + +--禁用当前表上所有触发器 +postgres=# ALTER TABLE test_trigger_src_tbl DISABLE TRIGGER ALL ; +
修改一个类型的定义。
+--重命名数据类型。 +postgres=# ALTER TYPE compfoo RENAME TO compfoo1 ; + +--要改变一个用户定义类型compfoo1的所有者为usr1。 +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; + +--把用户定义类型compfoo1的模式改变为usr1。 +postgres=# ALTER TYPE compfoo1 SET SCHEMA usr1 ; + +--给一个数据类型增加一个新的属性。 +postgres=# ALTER TYPE usr1.compfoo1 ADD ATTRIBUTE f3 int; + +--添加一个标签值。 +postgres=# ALTER TYPE bugstatus ADD VALUE IF NOT EXISTS ' regress ' BEFORE ' closed ' ; + +--重命名一个标签值。 +postgres=# ALTER TYPE bugstatus RENAME VALUE ' create ' TO ' new ' ; +
修改数据库用户的属性。
+ALTER USER中修改的会话参数只针对指定的用户,且在下一次会话中有效。
+--将用户jim的登录密码由Bigdata@123修改为Abcd@123。 +postgres=# ALTER USER jim IDENTIFIED BY ' Abcd@123 ' REPLACE ' Bigdata@123 ' ; + +--为用户jim追加CREATEROLE权限。 +postgres=# ALTER USER jim CREATEROLE ; + +--将enable_seqscan的值设置为on, 设置成功后,在下一会话中生效。 +postgres=# ALTER USER jim SET enable_seqscan TO on ; + +--重置jim的enable_seqscan参数。 +postgres=# ALTER USER jim RESET enable_seqscan ; + +--锁定jim帐户。 +postgres=# ALTER USER jim ACCOUNT LOCK ; +
ALTER VIEW更改视图的各种辅助属性。(如果用户是更改视图的查询定义,要使用CREATE OR REPLACE VIEW。)
+--修改视图名称。 +postgres=# ALTER VIEW tpcds.customer_details_view_v1 RENAME TO customer_details_view_v2 ; + +--修改视图所属schema。 +postgres=# ALTER VIEW tpcds.customer_details_view_v2 SET schema public ; +
用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。
+如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table_name、column和partition_name参数把分析限定在特定的表、列或分区表中。
+ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。
+ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。
+ANALYZE VERIFY 操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。
+postgres=# CREATE TABLE customer_info + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) + ; + +-- 创建分区表。 +postgres=# CREATE TABLE customer_par + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2452275 ) , +PARTITION P2 VALUES LESS THAN ( 2452640 ) , +PARTITION P3 VALUES LESS THAN ( 2453000 ) , +PARTITION P4 VALUES LESS THAN ( MAXVALUE ) + ) +ENABLE ROW MOVEMENT ; + +-- 使用ANALYZE语句更新统计信息。 +postgres=# ANALYZE customer ; + +-- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。 +postgres=# ANALYZE VERBOSE customer_info ; +INFO: analyzing "cstore.pg_delta_3394584009" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" inheritance tree ( cn_5002 pid=53078 ) +ANALYZE +若环境若有故障,需查看数据库主节点的log。 + +-- 删除表。 +postgres=# DROP TABLE customer ; +postgres=# DROP TABLE customer_par ; +
用于收集与数据库中普通表内容相关的统计信息,统计结果存储在系统表PG_STATISTIC下。执行计划生成器会使用这些统计数据,以确定最有效的执行计划。
+如果没有指定参数,ANALYZE会分析当前数据库中的每个表和分区表。同时也可以通过指定table_name、column和partition_name参数把分析限定在特定的表、列或分区表中。
+ANALYZE|ANALYSE VERIFY用于检测数据库中普通表(行存表、列存表)的数据文件是否损坏。
+ANALYZE非临时表不能在一个匿名块、事务块、函数或存储过程内被执行。支持存储过程中ANALYZE临时表,不支持统计信息回滚操作。
+ANALYZE VERIFY 操作处理的大多为异常场景检测需要使用RELEASE版本。ANALYZE VERIFY 场景不触发远程读,因此远程读参数不生效。对于关键系统表出现错误被系统检测出页面损坏时,将直接报错不再继续检测。
+postgres=# CREATE TABLE customer_info + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) + ; + +-- 创建分区表。 +postgres=# CREATE TABLE customer_par + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER + ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2452275 ) , +PARTITION P2 VALUES LESS THAN ( 2452640 ) , +PARTITION P3 VALUES LESS THAN ( 2453000 ) , +PARTITION P4 VALUES LESS THAN ( MAXVALUE ) + ) +ENABLE ROW MOVEMENT ; + +-- 使用ANALYZE语句更新统计信息。 +postgres=# ANALYZE customer ; + +-- 使用ANALYZE VERBOSE语句更新统计信息,并输出表的相关信息。 +postgres=# ANALYZE VERBOSE customer_info ; +INFO: analyzing "cstore.pg_delta_3394584009" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" ( cn_5002 pid=53078 ) +INFO: analyzing "public.customer_info" inheritance tree ( cn_5002 pid=53078 ) +ANALYZE +若环境若有故障,需查看数据库主节点的log。 + +-- 删除表。 +postgres=# DROP TABLE customer ; +postgres=# DROP TABLE customer_par ; +
BEGIN可以用于开始一个匿名块,也可以用于开始一个事务。本节描述用BEGIN开始匿名块的语法,以BEGIN开始事务的语法见START TRANSACTION。
+匿名块是能够动态地创建和执行过程代码的结构,而不需要以持久化的方式将代码作为数据库对象储存在数据库中。
+使用CALL命令可以调用已定义的函数和存储过程。
+--按参数值传递。 +postgres=# CALL func_add_sql ( 1 , 3 ) ; + +--使用命名标记法传参。 +postgres=# CALL func_add_sql ( num1 => 1 , num2 => 3 ) ; +postgres=# CALL func_add_sql ( num2 := 2 , num1 := 3 ) ; + +--出参传入常量。 +postgres=# CALL func_increment_sql ( 1 , 2 , 1 ) ; + +--函数调用。 +postgres=# call package_func_overload ( 1 , ' test ' ) ; +postgres=# call package_func_overload ( 1 , 1 ) ; +
检查点(CHECKPOINT)是一个事务日志中的点,所有数据文件都在该点被更新以反映日志中的信息,所有数据文件都将被刷新到磁盘。
+设置事务日志检查点。预写式日志(WAL)缺省时在事务日志中每隔一段时间放置一个检查点。可以使用gs_guc命令设置相关运行时参数(checkpoint_segments和checkpoint_timeout)来调整这个原子化检查点的间隔。
+--设置检查点。 +postgres=# CHECKPOINT ; +
CLOSE释放和一个游标关联的所有资源。
+--关闭游标并提交事务。 +postgres=# CLOSE cursor1 ; + +--关闭游标并提交事务。 +postgres=# CLOSE cursor2 ; + +--关闭游标。 +postgres=# CLOSE cursor1 ; +
根据一个索引对表进行聚簇排序。
+CLUSTER指定openGauss通过索引名指定的索引聚簇由表名指定的表。 表名上必须已经定义该索引。
+当对一个表聚集后,该表将基于索引信息进行物理存储。聚集是一次性操作:当表被更新之后, 更改的内容不会被聚集。也就是说,系统不会试图按照索引顺序对新的存储内容及更新记录进行重新聚集。
+在对一个表聚簇之后,openGauss会记录在哪个索引上建立了聚集。 CLUSTER table_name的聚集形式在之前的同一个索引的表上重新聚集。用户也可以用ALTER TABLE的CLUSTER或SET WITHOUT CLUSTER形式来设置索引来用于后续的聚集操作或清除任何之前的设置。
+不含参数的CLUSTER会将当前用户所拥有的数据库中的先前做过聚簇的所有表重新处理,或者系统管理员调用的这些表。
+在对一个表进行聚簇的时候,会在其上请求一个ACCESS EXCLUSIVE锁。这样就避免了在CLUSTER完成之前对此表执行其它的操作(包括读写)。
+只有行存B-tree索引支持CLUSTER操作。
+如果用户只是随机访问表中的行,那么表中数据的实际存储顺序是无关紧要的。但是, 如果对某些数据的访问多于其它数据,而且有一个索引将这些数据分组, 那么将使用CLUSTER中会有所帮助。如果从一个表中请求一定索引范围的值, 或者是一个索引值对应多行,CLUSTER也会有助于应用,因为如果索引标识出第一匹配行所在的存储页,所有其它行也可能已经在同一个存储页里了,这样便节省了磁盘访问的时间,加速了查询。
+在聚簇过程中,系统先创建一个按照索引顺序建立的表的临时拷贝。同时也建立表上的每个索引的临时拷贝。因此,需要磁盘上有足够的剩余空间, 至少是表大小和索引大小的和。
+因为CLUSTER记忆聚集信息,可以在第一次的时候手工对表进行聚簇,然后设置一个类似VACUUM的时间,这样就可以周期地自动对表进行聚簇操作。
+因为优化器记录着有关表的排序的统计,所以建议在新近聚簇的表上运行ANALYZE。否则,优化器可能会选择很差劲的查询规划。
+CLUSTER不允许在事务中执行。
+-- 对表tpcds.inventory_p1进行聚集。 +postgres=# CLUSTER tpcds.inventory_p1 USING ds_inventory_p1_index1 ; + +-- 对分区p3进行聚集。 +postgres=# CLUSTER tpcds.inventory_p1 PARTITION ( p3 ) USING ds_inventory_p1_index1 ; + +-- 对数据库中可以进行聚集的表进聚集。 +postgres=# CLUSTER ; +
定义或修改一个对象的注释。
+-- 为tpcds.customer_demographics_t2.cd_demo_sk列加注释。 +postgres=# COMMENT ON COLUMN tpcds.customer_demographics_t2.cd_demo_sk IS ' Primary key of customer demographics table. ' ; + +-- 为tpcds.customer_details_view_v2视图加注释。 +postgres=# COMMENT ON VIEW tpcds.customer_details_view_v2 IS ' View of customer detail ' ; +
通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。
+执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作可以不在同一个会话中。
+--创建表。 +postgres=# CREATE TABLE tpcds.customer_demographics_t2 + ( +CD_DEMO_SK INTEGER NOT NULL , +CD_GENDER CHAR ( 1 ) , +CD_MARITAL_STATUS CHAR ( 1 ) , +CD_EDUCATION_STATUS CHAR ( 20 ) , +CD_PURCHASE_ESTIMATE INTEGER , +CD_CREDIT_RATING CHAR ( 10 ) , +CD_DEP_COUNT INTEGER , +CD_DEP_EMPLOYED_COUNT INTEGER , +CD_DEP_COLLEGE_COUNT INTEGER + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) + ; + +--开启事务。 +postgres=# START TRANSACTION ; + +--插入数据。 +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; + +--提交事务,让所有更改永久化。 +postgres=# COMMIT ; + +--查询数据。 +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; + +--删除表tpcds.customer_demographics_t2。 +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; +
通过COMMIT或者END可完成提交事务的功能,即提交事务的所有操作。
+执行COMMIT这个命令的时候,命令执行者必须是该事务的创建者或系统管理员,且创建和提交操作可以不在同一个会话中。
+--创建表。 +postgres=# CREATE TABLE tpcds.customer_demographics_t2 + ( +CD_DEMO_SK INTEGER NOT NULL , +CD_GENDER CHAR ( 1 ) , +CD_MARITAL_STATUS CHAR ( 1 ) , +CD_EDUCATION_STATUS CHAR ( 20 ) , +CD_PURCHASE_ESTIMATE INTEGER , +CD_CREDIT_RATING CHAR ( 10 ) , +CD_DEP_COUNT INTEGER , +CD_DEP_EMPLOYED_COUNT INTEGER , +CD_DEP_COLLEGE_COUNT INTEGER + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) + ; + +--开启事务。 +postgres=# START TRANSACTION ; + +--插入数据。 +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 1 , ' M ' , ' U ' , ' DOCTOR DEGREE ' , 1200 , ' GOOD ' , 1 , 0 , 0 ) ; +postgres=# INSERT INTO tpcds.customer_demographics_t2 VALUES ( 2 , ' F ' , ' U ' , ' MASTER DEGREE ' , 300 , ' BAD ' , 1 , 0 , 0 ) ; + +--提交事务,让所有更改永久化。 +postgres=# COMMIT ; + +--查询数据。 +postgres=# SELECT * FROM tpcds.customer_demographics_t2 ; + +--删除表tpcds.customer_demographics_t2。 +postgres=# DROP TABLE tpcds.customer_demographics_t2 ; +
提交一个早先为两阶段提交准备好的事务。
+--提交标识符为的trans_test的事务。 +postgres=# COMMIT PREPARED ' trans_test ' ; +
通过COPY命令实现在表和文件之间拷贝数据。
+COPY FROM从一个文件拷贝数据到一个表,COPY TO把一个表的数据拷贝到一个文件。
+--将tpcds.ship_mode中的数据拷贝到/home/omm/ds_ship_mode.dat文件中。 +postgres=# COPY tpcds.ship_mode TO ' /home/omm/ds_ship_mode.dat ' ; + +--将tpcds.ship_mode 输出到stdout。 +postgres=# COPY tpcds.ship_mode TO stdout; + +--从stdin拷贝数据到表tpcds.ship_mode_t1。 +postgres=# COPY tpcds.ship_mode_t1 FROM stdin ; + +--从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1。 +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' ; + +--从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为TEXT(format 'text'),分隔符为'\t'(delimiter E'\t'),忽略多余列(ignore_extra_data 'true'),不指定转义(noescaping 'true')。 +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' WITH ( format ' text ' , delimiter E ' \t ' , ignore_extra_data ' true ' , noescaping ' true ' ) ; + +--从/home/omm/ds_ship_mode.dat文件拷贝数据到表tpcds.ship_mode_t1,使用参数如下:导入格式为FIXED(FIXED),指定定长格式(FORMATTER ( SM_SHIP_MODE_SK ( 0, 2 ) , SM_SHIP_MODE_ID ( 2,16 ) , SM_TYPE ( 18,30 ) , SM_CODE ( 50,10 ) , SM_CARRIER ( 61,20 ) , SM_CONTRACT ( 82,20 ) ) ),忽略多余列(ignore_extra_data),有数据头(header)。 +postgres=# COPY tpcds.ship_mode_t1 FROM ' /home/omm/ds_ship_mode.dat ' FIXED FORMATTER ( SM_SHIP_MODE_SK ( 0 , 2 ) , SM_SHIP_MODE_ID ( 2 , 16 ) , SM_TYPE ( 18 , 30 ) , SM_CODE ( 50 , 10 ) , SM_CARRIER ( 61 , 20 ) , SM_CONTRACT ( 82 , 20 ) ) header ignore_extra_data ; +
创建一个新的数据库。缺省情况下新数据库将通过复制标准系统数据库template0来创建,且仅支持使用template0来创建。
+--创建一个GBK编码的数据库music(本地环境的编码格式必须也为GBK)。 +postgres=# CREATE DATABASE music ENCODING ' GBK ' template = template0 ; + +--创建数据库music2,并指定所有者为jim。 +postgres=# CREATE DATABASE music2 OWNER jim ; + +--用模板template0创建数据库music3,并指定所有者为jim。 +postgres=# CREATE DATABASE music3 OWNER jim TEMPLATE template0 ; + +--创建兼容TD格式的数据库。 +postgres=# CREATE DATABASE td_compatible_db DBCOMPATIBILITY ' C ' ; + +--创建兼容ORA格式的数据库。 +postgres=# CREATE DATABASE ora_compatible_db DBCOMPATIBILITY ' A ' ; +
创建一个新的外部数据源对象,该对象用于定义openGauss要连接的目标库信息。
+--创建一个空的Data Source对象,不含任何信息。 +postgres=# CREATE DATA SOURCE ds_test1 ; + +--创建一个Data Source对象,含TYPE信息,VERSION为NULL。 +postgres=# CREATE DATA SOURCE ds_test2 TYPE ' MPPDB ' VERSION NULL ; + +--创建一个Data Source对象,仅含OPTIONS。 +postgres=# CREATE DATA SOURCE ds_test3 OPTIONS ( dsn ' openGauss ' , encoding ' utf8 ' ) ; + +--创建一个Data Source对象,含TYPE, VERSION, OPTIONS。 +postgres=# CREATE DATA SOURCE ds_test4 TYPE ' unknown ' VERSION ' 11.2.3 ' OPTIONS ( dsn ' openGauss ' , username ' userid ' , password ' pwd@123456 ' , encoding ' ' ) ; +
使用CREATE DIRECTORY语句创建一个目录对象,该目录对象定义了服务器文件系统上目录的别名,用于存放用户使用的数据文件。
+--创建目录。 +postgres=# CREATE OR REPLACE DIRECTORY dir as ' /tmp/ ' ; +
创建一个函数。
+--定义函数为SQL查询。 +postgres=# CREATE FUNCTION func_add_sql ( integer , integer ) RETURNS integer +AS ' select $1 + $2 ; ' +LANGUAGE SQL +IMMUTABLE +RETURNS NULL ON NULL INPUT ; + +--利用参数名用 PL/pgSQL 自增一个整数。 +postgres=# CREATE OR REPLACE FUNCTION func_increment_plsql ( i integer ) RETURNS integer AS $$ +BEGIN +RETURN i + 1 ; +END ; +$$ LANGUAGE plpgsql ; + +--返回RECORD类型 +CREATE OR REPLACE FUNCTION compute ( i int , out result_1 bigint , out result_2 bigint ) +returns SETOF RECORD +as $$ +begin +result_1 = i + 1 ; +result_2 = i * 10 ; +return next; +end ; +$$language plpgsql ; + +--返回一个包含多个输出参数的记录。 +postgres=# CREATE FUNCTION func_dup_sql ( in int , out f1 int , out f2 text ) +AS $$ SELECT $1 , CAST ( $1 AS text ) || ' is text ' $$ +LANGUAGE SQL ; +postgres=# SELECT * FROM func_dup_sql ( 42 ) ; + +--计算两个整数的和,并返回结果。若果输入为null,则返回null。 +postgres=# CREATE FUNCTION func_add_sql2 ( num1 integer , num2 integer ) RETURN integer +AS +BEGIN +RETURN num1 + num2 ; +END ; +/ +
创建一个新用户组。
+CREATE GROUP是CREATE ROLE的别名,非SQL标准语法,不推荐使用,建议用户直接使用CREATE ROLE替代。
+在指定的表上创建索引。
+索引可以用来提高数据库查询性能,但是不恰当的使用将导致数据库性能下降。建议仅在匹配如下某条原则时创建索引:
+在分区表上创建索引与在普通表上创建索引的语法不太一样,使用时请注意,如分区表上不支持并行创建索引、不支持创建部分索引、不支持NULL FIRST特性。
+--在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建普通索引。 +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index1 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) ; + +--在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建指定B-tree索引。 +postgres=# CREATE INDEX ds_ship_mode_t1_index4 ON tpcds.ship_mode_t1 USING btree ( SM_SHIP_MODE_SK ) ; + +--在表tpcds.ship_mode_t1上SM_CODE字段上创建表达式索引。 +postgres=# CREATE INDEX ds_ship_mode_t1_index2 ON tpcds.ship_mode_t1 ( SUBSTR ( SM_CODE , 1 , 4 ) ) ; + +--在表tpcds.ship_mode_t1上的SM_SHIP_MODE_SK字段上创建SM_SHIP_MODE_SK大于10的部分索引。 +postgres=# CREATE UNIQUE INDEX ds_ship_mode_t1_index3 ON tpcds.ship_mode_t1 ( SM_SHIP_MODE_SK ) WHERE SM_SHIP_MODE_SK>10 ; + +--创建分区表索引ds_customer_address_p1_index1,不指定索引分区的名称。 +postgres=# CREATE INDEX ds_customer_address_p1_index1 ON tpcds.customer_address_p1 ( CA_ADDRESS_SK ) LOCAL ; + +--创建分区表索引ds_customer_address_p1_index2,并指定索引分区的名称。 +postgres=# CREATE INDEX ds_customer_address_p1_index2 ON tpcds.customer_address_p1 ( CA_ADDRESS_SK ) LOCAL + ( +PARTITION CA_ADDRESS_SK_index1 , +PARTITION CA_ADDRESS_SK_index2 TABLESPACE example3 , +PARTITION CA_ADDRESS_SK_index3 TABLESPACE example4 + ) +TABLESPACE example2 ; + +--创建列存表以及列存表GIN索引。 +postgres=# create table cgin_create_test ( a int , b text ) with ( orientation = column ) ; +CREATE TABLE +postgres=# create index cgin_test on cgin_create_test using gin ( to_tsvector ( ' ngram ' , b ) ) ; +CREATE INDEX +
对表创建行访问控制策略。
+当对表创建了行访问控制策略,只有打开该表的行访问控制开关(ALTER TABLE ... ENABLE ROW LEVEL SECURITY),策略才能生效。否则不生效。
+当前行访问控制影响数据表的读取操作(SELECT、UPDATE、DELETE),暂不影响数据表的写入操作(INSERT、MERGE INTO)。表所有者或系统管理员可以在USING子句中创建表达式,在客户端执行数据表读取操作时,数据库后台在查询重写阶段会将满足条件的表达式拼接并应用到执行计划中。针对数据表的每一条元组,当USING表达式返回TRUE时,元组对当前用户可见,当USING表达式返回FALSE或NULL时,元组对当前用户不可见。
+行访问控制策略名称是针对表的,同一个数据表上不能有同名的行访问控制策略;对不同的数据表,可以有同名的行访问控制策略。
+行访问控制策略可以应用到指定的操作(SELECT、UPDATE、DELETE、ALL),ALL表示会影响SELECT、UPDATE、DELETE三种操作;定义行访问控制策略时,若未指定受影响的相关操作,默认为ALL。
+行访问控制策略可以应用到指定的用户(角色),也可应用到全部用户(PUBLIC);定义行访问控制策略时,若未指定受影响的用户,默认为PUBLIC。
+--创建行访问控制策略,当前用户只能查看用户自身的数据 +postgres=# CREATE ROW LEVEL SECURITY POLICY all_data_rls ON all_data USING ( role = CURRENT_USER ) ; +
创建一个新的存储过程。
+创建角色。
+角色是拥有数据库对象和权限的实体。在不同的环境中角色可以认为是一个用户,一个组或者兼顾两者。
+--创建一个角色,名为manager,密码为Bigdata@123。 +postgres=# CREATE ROLE manager IDENTIFIED BY ' Bigdata@123 ' ; + +--创建一个角色,从2015年1月1日开始生效,到2026年1月1日失效。 +postgres=# CREATE ROLE miriam WITH LOGIN PASSWORD ' Bigdata@123 ' VALID BEGIN ' 2015-01-01 ' VALID UNTIL ' 2026-01-01 ' ; +
创建模式。
+访问命名对象时可以使用模式名作为前缀进行访问,如果无模式名前缀,则访问当前模式下的命名对象。创建命名对象时也可用模式名作为前缀修饰。
+另外,CREATE SCHEMA可以包括在新模式中创建对象的子命令,这些子命令和那些在创建完模式后发出的命令没有任何区别。如果使用了AUTHORIZATION子句,则所有创建的对象都将被该用户所拥有。
+-- 为用户role1创建一个同名schema,子命令创建的表films和winners的拥有者为role1。 +postgres=# CREATE SCHEMA AUTHORIZATION role1 +CREATE TABLE films ( title text , release date , awards text[] ) +CREATE VIEW winners AS +SELECT title , release FROM films WHERE awards IS NOT NULL ; +
CREATE SEQUENCE用于向当前数据库里增加一个新的序列。序列的Owner为创建此序列的用户。
+postgres=# CREATE SEQUENCE serial +START 101 +CACHE 20 ; +从序列中选出下一个数字: +postgres=# SELECT nextval ( ' serial ' ) ; +nextval + +-- +102 +创建与表关联的序列: +postgres=# CREATE TABLE customer_address + ( +ca_address_sk integer not null , +ca_address_id char ( 16 ) not null , +ca_street_number char ( 10 ) , +ca_street_name varchar ( 60 ) , +ca_street_type char ( 15 ) , +ca_suite_number char ( 10 ) , +ca_city varchar ( 60 ) , +ca_county varchar ( 30 ) , +ca_state char ( 2 ) , +ca_zip char ( 10 ) , +ca_country varchar ( 20 ) , +ca_gmt_offset decimal ( 5 , 2 ) , +ca_location_type char ( 20 ) + ) ; +postgres=# CREATE SEQUENCE serial1 +START 101 +CACHE 20 +OWNED BY customer_address.ca_address_sk ; +
创建一个同义词对象。同义词是数据库对象的别名,用于记录与其他数据库对象名间的映射关系,用户可以使用同义词访问关联的数据库对象。
+--创建表ot.t1及其同义词t1。 +postgres=# CREATE TABLE ot.t1 ( id int , name varchar2 ( 10 ) ) ; +postgres=# CREATE OR REPLACE SYNONYM t1 FOR ot.t1 ; + +--创建同义词v1及其关联视图ot.v_t1。 +postgres=# CREATE SYNONYM v1 FOR ot.v_t1 ; +postgres=# CREATE VIEW ot.v_t1 AS SELECT * FROM ot.t1 ; + +--创建重载函数ot.add及其同义词add。 +postgres=# CREATE OR REPLACE FUNCTION ot.add ( a integer , b integer ) RETURNS integer AS +$$ +SELECT $1 + $2 +$$ +LANGUAGE sql ; +postgres=# CREATE OR REPLACE FUNCTION ot.add ( a decimal ( 5 , 2 ) , b decimal ( 5 , 2 ) ) RETURNS decimal ( 5 , 2 ) AS +$$ +SELECT $1 + $2 +$$ +LANGUAGE sql ; +postgres=# CREATE OR REPLACE SYNONYM add FOR ot.add ; + +--创建存储过程ot.register及其同义词register。 +postgres=# CREATE PROCEDURE ot.register ( n_id integer , n_name varchar2 ( 10 ) ) +SECURITY INVOKER +AS +BEGIN +INSERT INTO ot.t1 VALUES ( n_id , n_name ) ; +END ; +/ +postgres=# CREATE OR REPLACE SYNONYM register FOR ot.register ; +
在当前数据库中创建一个新的空白表,该表由命令执行者所有。
+--创建简单的表。 +postgres=# CREATE TABLE tpcds.warehouse_t1 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; +postgres=# CREATE TABLE tpcds.warehouse_t2 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) DICTIONARY , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建表,并指定W_STATE字段的缺省值为GA。 +postgres=# CREATE TABLE tpcds.warehouse_t3 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) DEFAULT ' GA ' , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建表,并在事务结束时检查W_WAREHOUSE_NAME字段是否有重复。 +postgres=# CREATE TABLE tpcds.warehouse_t4 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) UNIQUE DEFERRABLE , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建一个带有70%填充因子的表。 +postgres=# CREATE TABLE tpcds.warehouse_t5 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +UNIQUE ( W_WAREHOUSE_NAME ) WITH ( fillfactor=70 ) + ) ; + +--或者用下面的语法。 +postgres=# CREATE TABLE tpcds.warehouse_t6 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) UNIQUE , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) WITH ( fillfactor=70 ) ; + +--创建表,并指定该表数据不写入预写日志。 +postgres=# CREATE UNLOGGED TABLE tpcds.warehouse_t7 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建表临时表。 +postgres=# CREATE TEMPORARY TABLE warehouse_t24 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--事务中创建表临时表,并指定提交事务时删除该临时表数据。 +postgres=# CREATE TEMPORARY TABLE warehouse_t25 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ON COMMIT DELETE ROWS ; + +--创建表时,不希望因为表已存在而报错。 +postgres=# CREATE TABLE IF NOT EXISTS tpcds.warehouse_t8 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建普通表空间。 +postgres=# CREATE TABLESPACE DS_TABLESPACE1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; + +--创建表时,指定表空间。 +postgres=# CREATE TABLE tpcds.warehouse_t9 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) TABLESPACE DS_TABLESPACE1 ; + +--创建表时,单独指定W_WAREHOUSE_NAME的索引表空间。 +postgres=# CREATE TABLE tpcds.warehouse_t10 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) UNIQUE USING INDEX TABLESPACE DS_TABLESPACE1 , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--创建一个有主键约束的表。 +postgres=# CREATE TABLE tpcds.warehouse_t11 + ( +W_WAREHOUSE_SK INTEGER PRIMARY KEY , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--或是用下面的语法,效果完全一样。 +postgres=# CREATE TABLE tpcds.warehouse_t12 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +PRIMARY KEY ( W_WAREHOUSE_SK ) + ) ; + +--或是用下面的语法,指定约束的名称。 +postgres=# CREATE TABLE tpcds.warehouse_t13 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +CONSTRAINT W_CSTR_KEY1 PRIMARY KEY ( W_WAREHOUSE_SK ) + ) ; + +--创建一个有复合主键约束的表。 +postgres=# CREATE TABLE tpcds.warehouse_t14 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +CONSTRAINT W_CSTR_KEY2 PRIMARY KEY ( W_WAREHOUSE_SK , W_WAREHOUSE_ID ) + ) ; + +--创建列存表。 +postgres=# CREATE TABLE tpcds.warehouse_t15 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) WITH ( ORIENTATION = COLUMN ) ; + +--创建局部聚簇存储的列存表。 +postgres=# CREATE TABLE tpcds.warehouse_t16 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +PARTIAL CLUSTER KEY ( W_WAREHOUSE_SK , W_WAREHOUSE_ID ) + ) WITH ( ORIENTATION = COLUMN ) ; + +--定义一个带压缩的列存表。 +postgres=# CREATE TABLE tpcds.warehouse_t17 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) WITH ( ORIENTATION = COLUMN , COMPRESSION=HIGH ) ; + +--定义一个带压缩的表。 +postgres=# CREATE TABLE tpcds.warehouse_t18 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) COMPRESS ; + +--定义一个检查列约束。 +postgres=# CREATE TABLE tpcds.warehouse_t19 + ( +W_WAREHOUSE_SK INTEGER PRIMARY KEY CHECK ( W_WAREHOUSE_SK > 0 ) , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) CHECK ( W_WAREHOUSE_NAME IS NOT NULL ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; +postgres=# CREATE TABLE tpcds.warehouse_t20 + ( +W_WAREHOUSE_SK INTEGER PRIMARY KEY , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) CHECK ( W_WAREHOUSE_NAME IS NOT NULL ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +CONSTRAINT W_CONSTR_KEY2 CHECK ( W_WAREHOUSE_SK > 0 AND W_WAREHOUSE_NAME IS NOT NULL ) + ) ; + +--定义一个表,表中每一个行存在数据库节点中。 +postgres=# CREATE TABLE tpcds.warehouse_t21 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) + ) ; + +--定义一个表,使用HASH分布。 +postgres=# CREATE TABLE tpcds.warehouse_t22 + ( +W_WAREHOUSE_SK INTEGER NOT NULL , +W_WAREHOUSE_ID CHAR ( 16 ) NOT NULL , +W_WAREHOUSE_NAME VARCHAR ( 20 ) , +W_WAREHOUSE_SQ_FT INTEGER , +W_STREET_NUMBER CHAR ( 10 ) , +W_STREET_NAME VARCHAR ( 60 ) , +W_STREET_TYPE CHAR ( 15 ) , +W_SUITE_NUMBER CHAR ( 10 ) , +W_CITY VARCHAR ( 60 ) , +W_COUNTY VARCHAR ( 30 ) , +W_STATE CHAR ( 2 ) , +W_ZIP CHAR ( 10 ) , +W_COUNTRY VARCHAR ( 20 ) , +W_GMT_OFFSET DECIMAL ( 5 , 2 ) , +CONSTRAINT W_CONSTR_KEY3 UNIQUE ( W_WAREHOUSE_SK ) + ) ; +
根据查询结果创建表。
+CREATE TABLE AS创建一个表并且用来自SELECT命令的结果填充该表。该表的字段和SELECT输出字段的名称及数据类型相关。不过用户可以通过明确地给出一个字段名称列表来覆盖SELECT输出字段的名称。
+CREATE TABLE AS对源表进行一次查询,然后将数据写入新表中,而查询视图结果会根据源表的变化而有所改变。相比之下,每次做查询的时候,视图都重新计算定义它的SELECT语句。
+--创建一个表tpcds.store_returns_t1并插入tpcds.store_returns表中sr_item_sk字段中大于16的数值。 +postgres=# CREATE TABLE tpcds.store_returns_t1 AS SELECT * FROM tpcds.store_returns WHERE sr_item_sk > ' 4795 ' ; + +--使用tpcds.store_returns拷贝一个新表tpcds.store_returns_t2。 +postgres=# CREATE TABLE tpcds.store_returns_t2 AS table tpcds.store_returns ; +
创建分区表。分区表是把逻辑上的一张表根据某种方案分成几张物理块进行存储,这张逻辑上的表称之为分区表,物理块称之为分区。分区表是一张逻辑表,不存储数据,数据实际是存储在分区上的。
+常见的分区方案有范围分区(Range Partitioning)、哈希分区(Hash Partitioning)、列表分区(List Partitioning)、数值分区(Value Partition)等。目前行存表、列存表仅支持范围分区。
+范围分区是根据表的一列或者多列,将要插入表的记录分为若干个范围,这些范围在不同的分区里没有重叠。为每个范围创建一个分区,用来存储相应的数据。
+范围分区的分区策略是指记录插入分区的方式。目前范围分区仅支持范围分区策略。
+范围分区策略:根据分区键值将记录映射到已创建的某个分区上,如果可以映射到已创建的某一分区上,则把记录插入到对应的分区上,否则给出报错和提示信息。这是最常用的分区策略。
+分区可以提供若干好处:
+有限地支持唯一约束和主键约束,即唯一约束和主键约束的约束键必须包含所有分区键。
+--创建分区表tpcds.web_returns_p1。 +postgres=# CREATE TABLE tpcds.web_returns_p1 + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER , +WR_REFUNDED_CDEMO_SK INTEGER , +WR_REFUNDED_HDEMO_SK INTEGER , +WR_REFUNDED_ADDR_SK INTEGER , +WR_RETURNING_CUSTOMER_SK INTEGER , +WR_RETURNING_CDEMO_SK INTEGER , +WR_RETURNING_HDEMO_SK INTEGER , +WR_RETURNING_ADDR_SK INTEGER , +WR_WEB_PAGE_SK INTEGER , +WR_REASON_SK INTEGER , +WR_ORDER_NUMBER BIGINT NOT NULL , +WR_RETURN_QUANTITY INTEGER , +WR_RETURN_AMT DECIMAL ( 7 , 2 ) , +WR_RETURN_TAX DECIMAL ( 7 , 2 ) , +WR_RETURN_AMT_INC_TAX DECIMAL ( 7 , 2 ) , +WR_FEE DECIMAL ( 7 , 2 ) , +WR_RETURN_SHIP_COST DECIMAL ( 7 , 2 ) , +WR_REFUNDED_CASH DECIMAL ( 7 , 2 ) , +WR_REVERSED_CHARGE DECIMAL ( 7 , 2 ) , +WR_ACCOUNT_CREDIT DECIMAL ( 7 , 2 ) , +WR_NET_LOSS DECIMAL ( 7 , 2 ) + ) +WITH ( ORIENTATION = COLUMN , COMPRESSION=MIDDLE ) +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2450815 ) , +PARTITION P2 VALUES LESS THAN ( 2451179 ) , +PARTITION P3 VALUES LESS THAN ( 2451544 ) , +PARTITION P4 VALUES LESS THAN ( 2451910 ) , +PARTITION P5 VALUES LESS THAN ( 2452275 ) , +PARTITION P6 VALUES LESS THAN ( 2452640 ) , +PARTITION P7 VALUES LESS THAN ( 2453005 ) , +PARTITION P8 VALUES LESS THAN ( MAXVALUE ) + ) ; + +--查询分区P1的行数。 +postgres=# SELECT COUNT ( * ) FROM tpcds.web_returns_p1 PARTITION FOR ( 2450815 ) ; +count +-------- +0 + ( 1 row ) +示例2:创建范围分区表tpcds.web_returns_p2,含有8个分区,分区键类型为integer类型,其中第8个分区上边界为MAXVALUE。八个分区的范围分别为: wr_returned_date_sk< 2450815,2450815<= wr_returned_date_sk< 2451179,2451179<=wr_returned_date_sk< 2451544,2451544 <= wr_returned_date_sk< 2451910,2451910 <= wr_returned_date_sk< 2452275,2452275 <= wr_returned_date_sk< 2452640,2452640 <= wr_returned_date_sk< 2453005,wr_returned_date_sk>=2453005。 +分区表tpcds.web_returns_p2的表空间为example1;分区P1到P7没有声明表空间,使用采用分区表tpcds.web_returns_p2的表空间example1;指定分区P8的表空间为example2。 +假定数据库节点的数据目录/pg_location/mount1/path1,数据库节点的数据目录/pg_location/mount2/path2,数据库节点的数据目录/pg_location/mount3/path3,数据库节点的数据目录/pg_location/mount4/path4是dwsadmin用户拥有读写权限的空目录。 +postgres=# CREATE TABLESPACE example1 RELATIVE LOCATION ' tablespace1/tablespace_1 ' ; +postgres=# CREATE TABLESPACE example2 RELATIVE LOCATION ' tablespace2/tablespace_2 ' ; +postgres=# CREATE TABLESPACE example3 RELATIVE LOCATION ' tablespace3/tablespace_3 ' ; +postgres=# CREATE TABLESPACE example4 RELATIVE LOCATION ' tablespace4/tablespace_4 ' ; +postgres=# CREATE TABLE tpcds.web_returns_p2 + ( +WR_RETURNED_DATE_SK INTEGER , +WR_RETURNED_TIME_SK INTEGER , +WR_ITEM_SK INTEGER NOT NULL , +WR_REFUNDED_CUSTOMER_SK INTEGER , +WR_REFUNDED_CDEMO_SK INTEGER , +WR_REFUNDED_HDEMO_SK INTEGER , +WR_REFUNDED_ADDR_SK INTEGER , +WR_RETURNING_CUSTOMER_SK INTEGER , +WR_RETURNING_CDEMO_SK INTEGER , +WR_RETURNING_HDEMO_SK INTEGER , +WR_RETURNING_ADDR_SK INTEGER , +WR_WEB_PAGE_SK INTEGER , +WR_REASON_SK INTEGER , +WR_ORDER_NUMBER BIGINT NOT NULL , +WR_RETURN_QUANTITY INTEGER , +WR_RETURN_AMT DECIMAL ( 7 , 2 ) , +WR_RETURN_TAX DECIMAL ( 7 , 2 ) , +WR_RETURN_AMT_INC_TAX DECIMAL ( 7 , 2 ) , +WR_FEE DECIMAL ( 7 , 2 ) , +WR_RETURN_SHIP_COST DECIMAL ( 7 , 2 ) , +WR_REFUNDED_CASH DECIMAL ( 7 , 2 ) , +WR_REVERSED_CHARGE DECIMAL ( 7 , 2 ) , +WR_ACCOUNT_CREDIT DECIMAL ( 7 , 2 ) , +WR_NET_LOSS DECIMAL ( 7 , 2 ) + ) +TABLESPACE example1 +PARTITION BY RANGE ( WR_RETURNED_DATE_SK ) + ( +PARTITION P1 VALUES LESS THAN ( 2450815 ) , +PARTITION P2 VALUES LESS THAN ( 2451179 ) , +PARTITION P3 VALUES LESS THAN ( 2451544 ) , +PARTITION P4 VALUES LESS THAN ( 2451910 ) , +PARTITION P5 VALUES LESS THAN ( 2452275 ) , +PARTITION P6 VALUES LESS THAN ( 2452640 ) , +PARTITION P7 VALUES LESS THAN ( 2453005 ) , +PARTITION P8 VALUES LESS THAN ( MAXVALUE ) TABLESPACE example2 + ) +ENABLE ROW MOVEMENT ; + +--以like方式创建一个分区表。 +postgres=# CREATE TABLE tpcds.web_returns_p3 ( LIKE tpcds.web_returns_p2 INCLUDING PARTITION ) ; +
在数据库中创建一个新的表空间。
+--创建表空间。 +postgres=# CREATE TABLESPACE ds_location1 RELATIVE LOCATION ' tablespace/tablespace_1 ' ; + +--创建表空间,且所有者指定为用户joe。 +postgres=# CREATE TABLESPACE ds_location2 OWNER joe RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +
创建新的文本搜索配置。一个文本搜索配置声明一个能将一个字符串划分成符号的文本搜索解析器,加上可以用于确定搜索对哪些标记感兴趣的字典。
+--创建文本搜索配置。 +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram2 ( parser=ngram ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; + +--创建文本搜索配置。 +postgres=# CREATE TEXT SEARCH CONFIGURATION ngram3 ( copy=ngram2 ) WITH ( gram_size = 2 , grapsymbol_ignore = false ) ; +
创建一个新的全文检索词典。词典是一种指定在全文检索时识别特定词并处理的方法。
+词典的创建依赖于预定义模板(在系统表PG_TS_TEMPLATE中定义),支持创建五种类型的词典,分别是Simple、Ispell、Synonym、Thesaurus、以及Snowball,每种类型的词典可以完成不同的任务。
+创建一个触发器。 触发器将与指定的表或视图关联,并在特定条件下执行指定的函数。
+--创建源表及触发表 +postgres=# CREATE TABLE test_trigger_src_tbl ( id1 INT , id2 INT , id3 INT ) ; +postgres=# CREATE TABLE test_trigger_des_tbl ( id1 INT , id2 INT , id3 INT ) ; + +--创建触发器函数 +postgres=# CREATE OR REPLACE FUNCTION tri_insert_func ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +INSERT INTO test_trigger_des_tbl VALUES ( NEW.id1 , NEW.id2 , NEW.id3 ) ; +RETURN NEW ; +END +$$ LANGUAGE PLPGSQL ; +postgres=# CREATE OR REPLACE FUNCTION tri_update_func ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +UPDATE test_trigger_des_tbl SET id3 = NEW.id3 WHERE id1=OLD.id1 ; +RETURN OLD ; +END +$$ LANGUAGE PLPGSQL ; +postgres=# CREATE OR REPLACE FUNCTION TRI_DELETE_FUNC ( ) RETURNS TRIGGER AS +$$ +DECLARE +BEGIN +DELETE FROM test_trigger_des_tbl WHERE id1=OLD.id1 ; +RETURN OLD ; +END +$$ LANGUAGE PLPGSQL ; + +--创建INSERT触发器 +postgres=# CREATE TRIGGER insert_trigger +BEFORE INSERT ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_insert_func ( ) ; + +--创建UPDATE触发器 +postgres=# CREATE TRIGGER update_trigger +AFTER UPDATE ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_update_func ( ) ; + +--创建DELETE触发器 +postgres=# CREATE TRIGGER delete_trigger +BEFORE DELETE ON test_trigger_src_tbl +FOR EACH ROW +EXECUTE PROCEDURE tri_delete_func ( ) ; +
在当前数据库中定义一种新的数据类型。定义数据类型的用户将成为该数据类型的拥有者。类型只适用于行存表
+有四种形式的CREATE TYPE,分别为:复合类型、基本类型、shell类型和枚举类型。
+复合类型由一个属性名和数据类型的列表指定。如果属性的数据类型是可排序的,也可以指定该属性的排序规则。复合类型本质上和表的行类型相同,但是如果只想定义一种类型,使用CREATE TYPE避免了创建一个实际的表。单独的复合类型也是很有用的,例如可以作为函数的参数或者返回类型。
+为了能够创建复合类型,必须拥有在其所有属性类型上的USAGE特权。
+用户可以自定义一种新的基本类型(标量类型)。通常来说这些函数必须是底层语言所编写。
+shell类型是一种用于后面要定义的类型的占位符,通过发出一个不带除类型名之外其他参数的CREATE TYPE命令可以创建这种类型。在创建基本类型时,需要shell类型作为一种向前引用。
+由若干个标签构成的列表,每一个标签值都是一个非空字符串,且字符串长度必须不超过64个字节。
+如果给定一个模式名,那么该类型将被创建在指定的模式中。否则它会被创建在当前模式中。类型名称必须与同一个模式中任何现有的类型或者域相区别(因为表具有相关的数据类型,类型名称也必须与同一个模式中任何现有表的名称不同)。
+--创建一种复合类型,建表并插入数据以及查询。 +postgres=# CREATE TYPE compfoo AS ( f1 int , f2 text ) ; +postgres=# CREATE TABLE t1_compfoo ( a int , b compfoo ) ; +postgres=# CREATE TABLE t2_compfoo ( a int , b compfoo ) ; +postgres=# INSERT INTO t1_compfoo values ( 1 , ( 1 , ' demo ' ) ) ; +postgres=# INSERT INTO t2_compfoo select * from t1_typ5 ; +postgres=# SELECT ( b ) .f1 FROM t1_compfoo ; +postgres=# SELECT * FROM t1_compfoo t1 join t2_compfoo t2 on ( t1.b ) .f1= ( t1.b ) .f1 ; + +--要改变一个用户定义类型compfoo1的所有者为usr1。 +postgres=# CREATE USER usr1 PASSWORD ' Bigdata@123 ' ; +postgres=# ALTER TYPE compfoo1 OWNER TO usr1 ; + +--创建一个枚举类型。 +postgres=# CREATE TYPE bugstatus AS ENUM ( ' create ' , ' modify ' , ' closed ' ) ; +
创建一个用户。
+--创建用户jim,登录密码为Bigdata@123。 +postgres=# CREATE USER jim PASSWORD ' Bigdata@123 ' ; + +--下面语句与上面的等价。 +postgres=# CREATE USER kim IDENTIFIED BY ' Bigdata@123 ' ; + +--如果创建有“创建数据库”权限的用户,则需要加CREATEDB关键字。 +postgres=# CREATE USER dim CREATEDB PASSWORD ' Bigdata@123 ' ; +
创建一个视图。视图与基本表不同,是一个虚拟的表。数据库中仅存放视图的定义,而不存放视图对应的数据,这些数据仍存放在原来的基本表中。若基本表中的数据发生变化,从视图中查询出的数据也随之改变。从这个意义上讲,视图就像一个窗口,透过它可以看到数据库中用户感兴趣的数据及变化。
+--创建字段spcname为pg_default组成的视图。 +postgres=# CREATE VIEW myView AS +SELECT * FROM pg_tablespace WHERE spcname = ' pg_default ' ; +
CURSOR命令定义一个游标,用于在一个大的查询里面检索少数几行数据。
+为了处理SQL语句,存储过程进程分配一段内存区域来保存上下文联系。游标是指向上下文区域的句柄或指针。借助游标,存储过程可以控制上下文区域的变化。
+--建立一个名为cursor1的游标。 +postgres=# CURSOR cursor1 FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; + +--抓取头3行到游标cursor1里。 +postgres=# FETCH FORWARD 3 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 3 rows ) + +--关闭游标并提交事务。 +postgres=# CLOSE cursor1 ; + +--建立一个名为cursor2的游标。 +postgres=# CURSOR cursor2 FOR VALUES ( 1 , 2 ) , ( 0 , 3 ) ORDER BY 1 ; + +--抓取头2行到游标cursor2里。 +postgres=# FETCH FORWARD 2 FROM cursor2 ; +column1 | column2 +---------+--------- +0 | 3 +1 | 2 + ( 2 rows ) + +--关闭游标并提交事务。 +postgres=# CLOSE cursor2 ; + +--创建一个with hold游标。 +postgres=# DECLARE cursor1 CURSOR WITH HOLD FOR SELECT * FROM tpcds.customer_address ORDER BY 1 ; + +--抓取头2行到游标cursor1里。 +postgres=# FETCH FORWARD 2 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo + ( 2 rows ) + +--抓取下一行到游标cursor1里。 +postgres=# FETCH FORWARD 1 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 1 row ) + +--关闭游标。 +postgres=# CLOSE cursor1 ; +
DEALLOCATE用于删除前面编写的预备语句。如果用户没有明确删除一个预备语句,那么它将在会话结束的时候被删除。
+PREPARE关键字总被忽略。
+DECLARE命令既可以定义一个游标,用于在一个大的查询里面检索少数几行数据,也可以作为一个匿名块的开始。
+本节主要描述定义为游标的用法,开启匿名块的用法见BEGIN。
+为了处理SQL语句,存储过程进程分配一段内存区域来保存上下文联系。游标是指向上下文区域的句柄或指针。借助游标,存储过程可以控制上下文区域的变化。
+通常游标和SELECT一样返回文本格式。因为数据在系统内部是用二进制格式存储的,系统必须对数据做一定转换以生成文本格式。一旦数据是以文本形式返回,客户端应用需要把它们转换成二进制进行操作。使用FETCH语句,游标可以返回文本或二进制格式。
+DELETE从指定的表里删除满足WHERE子句的行。如果WHERE子句不存在,将删除表中所有行,结果只保留表结构。
+--删除tpcds.customer_address_bak中ca_address_sk小于14888的职员。 +postgres=# DELETE FROM tpcds.customer_address_bak WHERE ca_address_sk < 14888 ; + +--删除tpcds.customer_address_bak中所有数据。 +postgres=# DELETE FROM tpcds.customer_address_bak ; +
执行匿名代码块。
+代码块被看做是没有参数的一段函数体,返回值类型是void。它的解析和执行是同一时刻发生的。
+--授予用户webuser对模式tpcds下视图的所有操作权限。 +postgres=# DO $$DECLARE r record ; +BEGIN +FOR r IN SELECT c.relname table_name , n.nspname table_schema FROM pg_class c , pg_namespace n +WHERE c.relnamespace = n.oid AND n.nspname = ' tpcds ' AND relkind IN ( ' r ' , ' v ' ) +LOOP +EXECUTE ' GRANT ALL ON ' || quote_ident ( r.table_schema ) || ' . ' || quote_ident ( r.table_name ) || ' TO webuser ' ; +END LOOP ; +END$$ ; +
删除一个数据库。
+DROP DATABASE一旦执行将无法撤销,请谨慎使用。
+--删除数据库。 +postgres=# DROP DATABASE music2 ;
删除一个Data Source对象。
+只有属主/系统管理员/初始用户才可以删除一个Data Source对象。
+--删除Data Source对象。 +postgres=# DROP DATA SOURCE ds_tst1 CASCADE ;
删除指定的directory对象。
+默认只有初始化用户可以执行drop操作,当enable_access_server_directory开启时(可参考enable_access_server_directory),sysadmin权限的用户也可以执行drop操作。
+--删除目录。 +postgres=# DROP DIRECTORY dir ;
删除一个已存在的函数。
+如果函数中涉及对临时表相关操作,则无法使用DROP FUNCTION删除函数。
+删除用户组。
+DROP GROUP是DROP ROLE的别名。
+DROP GROUP是openGauss管理工具封装的内部接口,用来实现openGauss管理。该接口不建议用户直接使用,以免对openGauss状态造成影响。
+删除索引。
+只有索引的所有者有权限执行DROP INDEX命令,系统管理员默认拥有此权限。
+--删除一个现有的索引。 +postgres=# DROP INDEX tpcds.ds_ship_mode_t1_index2 ;
删除一个数据库角色所拥有的数据库对象。
+删除表上某个行访问控制策略。
+仅表的所有者或者管理员用户才能删除表的行访问控制策略。
+--删除行访问控制策略 +postgres=# DROP ROW LEVEL SECURITY POLICY all_data_rls ON all_data ;
删除已存在的存储过程。
+删除指定的角色。
+--删除角色manager。 +postgres=# DROP ROLE manager ;
从数据库中删除模式。
+只有模式的所有者有权限执行DROP SCHEMA命令,系统管理员默认拥有此权限。
+--删除schema。 +postgres=# DROP SCHEMA role1 CASCADE ;
从当前数据库里删除序列。
+只有序列的所有者或者系统管理员才能删除。
+--删除序列。 +postgres=# DROP SEQUENCE serial ;
删除指定的SYNONYM对象。
+只有SYNONYM的所有者有权限执行DROP SYNONYM命令,系统管理员默认拥有此权限。
+--删除同义词。 +postgres=# DROP SYNONYM t1 ;
删除指定的表。
+DROP TABLE会强制删除指定的表,删除表后,依赖该表的索引会被删除,而使用到该表的函数和存储过程将无法执行。删除分区表,会同时删除分区表中的所有分区。
+--删除表空间、模式joe和模式表warehouse。 +postgres=# DROP TABLE tpcds.warehouse_t1 ;
删除一个表空间。
+--删除表空间。 +postgres=# DROP TABLESPACE ds_location2 ;
删除已有文本搜索配置。
+要执行这个命令,用户必须是该配置的所有者。
+--删除文本搜索配置。 +postgres=# DROP TEXT SEARCH CONFIGURATION joe.ngram_2 ;
删除全文检索词典。
+--删除词典english +DROP TEXT SEARCH DICTIONARY english ;
删除触发器。
+只有触发器的所有者可以执行DROP TRIGGER操作,系统管理员默认拥有此权限。
+--删除触发器 +postgres=# DROP TRIGGER insert_trigger ON test_trigger_src_tbl ;
删除一个用户定义的数据类型。只有类型所有者才有删除权限。
+--删除compfoo1类型。 +postgres=# DROP TYPE usr1.compfoo1 cascade ;
删除用户,同时会删除同名的schema。
+--删除用户。 +postgres=# DROP USER kim CASCADE ;
数据库中强制删除已有的视图。
+只有视图的所有者有权限执行DROP VIEW的命令,系统管理员默认拥有此权限。
+--删除视图myView。 +postgres=# DROP VIEW myView ;
执行一个前面准备好的预备语句。因为一个预备语句只在会话的生命期里存在,那么预备语句必须是在当前会话的前些时候用PREPARE语句创建的。
+如果创建预备语句的PREPARE语句声明了一些参数,那么传递给EXECUTE语句的必须是一个兼容的参数集,否则就会生成一个错误。
+--为一个INSERT语句创建一个预备语句然后执行它。 +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; +
显示SQL语句的执行计划。
+执行计划将显示SQL语句所引用的表会采用什么样的扫描方式,如:简单的顺序扫描、索引扫描等。如果引用了多个表,执行计划还会显示用到的JOIN算法。
+执行计划的最关键的部分是语句的预计执行开销,这是计划生成器估算执行该语句将花费多长的时间。
+若指定了ANALYZE选项,则该语句会被执行,然后根据实际的运行结果显示统计数据,包括每个计划节点内时间总开销(毫秒为单位)和实际返回的总行数。这对于判断计划生成器的估计是否接近现实非常有用。
+在指定ANALYZE选项时,语句会被执行。如果用户想使用EXPLAIN分析INSERT,UPDATE,DELETE,CREATE TABLE AS或EXECUTE语句,而不想改动数据(执行这些语句会影响数据),请使用这种方法:
+START TRANSACTION; +EXPLAIN ANALYZE ...; +ROLLBACK;+
--修改explain_perf_mode为normal +postgres=# SET explain_perf_mode=normal ; + +--显示表简单查询的执行计划。 +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 ; +QUERY PLAN +-------------------------------------------------- +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) +Node/s: All dbnodes + ( 2 rows ) + +--以JSON格式输出的执行计划(explain_perf_mode为normal时)。 +postgres=# EXPLAIN ( FORMAT JSON ) SELECT * FROM tpcds.customer_address_p1 ; +QUERY PLAN +-------------------------------------- +[ + +{ + +"Plan": { + +"Node Type": "Data Node Scan" , + +"Startup Cost": 0.00 , + +"Total Cost": 0.00 , + +"Plan Rows": 0 , + +"Plan Width": 0 , + +"Node/s": "All dbnodes" + +} + +} + +] + ( 1 row ) + +--如果有一个索引,当使用一个带索引WHERE条件的查询,可能会显示一个不同的计划。 +postgres=# EXPLAIN SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +-------------------------------------------------- +Data Node Scan ( cost=0.00..0.00 rows=0 width=0 ) +Node/s: dn_6005_6006 + ( 2 rows ) + +--以YAML格式输出的执行计划(explain_perf_mode为normal时)。 +postgres=# EXPLAIN ( FORMAT YAML ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +--------------------------------- +- Plan: + +Node Type: "Data Node Scan"+ +Startup Cost: 0.00 + +Total Cost: 0.00 + +Plan Rows: 0 + +Plan Width: 0 + +Node/s: "dn_6005_6006" + ( 1 row ) + +--禁止开销估计的执行计划。 +postgres=# EXPLAIN ( COSTS FALSE ) SELECT * FROM tpcds.customer_address_p1 WHERE ca_address_sk=10000 ; +QUERY PLAN +------------------------ +Data Node Scan +Node/s: dn_6005_6006 + ( 2 rows ) + +--带有聚集函数查询的执行计划。 +postgres=# EXPLAIN SELECT SUM ( ca_address_sk ) FROM tpcds.customer_address_p1 WHERE ca_address_sk<10000 ; +QUERY PLAN +--------------------------------------------------------------------------------------- +Aggregate ( cost=18.19..14.32 rows=1 width=4 ) +-> Streaming ( type: GATHER ) ( cost=18.19..14.32 rows=3 width=4 ) +Node/s: All dbnodes +-> Aggregate ( cost=14.19..14.20 rows=3 width=4 ) +-> Seq Scan on customer_address_p1 ( cost=0.00..14.18 rows=10 width=4 ) +Filter: ( ca_address_sk < 10000 ) + ( 6 rows ) +
通过EXPLAIN PLAN命令可以将查询执行的计划信息存储于PLAN_TABLE表中。与EXPLAIN命令不同的是,EXPLAIN PLAN仅将计划信息进行存储,而不会打印到屏幕。
+explain plan set statement_id= ' TPCH-Q4 ' for +select +o_orderpriority , +count ( * ) as order_count +from +orders +where +o_orderdate >= ' 1993-07-01 ' ::date +and o_orderdate < ' 1993-07-01 ' ::date + interval ' 3 month ' +and exists ( +select +* +from +lineitem +where +l_orderkey = o_orderkey +and l_commitdate < l_receiptdate + ) +group by +o_orderpriority +order by +o_orderpriority ; +查询PLAN_TABLE。SELECT * FROM PLAN_TABLE ; +清理PLAN_TABLE表中的数据。DELETE FROM PLAN_TABLE WHERE xxx ; +
FETCH通过已创建的游标来检索数据。
+每个游标都有一个供FETCH使用的关联位置。游标的关联位置可以在查询结果的第一行之前,或者在结果中的任意行,或者在结果的最后一行之后:
+--抓取头3行到游标cursor1里。 +postgres=# FETCH FORWARD 3 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 3 rows ) + +--抓取头2行到游标cursor2里。 +postgres=# FETCH FORWARD 2 FROM cursor2 ; +column1 | column2 +---------+--------- +0 | 3 +1 | 2 + ( 2 rows ) + +--抓取头2行到游标cursor1里。 +postgres=# FETCH FORWARD 2 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +1 | AAAAAAAABAAAAAAA | 18 | Jackson | Parkway | Suite 280 | Fairfield | Maricopa County | AZ | 86192 | United States | -7.00 | condo +2 | AAAAAAAACAAAAAAA | 362 | Washington 6th | RD | Suite 80 | Fairview | Taos County | NM | 85709 | United States | -7.00 | condo + ( 2 rows ) + +--抓取下一行到游标cursor1里。 +postgres=# FETCH FORWARD 1 FROM cursor1 ; +ca_address_sk | ca_address_id | ca_street_number | ca_street_name | ca_street_type | ca_suite_number | ca_city | ca_county | ca_state | ca_zip | ca_country | ca_gmt_offset | ca_location_type +---------------+------------------+------------------+--------------------+-----------------+-----------------+-----------------+-----------------+----------+------------+---------------+---------------+---------------------- +3 | AAAAAAAADAAAAAAA | 585 | Dogwood Washington | Circle | Suite Q | Pleasant Valley | York County | PA | 12477 | United States | -5.00 | single family + ( 1 row ) +
对角色和用户进行授权操作。
+使用GRANT命令进行用户授权包括以下三种场景:
+系统权限又称为用户属性,包括SYSADMIN、CREATEDB、CREATEROLE、AUDITADMIN和LOGIN。
+系统权限一般通过CREATE/ALTER ROLE语法来指定。其中,SYSADMIN权限可以通过GRANT/REVOKE ALL PRIVILEGE授予或撤销。但系统权限无法通过ROLE和USER的权限被继承,也无法授予PUBLIC。
+将数据库对象(表和视图、指定字段、数据库、函数、模式、表空间等)的相关权限授予特定角色或用户;
+GRANT命令将数据库对象的特定权限授予一个或多个角色。这些权限会追加到已有的权限上。
+关键字PUBLIC表示该权限要赋予所有角色,包括以后创建的用户。PUBLIC可以看做是一个隐含定义好的组,它总是包括所有角色。任何角色或用户都将拥有通过GRANT直接赋予的权限和所属的权限,再加上PUBLIC的权限。
+如果声明了WITH GRANT OPTION,则被授权的用户也可以将此权限赋予他人,否则就不能授权给他人。这个选项不能赋予PUBLIC,这是openGauss特有的属性。
+openGauss会将某些类型的对象上的权限授予PUBLIC。默认情况下,对表、表字段、序列、外部数据源、外部服务器、模式或表空间对象的权限不会授予PUBLIC,而以下这些对象的权限会授予PUBLIC:数据库的CONNECT权限和CREATE TEMP TABLE权限、函数的EXECUTE特权、语言和数据类型(包括域)的USAGE特权。当然,对象拥有者可以撤销默认授予PUBLIC的权限并专门授予权限给其他用户。为了更安全,建议在同一个事务中创建对象并设置权限,这样其他用户就没有时间窗口使用该对象。另外,这些初始的默认权限可以使用ALTER DEFAULT PRIVILEGES命令修改。
+将一个角色或用户的权限授予一个或多个其他角色或用户。在这种情况下,每个角色或用户都可视为拥有一个或多个数据库权限的集合。
+当声明了WITH ADMIN OPTION,被授权的用户可以将该权限再次授予其他角色或用户,以及撤销所有由该角色或用户继承到的权限。当授权的角色或用户发生变更或被撤销时,所有继承该角色或用户权限的用户拥有的权限都会随之发生变更。
+数据库系统管理员可以给任何角色或用户授予/撤销任何权限。拥有CREATEROLE权限的角色可以赋予或者撤销任何非系统管理员角色的权限。
+postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT ALL PRIVILEGES TO joe ; +授权成功后,用户joe会拥有sysadmin的所有权限。 +示例:将对象权限授权给用户或者角色。 +撤销joe用户的sysadmin权限,然后将模式tpcds的使用权限和表tpcds.reason的所有权限授权给用户joe。postgres=# REVOKE ALL PRIVILEGES FROM joe ; +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; +授权成功后,joe用户就拥有了tpcds.reason表的所有权限,包括增删改查等权限。 +将tpcds.reason表中r_reason_sk、r_reason_id、r_reason_desc列的查询权限,r_reason_desc的更新权限授权给joe。postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; +授权成功后,用户joe对tpcds.reason表中r_reason_sk,r_reason_id的查询权限会立即生效。如果joe用户需要拥有将这些权限授权给其他用户的权限,可以通过以下语法对joe用户进行授权。 +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; +将数据库postgres的连接权限授权给用户joe,并给予其在postgres中创建schema的权限,而且允许joe将此权限授权给其他用户。 +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; +创建角色tpcds_manager,将模式tpcds的访问权限授权给角色tpcds_manager,并授予该角色在tpcds下创建对象的权限,不允许该角色中的用户将权限授权给其他人。 +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; +将表空间tpcds_tbspc的所有权限授权给用户joe,但用户joe无法将权限继续授予其他用户。 +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; +示例:将用户或者角色的权限授权给其他用户或角色。 +创建角色manager,将joe的权限授权给manager,并允许该角色将权限授权给其他人。postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; +创建用户senior_manager,将用户manager的权限授权给该用户。postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT manager TO senior_manager ; +撤销权限,并清理用户。postgres=# REVOKE manager FROM joe ; +postgres=# REVOKE senior_manager FROM manager ; +postgres=# DROP USER manager ; +示例:撤销上述授予的权限,并清理角色和用户。 +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; +postgres=# DROP TABLESPACE tpcds_tbspc ; +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; +postgres=# DROP ROLE tpcds_manager ; +postgres=# DROP ROLE senior_manager ; +postgres=# DROP USER joe CASCADE ; +
向表中添加一行或多行数据。
+如果向字符集为字节类型编码(SQL_ASCII,LATIN1等)的数据库中插入多字节字符数据(如汉字等),且字符数据跨越截断位置,这种情况下,按照字节长度自动截断,自动截断后会在尾部产生非预期结果。如果用户有对于截断结果正确性的要求,建议用户采用UTF8等能够按照字符截断的输入字符集作为数据库的编码集。
+--向表中插入一条记录。 +postgres=# INSERT INTO tpcds.reason_t2 ( r_reason_sk , r_reason_id , r_reason_desc ) VALUES ( 1 , ' AAAAAAAABAAAAAAA ' , ' reason1 ' ) ; + +--向表中插入一条记录,和上一条语法等效。 +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 2 , ' AAAAAAAABAAAAAAA ' , ' reason2 ' ) ; + +--向表中插入多条记录。 +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 3 , ' AAAAAAAACAAAAAAA ' , ' reason3 ' ) , ( 4 , ' AAAAAAAADAAAAAAA ' , ' reason4 ' ) , ( 5 , ' AAAAAAAAEAAAAAAA ' , ' reason5 ' ) ; + +--向表中插入tpcds.reason中r_reason_sk小于5的记录。 +postgres=# INSERT INTO tpcds.reason_t2 SELECT * FROM tpcds.reason WHERE r_reason_sk <5 ; + +--向表中插入多条记录,如果冲突则更新冲突数据行中r_reason_id字段为'BBBBBBBBCAAAAAAA'。 +postgres=# INSERT INTO tpcds.reason_t2 VALUES ( 5 , ' BBBBBBBBCAAAAAAA ' , ' reason5 ' ) , ( 6 , ' AAAAAAAADAAAAAAA ' , ' reason6 ' ) ON DUPLICATE KEY UPDATE r_reason_id = ' BBBBBBBBCAAAAAAA ' ; +
LOCK TABLE获取表级锁。
+openGauss在为一个引用了表的命令自动请求锁时,尽可能选择最小限制的锁模式。如果用户需要一种更为严格的锁模式,可以使用LOCK命令。例如,一个应用是在Read Committed隔离级别上运行事务,并且它需要保证表中的数据在事务的运行过程中不被修改。为实现这个目的,则可以在查询之前对表使用SHARE锁模式进行锁定。这样将防止数据不被并发修改,从而保证后续的查询可以读到已提交的持久化的数据。因为SHARE锁模式与任何写操作需要的ROW EXCLUSIVE模式冲突,并且LOCK TABLE name IN SHARE MODE语句将等到所有当前持有ROW EXCLUSIVE模式锁的事务提交或回滚后才能执行。因此,一旦获得该锁,就不会存在未提交的写操作,并且其他操作也只能等到该锁释放之后才能开始。
+--在执行删除操作时对一个有主键的表进行 SHARE ROW EXCLUSIVE 锁。 +postgres=# CREATE TABLE tpcds.reason_t1 AS TABLE tpcds.reason ; +postgres=# START TRANSACTION ; +postgres=# LOCK TABLE tpcds.reason_t1 IN SHARE ROW EXCLUSIVE MODE ; +postgres=# DELETE FROM tpcds.reason_t1 WHERE r_reason_desc IN ( SELECT r_reason_desc FROM tpcds.reason_t1 WHERE r_reason_sk < 6 ) ; +postgres=# DELETE FROM tpcds.reason_t1 WHERE r_reason_sk = 7 ; +postgres=# COMMIT ; +
MOVE在不检索数据的情况下重新定位一个游标。MOVE的作用类似于FETCH命令,但只是重定位游标而不返回行。
+--忽略游标cursor1的前3行。 +postgres=# MOVE FORWARD 3 FROM cursor1 ; +
通过MERGE INTO语句,将目标表和源表中数据针对关联条件进行匹配,若关联条件匹配时对目标表进行UPDATE,无法匹配时对目标表执行INSERT。此语法可以很方便地用来合并执行UPDATE和INSERT,避免多次执行。
+-- 进行MERGE INTO操作 +postgres=# MERGE INTO products p +USING newproducts np +ON ( p.product_id = np.product_id ) +WHEN MATCHED THEN +UPDATE SET p.product_name = np.product_name , p.category = np.category WHERE p.product_name != ' play gym ' +WHEN NOT MATCHED THEN +INSERT VALUES ( np.product_id , np.product_name , np.category ) WHERE np.category = ' books ' ; +MERGE 4 +
创建一个预备语句。
+预备语句是服务端的对象,可以用于优化性能。在执行PREPARE语句的时候,指定的查询被解析、分析、重写。当随后发出EXECUTE语句的时候,预备语句被规划和执行。这种设计避免了重复解析、分析工作。PREPARE语句创建后在整个数据库会话期间一直存在,一旦创建成功,即便是在事务块中创建,事务回滚,PREPARE也不会删除。只能通过显式调用DEALLOCATE进行删除,会话结束时,PREPARE也会自动删除。
+--为一个INSERT语句创建一个预备语句然后执行它。 +postgres=# PREPARE insert_reason ( integer , character ( 16 ) , character ( 100 ) ) AS INSERT INTO tpcds.reason_t1 VALUES ( $1 , $2 , $3 ) ; +postgres=# EXECUTE insert_reason ( 52 , ' AAAAAAAADDAAAAAA ' , ' reason 52 ' ) ; +
为当前事务做两阶段提交的准备。
+在命令之后,事务就不再和当前会话关联了;它的状态完全保存在磁盘上,它被提交成功的可能性非常高,即使是在请求提交之前数据库发生了崩溃也如此。
+一旦准备好了,一个事务就可以在稍后用COMMIT PREPARED或 ROLLBACK PREPARED命令分别进行提交或者回滚。这些命令可以从任何会话中发出,而不光是最初执行事务的那个会话。
+从发出命令的会话的角度来看,PREPARE TRANSACTION不同于ROLLBACK:在执行它之后,就不再有活跃的当前事务了,并且预备事务的效果无法见到 (在事务提交的时候其效果会再次可见)。
+如果PREPARE TRANSACTION因为某些原因失败,那么它就会变成一个ROLLBACK,当前事务被取消。
+修改数据库对象的属主。
+REASSIGN OWNED要求系统将所有old_roles拥有的数据库对象的属主更改为new_role。
+为表中的数据重建索引。
+在以下几种情况下需要使用REINDEX重建索引:
+使用CONCURRENTLY选项创建索引失败,留下了一个“非法”索引。
+REINDEX DATABASE和SYSTEM这种形式的重建索引不能在事务块中执行。
+--重建一个单独索引。 +postgres=# REINDEX INDEX tpcds.tpcds_customer_index1 ; + +--重建表tpcds.customer_t1上的所有索引。 +postgres=# REINDEX TABLE tpcds.customer_t1 ; +
RELEASE SAVEPOINT删除一个当前事务先前定义的保存点。
+把一个保存点删除就令其无法作为回滚点使用,除此之外它没有其它用户可见的行为。它并不能撤销在保存点建立起来之后执行的命令的影响。要撤销那些命令可以使用ROLLBACK TO SAVEPOINT 。在不再需要的时候删除一个保存点可以令系统在事务结束之前提前回收一些资源。
+RELEASE SAVEPOINT也删除所有在指定的保存点建立之后的所有保存点。
+--删除保存点。 +postgres=# RELEASE SAVEPOINT my_savepoint; +
RESET将指定的运行时参数恢复为缺省值。这些参数的缺省值是指postgresql.conf配置文件中所描述的参数缺省值。
+RESET命令与如下命令的作用相同:
+SET configuration_parameter TO DEFAULT
+RESET的事务性行为和SET相同:它的影响将会被事务回滚撤销。
+--把timezone设为缺省值。 +postgres=# RESET timezone ; + +--把所有参数设置为缺省值。 +postgres=# RESET ALL ; +
REVOKE用于撤销一个或多个角色的权限。
+非对象所有者试图在对象上REVOKE权限,命令按照以下规则执行:
+postgres=# CREATE USER joe PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT ALL PRIVILEGES TO joe ; +授权成功后,用户joe会拥有sysadmin的所有权限。 +示例:将对象权限授权给用户或者角色。 +撤销joe用户的sysadmin权限,然后将模式tpcds的使用权限和表tpcds.reason的所有权限授权给用户joe。postgres=# REVOKE ALL PRIVILEGES FROM joe ; +postgres=# GRANT USAGE ON SCHEMA tpcds TO joe ; +postgres=# GRANT ALL PRIVILEGES ON tpcds.reason TO joe ; +授权成功后,joe用户就拥有了tpcds.reason表的所有权限,包括增删改查等权限。 +将tpcds.reason表中r_reason_sk、r_reason_id、r_reason_desc列的查询权限,r_reason_desc的更新权限授权给joe。postgres=# GRANT select ( r_reason_sk , r_reason_id , r_reason_desc ) , update ( r_reason_desc ) ON tpcds.reason TO joe ; +授权成功后,用户joe对tpcds.reason表中r_reason_sk,r_reason_id的查询权限会立即生效。如果joe用户需要拥有将这些权限授权给其他用户的权限,可以通过以下语法对joe用户进行授权。 +postgres=# GRANT select ( r_reason_sk , r_reason_id ) ON tpcds.reason TO joe WITH GRANT OPTION ; +将数据库postgres的连接权限授权给用户joe,并给予其在postgres中创建schema的权限,而且允许joe将此权限授权给其他用户。 +postgres=# GRANT create , connect on database postgres TO joe WITH GRANT OPTION ; +创建角色tpcds_manager,将模式tpcds的访问权限授权给角色tpcds_manager,并授予该角色在tpcds下创建对象的权限,不允许该角色中的用户将权限授权给其他人。 +postgres=# CREATE ROLE tpcds_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT USAGE , CREATE ON SCHEMA tpcds TO tpcds_manager ; +将表空间tpcds_tbspc的所有权限授权给用户joe,但用户joe无法将权限继续授予其他用户。 +postgres=# CREATE TABLESPACE tpcds_tbspc RELATIVE LOCATION ' tablespace/tablespace_1 ' ; +postgres=# GRANT ALL ON TABLESPACE tpcds_tbspc TO joe ; +示例:将用户或者角色的权限授权给其他用户或角色。 +创建角色manager,将joe的权限授权给manager,并允许该角色将权限授权给其他人。postgres=# CREATE ROLE manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT joe TO manager WITH ADMIN OPTION ; +创建用户senior_manager,将用户manager的权限授权给该用户。postgres=# CREATE ROLE senior_manager PASSWORD ' Bigdata@123 ' ; +postgres=# GRANT manager TO senior_manager ; +撤销权限,并清理用户。postgres=# REVOKE manager FROM joe ; +postgres=# REVOKE senior_manager FROM manager ; +postgres=# DROP USER manager ; +示例:撤销上述授予的权限,并清理角色和用户。 +postgres=# REVOKE ALL PRIVILEGES ON tpcds.reason FROM joe ; +postgres=# REVOKE ALL PRIVILEGES ON SCHEMA tpcds FROM joe ; +postgres=# REVOKE ALL ON TABLESPACE tpcds_tbspc FROM joe ; +postgres=# DROP TABLESPACE tpcds_tbspc ; +postgres=# REVOKE USAGE , CREATE ON SCHEMA tpcds FROM tpcds_manager ; +postgres=# DROP ROLE tpcds_manager ; +postgres=# DROP ROLE senior_manager ; +postgres=# DROP USER joe CASCADE ; +
回滚当前事务并取消当前事务中的所有更新。
+在事务运行的过程中发生了某种故障,事务不能继续执行,系统将事务中对数据库的所有已完成的操作全部撤销,数据库状态回到事务开始时。
+如果不在一个事务内部发出ROLLBACK不会有问题,但是将抛出一个NOTICE信息。
+--取消所有更改 +postgres=# ROLLBACK ; +
取消一个先前为两阶段提交准备好的事务。
+ROLLBACK TO SAVEPOINT用于回滚到一个保存点,隐含地删除所有在该保存点之后建立的保存点。
+回滚所有指定保存点建立之后执行的命令。保存点仍然有效,并且需要时可以再次回滚到该点。
+--撤销 my_savepoint 建立之后执行的命令的影响。 +postgres=# START TRANSACTION ; +postgres=# SAVEPOINT my_savepoint; +postgres=# ROLLBACK TO SAVEPOINT my_savepoint; + +--游标位置不受保存点回滚的影响。 +postgres=# DECLARE foo CURSOR FOR SELECT 1 UNION SELECT 2 ; +postgres=# SAVEPOINT foo ; +postgres=# FETCH 1 FROM foo ; +?column? +---------- +1 +postgres=# ROLLBACK TO SAVEPOINT foo ; +postgres=# FETCH 1 FROM foo ; +?column? +---------- +2 +postgres=# RELEASE SAVEPOINT my_savepoint; +postgres=# COMMIT ; +
SAVEPOINT用于在当前事务里建立一个新的保存点。
+保存点是事务中的一个特殊记号,它允许将那些在它建立后执行的命令全部回滚,把事务的状态恢复到保存点所在的时刻。
+--建立保存点。 +postgres=# SAVEPOINT my_savepoint; + +--回滚保存点。 +postgres=# ROLLBACK TO SAVEPOINT my_savepoint; + +--建立保存点。 +postgres=# SAVEPOINT my_savepoint; + +--回滚保存点。 +postgres=# RELEASE SAVEPOINT my_savepoint; +
SELECT用于从表或视图中取出数据。
+SELECT语句就像叠加在数据库表上的过滤器,利用SQL关键字从数据表中过滤出用户需要的数据。
+--先通过子查询得到一张临时表temp_t,然后查询表temp_t中的所有数据。 +postgres=# WITH temp_t ( name , isdba ) AS ( SELECT usename , usesuper FROM pg_user ) SELECT * FROM temp_t; + +--查询tpcds.reason表的所有r_reason_sk记录,且去除重复。 +postgres=# SELECT DISTINCT ( r_reason_sk ) FROM tpcds.reason ; + +--LIMIT子句示例:获取表中一条记录。 +postgres=# SELECT * FROM tpcds.reason LIMIT 1 ; + +--查询所有记录,且按字母升序排列。 +postgres=# SELECT r_reason_desc FROM tpcds.reason ORDER BY r_reason_desc ; + +--通过表别名,从pg_user和pg_user_status这两张表中获取数据。 +postgres=# SELECT a.usename , b.locktime FROM pg_user a , pg_user_status b WHERE a.usesysid=b.roloid ; + +--FULL JOIN子句示例:将pg_user和pg_user_status这两张表的数据进行全连接显示,即数据的合集。 +postgres=# SELECT a.usename , b.locktime , a.usesuper FROM pg_user a FULL JOIN pg_user_status b on a.usesysid=b.roloid ; + +--GROUP BY子句示例:根据查询条件过滤,并对结果进行分组。 +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY r_reason_id HAVING AVG ( r_reason_sk ) > 25 ; + +--GROUP BY CUBE子句示例:根据查询条件过滤,并对结果进行分组汇总。 +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk ) ; + +--GROUP BY GROUPING SETS子句示例:根据查询条件过滤,并对结果进行分组汇总。 +postgres=# SELECT r_reason_id , AVG ( r_reason_sk ) FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_sk ) ; + +--UNION子句示例:将表tpcds.reason里r_reason_desc字段中的内容以W开头和以N开头的进行合并。 +postgres=# SELECT r_reason_sk , tpcds.reason.r_reason_desc +FROM tpcds.reason +WHERE tpcds.reason.r_reason_desc LIKE ' W% ' +UNION +SELECT r_reason_sk , tpcds.reason.r_reason_desc +FROM tpcds.reason +WHERE tpcds.reason.r_reason_desc LIKE ' N% ' ; + +--NLS_SORT子句示例:中文拼音排序。 +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = SCHINESE_PINYIN_M ' ) ; + +--不区分大小写排序: +postgres=# SELECT * FROM tpcds.reason ORDER BY NLSSORT ( r_reason_desc , ' NLS_SORT = generic_m_ci ' ) ; + +--PARTITION子句示例:从tpcds.reason_p的表分区P_05_BEFORE中获取数据。 +postgres=# SELECT * FROM tpcds.reason_p PARTITION ( P_05_BEFORE ) ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +4 | AAAAAAAABAAAAAAA | reason 3 +3 | AAAAAAAABAAAAAAA | reason 1 + ( 2 rows ) + +--GROUP BY子句示例:按r_reason_id分组统计tpcds.reason_p表中的记录数。 +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id ; +count | r_reason_id +-------+------------------ +2 | AAAAAAAACAAAAAAA +5 | AAAAAAAABAAAAAAA + ( 2 rows ) + +--GROUP BY CUBE子句示例:根据查询条件过滤,并对查询结果分组汇总。 +postgres=# SELECT * FROM tpcds.reason GROUP BY CUBE ( r_reason_id , r_reason_sk , r_reason_desc ) ; + +--GROUP BY GROUPING SETS子句示例:根据查询条件过滤,并对查询结果分组汇总。 +postgres=# SELECT * FROM tpcds.reason GROUP BY GROUPING SETS ( ( r_reason_id , r_reason_sk ) , r_reason_desc ) ; + +--HAVING子句示例:按r_reason_id分组统计tpcds.reason_p表中的记录,并只显示r_reason_id个数大于2的信息。 +postgres=# SELECT COUNT ( * ) c , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING c>2 ; +c | r_reason_id + +--IN子句示例:按r_reason_id分组统计tpcds.reason_p表中的r_reason_id个数,并只显示r_reason_id值为 AAAAAAAABAAAAAAA或AAAAAAAADAAAAAAA的个数。 +postgres=# SELECT COUNT ( * ) , r_reason_id FROM tpcds.reason_p GROUP BY r_reason_id HAVING r_reason_id IN ( ' AAAAAAAABAAAAAAA ' , ' AAAAAAAADAAAAAAA ' ) ; +count | r_reason_id +-------+------------------ +5 | AAAAAAAABAAAAAAA + ( 1 row ) + +--INTERSECT子句示例:查询r_reason_id等于AAAAAAAABAAAAAAA,并且r_reason_sk小于5的信息。 +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' INTERSECT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<5 ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +4 | AAAAAAAABAAAAAAA | reason 3 +3 | AAAAAAAABAAAAAAA | reason 1 + ( 2 rows ) + +--EXCEPT子句示例:查询r_reason_id等于AAAAAAAABAAAAAAA,并且去除r_reason_sk小于4的信息。 +postgres=# SELECT * FROM tpcds.reason_p WHERE r_reason_id= ' AAAAAAAABAAAAAAA ' EXCEPT SELECT * FROM tpcds.reason_p WHERE r_reason_sk<4 ; +r_reason_sk | r_reason_id | r_reason_desc +-------------+------------------+------------------------------------ +10 | AAAAAAAABAAAAAAA | reason 2 +10 | AAAAAAAABAAAAAAA | reason 5 +10 | AAAAAAAABAAAAAAA | reason 4 +4 | AAAAAAAABAAAAAAA | reason 3 + ( 4 rows ) + +--通过在where子句中指定" ( + ) "来实现左连接。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) +order by 1 desc limit 1 ; +sr_item_sk | c_customer_id +------------+--------------- +18000 | + ( 1 row ) + +--通过在where子句中指定" ( + ) "来实现右连接。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk +order by 1 desc limit 1 ; +sr_item_sk | c_customer_id +------------+------------------ +| AAAAAAAAJNGEBAAA + ( 1 row ) + +--通过在where子句中指定" ( + ) "来实现左连接,并且增加连接条件。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 order by 1 limit 1 ; +sr_item_sk | c_customer_id +------------+--------------- +1 | + ( 1 row ) + +--不支持在where子句中指定" ( + ) "的同时使用内层嵌套AND/OR的表达式。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where not ( t1.sr_customer_sk = t2.c_customer_sk ( + ) and t2.c_customer_sk ( + ) < 1 ) ; +ERROR: Operator " ( + ) " can not be used in nesting expression. +LINE 1: ...tomer_id from store_returns t1 , customer t2 where not ( t1.sr_... +^ + +--where子句在不支持表达式宏指定" ( + ) "会报错。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where ( t1.sr_customer_sk = t2.c_customer_sk ( + ) ) ::bool ; +ERROR: Operator " ( + ) " can only be used in common expression. + +--where子句在表达式的两边都指定" ( + ) "会报错。 +postgres=# select t1.sr_item_sk , t2.c_customer_id from store_returns t1 , customer t2 where t1.sr_customer_sk ( + ) = t2.c_customer_sk ( + ) ; +ERROR: Operator " ( + ) " can ' t be specified on more than one relation in one join condition +HINT: "t1" , "t2"...are specified Operator " ( + ) " in one condition. +
SELECT INTO用于根据查询结果创建一个新表,并且将查询到的数据插入到新表中。
+数据并不返回给客户端,这一点和普通的SELECT不同。新表的字段具有和SELECT的输出字段相同的名称和数据类型。
+CREATE TABLE AS的作用和SELECT INTO类似,且提供了SELECT INTO所提供功能的超集。建议使用CREATE TABLE AS语法替代SELECT INTO,因为SELECT INTO不能在存储过程中使用。
+--将tpcds.reason表中r_reason_sk小于5的值加入到新建表中。 +postgres=# SELECT * INTO tpcds.reason_t1 FROM tpcds.reason WHERE r_reason_sk < 5 ; +INSERT 0 6 +
用于修改运行时配置参数。
+大多数运行时参数都可以用SET在运行时设置,但有些则在服务运行过程中或会话开始之后不能修改。
+--设置模式搜索路径。 +postgres=# SET search_path TO tpcds , public ; + +--把日期时间风格设置为传统的 POSTGRES 风格 ( 日在月前 ) 。 +postgres=# SET datestyle TO postgres ; +
SET CONSTRAINTS设置当前事务检查行为的约束条件。
+IMMEDIATE约束是在每条语句后面进行检查。DEFERRED约束一直到事务提交时才检查。每个约束都有自己的模式。
+从创建约束条件开始,一个约束总是设定为DEFERRABLE INITIALLY DEFERRED,DEFERRABLE INITIALLY IMMEDIATE,NOT DEFERRABLE三个特性之一。第三种总是IMMEDIATE,并且不会受SET CONSTRAINTS影响。前两种以指定的方式启动每个事务,但是其行为可以在事务里用SET CONSTRAINTS改变。
+带着一个约束名列表的SET CONSTRAINTS改变这些约束的模式(都必须是可推迟的)。如果有多个约束匹配某个名称,则所有都会被影响。SET CONSTRAINTS ALL改变所有可推迟约束的模式。
+当SET CONSTRAINTS把一个约束从DEFERRED改成IMMEDIATE的时候,新模式反作用式地起作用:任何将在事务结束准备进行的数据修改都将在SET CONSTRAINTS的时候执行检查。如果违反了任何约束,SET CONSTRAINTS都会失败(并且不会修改约束模式)。因此,SET CONSTRAINTS可以用于强制在事务中某一点进行约束检查。
+检查和唯一约束总是不可推迟的。
+SET CONSTRAINTS只在当前事务里设置约束的行为。因此,如果用户在事务块之外(START TRANSACTION/COMMIT对)执行这个命令,它将没有任何作用。
+--设置所有约束在事务提交时检查。 +postgres=# SET CONSTRAINTS ALL DEFERRED ; +
设置当前会话的当前用户标识符。
+--设置当前用户为paul。 +postgres=# SET ROLE paul PASSWORD ' Bigdata@123 ' ; + +--重置当前用户。 +postgres=# RESET role ; +
把当前会话里的会话用户标识和当前用户标识都设置为指定的用户。
+只有在初始会话用户有系统管理员权限的时候,会话用户标识符才能改变。否则,只有在指定了被认证的用户名的情况下,系统才接受该命令。
+--设置当前用户为paul。 +postgres=# SET SESSION AUTHORIZATION paul password ' Bigdata@123 ' ; + +--重置当前用户。 +postgres=# RESET SESSION AUTHORIZATION ; +
为当前事务设置特性。它对后面的事务没有影响。事务特性包括事务隔离级别、事务访问模式(读/写或者只读)。
+--开启一个事务,设置事务的隔离级别为READ COMMITTED,访问模式为READ ONLY。 +postgres=# START TRANSACTION ; +postgres=# SET LOCAL TRANSACTION ISOLATION LEVEL READ COMMITTED READ ONLY ; +postgres=# COMMIT ; +
SHOW将显示当前运行时参数的数值。
+--显示 timezone 参数值。 +postgres=# SHOW timezone ; + +--显示所有参数。 +postgres=# SHOW ALL ; +
通过START TRANSACTION启动事务。如果声明了隔离级别、读写模式,那么新事务就使用这些特性,类似执行了SET TRANSACTION。
+--以默认方式启动事务。 +postgres=# START TRANSACTION ; +postgres=# SELECT * FROM tpcds.reason ; +postgres=# END ; + +--以隔离级别为READ COMMITTED,读/写方式启动事务。 +postgres=# START TRANSACTION ISOLATION LEVEL READ COMMITTED READ WRITE ; +postgres=# SELECT * FROM tpcds.reason ; +postgres=# COMMIT ; +
清理表数据,TRUNCATE快速地从表中删除所有行。
+它和在目标表上进行无条件的DELETE有同样的效果,但由于TRUNCATE不做表扫描,因而快得多。在大表上操作效果更明显。
+--清空表tpcds.reason_t1。 +postgres=# TRUNCATE TABLE tpcds.reason_t1 ; + +--清空分区p_05_before。 +postgres=# ALTER TABLE tpcds.reason_p TRUNCATE PARTITION p_05_before ; + +--清空分区p_15。 +postgres=# ALTER TABLE tpcds.reason_p TRUNCATE PARTITION for ( 13 ) ; + +--清空分区表。 +postgres=# TRUNCATE TABLE tpcds.reason_p ; +
更新表中的数据。UPDATE修改满足条件的所有行中指定的字段值,WHERE子句声明条件,SET子句指定的字段会被修改,没有出现的字段则保持它们的原值。
+--直接更新所有记录的值。 +postgres=# UPDATE student1 SET classno = classno*2 ; +
通过操作列表,您只需要知道自己要“做什么”,就可以快速找到所需命令,而不需要事先知道命令名称。
+