You are on page 1of 228
aster data Contents Preface Conventions Used in This Guide Contacting Technical Support About Aster Dato. About This Document Teradata Aster MapReduce Appliance 2 Database SQL and Function Reference Version 4.6.2 — December 14, 2011 Updated versions of this guide: hp /tay erat com Aster SQL and Function Reference va V-1 SQL Commands v-3 ABORT V6 ATER INDEX 7 ALTER ROLE V-7 ATER SCHEMA ve ATER TABLE ve ALTER USER V-15, ALTER VIEW V-16 ANALYZE V-17, BEGIN V-18 case v-20 ‘CLOSE V-20 CLUSTER V-21 ‘COALESCE V-22 comrt vee copy ves CREATE DATABASE V-28 GREATE INDEX v9 CREATE ROLE V-31 GREATE SCHENA vee GREATE TABLE vee GREATE TABLE AS yaa CREATE USER V-43, CREATE VIEW V-45, DECLARE V-46 ‘DELETE. V-49 DROP DATABASE V-51 DROP INDEX. V-51 Decomber 14,2011 va DROP ROLE v-82 DROP SCHEMA v-s3 DROP TABLE v-83 DROP USER v-8a DROP VIEW v-8s END v-86 EXPLAIN v-87 FETCH v-s7 GRANT v-41 INSERT v6 MERGE v-66 MOVE v-69 REINDEX v-70 REVOKE vn ROLLBACK v-74 SELECT v-78 set v-83 show v-8s START TRANSACTION v-87 TRUNCATE vse uppaTe v-89 vacuuM v.92 wre ve94 V-2 Functions and Operators v.95 Logical Operators v.95 Comparison Operators v-96 Mathematical Operators and Functions v-97 TTigonometric Functions v-99 Shing Functions and Operators v-100 Bit ring Functions and Operators v-103, $QL/MapReduce Functions v-103, Path v-1oa Paltern Maiching Functions and Operators v-108 Datalype Formatling Functions and Operators v-121 Date/Time Functions and Operators: V-123 Aggregale Functions v-130 Aggregate Functions for Stalisics v-130 Condiifional SQL Expressions v-131 Subquery SAL Expressions v-133 V-3 Window Functions v-37 ‘Synopsis of Window Function Syntax V-137 Window Function Order of Evaluation v-138 Numbering Window Functions v-139 LEAD and LAG functions . v-145 ‘Aggregate Window Functions vos coon v-146 Repatiiioning Performance for Window Functions and S@L-MapReduce Queries... v-154 Deprecated Behavior v-154 Window Function Known Issues V-155 \-4 Datatypes v-157 List of Supported Datatypes V-157 Numeric Types v-159 Vali Database SQL and Function Reference, version 4.6.2 ‘aster data: Character Types v-163 Date/Time Types v-165 Bit Sting Types v-169 Boolean Types v-169 Binary Types v-170 Network Address Types v-172 UID Type. v-178 Type Casts v-179 V-5 Date and Time v-181 Date/Time Input Interpretation v-181 Date/Time Keywords v-182 V-6 Data Dictionary Views v-18s Introduction fo Data Dielionary Views v-186 User Related Data Dictionary Views v-186 Role-Related Data Dictionary Views v-s7 Group Membership Data Dictionary Views v-s7 Database-Related Data Dictionary Views v-s7 ‘Schema-Relaled Data Dictionary Views . v-iss SQL-MapReduce and installed File Related Data Dictionary Views v-iss Table-Related Data Dictionary Views se v-190 Column Related Data Dictionary Views v-190 Index-Related Data Dictionary Views vag Constraint Related Data Dictionary Views « vg Logical Parlifion Related Data Dictionary Views ... v-ig2 Inheritance-Related Data Dictionary Views v-193 Types Data Dictionary View v-193 Cluster State Data Dictionary Views v-193 Activity Data Dictionary Views v-194 Temporary Data Dictionary Views v-98 V-7 SQL Vocabulary v-199 Identifiers, Keywords, and Naming Conventions... v9 ‘Comments in SAL. o v-201 Value Expressions v-201 system Limits Error Codes V-205 Index van December 14, 2017 Vail \VeivDaiabase SQL and Function Reference, version 46.2 aster data This guide provides data analysts and database administrators with detailed explanations of functions, SQL commands, datatypes, and error codes in Aster Database. ‘You can download other useful taols and documents from asterdata.com/suppor. In addition, the Aster Data Resource Center at hitps://everest asterdata.com/resourcecenter provides documents, videos, and downloadable client software for various operating systems. ‘any operating stom: Lino 32 bt Operating System: usta Cporar ios 64 bit Operating System: Conventions Used in This Guide ‘This document assumes that the reader is comfortable working in Windows and Linux/UNIX ‘environments, Many sections assume you are familiar with SQL. This document uses the following typographical conventions. Typefaces ‘Command line input and output, commands, program code, filenames, directory names, and system variables are shown in a moncepaced font. Words in italics indicate an example or placeholder value that you must replace with a real value, Bold type is intended to daw your attention to important or changed items, SAL Text Conventions In the SQL synopsis sections, we follow these conventions ‘Square brackets ([ and ]) indicate one or more optional items, Curly braces ({ and }) indicate that you must choose an item from the list inside the braces. Choices are separated by vertical lines (|) December 14, 2017 ‘Aster Data proprielary and confidential V-v Contacting Technical Support Aster Data proprietary and confidential En ellipsis (...) means the preceding element can be repeated A comma and an ellipsis (,..) means the preceding element ean be repeated in a comma-separated list In command line instructions, SQL commands and shell commands are typically written ‘with no preceding prompt, but where needed the default Aster Database SQL prompt is shown: beehive=> Command Shell Text Conventions: For shell commands, the prompt is usually shown, The $ siga introduces a command that's being rua by a non-root user gas The# ign introduces a command that's being run as 100! eas Contacting Technical Support If you need the latest documentation or client software, check the Aster Data Resource Center at hitips:/ /evorest.ostercata.com/resourcocentr. Here you will find the latest documents, videos, ‘and downloadable client software for various operating systems. ‘amy Operating Syston: LUnox 32 bt operating System: ncuate porter Soewnloes mex 64 tt Operating Syston: For futher assistance, contact Aster Data technical support. Support Portal: to tp: //tays.teradata.com, Email: coresupport@asterdata.com Telephone: +1-650-273-5599 About Aster Data Aster Data provides data management and advanced analyties for diverse and big data, enabling the powerful combination of cost-effective storage and ultra-fast analysis of relational and non-relational data, Aster Data is a division of Teradata and is headquartered in San Carlos, California, For more information, go to hiip://tayseradata.com. Vevi_ Daiabase SQL and Function Reference, version 46.2 aster data Aster Data proprietary and confidential About This Document About This Document ‘This is the “Aster Data Teradata Aster MapReduee Appliance 2 Database SQL and Function Reference,” version 4.6.2, edition B035-5488-121K. This edition covers Aster Database version 4.6.2. #27284 and was published December 14, 2011. You ean open the HTML-formatted version ‘of this document by clicking the Help link ia the Aster Database AMC. Got the latest edition of this guide! This guide updated very frequently. You can find the latest edition at www.asterdaia.com/support Copyright and Legal Statements ‘The product or products deseribed in this book are licensed products of Teradata Corporation or its aftliates. ‘Teradata, Aster Data, nCluster, SQL-MapReduce, Aprimo, BYNET, DBC/1012, DecisionCast, DecisionFlow, DecisionPoint, Eye logo design, InfoWise, Meta Warehouse, MyCommerce, SeeChain, SeeCommerce, SeeRisk, Teradata Decision Experts, Teradata Source Experss, ‘Web Analyst, "More Data, Big Insights," and "You've Never Seen Your Business Like This Before" are trademarks or registered trademarks of Teradata Corporation or its affiliates. ‘Adaptec and SCSISeleet are trademarks or registered trademarks of Adaptec, Ine. AMD Opteron and Opteron are trademarks of Advanced Miero Devices, Inc Bakone and NetVault are trademarks or registered trademarks of BakBone Software, Ine EMC, PowerPath, SRDF, and Symmetrix are registered trademarks of EMC Corporation GoldenGate isa trademark of GoldenGate Software, Ine Howlett Packard ang HP are registered trademarks of Hewlett-Packard Company. Intel, Pentium, and NEON are registered trademarks of Intel Corporation IBM, CICS, RACE, Tivoli, and 2/0S are registered trademarks of International Business Machines Corporation. Linux is registered trademark of Linus Torvalds LSI and Engenio are registered trademarks of LSI Corporation ‘Microsoft, Active Directory, Windows, Windows NT, and Windows Server are registered trademarks of Microsoft Comporation in the United States and other countries. Novell and SUSE are registered trademarks of Novell, Inc, in the United States and other countries, QLogic and SANbox are trademarks or registered trademarks of QL Corporation SAS and SASIC are trademarks or registered trademarks of SAS Institute Ine. SPARC is a registered trademark of SPARC International, Ine. Sun Microsystems, Solaris, Sun, and Sun Java are trademarks or registered trademarks of Sun Microsystems, Inc, in the United States and other countries, Symantec, NetBackup, and VERITAS are trademarks or registered trademarks of Symantec Corporation or is aflliates in the United States and other countries. Unicode is a collective membership mark and a service mark of Unicode, Ine, UNIX is a registered trademark of The Open Group in the United States and other countries Other product and company names mentioned herein may be the trademarks of their respective December 14, 2017 vv About This Document Aster Data proprietary and confidential ‘THE INFORMATION CONTAINED IN THIS DOCUMENT IS PROVIDED ON AN“AS-IS" BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT APPLY TO YOU. INNO EVENT WILL TERADATA CORPORATION BE LIABLE FOR ANY INDIRECT, DIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL, DAMAGES, INCLUDING LOST PROFITS OR LOST SAVINGS, EVEN IF EXPRESSLY ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, ‘The information contained in this document may contain references or cross-references to features, functions, products, of services that are not announced or available in your country. Such references do not imply that Teradata Corporation intends to announce such features, functions, products, of services in your country. Please consult your local Teradata Corporation. representative for those features, functions, products, or services available in your country. Information contained in this document may contain technical inaceuracies or typographical errors. Information may be changed or updated without notice, Teradata Corporation may also ‘make improvements or changes in the products or services described in this information at any time without notice, If you'd like to help maintain the quality of this documentation, please send us your comments ‘on the accuracy, clarity, organization, and usefulness of this document. You ean send your ‘comments to teradata-books @liss teradata.com. Any comments or materials (collectively referred to as “Feedback”) sent to Teradata Corporation will be deemed non-confidential. Teradata Corporation will have no obligation of any kind with respect to Feedback and will be free to use, reproduce, disclose, exhibit, display, transform, create derivative works of, and distribute the Feedback and derivative works thereof without limitation on a royalty-fiee basis. Further, Teradata Corporation will be free to use any ideas, concep, know-how, of techniques contained in such Feedback for any purpose whatsoever, including developing, manufacturing, of marketing products or services incorporating Feedback. Copyright © 2011 by Teradata Corporation. All Rights Reserved wnnasterdata.com Document revision history: December, 2011: 4.6.2 vil Database SL and Function Reference, version 4.6.2 ‘aster data, This volume of the guide explains the SQL commands available in Aster Database. Later sections lis all functions and operators, date and time constraints, and exror codes. The subsections are: SQL Commands (page V-3) -Fuuetions aad Operators (page V-95) Window Functions (page V-137) Datatypes (page V-157) ‘Date and Time (page V-181) ‘Data Dictionary Views (page V-185) SQL Vocabulary (page V-199) System Limits (page V-208) Enror Codes (page V-205) December 14, 2017 va \2 Dolabase $@l and Function Reference, version 46.2 ‘aster data SQL Commands ‘Thic chaptor provides « reference for SQL aad SQL-like commands supported in Aster Database. To find the command descriptions, fallow the cross refereneas in the table below. This table also ists Aster Data / PostgreSQL syntactic eomypatibility. Table 1-1_ Aster Data/Postgresat Command Compalisility Statement ‘Supported —Supy in Notes nasier Pangresa? ABORT (page V-6) ‘Yes Yes ALL (page V-135) ‘Yes Yes ALTER INDEX (page V-7) Yes Yer ALTER ROLE (page V-7) Yes Yas ALTER SCHEMA (paze V8) ‘Yes Yes ALTER TABLE (page V.9) ‘Yes Ses ALTER USER ¢page W215) Yes Yes ALTER VIEW (page V-16) Yes Yas ANALYZE (page V-17) ‘Yes Yes ANYISOME (page W-134) ‘Yes Yes BEGIN (page V-18) Yes Yee (CASE (page V-131) Yes Yas (CHECKPOINT NO Yes CLOSE (page Vi20) ‘Yes Yes (CLUSTER (page V-28) Yes Yee COALESCE (page V-132) Ves Yas COMMENT ‘NO Yes COMMIT (page V22) ‘Yes Yee COPY (page V-23) Yes Yee CREATE DATABASE (pags V.28) Ves wee CREATE INDEX (paze V-29) ‘Yes Yes CREATE ROLE (page V-31) ‘Yes Yes (CREATE SCHEMA (page V-32) Yes Yee December 14, 2011 Aster Data proprietary and confidential V-3 Aster Data proprietary and confidential Slotement Supperied — Supporiedin Notes in ster PosigreS@QL? Database? (CREATE TABLE (page ¥-34) Yes Yes CREATE TABLE AS (page V-42) ‘Yes Yes CREATE USER (page V-43) Yes Yes CREATE VIEW (page V-45) Yes Yes DEALLOCATE ‘NO Yer DECLARE (page V-46) ‘Yes Yes DELETE (page ¥-49) Yes Yes DROP DATABASE (page VSI) Yes Yes DROP INDEX (page V-51) Yes Yer DROP ROLE (page ¥-52 ‘Yes Ye DROP SCHEMA tpage ¥-53) Yes Yes DROP TABLE (page V-53) Yes Yes DROP USER {page V-54) Yes Yes DROP VIEW (page ¥-58) Yes Yes END (page 56) Yes Yes EXECUTE No Yes EXISTS (page V-133) Yes Yer EXPLAIN (page V-57) Yes Yes ENTRACT Funetion (page ¥-124) Yes Yes FETCH (poge V- Yes Yes GRANT (page V-61) Yes ves GREATEST and LEAST (page V-133) Yes Ye IN fpage V-133) Yes Yes INSERT (page V-64) Yes Ses LISTEN No ves LIKE (page ¥-108) Yes ye Loan No Yes To land a function, use Aster Database ACT's \inet 211 command, LOCK No yes MERGE (page V-65) Yes Ne MOVE (page V-69) Ves Yes NOTIN (page V.134) Yes Yes NOTIFY No Yes NULLIF (page V-133) Yes Yes PREPARE No Yes PREPARE TRANSACTION No Yes \oE Dotabase S€ and Function Reference, version 4.4.2 ‘aster data Aster Data proprietary and confidential Statement Supporied Supporiedin Notes indster— PosigreSQL? Database? REASSIGN OWNED xO Yes REINDEX (page V-70) Yes ve RELEASE SAVEPOINT xO Yes RESET xo Yes REVOKE (page W-71) Yes Yes ROLLBACK (page ¥-74) Yes Yer SAVEPOINT No Yes SELECT (page V-75) Yes Yes SET (page V-83) Yes Yes SHOW (poge V-55) Yes Yes START TRANSACTION (page V4 Yes Yes ‘TRUNCATE (page ¥.88) Yes Yes UNLISTEN xo vies UPDATE (page V-9) Yes Yes VACUUM (page 92) Yes Yes WITH (page V-54) Yes Yes December 14, 2017 SEL Commands V5 ABORT Aster Data proprietary and confidential ABORT ABORT ~ abort the current transaction synopsis AGERE [ WORK | TRANSACTION 1; Description ABORT rolls back the current transaction aad eauses all the updates made by the twausaetion to be discarded, This command is ideatical in Belsioe to the staadagd SQL command ROLLBACK, Parameters. WORK and TRANSACTION These are optional keywords, to successfully terminate a transaction, Issuing ABORT when not inside a transaction does no asin Examples To abort all changes: apoRT: Compatibility ‘Thic command is an Aster Database extension, ROLLBACK isthe equivalent standasd SQL command. See Also. To initiate a transaction: + BEGIN (page V-I8) + START TRANSACTION «page V-87) To finish a transaction + COMMIT (page ¥-22) + END (page ¥-56) To cancel a transaction: + ROLLBACK (page ¥-72) V6 Dotabase S€l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential ALTER ROLE ALTER INDEX ALTER INDEX ~ change the definition of an index synopsis ALTER IN wnamet Description ALTER INDEX chauges the name of au existing ides, Theve is uo effect oa the stoved data, Parameters. ame The name ofan enisting index to alter, ew_name New name forthe index, Notes ‘These operations ae also possible using ALTER TABLE. The phase ALTER TNDEXis in fact Jjust an alias forthe forms of ALTER. TABLE that apply to indexes. Examples “To rename an existing index: ALTER INDEX sistyiputers RENAME TO suppliers; Compatibility ALTER INDEX isan Aster Database extusion, ALTER ROLE ALTER ROLE — change 4 database role Synopsis me [ [ wirH ] epeion PJ] ‘where option can be: December 14, 2017 SEL Commands V-7 ALTER SCHEMA Aster Data proprietary and confidential Description ALTER ROLE changes the tributes ofa database role ‘The fist variant ofthis command listed in the synopsis ean ehange many ofthe role attributes that ean be specified in CREATE ROLE. all the possible aribures are coveved, exeapt that there are no options for adding er removing memberships; use GRANT and REVOKE fr thst. Attributes not mentioned in the eomunand retain theie previeus settings. A superuser ean chaage any of these sotings. ‘The second variant changes the name of the role, Users and roles having the db_s:inin privilege ccaa rename roles. Parameters nano - The name of the role whoce attributes are to be altered. INHERIT, NOTSHERTT - These clauses alter attributes originally set by CREATE ROLE, Fer :moce information, see the CREATE ROLE reference page. nesnane - The new name ofthe role Notes Use CREATE ROLE to add new soles, aad TROP ROLE to remove a role. Px “R ROLE cannot change a role's memberships. Use GRANT and Compatitallity ‘The ALTER ROLE statement is an Aster Database extension. See Also. “CREATE ROLE” oa page V-31, “DROP ROLE" oa page V-52, “GRANT” on page V-61. “REVOKE” oa paze V-71 ALTER SCHEMA Synopsis: ALTER ACHEMA name RENENE TO newnane ALTER SCHEMA name OWN Description ALTER SCHEMA changes the defiaitiou of a schema ‘You must own the schema to use ALTER SCHEMA. To soname a schema you aust also have the CREATE privilege for the databace. To alter the owner, you ust also be a dicect ar indizect member of the nsw owning role, and you amt bave the CREATE privilege forthe databace. Parameters. ame The name ofan existing schema, \-8 Dotabase Sl and Function Reference, version 44.2 ‘aster data Aster Data proprietary and confidential ‘ALTER TABLE Rewname The new nant of the schema. The new name cannot begin with nc_. as such names are reserved for system schemas newowner The new owner of the schema See Also. “CREATE SCHEM * ou poue V-82 and “DROP SCHEMA" on page V-53, ALTER TABLE ALTER TABLE - change the definition af a table Synopsis ALTER TABLE [ ONLY ] name action [2.2 1 ALTER TABLE [ ONLY ] name RENEE mat] columa 7a new_co: ALTER TABLE name SET SCHEMA new ALTER partiti, ALTER TABLE nam ASSES pares { MOCCMPRESS | COMPRESS [HIGH | MEDIUM | LOK] 17 ALTER pastitics ference FENAME TO arw_pastitie: DETACH part itl geference INTO aew_tebl ‘where action is one of: app [ COMMMN ] seluma ereint Cena dstatype ( DEFAULT default value ] ( ood BROF [ COLUEN ] column [ RESTRICT | CASCADE ] ALTER [ COLUMN ] column T¥EE ¢ype [ USING expression 1 auren [ co 8] eeduma { SED | EROP } yeu December 14, 2011 SQL Commands V-9 ‘ALTER TABLE Aster Data proprietary and confidential au mn SET DEFAULT a [ conmar] « AED table const DROP CONSTRATIT streiat_seme ( RESTRICT | CASCADE | 35 [ HIGH | MEDIUM | LOW } where aitach_pertition list is where autach_parnition_range i START { constant [ INCLUSIVE | EXCLUSIVE | | MINVAR END { constane (INCLUSIVE | EXCLUSIVE ] | MANVALUE | where partition reference is PARTITION { petition name [. pertition name Description ALTER TABLE changes the deficition of an existing table ‘You must owa the table tose ALTER, TABLE, Tasltor the owner, you must alse bes direct or indigoet member of the naw ewning role, and that role must have CHEATE privilege oa the table. (Those restiiotions ensure that altering the owner doesit do anything you coulda’ de by dropping and roerenting the table, However, a superuser eaa alter ewaership of aay table in any way) Actions tor ALTER TABLE ADD COLUMN This form adds = new coluran tothe table, using the came syntax as CREATE TABLE. In ADD// DROP! ALTER COLUMN, the keyword COLUMN is noiseand can be omitted In ADD COLUMN and in ALTER COLUMN SET DEFAULT, the DEFAULT clause allows ‘you toensure thatthe column will be set tothe default valize ifro value is poavides! when a row is inserted or updated, The clause takes the same formas the DEFAULT slause in CREATE TABLE, Note that when you add a cohamn, all existing sows in the table are initialized with the solumn’s DEFAULT value, or with NULL if ne DEFAULT clause is specified, VF10. Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential ‘ALTER TABLE Tip In a table that coniains many rows, adding a column with a DEFAULT value may take Jong time, because Aster Database will add the defovlt valve to every existing row, Ifyou wish, to add a new column with a DEFAULT mle but not simultaneously add valves for existing rows in the tnble, then you should first performan ALTER TABLE ADD COLINO without a DEFAULT mile, ond then perform a second ALTER TABLE ALTES column_name SET PEEAULE 9 add the mle-withown inserting default valves for existing rows, DROP COLUMN This form drops a column from a able, If the table has indexes and table constraints that involve the colkunn, those will be dropped automatically, [Fa view (or any other ‘otbject outside the table) depends on the columa, then you can add the keyword CASCADE to foree the dropping of those dependent entities, A recursive DROF COLUMN operation will remove a child or descendant table's column oniy if the descendant (a) doesnot inkerit that column from any other parents and (b) never had an independent definition ofthe column, Note: The DROP COLUMN form docs net physically remeve the eclurn, but simply makes it invisible to SQL operations, Subsequent insert and update operations in the table will storea null ‘value for the column. Thus, dropping a column is quick but it will not immediately reduce the con-diske size of your table, as the space occupied by the dropped column is aot reclaimed, The space will be reclaimed aver time as existing rows are updated, [ALTER COLUMN TYPE This form changes the type of a cohumn of a table, Indenes and simple table constraints invotving the column will be automatically converted to use the new coluean type by reparsing the originally supplied expression, The optional USING clause specifies how to compute the new colin value from the el if omitted, the defaolt conversion isthe same as amassigament east from old dalatype to new. & USING clause mest be provides if there is ne implicit or assignment ast from old to new type Nose: The fact that ALTER. TYEE requires rewriting the whole table is sometimes an advantage because the resting process eliminates any dead space inthe table, For example, a retain the space accupied by'a dropped column immediatly, the fastest way is AUTER TABLE table ALTER couunal 1 TYPE anytyesr where anyco! is any remaining table column and anytyps isthe same type that column already has. Ths resuls in no semantically-visible change inthe table, but the caramel forces rewriting, which gets rd of no-longersuseful dats, SET/DROPINOT NULL These forms change whether » coluran is marked to allow sll values orto reject null values. You can only use SET NOT NULL when the column contains no cll values ADD fable constraint This form adds a new coastrint to. table using the same syotacas GREATE TABLE, Yousanmnt add DISTRIBUTE BY (or the now deprecated PARTTTT ON KEY) table constraints; see“Notes About ALTER TABLE” on page V-I3, ‘Adsing # CHECK or NOT NOLL constraint mines scanning the tble to weriffthat existing roms meet the consti In parent-child table hierarchies, adding a constraint to the parent cascades to the child om far CHECK constraints DROP CONSTRAINT This fornm drops the specified constraint on a table. You cannnt drop DISTRIBUTE BY (or the now deprecated FRRTITTON HEY) table constraints; see “Notes ‘About ALTER TABLE” oa page V-13. December 14, 2011 ‘SAL Commands W=11 ‘ALTER TABLE Aster Data proprietary and confidential ALTER TABLE test_table DROP CONSTRAINT my_conzt: NOCOMPRESS | COMPRESS [HIGH | MEDIUM | LOW] This form alters the level of fable compression to the level specified. Itcan change a compressed table to wacompressed, an ‘uncompressed table toa specified level of compressions, or a compressed table to-a different level of compression. See “Compression” on page II-§ for an overview of compression in Aster Database INHERIT/NO INHERIT This form stianges whether or not the table has an inheritance relationship with the specified parent table. OWNER This form changes the owner of the table to the specified user. Changing the O*NER, never recurses to child tables, ATTACH PARTITION This form takes an existing table and attaches it asa partition of an existing logically partitioned table. The tables do not need to reside in the same schema, Any table in.a schema other than the current schema raust be schema qualified, The database wer smst be an owner of both tables, and must possess the USAGE privilege for the schemas). ATTACH PARTITION takes as an argument either the lst of values (fora PARTITION BY LIST table) orthe rangeof values (fora PARTITION BY RANGE table) forthe partition to be created. “These may not overlap with the definitions of any existing partitions of the partitioned table Forthermore ifthe data within the table to le partitioned falls outde of the list or range of values for that partition to be created, the ATTACH will fail See ALTER TABLE, .ATTACH PARTITION (page 1-20) for more information on requirements fora lable to be attached asa partition. «Any existing constraints will be stripped from the table being attaches and replaced with the constants from the top level table in the pasttioned table hieraretiy, DETACH PARTITION ‘This form takes an existing partition and detaches it from its parent logically partitioned table, creating a new standalone table, The new table that is created will hhave the same constraints asthe top level table in the partitioned table hierarchy, The detaches table will be created in the same schema as the original parent table, unless another schema is specified, This operation is used when a subsequent operation must le perfarmed on the child pparition in isolation of ts parent (e:g, DROP), See ALTER TABLE,..ATTACH PARTITION (page 1-20) for more information. ‘ALTER PARTITION..,.NOCOMPRESS | COMPRESS [HIGH | MEDIUM | LOW] This form fakes an existing partition and compresses it (or uncompresses it) Ifthe compression is hanged oa.a partition with sul-parttions, then each sub-parttion will be compresses or “uncompressed in the sameway. See "Compression on page ILS for more information on sompression, RENAME The RENAME forms change the name of a table (or an indes, sequence, or view) oF the name of an individual coluran ina table. There is no effect on the stored data, ALTER PARTITION. .. RENAME takes an existing partition and renames it SET SCHEMA Moves the table into another schema. Associated indexes, constraints, and ‘sequences owned by table columns are moved ac well. The parameter new’_sehouna is the narne ofthe new sclera forthe table \r12. Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential ‘ALTER TABLE Parameters for ALTER TABLE ‘The parameters for ALTER TABLE are: ane The name (possibly schema-qualified) of an existing table to alter Ifouzy ie specified. oaly that table is altered. If cx. is not specified, the table and all its child snd descendant tables (if any) are updated, ‘Name of a new o¢ existing coluana. neW_codumn ‘New name for an existing colum, neW_nane ‘New name for the table, tre Datatype of the uew columa, or new datatype for an existing column, Tabis_consteaint New table constraint for the table, Sez “Notes About ALTER TABLE”, below. consteads ‘Name of an existing cousteaint to drop, See “Notes About ALTER TABLE”, below, ‘CASCADE Automatically drop objects that depend ou the dropped eotuma or coastraiat (for example, views referencing the column), BESIRICT Refuse to drap the column er constraint ifthere are aay dependant ebjeets. This is the default bebavior parent_taple The table name of the new parent table new_ounee The username of the new owaer of the table. new, schema The name of the new schema of which the table will be a member. partition_rererence The refereace to tbe individual partition of a logically partitioned table bieeauchy. The syntax is as follows: partition reference - PARTITION | partition_nams [. partition_ ams see] ‘Note that to refer toa partition several level dewa the hierarchy, you must list each of the partitions in order, separated by.” and thea the ehild partition you wish to seeess. For exaiuple, ro refer to the pastition tee lavele dawn the pasition hierarchy with the name~3001_11_30" you would reference it as (year2001.2001_ november 2001_11_30} new_partition_name The new name to give the partition, when renaming an existing pasttion. old_table_nane The name of the table to be attached to. logically partitioned table as.a new pariton new_taple_nane The uame of the new table ereated when detaching a partition, ‘Seo “CREATE TABLE" on page V-24 fora futher deseription of valid paraumaters. Notes About ALTER TABLE ‘You cannot modify a distribution key eoluran in any way, (See “Rules for distribution keys” an page I-10.) This means + ‘Theres no ALTER TABLE support for changing the DISTRIBUTE BY’ method of stable Instead, sea CTAS statement to recreate a new table with the distribution key you want. ‘+ For tables that use the legacy FRRTITION KEY eymtax + DROP CONSTRATNT cannot drop PARTITION KEY table constraints, + ADD table conetemint gamnot add FRETITTON KEY table constraints, ALTER TABLE Examples ‘To add a column oftype varchar to a table December 14, 2011 SAL Commands V=13 ‘ALTER TABLE Aster Data proprietary and confidential ALTER TABLE distributors aD couumN address varchar (30); To drop a column from a table: AMTER TABLE disteibuters DROF SLUM address RESTRICT) ‘To change the types of two existing columns in one eperation: ALTER TABLE distributors ALTER COLUMN address TYPE v: (20), ALTER COLUMM name TYRE varchar (100); ‘To change an integer column containing UNIX timestamps to timestamp with time zone visa TISING clause ALTER TABLE seles_fact ALTER COLUM eles tinestann TYFE tinestame with time zone finestenp with tine zoos second" + sales timestamp * inte: To attach a table to a logically pattioned table ms a new part ALTER TABLE distributors ATTACH BARTITION north_emeris venues ('us', ) FRG nocth america distzibuters; To detach a partition from a logically paritioned table ALTER TABLE distributors DETACH FRRTITIOM (asia) INTO asia distributors; ‘To reaame a partition: AUTER TABLE dizteibutees ALTER PARTITION (asia) RENAME 70 ‘To compress a partition: ALTER TABLE disteibuters ALTER PARTITION (asia) COMPRESS Low To rename an existing column: ALTER TABLE distributors RENAME COLIN address 7a citys ‘To rename an existing table: AUIER TABLE disteibuters RENAME TO suppliers; ‘To add not-mull constraint to a column: ALTER TABLE distributors ALTHS COLUM street SET NOT MULE ‘To remave a not-null constraint from a column: AUIER TABLE disteibuters ALTER COLUIM street DRO NOT MULL; “To add a check constraint to 2 table: \r14_ Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential ALTER USER ANTER TABLE distributors ADD CONSTRAINT =i Length (zipeed=} = 8); To remove a check constraint from a table and al its chikdren: ALTER TABLE distributors DOE ‘STRRINT zipchk; Compatibility of ALTER TABLE ‘The ADD and DROP forms conform to the SQL standard, The other forms are Aster Database exteasious ofthe SQL standard, also, the ability to specif}; more than one maaipolarioa in a single ALTER TABLE command is an Aster Database extension. ALTER TABLE DROP COLWMOV cam be used to drop the oaly column of table, leaving 4 ‘ero-columm table, This is an estension of SQL, and it violates the SQL rule thar disallow: evo-columa tables, ALTER USER ALTER USER - changes attributes of a user synopsis First variant, ALTER USER username ( [ WITH ] option [ -.. 1] ‘where option eaa be: Second variant: Third variant: ch path (To | =) { value } Example usage ALTER USER ovright PASSWORD ‘1scanFLignt': ALTER USER ovright REWME TO orvillew: ALTER USER orvillew S27 coaren_path TO capmitts, rixeaine,puBlio; Description ALTER USER changes the attributes of database uses ‘The frst variant of this command listed in the synopsis ean change many of the user atuibutes that can be speeified in CREATE USER. All the possible attributes are covered. except that there December 14, 2017 ‘SAL Commands V=15 ALTER VIEW Aster Data proprietary and confidential are no options for adding or removing mesberships; use GRANT and REVOKE for that Attributes not mentioned in the command retain their previous settings, A superuser can chnage any of these settings, Ordinary users can only change their own password ‘The second variant (RENAME) changes the name of the vser, A superuser can shange any of these settings, The current session user canaot be renamed, Connect as a different user if yon need to do that. Note that when a user is renamed, the pnssvord for that user i reset to be the same as the new wremame, It is recommended that renaming 1 user and setting a new password fora user be «done as part of the same transastion to avoid any security issues ‘The third variant sets the default schema search path ofthe user. See the description of search_patn, below, When the user subsequently stars a new session, the specified schema search path is used as his defi Parameters username - The name of the user whose attributes are to be altared, ENHER2T | norwatesrr - These clauses alter attributes originally set by CREATE USER. For ‘move information, see “CREATE USER" on page V-43, PASSWORD ‘password! - Sete theuser's password to pa sewers, newnone~ The new name of the user cch_path - Am ordeved, comms-separsted list of existing sehoma names that will be the user's default sehioma seareh path. When Aster Database ties to resalve an unqualified object ‘name, i searches thece schenaas in the order specified here. Ifthe user ereates an object without ‘qualifying it name with a seem, the object is created in her cusrent sehoma, whic, by default, is the first schema ia the search path. Tho usee ean ovettide this default using the~SET seareh_ pach” command. For more details, see “Schota Seaseh Path” ow page I-03 Compatitsility ‘The ALTER USER statement is an Aster Database extension, The SQL standard leaves the definition of users to the implementation. See Also “ALTER ROLE" au page V-7, “CREATE USER" oa page V-43 ALTER VIEW ALTER VIEW — change the definition of a view Synopsis Description ADTER TRIG changes the definition of a view. The only currently available funetionality is to resiame the view. To execute this command you must be the owner of the view: \Vr16 Database S@l and Function Reterence, version 4.6.2 ‘aster data Aster Data proprietary and confidential ANALYZE Parameters ame The same (optionally sehensa-qualified) of an existing view, ewname The naw aame ef the view. Notes In Aster Database, you cannot change the schema or owner of a view Examples To sename the view foo to bas: ALTER VIEW foo RENAME TO pags Compatibility ALTER VIEW isa PostgreSQL extension of the SQL standard, See Also CREATE VIEW, DROP VIEW ANALYZE ANALYZE - collect statistics about a database ‘Synopsis ausuxEe table [ (colum Description YZ collects statistics about the contents ofthe specified table inthe database and stoces the results in internal tables, Subsequently, the query planner uses these statistics to help determine the most efficient execution plans for queries. “You have the option of spesifving one or more columa names, in which ease only the statistics for those columns are collaeted. [f your table has child tables created through inheritance, don’t forget to include the CASCADE option. Ifthe table is» logically partitioned table, ANALYZE tomatically aets on the whole hierarchy, December 14, 2017 ‘SAL Commands V=17 BEGIN Aster Data proprietary and confidential The name of a table to analyze The name of a columa to analyze. This dafuults to all columas. Also analyzes all ehildven of the named table Outputs from ANALYZE None Notes About ANALYZE ris a good idea to ma ANALYZE periedically, or just after making major elaages in the contents ofa table, Aceursre statistics will help the planner to choose the mest appropriate query plan, and ‘hereby improve the speed of query processing. Also, the information provided by the 2xP=az21 ‘command is ealy as curroat as the last musing of sRLz=. ‘Aster Data recommends that you ma asaz‘r2e afer every batch ef writes so that the statistics are cefreshed in bulk. You should mun ANALYEE afier any running ofa cx: UPDATE, DELETE, of ALTER TABLE statement. A commoa strategy is te run .CUUM and ANALY2E once a day dusing 2 low-usage time of day. Unlike VACUUM FULL, the ANALYZE command requires ealy a.ead loek aa the target table, so iteaa mua in parallel with other activity oa the tabla, ‘The statistics collected by ANALYZE usually include alist of some of the most eomman values in esch column and a histogram showing the approximate data distibutioa in each column. One corboth of these may be omitted if ANALYZE deems them uninteresting (for example, ia a vunique-key eoluma, there are no common values) or ifthe column datatype does not support the appropriate operators. Compattitllity ‘There is no AMALYZE statement in the SQL standard, S86 Also. “EXPLAIN” on page V-57 and “VACUUM” on page V-92, and “5.3. Run ANALYZE segularly: to caste Aster Database produces the aiost optinaal query plaas” on page IL-63. BEGIN BEGIN ~ start a transaction block Synopsis SIM [ WORK | TRANSACTION 1) Description [BEGTY initiates transaction block, that js, all statements aftera DEGIN command will be ‘executed in single transaction until an explicit COMMIT of ROLLBACK is given, By default Vr18 Database S@l and Function Reterence, version 4.6.2 ‘aster data Aster Data proprietary and confidential BEGIN (without BEGTW), cach statement is executed in its own transaction and a commit is implicitly performed atthe end ofthe statement {if execution was successful, otherwise a rollback is done). In Aster Database, all statements are executed io an individual transaction by default, Growping anultiple statements together into an explisit transaction block not only provides transactional ‘atomicity, but allows transaction costs to be share across multiple statements, When executing modifying statements, it is highly recommended that these be grouped into a transaction, 2s they ‘will require replication neross Aster Database. Parameters WORK Optional keywand. Has no effet. TRANSACTION Optional keyword. Has no effect. Notes STA RT TRANSACTION has the same functionality as BEGIN, (Use COMMIT or ROLLBACK to terminate a transaction bloek: TT when already inside a transaction block will not affect the state ofthe Examples ‘To begin a uansaction block: BEGIN: Compatitollity [BEGIN is an Aster Database language extension. It is equivalent to the SQL-standard command START TRANSACTION, Click omthis link for additional corpntbilty information, Warning! The BEGIN keyword is wsed fora different purpose in embedded SQL, You are advised to be sareful about the transaction semanties when porting database applications See Also. To initiate a transaction: + START TRANSACTION (page V-87) To finish a tansaction: © COMMIT (page ¥-22) + END (page ¥-56) To cancel a transaction: ABORT (page V-6) + ROLLBACK (page V-74) December 14, 2011 SAL Commands V=19 Aster Data proprietary and confidential CASE See “CASE” on page V-L31 CLOSE CLOSE ~ close a cursor Synopsis Description CLOSE frees the resources associated with a open sursar, Afier the cursariis closed no subsequent operations are allowed on it, A cursor should be closed when itis ao longer needed, Every non-holdable open cursor is implicitly closed wten a transaction is terminated by COMMIT or ROLLBACK. « holdable cursor is implicitly claced if the transaction that created it aborts vin ROLLBACK. If the creating transaction successfully commits, the holdable cursor remains open ‘until an explicit CLOSE is executed, or the client disconnects Parameters for CLOSE name The same of an open cursor to close, Notes ‘Aster Database does net have an explicit OPEN cursor statement; a sursor is considered open ‘when itis declared, Use the DECLARE statement to declare a cursor. Examples For example, to close the eurser, mvappfeich: ee myapprecen; Compatibility CLOSE fully conforms to the SQL standard. S86 Also. “DECLARE” ou page V-46, “FETCH” oa page V5 MOVE" oa page V-69. \-20 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential CLUSTER CLUSTER ‘The CLUSTER command clusters table accondingto an index, thereby physically resorting records on disk according ton index. The goal isto unite ona single disk those records that you ‘might read together Synopsis CLUSTER tablenane [ USING indexname J Description CLUSTER instructs the database to cluster the table specified by tanlenane based om the index specified by anceuname, The index must already have been defined on rapt enans. ‘When a tables clustered, it is physically reordered based on the index information. Clustering is 1 onewtime operation: whea the table is subsequently updated, the changes are not clustered, Tint is, no attempt is made to sore new or updated rows according to their index order ‘When a table is clustered, the databace remembers which inde it was clustered by. The form CLUSTER taplenans re-clusters the table sing the same index as before, ‘When a table is being clustered, an exclusive access lock is acquired on it. This prevents any cher database operations thoth reads and writes) from operating the table until the CLUSTER: is finished Parameters fablename The name (possibly schema-qualified) of table. indexname The same ofan index. Notes In cases 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 accecs some data more than others, ancl there isan index that groups ther together, you will benefit from using CLUSTER. If you are requesting a range of indexed values from table, or a single indexed value the has alte roves that match, CLUSTER will help becauze ance 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 accesces and speed up the query. [During the cluster operation, a temporary copy of the table is ereated that contains the table data in the index order, Temporary copies of exch ince 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 inses sizes. It is advisable to rum ANALYZE on the newly clustered table to ensure tht fi make good choices. re query plans It is also important ta note tht, in the Aster Database implementation, clustering is done at the level of workers. There is no notion ofa global clustering. However, ifthe ince on which the slustering is done includes the distribution key, you create the effect of global clustering, December 14, 2011 SAL Commands W=21 COALESCE Aster Data proprietary and confidential Examples Closter the table employees on the bass ofits index employees (CLUSTER employees USING employess_inay (Closter the employees tnble using the same index that was used before: (GLUSTER employees; Compatibollity ‘There js no CLUSTER statement in the SQL standard, Our syntax is however compatible with PostgreSQL. PostgreSQL alsoallows an unqualified CLUSTER command that performs clustering on all tables in the system, aster Database does nor allow that since it may be too expensive an operation, and would disallow any access to nny ofthe tables while it rons COALESCE See “COALESCE” on page W132, COMMIT ‘COMMIT - commit the current transaction ‘Synopsis comer? {WORK | TRANSACTION 1: Description COMMIT commits the current transactioa. All changes made by the transaction become visible ta others and are guaranteed to be durable if acrash occurs. This command is equivalent to the ‘Aster Database command END. Parameters WORK Optional keyword. Has no effec. TRANSACTION Optional keyword. Has no effect. Notes [Use ROLLBACK to abort transaction, Issuing COMMTT when not inside transaction does nee harm. Examples ‘To comit the current tanssetion and make all changes permanent: \-22. Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential copy Compatibility ‘The SQL standard oaly specifies the two fonms COMMIT and Com command is fully conforming. WORE. Otherwise, this See Also To initiate a transaction; + BEGIN (page V-I8) + START TRANSACTION épage V+ To finish a transaction: + END (mage V-56) To cancel a transaction: + ABORT (page V-6) + ROLLBACK (page V-74) COPY ‘COPY — copy data between a client and a table + Synopsis (page ¥-23) + Deseription (page V-24) + Parameters for COPY (page V-24) + Notes About COPY (page ¥-26) + Input Femnats for COPY (page V-26) + Example Use of COPY (page + Conspatibilty of COPY (page V- Synopsis. Copy Into Aster Database ory toblenan= { ( colum [, -..1 ) 1 FROM STORN Twa] ( DELIMITER [ aS ] ‘delimiter’ ] (wae Pas ] ‘null steing' J (Ces Cguore [as] ‘guctet | [ Escare [aS ] teecape' J] 1 | avroganrition 1 [ nos sanoas Lingo { eeostablename | NOWMERE } ] [wrrw eapet label ] LERRoe Lim {Limit | minimereD } ] i December 14, 2017 ‘SAL Commands V-23 copy Aster Data proprietary and confidential Copy from Aster Database: COPY tablename ( ¢ column [, 662 1 70. STDOUT arta] t LIMITER [ AS] “delimiver’ 1 UMULE PAS] ‘null scring' 1 (oe [quore | as 1 tquotat } [ESCAPE (AS 1 ‘escape’ 111 Description COPY moves data between Aster Databace tables and a remote client (STDIN/STDOUT}, win the connection between the client and the server. Specifically, COPY TO copies the contents of 9 table to standard output, while COPY FROM copies data from standard input to a table (appending the data to whatewer isin the table already) alist of columns is specified, COPY will only copy the data inthe specified cokarans to or from the source: If there are any columns inthe tble thw are oot inthe column Lis, COPY FROM will insert the defnult value of ITLL for those columns. ‘To copy data from one or more files into Aster Database, you can also use the nsluster_loader Utility, a5 explained in “neluster_loader Client-Side Loading Too” on page U-130, The nelwster_ Joarer tool uses the COPY command te perform the data loading. Parameters for COPY Table 1-2 Paramsters for COPY ——— coluna sro sToour delimiter null string cov guste ‘The name of aa existing table ‘Anoptional list of columns to be copied. If ao coluaaa list is specified, all columns of the table will be copied. Specifies that input comes frum the clieat application, Specifies that output goes to the client application. ‘The single character that sepasates columns within each row (Line) ofthe file. ‘The default is a tab charactor in text aiede, a comuna ia CSV mods, ‘The sting that represents a aull value, The defuult is 'N thackslash-N) in text ‘mode, aad aa empty value with no quotes ia CSW mode. You might prefer aa empty string even ia text mode for cases where you doa't want co distinguish alls from empty strings. ‘Whea loading aay aoa-CSV delimited fowmuat (2.2. TSV), you cau ensily load files thet contain ompry strings (that is, files that don’t use the typical "N" 10 sepreseat nulls) To do this, use Cony With the nuit keyword, followed by two ddouble-quote characters. That is, the argumeat looks Like: pall" Note: Whon using COPY FCM, any data item that matelos this string will be ‘stoved 252 oull value, so you should make sure hat itis not a string thst might otherwise occur in the input Selects Comma Separated Value (CSV) mode tby default, the input is expected lterpreted using the text foumat described below! Specifies the quotation character in CSV mode, The default is dauble-quete. \-28 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential copy Zap output (OPARTETION LOG ERRORS INTO "errorcanrename ‘BITH LABEL om ERRORLIMET Limit Specifies the character tat should appear before a QUOTE data character vale in CSV mode. The defmult isthe QUOTE value (usally double-quote). ‘On successfil completion, a Ci 'Y command retums a command tag of the form: Wheve count isthe umber of tows copied. Auromutically partitions data during copying, With this fearure enabled, Aster Database automatically routas each cow within a logical partition hierarchy down to the apprapeiste child table. Logical partitioning is done based on the check constraints ofthe target table. See “Autopartitioning” ou page I-15 lncluding the LOG ERRORS clause activates erzor logging. With evror logging enabled, the COPY couumand tolesates poorly formatted iapun data like this: (COPY Logs each malformed row to the appropsinta lead exter logging table aad continues loading additional (correctly formed) rows in the current load job. Aster Data tefers to this as “ecror logging” (Ousiting the LOG ERRORS phrace disables ersor logging. With earor logging disabled, the COPY operation fails immodiately whea it acouaters a malformed row, With error logging disabled, COPY fails or succeeds in an atowaie fashiow: either all rows are copied, or none are. This festure is also available in the nefuster_foader tool as showa ia “acluster_ loader Clieat-Side Loading Tool” on page I T30, By default, malformed rows for distributed tables go into table n<_ eerorteble_pert table, and malformed rows for replicated tables go inte the ssesteble cep table. Optioaally, you cau create your own load extoz Toagiag tables, a explained ia “220 exrezteblenane”, below. The schema far error logging tablas is shown in “Load Eeror Logging Tables" on page V-19¥. ‘To see the aumber of sows that loaded or failed teload, query the load exoe ‘Mitsties tables nc_211_ezecrloguing_stets adnc eee sercelegging state, For more information, sea "Load Evel Statistics Tables on page V-197 10g ERRORS INTO ‘errosteblensme’ specifies che error loggiag table iato ‘which malformed rows should be copied together with detailed error information, You can specify aay table that inherits from the appropiate detiukt abla,ne ezeostable part table, ofne errortekle rep), See~Crostiag a Load Error Logging Table" on page V-197. Iftuco "errortebl=asne' is not specified. then malformed rows go into the default tables as explained in 20 ERRCRE, above, ‘WITH LABEL abel’ tags failed sows with label. The label ig useful for finding ‘you failed rows ia the oaroy logging table and for fading statistics about the load attempt in the ne_all_errorlogging_stats table. If you do not provide a label, Aster Database uses a statement identifier as the label valve. (There's one ‘statement identifier por COPY coaunand; iftheve s one map eatry for many Input files, chon you'll have a uaique statement identifier per input fle.) NOWHERE inswwets the COFY command to discard all malformed rows (and continue lasding cosrectly formed saws). ERRORLIMIT followed by aa iateger Limit value sets the maximum aumber of allowed failed rows for this COPY job before itis foreed to fail. ERRORLIMIT UNLIMITED tells the COPY to coutiaue maning, regardless of the aumber of crror rows it encounters, Stacemout failure is stom; the whole taacaetion aborts if the Limit is reached. This valve is a global limit: Aster Database aggregates the errors detected across all partitions, December 14, 2017 ‘SAL Commands V-25 copy Aster Data proprietary and confidential Notes About COPY ‘When a COPY operation fails, any rows it had inserted are removed, but they still occupy disk space, This may amouat to a considerable amoust of wasted disk space ifthe failure lappewed ‘well into a lage copy operation You may wish to invoke VACUUM, to recover the space. Input Formats for COPY Input can be: ‘+ “Text Formatted Input ta COPY™ on page V-26, or ‘+ °CSV Formatted Input to COPY" on page ¥-27 ‘Text Formatted Input to COPY ‘When COPY is used without the CSV option, the data read is interpreted as a tent file with one Age per table row: Colurans in a cow are separated by the DELIMITER character, The columa ‘values themselves are strings of each attribute's datatype. The specified uull string is used ia place of coluaans that are aul. COPY FROM will yaise aa ewor if any line ofthe input fle ‘contains aloes oy fewer columns thau are expected, End of data can be represented by a single line comtaining just backslash-petiod (\). Backslash characters (\) may be used ia the COPY data to.quote data characters that mab otherwise be taken as sow or coluan delimiters. In payticular, the following charactegs nuust be ‘preceded by a backslash if they appear as part of a colurun value: backslash itself, newline, ‘carriage rerum, and the cuszeat delimites character. Rote matches the iaput against the null string befoce removing backslashes. Thesefave, a aul string such as ‘N cannot be confused with the actual data value ‘Ni (which would be represented 26) ‘The following special backslash sequences are recoguized by COPY FROM. Table 1-3 Backslash sequences recognized by CORY FROM ‘Sequence Represents b Backspace (ASCH) f Form feed (ASCII 12) ‘ Newline (ASCTI 10) i" Comtiage rom (ASCII 13) Tub (ASC) Any other beckslashed charactor that is not mentioned in te above table will be take to seproseat itself. However, boware of adding bnekslashes uanoeessarify, sinco that might accidentally produce a sting matelting the ead-of-deta marke (\) os the woll string (3 by ") December 14, 2017 ‘SAL Commands V-39 (CREATE TABLE Aster Data proprietary and confidential In the following example we use a PARTITION BY RANGE clnuse to create a fact table trans ‘with four daify child partitions using automatic logical partitioning (strictly spenking. the frst pation is catcheall for older records} ceans( id ine, sountey varchar, te timestamp} DISTRIBUTE BY HASH (id) PARTITION S¥ BANISE (ES) ( FARTITION cldresceds( END ‘20i{-04-01" ), -~ everything pe-20tt PARTITION janOl_2011( END ‘20i1-01-02" ), ERRTITION 202i ( Exp 2011-01-03" ), PARTITION Jan03_20i1( sup ‘20i1-01-08" ) Mi ‘This example defines. check column constraint did integer « nee verchar (40) disteibutess ( (gig > 190), ‘This example defines a check table constraints CREATE DIMENSION TABLE distributors ( did integer, pene versher (40) CONSURAINE coni CHECK (did > 100 AND name <> 1) ae ‘This example creates a dictibuied dimension mble, di st rabutors, and distributes it based on its distributor id (a2 a) values: REATE DIMENSION TALE dizteibuters ( id integer, pene varchar (40) 3 EISTRIEVIE: EY HASH (did ‘This example defines two NOT. NOLL colurmn constraints onthe table sist inutors, one of which isesplicily given aname: CREATE DIMENSION TaBue distributors ( sid integer CONSTRAINT ac_aull NOT mL, name varchar ((O) NOP MULL ae Compatibility ‘The CREATE TRELE command conforms to the SQL standard, with exceptions listed below. Column Check Constraints The SOL standard says thar CHECK column constraints may aly refer ro the column they epply to: oaly CAECK table constraints may refer to multiple cofumas. Aster Database does not enforce this restriction; i treats column and table check: constraints air ayia Constraint The run "constant (scrually « noo-constaint)is an Aster Database extension o the SQL standard thet is included for compatbiliry with some other database \=40 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential (CREATE TABLE systems (and for symmetry with the HOT NULL constraint), Since it is the deft for any column, its presence is simply noise Distribution Key Constraint The distribution key constraint is an Aster Database extension, PITION KEY Constraint The deprecated PARTITION HEY constmint js an Aster Database extension See Also. “DROP TABLE” oa page W-52 A Note on Unique Constraints ‘Unique constraints ensure that the data contained in a coltunn or a group of sofumns is unique ‘with respect to all the rows in the table, The syatacs is: products ¢ preduct_no integer UNIguE, Rene text, price numeric DISTAISUIE Br HASH (product_nc) ‘whea written as a column constraint, and: CREATE ERCT TABLE products preduct_no integer, price nunesic, GaEgUE (preduce ney a DISTAISUTE Br HASH (product_nc} wheawritien as a table constraint If a mnique constraint refers toa group of columns, the columns are listed separated by commas: GREATE ERCT TABLE exemple ( = intesre, B integer, & integer, umrgue (a, cb ) DISVAIOUTE BE HASH (4) “This specifies that the combination of values in the indicated eolumns is wnique aeross the whole table, though any one ofthe columns need aot be and ordinarily is) wnique, ‘You can assign your own name for a unique eoastmint, in the usual way” CREATE CACY TABLE products { product no integer CONSTRAINT must be di pent UNIQUE, peice nunesic d DISTRIBUTE BY HASH (prod .ct_no) December 14, 2011 ‘SAL Commands W=81 (CREATE TABLE AS. Aster Data proprietary and confidential In general, a unique constmint is violated whea there are two er more rows in the table where the ‘values of all of the coturans incfuded in the constraint are equal. Flowever two mull values are not considered equal in this comparison. That means cvea in the presence of a unique constraint it is possible to store duplicate rows that contain a null value inat least one of the constrained columns. This behavior conforms to the SQL standard, CREATE TABLE AS CREATE TABLE AS - define a new fable from the results of a query Synopsis GREATE (| FACT | DIMENSION | TAR: (column name aata_type | tapie_constraint | tablename ( [ 1a ( DISTRIBUTE BY | HASH ( column_name ) | REPLICATION } ] [ STORAGE ( ROK | oarmor ) ] f COMERESS [ HIGH | MEDIUM | LOW) ] AS query Description CREATE TABLE AS creates a table and fills it with data computed by a SELECT command, ‘The table columas have the names aad datatypes associated with che output columns of the SELECT (except that you can ovenride the column names by giving aa explicit ist of new colum names). When you creste atable in Aster Database, you should declare it tobe a fact sable or a dimension cable. See “Fact Tables and Dimension Tables" oa page T-4. {Af the target table schema isn’t explicitly specified, it willbe inferred from the outpur columas of the SELECT clause, Eveu if you do aot specify aames for the aew tables columns, you ean sill specifY-a column as the diwibution key. CREATE TABLE AS creates now table and evaluates the query just ouce to fillhe new table, ‘The new table does nor wack subsequent changes to the source tabies of the query. Nowe tat CREATE TABLE AS is aot supported with logically pasttioned tables (tables created with PARTITION BY HASHor PARTITION BY RANGE). To woek around this, see Creating a logically partitioned table fiom data is another table (page 1-23). Warning! Whea you cainve TaSiE ... as SeLece, Aster Database nuns auaLyze onthe new table afier inserting the data. A read lock is placed on the new table while ananz= rans. \n82. Database @l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential CREATE USER Parameters table_nane column_nane “This eptioaal clause specifies whether the aw table sould be created 42.4 {aet table ar a dimension table. IF this elause is not specified, the new table ‘will be a fact table. See ~Fact Tables and Dimension Tablas" on page [t ‘Note that the distribution of the table may affect the performance of join ‘operations, For move details on distribution, see “Distributing Tables" on page 19. ‘The name of the table ta be ereated. ‘The name of aeouma te be exeatad ia the wew tabla. aata_type “The datatype of the column query A SELECT command. The following restriction applias: ‘The column referenced in the DISTRIBUTE BY clause aust be among the ‘columuts in the SELECT clause of the query. DISTRIB ‘The DISTRIBUTE BY clause specifies either hash distribution (with a clause ‘You must perform all updates and deletes inthe same vansaction in which you declared the ‘cursor. Iaside the curser, you canst see the results of your updates aad deletes: youcaa only sro forward in an updatable curso. For a eursor to bo updatable, it must bea NOSCROLL eursor and the SELECT statemont in ‘he curser declaration muust follow the rules shown below: + Tr not contain a join (that is, it must select from only a single table, and that table amist aot bbe joined to teal). + Traut aot eantain ax ORDER BY clause, + Iraust specify table, not a view. (Wiews are read-only.) + Tramst aot eantaina GROUP BY clause. Notes on DECLARE Unless WITH HOLD is specified, the cursor crested by this command can only be used within the current transaction. Thos, DECLARE without WITH HOLD ismseless ontside 9 transaction block: the cursor would survive only to the completion of the statement. Therefore Aster [Databave reports an error ifthis command is used outside a transaction bloek. Use BEST, COMMIT and ROLLBACK ta define a transaction block, I WITH HOLD is specified and the transaction that created the cursor successfully commits, the cursor ean continue to be accessed hy subsequent transactions in the same session. (But ifthe creating transaction is aborted, the cursor is removed.) A cursor created with 8TT# HOLD is closed whea an explicit CLOSE command is ised aa it, or the session ends. ‘The SCROLL option should be specified when defining a-cursar that will be wsed to fetch backwnrds. This is required by the SQL standard, 1f100 SCROLL is specified, then backward fetches are disallowed in any case. Updatable cursors are always 80. SCROLL EuROTs ‘The SQL standard only makes provisions forcursors in embedded SQL. Aster Database dees aot implement an OFF statemtent for cursors: a cursor is considered to be open when it is declared. \-48 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential DELETE Examples ‘To declare a cursor DECLARE Tilmesr CURSOR FOR SELECT * FROM rina; ‘Seo “FETCH” out page V-37 for more examples of cursor usage. Compatibility of DECLARE ‘The SQL standard allows cursors oaly in embedded SQL and in modules, Aster Database permits cursors to be used interactively, See Also “CLOSE" ou page V-20, “FETCH” oa page’ and “MOVE* oa page V-69, DELETE DELETE - delete rows of a table Synopsis DeLers snow [ owny ] table [ verus usinglist 1 [ WHERE senaitien | WHERE CURRENT OF cursor name J} Description DELETE deletes rows that satisfy the WHERE clause from the specified table Ifthe laws is absent, the effect is 0 delete all rows in the table, The reset is «valid, but empty table By default, DELETE will delete rows in the specified table and all its child tables. Ifyou wish to delete only from the specific table mentioned, you must use the ov" clause, ‘The USING clause eam be used to delete rows in a table using information contained in other tables inthe database, ‘You must have the DELETE privilege for any table in the TSTR cl T privilege on the table to delete from it, as well as the se or whose values are read in the condition December 14, 2017 ‘SAL Commands V-49 DELETE Aster Data proprietary and confidential Parameters for DELETE OnLy Tf specified, delete rows from the aamned table oaly. ‘Whon not specified, any tables inheriting trom the named table are also processed. tanie ‘The name of an existing table, usingiist A list of table expressions, allowing columns from other tables to appear in ‘he WHERE condition. This is similar to the list of tables that can be specified in the FROM clause of a 1 statement; foe example, an ang ‘for tho table nam ena be specified, ‘Do not repeat the target table in the uxingl ist, unless you wish ta set up a self-ji. condition ‘A Boolean-returning expression that determines which rovs will be deleted. Hf usinglist specifies mumltiple tables, a join predicate specified ia senator mst include the disuibution key columns of all included rubles, cursor_name ‘The name of the cursor to use ia a wnese ‘= oF condition, The row to be deleted isthe one most recently fetched from this cursor. The eursor saauat be & aoa-grouping query oa the nezeTE’s tuzget table, Note that HERE CURRENT OF eannat be specified together with a Boolean eeadition. See DECLARE for move information about using cursors with WHERE Outputs (On successful completion, 9: command retums a command tag of the form The count isthe number of rows deleted. If count is 0,no rows matched the condition (this isnot considered an error) Notes on DELETE Astor Database lets you reference columas of other tables in the WHERE eoadition by spocifyiag the other tables in the USING elause, For example, to delete all films produced by a given produeer, ono might do DELETE FROM films TSTNS producers WHERE promicer_id - proqucers.id AND producers name - tanith’? ‘What is essentially happenig here isa joia between films and producers, with all suossssfully Joined fils rows being marced for deletion, Examples Delete all films but musicals: DELETE GRC Eilme WHERE kind © 4 (Clear the table flrs Deners snow films; \=50 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential DROP INDEX Compatibility of DELETE This command conforms to th reference ether tables in the )L standard. except thatthe USTIYG clause and the ability to Lause are Aster Database exteusions. DROP DATABASE DROP DATABASE ~ remove a database Synopsis Description DEGE DATABASE drops a database, It removes the sataleg entries for the database and deletes the directory containing the data, It can only be executed by the database owner, Also, if cannot beexecuted while you oranyone else is connected to the target daiabase, SE cannot be undone. Us Parameters tor DROP DATABASE ‘ame "The name of «database to remove, Notes DROP DATABASE cannot be executed inside a transaction block, “This command eanast be executed while connected tothe target database Compatibility ‘There is eDROP DATABASE statement inthe SQL standard. See Also “CREATE DATABASE” on page V-28. DROP INDEX DROP INDEX — remove an index Synopsis December 14, 2017 ‘SAL Commands V-81 DROP ROLE Aster Data proprietary and confidential Description DROE INDEX drops an existing index from the daiabase system. To execute this command you ‘ust be the owner of the index. Parameters for DROP INDEX fame “The name of an index toemove, CASCADE ‘Awtomatically dop objects that depend on th inex. RESTRICT ‘Refuse to drop the inex if any objects depend oni. This isthe def Examples ‘This command will seaiove the iudex title_ids. DROP INDEX title_iax Compatibility DROE INDEX isan Aster Database language extension. There are no provisions for indexes in the SQL standard. See Also. “CREATE INDEX” on page DROP ROLE DROP ROLE - remove a tole from Aster Database Synopsis Parameters name - The mame of a role to remove. Examples To drop a aie: paor sox ny_sdminss Description DROP ROLE removes the specified roles). Te drop a mle, you must be a superuser A role cannot be removed if ti sil referenced in any datshave of the cluster; an error will be raised if so, Before dropping the role, you must drop al the abjacts it owns (or rexssign their ‘ownership) and revoke any privileges the role bas been granted \52 Database S@l and Function Reterence, version 4.6.2 aster date Aster Data proprietary and confidential DROP TABLE However itis not necessary to remove role memberships involving the mle; DROP ROLE automatically revokes any memberships of the target role in other roles, and of other users and soles in the target role. The other users and roles are not dropped nor otherwise affected. ‘Compatibility ‘The SQL staudard defines DROP ROLE, but it allows oaly one sole to be dropped sta time, and it spaeifies different privilege requisements than Aster Database uses, See Also. “CREATE ROLE” on page V-31 and "ALTER ROLE” on page V-7. DROP SCHEMA Synopsis EXISTS ] name [, RESTRICT 1 Description DROP SCHEMA removes schemas from the database, ‘Aschema can only be dropped by its owmer, Note thatthe owner ean drop the sehema and thereby all contnined objects) even if he does not own some of the objects within the schema Parameters IF EXISTS. Do not drow an exror ifthe schoma does not exist. A notic is issued in this case name The same of a schema, CASCADE Automatically deop objects (tables, funetions, ote-}thet are contained in the schema, RESTRICT Roftise ro deop tho schoms ifiteoatains any objects. This isthe default See Also. “CREATE SCHEMA’ on page V-32 and “ALTER SCHEMA” on page ¥°S, DROP TABLE DROP TABLE ~ remove a table Synopsis DROP TABLE [ TF EXISTS | mame (, +++] [ CASCADE | RESTRICT I+ December 14, 2017 ‘SAL Commands V-53 DROP USER Aster Data proprietary and confidential Description Ror TASLE removes tables from the database. Only its owner may destroy a table. To empty 2 table of rows, without destroying the table, use TAUHICATE or DEE: DAoe TASLE always removes any indexes and constnints chat oxic for the target table For logically partitioned tables, issuing once sa=2e drops the top level table and all child pparitioas as well. For pareatchild tables cxeated through inheritance, you aust issue DROF [ZRELE. . .CASCADE in oxder to doop the child tables in addition to the pare Parameters IF EXISTS ‘Do ot throw an error ifthe table dacs not exist same ‘The name of the table drop. CASCADE Automatically drop objects that depend on the table RESTRICT Refuse to drop the table if any objects depend om it. This is the deiut Examples “To destoy two tables, fms and distributors: peop TARLE tiims, aistriputors Compatitollity ‘This command conforms to the SQL standard, except thatthe standard only allows one table to be dropped per command. See Also. “TRUNCATE” on page V-88, “DELETE” on page V-49, and “CREATE TABLE” on page V-24 DROP USER DROP USER — delete a user from Aster Database Synopsis Example Usage DROP USER wright; Description DROP USER reaioves the specified user(s) To drop a user, vou must be a superuser, ‘A user cannot be removed ifit is stil referenced in any database of the cluster; an erzor will be snised if so. Befowe dropping the user, you must drop sll the objects it owns (or reassiga their ownership) and revoke any privileges the user has been granted \-54 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprielary and confidential DROP VIEW However it is not necessary to remove role memberships involving the wser; DROP ROLE automatically revokes any memberships of the target user in other roles. The other roles are not dropped nor otherwise affected. ‘Compatibility ‘The DROP USER statements an Astor Database extension. The SQL standard leaves the dafinition of users to the implementation, See Also. “CREATE USER" on page V-43,"REVOKE” on page V-71, and "DROP ROLE” on page 52, DROP VIEW DROP VIEW — remove a view synopsis DAOP VIEW ( TE EKITS J name L. vsT [68903 STRICT J Description BROP view drops au exist view. view, To exseute this command you aut be the owner of the Parameters IF EXISTS. Do not throw nn error if the view dees not exist A notice is issued in this ace, ame The name (optionslly schema-qualified) of the view to remove, CASCADE Automatically drop objects that depend on the view RESTRICT Do not simp the view if other objects depend om it This isthe default behavior Examples ‘This command will semove the view called kinds: DROP VIEW kinds; Compatibility ‘This command conforms to the SQL standard, except that the standard only allows one view to bbe dropped per command, and apart from the IF EXISTS option, whieh is an extension, See Also. ALTER VIEW, CREATE VIEW. December 14, 2017 ‘SAL Commands V-55 END Aster Data proprietary and confidential END END — commit the current transaction synopsis ESD [ WORK | TRANSACTION 1; Description ‘END commnits the eurreat transaction. All changes made by the transaction become visible 19 others and are guaranteed to be durable if a crash oceurs, This command is aa Aster Database ‘exteasion that is equivalent to COE Parameters. WORK oF TRANSACTION Optional keywords, They have no effect, Notes Use ROLLBACK to abort a transaction. io when not inside a transaction does no has. Issuing: Examples ‘To commit the current transaetion and make all changes permanent END: Compatibility ‘END is an Aster Databace extension that provides functionality equivalent to Cosa specified in the SQL standacd See Also. To initiate a transaction: + BEGIN (page V-I8) + START TRANSACTION ipage V-87) ‘To finish a transaction + COMMIT (page ¥- ‘To cancel + ABORT (page V-6) + ROLLBACK (page V-78) \-56 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential FETCH EXPLAIN EXPLAIN — show the execution plan of a statement synopsis EXELAIN statement Description ‘This command displays the execution plaa thet Aster Database wies for the supplied statement, ‘snd cost estiuates for each of the steps ofthis execution plan. The execution plan displays infomation oa the exact SQL statemiears executed in onder to satiaty the user-given query, including whether aetwork transfers of data ae cequired and for what purpose, The plan also ‘provides the location at which each step is exzcuted, and the low-level algorithius used to eRecUNe a step atthe slowest node ZXCPLAZN itzelf dows not execute the statemeat and therefore ‘has no side-effects (2.2. EX 00 8 CREATE TABLE statement dows not create the table), For more details oa EXPLAIN, plaase se2 “7. Tuning Techaiques Ill: Read the EXPLAIN Plan” ‘6a page LI-73, whicl peowides detailed documentation oa inteapeetiag EXPLAIN output, Parameters. statement A statement whose execttion plan you wish to see. You cannot run EXPLAL DELETE statement, ona Notes ‘The statement whose executioa plan you wish to see should be both syntactically and semantically courect outside the EXPLAIN context, For instance, you cannot nun EXE SELECT statement ana table that does aot exist. ‘Compatibility “There is no EXPLATN statement defined in the SQL standard, S86 Also. “ANALYZE” ou page V1 page I-73, 7, Tuning Techaiques II: Read the EXPLAIN Plan” oa FETCH FETGH — retrieve rows from a query using a cursor Synopsis WENCH [ directs: 2 FROM | aM} ] curse where direction ean be empty er one af December 14, 2017 ‘SAL Commands V-S7 FETCH Aster Data proprietary and confidential PRIOR Description FETCH retrieves rors using a previously-ereated cursor ‘A cursor lng an associated position, which is used by FETCH, The eursor position cas be before the first row ofthe quory result, on any’ partioulas sow of the result, at after the last row of the result, When erated, a cwssor is positioned before the fist row, Affer fotehing some sows, the ccursar is positionad on the vow most secently souieved. If FETCH runs off the end of the available rows thea the cursor is laft positioned after the last row. or before the first row if fetching backward, FETCH ALLor FETCH BACKWARD ALL will always leave the cursor positioned afer the lact sw or bofore the ust ow. ‘The forms NENT, PRIOR, FIRST, LAST, ABSOLUTE, RELATIVE fetcha single sow after maving the cursor appropriately. there is no such sow, am empty result is returned. and the ‘cursor is left positioned befoce the first zow or affer the last row as appropiate. ‘The forms using FORWARD and BACKWARD rewieve the specified number of ows moving in the forward or backward directioa, leaving the cursos positioned on the last-roturned row (oF aferbofore all rows, ifthe cout exceeds the aumbor of rows available). RELATIVE 0, FORWARD 0.and BACKWARD 0 alll zequest fetching the curreat row without moving the cursor, that is, ve-fetching the most recently fetched sew. This will succeed ualess the ‘cursor is positioned before the first row or after the last sow: in which case, no row is returned. \H58 Database S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential FETCH Parameters aiveetion ‘veetion defines the fetch diveetiou and aumber of cows to feteh. This, [parameter can have-one of the valuas listed below. zExT ‘Fatel the next row. This is the default if diectian is omitted. PRIOR ‘Fatelt the prior raw, FIRS? ‘Fateh the first row of the query (same ac ABSOLUTE. 1) Last ‘Fateh the nat gow of the query (sameas ABSOLUTE —1). ABSOLUTE count Fetch the count row of the query, or the abs(count)" row from the ead ‘if count is negative, Position before frst sow or after Last cow if count i out ‘of range; ia particular, ABSOLUTE 0 positians bafore the first row, HELATIVE count Fetch the count succeeding row. or the abs{count " prior rowif count ‘is megative, RELATIVE Q.e-fetches the cusreut cow, if any. ALD ‘Fetch all remaining sows (samme as FORWARD ALL. FORWARD Fateh the west row (same a: NEXT). FORWARD cout Fateh the west couat cows, FORMARD 0 re-fetehes the euereat sow. FORWARD ALL Fetch all remaining sows, BACEWARD Fateh the prior row (same az ERIOR). BACEWARD count ‘Fetch the prior count rows (scaaning backwusds), BACKWARD Ove-fetches {he cuiront rou: EACEWARD ALL ‘Forel all prior rows (seaauiag backwards), ‘count ‘count is a possibly-signed integer coustaat, detemining the leeation or suber of rows to fetch. If you supply a connt value alone, without FORWARD or any other keyword, Aster Database teats itas a FORWARD count) ‘i you supply a negative eound valuo with FORWARD of SACKWARD, you severse the sanse of FORWARD or BACKHARD. “An open cursor's name. Output ‘On successful completion, a FETCH eommand returns a command tag of the form: rwehere count is the number of rows fetched (possibly ze10). Notes ‘The curzoy should be declared with the SCROLL option if oue intends to use any vasinuts of FETCH other thaa FETCH NEXT og FETCH FORWARD with a positive cou. For simple ‘queries, Aster Databaze will allow backwards fetch trou cursors not declared with SCROLL, bur this bebavior is best aot reLieé oa. [Fthe cussor is declared with NO SCROLL, no backward fetches axe allowed, ABSOLUTE fetches are aot any fister than navigating to the desired row with a relat the underlying implementation rust traverse sll the iarermediate sows anyway. Negative absolute fetches are even worse: the query aust be read to the ead to find the last wr, and thea tuswersed backward from there. However, rewinding to the start of the query (as with F=TCH ABSOLUTE 0) is fast ‘Upéating data via a curcoris exerently aot supported by Aster Database. December 14, 2011 SAL Commands V-59 FETCH Aster Data proprietary and confidential DECLARE is used to define a cursor. Use MOVE to change the cursor position without retrieving daa Examples ‘The following example traverses a table using a curser: BEGIN WORK; - Sot up 2 curser: DECLARE Liahona SCROLL CURSOR FOR SELECT * FROW rilm n= Fetch the firat § rows an the cursor 1ianona: FETCH FORKARD § FROM Iiahonay code | title | did | date prod | kind the Third Man 1 | ton | 194saz-23 | | The Arrican queen | oa | rssi-os-21 | | Une Fee est une Fenme | 102 | 1981-03-12 | Romantic i 1203 | 1 1 | 203 | 1 Vertige 203 | 1958-11-14 | Action Backer 103 | 1ses-02-03 | Deana == Fetch the previous row: FETCH ERIOR FROM Iiancna; cons | title | aia | aateproa | king PS0L | Vertigo | 103 | 195e-11-16 | ation == close the cursor and end the trans CLOSE Lishonas COMAIT WORK: Compatisility ‘The SQL stanelard defines FETCH for use in embedded SQL only. The variant of FETCH lescribed here retums the data asif it were a SELECT result rather than pling i in best ‘variables. Other thaa this point, FETCH is fully upward-compatible with the SQL standard, ‘The FETCH forms involving FORWARD and BACKWARD, ac wel a the forms FETCH count and FETCH ALI, in which FORWARD is implicit, ae Aster Databace extensions. ‘The SQL standard allows only FROM preceding the cursor name; the option to use TN isan extension, See Also “CLOSE” ou page V-20, “DECLARE” oa page V-46, and “MOVE" oa page V- \-80 Daiabase S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential GRANT GRANT GRANT ~ define access privileges synopsis @eaND 4 ( SELECT | INSERT | UPDATE | DELE Lee] | ALL [ PRIVILEGES | ] ow (TABLE 1 cabzename [1 TO ( [GROUP] rolename | PUBLIC } [, ...] [ WITH GRANT OPTION } [ CASCADE 1 1 comvect ) 1, Md dbname (, -.-1 TO (CL GROUP] rolenane | PUBLIC } [, ...] WITH GRANT OPTION GRANT { ( CREATE | USAGE } [,...] | ALL [ PRIVILEGES | } OM SCHEYR schemanane C+.) 16 (username | GROUF rolename | PUBLIC ) [, .++) { WITH GRANT OPTION 1 GRANT | INSTALL FILE | CREATE FUNCTION } [, ...] [ PRIVILEGE | OM SCHENR schemanane C, ...) To (username | GROUF rolenane | PUBLIC } [, GRANT EXECUTE [ FRIW 1 OM FUNCTION [sctemanane. } tuncaams To (username | GROUF rolename | PUBLIC} [, GRANT rolename (, To username [, ...] [ WITH ADMIN OPTION J+ Description ‘The GRaur command has two basic vatiants: one that grants privileges on a database object like a table or database (see “GRANT on Database Objects" oa page V-61) and ome that grants ‘membership in a role (see “GRANT on Roles" on page V~63), These variants are similar in many ‘ways, bur they ave different enough that we'll describe them separately. below, GRANT on Database Objects “This variant of the GRANT command gives privileges on a database object to one ar more roles. “These privileges are added to those already granted, ifany: ‘The keyword PUBLTC specifies that the privileges are tobe granted to all roles, including those ‘that might be erented fater. PTBT.TC can be thought of as.an implicitly defined group that always includes all woles. Any particular role will have the sum of privileges granted directly toi, privileges granted to any role it s presently a member of, and privileges granted to PUBLIC. IERITH GRANT OPTION is specified, the recipient of the privilege may in tur gront it to ‘others, Without a grant option, the recipient cannot do that. Grant options carmat be granted to PUBLIC. If CASCADE is specified. then the rights you granton a parent table cascade to all its child tables. GRECADE works only when granting (able privileges. “There is no need to grant privileges to the owner of an abject (usually the user that create it) a the owner has all privileges by default, The righ! to-drop an object, oF to alter its definition in any’ December 14, 2011 ‘SAL Commands W-81 (GRANT Aster Data proprietary and confidential is not described by a grantable privilege; itis inherent inthe owner, and cannot be granted lor revoked. The owner implicitly has all grant options for the object, 10, ‘Depending on the type of object, the initial éfrult privileges might include ernating some privileges to PUBLIC, The defauit is no public access for tables and sehensns; CONNECT privilege for databases, The objest over can of course revoke these privileges. (Fer maxim ‘seeurity, isove the REVOKE in the same transaction that creates the object; then there is no ‘window in which another user ean use the object.) ‘The possible privileges are- CREATE For databases, gives the wsertole the right to create new schemas in the database. Note! Granting CREATE on 1 database does not confer the right ro create tables, To do that, you rust grat the user CREATE ona schema inthe database. (Granting CREATE on a schema gives the user or role the right to create new tables and objects im the schema, To rename an existing object, you must own te object a! lr this privilege for the containing sehema. See also, “Revoking Users Rights to Create Tables" on page SELECT Allows SEEECT fom any column of the specified table, Also allows the use of COPT ‘TO. This privilege is also needed to reference existing columa values in /PDATE or DELETE. INSERT Allows INSERT of a new rove into the specified table, Also allows COPY FROM, UPDATE Allows L:PDATE of any column of the specified table, {In practice, any nontrivial ‘UPDATE command will require SELECT privilege as wel, sines it nwt reference table columns to determine which rows te update, andlor to compote new valves for columns.) USAGE Granting USAGE on aschernn gives the weer or role the right 9 acces objects ‘contained in the spesified schema (assuming thatthe objets” own privilege requirements are also met), Essentially this allows the grantee to “Isok wp” objects within the seheraa DELETE Allows DEZETE of 3 row from the specified table, (In practice, any nontrivial DELETE command will require SELECT privilege as wel, since it must reference table colmns to determine which rows todelete.) CONNECT Allows the user to sonnest tothe specified database. This privilege is chesked ‘wher the user attempts to connect. For new éatabaces you erent, only you have the CONNECT privilege, Ifyou want other tices to be able to CONNECT toa datahase, you must GRANT CONNECT om the databnse to the useror group, For example, you ean give all users the right to connect as shown here! GRANT COWNEGT o OATARASH reteil sales To eumuIcy INSTALL FILE, CREATE FUNCTION Allow the user to upload and install files and 'SQL-MapReduce functions, respectively, in the schema. See "5QIL-MapResiuce Security” on page 1-79, EXECUTE Allows the user torun the SQL-MapReduee function, See “SQ1L-MapReduace ‘Security on page -79. ALL PRIVILEGES. Grant all of the available privileges at onee, The PRIVILEGES keyword is optional. \-82. Daiabase S@l and Function Reference, version 4.6.2 ‘aster data Aster Data proprietary and confidential GRANT GRANT on Roles ‘This variant of the GRANT command grants membership ita role to one ar more roles or users. ‘Membership in a role conveys the role's privileges to each of its members. Note that you eannot ‘rant dib_edmin cole (the Aster Database superuser role} to another role, because there is 20 seed for multiple privileged roles in Aster Database, Also, you canaot grant a user to another IEWITH ADMIN OPTION is specified, the member may ia tm grant membership in the gale to cothers, and evake membership in the rola as woll. Withauc the admia option, ordinary users ‘cuanot do that. Roles having clo acinin privilege can grant or reveke membership in aay role Unlike the case with privileges, membership in a role cannot be granted to PUBLIC. Note also. that this fort of the command daes not allow the noise wese GROUP. Notes on GRANT ‘The REVOKE command is used to remove users” access privileges, ‘When a non-owner of an objest atiempis to GRANT privileges on the object, the command will fail outright if the user has no privileges whatsoever on the object, As long as some privilege is available, the command will proceed, but it will grant only those privileges for which the wser ‘has grant options. GRANT and REVOKE camalso be done by a mle thatis not the owner of the affected object, but is 1a member of the role that owns the object, or isa member of arole tat hakds privileges &T73 GRANT CETTON on the object, In this-case the privileges will be reconded as having been rated by the role that actually owns the abject or holds the privileges WITTE GRANT (CETION, For example if table tis owned by role gl, of which role wl isa member, then w| ean ‘grant privileges on t] 10 u2, but those privileges will appear to have been granted directly by gl ‘Any other member of role g] coald revoke them lates. If the role executing GRANT holds the required privileges indirectly via mare than ane role membership path it is unspecified which containing role will be recorded as having done the erat Roles and privleges are one factor that determines what a user cand in the AMC. For more information oa what determines the actions a user may perform inthe AMC, see “Allowed ‘Aciministrative Actions” on page 11-23. [TATSSEA and TEMPSRARY privileges are not supported in Aster Database, Examples Grant insert privilege to all users on table £i3=: GRANT INSERT ON films 70. PUB ot (Groat all privileges to all usezs ou databaze £2.1n21 GaRNT ALL PRIVT 93 ON DATABASE tilms TO PUBLIC: Grant membership in role adains to user jstrmmmer: GAANT amins TO jstrmmsrs Compatibility “The SQL standard des not support setting the privileges on more than one object per command, December 14, 2011 SAL Commands V-63

You might also like