# CoraDB Manual Source: https://www.coradb.ai/manual/index.html [CoraDB](https://www.coradb.ai) is a native multi-model database that combines relational and graph processing in a single core engine. This architecture provides unified storage, native execution, one connection to access both relational and graph data, and the ability to combine **SQL** and **PGQL** in a single query. [CoraDB](https://www.coradb.ai) is based on an open-source database engine extended by [Arnia Software](https://www.arnia.com) – [CUBRID](https://www.cubrid.org) - a DBMS optimized for OLTP that offers high performance, stability, scalability and high availability for mission-critical applications. [CoraDB](https://www.coradb.ai) offers full compatibility with SQL standards, including joins, subqueries, recursive CTEs, analytic functions, partitioning, triggers, stored procedures, and transactions with multi-version concurrency control. Relational data such as customers, accounts, and products can therefore coexist with graph data used for fraud detection, recommendations, knowledge bases, or credit-risk analysis, without requiring migration, synchronization, or duplication. ![CoraDB overview: the built-in apps (graph viewer, administration, WebSQL, database migration) and custom apps use the drivers (JDBC, PHP, ADO.NET, Python, Node.js, CCI) to connect through the broker to one engine that serves both relational features (tables and views, indexes, recursive CTEs, analytic functions, partitioning, triggers, JSON, Java stored procedures) and graph features (vertex and edge tables, MATCH patterns, variable-length and shortest paths, path variables, graph functions, JSON graph output) in a single hybrid query; services and utilities: the coradb utility, CoraDB Manager Server (CMS), MCP Server and MCP Admin Server](https://www.coradb.ai/manual/coradb-overview.png) ## Start here - [What is CoraDB?](https://www.coradb.ai/manual/intro.html): Architecture, processes, volumes and key features. - [Install and run](https://www.coradb.ai/manual/install.html): Install CoraDB on Linux or Windows and start the service. - [Quick start](https://www.coradb.ai/manual/quick_start.html): Start CoraDB, open a demo database and run your first queries. - [Demo databases](https://www.coradb.ai/manual/demo-databases.html): Ten ready-to-use relational, graph and hybrid databases included with CoraDB. ## Explore the manual ### SQL reference [All SQL topics](https://www.coradb.ai/manual/sql.html), [Data types](https://www.coradb.ai/manual/sql/datatype.html), [Data definition (DDL)](https://www.coradb.ai/manual/sql/schema.html), [Data manipulation (DML)](https://www.coradb.ai/manual/sql/query.html), [Operators and functions](https://www.coradb.ai/manual/sql/function.html), [Query optimization](https://www.coradb.ai/manual/sql/tuning.html), [Partitioning](https://www.coradb.ai/manual/sql/partition.html), [Transactions and locking](https://www.coradb.ai/manual/sql/transaction.html), [Triggers](https://www.coradb.ai/manual/sql/trigger.html), [Java stored procedures](https://www.coradb.ai/manual/sql/jsp.html), [Users and privileges](https://www.coradb.ai/manual/sql/authorization.html), [Getting started with graph](https://www.coradb.ai/manual/graph/graph_getting_started.html), [MATCH clause](https://www.coradb.ai/manual/graph/match.html), [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html), [Graph types](https://www.coradb.ai/manual/sql/datatype_graph.html), [Vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge), [Relational tables and graphs in one query](https://www.coradb.ai/manual/sql/hybrid.html), [Combining tables and the graph (tutorial)](https://www.coradb.ai/manual/graph/graph_getting_started.html#4-combining-the-tables-and-the-graph) ### Administration [All administration topics](https://www.coradb.ai/manual/admin.html), [Controlling processes](https://www.coradb.ai/manual/admin/control.html), [Database management](https://www.coradb.ai/manual/admin/db_manage.html), [coradb utilities](https://www.coradb.ai/manual/admin/admin_utils.html), [Backup and restore](https://www.coradb.ai/manual/admin/admin_backup.html), [System parameters](https://www.coradb.ai/manual/admin/config.html), [Troubleshooting](https://www.coradb.ai/manual/admin/troubleshoot.html) ### Security [All security topics](https://www.coradb.ai/manual/security.html), [Users and privileges](https://www.coradb.ai/manual/sql/authorization.html), [Access control lists](https://www.coradb.ai/manual/security.html#acl-access-control-list), [Packet encryption](https://www.coradb.ai/manual/security.html#packet-encryption), [TDE](https://www.coradb.ai/manual/security.html#tde-transparent-data-encryption) ### Drivers & APIs [Drivers overview](https://www.coradb.ai/manual/api.html), [PHP](https://www.coradb.ai/manual/api/php.html), [ADO.NET](https://www.coradb.ai/manual/api/adodotnet.html), [Python](https://www.coradb.ai/manual/api/python.html), [Node.js](https://www.coradb.ai/manual/api/node_js.html), [JDBC](https://www.coradb.ai/manual/api/jdbc.html), [CCI (C)](https://www.coradb.ai/manual/api/cci.html) ### System catalog [System tables](https://www.coradb.ai/manual/sql/catalog_classes.html), [System views](https://www.coradb.ai/manual/sql/catalog_views.html) ## Building CoraDB apps with AI tools Every page of this manual is also published as clean Markdown for AI assistants and code generators: use the **View as Markdown** link under any page title, or point your tool at [llms.txt](https://www.coradb.ai/manual/llms.txt) (index of all pages) or [llms-full.txt](https://www.coradb.ai/manual/llms-full.txt) (the whole manual in one file), or [coradb-manual-md.zip](https://www.coradb.ai/manual/coradb-manual-md.zip) (one Markdown file per page). --- # CoraDB administration Source: https://www.coradb.ai/manual/admin.html The **coradb** command is the single entry point for administering CoraDB: it starts and stops the processes and runs the database utilities. | Topic | Pages | |---|---| | Processes | [Overview & services](https://www.coradb.ai/manual/admin/control.html), [Database server](https://www.coradb.ai/manual/admin/control_server.html), [Broker](https://www.coradb.ai/manual/admin/control_broker.html), [CoraDB Manager Server (CMS)](https://www.coradb.ai/manual/admin/control_manager.html), [Java SP server](https://www.coradb.ai/manual/admin/control_javasp.html) | | Database files and volumes | [Database management](https://www.coradb.ai/manual/admin/db_manage.html) | | Utilities | [Overview & database creation](https://www.coradb.ai/manual/admin/admin_utils.html), [Backup & restore](https://www.coradb.ai/manual/admin/admin_backup.html), [Unload & load](https://www.coradb.ai/manual/admin/admin_unload.html), [Space & statistics](https://www.coradb.ai/manual/admin/admin_space.html), [statdump](https://www.coradb.ai/manual/admin/admin_statdump.html), [Locks & transactions](https://www.coradb.ai/manual/admin/admin_transactions.html), [Diagnostics](https://www.coradb.ai/manual/admin/admin_diag.html) | | Configuration | [System parameters](https://www.coradb.ai/manual/admin/config.html), [Broker configuration](https://www.coradb.ai/manual/admin/config_broker.html) | | Monitoring and problems | [Troubleshooting](https://www.coradb.ai/manual/admin/troubleshoot.html), [DDL audit log](https://www.coradb.ai/manual/admin/ddl_audit.html) | ## Service commands | Command | Controls | |---|---| | `coradb service {start\|stop\|restart\|status}` | All processes listed in the `[service]` section of `coradb.conf` | | `coradb server {start\|stop\|restart\|status} [db]` | database servers | | `coradb server acl {reload\|status} db` | The access control list of a database server | | `coradb broker {start\|stop\|restart\|status\|on\|off\|reset\|info\|acl}` | Brokers and their CAS processes | | `coradb manager {start\|stop\|status}` | CMS | | `coradb javasp {start\|stop\|restart\|status} [db]` | Java SP servers | ## Database utilities | Task | Utilities | |---|---| | Create and remove | [createdb](https://www.coradb.ai/manual/admin/admin_utils.html#createdb), [addvoldb](https://www.coradb.ai/manual/admin/admin_utils.html#addvoldb), [deletedb](https://www.coradb.ai/manual/admin/admin_utils.html#deletedb) | | Rename, move, copy, register | [renamedb](https://www.coradb.ai/manual/admin/admin_utils.html#renamedb), [alterdbhost](https://www.coradb.ai/manual/admin/admin_utils.html#alterdbhost), [copydb](https://www.coradb.ai/manual/admin/admin_utils.html#copydb), [installdb](https://www.coradb.ai/manual/admin/admin_utils.html#installdb) | | Back up and restore | [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb), [restoredb](https://www.coradb.ai/manual/admin/admin_backup.html#restoredb) | | Export and import | [unloaddb](https://www.coradb.ai/manual/admin/admin_unload.html#unloaddb), [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb) | | Space and statistics | [spacedb](https://www.coradb.ai/manual/admin/admin_space.html#spacedb), [compactdb](https://www.coradb.ai/manual/admin/admin_space.html#compactdb), [vacuumdb](https://www.coradb.ai/manual/admin/admin_space.html#vacuumdb), [optimizedb](https://www.coradb.ai/manual/admin/admin_space.html#optimizedb), [plandump](https://www.coradb.ai/manual/admin/admin_space.html#plandump), [statdump](https://www.coradb.ai/manual/admin/admin_statdump.html#statdump) | | Locks and transactions | [lockdb](https://www.coradb.ai/manual/admin/admin_transactions.html#lockdb), [tranlist](https://www.coradb.ai/manual/admin/admin_transactions.html#tranlist), [killtran](https://www.coradb.ai/manual/admin/admin_transactions.html#killtran) | | Checks and diagnostics | [checkdb](https://www.coradb.ai/manual/admin/admin_diag.html#checkdb), [diagdb](https://www.coradb.ai/manual/admin/admin_diag.html#diagdb), [paramdump](https://www.coradb.ai/manual/admin/admin_diag.html#paramdump) | | Encryption, locales, time zones | [tde](https://www.coradb.ai/manual/admin/admin_utils.html#tde), [genlocale, dumplocale, synccolldb](https://www.coradb.ai/manual/admin/admin_utils.html#locale-commands), [gen_tz, dump_tz](https://www.coradb.ai/manual/admin/admin_utils.html#timezone-commands) | > **Note:** > On Windows, run the command prompt as administrator (right-click *Command Prompt* > *Run as administrator*) to control the CoraDB service with `coradb`. Without administrator rights the commands can run through the User Account Control dialog, but their result messages are not displayed. --- # Backup and restore: backupdb, restoredb Source: https://www.coradb.ai/manual/admin/admin_backup.html ## backupdb A database backup is the procedure of storing CoraDB database volumes, control files and log files, and it is executed by using the **coradb backupdb** utility. **DBA** must regularly back up the database so that the database can be properly restored in the case of storage media or file errors. The restore environment must have the same operating system and the same version of CoraDB as the backup environment. For such a reason, you must perform a backup in a new environment immediately after migrating a database to a new version. To recover all database pages, control files and the database to the state at the time of backup, the **coradb backupdb** utility copies all necessary log records. ``` bash coradb backupdb [options] database_name[@hostname] ``` The following shows options available with the **coradb backupdb** utility (options are case sensitive). **-D, --destination-path=PATH** The following shows how to use the **-D** option to store backup files in the specified directory. The backup file directory must be specified before performing this job. If the **-D** option is not specified, backup files are stored in the log directory specified in the **databases.txt** file which stores database location information. ``` bash coradb backupdb -D /home/coradb/backup testdb ``` The following shows how to store backup files in the current directory by using the **-D** option. If you enter a period (.) following the **-D** option as an argument, the current directory is specified. ``` bash coradb backupdb -D . testdb ``` **-r, --remove-archive** Writes an active log to a new archive log file when the active log is full. If a backup is performed in such a situation and backup volumes are created, backup logs created before the backup will not be used in subsequent backups. The **-r** option is used to remove archive log files that will not be used anymore in subsequent backups after the current one is complete. The **-r** option only removes unnecessary archive log files that were created before backup, and does not have any impact on backup; however, if an administrator removes the archive log file after a backup, it may become impossible to restore everything. For this reason, archive logs should be removed only after careful consideration. If you perform an incremental backup (backup level 1 or 2) with the **-r** option, there is the risk that normal recovery of the database will be impossible later on. Therefore, it is recommended that the **-r** option only be used when a full backup is performed. ``` bash coradb backupdb -r testdb ``` **-l, --level=LEVEL** The following shows how to execute an incremental backup of the level specified by using the **-l** option. If the **-l** option is not specified, a full backup is performed. For details on backup levels, see [Incremental backup](https://www.coradb.ai/manual/admin/admin_backup.html#incremental-backup) . ``` bash coradb backupdb -l 1 testdb ``` **-o, --output-file=FILE** The following shows how to write the progress of the database backup to the info_backup file by using the **-o** option. ``` bash coradb backupdb -o info_backup testdb ``` The following shows the contents of the info_backup file. You can check the information on the number of threads, compression method, backup start time, the number of permanent volumes, backup progress and backup end time. ``` text [ Database(testdb) Full Backup start ] - num-threads: 1 - compression method: NONE - backup start time: Mon Jul 21 16:51:51 2008 - number of permanent volumes: 1 - backup progress status ----------------------------------------------------------------------------- volume name | # of pages | backup progress status | done ----------------------------------------------------------------------------- testdb_keys | 1 | ######################### | done testdb_vinf | 1 | ######################### | done testdb | 25000 | ######################### | done testdb_lginf | 1 | ######################### | done testdb_lgat | 25000 | ######################### | done ----------------------------------------------------------------------------- # backup end time: Mon Jul 21 16:51:53 2008 [Database(testdb) Full Backup end] ``` **-S, --SA-mode** The following shows how to perform backup in standalone mode (that is, backup offline) by using the **-S** option. If the **-S** option is not specified, the backup is performed in client/server mode. ``` bash coradb backupdb -S testdb ``` **-C, --CS-mode** Backs up the database online, in client-server mode, while the server is running. This is the default. ``` bash coradb backupdb -C testdb ``` **--no-check** The following shows how to execute backup without checking the consistency of the database by using the **--no-check** option. ``` bash coradb backupdb --no-check testdb ``` **-t, --thread-count=COUNT** The following shows how to execute parallel backup with the number of threads specified by the administrator by using the **-t** option. Even when the argument of the **-t** option is not specified, a parallel backup is performed by automatically assigning as many threads as CPUs in the system. ``` bash coradb backupdb -t 4 testdb ``` **-z, --compress** The following shows how to compress the database and stores it in the backup file by using the **-z** option. The size of the backup file and the time required for backup can be reduced by using the **-z** option. ``` bash coradb backupdb -z testdb ``` **--sleep-msecs=NUMBER** This option allows you to specify the interval of idle time during the database backup. The default value is 0 in milliseconds. The system becomes idle for the specified amount of time whenever it reads 1 MB of data from a file. This option is used to reduce the performance degradation of an active server during a live backup. The idle time will prevent excessive disk I/O operations. ``` bash coradb backupdb --sleep-msecs=5 testdb ``` **-k, --separate-keys** This option is used not to include the key file in the backup volume. The key file that is not included is separated into a file named **\\_bk\\_keys**. If this option is not given, the key file is included in the backup volume by default. For a detailed description of key file separation, see [Backup encryption](https://www.coradb.ai/manual/security.html#backup-encryption). ``` bash coradb backupdb -k testdb ``` ### Backup strategy and method The following must be considered before performing a backup: - **Selecting the data to be backed up** - Determine whether it is valid data worth being preserved. - Determine whether to back up the entire database or only part of it. - Check whether there are other files to be backed up along with the database. - **Choosing a backup method** - Choose the backup method from one of incremental and online backups. Also, specify whether to use compression backup, parallel backup, and mode. - Prepare backup tools and devices available. - **Determining backup time** - Identify the time when the least usage in the database occur. - Check the size of the archive logs. - Check the number of clients using the database to be backed up. **Online backup** An online backup (or a hot backup) is a method of backing up a currently running database. It provides a snapshot of the database image at a certain point in time. Because the backup target is a currently running database, it is likely that uncommitted data will be stored and the backup may affect the operation of other databases. To perform an online backup, use the **coradb backupdb -C** command. **Offline backup** An offline backup (or a cold backup) is a method of backing up a stopped database. It provides a snapshot of the database image at a certain point in time. To perform an offline backup, use the **coradb backupdb -S** command. **Incremental backup** An incremental backup, which is dependent upon a full backup, is a method of only backing up data that have changed since the last backup. This type of backup has an advantage of requiring less volume and time than a full backup. CoraDB supports backup levels 0, 1 and 2. A higher level backup can be performed sequentially only after a lower lever backup is complete. To perform an incremental backup, use the **coradb backupdb -l** *LEVEL* command. The backup levels work as follows. - **Full backup (backup level 0)** : Backup level 0 is a full backup that includes all database pages. The level of a backup which is attempted first on the database naturally becomes a 0 level. **DBA** must perform full backups regularly to prepare for restore situations. In the example, full backups were performed on December 31st and January 5th. - **First incremental backup (backup level 1)** : Backup level 1 is an incremental backup that only stores changes since the level 0 full backup, and is called a "first incremental backup." Note that the first incremental backups are attempted sequentially such as \<1-1\>, \<1-2\> and \<1-3\> in the example, but they are always performed based on the level 0 full backup. Suppose that backup files are created in the same directory. If the first incremental backup \<1-1\> is performed on January 1st and then the first incremental backup \<1-2\> is attempted again on January 2nd, the incremental backup file created in \<1-1\> is overwritten. The final incremental backup file is created on January 3rd because the first incremental backup is performed again on that day. Since there can be a possibility that the database needs to be restored the state of January 1st or January 2nd, it is recommended for **DBA** to store the incremental backup files \<1-1\> and \<1-2\> separately in storage media before overwriting with the final incremental file. - **Second incremental backup (backup level 2)** : Backup level 2 is an incremental backup that only stores data that have changed since the first incremental backup, and is called a "second incremental backup." A second incremental backup can be performed only after the first incremental backup. Therefore, the second incremental backup attempted on January fourth succeeds; the one attempted on January sixth fails. Backup files created for backup levels 0, 1 and 2 may all be required for database restore. To restore the database to its state on January fourth, for example, you need the second incremental backup generated at \<2-1\>, the first incremental backup file generated at \<1-3\>, and the full backup file generated at \<0-1\>. That is, for a full restore, backup files from the most recent incremental backup file to the earliest created full backup file are required. **Compress backup** A compress backup is a method of backing up the database by compressing it. This type of backup reduces disk I/O costs and stores disk space because it requires less backup volume. To perform a compress backup, use the **coradb backupdb -z** \| **--compress** command. **Parallel backup mode** A parallel or multi-thread backup is a method of performing as many backups as the number of threads specified. In this way, it reduces backup time significantly. Basically, threads are given as many as the number of CPUs in the system. To perform a parallel backup, use the **coradb backupdb -t** \| **--thread-count** command. ### Managing backup files One or more backup files can be created in sequence based on the size of the database to be backed up. A unit number is given sequentially (000, 001-0xx) to the extension of each backup file based in the order of creation. **Managing disk capacity during the backup** During the backup process, if there is not enough space on the disk to store the backup files, a message saying that the backup cannot continue appears on the screen. This message contains the name and path of the database to be backed up, the backup file name, the unit number of backup files and the backup level. To continue the backup process, the administrator can choose one of the following options: - Option 0: An administrator enters 0 to discontinue the backup. - Option 1: An administrator inserts a new disk into the current device and enters 1 to continue the backup. - Option 2: An administrator changes the device or the path to the directory where backup files are stored and enters 2 to continue the backup. ``` text ****************************************************************** Backup destination is full, a new destination is required to continue: Database Name: /local1/testing/testdb Volume Name: /dev/rst1 Unit Num: 1 Backup Level: 0 (FULL LEVEL) Enter one of the following options: Type - 0 to quit. - 1 to continue after the volume is mounted/loaded. (retry) - 2 to continue after changing the volume's directory or device. ****************************************************************** ``` ### Managing archive logs You must not delete archive logs by using the file deletion command such as rm or del by yourself; the archive logs should be deleted by system configuration or the **coradb backupdb** utility. In the following three cases, archive logs can be deleted. If you want to delete logs as much as possible while operating a database, configure the value of **log_max_archives** to a small value or 0 and configure the value of **force_remove_log_archives** to yes. ## restoredb A database restore is the procedure of restoring the database to its state at a certain point in time by using the backup files, active logs and archive logs which have been created in an environment of the same CoraDB version. To perform a database restore, use the **coradb restoredb** utility. The **coradb restoredb** utility restores the database from the database backup by using the information written to all the active and archive logs since the execution of the last backup. ``` bash coradb restoredb [options] database_name ``` If no option is specified, a database is restored to the point of the last commit by default. If no active/archive log files are required to restore to the point of the last commit, the database is restored only to the point of the last backup. ``` bash coradb restoredb testdb ``` The following table shows options available with the **coradb restoredb** utility (options are case sensitive). **-d, --up-to-date=DATE** A database can be restored to the given point by the date-time specified by the **-d** option. The user can specify the restoration point manually in the dd-mm-yyyy:hh:mi:ss (e.g. 14-10-2008:14:10:00) format. If no active log/archive log files are required to restore to the point specified, the database is restored only to the point of the last backup. ``` bash coradb restoredb -d 14-10-2008:14:10:00 testdb ``` If the user specifies the restoration point by using the **backuptime** keyword, it restores a database to the point of the last backup. ``` bash coradb restoredb -d backuptime testdb ``` **--list** This option displays information on backup files of a database; restoration procedure is not performed. This option is available even if the database is working, from CoraDB 9.3. ``` bash coradb restoredb --list testdb ``` The following example shows how to display backup information by using the **--list** option. You can specify the path to which backup files of the database are originally stored as well as backup levels. ``` text *** BACKUP HEADER INFORMATION *** Database Name: /local1/testing/testdb DB Creation Time: Mon Oct 1 17:27:40 2008 Pagesize: 4096 Backup Level: 1 (INCREMENTAL LEVEL 1) Start_lsa: 513|3688 Last_lsa: 513|3688 Backup Time: Mon Oct 1 17:32:50 2008 Backup Unit Num: 0 Release: 8.1.0 Disk Version: 8 Backup Pagesize: 4096 Zip Method: 0 (NONE) Zip Level: 0 (NONE) Previous Backup level: 0 Time: Mon Oct 1 17:31:40 2008 (start_lsa was -1|-1) Database Volume name: /local1/testing/testdb_keys Volume Identifier: -6, Size: 65 bytes (1 pages) Database Volume name: /local1/testing/testdb_vinf Volume Identifier: -5, Size: 308 bytes (1 pages) Database Volume name: /local1/testing/testdb Volume Identifier: 0, Size: 2048000 bytes (500 pages) Database Volume name: /local1/testing/testdb_lginf Volume Identifier: -4, Size: 165 bytes (1 pages) Database Volume name: /local1/testing/testdb_bkvinf Volume Identifier: -3, Size: 132 bytes (1 pages) ``` With the backup information displayed by using the **--list** option, you can check that backup files have been created at the backup level 1 as well as the point where the full backup of backup level 0 has been performed. Therefore, to restore the database in the example, you must prepare backup files for backup levels 0 and 1. **-B, --backup-file-path=PATH** You can specify the directory where backup files are to be located by using the **-B** option. If this option is not specified, the system retrieves the backup information file (*dbname* **\_bkvinf**) generated upon a database backup; the backup information file in located in the **log-path** directory specified in the database location information file (**databases.txt**). And then it searches the backup files in the directory path specified in the backup information file. However, if the backup information file has been damaged or the location information of the backup files has been deleted, the system will not be able to find the backup files. Therefore, the administrator must manually specify the directory where the backup files are located by using the **-B** option. ``` bash coradb restoredb -B /home/coradb/backup testdb ``` If the backup files of a database is in the current directory, the administrator can specify the directory where the backup files are located by using the **-B** option. ``` bash coradb restoredb -B . testdb ``` **-l, --level=LEVEL** You can perform restoration by specifying the backup level of the database to 0, 1, or 2. For details on backup levels, see [Incremental backup](https://www.coradb.ai/manual/admin/admin_backup.html#incremental-backup) . ``` bash coradb restoredb -l 1 testdb ``` **-p, --partial-recovery** You can perform partial restoration without requesting for the user's response by using the **-p** option. If active or archive logs written after the backup point are not complete, by default the system displays a request message informing that log files are needed and prompting the user to enter an execution option. The partial restoration can be performed directly without such a request message by using the **-p** option. Therefore, if the **-p** option is used when performing restoration, data is always restored to the point of the last backup. ``` bash coradb restoredb -p testdb ``` When the **-p** option is not specified, the message requesting the user to select the execution option is as follows: ``` text *********************************************************** Log Archive /home/coradb/test/log/testdb_lgar002 is needed to continue normal execution. Type - 0 to quit. - 1 to continue without present archive. (Partial recovery) - 2 to continue after the archive is mounted/loaded. - 3 to continue after changing location/name of archive. *********************************************************** ``` - Option 0: Stops restoring - Option 1: Performing partial restoration without log files. - Option 2: Performing restoration after locating a log to the current device. - Option 3: Resuming restoration after changing the location of a log **-o, --output-file=FILE** The following syntax shows how to write the restoration progress of a database to the info_restore file by using the **-o** option. ``` bash coradb restoredb -o info_restore testdb ``` **-u, --use-database-location-path** This option restores a database to the path specified in the database location file(**databases.txt**). The **-u** option is useful when you perform a backup on server A and store the backup file on server B. ``` bash coradb restoredb -u testdb ``` **-k, --keys-file-path=PATH** This option specifies the path of a key file required to restore the database. If the valid key file is not given, it could fail to restore. If this option is not given, the appropriate key file is searched automatically according to a priority. For more information on this, refer to [Backup encryption](https://www.coradb.ai/manual/security.html#backup-encryption). ``` bash coradb restoredb -k /home/coradb/backup_keys/testdb_bk1_keys testdb ``` NOTIFICATION messages, log recovery starting time and ending time are written into the server error log file or the restoredb error log file when database server is started or backup volume is restored; so you can check the elapsed time of these operations. In this message, the number of log records to be applied(redo) and the number of log pages are written together. ``` text Time: 06/14/13 21:29:04.059 - NOTIFICATION *** file ../../src/transaction/log_recovery.c, line 748 CODE = -1128 Tran = -1, EID = 1 Log recovery is started. The number of log records to be applied: 96916. Log page: 343 ~ 5104. ..... Time: 06/14/13 21:29:05.170 - NOTIFICATION *** file ../../src/transaction/log_recovery.c, line 843 CODE = -1129 Tran = -1, EID = 4 Log recovery is finished. ``` ### Restoring strategy and procedure You must consider the following before restoring databases. - **Preparing backup files** - Identify the directory where the backup and log files are to be stored. - If the database has been incrementally backed up, check whether an appropriate backup file for each backup level exists. - Check whether the backed-up CoraDB database and the CoraDB database to be backed up are the same version. - **Choosing restore method** - Determine whether to perform a partial or full restore. - Determine whether or not to perform a restore using incremental backup files. - Prepare restore tools and devices available. - **Determining restore point** - Identify the point in time when the database server was terminated. - Identify the point in time when the last backup was performed before database failure. - Identify the point in time when the last commit was made before database failure. **Database restore procedure** The following procedure shows how to perform backup and restoration described in the order of time. 1. Performs a full backup of *testdb* which stopped running at 2008/8/14 04:30. 2. Performs the first incremental backup of *testdb* running at 2008/8/14 10:00. 3. Performs the first incremental backup of *testdb* running at 2008/8/14 15:00. Overwrites the first incremental backup file in step 2. 4. A system failure occurs at 2008/8/14 15:30, and the system administrator prepares the restore of *testdb*. Sets the restore time as 15:25, which is the time when the last commit was made before database failure 5. The system administrator prepares the full backup file created in Step 1 and the first incremental backup file created in Step 3, restores the *testdb* database up to the point of 15:00, and then prepares the active and archive logs to restore the database up to the point of 15:25. | Time | Command | Description | |-----------------|-----------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 2008/8/14 04:25 | coradb server stop testdb | Shuts down *testdb*. | | 2008/8/14 04:30 | coradb backupdb -S -D /home/backup -l 0 testdb | Performs a full backup of *testdb* in offline mode and creates backup files in the specified directory. | | 2008/8/14 05:00 | coradb server start testdb | Starts *testdb*. | | 2008/8/14 10:00 | coradb backupdb -C -D /home/backup -l 1 testdb | Performs the first incremental backup of *testdb* online and creates backup files in the specified directory. | | 2008/8/14 15:00 | coradb backupdb -C -D /home/backup -l 1 testdb | Performs the first incremental backup of *testdb* online and creates backup files in the specified directory. Overwrites the first incremental backup file created at 10:00. | | 2008/8/14 15:30 | | A system failure occurs. | | 2008/8/14 15:40 | coradb restoredb -l 1 -d 08/14/2008:15:25:00 testdb | Restores *testdb* based on the full backup file, first incremental backup file, active logs and archive logs. The database is restored to the point of 15:25 by the full and first incremental backup files, the active and archive logs. | ### Restoring database to different server The following shows how to back up *testdb* on server *A* and restore it on server *B* with the backed up files. **Backup and restore environments** Suppose that *testdb* is backed up in the /home/coradb/db/testdb directory on server *A* and restored into /home/coradb/data/testdb on server *B*. 1. Backing up on server A Back up *testdb* on server *A*. If a backup has been performed earlier, you can perform an incremental backup for data only that have changed since the last backup. The directory where the backup files are created, if not specified in the **-D** option, is created by default in the location where the log volume is stored. The following is a backup command with recommended options. For details on the options, see [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb) . ``` bash coradb backupdb -z testdb ``` 2. Editing the database location file on Server B Unlike a general scenario where a backup and restore are performed on the same server, in a scenario where backup files are restored using a different server, you need to add the location information on database restore in the database location file (**databases.txt**) on server *B*. In the diagram above, it is supposed that *testdb* is restored in the /home/coradb/data/testdb directory on server *B* (hostname: pmlinux); edit the location information file accordingly and create the directory on server *B*. Put the database location information in one single line. Separate each item with a space. The line should be written in \[database name\]. \[data volume path\] \[host name\] \[log volume path\] format; that is, write the location information of *testdb* as follows: ``` text testdb /home/coradb/data/testdb pmlinux /home/coradb/data/testdb ``` 3. Transferring backup files to server B For a restore, you must prepare backup files. Therefore, transfer a backup file (e.g. testdb_bk0v000) from server *A* to server *B*. That is, a backup file must be located in a directory (e.g. /home/coradb/temp) on server *B*. > **Note:** > If you want to restore until the current time after the backup, logs after backup, that is, an active log (e.g. testdb_lgat) and archive logs (e.g. testdb_lgar000) are additionally required to copy. > > An active log and archive logs should be located to the log directory of the database to be restored; that is, the directory of log files specified in \$CORADB/databases/databases.txt. (e.g. \$CORADB/databases/testdb/log) > > Also, if you want to apply the added logs after backup, archive logs should be copied before they are removed. By the way, the default of log_max_archives, which is a system parameter related to delete archive logs, is 0; therefore, archive logs after backup can be deleted. To prevent this situation, the value of log_max_archives should be big enough. See [log_max_archives](https://www.coradb.ai/manual/admin/config_logging.html#log_max_archives). 4. Restoring the database on server B Perform database restore by calling the **coradb restoredb** utility from the directory into which the backup files which were transferred to server *B* had been stored. With the **-u** option, *testdb* is restored in the directory path from the **databases.txt** file. ``` bash coradb restoredb -u testdb ``` To call the **coradb restoredb** utility from a different path, specify the directory path to the backup file by using the **-B** option as follows: ``` bash coradb restoredb -u -B /home/coradb/temp testdb ``` --- # Diagnostics: checkdb, diagdb, paramdump Source: https://www.coradb.ai/manual/admin/admin_diag.html ## checkdb The **coradb checkdb** utility is used to check the consistency of a database. You can use **coradb checkdb** to identify data structures that are different from indexes by checking the internal physical consistency of the data and log volumes. If the **coradb checkdb** utility reveals any inconsistencies, you must try automatic repair by using the --**repair** option. ``` bash coradb checkdb [options] database_name [table_name1 table_name2 ...] ``` - **coradb**: An integrated utility for CoraDB service and database management. - **checkdb**: A utility that checks the data consistency of a specific database. - *database_name*: The name of the database whose consistency status will be either checked or restored. - *table_name1 table_name2*: List the table names for consistency check or recovery The following shows \[options\] available with the **coradb checkdb** utility. **-S, --SA-mode** This option is used to access a database in standalone, which means it works without processing server; it does not have an argument. If **-S** is not specified, the system recognizes that a database is running in client/server mode. ``` bash coradb checkdb -S testdb ``` **-C, --CS-mode** This option is used to access a database in client/server mode, which means it works in client/server process respectively; it does not have an argument. If **-C** is not specified, the system recognize that a database is running in client/server mode by default. ``` bash coradb checkdb -C testdb ``` **-r, --repair** This option is used to restore an issue if a consistency error occurs in a database. ``` bash coradb checkdb -r testdb ``` **--check-prev-link** This option is used to check if there are errors on previous links of an index. ``` bash $ coradb checkdb --check-prev-link testdb ``` **--repair-prev-link** This option is used to restore if there are errors on previous links of an index. ``` bash $ coradb checkdb --repair-prev-link testdb ``` **-i, --input-class-file=FILE** You can specify tables to check the consistency or to restore, by specifying the **-i** *FILE* option or listing the table names after a database name. Both ways can be used together. If a target is not specified, entire database will be a target of consistency check or restoration. ``` bash coradb checkdb testdb tbl1 tbl2 coradb checkdb -r testdb tbl1 tbl2 coradb checkdb -r -i table_list.txt testdb tbl1 tbl2 ``` Empty string, tab, carriage return and comma are separators among table names in the table list file specified by **-i** option. The following example shows the table list file; from t1 to t10, it is recognized as a table for consistency check or restoration. ``` text t1 t2 t3,t4 t5 t6, t7 t8 t9 t10 ``` **--check-file-tracker** Check about all pages of all files in file-trackers. **--check-heap** Check about all heap-files. **--check-catalog** Check the consistency about catalog information. **--check-btree** Check the validity about all B-tree indexes. **--check-class-name** Check the identical between the hash table of a class name and the class information(oid) brought from a heap file. **--check-btree-entries** Check the consistency of all B-tree entries. **--check-graph** Checks the graph data of vertex and edge tables: the in-memory graph, the graph data on disk, and that both are in sync. The three checks can also be run one at a time: | Option | Checks | |---|---| | **--check-graph-in-memory** | The consistency of the in-memory graph | | **--check-graph-disk** | The consistency of the graph data on disk | | **--check-graph-sync-disk-mem** | That the in-memory graph matches the data on disk | **--check-level=LEVEL** The intensity of the graph checks, 1 or 2; the default is the highest level. **-I, --index-name=INDEX_NAME** Check if the index specified with this option about checking table. If you use this option, there is no heap validation check. Only one table and one index are permitted when you use this option; if you don't input a table name or input two tables, an error occurs. ## diagdb You can check various pieces of internal information on the database with the **coradb diagdb** utility. Information provided by **coradb diagdb** is helpful in diagnosing the current status of the database or figuring out a problem. ``` bash coradb diagdb options database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **diagdb**: A command that is used to check the current storage state of the database by Dumping the information contained in the binary file managed by CoraDB in text format. It normally executes only when the database is in a stopped state. You can check the whole database or the file table, file size, heap size, class name or disk bitmap selectively by using the provided option. - *database_name*: The name of the database whose internal information is to be diagnosed. The following shows \[options\] available with the **coradb diagdb** utility. **-d, --dump-type=TYPE** This option specifies the output range when you display the information of all files in the *testdb* database. If any option is not specified, the default value of -1 is used. ``` bash coradb diagdb -d 1 testdb ``` The utility has 9 types of **-d** options as follows: | | | |------|--------------------------------------| | Type | Description | | -1 | Displays all database information. | | 1 | Displays file table information. | | 2 | Displays file capacity information. | | 3 | Displays heap capacity information. | | 4 | Displays index capacity information. | | 5 | Displays class name information. | | 6 | Displays disk bitmap information. | | 7 | Displays catalog information. | | 8 | Displays log information. | | 9 | Displays heap information. | **-o, --output-file=FILE** The **-o** option is used to store information of the parameters used in the server/client process of the database into a specified file. The file is created in the current directory. If the **-o** option is not specified, the message is displayed on a console screen. ``` bash coradb diagdb -d8 -o logdump_output testdb ``` **--emergency** Use **--emergency** option to suppress recovery. **This option is meant ONLY for debugging, if there are recovery issues. It is recommended to backup your database before using this option.** ## paramdump The **coradb paramdump** utility outputs parameter information used in the server/client process. ``` bash coradb paramdump [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management - **paramdump**: A utility that outputs parameter information used in the server/client process - *database_name*: The name of the database in which parameter information is to be displayed. The following shows \[options\] available with the **coradb paramdump** utility. **-o, --output-file=FILE** The **-o** option is used to store information of the parameters used in the server/client process of the database into a specified file. The file is created in the current directory. If the **-o** option is not specified, the message is displayed on a console screen. ``` bash coradb paramdump -o db_output testdb ``` **-b, --both** The **-b** option is used to display parameter information used in server/client process on a console screen. If the **-b** option is not specified, only server-side information is displayed. ``` bash coradb paramdump -b testdb ``` **-S, --SA-mode** This option displays parameter information of the server process in standalone mode. ``` bash coradb paramdump -S testdb ``` **-C, --CS-mode** This option displays parameter information of the server process in client/server mode. ``` bash coradb paramdump -C testdb ``` --- # Space and statistics: spacedb, compactdb, optimizedb, plandump, vacuumdb Source: https://www.coradb.ai/manual/admin/admin_space.html ## spacedb The **coradb spacedb** utility is used to check how much space of database volumes is being used. The tool can show brief aggregated information on database space usage, or detailed descriptions of all volumes and files in use, based on its options. Information returned by the **coradb spacedb** utility includes the volume ID's, names, purpose and total/free space of each volume. ``` bash coradb spacedb [options] database_name ``` - **coradb** : An integrated utility for the CoraDB service and database management. - **spacedb** : A command that checks the space in the database. It executes successfully only when the database is in a stopped state. - *database_name* : The name of the database whose space is to be checked. The path-name to the directory where the database is to be created must not be included. The following shows \[options\] available with the **coradb spacedb** utility. **-o, --output-file=FILE** This option stores the result of checking the space information of *testdb* to a file named *db_output*. ``` bash coradb spacedb -o db_output testdb ``` **-S, --SA-mode** This option is used to access a database in standalone, which means it works without processing server; it does not have an argument. If **-S** is not specified, the system recognizes that a database is running in client/server mode. ``` bash coradb spacedb --SA-mode testdb ``` **-C, --CS-mode** This option is used to access a database in client/server mode, which means it works in client/server process respectively; it does not have an argument. If **-C** is not specified, the system recognize that a database is running in client/server mode by default. ``` bash coradb spacedb --CS-mode testdb ``` **--size-unit={PAGE\|M\|G\|T\|H}** This option specifies the size unit of the space information of the database to be one of PAGE, M(MB), G(GB), T(TB), H(print-friendly). The default value is **H**. If you set the value to H, the unit is automatically determined as follows: M if 1 MB = DB size \< 1024 MB, G if 1 GB = DB size \< 1024 GB. ``` bash $ coradb spacedb --size-unit=H testdb Space description for database 'testdb' with pagesize 16.0K. (log pagesize: 16.0K) type purpose volume_count used_size free_size total_size PERMANENT PERMANENT DATA 2 61.0 M 963.0 M 1.0 G PERMANENT TEMPORARY DATA 1 12.0 M 500.0 M 512.0 M TEMPORARY TEMPORARY DATA 1 40.0 M 88.0 M 128.0 M - - 4 113.0 M 1.5 G 1.6 G Space description for all volumes: volid type purpose used_size free_size total_size volume_name 0 PERMANENT PERMANENT DATA 60.0 M 452.0 M 512.0 M /home1/coradb/testdb 1 PERMANENT PERMANENT DATA 1.0 M 51.0 M 512.0 M /home1/coradb/testdb_x001 2 PERMANENT TEMPORARY DATA 12.0 M 500.0 M 512.0 M /home1/coradb/testdb_x002 32766 TEMPORARY TEMPORARY DATA 40.0 M 88.0 M 128.0 M /home1/coradb/testdb_t32766 LOB space description file:/home1/coradb/lob ``` **-s, --summarize** This option aggregates volume count, used size, free size and total size by volume types and purposes. There are three classes of volumes: permanent volumes with permanent data, permanent volumes with temporary data and temporary volume with temporary data; no temporary volumes with permanent data. Last row shows the total values for all types of volumes. ``` bash $ coradb spacedb -s testdb Space description for database 'testdb' with pagesize 16.0K. (log pagesize: 16.0K) type purpose volume_count used_size free_size total_size PERMANENT PERMANENT DATA 2 61.0 M 963.0 M 1.0 G PERMANENT TEMPORARY DATA 1 12.0 M 500.0 M 512.0 M TEMPORARY TEMPORARY DATA 1 40.0 M 88.0 M 128.0 M - - 4 113.0 M 1.5 G 1.6 G ``` **-p, --purpose** This option shows detailed information on the purpose of stored data. The information includes number of files, used size, size of file tables, reserved sectors size and total size. ``` text Space description for database 'testdb' with pagesize 16.0K. (log pagesize: 16.0K) Detailed space description for files: data_type file_count used_size file_table_size reserved_size total_size INDEX 17 0.3 M 0.3 M 16.5 M 17.0 M HEAP 28 7.6 M 0.4 M 26.0 M 34.0 M SYSTEM 8 0.4 M 0.1 M 7.5 M 8.0 M TEMP 10 0.0 M 0.2 M 49.8 M 50.0 M - 63 8.2 M 1.0 M 99.8 M 109.0 M ``` ## compactdb The **coradb compactdb** utility is used to secure unused space of the database volume. In case the database server is not running (offline), you can perform the job in standalone mode. In case the database server is running, you can perform it in client-server mode. > **Note:** > The **coradb compactdb** utility secures the space being taken by OIDs of deleted objects and by class changes. When an object is deleted, the space taken by its OID is not immediately freed because there might be other objects that refer to the deleted one. > > Therefore, when you make a table to reuse OIDs, it is recommended to use a REUSE_OID option as below. > > ``` sql > CREATE TABLE tbl REUSE_OID > ( > id INT PRIMARY KEY, > b VARCHAR > ); > ``` > > However, a table with a REUSE_OID option cannot be referred by the other table. That is, this table cannot be used as a type of the other table. > > ``` sql > CREATE TABLE reuse_tbl (a INT PRIMARY KEY) REUSE_OID; > CREATE TABLE tbl_1 ( a reuse_tbl); > ``` > > ``` text > ERROR: The class 'reuse_tbl' is marked as REUSE_OID and is non-referable. Non-referable classes can't be the domain of an attribute and their instances' OIDs cannot be returned. > ``` > > To see details of REUSE_OID, please refer to [REUSE_OID](https://www.coradb.ai/manual/sql/schema/table_stmt.html#reuse_oid). Reference to the object deleted during compacting is displayed as **NULL**, which means this can be reused by OIDs. ``` bash coradb compactdb [options] database_name [class_name], class_name2, ...] ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **compactdb**: A command that compacts the space of the database so that OIDs assigned to deleted data can be reused. - *database_name*: The name of the database whose space is to be compacted. The path name to the directory where the database is to be created must not be included. - *class_name_list*: You can specify the list of tables names that you want to compact space after a database name; the **-i** option cannot be used together. If you use the lists on client/server mode, it skips securing space taken by objects such as catalog, delete files and tracker, etc. **-I**, **-c**, **-d**, **-p** options are applied in client/server mode only. The following shows \[options\] available with the **coradb compactdb** utility. **-v, --verbose** You can output messages that shows which class is currently being compacted and how many instances have been processed for the class by using the **-v** option. ``` bash coradb compactdb -v testdb ``` **-S, --SA-mode** This option specifies to compact used space in standalone mode while database server is not running; no argument is specified. If the **-S** option is not specified, system recognizes that the job is executed in client/server mode. ``` bash coradb compactdb --SA-mode testdb ``` **-C, --CS-mode** This option specifies to compact used space in client/server mode while database server is running; no argument is specified. Even though this option is omitted, system recognizes that the job is executed in client/server mode. **-i, --input-class-file=FILE** You can specify an input file name that contains the table name with this option. Write one table name in a single line; invalid table name is ignored. Note that you cannot specify the list of the table names after a database name in case of you use this option. If you use this option on client/server mode, it skips securing space taken by objects such as catalog, delete files and tracker, etc. The following options can be used in client/server mode only. **-p, --pages-commited-once=NUMBER** You can specify the number of maximum pages that can be committed once with this option. The default value is 10, the minimum value is 1, and the maximum value is 10. The less option value is specified, the more concurrency is enhanced because the value for class/instance lock is small; however, it causes slowdown on operation, and vice versa. ``` bash coradb compactdb --CS-mode -p 10 testdb tbl1, tbl2, tbl5 ``` **-d, --delete-old-repr** You can delete an existing table representation (schema structure) from catalog with this option. Generally you'd better keep the existing table representation because schema updating cost will be saved when you keep the status as referring to the past schema for the old records. **-I, --Instance-lock-timeout=NUMBER** You can specify a value of instance lock timeout with this option. The default value is 2 (seconds), the minimum value is 1, and the maximum value is 10. The less option value is specified, the more operation speeds up. However, the number of instances that can be processed becomes smaller, and vice versa. **-c, --class-lock-timeout=NUMBER** You can specify a value of instance lock timeout with this option. The default value is 10 (seconds), the minimum value is 1, and the maximum value is 10. The less option value is specified, the more operation speeds up. However, the number of tables that can be processed becomes smaller, and vice versa. ## vacuumdb **coradb vacuumdb** removes the old row versions and index entries left behind by updates and deletes (see [MVCC and VACUUM](https://www.coradb.ai/manual/sql/transaction_mvcc.html)). The database server normally does this continuously in the background; vacuumdb runs the same cleanup on demand for a stopped database. ```text coradb vacuumdb [option] database_name ``` | Option | Meaning | |---|---| | **-S**, **--SA-mode** | Standalone mode: the database server must be stopped | | **-C**, **--CS-mode** | Client-server mode; currently not available (`Vacuumdb is temporary not available for client-server mode`) | ```bash coradb server stop testdb coradb vacuumdb -S testdb ``` The SQL statement **VACUUM** does the same in a standalone corasql session (`corasql -S`). ## optimizedb Updates statistical information such as the number of objects, the number of pages to access, and the distribution of attribute values. ``` bash coradb optimizedb [option] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **optimizedb**: Updates the statistics information, which is used for cost-based query optimization of the database. If the option is specified, only the information of the specified class is updated. - *database_name*: The name of the database whose cost-based query optimization statistics are to be updated. The following shows \[option\] available with the **coradb optimizedb** utility. **-n, --class-name** The following example shows how to update the query statistics information of the given class by using the **-n** option. ``` bash coradb optimizedb -n event_table testdb ``` The following example shows how to update the query statistics information of all classes in the database. ``` bash coradb optimizedb testdb ``` ## plandump The **coradb plandump** utility is used to display information on the query plans stored (cached) on the server. ``` bash coradb plandump [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **plandump**: A utility that displays the query plans stored in the current cache of a specific database. - *database_name*: The name of the database where the query plans are to be checked or dropped from its server cache. If no option is used, it checks the query plans stored in the cache. ``` bash coradb plandump testdb ``` The following shows \[options\] available with the **coradb plandump** utility. **-d, --drop** This option drops the query plans stored in the cache. ``` bash coradb plandump -d testdb ``` **-o, --output-file=FILE** This option stores the results of the query plans stored in the cache to a file. ``` bash coradb plandump -o output.txt testdb ``` --- # Server statistics: statdump Source: https://www.coradb.ai/manual/admin/admin_statdump.html ## statdump **coradb statdump** utility checks statistics information processed by the CoraDB database server. The statistics information mainly consists of the following: File I/O, Page buffer, Logs, Transactions, Concurrency/Lock, Index, and Network request. You can also use corasql's session commands to check the statistics information only about the corasql's connection. For details, see [Dumping corasql execution statistics information](https://www.coradb.ai/manual/corasql.html#corasql-execution-statistics). ``` bash coradb statdump [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **statdump**: A command that dumps the statistics information on the database server execution. - *database_name*: The name of database which has the statistics data to be dumped. The following shows \[options\] available with the **coradb statdump** utility. **-i, --interval=SECOND** This option specifies the periodic number of Dumping statistics as seconds. The following outputs the accumulated values per second. ``` bash coradb statdump -i 1 -c testdb ``` The following outputs the accumulated values during 1 second, as starting with 0 value per every 1 second. ``` bash coradb statdump -i 1 testdb ``` The following outputs the last values which were executed with **-i** option. ``` bash coradb statdump testdb ``` The following outputs the same values with the above. **-c** option doesn't work if it is not used with **-i** option together. > coradb statdump -c testdb The following outputs the values per every 5 seconds. ``` bash $ coradb statdump -i 5 -c testdb Mon November 11 23:44:36 KST 2019 *** SERVER EXECUTION STATISTICS *** Num_file_creates = 0 Num_file_removes = 0 Num_file_ioreads = 0 Num_file_iowrites = 3 Num_file_iosynches = 3 The timer values for file_iosync_all are: Num_file_iosync_all = 0 Total_time_file_iosync_all = 0 Max_time_file_iosync_all = 0 Avg_time_file_iosync_all = 0 Num_file_page_allocs = 0 Num_file_page_deallocs = 0 Num_data_page_fetches = 0 Num_data_page_dirties = 0 Num_data_page_ioreads = 0 Num_data_page_iowrites = 0 Num_data_page_flushed = 0 Num_data_page_private_quota = 11327 Num_data_page_private_count = 0 Num_data_page_fixed = 1 Num_data_page_dirty = 0 Num_data_page_lru1 = 18 Num_data_page_lru2 = 10 Num_data_page_lru3 = 0 Num_data_page_victim_candidate = 0 Num_log_page_fetches = 0 Num_log_page_ioreads = 0 Num_log_page_iowrites = 6 Num_log_append_records = 9 Num_log_archives = 0 Num_log_start_checkpoints = 0 Num_log_end_checkpoints = 0 Num_log_wals = 0 Num_log_page_iowrites_for_replacement = 0 Num_log_page_replacements = 0 Num_page_locks_acquired = 0 Num_object_locks_acquired = 0 Num_page_locks_converted = 0 Num_object_locks_converted = 0 Num_page_locks_re-requested = 0 ... ``` The following are the explanation about the above statistical information. You can find the statistic category (database module), the name, the stat type and a brief description for each statistic. There are several types of statistic, based on how they are collected: - Accumulator: The stat values are incremented whenever the tracked action happens. - Counter/timer: The stat tracks both the number and the duration of an action. Also biggest and average duration are tracked. - Snapshot: The stat is peeked from database. - Complex: The stat tracks multiple values for an action, separated by various attributes. Most statistics are accumulators (they are incremented when an action happens). Other statistics can be counter/timers (they track both number of actions and their duration), some are peeked from database (snapshot) and some are computed based on other values. Lastly, there are several complex statistics which track detailed information on some operations. **File I/O** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_file_removes | Accumulator | The number of files removed | | Num_file_creates | Accumulator | The number of files created | | Num_file_ioreads | Accumulator | The number of files read | | Num_file_iowrites | Accumulator | The number of files stored | | Num_file_iosynches | Accumulator | The number of file synchronization | | ..file_iosync_all | Counter/timer | The number and duration of sync all files | | Num_file_page_allocs | Accumulator | The number of page allocations | | Num_file_page_deallocs | Accumulator | The number of page deallocations | **Page buffer** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_data_page_fetches | Accumulator | The number of fetched pages | | Num_data_page_dirties | Accumulator | The number of dirty pages | | Num_data_page_ioreads | Accumulator | The number of pages read from disk (more means less efficient, it correlates with lower hit ratio) | | Num_data_page_iowrites | Accumulator | The number of pages write to disk (more means less efficient) | | Num_data_page_private_quota | Snapshot | The target number of pages for private LRU lists | | Num_data_page_private_count | Snapshot | The actual number of pages for private LRU lists | | Num_data_page_fixed | Snapshot | The number of fixed pages in data buffer | | Num_data_page_dirty | Snapshot | The number of dirty pages in data buffer | | Num_data_page_lru1 | Snapshot | The number of pages in LRU1 zone in data buffer | | Num_data_page_lru2 | Snapshot | The number of pages in LRU2 zone in data buffer | | Num_data_page_lru3 | Snapshot | The number of pages in LRU3 zone in data buffer | | Num_data_page_victim_candidate | Snapshot | The number of victim candidate pages in data buffer | **Logs** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_log_page_fetches | Accumulator | The number of fetched log pages | | Num_log_page_ioreads | Accumulator | The number of log pages read | | Num_log_page_iowrites | Accumulator | The number of log pages stored | | Num_log_append_records | Accumulator | The number of log records appended | | Num_log_archives | Accumulator | The number of logs archived | | Num_log_start_checkpoints | Accumulator | The number of started checkpoints | | Num_log_end_checkpoints | Accumulator | The number of ended checkpoints | | Num_log_wals | Accumulator | The number of log flushes requested to write a data page. | | Num_log_page_iowrites_for_replacement | Accumulator | The number of log data pages written to disk due to replacements (should be zero) | | Num_log_page_replacements | Accumulator | The number of log data pages discarded due to replacements | | Num_prior_lsa_list_size | Accumulator | Current size of the prior LSA(Log Sequence Address) list. CoraDB write the order of writing into the prior LSA list, before writing operation from the log buffer to the disk; this list is used to raise up the concurrency by reducing the waiting time of the transaction from writing to disk | | Num_prior_lsa_list_maxed | Accumulator | The count of the prior LSA list being reached at the maximum size. The maximum size of the prior LSA list is log_buffer_size * 2. If this value is big, we can assume that log writing jobs happen a lot at the same time | | Num_prior_lsa_list_removed | Accumulator | The count of LSA being moved from prior LSA list into log buffer. We can assume that the commits have happened at the similar count with this value | | Log_page_buffer_hit_ratio | Computed | Hit ratio of log page buffers (Num_log_page_fetches - Num_log_page_fetch_ioreads)*100 / Num_log_page_fetches | **Concurrency/lock** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_page_locks_acquired | Accumulator | The number of locked pages acquired | | Num_object_locks_acquired | Accumulator | The number of locked objects acquired | | Num_page_locks_converted | Accumulator | The number of locked pages converted | | Num_object_locks_converted | Accumulator | The number of locked objects converted | | Num_page_locks_re-requested | Accumulator | The number of locked pages requested | | Num_object_locks_re-requested | Accumulator | The number of locked objects requested | | Num_page_locks_waits | Accumulator | The number of locked pages waited | | Num_object_locks_waits | Accumulator | The number of locked objects waited | | Num_object_locks_time_waited_usec | Accumulator | The time in microseconds spent on waiting for all object locks | | Time_obj_lock_acquire_time | Complex | Time consumer for locking objects classified by lock mode | **Transactions** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_tran_commits | Accumulator | The number of commits | | Num_tran_rollbacks | Accumulator | The number of rollbacks | | Num_tran_savepoints | Accumulator | The number of savepoints | | Num_tran_start_topops | Accumulator | The number of top operations started | | Num_tran_end_topops | Accumulator | The number of top operations stopped | | Num_tran_interrupts | Accumulator | The number of interruptions | | Num_tran_postpone_cache_hits | Accumulator | The number of cache hits when executing transaction postpone ops | | Num_tran_postpone_cache_miss | Accumulator | The number of cache misses when executing transaction postpone ops Cache misses may degrade performance of transaction commits and may impact all log operations | | Num_tran_topop_postpone_cache_hits | Accumulator | The number of cache hits when executing top operations postpone ops | | Num_tran_topop_postpone_cache_miss | Accumulator | The number of cache misses when executing top operations postpone Cache misses may degrade performance of top operations commits and may impact all log operations | **Index** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_btree_inserts | Accumulator | The number of nodes inserted | | Num_btree_deletes | Accumulator | The number of nodes deleted | | Num_btree_updates | Accumulator | The number of nodes updated | | Num_btree_covered | Accumulator | The number of cases in which an index includes all data upon query execution | | Num_btree_noncovered | Accumulator | The number of cases in which an index includes some or no data upon query execution | | Num_btree_resumes | Accumulator | The exceeding number of index scan specified due to too many results | | Num_btree_multirange_optimization | Accumulator | The number of executions on multi-range optimization for the WHERE ... IN ... LIMIT condition query statement | | Num_btree_splits | Accumulator | The number of B-tree split-operations | | Num_btree_merges | Accumulator | The number of B-tree merge-operations | | Num_btree_get_stats | Accumulator | The number of B-tree get stat calls | | ..bt_leaf | Counter/timer | The number and duration of all operations in index leaves | | ..bt_find_unique | Counter/timer | The number and duration of B-tree 'find-unique' operations | | ..btrange_search | Counter/timer | The number and duration of B-tree 'range-search' operations | | ..bt_insert_obj | Counter/timer | The number and duration of B-tree 'insert object' operations | | ..bt_delete_obj | Counter/timer | The number and duration of B-tree 'physical delete object' operations | | ..bt_mvcc_delete | Counter/timer | The number and duration of B-tree 'mvcc delete' operations | | ..bt_mark_delete | Counter/timer | The number and duration of B-tree mark delete operations | | ..bt_undo_insert | Counter/timer | The number and duration of B-tree 'undo insert' operations | | ..bt_undo_delete | Counter/timer | The number and duration of B-tree 'undo physical delete' operations | | ..bt_undo_mvcc_delete | Counter/timer | The number and duration of B-tree 'undo mvcc delete' operations | | ..bt_vacuum | Counter/timer | The number and duration of B-tree vacuum deleted object operations | | ..bt_vacuum_insid | Counter/timer | The number and duration of vacuum operations on B-tree 'insert id' | | ..bt_fix_ovf_oids | Counter/timer | The number and duration of B-tree overflow page fixes | | ..bt_unique_rlocks | Counter/timer | The number and duration of blocked read locks on unique indexes | | ..bt_unique_wlocks | Counter/timer | The number and duration of blocked write locks on unique indexes | | ..bt_traverse | Counter/timer | The number and duration of B-tree traverse | | ..bt_find_unique_traverse | Counter/timer | The number and duration of B-tree traverse for 'find unique' | | ..bt_range_search_traverse | Counter/timer | The number and duration of B-tree traverse for 'range search' | | ..bt_insert_traverse | Counter/timer | The number and duration of B-tree traverse for 'insert' | | ..bt_delete_traverse | Counter/timer | The number and duration of B-tree traverse for 'physical delete' | | ..bt_mvcc_delete_traverse | Counter/timer | The number and duration of B-tree traverse for 'mvcc delete' | | ..bt_mark_delete_traverse | Counter/timer | The number and duration of B-tree traverse for 'mark delete' | | ..bt_undo_insert_traverse | Counter/timer | The number and duration of B-tree traverse for 'undo physical insert' | | ..bt_undo_delete_traverse | Counter/timer | The number and duration of B-tree traverse for 'undo physical delete' | | ..bt_undo_mvcc_delete_traverse | Counter/timer | The number and duration of B-tree traverse for 'undo delete' | | ..bt_vacuum_traverse | Counter/timer | The number and duration of B-tree traverse for vacuum deleted object | | ..bt_vacuum_insid_traverse | Counter/timer | The number and duration of B-tree traverse for vacuum 'insert id' | **Load index online** | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..btree_online_load | Counter/timer | The number and duration of B-tree online index loading statements | | ..btree_online_insert_task | Counter/timer | The number and duration of batch insert tasks by index loader | | ..btree_online_prepare_task | Counter/timer | The number and duration of preparing (sorting) index loader tasks | | ..btree_online_insert_leaf | Counter/timer | The number and duration of leaf pages processed by index loader (multiple keys may be inserted while a leaf page is processed) | | Num_btree_online_inserts | Accumulator | The number of key inserts by index loader | | Num_btree_online_inserts_same_page_hold | Accumulator | The number of successive inserts by index loader in same leaf page (loader optimization to avoid expensive index traversals) | | Num_btree_online_inserts_retry | Accumulator | The number of restarted inserts because successive keys do not belong to same leaf or because there is not enough space | | Num_btree_online_inserts_retry_nice | Accumulator | The number of restarted inserts to let others access leaf page | **Query** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_query_selects | Accumulator | The number of SELECT query execution | | Num_query_inserts | Accumulator | The number of INSERT query execution | | Num_query_deletes | Accumulator | The number of DELETE query execution | | Num_query_updates | Accumulator | The number of UPDATE query execution | | Num_query_sscans | Accumulator | The number of sequential scans (full scan) | | Num_query_iscans | Accumulator | The number of index scans | | Num_query_lscans | Accumulator | The number of LIST scans | | Num_query_setscans | Accumulator | The number of SET scans | | Num_query_methscans | Accumulator | The number of METHOD scans | | Num_query_nljoins | Accumulator | The number of nested loop joins | | Num_query_mjoins | Accumulator | The number of parallel joins | | Num_query_objfetches | Accumulator | The number of fetch objects | | Num_query_holdable_cursors | Snapshot | The number of holdable cursors in the current server. | **Sort** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_sort_io_pages | Accumulator | The number of pages fetched on the disk during sorting (more means less efficient) | | Num_sort_data_pages | Accumulator | The number of pages found on the page buffer during sorting (more means less efficient) | **Network** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_network_requests | Accumulator | The number of network requested | **Heap** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_heap_stats_sync_bestspace | Accumulator | The updated number of the "best page" list. "Best pages" means that the data pages of which the free space is more than 30% in the environment of multiple INSERTs and DELETEs. Only some information of these pages are saved as the "best page" list. In the "best page" list, the information of a million pages is saved at once. This list is searched when INSERTing a record, and then this list is updated when there are no free space to store this record on the pages. If there are still no free space to store this record even this list is updated for several times, this recorded is stored into a new page. | | Num_heap_home_inserts | Accumulator | The number of inserts in heap HOME type records | | Num_heap_big_inserts | Accumulator | The number of inserts in heap BIG type records | | Num_heap_assign_inserts | Accumulator | The number of inserts in heap ASSIGN type records | | Num_heap_home_deletes | Accumulator | The number of deletes from heap HOME type records in non-MVCC mode | | Num_heap_home_mvcc_deletes | Accumulator | The number of deletes from heap HOME type records in MVCC mode | | Num_heap_home_to_rel_deletes | Accumulator | The number of deletes from heap HOME to RELOCATION type records in MVCC mode | | Num_heap_home_to_big_deletes | Accumulator | The number of deletes from heap HOME to BIG type records in MVCC mode | | Num_heap_rel_deletes | Accumulator | The number of deletes from heap RELOCATION type records in non-MVCC mode | | Num_heap_rel_mvcc_deletes | Accumulator | The number of deletes from heap RELOCATION type records in MVCC mode | | Num_heap_rel_to_home_deletes | Accumulator | The number of deletes from heap RELOCATION to HOME type records in MVCC mode | | Num_heap_rel_to_big_deletes | Accumulator | The number of deletes from heap RELOCATION to BIG type records in MVCC mode | | Num_heap_rel_to_rel_deletes | Accumulator | The number of deletes from heap RELOCATION to RELOCATION type records in MVCC mode | | Num_heap_big_deletes | Accumulator | The number of deletes from heap BIG type records in non-MVCC mode | | Num_heap_big_mvcc_deletes | Accumulator | The number of deletes from heap BIG type records in MVCC mode | | Num_heap_home_updates | Accumulator | The number of updates in place of heap HOME type records in non-MVCC mode(*) | | Num_heap_home_to_rel_updates | Accumulator | The number of updates of heap HOME to RELOCATION type records in non-MVCC mode(*) | | Num_heap_home_to_big_updates | Accumulator | The number of updates of heap HOME to BIG type records in non-MVCC mode(*) | | Num_heap_rel_updates | Accumulator | The number of updates of heap RELOCATION type records in non-MVCC mode(*) | | Num_heap_rel_to_home_updates | Accumulator | The number of updates of heap RELOCATION to HOME type records in non-MVCC mode(*) | | Num_heap_rel_to_rel_updates | Accumulator | The number of updates of heap RELOCATION to RELOCATION type records in non-MVCC mode(*) | | Num_heap_rel_to_big_updates | Accumulator | The number of updates of heap RELOCATION to BIG type records in non-MVCC mode(*) | | Num_heap_big_updates | Accumulator | The number of updates of heap BIG type records in non-MVCC mode(*) | | Num_heap_home_vacuums | Accumulator | The number of vacuumed heap HOME type records | | Num_heap_big_vacuums | Accumulator | The number of vacuumed heap BIG type records | | Num_heap_rel_vacuums | Accumulator | The number of vacuumed heap RELOCATION type records | | Num_heap_insid_vacuums | Accumulator | The number of vacuumed heap newly inserted records | | Num_heap_remove_vacuums | Accumulator | The number of vacuum operations that remove heap records | | ..heap_insert_prepare | Counter/timer | The number and duration of preparing heap insert operation | | ..heap_insert_execute | Counter/timer | The number and duration of executing heap insert operation | | ..heap_insert_log | Counter/timer | The number and duration of logging heap insert operation | | ..heap_delete_prepare | Counter/timer | The number and duration of preparing heap delete operation | | ..heap_delete_execute | Counter/timer | The number and duration of executing heap delete operation | | ..heap_delete_log | Counter/timer | The number and duration of logging heap delete operation | | ..heap_update_prepare | Counter/timer | The number and duration of preparing heap update operation | | ..heap_update_execute | Counter/timer | The number and duration of executing heap update operation | | ..heap_update_log | Counter/timer | The number and duration of logging heap update operation | | ..heap_vacuum_prepare | Counter/timer | The number and duration of preparing heap vacuum operation | | ..heap_vacuum_execute | Counter/timer | The number and duration of executing heap vacuum operation | | ..heap_vacuum_log | Counter/timer | The number and duration of logging heap vacuum operation | **Query plan cache** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_plan_cache_add | Accumulator | The number of entries added to query cache | | Num_plan_cache_lookup | Accumulator | The number of lookups in query cache | | Num_plan_cache_hit | Accumulator | The number of hits in query cache | | Num_plan_cache_miss | Accumulator | The number of misses in query cache | | Num_plan_cache_full | Accumulator | The number of times query cache becomes full | | Num_plan_cache_delete | Accumulator | The number of entries deleted from query cache | | Num_plan_cache_invalid_xasl_id | Accumulator | The number of failed attempts of retrieving entries by XASL ID. | | Num_plan_cache_entries | Snapshot | The current number of entries in query cache | **Vacuuming** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_vacuum_log_pages_vacuumed | Accumulator | The number of log data pages processed by vacuum workers. | | Num_vacuum_log_pages_to_vacuum | Accumulator | The number of log data pages to be vacuumed by vacuum workers. (if value is much bigger than Num_vacuum_log_pages_vacuumed, it means vacuum system lags behind) | | Num_vacuum_prefetch_requests_log_pages | Accumulator | The number of requests to prefetch buffer for log pages from vacuum | | Num_vacuum_prefetch_hits_log_pages | Accumulator | The number of hits to prefetch buffer for log pages from vacuum | | ..vacuum_master | Counter/timer | The number and duration of vacuum master iterations. | | ..vacuum_job | Counter/timer | The number and duration of vacuum jobs | | ..vacuum_worker_process_log | Counter/timer | The number and duration of process log tasks | | ..vacuum_worker_execute | Counter/timer | The number and duration of execute vacuum tasks | | Vacuum_data_page_buffer_hit_ratio | Computed | Hit ratio of vacuuming data page buffers | | Vacuum_page_efficiency_ratio | Computed | Ratio between number of page unfix of vacuum with dirty flag and total number of page unfix of vacuum. Ideally, the vacuum process performsonly write operations since it cleans up all unused records. Even with an optimized vacuum process, 100% efficiency is not possible. | | Vacuum_page_fetch_ratio | Computed | Ratio (percentage) of page unfix from vacuum module versus total. | | Num_data_page_avoid_dealloc | Snapshot | The number of data pages that cannot be deallocated by vacuum | **Heap bestspace** | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..heap_stats_sync_bestspace | Counter/timer | The number and duration of bestspace synchronization operations | | Num_heap_stats_bestspace_entries | Accumulator | The number of best pages which are saved on the "best page" list | | Num_heap_stats_bestspace_maxed | Accumulator | The maximum number of pages which can be saved on the "best page" list | | ..bestspace_add | Counter/timer | The number and duration of adding entries to bestspace cache | | ..bestspace_del | Counter/timer | The number and duration of deleting from bestpace cache | | ..bestspace_find | Counter/timer | The number and duration of finding a bestpace cache entry | | ..heap_find_page_bestspace | Counter/timer | The number and duration of searching heap pages in bestspace cache | | ..heap_find_best_page | Counter/timer | The number and duration of finding or creating (if not found) a page to insert in heap. | **Page buffer fix** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Data_page_fix_lock_acquire_time_msec | Computed | Time waiting for other transaction to load page from disk | | Data_page_fix_hold_acquire_time_msec | Computed | Time to obtain page latch | | Data_page_fix_acquire_time_msec | Computed | Total time to fix page | | Data_page_allocate_time_ratio | Computed | Ratio of time necessary for page loading from disk versus the total time of fixing a page | | Data_page_total_promote_success | Computed | Number of successful page latch promotions from shared to exclusive | | Data_page_total_promote_fail | Computed | Number of failed page latch promotions | | Data_page_total_promote_time_msec | Computed | Time for promoting page latches | | Num_data_page_hash_anchor_waits | Accumulator | Number of waits on page buffer hash bucket | | Time_data_page_hash_anchor_wait | Accumulator | Total wait time on page buffer hash bucket | | Num_data_page_fix_ext | Complex | Number of data page fixes classified by: - module (system, worker, vacuum) - page type - page fetch/found mode - page latch mode - page latch condition | | Time_data_page_lock_acquire_time | Complex | Time consumed waiting for other thread to load data page from disk: - module (system, worker, vacuum) - page type - page fetch/found mode - page latch mode - page latch condition | | Time_data_page_hold_acquire_time | Complex | Time consumed waiting for data page latch: - module (system, worker, vacuum) - page type - page fetch/found mode - page latch mode | | Time_data_page_fix_acquire_time | Complex | Time consumed fixing data page: - module (system, worker, vacuum) - page type - page fetch/found mode - page latch mode - page latch condition | | Num_data_page_promote_ext | Complex | Number of data page promotions classified by: - module (system, worker, vacuum) - page type - promote latch condition - holder latch mode - successful/failed promotion | | Num_data_page_promote_time_ext | Complex | Time consumed for data page promotions classified by: - module (system, worker, vacuum) - page type - promote latch condition - holder latch mode - successful/failed promotion | **Page buffer unfix** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Num_unfix_void_to_private_top | Accumulator | Unfix newly loaded data page and add to top of private LRU list | | Num_unfix_void_to_private_mid | Accumulator | Unfix newly loaded data page and add to middle of private LRU list | | Num_unfix_void_to_shared_mid | Accumulator | Unfix newly loaded data page and add to middle of shared LRU list | | Num_unfix_lru1_private_to_shared_mid | Accumulator | Unfix data page and move from zone 1 of private list to shared middle | | Num_unfix_lru2_private_to_shared_mid | Accumulator | Unfix data page and move from zone 2 of private list to shared middle | | Num_unfix_lru3_private_to_shared_mid | Accumulator | Unfix data page and move from zone 3 of private list to shared middle | | Num_unfix_lru2_private_keep | Accumulator | Unfix data page and keep it in zone 2 of private list | | Num_unfix_lru2_shared_keep | Accumulator | Unfix data page and keep it in zone 2 of shared list | | Num_unfix_lru2_private_to_top | Accumulator | Unfix data page and boost it from zone 2 of private list to its top | | Num_unfix_lru2_shared_to_top | Accumulator | Unfix data page and boost it from zone 2 of shared list to its top | | Num_unfix_lru3_private_to_top | Accumulator | Unfix data page and boost it from zone 3 of private list to its top | | Num_unfix_lru3_shared_to_top | Accumulator | Unfix data page and boost it from zone 3 of shared list to its top | | Num_unfix_lru1_private_keep | Accumulator | Unfix data page and keep it in zone 1 of private list | | Num_unfix_lru2_shared_keep | Accumulator | Unfix data page and keep it in zone 2 of shared list | | Num_unfix_void_to_private_mid_vacuum | Accumulator | Unfix newly loaded data page and add to middle of private LRU list (vacuum thread) | | Num_unfix_lru1_any_keep_vacuum | Accumulator | Unfix data page and keep it in zone 1 of private/shared list (vacuum thread) | | Num_unfix_lru2_any_keep_vacuum | Accumulator | Unfix data page and keep it in zone 2 of private/shared list (vacuum thread) | | Num_unfix_lru3_any_keep_vacuum | Accumulator | Unfix data page and keep it in zone 3 of private/shared list (vacuum thread) | | Num_unfix_void_aout_found | Accumulator | Newly loaded data page was found in AOUT list | | Num_unfix_void_aout_not_found | Accumulator | Newly loaded data page was not found in AOUT list | | Num_unfix_void_aout_found_vacuum | Accumulator | Newly loaded data page was found in AOUT list (vacuum thread) | | Num_unfix_void_aout_not_found_vacuum | Accumulator | Newly loaded data page was not found in AOUT list (vacuum thread) | | Num_data_page_unfix_ext | Complex | Number of data page unfixes classified by: - module (system, worker, vacuum) - page type - dirty or not - dirtied by holder or not - holder latch mode | **Page buffer I/O** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Data_page_buffer_hit_ratio | Computed | Hit ratio of data page buffers (Num_data_page_fetches - Num_data_page_ioreads)*100 / Num_data_page_fetches | | Num_adaptive_flush_pages | Accumulator | The number of data pages requested from adaptive flush controller. | | Num_adaptive_flush_log_pages | Accumulator | The number of log data pages requested from adaptive flush controller | | Num_adaptive_flush_max_pages | Accumulator | The total number of page tokens assigned by adaptive flush controller | | ..compensate_flush | Counter/timer | The number and duration of flush compensations force by adaptive flush controller | | ..assign_direct_bcb | Counter/timer | The number and duration of assigning bcb's directly to waiters | | ..wake_flush_waiter | Counter/timer | The number and duration of waking up a thread waiting for bcb | | ..flush_collect | Counter/timer | The number and duration of flush thread collecting BCB sets | | ..flush_flush | Counter/timer | The number and duration of flush thread flushing BCB sets | | ..flush_sleep | Counter/timer | The number and duration of flush thread pauses | | ..flush_collect_per_page | Counter/timer | The number and duration of flush thread collecting one BCB | | ..flush_flush_per_page | Counter/timer | The number and duration of flush thread flushing one BCB | | Num_data_page_writes | Accumulator | The total number of data pages flushed to disk | | Num_data_page_dirty_to_post_flush | Accumulator | Number of flushed pages sent to post-flush thread for processing | | Num_data_page_skipped_flush | Accumulator | The total number of BCB's that flush thread skipped | | Num_data_page_skipped_flush_need_wal | Accumulator | The number of BCB's that flush thread skipped because it required log data pages be flushed first | | Num_data_page_skipped\ _flush_already_flushed | Accumulator | The number of BCB's that flush thread skipped because they have been flushed already | | Num_data_page_skipped_flush_fixed_or_hot | Accumulator | The number of BCB's that flush thread skipped because they are fixed or have been fixed since collected. | **Page buffer victimization** | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..alloc_bcb | Counter/timer | The number and duration of BCB allocation to store new data page. When a database is just started, the page buffer has available BCB's ready to be picked. However, once page buffer becomes full all BCB's are in use, one must be victimized. The time tracked here includes BCB victimization and loading from disk. | | ..alloc_bcb_search_victim | Counter/timer | The number and duration of searches through all LRU lists for victims | | ..alloc_bcb_cond_wait_high_prio | Counter/timer | The number and duration of direct victim waits in high-priority queue | | ..alloc_bcb_cond_wait_low_prio | Counter/timer | The number and duration of direct victim waits in low-priority queue | | Num_alloc_bcb_prioritize_vacuum | Accumulator | The number of vacuum direct victim waits in high-priority queue | | Num_alloc_bcb_wait_threads_high_priority | Snapshot | The current number of direct victim waiters in high-priority queue | | Num_alloc_bcb_wait_threads_low_priority | Snapshot | The current number of direct victim waiters in low-priority queue | | Num_flushed_bcbs_wait_for_direct_victim | Snapshot | The current number of BCB's waiting for post-flush thread to process them and assign directly. | | Num_victim_use_invalid_bcb | Accumulator | The number of BCB's allocated from invalid list | | ..alloc_bcb_get_victim_search_own_private_list | Counter/timer | The number and duration of getting a victim from own private list | | ..alloc_bcb_get_victim_search_others_private_list | Counter/timer | The number and duration of getting a victim from other private lists | | ..alloc_bcb_get_victim_searchshared_list | Counter/timer | The number and duration of getting a victim from a shared list | | Num_data_page_avoid_victim | Accumulator | The number of BCB's that cannot be victimized because they are in process of being flushed to disk | | Num_victim_assign_direct_vacuum_void | Accumulator | The number of direct victims assigned from void zone by vacuum worker | | Num_victim_assign_direct_vacuum_lru | Accumulator | The number of direct victims assigned from LRU zone 3 by vacuum worker | | Num_victim_assign_direct_flush | Accumulator | The number of direct victims assigned by flush thread | | Num_victim_assign_direct_panic | Accumulator | The number of direct victims assigned by panicked LRU searches. If there are a lot of waiters for victims, threads that found other victims while searching LRU list, will also try to assign more directly. Page buffer maintenance thread assignments are also counted here | | Num_victim_assign_direct_adjust_lru | Accumulator | The number of direct victims assigned when BCB falls to LRU zone 3 | | Num_victim_assign_direct_adjust_lru_to_vacuum | Accumulator | The number of BCB's falling to LRU zone 3 **not** assigned as direct victims because a vacuum thread is expected to access it | | Num_victim_assign_direct_search_for_flush | Accumulator | The number of direct victims assigned by flush thread while collecting BCB sets for flush | | Num_victim_shared_lru_success | Accumulator | The number of successful victim searches in shared LRU lists | | Num_victim_own_private_lru_success | Accumulator | The number of successful victim searches in own private LRU lists | | Num_victim_other_private_lru_success | Accumulator | The number of successful victim searches in other private LRU lists | | Num_victim_shared_lru_fail | Accumulator | The number of failed victim searches in shared LRU lists | | Num_victim_own_private_lru_fail | Accumulator | The number of failed victim searches in own private LRU lists | | Num_victim_other_private_lru_fail | Accumulator | The number of failed victim searches in other private LRU lists | | Num_victim_all_lru_fail | Accumulator | The number of unlucky streaks to find victims in the sequence: 1. Own private LRU list (if over quota) 2. Other private LRU list (if own private is over quota) 3. Shared LRU list (this is simplified explanation, see *pgbuf_get_victim* function) | | Num_victim_get_from_lru | Accumulator | The total number of victim searches in any LRU list | | Num_victim_get_from_lru_was_empty | Accumulator | The number of victim searches in any LRU list that stop immediately because candidate count is zero | | Num_victim_get_from_lru_fail | Accumulator | The number of failed victim searches in any LRU list although the candidate count was not zero | | Num_victim_get_from_lru_bad_hint | Accumulator | The number of failed victim searches in any LRU list because victim was wrong | | Num_lfcq_prv_get_total_calls | Accumulator | The number of victim searches in non-zero candidate private LRUs queue | | Num_lfcq_prv_get_empty | Accumulator | The number of times non-zero candidate private LRUs queue was empty | | Num_lfcq_prv_get_big | Accumulator | The number of victim searches in only very big non-zero candidate private LRUs queue (in this context, very big means way over quota) | | Num_lfcq_shr_get_total_calls | Accumulator | The number of victim searches in non-zero candidate shared LRUs queue | | Num_lfcq_shr_get_empty | Accumulator | The number of times non-zero candidate shared LRUs queue was empty | | Num_lfcq_big_private_lists | Snapshot | The current number of very big non-zero candidate private LRU lists | | Num_lfcq_private_lists | Snapshot | The current number of non-zero candidate private LRU lists | | Num_lfcq_shared_lists | Snapshot | The current number of non-zero candidate shared LRU lists | **Double write buffer** | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..DWB_flush_block | Counter/timer | The number of blocks flushed and total writing duration | | ..DWB_file_sync_helper | Counter/timer | The number and duration of files synchronized by DWB helper | | ..DWB_flush_block_cond_wait | Counter/timer | The number and duration of DWB thread waits | | ..DWB_flush_block_sort | Counter/timer | The number and duration of sorting pages for flush | | ..DWB_decache_pages_after_write | Counter/timer | The number and duration of removing pages from DWB cache after flush | | ..DWB_wait_flush_block | Counter/timer | The number and duration of waiting for block to be flush to add a page | | ..DWB_wait_file_sync_helper | Counter/timer | The number and duration of waiting for DWB helper to sync file | | ..DWB_flush_force | Counter/timer | The number and duration of forced full DWB flushes | | Num_dwb_flushed_block_volumes | Complex | A histogram of number of files synchronized by each block flush (last value is for ten or more files) | **MVCC snapshot** | **Stat name** | **Stat type** | **Description** | |---|---|---| | Time_get_snapshot_acquire_time: | Accumulator | Total time consumed by all transactions to get a snapshot | | Count_get_snapshot_retry: | Accumulator | The number of retries to acquire MVCC snapshot | | Time_tran_complete_time: | Accumulator | Time spent to invalidate snapshot and MVCCID on commit/rollback | | Time_get_oldest_mvcc_acquire_time: | Accumulator | Time spend to acquire "global oldest MVCC ID" | | Count_get_oldest_mvcc_retry: | Accumulator | The number of retries to acquire "global oldest MVCC ID" | | Num_mvcc_snapshot_ext | Complex | Number of data page fixes classified by: - snapshot type - insert/delete MVCCID's status - visible/invisible | **Thread workers** Statistics collected by thread worker pools: | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..start_thread | Counter/timer | The number and duration of starting new threads | | ..create_context | Counter/timer | The number and duration of creating thread context | | ..execute_task | Counter/timer | The number and duration of executed tasks | | ..retire_task | Counter/timer | The number and duration of retiring task objects | | ..found_task_in_queue | Counter/timer | The number of tasks found in queue and the duration of claiming from queue after finishing previous task | | ..wakeup_with_task | Counter/timer | The number of tasks assigned to threads on standby and the duration to wakeup thread | | ..recycle_context | Counter/timer | The number and duration of thread context recyclings between task executions | | ..retire_context | Counter/timer | The number and duration of retired thread contexts | Statistics are collected from two worker pools: - **Thread_stats_counters_timers**: statistics for workers executing client requests. - **Thread_loaddb_stats_counters_timers**: statistics for workers loading data into database (using **loaddb** command). *At least one load session must be active to see these statistics*. **Thread daemons** Statistics collected by background daemon threads: | **Stat name** | **Stat type** | **Description** | |---|---|---| | ..daemon_loop_count | Accumulator | The number of loops executed by daemon thread | | ..daemon_execute_time | Accumulator | The total duration spent by daemon thread on execution | | ..daemon_pause_time | Accumulator | The total duration spent by daemon thread between executions | | ..looper_sleep_count | Accumulator | The number of times thread looper was put to sleep | | ..looper_sleep_time | Accumulator | The total duration thread looper spent on sleep | | ..looper_reset_count | Accumulator | The number of times an incremental looper is reset by wakeup | | ..waiter_wakeup_count | Accumulator | The number of wakeup requests on daemon thread | | ..waiter_lock_wakeup_count | Accumulator | The number of wakeup requests on daemon thread that required lock | | ..waiter_sleep_count | Accumulator | The number of times daemon thread went to sleep | | ..waiter_timeout_count | Accumulator | The number of daemon thread waits ended with timeout | | ..waiter_no_sleep_count | Accumulator | The number of times daemon thread spins with no wait | | ..waiter_awake_count | Accumulator | The number of times daemon thread is awaken by other thread request | | ..waiter_wakeup_delay_time | Accumulator | The total duration of awaking daemon thread | Statistics are collected for next daemon threads: | **Daemon name** | **Description** | |---|---| | Page_flush_daemon_thread | Background thread that flushes data pages to disk | | Page_post_flush_daemon_thread | Background thread that may reclaim memory space occupied by flushes data pages | | Page_flush_control_daemon_thread | Background thread that controls data flush rate | | Page_maintenance_daemon_thread | Background thread that recalculates quotas for private LRU lists | | Deadlock_detect_daemon_thread | Background thread that looks for deadlocks and chooses victims to unblock the system | | Log_flush_daemon_thread | Background thread that flushes log data to disk | > **Note:** > (\*) : These statistics measure the non-MVCC operations or MVCC operations which are performed in-place (decided internally) **-o, --output-file=FILE** **-o** options is used to store statistics information of server processing for the database to a specified file. ``` bash coradb statdump -o statdump.log testdb ``` **-c, --cumulative** You can display the accumulated operation statistics information of the target database server by using the **-c** option. Num_data_page_fix_ext, Num_data_page_unfix_ext, Time_data_page_hold_acquire_time, Time_data_page_fix_acquire_time information can be output only when this option is specified; however, these information will be omitted because they are for CoraDB Engine developers. By combining this with the **-i** option, you can check the operation statistics information at a specified interval. ``` bash coradb statdump -i 5 -c testdb ``` **-s, --substr=STRING** You can display statistics about items, the names of which include the specified string by using **-s** option. The following example shows how to display statistics about items, the names of which include "data". ``` bash coradb statdump -s data testdb *** SERVER EXECUTION STATISTICS *** Num_data_page_fetches = 0 Num_data_page_dirties = 0 Num_data_page_ioreads = 0 Num_data_page_iowrites = 0 Num_data_page_flushed = 0 Num_data_page_private_quota = 327 Num_data_page_private_count = 898 Num_data_page_fixed = 1 Num_data_page_dirty = 3 Num_data_page_lru1 = 857 Num_data_page_lru2 = 873 Num_data_page_lru3 = 898 Num_data_page_victim_candidate = 898 Num_sort_data_pages = 0 Vacuum_data_page_buffer_hit_ratio = 0.00 Num_data_page_hash_anchor_waits = 0 Time_data_page_hash_anchor_wait = 0 Num_data_page_writes = 0 Num_data_page_dirty_to_post_flush = 0 Num_data_page_skipped_flush = 0 Num_data_page_skipped_flush_need_wal = 0 Num_data_page_skipped_flush_already_flushed = 0 Num_data_page_skipped_flush_fixed_or_hot = 0 Num_data_page_avoid_dealloc = 0 Num_data_page_avoid_victim = 0 Num_data_page_fix_ext: Num_data_page_promote_ext: Num_data_page_promote_time_ext: Num_data_page_unfix_ext: Time_data_page_lock_acquire_time: Time_data_page_hold_acquire_time: Time_data_page_fix_acquire_time: ``` > **Note:** > Each status information consists of 64-bit INTEGER data and the corresponding statistics information can be lost if the accumulated value exceeds the limit (highly unlikely though). > **Note:** > Some sets of performance statistics are activated/deactivated by **extended_statistics_activation** system parameter. Each set is represented by a value power of two. To be activated, it needs to be present in the base-2 representation of the system parameter. This is the lists of sets that can be manipulated: > > | Value | Name | Active default | Description | > |---|---|---|---| > | **1** | **Detailed b-tree pages** | Yes | Classifies b-tree pages into 3 categories: root, non-leaf and leaf Affected statistics: - Num_data_page_fix_ext - Time_data_page_lock_acquire_time - Time_data_page_hold_acquire_time - Time_data_page_fix_acquire_time - Num_data_page_promote_ext - Num_data_page_promote_time_ext - Num_data_page_unfix_ext | > | **2** | **MVCC Snapshot** | Yes | Activates statistics collection for MVCC snapshot: - Num_mvcc_snapshot_ext | > | **4** | **Time locks** | Yes | Activate statistics collection for timing lock waits: - Num_object_locks_time_waited_usec | > | **8** | **Hash anchor waits** | Yes | Activate statistics collection for hash anchor waits: - Num_data_page_hash_anchor_waits - Time_data_page_hash_anchor_wait | > | **16** | **Extended victimization** | No | Activate statistics collection for extended page buffer I/O and victimization module: - Num_data_page_writes - flush_collect_per_page - flush_flush_per_page - Num_data_page_skipped_flush_already_flushed - Num_data_page_skipped_flush_need_wal - Num_data_page_skipped_flush_fixed_or_hot - Num_data_page_dirty_to_post_flush - Num_alloc_bcb_prioritize_vacuum - Num_victim_assign_direct_vacuum_void - Num_victim_assign_direct_vacuum_lru - Num_victim_assign_direct_flush - Num_victim_assign_direct_panic - Num_victim_assign_direct_adjust_lru - Num_victim_assign_direct_adjust_lru_to_vacuum - Num_victim_assign_direct_search_for_flush - Num_victim_shared_lru_success - Num_victim_own_private_lru_success - Num_victim_other_private_lru_success - Num_victim_shared_lru_fail - Num_victim_own_private_lru_fail - Num_victim_other_private_lru_fail - Num_victim_get_from_lru - Num_victim_get_from_lru_was_empty - Num_victim_get_from_lru_fail - Num_victim_get_from_lru_bad_hint - Num_lfcq_prv_get_total_calls - Num_lfcq_prv_get_empty - Num_lfcq_prv_get_big - Num_lfcq_shr_get_total_calls - Num_lfcq_shr_get_empty | > | **32** | **Thread workers** | No | Activate statistics collection for thread worker pools - Thread_stats_counters_timers - Thread_loaddb_stats_counters_timers | > | **64** | **Thread daemons** | No | Activate statistics collection for daemon threads - Thread_pgbuf_daemon_stats_counters_timers | > | **128** | **Extended DWB** | No | Activate extended statistics collection for Double Write Buffer - Num_dwb_flushed_block_volumes | > | **MAX** | **All statistics** | No | Activate collection of all statistics | --- # Locks and transactions: lockdb, tranlist, killtran Source: https://www.coradb.ai/manual/admin/admin_transactions.html ## lockdb The **coradb lockdb** utility is used to check the information on the lock being used by the current transaction in the database. ``` bash coradb lockdb [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **lockdb**: A command used to check the information on the lock being used by the current transaction in the database. - *database_name*: The name of the database where lock information of the current transaction is to be checked. The following example shows how to display lock information of the *testdb* database on a screen without any option. ``` bash coradb lockdb testdb ``` The following shows \[options\] available with the **coradb lockdb** utility. **-o, --output-file=FILE** The **-o** option displays the lock information of the *testdb* database as a output.txt. ``` bash coradb lockdb -o output.txt testdb ``` ### Output contents The output contents of **coradb lockdb** are divided into three logical sections. - Server lock settings - Clients that are accessing the database - The contents of an object lock table **Server lock settings** The first section of the output of **coradb lockdb** is the database lock settings. ``` text *** Lock Table Dump *** Lock Escalation at = 100000, Run Deadlock interval = 0 ``` The lock escalation level is 100,000 records, and the interval to detect deadlock is set to 0 seconds. For a description of the related system parameters, **lock_escalation** and **deadlock_detection_interval**, see [Concurrency/lock-related parameters](https://www.coradb.ai/manual/admin/config_logging.html#concurrencylock-related-parameters). **Clients that are accessing the database** The second section of the output of **coradb lockdb** includes information on all clients that are connected to the database. This includes the transaction index, program name, user ID, host name, process ID, isolation level and lock timeout settings of each client. ``` text Transaction (index 1, corasql, dba@coradbdb|12854) Isolation COMMITTED READ Timeout_period : Infinite wait ``` Here, the transaction index is 1, the program name is corasql, the user ID is dba, the host name is coradbdb, the client process identifier is 12854, the isolation level is COMMITTED READ and the lock timeout is unlimited. A client for which transaction index is 0 is the internal system transaction. It can obtain the lock at a specific time, such as the processing of a checkpoint by a database. In most cases, however, this transaction will not obtain any locks. Because **coradb lockdb** utility accesses the database to obtain the lock information, the **coradb lockdb** is an independent client and will be output as such. **Object lock table** The third section of the output of the **coradb lockdb** includes the contents of the object lock table. It shows which client has the lock for which object in which mode, and which client is waiting for which object in which mode. The first part of the result of the object lock table shows how many objects are locked. ``` text Object lock Table: Current number of objects which are locked = 2001 ``` **coradb lockdb** outputs the OID, object type and table name of each object that obtained lock. In addition, it outputs the number of transactions that hold lock for the object (*Num holders*), the number of transactions (*Num blocked-holders*) that hold lock but are blocked since it could not convert the lock to the upper lock (e.g., conversion from **SCH_S_LOCK** to **SCH_M_LOCK**), and the number of different transactions that are waiting for the lock of the object (*Num waiters*). It also outputs the list of client transactions that hold lock, blocked client transactions and waiting client transactions. For rows, but not class, MVCC information is also shown. The example below shows an object in which the object type is a class, that will be blocked because the class OID( 0\| 62\| 5 ) that has **IX_LOCK** for transaction 1 and **SCH_S_LOCK** for transaction 2 cannot be converted into **SCH_M_LOCK**. It also shows that transaction 3 is blocked because transaction 2 is waiting for **SCH_M_LOCK** even when transaction 3 is only waiting for **SCH_S_LOCK**. ``` text OID = 0| 62| 5 Object type: Class = athlete. Num holders = 1, Num blocked-holders= 1, Num waiters = 1 LOCK HOLDERS Tran_index = 1, Granted_mode = IX_LOCK, Count = 1, Nsubgranules = 1 BLOCKED LOCK HOLDERS Tran_index = 2, Granted_mode = SCH_S_LOCK, Count = 1, Nsubgranules = 0 Blocked_mode = SCH_M_LOCK Start_waiting_at = Wed Feb 3 14:44:31 2016 Wait_for_secs = -1 LOCK WAITERS Tran_index = 3, Blocked_mode = SCH_S_LOCK Start_waiting_at = Wed Feb 3 14:45:14 2016 Wait_for_secs = -1 ``` The next example shows an instance of class, object OID( 2\| 50\| 1 ), that was inserted by transaction 1 which holds **X_LOCK** on the object. The class has a unique index and the key of inserted instance is about to be modified by transaction 2, which is blocked until transaction 1 is completed. ``` text OID = 2| 50| 1 Object type: instance of class ( 0| 62| 5) = athlete. MVCC info: insert ID = 6, delete ID = missing. Num holders = 1, Num blocked-holders= 1, Num waiters = 1 LOCK HOLDERS Tran_index = 1, Granted_mode = X_LOCK, Count = 1 LOCK WAITERS Tran_index = 2, Blocked_mode = X_LOCK Start_waiting_at = Wed Feb 3 14:45:14 2016 Wait_for_secs = -1 ``` *Granted_mode* refers to the mode of the obtained lock, and *Blocked_mode* refers to the mode of the blocked lock. *Starting_waiting_at refers* to the time at which the lock was requested, and *Wait_for_secs* refers to the waiting time of the lock. The value of *Wait_for_secs* is determined by **lock_timeout**, a system parameter. When the object type is a class (table), *Nsubgranules* is displayed, which is the sum of the record locks and the key locks obtained by a specific transaction in the table. ``` text OID = 0| 62| 5 Object type: Class = athlete. Num holders = 2, Num blocked-holders= 0, Num waiters= 0 LOCK HOLDERS: Tran_index = 3, Granted_mode = IX_LOCK, Count = 2, Nsubgranules = 0 Tran_index = 1, Granted_mode = IX_LOCK, Count = 3, Nsubgranules = 1 Tran_index = 2, Granted_mode = IX_LOCK, Count = 2, Nsubgranules = 1 ``` ## tranlist The **coradb tranlist** is used to check the transaction information of the target database. ``` bash coradb tranlist [options] database_name ``` If you omit the \[options\], it displays the total information about each transaction. "coradb tranlist testdb" outputs the similar result with "coradb killtran -q testdb", but tranlist outputs more items; "User name" and "Host name". "coradb tranlist -s testdb" outputs the same result with "coradb killtran -d testdb". The following shows what information is displayed when you run "coradb tranlist testdb". ``` bash $ coradb tranlist testdb Tran index User name Host name Process id Program name Query time Tran time Wait for lock holder SQL_ID SQL Text -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1(ACTIVE) public test-server 1681 broker1_cora_cas_1 0.00 0.00 -1 *** empty *** 2(ACTIVE) public test-server 1682 broker1_cora_cas_2 0.00 0.00 -1 *** empty *** 3(ACTIVE) public test-server 1683 broker1_cora_cas_3 0.00 0.00 -1 *** empty *** 4(ACTIVE) public test-server 1684 broker1_cora_cas_4 1.80 1.80 3, 2, 1 e5899a1b76253 update ta set a = 5 where a > 0 5(ACTIVE) public test-server 1685 broker1_cora_cas_5 0.00 0.00 -1 *** empty *** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- SQL_ID: e5899a1b76253 Tran index : 4 update ta set a = 5 where a > 0 ``` In the above example, when each three transaction is running INSERT statement, UPDATE statement is tried to run in the other transaction. In the above, UPDATE statement with "Tran index" 4 waits for the transactions 3,2,1, which are found in "Wait for lock holder", to be ended. "SQL Text" is SQLs which are stored into the query plan cache; this is printed out as **empty** when this query's execution is terminated. Each column's meaning is as following. > - Tran index : the index of transaction > - User name: database user's name > - Host name: host name of CAS which running this transaction > - Process id : client's process id > - Program name : program name of a client > - Query time : total execution time for the running query (unit: second) > - Tran time : total run time for the current transaction (unit: second) > - Wait for lock holder : the list of transactions which own the lock when the current transaction is waiting for a lock > - SQL_ID: an ID for SQL Text > - SQL Text : running SQL text (maximum 30 characters) Transaction status messages, which are shown on "Tran index", are as follows. > - ACTIVE : active state > - RECOVERY : recovering transaction > - COMMITTED : transaction which is already committed and will be ended soon. > - COMMITTING : transaction which is committing > - ABORTED : transaction which is rolled back and will be ended soon. > - KILLED : transaction which is forcefully killed by the server. The following shows \[options\] available with the **coradb tranlist** utility. **-s, --summary** This option outputs only summarized information(it omits query execution information or locking information). ``` bash $ coradb tranlist -s testdb Tran index User name Host name Process id Program name ------------------------------------------------------------------------------- 1(ACTIVE) public test-server 1681 broker1_cora_cas_1 2(ACTIVE) public test-server 1682 broker1_cora_cas_2 3(ACTIVE) public test-server 1683 broker1_cora_cas_3 4(ACTIVE) public test-server 1684 broker1_cora_cas_4 5(ACTIVE) public test-server 1685 broker1_cora_cas_5 ------------------------------------------------------------------------------- ``` **--sort-key=NUMBER** This option outputs the ascending values sorted by the NUMBERth column. If the type of the column is the number, it is sorted by the number; if not, it is sorted by the string. If this option is omitted, the output is sorted by "Tran index". The following is an example which outputs the sorted information by specifying the "Process id", the 4th column. ``` bash $ coradb tranlist --sort-key=4 testdb Tran index User name Host name Process id Program name Query time Tran time Wait for lock holder SQL_ID SQL Text -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1(ACTIVE) public test-server 1681 broker1_cora_cas_1 0.00 0.00 -1 *** empty *** 2(ACTIVE) public test-server 1682 broker1_cora_cas_2 0.00 0.00 -1 *** empty *** 3(ACTIVE) public test-server 1683 broker1_cora_cas_3 0.00 0.00 -1 *** empty *** 4(ACTIVE) public test-server 1684 broker1_cora_cas_4 1.80 1.80 3, 1, 2 e5899a1b76253 update ta set a = 5 where a > 0 5(ACTIVE) public test-server 1685 broker1_cora_cas_5 0.00 0.00 -1 *** empty *** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- SQL_ID: e5899a1b76253 Tran index : 4 update ta set a = 5 where a > 0 ``` **--reverse** This option outputs the reversely sorted values. The following is an example which outputs the reversely sorted values by the "Tran index". ``` text Tran index User name Host name Process id Program name Query time Tran time Wait for lock holder SQL_ID SQL Text ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 5(ACTIVE) public test-server 1685 broker1_cora_cas_5 0.00 0.00 -1 *** empty *** 4(ACTIVE) public test-server 1684 broker1_cora_cas_4 1.80 1.80 3, 2, 1 e5899a1b76253 update ta set a = 5 where a > 0 3(ACTIVE) public test-server 1683 broker1_cora_cas_3 0.00 0.00 -1 *** empty *** 2(ACTIVE) public test-server 1682 broker1_cora_cas_2 0.00 0.00 -1 *** empty *** 1(ACTIVE) public test-server 1681 broker1_cora_cas_1 0.00 0.00 -1 *** empty *** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ SQL_ID: e5899a1b76253 Tran index : 4 update ta set a = 5 where a > 0 ``` ## killtran The **coradb killtran** is used to check transactions or abort specific transaction. Only a **DBA** can use options for killing a transaction. ``` bash coradb killtran [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management - **killtran**: A utility that manages transactions for a specified database - *database_name*: The name of database whose transactions are to be killed Some \[options\] refer to killing specified transactions; others refer to print active transactions. If no option is specified, **-d** is specified by default so all transactions are displayed on the screen. ``` bash coradb killtran testdb Tran index User name Host name Process id Program name ------------------------------------------------------------------------------- 1(ACTIVE) dba myhost 664 cora_cas 2(ACTIVE) dba myhost 6700 corasql 3(ACTIVE) dba myhost 2188 cora_cas 4(ACTIVE) dba myhost 696 corasql 5(ACTIVE) public myhost 6944 corasql ------------------------------------------------------------------------------- ``` The following shows \[options\] available with the **coradb killtran** utility. **-i, --kill-transaction-index=ID1,ID2,ID3** This option kills transactions in a specified index. Several transaction indexes can be specified by separating with comma(,). If there is an invalid transaction ID among several IDs, it is ignored. ``` bash $ coradb killtran -i 1 testdb Ready to kill the following transactions: Tran index User name Host name Process id Program name ------------------------------------------------------------------------------- 1(ACTIVE) DBA myhost 15771 corasql 2(ACTIVE) DBA myhost 2171 corasql ------------------------------------------------------------------------------- Do you wish to proceed ? (Y/N)y Killing transaction associated with transaction index 1 Killing transaction associated with transaction index 2 ``` **--kill-user-name=ID** This option kills transactions for a specified OS user ID. ``` bash coradb killtran --kill-user-name=os_user_id testdb ``` **--kill-host-name=HOST** This option kills transactions of a specified client host. ``` bash coradb killtran --kill-host-name=myhost testdb ``` **--kill-program-name=NAME** This option kills transactions for a specified program. ``` bash coradb killtran --kill-program-name=cora_cas testdb ``` **--kill-sql-id=SQL_ID** This option kills transactions for a specified SQL ID. ``` bash coradb killtran --kill-sql-id=5377225ebc75a testdb ``` **-p, --dba-password=PASSWORD** The password of the **DBA** user. It can only be used together with **-i** or a **--kill-…** option; without it, killtran prompts for the password. **-q, --query-exec-info** The difference with the output of "coradb tranlist" command is that there are no "User name" column and "Host name" column. See [tranlist](https://www.coradb.ai/manual/admin/admin_transactions.html#tranlist). **-d, --display-information** This is the default option and it displays the summary of transactions. Its output is the same as the output of "coradb tranlist" with **-s** option. See `tranlist -s` **-f, --force** This option omits a prompt to check transactions to be stopped. ``` bash coradb killtran -f -i 1 testdb ``` --- # Unload and load: unloaddb, loaddb Source: https://www.coradb.ai/manual/admin/admin_unload.html ## unloaddb The purposes of loading/unloading databases are as follows: - To rebuild databases by volume reconfiguration - To migrate database in different system environments - To migrate database in different versions ``` bash coradb unloaddb [options] database_name ``` **coradb unloaddb** utility creates the following files: - Schema file(*database-name***\_schema**): A file that contains information on the schema defined in the database. - Object file(*database-name***\_objects**): A file that contains information on the records in the database. - Index file(*database-name***\_indexes**): A file that contains information on the indexes defined in the database. - Trigger file(*database-name***\_trigger**): A file that contains information on the triggers defined in the database. If you don't want triggers to be running while loading the data, load the trigger definitions after the data loading has completed. The schema, object, index, and trigger files are created in the same directory. The following is \[options\] used in **coradb unloaddb**. **-u, --user=ID** Specify a user account of a database to be unloaded. If this is not specified, the default is **DBA**. ``` bash coradb unloaddb -u dba -i table_list.txt testdb ``` **-p, --password=PASS** Specify a user's password of a database to be unloaded. If this is not specified, it is regarded as the empty string is entered. ``` bash coradb unloaddb -u dba -p dba_pwd -i table_list.txt testdb ``` **-i, --input-class-file FILE** Unload all schema and index of all tables; however, only the data of specified tables in this file are unloaded. ``` bash coradb unloaddb -i table_list.txt testdb ``` The following example shows an input file (table_list.txt). ``` text table_1 table_2 .. table_n ``` If this option is used together with the **--input-class-only** option, it creates schema, index, and data files of tables only specified in the input file of **-i** option. ``` bash coradb unloaddb --input-class-only -i table_list.txt testdb ``` If this option is used together with the **--include-reference** option, it unloads the referenced tables as well. ``` bash coradb unloaddb --include-reference -i table_list.txt testdb ``` **--include-reference** This option is used together with the **-i** option, and also unloads the referenced tables. **--input-class-only** This option is used together with the **-i** option, and creates only a schema file of tables specified in the input file of **-i** option. **--estimated-size=NUMBER** This option allows you to assign hash memory to store records of the database to be unloaded. If the **--estimated-size** option is not specified, the number of records of the database is determined based on recent statistics information. This option can be used if the recent statistics information has not been updated or if a large amount of hash memory needs to be assigned. Therefore, if the number given as the argument for the option is too small, the unload performance deteriorates due to hash conflicts. ``` bash coradb unloaddb --estimated-size=1000 testdb ``` **--cached-pages=NUMBER** The **--cached-pages** option specifies the number of pages of tables to be cached in the memory. Each page is 4,096 bytes. The administrator can configure the number of pages taking into account the memory size and speed. If this option is not specified, the default value is 100 pages. ``` bash coradb unloaddb --cached-pages 500 testdb ``` **-O, --output-path=PATH** This option specifies the directory in which to create schema and object files. If this is not specified, files are created in the current directory. ``` bash coradb unloaddb -O ./CoraDB/Databases/testdb testdb ``` If the specified directory does not exist, the following error message will be displayed. ``` text unloaddb: No such file or directory. ``` **-s, --schema-only** This option specifies that only the schema file will be created from amongst all the output files which can be created by the unload operation. ``` bash coradb unloaddb -s testdb ``` **-d, --data-only** This option specifies that only the data file will be created from amongst all of the output files which can be created by the unload operation. ``` bash coradb unloaddb -d testdb ``` **--output-prefix=PREFIX** This option specifies the prefix for the names of schema and object files created by the unload operation. Once the example is executed, the schema file name becomes *abcd_schema* and the object file name becomes *abcd_objects*. If the **--output-prefix** option is not specified, the name of the database to be unloaded is used as the prefix. ``` bash coradb unloaddb --output-prefix abcd testdb ``` **--hash-file=FILE** This option specifies the name of the hash file. **-v, --verbose** This option displays detailed information on the database tables and records being unloaded while the unload operation is under way. ``` bash coradb unloaddb -v testdb ``` **--use-delimiter** This option writes the double quote(") on the beginning and end of an identifier. The default is not to write the double quote("). **-S, --SA-mode** The **-S** option performs the unload operation by accessing the database in standalone mode. ``` bash coradb unloaddb -S testdb ``` **-C, --CS-mode** The **-C** option performs the unload operation by accessing the database in client/server mode. ``` bash coradb unloaddb -C testdb ``` **--datafile-per-class** This option specifies that the output file generated through unload operation creates a data file per each table. The file name is generated as *\\_\*\_ **objects** for each table. However, all column values in object types are unloaded as NULL and %id class_name class_id part is not written in the unloaded file (see [How to write files to load database](https://www.coradb.ai/manual/admin/admin_unload.html#how-to-write-files-to-load-database)). ``` bash coradb unloaddb --datafile-per-class testdb ``` ## loaddb You can load a database by using the **coradb loaddb** utility in the following situations: - Migrating previous version of CoraDB database to new version of CoraDB database - Migrating a third-party DBMS database to a CoraDB database - Inserting massive amount of data faster than using the **INSERT** statement In general, the **coradb loaddb** utility uses files (schema definition, object input, and index definition files) created by the **coradb unloaddb** utility. ``` bash coradb loaddb [options] database_name ``` **Input files** - Schema file(*database-name***\_schema**): A file generated by the unload operation; it contains schema information defined in the database. - Object file(*database-name***\_objects**): A file created by an unload operation. It contains information on the records in the database. - Index file(*database-name***\_indexes**): A file created by an unload operation. It contains information on the indexes defined in the database. - Trigger file(*database-name***\_trigger**): A file created by an unload operation. It contains information on the triggers defined in the database. - User-defined object file(*user_defined_object_file*): A file in table format written by the user to enter mass data. (For details, see [How to write files to load database](https://www.coradb.ai/manual/admin/admin_unload.html#how-to-write-files-to-load-database) .) **Execution order of input files** The **coradb loaddb** utility follows a specific order of parsing and executing input files, ensuring both correctness and optimized performance. The order is as follows: 1. Load schema file (including primary keys) 2. Load object file 3. Load index file (secondary keys and foreign keys) 4. Load trigger file **Loading modes** The **coradb loaddb** utility provides two modes of loading the data into a database. - **Stand-alone** mode loads the data offline, within a single thread environment. - **Client-server** mode connects to a server and loads the data online and in parallel. **Client-server** mode can be much faster, but object references and class/shared attributes are not supported in this mode and they can only be loaded in **stand-alone** mode The following table shows \[options\] available with the **coradb loaddb** utility. **-u, --user=ID** This option specifies the user account of a database where records are loaded. If the option is not specified, the default value is **PUBLIC**. ``` bash coradb loaddb -u admin -d testdb_objects newdb ``` **-p, --password=PASS** This option specifies the password of a database user who will load records. If the option is not specified, you will be prompted to enter the password. ``` bash coradb loaddb -u dba -p pass -d testdb_objects newdb ``` **-S, --SA-mode** This option loads data into a database in **stand-alone** mode. This is the default loading mode of **loaddb** and it is fully compatible with CoraDB 10.1 and older database versions. ``` bash coradb loaddb -S -u dba -d testdb_objects newdb ``` **-C, --CS-mode** This option connects to a running server process. Unlike the **stand-alone** mode, the **client-server** mode loads the data using multiple threads, leading to greater performance for large amounts of data. Multiple **loaddb** sessions may run at the same time. Object references and class/shared attributes are not supported in this mode. ``` bash coradb loaddb -C -u dba -d testdb_objects newdb ``` **--data-file-check-only** This option checks only the syntax of the data contained in testdb_objects, and does not load the data to the database. ``` bash coradb loaddb --data-file-check-only -d testdb_objects newdb ``` **-l, --load-only** **Stand-alone** mode does, by default, one prior syntax check on the whole data file before actually loading the data into the database. If a syntax error occurs, no data is loaded and the error is reported. Using the **-l** option, the prior syntax check is skipped, thus increasing the loading speed. Syntax is still checked before loading each row into the database. Loading is stopped if a syntax error occurs, but data may be partially loaded. **Client-server mode** doesn't do the prior syntax check, so this option has no effect. ``` bash coradb loaddb -l -d testdb_objects newdb ``` **--estimated-size=NUMBER** This option can be used to improve loading performance when the number of records to be unloaded exceeds the default value of 5,000. You can improve the load performance by assigning large hash memory for record storage with this option. ``` bash coradb loaddb --estimated-size 8000 -d testdb_objects newdb ``` **-v, --verbose** This option shows how to display detailed information on the tables and records of the database being loaded while the database loading operation is performed. You can check the detailed information such as the progress, the class being loaded and the number of records to be entered. ``` bash coradb loaddb -v -d testdb_objects newdb ``` **-c, --periodic-commit=COUNT** This option commits periodically every time COUNT records are entered into the database. If this option is not specified, all records included in testdb_objects are loaded to the database before the transaction is committed. If this option is used together with the **-s** or **-i** option, commit is performed periodically every time 100 DDL statements are loaded. The recommended commit interval varies depending on the data to be loaded. It is recommended that the parameter of the **-c** option be configured to 50 for schema loading and 1 for index loading. For record loading, the recommended and default value is 10240. To commit only once, after all the data is loaded, set **--periodic-commit** to a very high value. ``` bash coradb loaddb -c 100 -d testdb_objects newdb ``` **--no-oid** The following is a command that loads records into newdb ignoring the OIDs in testdb_objects. ``` bash coradb loaddb --no-oid -d testdb_objects newdb ``` **--no-statistics** The following is a command that does not update the statistics information of newdb after loading testdb_objects. It is useful especially when small data is loaded to a relatively big database; you can improve the load performance by using this command. ``` bash coradb loaddb --no-statistics -d testdb_objects newdb ``` **-s, --schema-file=FILE\[:LINE\]** This option loads the schema information or the trigger information defined in the schema file or the trigger file, from the LINE-th. You can load the actual records after loading the schema information first by using the **-s** option. On the following example, testdb_schema is a file created by the unload operation and contains the schema information of the unloaded database. ``` bash coradb loaddb -u dba -s testdb_schema newdb Start schema loading. Total 86 statements executed. Schema loading from testdb_schema finished. Statistics for Catalog classes have been updated. ``` The following loads the triggers defined in *testdb* into the newly created newdb database. testdb_trigger is a file created by the unload operation and contains the trigger information of the unloaded database. It is recommended to load the schema information after loading the records. ``` bash coradb loaddb -u dba -s testdb_trigger newdb ``` **-i, --index-file=FILE\[:LINE\]** The following loads the index information defined in the index file, from the LINE-th. On the following example, demo_indexes is a file created by the unload operation and contains the index information of the unloaded database. You can create indexes with the **-i** option, after loading records with the **-d** option. ``` bash coradb loaddb -c 100 -d testdb_objects newdb coradb loaddb -u dba -i testdb_indexes newdb ``` **-d, --data-file=FILE** This option loads the record information into newdb by specifying the data file or the user-defined object file. testdb_objects is either an object file created by the unload operation or a user-defined object file written by the user for mass data loading. ``` bash coradb loaddb -u dba -d testdb_objects newdb ``` **-t, --table=TABLE** This option specifies the table name if a table name header is omitted in the data file to be loaded. ``` bash coradb loaded -u dba -d testdb_objects -t tbl_name newdb ``` **--error-control-file=FILE** This option specifies the file that describes how to handle specific errors occurring during database loading. ``` bash coradb loaddb --error-control-file=error_test -d testdb_objects newdb ``` For the server error code name, see the **\$CORADB/include/dbi.h** file. For error messages by error code (error number), see the number under \$set 5 MSGCAT_SET_ERROR in the **\$CORADB/msg/***\***/coradb.msg** file. ``` text vi $CORADB/msg/en_US/coradb.msg $set 5 MSGCAT_SET_ERROR 1 Missing message for error code %1$d. 2 Internal system failure: no more specific information is available. 3 Out of virtual memory: unable to allocate %1$ld memory bytes. 4 Has been interrupted. ... 670 Operation would have caused one or more unique constraint violations. ... ``` The format of a file that details specific errors is as follows: - -\: Configures to ignore the error that corresponds to the \ (**loaddb** is continuously executed even when an error occurs while it is being executed). - +\: Configures not to ignore the error that corresponds to the \ (**loaddb** is stopped when an error occurs while it is being executed). - +DEFAULT: Configures not to ignore errors from 24 to 33. If the file that details errors is not specified by using the **--error-control-file** option, the **loaddb** utility is configured to ignore errors from 24 to 33 by default. As a warning error, it indicates that there is no enough space in the database volume. If there is no space in the assigned database volume, a generic volume is automatically created. The following example shows a file that details errors. - The warning errors from 24 to 33 indicating DB volume space is insufficient are not ignored by configuring +DEFAULT. - The error code 2 is not ignored because +2 has been specified later, even when -2 has been specified first. - -670 has been specified to ignore the error code 670, which is a unique violation error. - \#-115 has been processed as a comment since \# is added. ``` text vi error_file +DEFAULT -2 -670 #-115 --> comment +2 ``` **--ignore-class-file=FILE** You can specify a file that lists classes to be ignored during loading records. All records of classes except ones specified in the file will be loaded. ``` bash coradb loaddb --ignore-class-file=skip_class_list -d testdb_objects newdb ``` **--trigger-file=FILE** You can specify a file that contains triggers that need to be loaded into a database. ``` bash coradb loaddb --trigger-file=testdb_triggers -d testdb_objects newdb ``` > **Warning:** > The **--no-logging** option enables to load data file quickly when **loaddb** is executed by not storing transaction logs; however, it has risk, which data cannot be recovered in case of errors occurred such as incorrect file format or system failure. In this case, you must rebuild database to solve the problem. Thus, in general, it is not recommended to use this option exception of building a new database which does not require data recovery. If you use this option, **loaddb** does not check the errors like unique violation. To use this option, you should consider these issues. ### How to write files to load database You can add mass data to the database more rapidly by writing the object input file used in the **coradb loaddb** utility. An object input file is a text file in simple table form that consists of comments and command/data lines. #### Comment In CoraDB, a comment is represented by two hyphens (--). ``` sql -- This is a comment! ``` #### Command line A command line begins with a percent character (%) and consists of **%class** and **%id** commands; the former defines classes, and the latter defines aliases and identifiers used for class identification. - Assigning an Identifier to a Class You can assign an identifier to class reference relations by using the **%id** command. ``` text %id class_name class_id class_name: identifier class_id: integer ``` The *class_name* specified by the **%id** command is the class name defined in the database, and *class_id* is the numeric identifier which is assigned for object reference. ``` text %id employee 2 %id office 22 %id project 23 %id phone 24 ``` - Specifying the Class and Attribute You can specify the classes (tables) and attributes (columns) upon loading data by using the **%class** command. The data line should be written based on the order of attributes specified. When a class name is provided by using the **-t** option while executing the **coradb loaddb** utility, you don't have to specify the class and attribute in the data file. However, the order of writing data must comply with the order of the attribute defined when creating a class. ``` text %class class_name ( attr_name [attr_name... ] ) ``` The schema must be pre-defined in the database to be loaded. The *class_name* specified by the **%class** command is the class name defined in the database and the *attr_name* is the name of the attribute defined. The following example shows how to specify a class and three attributes by using the **%class** command to enter data into a class named *employee*. Three pieces of data should be entered on the data lines after the **%class** command. For this, see [Configuring reference relation](https://www.coradb.ai/manual/admin/admin_unload.html#conf-reference-relation). ``` text %class employee (name age department) ``` #### Data line A data line comes after the **%class** command line. Data loaded must have the same type as the class attributes specified by the **%class** command. The data loading operation stops if these two types are different. Data for each attribute must be separated by at least one space and be basically written as a single line. However, if the data to be loaded takes more than one line, you should specify the plus sign (+) at the end of the first data line to enter data continuously on the following line. Note that no space is allowed between the last character of the data and the plus sign. - Loading an Instance As shown below, you can load an instance that has the same type as the specified class attribute. Each piece of data is separated by at least one space. ``` text %class employee (name) 'jordan' 'james' 'garnett' 'malone' ``` - Assigning an Instance Number You can assign a number to a given instance at the beginning of the data line. An instance number is a unique positive number in the specified class. Spaces are not allowed between the number and the colon (:). Assigning an instance number is used to configure the reference relation for later. ``` text %class employee (name) 1: 'jordan' 2: 'james' 3: 'garnett' 4: 'malone' ``` - Configuring Reference Relation You can configure the object reference relation by specifying the reference class after an "at sign (**@**)" and the instance number after the "vertical line (\|)." ``` text @class_ref | instance_no class_ref: class_name class_id ``` Specify a class name or a class id after the **@** sign, and an instance number after a vertical line (). The following example shows how to load class instances into the *paycheck* class. The *name* attribute references an instance of the *employee* class. As in the last line, data is loaded as **NULL** if you configure the reference relation by using an instance number not specified earlier. ``` text %class paycheck(name department salary) @employee|1 'planning' 8000000 @employee|2 'planning' 6000000 @employee|3 'sales' 5000000 @employee|4 'development' 4000000 @employee|5 'development' 5000000 ``` Since the id 21 was assigned to the *employee* class by using the **%id** command in the [Assigning an identifier to a class](https://www.coradb.ai/manual/admin/admin_unload.html#assign-id-to-class) section, the above example can be written as follows: ``` text %class paycheck(name department salary) @21|1 'planning' 8000000 @21|2 'planning' 6000000 @21|3 'sales' 5000000 @21|4 'development' 4000000 @21|5 'development' 5000000 ``` ### Migrating database To use a new version of CoraDB database, you may need to migrate an existing data to a new one. For this purpose, you can use the "Export to an ASCII text file" and "Import from an ASCII text file" features provided by CoraDB. The following section explains migration steps using the **coradb unloaddb** and **coradb loaddb** utilities. **Recommended scenario and procedures** The following steps describes migration scenario that can be applied while the existing version of CoraDB is running. For database migration, you should use the **coradb unloaddb** and **coradb loaddb** utilities. For details, see [unloaddb](https://www.coradb.ai/manual/admin/admin_unload.html#unloaddb) and [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb). 1. Stop the existing CoraDB service > Execute **coradb service stop** to stop all service processes running on the existing CoraDB and then check whether all CoraDB-related processes have been successfully stopped. > > To verify whether all CoraDB-related processes have been successfully stopped, execute **ps -ef \| grep cora\_** in Linux. If there is no process starting with cora\_, all CoraDB-related processes have been successfully stopped. In Windows, press the \ key and select \[Start Task Manager\]. If there is no process starting with cora\_ in the \[Processes\] tab, all CoraDB-related processes have been successfully stopped. In Linux, when the related processes remain even after the CoraDB service has been terminated, use **kill** command to forcibly terminate them, and use **ipcs -m** command to check and release the shared memory used by the CoraDB broker. To forcibly terminate related processes in Windows, go to the \[Processes\] tab of Task Manager, right-click the image name, and then select \[End Process\]. 2. Back up the existing database > Perform backup of the existing version of the database by using the **coradb backupdb** utility. The purpose of this step is to safeguard against failures that might occur during the database unload/load operations. For details on the database backup, see [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb). 3. Unload the existing database > Unload the database created for the existing version of CoraDB by using the **coradb unloaddb** utility. For details on unloading a database, see [unloaddb](https://www.coradb.ai/manual/admin/admin_unload.html#unloaddb) . 4. Store the existing CoraDB configuration files > Store the configuration files such as **coradb.conf**, **coradb_broker.conf** and **cm.conf** in the **\$CORADB/conf** directory. The purpose of this step is to conveniently apply parameter values for the existing CoraDB database environment to the new one. 5. Install a new version of CoraDB > Once backing up and unloading of the data created by the existing version of CoraDB have been completed, delete the existing version of CoraDB and its databases and then install the new version of CoraDB. For details on installing CoraDB, see [Getting started](https://www.coradb.ai/manual/start.html). 6. Configure the new CoraDB environment > Configure the new version of CoraDB by referring to configuration files of the existing database stored in the step 3, " **Store the existing CoraDB configuration files** ." For details on configuring new environment, see [Installing and running CoraDB](https://www.coradb.ai/manual/install.html) in "Getting Started." 7. Load the new database > Create a database by using the **coradb createdb** utility and then load the data which had previously been unloaded into the new database by using the **coradb loaddb** utility. Please see [createdb](https://www.coradb.ai/manual/admin/admin_utils.html#createdb) for creating a database and [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb) for loading a database. 8. Back up the new database > Once the data has been successfully loaded into the new database, back up the database created for the new version of CoraDB by using the **coradb backupdb** utility. The reason for this step is because you cannot restore the data backed up in the existing version of CoraDB when using the new version. For details on backing up the database, see [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb) . > **Warning:** > Even if the version is identical, the 32-bit database volume and the 64-bit database volume are not compatible for backup and recovery. Therefore, it is not recommended to recover a 32-bit database backup on the 64-bit CoraDB or vice versa. > **Warning:** > When using the TDE feature in CoraDB 11, it does not provide backward compatibility. So, the unloaded file in CoraDB 11 cannot be loaded into a lower version if more the one TDE table exists. --- # coradb utilities Source: https://www.coradb.ai/manual/admin/admin_utils.html The **coradb** command runs the administration utilities of CoraDB. Each utility is called as `coradb utility_name [options] database_name`; `coradb utility_name` without arguments prints its options. ```text coradb utility_name [option] database_name ``` | Task | Utilities | |---|---| | Create, extend and remove databases | [createdb](https://www.coradb.ai/manual/admin/admin_utils.html#createdb), [addvoldb](https://www.coradb.ai/manual/admin/admin_utils.html#addvoldb), [deletedb](https://www.coradb.ai/manual/admin/admin_utils.html#deletedb) | | Rename, move, copy and register databases | [renamedb](https://www.coradb.ai/manual/admin/admin_utils.html#renamedb), [alterdbhost](https://www.coradb.ai/manual/admin/admin_utils.html#alterdbhost), [copydb](https://www.coradb.ai/manual/admin/admin_utils.html#copydb), [installdb](https://www.coradb.ai/manual/admin/admin_utils.html#installdb) | | Back up and restore | [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb), [restoredb](https://www.coradb.ai/manual/admin/admin_backup.html#restoredb) | | Export and import schema and data | [unloaddb](https://www.coradb.ai/manual/admin/admin_unload.html#unloaddb), [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb) | | Space, statistics and plans | [spacedb](https://www.coradb.ai/manual/admin/admin_space.html#spacedb), [compactdb](https://www.coradb.ai/manual/admin/admin_space.html#compactdb), [vacuumdb](https://www.coradb.ai/manual/admin/admin_space.html#vacuumdb), [optimizedb](https://www.coradb.ai/manual/admin/admin_space.html#optimizedb), [plandump](https://www.coradb.ai/manual/admin/admin_space.html#plandump) | | Server statistics | [statdump](https://www.coradb.ai/manual/admin/admin_statdump.html#statdump) | | Locks and transactions | [lockdb](https://www.coradb.ai/manual/admin/admin_transactions.html#lockdb), [tranlist](https://www.coradb.ai/manual/admin/admin_transactions.html#tranlist), [killtran](https://www.coradb.ai/manual/admin/admin_transactions.html#killtran) | | Consistency checks and diagnostics | [checkdb](https://www.coradb.ai/manual/admin/admin_diag.html#checkdb), [diagdb](https://www.coradb.ai/manual/admin/admin_diag.html#diagdb), [paramdump](https://www.coradb.ai/manual/admin/admin_diag.html#paramdump) | | Encryption keys | [tde](https://www.coradb.ai/manual/admin/admin_utils.html#tde) | | Locales and time zones | [genlocale, dumplocale, synccolldb](https://www.coradb.ai/manual/admin/admin_utils.html#locale-commands), [gen_tz, dump_tz](https://www.coradb.ai/manual/admin/admin_utils.html#timezone-commands) | The processes themselves — the service, database servers, brokers and the Java SP server — are controlled with `coradb service`, `coradb server`, `coradb broker` and `coradb javasp`; see [Controlling CoraDB processes](https://www.coradb.ai/manual/admin/control.html). Most utilities can run in client-server mode (**-C**), against a running database server, or in standalone mode (**-S**), opening the database files directly; standalone mode needs the database server to be stopped. Which modes a utility supports is given in its section. ## coradb utility logging CoraDB supports logging feature for the execution result of **coradb** utilities; for details, see [coradb utility logging](https://www.coradb.ai/manual/admin/control.html#coradb-utility-logging). ## createdb The **coradb createdb** utility creates databases and initializes them with the built-in CoraDB system tables. It can also define initial users to be authorized in the database and specify the locations of the logs and databases. In general, the **coradb createdb** utility is used only by DBA. > **Warning:** > When you create database, a locale name and a charset name after a DB name must be specified(e.g. ko_KR.utf8). It affects the length of string type, string comparison operation, etc. The specified charset when creating database cannot be changed later, so you should be careful when specifying it. > > For charset, locale and collation setting, see [An overview of globalization](https://www.coradb.ai/manual/sql/i18n.html). ``` bash coradb createdb [options] database_name locale_name.charset ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **createdb**: A command used to create a new database. - *database_name*: Specifies a unique name for the database to be created, without including the path name to the directory where the database will be created. If the specified database name is the same as that of an existing database name, CoraDB halts creation of the database to protect existing files. - *locale_name*: A locale name to use in the database should be input. For a locale name which can be used in CoraDB, refer to [Step 1: selecting a locale](https://www.coradb.ai/manual/sql/i18n_locale.html#step-1-selecting-a-locale). - *charset*: A characterset to use in the database should be input. A character set which can be used in CoraDB is iso88591, euckr or utf8. - If *locale_name* is en_US and *charset* is omitted, a character set will be iso88591. - If *locale_name* is ko_KR and *charset* is omitted, a character set will be utf8. - All locale names except en_US and ko_KR cannot omit *charset*, and a *charset* can be specified only with utf8. The maximum length of database name is 17 in English. The following shows \[options\] available with the **coradb** **createdb** utility. **--db-volume-size=SIZE** This option specifies the size of the database volume that will be created first. The default value is the value of the system parameter **db_volume_size**. You can set units as K, M, G and T, which stand for kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively; if you omit the unit, bytes will be applied. The size of the database is always rounded up to 64 disk sectors, which depends on the size of a page and can be 16M, 32M or 64M for page size 4k, 8k and 16k respectively. The following example shows how to create a database named *testdb* and assign 512 MB to its first volume. ``` bash coradb createdb --db-volume-size=512M testdb en_US ``` **--db-page-size=SIZE** This option specifies the size of the database page; the minimum value is 4K and the maximum value is **16K** (default). K stands for kilobytes (KB). The value of page size is one of the following: 4K, 8K, or 16K. If a value between 4K and 16K is specified, system rounds up the number. If a value greater than 16K or less than 4K, the specified number is used. The following example shows how to create a database named *testdb* and configure its page size 16K. ``` bash coradb createdb --db-page-size=16K testdb en_US ``` **--log-volume-size=SIZE** This option specifies the size of the database log volume. The default value is the same as database volume size, and the minimum value is 20M. You can set units as K, M, G and T, which stand for kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The following example shows how to create a database named *testdb* and assign 256 MB to its log volume. ``` bash coradb createdb --log-volume-size=256M testdb en_US ``` **--log-page-size=SIZE** This option specifies the size of the log volume page. The default value is the same as data page size. The minimum value is 4K and the maximum value is 16K. K stands for kilobytes (KB). The value of page size is one of the following: 4K, 8K, or 16K. If a value between 4K and 16K is specified, system rounds up the number. If a value greater than 16K or less than 4K, the specified number is used. The following example shows how to create a database named *testdb* and configure its log volume page size 8K. ``` bash coradb createdb --log-page-size=8K testdb en_US ``` **--comment=COMMENT** This option specifies a comment to be included in the database volume header. If the character string contains spaces, the comment must be enclosed in double quotes. The following example shows how to create a database named *testdb* and add a comment to the database volume. ``` bash coradb createdb --comment "a new database for study" testdb en_US ``` **-F, --file-path=PATH** The **-F** option specifies an absolute path to a directory where the new database will be created. If the **-F** option is not specified, the new database is created in the current working directory. The following example shows how to create a database named *testdb* in the directory /dbtemp/new_db. ``` bash coradb createdb -F "/dbtemp/new_db/" testdb en_US ``` **-L, --log-path=PATH** The **-L** option specifies an absolute path to the directory where database log files are created. If the **-L** option is not specified, log files are created in the directory specified by the **-F** option. If neither **-F** nor **-L** option is specified, database log files are created in the current working directory. The following example shows how to create a database named *testdb* in the directory /dbtemp/newdb and log files in the directory /dbtemp/db_log. ``` bash coradb createdb -F "/dbtemp/new_db/" -L "/dbtemp/db_log/" testdb en_US ``` **-B, --lob-base-path=PATH** This option specifies a directory where **LOB** data files are stored when **BLOB/CLOB** data is used. If the **--lob-base-path** option is not specified, LOB data files are store in \<*location of database volumes created*\>/**lob** directory. The following example shows how to create a database named *testdb* in the working directory and specify /home/data1 of local file system as a location of LOB data files. ``` bash coradb createdb --lob-base-path "file:/home1/data1" testdb en_US ``` **--server-name=HOST** This option enables the server of a specific database to run in the specified host when CoraDB client/server is used. The information of a host specified is stored in the **databases.txt** file. If this option is not specified, the current localhost is specified by default. The following example shows how to create a database named *testdb* and register it on the host *aa_host*. ``` bash coradb createdb --server-name aa_host testdb en_US ``` **-r, --replace** This option creates a new database and overwrites an existing database if one with the same name exists. The following example shows how to create a new database named *testdb* and overwrite the existing database with the same name. ``` bash coradb createdb -r testdb en_US ``` **--more-volume-file=FILE** This option creates an additional volume based on the specification contained in the file specified by the option. The volume is created in the same directory where the database is created. Instead of using this option, you can add a volume by using the **coradb addvoldb** utility. The following example shows how to create a database named *testdb* as well as an additional volume based on the specification stored in the **vol_info.txt** file. ``` bash coradb createdb --more-volume-file vol_info.txt testdb en_US ``` The following is a specification of the additional volume contained in the **vol_info.txt** file. The specification of each volume must be written on a single line. ``` text #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # NAME volname COMMENTS volcmnts PURPOSE volpurp NPAGES volnpgs NAME data_v1 COMMENTS "data information volume" PURPOSE data NPAGES 1000 NAME data_v2 COMMENTS "data information volume" NPAGES 1000 NAME temp_v1 COMMENTS "temporary information volume" PURPOSE temp NPAGES 500 #xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` As shown in the example, the specification of each volume consists following. ``` text [NAME volname] [COMMENTS volcmnts] [PURPOSE volpurp] NPAGES volnpgs ``` - *volname*: The name of the volume to be created. It must follow the UNIX file name conventions and be a simple name not including the directory path. The specification of a volume name can be omitted. If it is, the "database name to be created by the system_volume identifier" becomes the volume name. - *volcmnts*: Comment to be written in the volume header. It contains information on the additional volume to be created. The specification of the comment on a volume can also be omitted. - *volpurp*: The purpose for which the volume will be used. It can be either permanent data (default option) or temporary. > **Note:** > For backward compatibility, all old keywords, **data**, **index**, **temp**, or **generic** are accepted. **temp** stands for temporary data purpose, while the rest stand for permanent data purpose. - *volnpgs*: The number of pages of the additional volume to be created. The specification of the number of pages of the volume cannot be omitted; it must be specified. The actual volume size is rounded up to the next multiple of **64 sectors**. **--user-definition-file=FILE** This option adds users who have access to the database to be created. It adds a user based on the specification contained in the user information file specified by the parameter. Instead of using the **--user-definition-file** option, you can add a user by using the **CREATE USER** statement (for details, see [CREATE USER](https://www.coradb.ai/manual/sql/authorization.html#create-user)). The following example shows how to create a database named *testdb* and add users to *testdb* based on the user information defined in the **user_info.txt** file. ``` bash coradb createdb --user-definition-file=user_info.txt testdb en_US ``` The syntax of a user information file is as follows: ``` text USER user_name [ | ] : [ GROUPS [ { }... ] ] : [ MEMBERS [ { }... ] ] ``` - The *user_name* is the name of the user who has access to the database. It must not include spaces. - The **GROUPS** clause is optional. The *group_name* is the upper level group that contains the *user_name* . Here, the *group_name* can be multiply specified and must be defined as **USER** in advance. - The **MEMBERS** clause is optional. The *member_name* is the name of the lower level member that belongs to the *user_name* . Here, the *member_name* can be multiply specified and must be defined as **USER** in advance. Comments can be used in a user information file. A comment line must begin with a consecutive hyphen lines (--). Blank lines are ignored. The following example shows a user information in which *grandeur* and *sonata* are included in *sedan* group, *tuscan* is included in *suv* group, and *i30* is included in *hatchback* group. The name of the user information file is **user_info.txt**. ``` sql -- -- Example 1 of a user information file -- USER sedan USER suv USER hatchback USER grandeur GROUPS sedan USER sonata GROUPS sedan USER tuscan GROUPS suv USER i30 GROUPS hatchback ``` The following example shows a file that has the same user relationship information as the file above. The difference is that the **MEMBERS** statement is used in the file below. ``` sql -- -- Example 2 of a user information file -- USER grandeur USER sonata USER tuscan USER i30 USER sedan MEMBERS sonata grandeur USER suv MEMBERS tuscan USER hatchback MEMBERS i30 ``` **--corasql-initialization-file=FILE** This option executes an SQL statement on the database to be created by using the corasql interpreter. A schema can be created based on the SQL statement contained in the file specified by the parameter. The following example shows how to create a database named *testdb* and execute the SQL statement defined in table_schema.sql through the corasql interpreter. ``` bash coradb createdb --corasql-initialization-file table_schema.sql testdb en_US ``` **-o, --output-file=FILE** This option stores messages related to the database creation to the file given as a parameter. The file is created in the same directory where the database was created. If the **-o** option is not specified, messages are displayed on the console screen. The **-o** option allows you to use information on the creation of a certain database by storing messages, generated during the database creation, to a specified file. The following example shows how to create a database named *testdb* and store the output of the utility to the **db_output** file instead of displaying it on the console screen. ``` bash coradb createdb -o db_output testdb en_US ``` **-v, --verbose** This option displays all information on the database creation operation onto the screen. Like the **-o** option, this option is useful in checking information related to the creation of a specific database. Therefore, if you specify the **-v** option together with the **-o** option, you can store the output messages in the file given as a parameter; the messages contain the operation information about the **coradb createdb** utility and database creation process. The following example shows how to create a database named *testdb* and display detailed information on the operation onto the screen. ``` bash coradb createdb -v testdb en_US ``` > **Note:** > - **temp_file_max_size_in_pages** is a parameter used to configure the maximum size of temporary volumes - used for complicated queries or storing arrays - on the disk. With the default value **-1**, the temporary volumes size is only limited by the capacity of the disk specified by the **temp_volume_path** parameter. If the value is 0, no temporary volumes can be created. In this case, a permanent volume with temporary data purpose should be added by using the [coradb addvoldb](https://www.coradb.ai/manual/admin/admin_utils.html#addvoldb) utility. For an efficient storage management, it is recommended to use the latter approach. > - By using the [coradb spacedb](https://www.coradb.ai/manual/admin/admin_space.html#spacedb) utility, you can check the remaining space of each volume. By using the [coradb addvoldb](https://www.coradb.ai/manual/admin/admin_utils.html#addvoldb) utility, you can add more volumes as needed while managing the database. You are advised to add more volumes when there is less system load. When all preassigned volumes are completely in use, the database system automatically creates new volumes. The following example shows how to create a database, with additional volumes, including one for temporary data purpose. ``` bash coradb createdb --db-volume-size=512M --log-volume-size=256M coradbdb en_US coradb addvoldb -S -n coradbdb_DATA01 --db-volume-size=512M coradbdb coradb addvoldb -S -p temp -n coradbdb_TEMP01 --db-volume-size=512M coradbdb ``` > **Note:** > **Creating a database using an existing key file** > > When the database is created, a key file is created together by default. If you want to use an existing key file when creating a database: > > 1. Copy the key file with the name **\\_keys**. > 2. Specify the directory path of the copied key file by the system parameter **tde_keys_file_path**. > 3. Create a database by using the **createdb utility**. > > For more information on the TDE key file, see [File-based master key management](https://www.coradb.ai/manual/security.html#file-based-master-key-management). ## addvoldb If you want to micromanage CoraDB storage volumes, addvoldb is the tool for you. You can finely tune each file name, path, purpose, and size. The database system can handle all storage by itself, but it uses default values to configure each new volume. The command for manually adding a database volume is as follows. ``` bash coradb addvoldb [options] database_name ``` - **coradb**: An integrated utility for CoraDB service and database management. - **addvoldb**: A command that adds a specified number of pages of the new volume to a specified database. - *database_name*: Specifies the name of the database to which a volume is to be added without including the path name to the directory where the database is to be created. The following example shows how to create a database, with additional multi-purpose volumes. ``` bash coradb createdb --db-volume-size=512M --log-volume-size=256M coradbdb en_US coradb addvoldb -S -n coradbdb_DATA01 --db-volume-size=512M coradbdb coradb addvoldb -S -p temp -n coradbdb_TEMP01 --db-volume-size=512M coradbdb ``` The following shows \[options\] available with the **coradb addvoldb** utility. **--db-volume-size=SIZE** **--db-volume-size** is an option that specifies the size of the volume to be added to a specified database. If the **--db-volume-size** option is omitted, the value of the system parameter **db_volume_size** is used by default. You can set units as K, M, G and T, which stand for kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The size of the database is always rounded up to 64 disk sectors, which depends on the size of a page and can be 16M, 32M or 64M for page size 4k, 8k and 16k respectively. The following example shows how to add a volume for which 256 MB are assigned to the *testdb* database. ``` bash coradb addvoldb --db-volume-size=256M testdb ``` **-n, --volume-name=NAME** This option specifies the name of the volume to be added to a specified database. The volume name must follow the file name protocol of the operating system and be a simple one without including the directory path or spaces. If the **-n** option is omitted, the name of the volume to be added is configured by the system automatically as "database name_volume identifier". For example, if the database name is *testdb*, the volume name *testdb_x001* is automatically configured. The following example shows how to specify a different name, *testdb_v1*, to newly added volume. ``` bash coradb addvoldb -n testdb_v1 testdb ``` **-F, --file-path=PATH** This option specifies the directory path where the volume to be added will be stored. If the **-F** option is omitted, the value of the system parameter **volume_extension_path** is used by default. The following example shows how to add a volume in the */dbtemp/addvol* directory. Since the **-n** option is not specified for the volume name, the volume name *testdb_x001* will be created. ``` bash coradb addvoldb -F /dbtemp/addvol/ testdb ``` **--comment COMMENT** This option facilitates to retrieve information on the added volume by adding such information in the form of comments. It is recommended that the contents of a comment include the name of **DBA** who adds the volume, or the purpose of adding the volume. The comment must be enclosed in double quotes. The following example shows how to add a volume and inserts a comment with additional information. ``` bash coradb addvoldb --comment "Data volume added by cheolsoo kim because permanent data space was almost depleted." testdb ``` **-p, --purpose=PURPOSE** This option specifies the purpose of the volume to be added. The purpose defines the type of files that will be stored in added volume: - **PERMANENT DATA** to store table rows, indexes and system files. - **TEMPORARY DATA** to store intermediate and final results of query processing and sorting. If not specified, the purpose of the volume is by default considered **PERMANENT DATA**. The following example shows how to change it to temporary. ``` bash coradb addvoldb -p temp testdb ``` > **Note:** > PERMANENT DATA volumes used to be classified as generic, data and index. The design of volumes has been changed, and since then the classification no longer exists. In order to avoid invalidating your old scripts, we chose to keep the keywords as valid options, but their effect will be the same. The only remaining option value with a real effect is temp. > > For detailed information on each purpose, see [Database volume structure](https://www.coradb.ai/manual/intro.html#database-volume-structure). **-S, --SA-mode** This option accesses the database in standalone mode without running the server process. This option has no parameter. If the **-S** option is not specified, the system assumes to be in client/server mode. ``` bash coradb addvoldb -S --db-volume-size=256M testdb ``` **-C, --CS-mode** This option accesses the database in client/server mode by running the server and the client separately. There is no parameter. Even when the **-C** option is not specified, the system assumes to be in client/server mode by default. ``` bash coradb addvoldb -C --db-volume-size=256M testdb ``` **--max-writesize-in-sec=SIZE** The **--max-writesize-in-sec** is used to limit the impact of system operating when you add a volume to the database. This can limit the maximum writing size per second. The unit of this option is K(kilobytes) and M(megabytes). The minimum value is 160K. If you set this value as less than 160K, it is changed as 160K. It can be used only in client/server mode. The below is an example to limit the writing size of the 2GB volume as 1MB. Consuming time will be about 35 minutes(= (2048MB/1MB) /60 sec.). ``` bash coradb addvoldb -C --db-volume-size=2G --max-writesize-in-sec=1M testdb ``` ## deletedb The **coradb deletedb** utility is used to delete a database. You must use the **coradb deletedb** utility to delete a database, instead of using the file deletion commands of the operating system; a database consists of a few interdependent files. The **coradb deletedb** utility also deletes the information on the database from the database location file (**databases.txt**). The **coradb deletedb** utility must be run offline, that is, in standalone mode when nobody is using the database. ``` bash coradb deletedb [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **deletedb**: A command to delete a database, its related data, logs and all backup files. It can be executed successfully only when the database is in a stopped state. - *database_name*: Specifies the name of the database to be deleted without including the path name. The following shows \[options\] available with the **coradb deletedb** utility. **-o, --output-file=FILE** This option specifies the file name for writing messages: ``` bash coradb deletedb -o deleted_db.out testdb ``` The **coradb** **deletedb** utility also deletes the database information contained in the database location file (**databases.txt**). The following message is returned if you enter a utility that tries to delete a non-existing database. ``` bash coradb deletedb testdb Database "testdb" is unknown, or the file "databases.txt" cannot be accessed. ``` **-d, --delete-backup** This option deletes database volumes, backup volumes and backup information files simultaneously. If the -**d** option is not specified, backup volume and backup information files are not deleted. ``` bash coradb deletedb -d testdb ``` ## renamedb The **coradb renamedb** utility renames a database. The names of information volumes, log volumes and control files are also renamed to conform to the new database one. In contrast, the **coradb alterdbhost** utility configures or changes the host name of the specified database. In other words, it changes the host name configuration in the **databases.txt** file. ``` bash coradb renamedb [options] src_database_name dest_database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **renamedb**: A command that changes the existing name of a database to a new one. It executes successfully only when the database is in a stopped state. The names of related information volumes, log volumes and control files are also changed to new ones accordingly. - *src_database_name*: The name of the existing database to be renamed. The path name to the directory where the database is to be created must not be included. - *dest_database_name*: The new name of the database. It must not be the same as that of an existing database. The path name to the directory where the database is to be created must not be included. The following shows \[options\] available with the **coradb renamedb** utility. **-E, --extended-volume-path=PATH** This option renames an extended volume created in a specific directory path (e.g. /dbtemp/addvol/), and then moves the volume to a new directory. This specifies a new directory path (e.g. /dbtemp/newaddvols/) where the renamed extended volume will be moved. If it is not specified, the extended volume is only renamed in the existing path without being moved. If a directory path outside the disk partition of the existing database volume or an invalid one is specified, the rename operation is not executed. This option cannot be used together with the **-i** option. ``` bash coradb renamedb -E /dbtemp/newaddvols/ testdb testdb_1 ``` **-i, --control-file=FILE** The option specifies an input file in which directory information is stored to change all database name of volumes or files and assign different directory at once. To perform this work, the **-i** option is used. The **-i** option cannot be used together with the **-E** option. ``` bash coradb renamedb -i rename_path testdb testdb_1 ``` The following are the syntax and example of a file that contains the name of each volume, the current directory path and the directory path where renamed volumes will be stored. ``` text volid source_fullvolname dest_fullvolname ``` - *volid*: An integer that is used to identify each volume. It can be checked in the database volume control file (database_name_vinf). - *source_fullvolname*: The current directory path to each volume. - *dest_fullvolname*: The target directory path where renamed volumes will be moved. If the target directory path is invalid, the database rename operation is not executed. ``` text -5 /home1/user/testdb_vinf /home1/CoraDB/databases/testdb_1_vinf -4 /home1/user/testdb_lginf /home1/CoraDB/databases/testdb_1_lginf -3 /home1/user/testdb_bkvinf /home1/CoraDB/databases/testdb_1_bkvinf -2 /home1/user/testdb_lgat /home1/CoraDB/databases/testdb_1_lgat 0 /home1/user/testdb /home1/CoraDB/databases/testdb_1 1 /home1/user/backup/testdb_x001/home1/CoraDB/databases/backup/testdb_1_x001 ``` **-d, --delete-backup** This option renames the *testdb* database and at once forcefully delete all backup volumes and backup information files that are in the same location as *testdb*. Note that you cannot use the backup files with the old names once the database is renamed. If the **-d** option is not specified, backup volumes and backup information files are not deleted. ``` bash coradb renamedb -d testdb testdb_1 ``` ## alterdbhost The **coradb alterdbhost** utility sets or changes the host name of the specified database. It changes the host name set in the **databases.txt** file. ``` bash coradb alterdbhost [option] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management - **alterdbhost**: A command used to change the host name of the current database The following shows the option available with the **coradb alterdbhost** utility. **-h, --host=HOST** The *-h* option specifies the host name to be changed. When this option is omitted, specifies the host name to localhost. ## copydb The **coradb copydb** utility copy or move a database to another location. As arguments, source and target name of database must be given. A target database name must be different from a source database name. When the target name argument is specified, the location of target database name is registered in the **databases.txt** file. The **coradb copydb** utility can be executed only offline (that is, state of a source database stop). ``` bash coradb copydb [options] src-database-name dest-database-name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **copydb**: A command that copy or move a database from one to another location. - *src-database-name*: The names of source and target databases to be copied or moved. - *dest-database-name*: A new (target) database name. If options are omitted, a target database is copied into the same directory of a source database. The following shows \[options\] available with the **coradb copydb** utility. **--server-name=HOST** The *--server-name* option specifies a host name of new database. The host name is registered in the **databases.txt** file. If this option is omitted, a local host is registered. ``` bash coradb copydb --server-name=cora_server1 testdb new_testdb ``` **-F, --file-path=PATH** The *-F* option specifies a specific directory path where a new database volume is stored with an **-F** option. It represents specifying an absolute path. If the specified directory does not exist, an error is displayed. If this option is omitted, a new database volume is created in the current working directory. And this information is specified in **vol-path** of the **databases.txt** file. ``` bash coradb copydb -F /home/usr/CoraDB/databases testdb new_testdb ``` **-L, --log-path=PATH** The *-L* option specifies a specific directory path where a new database volume is stored with an **-L** option. It represents specifying an absolute path. If the specified directory does not exist, an error is displayed. If this option is omitted, a new database volume is created in the current working directory. And this information is specified in **log-path** of the **databases.txt** file. ``` bash coradb copydb -L /home/usr/CoraDB/databases/logs testdb new_testdb ``` **-E, --extended-volume-path=PATH** The *-E* option specifies a specific directory path where a new database extended volume is stored with an **-E**. If this option is omitted, a new database extended volume is created in the location of a new database volume or in the registered path of controlling file. The **-i** option cannot be used with this option. ``` bash coradb copydb -E home/usr/CoraDB/databases/extvols testdb new_testdb ``` **-i, --control-file=FILE** The **-i** option specifies an input file where a new directory path information and a source volume are stored to copy or move multiple volumes into a different directory, respectively. This option cannot be used with the **-E** option. An input file named copy_path is specified in the example below. ``` bash coradb copydb -i copy_path testdb new_testdb ``` The following is an example of input file that contains each volume name, current directory path, and new directory and volume names. ``` text # volid source_fullvolname dest_fullvolname 0 /usr/databases/testdb /drive1/usr/databases/new_testdb 1 /usr/databases/testdb_data1 /drive1/usr/databases/new_testdb_data1 2 /usr/databases/ext/testdb_ext1 /drive2//usr/databases/new_testdb_ext1 3 /usr/databases/ext/testdb_ext2 /drive2/usr/databases/new_testdb_ext2 ``` - *volid*: An integer that is used to identify each volume. It can be checked in the database volume control file (**database_name_vinf**). - *source_fullvolname*: The current directory path to each source database volume. - *dest_fullvolname*: The target directory path where new volumes will be stored. You should specify a valid path. **-r, --replace** If the **-r** option is specified, a new database name overwrites the existing database name if it is identical, instead of outputting an error. ``` bash coradb copydb -r -F /home/usr/CoraDB/databases testdb new_testdb ``` **-d, --delete-source** If the **-d** option is specified, a source database is deleted after the database is copied. This execution brings the same the result as executing **coradb deletedb** utility after copying a database. Note that if a source database contains LOB data, LOB file directory path of a source database is copied into a new database and it is registered in the **lob-base-path** of the **databases.txt** file. ``` bash coradb copydb -d -F /home/usr/CoraDB/databases testdb new_testdb ``` **--copy-lob-path=PATH** If the **--copy-lob-path** option is specified, a new directory path for LOB files is created and a source database is copied into a new directory path. If this option is omitted, the directory path is not created. Therefore, the **lob-base-path** of the **databases.txt** file should be modified separately. This option cannot be used with the **-B** option. ``` bash coradb copydb --copy-lob-path testdb new_testdb ``` **-B, --lob-base-path=PATH** If the **-B** option is specified, a specified directory is specified as for LOB files of a new database and a source database is copied. This option cannot be used with the **--copy-lob-path** option. ``` bash coradb copydb -B /home/usr/CoraDB/databases/new_lob testdb new_testdb ``` ## installdb The **coradb installdb** utility is used to register the information of a newly installed database to **databases.txt**, which stores database location information. The execution of this utility does not affect the operation of the database to be registered. ``` bash coradb installdb [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **installdb**: A command that registers the information of a moved or copied database to **databases.txt**. - *database_name*: The name of database to be registered to **databases.txt**. If no \[options\] are used, the command must be executed in the directory where the corresponding database exists. The following shows \[options\] available with the **coradb installdb** utility. **--server-name=HOST** This option registers the server host information of a database to **databases.txt** with a specific host name. If this is not specified, the current host information is registered. ``` bash coradb installdb --server-name=cora_server1 testdb ``` **-F, --file-path=PATH** This option registers the absolute directory path of a database volume to **databases.txt** by using the **-F** option. If this option is not specified, the path of a current directory is registered as default. ``` bash coradb installdb -F /home/coradb/CoraDB/databases/testdb testdb ``` **-L, --log-path=PATH** This option registers the absolute directory path of a database log volume to **databases.txt** by using the **-L** option. If this option is not specified, the directory path of a volume is registered. ``` bash coradb installdb -L /home/coradb/CoraDB/databases/logs/testdb testdb ``` ## tde The **coradb tde** utility is used to manage the TDE encryption of the database and can only be executed by the **DBA** user. With **coradb tde** utility, you can change the key set on the database, add a new key, or remove a key in the key file stably. Also, you can inquire about the keys added to the key file and the key set on the database. For more information, see [TDE (transparent data encryption)](https://www.coradb.ai/manual/security.html#tde-transparent-data-encryption). ``` bash coradb tde [option] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **tde**: A utility that manages TDE encryption applied to the database. - *operation*: There are four types of operation: key addition, key deletion, key change, and showing keys' information. One operation must be set, and they are exclusive. - *database_name*: The name of the database on which TDE administration operations to be performed. The following table shows \ available with the coradb tde utility. **-s, --show-keys** This option displays information about the keys set on the database and keys in the key file (\_keys). ``` bash $ coradb tde -s testdb Key File: /home/usr/CoraDB/databases/testdb/testdb_keys The current key set on testdb: Key Index: 2 Created on Fri Nov 27 11:14:54 2020 Set on Fri Nov 27 11:15:30 2020 Keys Information: Key Index: 0 created on Fri Nov 27 11:11:27 2020 Key Index: 1 created on Fri Nov 27 11:14:47 2020 Key Index: 2 created on Fri Nov 27 11:14:54 2020 Key Index: 3 created on Fri Nov 27 11:14:55 2020 The number of keys: 4 ``` **The current key** section shows the information on the key set on the current database, which displays the index for the key in the key file, the creation time, and the set time. The set key can be identified by the key index and creation time, and a key change plan can be established with the set time. **Keys Information** section shows the keys added and being managed in the key file, through which the key indexes and creation time of them is checked. **-n, --generate-new-key** This option is used to add a new key to the key file (up to 128). If it is successful, the index of the added key is displayed, and this index is used to identify the key when changing or removing the key later. Information of added keys can be checked by \\\\show-keys. ``` bash $ coradb tde -n testdb Key File: /home/usr/CoraDB/databases/testdb/testdb_keys SUCCESS: A new key has been generated - key index: 1 created on Tue Dec 1 11:30:47 2020 ``` **-d, --delete-key=KEY_INDEX** This option is used to remove a key specified by index from the key file. The key currently set on the database cannot be removed. ``` bash $ coradb tde -d 1 testdb Key File: /home/usr/CoraDB/databases/testdb/testdb_keys SUCCESS: The key (index: 1) has been deleted ``` **-c, --change-key=KEY_INDEX** This option is used to change the key set on the database to another key existing in the key file. When changing, both the previously set key and the new key to be set must exist. ``` bash $ coradb tde -c 2 testdb Key File: /home/usr/CoraDB/databases/testdb/testdb_keys Trying to change the key from the key (index: 0) to the key (index: 2).. SUCCESS: The key has been changed from the key (index: 0) to the key (index: 2) ``` To change the key set on the database, a user must first create a key to be set by the \\\\generate-new-key option. The user can create a new key to change, or create multiple keys in advance for changing the key according to their own security plans. The following table shows \[options\] available with the coradb tde utility. **-p, --dba-password=PASSWORD** This option specifies the password of the DBA. ## Locale commands **coradb genlocale** utility compiles the locale information to use. This utility is executed in the **make_locale.sh** script ( **.bat** for Windows). **coradb dumplocale** utility dumps the compiled binary locale (CoraDB locale library) file as a human-readable format on the console. It is better to save the output as a file by output redirection. **coradb synccolldb** utility checks if the collations between database and locale library are consistent or not, and synchronize them. For more detailed usage, see [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html#locale-setting). ## Timezone commands **coradb gen_tz** utility has two modes: - **new** mode when it compiles the IANA timezone data stored in the tzdata folder into a C source code file. This file is then converted into a .so shared library for Linux or .dll library for Windows using the **make_tz.sh** (Linux) / **make_tz.bat** (Windows) scripts. - **extend** mode is similar to new but is used when you want to update your timezone data to a different version and ensure backward compatibility with the old data. It is always used with a database name argument. In some situations, when it is impossible to ensure backward compatibility just by merging the two versions of timezone data, an update of the data in the tables of the database is done. It is executed using **make_tz.sh -g extend** for Linux and **make_tz.bat /extend** for Windows. **coradb dump_tz** utility dumps the compiled CoraDB timezone library file as a human-readable format on the console. It is better to save the output as a file by output redirection. --- # System parameters Source: https://www.coradb.ai/manual/admin/config.html System parameters control how the CoraDB server, the broker and the client tools behave: memory sizes, ports, logging, locking and SQL compatibility options. This page explains where the parameters are set and how to change them, and lists every database server parameter with a link to its description. The parameters are described in detail on these pages: - [Connection, memory, disk and thread parameters](https://www.coradb.ai/manual/admin/config_resources.html) - [Error log, lock, logging and transaction parameters](https://www.coradb.ai/manual/admin/config_logging.html) - [SQL statement, type, timezone and cache parameters](https://www.coradb.ai/manual/admin/config_sql.html) - [Utility, graph and other parameters](https://www.coradb.ai/manual/admin/config_other.html) - [Broker parameters](https://www.coradb.ai/manual/admin/config_broker.html) (**coradb_broker.conf**) ## Configuration files CoraDB reads its configuration from files in the **$CORADB/conf** directory: | File | Used by | |---|---| | **coradb.conf** | The database server, and the client programs (CAS, corasql and the `coradb` utilities) | | **coradb_broker.conf** | The brokers. See [Broker parameters](https://www.coradb.ai/manual/admin/config_broker.html). | | **cm.conf** | CoraDB Manager Server (CMS) | **coradb.conf** is divided into sections: `[common]` applies to every database, `[@dbname]` to one database, `[standalone]` to utilities run in stand-alone mode, and `[service]` lists the processes that `coradb service start` launches. See [Sections of coradb.conf](https://www.coradb.ai/manual/admin/config.html#sections-of-coradbconf). ## Client, server and session parameters The database server has a client/server architecture. The server process (`cora_server`) manages storage, concurrency and transactions; the client side (the broker's CAS processes, corasql and the `coradb` utilities in client/server mode) parses and prepares queries. Each parameter in **coradb.conf** applies to one side or both: - A **server** parameter is read by the `cora_server` process. - A **client** parameter is read by CAS, corasql and the `coradb` utilities. - A **client/server** parameter is read by both. Some parameters can be changed while the database is running (**Dynamic** in the reference tables below). What a change affects depends on the kind of parameter: - A dynamic **server** parameter changes for the whole server, until the server restarts. - A dynamic **session** parameter changes only for the session (application connection) that changed it. For example, after a session sets `block_ddl_statement=yes`, only that session is refused DDL statements. - A dynamic **client/server** parameter that is not a session parameter changes on the server and in the client that changed it, but not in other clients. For example, if one corasql session changes `error_log_level` from `ERROR` to `WARNING`, the server and that corasql session use `WARNING`; other clients keep `ERROR`. A DBA can change any dynamic parameter. Other users can change only session parameters. > **Note:** > A change made while the database is running is lost when the server restarts. To keep it, also change **coradb.conf** and restart the database server and the brokers. ## Changing parameters ### In the configuration file Edit **coradb.conf** in **$CORADB/conf** and restart the server. These rules apply: - Parameter names are not case-sensitive. - The name and value of a parameter must be on the same line, separated by an equal sign (`=`). Spaces around the equal sign are allowed. - String values are written without quotes, unless they contain spaces. - Size parameters accept the units `B`, `K`, `M`, `G` and `T` (for example `data_buffer_size=512M`); time parameters accept `ms`, `s`, `min` and `h`. Without a unit, sizes are in bytes and times in the unit given in the parameter's description. ### With SQL The [SET SYSTEM PARAMETERS](https://www.coradb.ai/manual/sql/query/set.html#system-parameters) statement changes one or more dynamic parameters. Separate several assignments with semicolons; the value `DEFAULT` restores the default value (except for `call_stack_dump_activation_list`). ```sql SET SYSTEM PARAMETERS 'cte_max_recursions=100; lock_timeout=10'; SET SYSTEM PARAMETERS 'lock_timeout=DEFAULT'; ``` ### With a corasql session command In the corasql interpreter, the `;set` session command (abbreviated `;se`) changes a parameter for the current session: ```text corasql> ;se block_ddl_statement=1 === Set Param Input === block_ddl_statement=1 ``` ## Parameter reference In the tables below, **Applied to** tells which processes read the parameter (*client*: CAS, CSQL and the coradb utilities in client/server mode; *server*: the database server process; *client/server*: both). **Session** marks session parameters, and **Dynamic** marks parameters that can be changed while the database is running. ### Connection-related parameters Described in [Connection-related parameters](https://www.coradb.ai/manual/admin/config_resources.html#connection-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [coradb_port_id](https://www.coradb.ai/manual/admin/config_resources.html#coradb_port_id) | client | | int | 1,523 | | | [check_peer_alive](https://www.coradb.ai/manual/admin/config_resources.html#check_peer_alive) | client/server | yes | string | both | yes | | [db_hosts](https://www.coradb.ai/manual/admin/config_resources.html#db_hosts) | client | yes | string | NULL | yes | | [max_clients](https://www.coradb.ai/manual/admin/config_resources.html#max_clients) | server | | int | 100 | | | [tcp_keepalive](https://www.coradb.ai/manual/admin/config_resources.html#tcp_keepalive) | client/server | | bool | yes | | ### Memory-related parameters Described in [Memory-related parameters](https://www.coradb.ai/manual/admin/config_resources.html#memory-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [data_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#data_buffer_size) | server | | byte | 32,768 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | | [index_scan_oid_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#index_scan_oid_buffer_size) | server | | byte | 4 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | | [max_agg_hash_size](https://www.coradb.ai/manual/admin/config_resources.html#max_agg_hash_size) | server | | byte | 2,097,152(2M) | | | [max_hash_list_scan_size](https://www.coradb.ai/manual/admin/config_resources.html#max_hash_list_scan_size) | server | | byte | 134,217,728 (128M) | | | [sort_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#sort_buffer_size) | server | | byte | 128 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | | [temp_file_memory_size_in_pages](https://www.coradb.ai/manual/admin/config_resources.html#temp_file_memory_size_in_pages) | server | | int | 4 | | | [thread_stacksize](https://www.coradb.ai/manual/admin/config_resources.html#thread_stacksize) | server | | byte | 1,048,576 | | ### Disk-related parameters Described in [Disk-related parameters](https://www.coradb.ai/manual/admin/config_resources.html#disk-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [db_volume_size](https://www.coradb.ai/manual/admin/config_resources.html#db_volume_size) | server | | byte | 512M | | | [dont_reuse_heap_file](https://www.coradb.ai/manual/admin/config_resources.html#dont_reuse_heap_file) | server | | bool | no | | | [log_volume_size](https://www.coradb.ai/manual/admin/config_resources.html#log_volume_size) | server | | byte | 512M | | | [temp_file_max_size_in_pages](https://www.coradb.ai/manual/admin/config_resources.html#temp_file_max_size_in_pages) | server | | int | -1 | | | [temp_volume_path](https://www.coradb.ai/manual/admin/config_resources.html#temp_volume_path) | server | | string | NULL | | | [unfill_factor](https://www.coradb.ai/manual/admin/config_resources.html#unfill_factor) | server | | float | 0.1 | | | [volume_extension_path](https://www.coradb.ai/manual/admin/config_resources.html#volume_extension_path) | server | | string | NULL | | | [double_write_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#double_write_buffer_size) | server | | byte | 2M | | | [data_file_os_advise](https://www.coradb.ai/manual/admin/config_resources.html#data_file_os_advise) | server | | int | 0 | | | [max_values_unpaged_list](https://www.coradb.ai/manual/admin/config_resources.html#max_values_unpaged_list) | client/server | yes | int | 2,048 | yes | | [ro_data_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#ro_data_buffer_size) | server | | byte | 512M | | | [ro_data_buffer_pages](https://www.coradb.ai/manual/admin/config_resources.html#ro_data_buffer_pages) | server | | int | 32,768 | | ### Error message-related parameters Described in [Error message-related parameters](https://www.coradb.ai/manual/admin/config_logging.html#error-message-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [call_stack_dump_activation_list](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_activation_list) | client/server | | string | DEFAULT | | | [call_stack_dump_deactivation_list](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_deactivation_list) | client/server | | string | NULL | | | [call_stack_dump_on_error](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_on_error) | client/server | | bool | no | | | [error_log](https://www.coradb.ai/manual/admin/config_logging.html#error_log) | client/server | | string | cora_client.err, cora_server.err | | | [error_log_level](https://www.coradb.ai/manual/admin/config_logging.html#error_log_level) | client/server | | string | NOTIFICATION | | | [error_log_warning](https://www.coradb.ai/manual/admin/config_logging.html#error_log_warning) | client/server | | bool | no | | | [error_log_size](https://www.coradb.ai/manual/admin/config_logging.html#error_log_size) | client/server | | int | 512M | | ### Concurrency/lock-related parameters Described in [Concurrency/lock-related parameters](https://www.coradb.ai/manual/admin/config_logging.html#concurrencylock-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [deadlock_detection_interval_in_secs](https://www.coradb.ai/manual/admin/config_logging.html#deadlock_detection_interval_in_secs) | server | | float | 1.0 | | | [isolation_level](https://www.coradb.ai/manual/admin/config_logging.html#isolation_level) | client | yes | int | 4 | yes | | [lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#lock_escalation) | server | | int | 100,000 | | | [lock_timeout](https://www.coradb.ai/manual/admin/config_logging.html#lock_timeout) | client | yes | msec | -1 | yes | | [rollback_on_lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#rollback_on_lock_escalation) | server | | bool | no | | ### Logging-related parameters Described in [Logging-related parameters](https://www.coradb.ai/manual/admin/config_logging.html#logging-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [adaptive_flush_control](https://www.coradb.ai/manual/admin/config_logging.html#adaptive_flush_control) | server | | bool | yes | | | [background_archiving](https://www.coradb.ai/manual/admin/config_logging.html#background_archiving) | server | | bool | yes | | | [checkpoint_every_size](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_every_size) | server | | byte | 100,000 × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | | | [checkpoint_interval](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_interval) | server | | msec | 6min | | | [checkpoint_sleep_msecs](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_sleep_msecs) | server | | msec | 1 | | | [force_remove_log_archives](https://www.coradb.ai/manual/admin/config_logging.html#force_remove_log_archives) | server | | bool | yes | | | [log_buffer_size](https://www.coradb.ai/manual/admin/config_logging.html#log_buffer_size) | server | | byte | 16k × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | | | [log_max_archives](https://www.coradb.ai/manual/admin/config_logging.html#log_max_archives) | server | | int | INT_MAX | | | [log_trace_flush_time](https://www.coradb.ai/manual/admin/config_logging.html#log_trace_flush_time) | server | | msec | 0 | | | [max_flush_size_per_second](https://www.coradb.ai/manual/admin/config_logging.html#max_flush_size_per_second) | server | | byte | 10,000 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | | [remove_log_archive_interval_in_secs](https://www.coradb.ai/manual/admin/config_logging.html#remove_log_archive_interval_in_secs) | server | | sec | 0 | | | [sync_on_flush_size](https://www.coradb.ai/manual/admin/config_logging.html#sync_on_flush_size) | server | | byte | 200 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | | [ddl_audit_log](https://www.coradb.ai/manual/admin/config_logging.html#ddl_audit_log) | client | | bool | no | | | [ddl_audit_log_size](https://www.coradb.ai/manual/admin/config_logging.html#ddl_audit_log_size) | client | | byte | 10M | | ### Transaction processing-related parameters Described in [Transaction processing-related parameters](https://www.coradb.ai/manual/admin/config_logging.html#transaction-processing-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [async_commit](https://www.coradb.ai/manual/admin/config_logging.html#async_commit) | server | | bool | no | | | [group_commit_interval_in_msecs](https://www.coradb.ai/manual/admin/config_logging.html#group_commit_interval_in_msecs) | server | | msec | 0 | | ### Statement/type-related parameters Described in [Statement/type-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [add_column_update_hard_default](https://www.coradb.ai/manual/admin/config_sql.html#add_column_update_hard_default) | client/server | yes | bool | no | yes | | [alter_table_change_type_strict](https://www.coradb.ai/manual/admin/config_sql.html#alter_table_change_type_strict) | client/server | yes | bool | yes | yes | | [allow_truncated_string](https://www.coradb.ai/manual/admin/config_sql.html#allow_truncated_string) | client/server | yes | bool | no | yes | | [ansi_quotes](https://www.coradb.ai/manual/admin/config_sql.html#ansi_quotes) | client | | bool | yes | | | [block_ddl_statement](https://www.coradb.ai/manual/admin/config_sql.html#block_ddl_statement) | client | yes | bool | no | yes | | [block_nowhere_statement](https://www.coradb.ai/manual/admin/config_sql.html#block_nowhere_statement) | client | yes | bool | no | yes | | [compat_numeric_division_scale](https://www.coradb.ai/manual/admin/config_sql.html#compat_numeric_division_scale) | client/server | yes | bool | no | yes | | [create_table_reuseoid](https://www.coradb.ai/manual/admin/config_sql.html#create_table_reuseoid) | client | yes | bool | yes | yes | | [cte_max_recursions](https://www.coradb.ai/manual/admin/config_sql.html#cte_max_recursions) | client/server | yes | int | 2000 | yes | | [default_week_format](https://www.coradb.ai/manual/admin/config_sql.html#default_week_format) | client/server | yes | int | 0 | yes | | [group_concat_max_len](https://www.coradb.ai/manual/admin/config_sql.html#group_concat_max_len) | server | yes | byte | 1,024 | | | [intl_check_input_string](https://www.coradb.ai/manual/admin/config_sql.html#intl_check_input_string) | client | yes | bool | no | yes | | [intl_collation](https://www.coradb.ai/manual/admin/config_sql.html#intl_collation) | client | yes | string | | yes | | [intl_date_lang](https://www.coradb.ai/manual/admin/config_sql.html#intl_date_lang) | client | yes | string | | yes | | [intl_number_lang](https://www.coradb.ai/manual/admin/config_sql.html#intl_number_lang) | client | yes | string | | yes | | [json_max_array_idx](https://www.coradb.ai/manual/admin/config_sql.html#json_max_array_idx) | server | yes | string | 65,536 | yes | | [no_backslash_escapes](https://www.coradb.ai/manual/admin/config_sql.html#no_backslash_escapes) | client | | bool | yes | | | [only_full_group_by](https://www.coradb.ai/manual/admin/config_sql.html#only_full_group_by) | client | yes | bool | no | yes | | [oracle_style_empty_string](https://www.coradb.ai/manual/admin/config_sql.html#oracle_style_empty_string) | client | | bool | no | | | [pipes_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#pipes_as_concat) | client | | bool | yes | | | [plus_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#plus_as_concat) | client | | bool | yes | | | [require_like_escape_character](https://www.coradb.ai/manual/admin/config_sql.html#require_like_escape_character) | client | | bool | no | | | [return_null_on_function_errors](https://www.coradb.ai/manual/admin/config_sql.html#return_null_on_function_errors) | client/server | yes | bool | no | yes | | [string_max_size_bytes](https://www.coradb.ai/manual/admin/config_sql.html#string_max_size_bytes) | client/server | yes | byte | 1,048,576 | yes | | [unicode_input_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_input_normalization) | client | yes | bool | no | yes | | [unicode_output_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_output_normalization) | client | yes | bool | no | yes | | [update_use_attribute_references](https://www.coradb.ai/manual/admin/config_sql.html#update_use_attribute_references) | client | yes | bool | no | yes | ### Thread-related parameters Described in [Thread-related parameters](https://www.coradb.ai/manual/admin/config_resources.html#thread-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [thread_connection_pooling](https://www.coradb.ai/manual/admin/config_resources.html#thread_connection_pooling) | server | | bool | yes | | | [thread_connection_timeout_seconds](https://www.coradb.ai/manual/admin/config_resources.html#thread_connection_timeout_seconds) | server | | int | 300 | | | [thread_worker_pooling](https://www.coradb.ai/manual/admin/config_resources.html#thread_worker_pooling) | server | | bool | yes | | | [thread_worker_timeout_seconds](https://www.coradb.ai/manual/admin/config_resources.html#thread_worker_timeout_seconds) | server | | int | 300 | | | [loaddb_worker_count](https://www.coradb.ai/manual/admin/config_resources.html#loaddb_worker_count) | server | | int | 8 | | ### Timezone parameter Described in [Timezone parameter](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [server_timezone](https://www.coradb.ai/manual/admin/config_sql.html#server_timezone) | server | | string | OS timezone | yes | | [timezone](https://www.coradb.ai/manual/admin/config_sql.html#timezone) | client/server | yes | string | The value of server_timezone | yes | | [tz_leap_second_support](https://www.coradb.ai/manual/admin/config_sql.html#tz_leap_second_support) | server | | bool | no | yes | ### Query plan cache-related parameters Described in [Query plan cache-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#query-plan-cache-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [max_plan_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_plan_cache_entries) | client/server | | int | 1,000 | | | [max_filter_pred_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_filter_pred_cache_entries) | client/server | | int | 1,000 | | ### Query cache-related parameters Described in [Query cache-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#query-cache-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [max_query_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_query_cache_entries) | server | | int | 0 | yes | | [query_cache_size_in_pages](https://www.coradb.ai/manual/admin/config_sql.html#query_cache_size_in_pages) | server | | int | 0 | yes | ### Utility-related parameters Described in [Utility-related parameters](https://www.coradb.ai/manual/admin/config_other.html#utility-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [backup_volume_max_size_bytes](https://www.coradb.ai/manual/admin/config_other.html#backup_volume_max_size_bytes) | server | | byte | 0 | | | [communication_histogram](https://www.coradb.ai/manual/admin/config_other.html#communication_histogram) | client | yes | bool | no | yes | | [compactdb_page_reclaim_only](https://www.coradb.ai/manual/admin/config_other.html#compactdb_page_reclaim_only) | server | | int | 0 | | | [corasql_history_num](https://www.coradb.ai/manual/admin/config_other.html#corasql_history_num) | client | yes | int | 50 | yes | ### Other parameters Described in [Other parameters](https://www.coradb.ai/manual/admin/config_other.html#other-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [access_ip_control](https://www.coradb.ai/manual/admin/config_other.html#access_ip_control) | server | | bool | no | | | [access_ip_control_file](https://www.coradb.ai/manual/admin/config_other.html#access_ip_control_file) | server | | string | | | | [agg_hash_respect_order](https://www.coradb.ai/manual/admin/config_other.html#agg_hash_respect_order) | client | yes | bool | yes | yes | | [auto_restart_server](https://www.coradb.ai/manual/admin/config_other.html#auto_restart_server) | server | yes | bool | yes | | | [enable_string_compression](https://www.coradb.ai/manual/admin/config_other.html#enable_string_compression) | client/server | | bool | yes | | | [index_scan_in_oid_order](https://www.coradb.ai/manual/admin/config_other.html#index_scan_in_oid_order) | client | yes | bool | no | yes | | [index_unfill_factor](https://www.coradb.ai/manual/admin/config_other.html#index_unfill_factor) | server | | float | 0.05 | | | [java_stored_procedure](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure) | server | | bool | no | | | [java_stored_procedure_port](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure_port) | server | | int | 0 | | | [java_stored_procedure_jvm_options](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure_jvm_options) | server | | string | | | | [multi_range_optimization_limit](https://www.coradb.ai/manual/admin/config_other.html#multi_range_optimization_limit) | server | yes | int | 100 | | | [optimizer_enable_merge_join](https://www.coradb.ai/manual/admin/config_other.html#optimizer_enable_merge_join) | client | yes | bool | no | yes | | [use_stat_estimation](https://www.coradb.ai/manual/admin/config_other.html#use_stat_estimation) | server | | bool | no | | | [pthread_scope_process](https://www.coradb.ai/manual/admin/config_other.html#pthread_scope_process) | server | | bool | yes | | | [server](https://www.coradb.ai/manual/admin/config_other.html#server) | server | | string | | | | [service](https://www.coradb.ai/manual/admin/config_other.html#service) | server | | string | | | | [session_state_timeout](https://www.coradb.ai/manual/admin/config_other.html#session_state_timeout) | server | | sec | 21,600 | | | [sort_limit_max_count](https://www.coradb.ai/manual/admin/config_other.html#sort_limit_max_count) | client | yes | int | 0 | yes | | [sql_trace_slow](https://www.coradb.ai/manual/admin/config_other.html#sql_trace_slow) | server | yes | msec | -1 | | | [sql_trace_execution_plan](https://www.coradb.ai/manual/admin/config_other.html#sql_trace_execution_plan) | server | yes | bool | no | | | [use_orderby_sort_limit](https://www.coradb.ai/manual/admin/config_other.html#use_orderby_sort_limit) | server | yes | bool | yes | | | [data_buffer_neighbor_flush_pages](https://www.coradb.ai/manual/admin/config_other.html#data_buffer_neighbor_flush_pages) | server | | int | 8 | | | [data_buffer_neighbor_flush_nondirty](https://www.coradb.ai/manual/admin/config_other.html#data_buffer_neighbor_flush_nondirty) | server | | bool | no | | | [tde_keys_file_path](https://www.coradb.ai/manual/admin/config_other.html#tde_keys_file_path) | server | | string | NULL | | | [tde_default_algorithm](https://www.coradb.ai/manual/admin/config_other.html#tde_default_algorithm) | server | | string | AES | | ### Graph-related parameters Described in [Graph-related parameters](https://www.coradb.ai/manual/admin/config_other.html#graph-related-parameters). | Parameter | Applied to | Session | Type | Default | Dynamic | |---|---|---|---|---|---| | [graph_query_rewrite_mode](https://www.coradb.ai/manual/admin/config_other.html#graph_query_rewrite_mode) | client | yes | bool | no | yes | | [graph_query_filter_mode](https://www.coradb.ai/manual/admin/config_other.html#graph_query_filter_mode) | client/server | yes | string | NULL | yes | | [concurrent_map_erase_threshold](https://www.coradb.ai/manual/admin/config_other.html#concurrent_map_erase_threshold) | server | | float | 0.7 | | | [graph_insert_dml_logging](https://www.coradb.ai/manual/admin/config_other.html#graph_insert_dml_logging) | server | | bool | no | | | [graph_deferred_load_threads](https://www.coradb.ai/manual/admin/config_other.html#graph_deferred_load_threads) | server | | int | 0 | yes | | [graph_edges_container_buckets_count](https://www.coradb.ai/manual/admin/config_other.html#graph_edges_container_buckets_count) | server | | int | 1,009 | yes | | [graph_vertices_container_buckets_count](https://www.coradb.ai/manual/admin/config_other.html#graph_vertices_container_buckets_count) | server | | int | 1,009 | yes | | [graph_use_dagger](https://www.coradb.ai/manual/admin/config_other.html#graph_use_dagger) | server | | bool | yes | yes | - **log_page_size**: A log volume page size specified by **--log-page-size** option when you are [creating database](https://www.coradb.ai/manual/admin/admin_utils.html#createdb). Default: 16KB. log page related parameter's value is rounded off by page unit. For example, the value of checkpoint_every_size is divided by 16KB and its decimal point is dropped, then it is multiplied by 16KB. - **db_page_size**: A DB volume page size specified by **--db-page-size** option when you are [creating database](https://www.coradb.ai/manual/admin/admin_utils.html#createdb). Default: 16KB. DB page related parameter's value is rounded off by page unit. For example, the value of data_buffer_size is divided by 16KB and its decimal point is dropped, then it is multiplied by 16KB. ## Sections of coradb.conf Parameters specified in **coradb.conf** have the following four sections: - Used when the CoraDB service starts: \[service\] section - Applied commonly to all databases: \[common\] section - Applied individually to each database: \[@\<*database*\>\] section - Used only when the coradb utilities are run with stand-alone mode(--SA-mode): \[standalone\] section Where \<*database*\> is the name of the database to which each parameter applies. If a parameter configured in \[common\] is the same as the one configured in \[@\<*database*\>\], the one configured in \[@\<*database*\>\] is applied. ``` text ..... [common] ..... sort_buffer_size=2M ..... [standalone] sort_buffer_size=256M ..... ``` Configuration defined in \[standalone\] is used only when coradb utilities started with "coradb" are run with stand-alone mode. For example, on the above configuration, if DB is started with --CS-mode(default)(coradb databases start db_name), "sort_buffer_size=2M" is applied. However, if DB is stopped and "coradb loaddb --SA-mode" is executed, "sort_buffer_size=256M" is applied. If you run "coradb loaddb --SA-mode", bigger size of sort buffer will be required during index creation; therefore, increasing sort buffer size will be better for the performance of "loaddb" execution. ## Default coradb.conf The **coradb.conf** file installed with CoraDB sets the most important parameters. Any parameter not listed here takes its default value; to change it, add it to the file. Without the license header, the file looks like this: ```ini # Service section - a section for 'coradb service' command [service] # The list of processes to be started automatically by 'coradb service start' command service=server,broker,manager # The list of database servers in all by 'coradb service start' command. # This property is effective only when the above 'service' property contains 'server' keyword. #server=foo,bar # Common section - properties for all databases # This section will be applied before other database specific sections. [common] # Size of data buffer are using K, M, G, T unit data_buffer_size=512M # Size of data buffer are using K, M, G, T unit ro_data_buffer_size=512M # Size of log buffer are using K, M, G, T unit log_buffer_size=256M # Size of sort buffer are using K, M, G, T unit # The sort buffer should be allocated per thread. # So, the max size of the sort buffer is sort_buffer_size * max_clients. sort_buffer_size=2M # The maximum number of concurrent client connections the server will accept. # This value also means the total # of concurrent transactions. max_clients=100 # TCP port id for the CORADB programs (used by all clients). coradb_port_id=1523 # The createdb and addvoldb create a volume file of 'db_volume_size' size # if don't have any options about size. db_volume_size=512M # The createdb creates a log volume file of 'log_volume_size' size # if don't have any options about size. log_volume_size=512M # The log_max_archives parameter configures the maximum number of archive log files kept. log_max_archives=0 ``` To give one database its own values, add a section named after it. Here *testdb* gets a smaller data buffer and fewer clients than the other databases: ```ini [common] data_buffer_size=512M max_clients=100 [@testdb] data_buffer_size=128M max_clients=10 ``` ## Broker parameters The broker reads its own file, **coradb_broker.conf**. Its parameters are listed in [Broker parameters](https://www.coradb.ai/manual/admin/config_broker.html). --- # Broker parameters Source: https://www.coradb.ai/manual/admin/config_broker.html The broker configuration file **coradb_broker.conf** is in the **$CORADB/conf** directory. It has a `[broker]` section with parameters common to all brokers, followed by one `[%broker_name]` section for each broker. ## Broker parameter reference The following table shows the broker parameters available in the broker configuration file (**coradb_broker.conf**). For details, see [Common parameters](https://www.coradb.ai/manual/admin/config_broker.html#common-parameters) and [Parameter by broker](https://www.coradb.ai/manual/admin/config_broker.html#parameter-by-broker). You can temporarily change the parameter of which configuration values can be dynamically changed by using the **broker_changer** utility. To apply configuration values even after restarting all brokers with **coradb broker restart**, you should change the values in the **coradb_broker.conf** file. **Common (`[broker]`)** | Use | Parameter | Type | Default | Dynamic change | |---|---|---|---|---| | Access | [ACCESS_CONTROL](https://www.coradb.ai/manual/admin/config_broker.html#access_control) | bool | no | | | Access | [ACCESS_CONTROL_FILE](https://www.coradb.ai/manual/admin/config_broker.html#access_control_file) | string | | | | Logging | [ADMIN_LOG_FILE](https://www.coradb.ai/manual/admin/config_broker.html#admin_log_file) | string | Log/broker/coradb_broker.log | | | Broker server (cora_broker) | [MASTER_SHM_ID](https://www.coradb.ai/manual/admin/config_broker.html#master_shm_id) | int | 30,001 | | **Per broker (`[%broker_name]`)** | Use | Parameter | Type | Default | Dynamic change | |---|---|---|---|---| | Access | [ACCESS_LIST](https://www.coradb.ai/manual/admin/config_broker.html#access_list) | string | | | | Access | [ACCESS_MODE](https://www.coradb.ai/manual/admin/config_broker.html#access_mode) | string | RW | yes | | Access | [BROKER_PORT](https://www.coradb.ai/manual/admin/config_broker.html#broker_port) | int | 30,000(max : 65,535) | | | Access | [CONNECT_ORDER](https://www.coradb.ai/manual/admin/config_broker.html#connect_order) | string | SEQ | yes | | Access | [ENABLE_MONITOR_HANG](https://www.coradb.ai/manual/admin/config_broker.html#enable_monitor_hang) | string | OFF | | | Access | [KEEP_CONNECTION](https://www.coradb.ai/manual/admin/config_broker.html#keep_connection) | string | AUTO | yes | | Access | [MAX_NUM_DELAYED_HOSTS_LOOKUP](https://www.coradb.ai/manual/admin/config_broker.html#max_num_delayed_hosts_lookup) | int | -1 | | | Access | [PREFERRED_HOSTS](https://www.coradb.ai/manual/admin/config_broker.html#preferred_hosts) | string | | yes | | Access | [RECONNECT_TIME](https://www.coradb.ai/manual/admin/config_broker.html#reconnect_time) | sec | 600 | yes | | Broker App. Server(CAS) | [APPL_SERVER_MAX_SIZE](https://www.coradb.ai/manual/admin/config_broker.html#appl_server_max_size) | MB | Windows 32bit: 40, Windows 64bit: 80, Linux: 0(max: 2,097,151) | yes | | Broker App. Server(CAS) | [APPL_SERVER_MAX_SIZE_HARD_LIMIT](https://www.coradb.ai/manual/admin/config_broker.html#appl_server_max_size_hard_limit) | MB | 1,024 | yes | | Broker App. Server(CAS) | [APPL_SERVER_PORT](https://www.coradb.ai/manual/admin/config_broker.html#appl_server_port) | int | BROKER_PORT+1 | | | Broker App. Server(CAS) | [APPL_SERVER_SHM_ID](https://www.coradb.ai/manual/admin/config_broker.html#appl_server_shm_id) | int | 30,000 | | | Broker App. Server(CAS) | [AUTO_ADD_APPL_SERVER](https://www.coradb.ai/manual/admin/config_broker.html#auto_add_appl_server) | string | ON | | | Broker App. Server(CAS) | [MAX_NUM_APPL_SERVER](https://www.coradb.ai/manual/admin/config_broker.html#max_num_appl_server) | int | 40 | | | Broker App. Server(CAS) | [MIN_NUM_APPL_SERVER](https://www.coradb.ai/manual/admin/config_broker.html#min_num_appl_server) | int | 5 | | | Broker App. Server(CAS) | [TIME_TO_KILL](https://www.coradb.ai/manual/admin/config_broker.html#time_to_kill) | sec | 120 | yes | | Transaction & Query | [CCI_DEFAULT_AUTOCOMMIT](https://www.coradb.ai/manual/admin/config_broker.html#cci_default_autocommit) | string | ON | | | Transaction & Query | [LONG_QUERY_TIME](https://www.coradb.ai/manual/admin/config_broker.html#long_query_time) | sec | 60(max: 86,400) | yes | | Transaction & Query | [LONG_TRANSACTION_TIME](https://www.coradb.ai/manual/admin/config_broker.html#long_transaction_time) | sec | 60(max: 86,400) | yes | | Transaction & Query | [MAX_PREPARED_STMT_COUNT](https://www.coradb.ai/manual/admin/config_broker.html#max_prepared_stmt_count) | int | 2,000(min: 1) | yes | | Transaction & Query | [MAX_QUERY_TIMEOUT](https://www.coradb.ai/manual/admin/config_broker.html#max_query_timeout) | sec | 0(max: 86,400) | yes | | Transaction & Query | [SESSION_TIMEOUT](https://www.coradb.ai/manual/admin/config_broker.html#session_timeout) | sec | 300 | yes | | Transaction & Query | [STATEMENT_POOLING](https://www.coradb.ai/manual/admin/config_broker.html#statement_pooling) | string | ON | yes | | Transaction & Query | [JDBC_CACHE](https://www.coradb.ai/manual/admin/config_broker.html#jdbc_cache) | string | OFF | yes | | Transaction & Query | [JDBC_CACHE_HINT_ONLY](https://www.coradb.ai/manual/admin/config_broker.html#jdbc_cache_hint_only) | string | OFF | yes | | Transaction & Query | [JDBC_CACHE_LIFE_TIME](https://www.coradb.ai/manual/admin/config_broker.html#jdbc_cache_life_time) | sec | 1000 | yes | | Transaction & Query | [TRIGGER_ACTION](https://www.coradb.ai/manual/admin/config_broker.html#trigger_action) | string | ON | yes | | Logging | [ACCESS_LOG](https://www.coradb.ai/manual/admin/config_broker.html#access_log) | string | OFF | yes | | Logging | [ACCESS_LOG_DIR](https://www.coradb.ai/manual/admin/config_broker.html#access_log_dir) | string | Log/broker | | | Logging | [ACCESS_LOG_MAX_SIZE](https://www.coradb.ai/manual/admin/config_broker.html#access_log_max_size) | KB | 10M(max: 2G) | yes | | Logging | [ERROR_LOG_DIR](https://www.coradb.ai/manual/admin/config_broker.html#error_log_dir) | string | Log/broker/error_log | yes | | Logging | [LOG_DIR](https://www.coradb.ai/manual/admin/config_broker.html#log_dir) | string | Log/broker/sql_log | yes | | Logging | [SLOW_LOG](https://www.coradb.ai/manual/admin/config_broker.html#slow_log) | string | ON | yes | | Logging | [SLOW_LOG_DIR](https://www.coradb.ai/manual/admin/config_broker.html#slow_log_dir) | string | Log/broker/sql_log | yes | | Logging | [SQL_LOG](https://www.coradb.ai/manual/admin/config_broker.html#sql_log) | string | ON | yes | | Logging | [SQL_LOG_MAX_SIZE](https://www.coradb.ai/manual/admin/config_broker.html#sql_log_max_size) | KB | 10,000 | yes | | Etc | [MAX_STRING_LENGTH](https://www.coradb.ai/manual/admin/config_broker.html#max_string_length) | int | -1 | | | Etc | [SERVICE](https://www.coradb.ai/manual/admin/config_broker.html#service) | string | ON | | | Etc | [SSL](https://www.coradb.ai/manual/admin/config_broker.html#ssl) | string | OFF | | | Etc | [SOURCE_ENV](https://www.coradb.ai/manual/admin/config_broker.html#source_env) | string | coradb.env | | ## Default coradb_broker.conf The **coradb_broker.conf** file installed with CoraDB defines a `[%query_editor]` broker on port 30000 and a `[%BROKER1]` broker on port 33000: ```ini [broker] MASTER_SHM_ID =30001 ADMIN_LOG_FILE =log/broker/coradb_broker.log [%query_editor] SERVICE =ON SSL =OFF BROKER_PORT =30000 MIN_NUM_APPL_SERVER =5 MAX_NUM_APPL_SERVER =40 APPL_SERVER_SHM_ID =30000 LOG_DIR =log/broker/sql_log ERROR_LOG_DIR =log/broker/error_log SQL_LOG =ON TIME_TO_KILL =120 SESSION_TIMEOUT =300 KEEP_CONNECTION =AUTO CCI_DEFAULT_AUTOCOMMIT =ON [%BROKER1] SERVICE =ON SSL =OFF BROKER_PORT =33000 MIN_NUM_APPL_SERVER =5 MAX_NUM_APPL_SERVER =40 APPL_SERVER_SHM_ID =33000 LOG_DIR =log/broker/sql_log ERROR_LOG_DIR =log/broker/error_log SQL_LOG =ON TIME_TO_KILL =120 SESSION_TIMEOUT =300 KEEP_CONNECTION =AUTO CCI_DEFAULT_AUTOCOMMIT =ON ``` ## Using another configuration file You can specify the location of broker configuration file (**coradb_broker.conf**) file by using the **CORADB_BROKER_CONF_FILE** variable. The variable is used when executing several brokers with different configuration. ## Common parameters The following are parameters commonly applied to entire brokers; it is written under \[broker\] section. ### Access #### ACCESS_CONTROL **ACCESS_CONTROL** is a parameter used to limit applications which are trying to connect a broker. The default value is **OFF**. For details, see [Limiting broker access](https://www.coradb.ai/manual/admin/control_broker.html#limiting-broker-access). #### ACCESS_CONTROL_FILE **ACCESS_CONTROL_FILE** is a parameter to configure the name of a file in which a database name, database user ID, and the list of IPs are stored. List of IPs can be written up to the maximum of 256 lines per \<*db_name*\>:\<*db_user*\> in a broker. For details, see [Limiting broker access](https://www.coradb.ai/manual/admin/control_broker.html#limiting-broker-access). ### Logging #### ADMIN_LOG_FILE **ADMIN_LOG_FILE** is a parameter to configure the file in which time of running CoraDB broker is stored. The default value is a **log/broker/coradb_broker.log** file. ### Broker server(cora_broker) #### MASTER_SHM_ID **MASTER_SHM_ID** is a parameter used to specify the identifier of shared memory which is used to manage the CoraDB broker. Its value must be unique in the system. The default value is **30001**. ## Parameter by broker The following describes parameters to configure the environment variables of brokers; each parameter is located under *\[%broker_name\]*. The maximum length of *broker_name* is 63 characters in English. ### Access #### ACCESS_LIST **ACCESS_LIST** is a parameter to configure the name of a file where the list of IP addresses of an application which allows access to the CoraDB broker is stored. To allow access by IP addresses access 210.192.33.\* and 210.194.34.\*, store them to a file (ip_lists.txt) and then assign the file name with the value of this parameter. #### ACCESS_MODE **ACCESS_MODE** is a parameter to configure default mode of the broker. The default value is **RW**. For details, see *coradb_broker.conf*. #### BROKER_PORT **BROKER_PORT** is a parameter to configure the port number of the broker; the value must be unique and smaller than 65,535. The default port value of **query_editor**' broker is **30,000** and the port value of the **broker1** is **33,000**. #### CONNECT_ORDER **CONNECT_ORDER** is a parameter to specify whether a CAS tries to connect to one of hosts in the order or randomly in **$CORADB_DATABASES/databases.txt**, when a CAS decides the order of connecting to a host. The default is **SEQ**; a CAS tries to connect to a host in the order. if this value is **RANDOM**, a CAS tries to connect to a host randomly. If **PREFERRED_HOSTS** parameter is specified, firstly a CAS tries to connect to one of hosts specified in **PREFERRED_HOSTS**, then uses db-host values in **$CORADB_DATABASES/databases.txt** only when the connection is failed. #### ENABLE_MONITOR_HANG **ENABLE_MONITOR_HANG** is a parameter to configure whether to block the access from the application to the broker or not, when more than a certain ratio of CASes on that broker are hung. If the **ENABLE_MONITOR_HANG** parameter value is **ON**, blocking feature is processed. The default value is **OFF**. If it is **OFF**, don't do the behavior. The broker process judges the CAS as hung if the hanging status of the CAS keeps more than one minute, then block the access from applications to that broker; it brings the behavior which the applications try to access to the alternative hosts(altHosts) configured by the connection URL. #### KEEP_CONNECTION **KEEP_CONNECTION** is a parameter to configure the way of connection between CAS and application clients; it is set to one of the following: **ON** or **AUTO**. If this value is **ON**, it is connected in connection unit. If it is **AUTO** and the number of servers is more than that of clients, transaction unit is used; in the reverse case, connection unit is used. The default value is **AUTO**. #### MAX_NUM_DELAYED_HOSTS_LOOKUP See *MAX_NUM_DELAYED_HOSTS_LOOKUP* for further information. #### PREFERRED_HOSTS **PREFERRED_HOSTS** is a parameter to specify the order of a host to which a CAS tries to connect in a first priority. If the connection is failed after trying connection in the order specified in **PREFERRED_HOSTS**, a CAS tries to connect to the one of hosts specified in **$CORADB_DATABASES/databases.txt**. The default value is **NULL**. For details, see *coradb_broker.conf*. #### RECONNECT_TIME If the time specified by **RECONNECT_TIME** is elapsed in a certain status, CAS will try to reconnect to the other DB server. The default of this parameter is **600s(10min)**. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, s will be applied. a certain status which CAS tries to reconnect is as follows. - When CAS is connected to not a DB server in **PREFERRED_HOSTS**, but the DB server of db-host in databases.txt. When **RECONNECT_TIME** is 0, CAS does not try to reconnect. The default is **OFF**. > **Note:** > ### Broker app. server(CAS) #### APPL_SERVER_MAX_SIZE **APPL_SERVER_MAX_SIZE** is a parameter to configure the maximum size of the process memory usage handled by CAS. You can set a unit as B, K, M or G, which stands for bytes, kilobytes(KB), megabytes(MB) or gigabytes(GB) respectively. If you omit the unit, M will be applied. Specifying this parameter makes transactions terminate (commit or rollback) only when it is executed by a user. In contrast to this, specifying **APPL_SERVER_MAX_SIZE_HARD_LIMIT** makes transactions forcibly terminate (rollback) and restart CAS. Note that the default values of Windows and Linux are different from each other. For 32-bit Windows, the default value is **40** MB; for 64-bit Windows, it is **80** MB. The maximum value is the same on Windows and Linux as 2,097,151 MB. When current process size exceeds the value of **APPL_SERVER_MAX_SIZE**, broker restarts the corresponding CAS. For Linux, the default value of **APPL_SERVER_MAX_SIZE** is **0**; CAS restarts in the following conditions. - **APPL_SERVER_MAX_SIZE** is zero or negative: At the point when current process size becomes twice as large as initial memory - **APPL_SERVER_MAX_SIZE** is positive: At the point when it exceeds the value specified in **APPL_SERVER_MAX_SIZE** > **Note:** > Be careful not to make the value too small because application servers may restart frequently and unexpectedly. In general, the value of **APPL_SERVER_MAX_SIZE_HARD_LIMIT** is greater than that of **APPL_SERVER_MAX_SIZE**. For details, see description of **APPL_SERVER_MAX_SIZE_HARD_LIMIT**. #### APPL_SERVER_MAX_SIZE_HARD_LIMIT **APPL_SERVER_MAX_SIZE_HARD_LIMIT** is a parameter to configure the maximum size of process memory usage handled by CAS. You can set a unit as B, K, M or G, which stands for bytes, kilobytes(KB), megabytes(MB) or gigabytes(GB) respectively. If you omit the unit, M will be applied. The default value is **1,024** (MB), and the maximum value is 2,097,151 (MB). Specifying this parameter makes transactions being processed forcibly terminate (rollback) and restart CAS. In contrast to this, specifying **APPL_SERVER_MAX_SIZE** makes transactions terminate only when it is executed by a user. > **Note:** > Be careful not to make the value too small because application servers may restart frequently and unexpectedly. When restarting CAS, **APPL_SERVER_MAX_SIZE** is specified to wait for normal termination of transactions although memory usage increases; **APPL_SERVER_MAX_SIZE_HARD_LIMIT** is specified to forcibly terminate transactions if memory usage exceeds the maximum value allowed. Therefore, in general, the value of **APPL_SERVER_MAX_SIZE_HARD_LIMIT** is greater than that of **APPL_SERVER_MAX_SIZE**. #### APPL_SERVER_PORT **APPL_SERVER_PORT** is a parameter to configure the connection port of CAS that communicates with application clients; it is used only in Windows. In Linux, the application clients and CAS use the UNIX domain socket for communication; therefore, **APPL_SERVER_PORT** is not used. The default value is determined by adding plus 1 to the **BROKER_PORT** parameter value. The number of ports used is the same as the number of CAS, starting from the specified port's number plus 1. For example, when the value of **BROKER_PORT** is 30,000 and the **APPL_SERVER_PORT** parameter value has been configured, and if the **MIN_NUM_APPL_SERVER** value is 5, five CASes uses the ports numbering between 30,001 and 30,005, respectively. The maximum number of CAS specified in the **MAX_NUM_APPL_SERVER** parameter in **coradb_broker_conf**; therefore, the maximum number of connection ports is also determined by the value of **MAX_NUM_APPL_SERVER** parameter. On the Windows system, if a firewall exists between an application and a CoraDB broker, the communication port specified in **BROKER_PORT** and **APPL_SERVER_PORT** must be opened. > **Note:** > For the **CORADB_TMP** environment variable that specifies the UNIX domain socket file path of **cora_master** and **cora_broker** processes, see [Configuring environment variables](https://www.coradb.ai/manual/env.html). #### APPL_SERVER_SHM_ID **APPL_SERVER_SHM_ID** is a parameter to configure the ID of shared memory used by CAS; the value must be unique within system. The default value is the same as the port value of the broker. #### AUTO_ADD_APPL_SERVER **AUTO_ADD_APPL_SERVER** is a parameter to configure whether CAS increase automatically to the value specified in **MAX_NUM_APPL_SERVER** in case of needed; the value will be either **ON** or **OFF** (default: **ON**). #### MAX_NUM_APPL_SERVER **MAX_NUM_APPL_SERVER** is a parameter to configure the maximum number of simultaneous connections allowed. The default value is **40**. #### MIN_NUM_APPL_SERVER **MIN_NUM_APPL_SERVER** is a parameter to configure the minimum number of CAS even if any request to connect the broker has not been made. The default value is **5**. #### TIME_TO_KILL **TIME_TO_KILL** is a parameter to configure the time to remove CAS in idle state among CAS added dynamically. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, s will be applied. The default value is **120** (seconds). An idle state is one in which the server is not involved in any jobs. If this state continues exceeding the value specified in **TIME_TO_KILL**, CAS is removed. The value configured in this parameter affects only CAS added dynamically, so it applies only when the **AUTO_ADD_APPL_SERVER** parameter is configured to **ON**. Note that times to add or remove CAS will be increased more if the **TIME_TO_KILL** value is so small. ### Transaction & query #### CCI_DEFAULT_AUTOCOMMIT **CCI_DEFAULT_AUTOCOMMIT** is a parameter to configure whether to make application implemented in CCI interface or CCI-based interface such as PHP, OLE DB, Perl, Python, and Ruby commit automatically. The default value is **ON**. This parameter does not affect applications implemented in JDBC. If the **CCI_DEFAULT_AUTOCOMMIT** parameter value is **OFF**, the broker application server (CAS) process is occupied until the transaction is terminated. Therefore, it is recommended to execute commit after completing fetch when executing the **SELECT** statement. #### LONG_QUERY_TIME **LONG_QUERY_TIME** is a parameter to configure execution time of query which is evaluated as long-duration query. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied. The default value is **60** (seconds) and the maximum value is 86,400(1 day). When you run a query and this query's running time takes more than the specified time, a value of LONG-Q, which is printed out from "coradb broker status" command, is increased 1; this SQL is written to SLOW log file ($CORADB/log/broker/sql_log/\*.slow.log) of CAS. See [SLOW_LOG](https://www.coradb.ai/manual/admin/config_broker.html#slow_log). This value can be valued in milliseconds with a decimal separator. For example, the value can be configured into 0.5 to configure 500 msec. Note that if a parameter value is configured to **0**, a long-duration query is not evaluated. #### LONG_TRANSACTION_TIME **LONG_TRANSACTION_TIME** is a parameter to configure execution time of query which is evaluated as long-duration transaction. The default value is **60** (seconds) and the maximum value is 86,400(1 day). This value can be valued in milliseconds with a decimal separator. For example, the value can be configured into 0.5 to configure 500 msec. Note that if a parameter value is configured to **0**, a long-duration transaction is not evaluated. #### MAX_PREPARED_STMT_COUNT **MAX_PREPARED_STMT_COUNT** is a parameter used to limit the number of prepared statements by user (application) access. The default value is **2,000** and the minimum value is 1. The problem in which prepared statement exceeding allowed memory is mistakenly generated by system can be prohibited by making users specify the parameter value. > **Note:** > When you want to change the value of **MAX_PREPARED_STMT_COUNT** dynamically by **broker_changer** command, this can be changed only when this is bigger than the existing value; this cannot be changed when this is smaller than the existing value. #### MAX_QUERY_TIMEOUT **MAX\_ QUERY_TIMEOUT** is a parameter to configure timeout value of query execution. When time exceeds a value specified in this parameter after starting query execution, the query being executed stops and rolls back. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied. The default value is **0** (seconds) and it means infinite waiting. The value range is available from 0 to 86,400 seconds(one day). The smallest value (except 0) between the **MAX_QUERY_TIMEOUT** value and query timeout value of an application is applied if query timeout is configured in an application. > **Note:** > See the [cci_connect_with_url](https://www.coradb.ai/manual/api/cciapi.html#cci_connect_with_url) and [cci_set_query_timeout](https://www.coradb.ai/manual/api/cciapi.html#cci_set_query_timeout) functions to configure query timeout of CCI applications. For configuring query timeout of JDBC applications, see the **setQueryTimeout** method. #### SESSION_TIMEOUT **SESSION_TIMEOUT** is a parameter to configure timeout value for the session of the broker. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied. The default value is **300** (seconds). If there is no response to the job request for the specified time period, session will be terminated. If a value exceeds the value specified in this parameter without any action taken after starting transaction, the connections are terminated. #### STATEMENT_POOLING **STATEMENT_POOLING** is a parameter to configure whether to use statement pool feature. The default value is **ON**. CoraDB closes all handles of prepared statement in the corresponding client sessions when transaction commit or rollback is made. If the value of **STATEMENT_POOLING** is set to **ON**, the handles are reusable because they are maintained in the pool. Therefore, in an environment where libraries, such as general applications reusing prepared statement or DBCP where statement pooling is implemented is applied, the default configuration (**ON**) should be maintained. If the prepared statement is executed after transaction commit or termination while **STATEMENT_POOLING** is set to **OFF**, the following message will be displayed. ``` text Caused by: coradb.jdbc.driver.CoraDBException: Attempt to access a closed Statement. ``` #### JDBC_CACHE **JDBC_CACHE** is a parameter to configure whether to use result-cache feature. The default value is **OFF**. If the parameter is **ON**, all of SELECT queries from JDBC is cached at client for life time which is configured by **JDBC_CACHE_LIFE_TIME** #### JDBC_CACHE_HINT_ONLY **JDBC_CACHE_HINT_ONLY** is a parameter to configure whether to use result-cache feature only by query hint /\*+ JDBC_CACHE \*/. It works as if the parameter is **ON** when the query hint is given. #### JDBC_CACHE_LIFE_TIME **JDBC_CACHE_HINT_ONLY** is a parameter to configure JDBC client's result-cache life time. The default value is 1000 (sec). For only cache life time, the result-cache is available. After the cache lifetime expired, the prior cached results are no more available and a new result is cached. The cache life time works only when the parameter **JDBC_CACHE** or **JDBC_CACHE_HINT_ONLY** is configured to "ON". **WARNING** **JDBC_CACHE**, **JDBC_CACHE_HINT_ONLY**, and **JDBC_CACHE_LIFE_TIME** parameters are meaningless when the system parameter both of **max_query_cache_entries** and **query_cache_size_in_pages** are not set to positive value. For result cache working, the SELECT query must include query hint /\*+ QUERY_CACHE \*/ together with these JDBC related parameter setting. #### TRIGGER_ACTION Turn on or off of the trigger's action about the broker which specified this parameter. Specify **ON** or **OFF** as a value; The default is **ON**. ### Logging #### ACCESS_LOG **ACCESS_LOG** is a parameter to configure whether to store the access log of the broker. The default value is **OFF**. The name of the access log file for the broker is *broker_name***.access** and the file is stored under **$CORADB/log/broker** directory. #### ACCESS_LOG_DIR **ACCESS_LOG_DIR** specifies the directory for broker access logging files(**ACCESS_LOG**) to be created. The default is **log/broker**. #### ACCESS_LOG_MAX_SIZE **ACCESS_LOG_MAX_SIZE** specifies the maximum size of broker access logging files(**ACCESS_LOG**); if a broker access logging file is bigger than a specified size, this file is backed up into the name of *broker_name***.access.***YYYYMMDDHHMISS*, then logging messages are written to the new file(`broker_name`.**access**). The default is 10M and the maximum is 2G. It can be dynamically changed during operating a broker. #### ERROR_LOG_DIR **ERROR_LOG_DIR** is a parameter to configure default directory in which error logs about broker is stored. The default value is **log/broker/error_log**. The log file name for the broker error is *broker\_ name_id.err*. #### LOG_DIR **LOG_DIR** is a parameter to configure the directory where SQL logs are stored. The default value is **log/broker/sql_log**. The file name of the SQL logs is *broker_name_id.sql.log*. #### SLOW_LOG **SLOW_LOG** is a parameter to configure whether to log. The default value is **ON**. If the value is **ON**, long transaction query which exceeds the time specified in **LONG_QUERY_TIME** or query where an error occurred is stored in the **SLOW SQL** log file. The name of file created is *broker_name_id.slow.log* and it is located under **SLOW_LOG_DIR**. #### SLOW_LOG_DIR **SLOW_LOG_DIR** is a parameter to configure the location of directory where the log file is generated. The default value is **log/broker/sql_log**. #### SQL_LOG **SQL_LOG** is a parameter to configure whether to leave logs for SQL statements processed by CAS when CAS handles requests from a client. The default value is **ON**. When this parameter is configured to **ON**, all logs are stored. The log file name becomes *broker_name_id.sql.log*. The file is created in the **log/broker/sql_log** directory under the installation directory. The parameter values are as follows: - **OFF** : Does not leave any logs. - **ERROR** : Stores logs for queries which occur an error. only queries where an error occurs. - **NOTICE** : Stores logs for the long-duration execution queries which exceeds the configured time/transaction, or leaves logs for queries which occur an error. - **TIMEOUT** : Stores logs for the long-duration execution queries which exceeds the configured time/transaction. - **ON** / **ALL** : Stores all logs. #### SQL_LOG_MAX_SIZE **SQL_LOG_MAX_SIZE** is a parameter to configure the maximum size of the SQL log file. You can set a unit as B, K, M or G, which stands for bytes, kilobytes(KB) or megabytes(MB) or gigabytes(GB) respectively. If you omit the unit, M will be applied. The default value is **10,000**\* (KB). - If the size of the SQL log file, which is created when the **SQL_LOG** parameter is configured to **ON**, reaches to the size configured by the parameter, *broker_name_id.sql.log.bak* is created. - If the size of the SLOW SQL log file, which is created when the **SLOW_LOG** parameter is configured to **ON**, reaches to the size configured by the parameter, *broker_name_id.slow.log.bak* is created. ### Etc #### MAX_STRING_LENGTH **MAX_STRING_LENGTH** is a parameter to configure the maximum string length for BIT, VARBIT, CHAR and VARCHAR data types. If the value is **-1**, which is the default value, the length defined in the database is used. If the value is **100**, the value acts like 100 being applied even when a certain attribute is defined as VARCHAR(1000). #### SERVICE **SERVICE** is a parameter to configure whether to run the broker. It can be either **ON** or **OFF**. The default value is **ON**. The broker can run only when this value is configured to **ON**. #### SSL **SSL** is a parameter to configure whether to apply packet encryption (**SSL**) to the broker. It can be either **ON** or **OFF**. The default value is **OFF**. When this value is configured to **ON**, packet encryption using **TLS** will be applied to the broker/CAS. > **Warning:** > When the broker is configured to do **TLS** (**SSL=ON**), clients such as **jdbc** client must connect in encryption mode, otherwise the connection request to the broker will be rejected. The opposite is also true. The connection request of SSL clients to the non-SSL broker will be rejected. #### SOURCE_ENV **SOURCE_ENV** is a parameter used to determine the file where the operating system variable for each broker is configured. The extension of the file must be **env**. All parameters specified in **coradb.conf** can also be configured by environment variables. For example, the **lock_timeout** parameter in **coradb.conf** can also be configured by the **CORADB_LOCK_TIMEOUT** environment variable. As another example, to block execution of DDL statements on broker1, you can configure **CORADB_BLOCK_DDL_STATEMENT** to 1 in the file specified by **SOURCE_ENV**. An environment variable, if exists, has priority over **coradb.conf**. The default value is **coradb.env**. --- # Error log, lock, logging and transaction parameters Source: https://www.coradb.ai/manual/admin/config_logging.html These parameters are set in **coradb.conf**. For how to set them, which ones can be changed while the server runs, and the full list of parameters, see [System parameters](https://www.coradb.ai/manual/admin/config.html). ## Error message-related parameters The following are parameters related to processing error messages recorded by CoraDB. The type and value range for each parameter are as follows: | Parameter name | Type | Default | |-----------------------------------|--------|----------------------------------| | [call_stack_dump_activation_list](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_activation_list) | string | DEFAULT | | [call_stack_dump_deactivation_list](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_deactivation_list) | string | NULL | | [call_stack_dump_on_error](https://www.coradb.ai/manual/admin/config_logging.html#call_stack_dump_on_error) | bool | no | | [error_log](https://www.coradb.ai/manual/admin/config_logging.html#error_log) | string | cora_client.err, cora_server.err | | [error_log_level](https://www.coradb.ai/manual/admin/config_logging.html#error_log_level) | string | NOTIFICATION | | [error_log_warning](https://www.coradb.ai/manual/admin/config_logging.html#error_log_warning) | bool | no | | [error_log_size](https://www.coradb.ai/manual/admin/config_logging.html#error_log_size) | int | 512M | ### call_stack_dump_activation_list **call_stack_dump_activation_list** is a parameter to configure a certain error number for which a call stack is to be dumped to a server error log (located in $CORADB/log/server directory) as an exception even when you configure that a call stack will not be dumped for any errors. Therefore, the **call_stack_dump_activation_list** parameter is effective only when **call_stack_dump_on_error=no**. If this value is not configured, the default value is "DEFAULT" keyword. This keyword includes below errors. "DEFAULT" keyword can be used together with other error numbers. | Error number | Error message | |--------------|-----------------------------------------------------------------------------------------------------------------------------| | -2 | Internal system failure: no more specific information is available. | | -7 | Trying to format disk volume xxx with an incorrect value xxx for number of pages. | | -13 | An I/O error occurred while reading page xxx of volume xxx. | | -14 | An I/O error occurred while writing page xxx of volume xxx. | | -17 | Internal error: fetching deallocated pageid xxx of volume xxx. | | -19 | Internal error: pageptr = xxx of page xxx of volume xxx is not fixed. | | -21 | Internal error: unknown sector xxx of volume xxx. | | -22 | Internal error: unknown page xxx of volume xxx. | | -45 | Slot xxx on page xxx of volume xxx is allocated to an anchored record. A new record cannot be inserted here. | | -46 | Internal error: slot xxx on page xxx of volume xxx is not allocated. | | -48 | Accessing deleted object xxxxxx. | | -50 | Internal error: relocation record of object xxxxxx may be corrupted. | | -51 | Internal error: object xxxxxx may be corrupted. | | -52 | Internal error: object overflow address xxxxxx may be corrupted. | | -76 | Your transaction (index xxx, xxx@xxxxxx. You are waiting for user(s) xxx to release the page lock. | | -78 | Internal error: an I/O error occurred while reading logical log page xxx (physical page xxx) of xxx. | | -79 | Internal error: an I/O error occurred while writing logical log page xxx (physical page xxx) of xxx. | | -81 | Internal error: logical log page xxx may be corrupted. | | -90 | Redo logging is always a page level logging operation. A data page pointer must be given as part of the address. | | -96 | Media recovery may be needed on volume xxx. | | -97 | Internal error: unable to find log page xxx in log archives. | | -313 | Object buffer underflow while reading. | | -314 | Object buffer overflow while writing. | | -407 | Unknown key xxx referenced in B+tree index {vfid: (xxx, xxx), rt_pgid: xxx, key_type: xxx}. | | -414 | Unknown class identifier: xxxxxx. | | -415 | Invalid class identifier: xxxxxx. | | -416 | Unknown representation identifier: xxx. | | -417 | Invalid representation identifier: xxx. | | -583 | Trying to allocate an invalid number (xxx) of pages. | | -603 | Internal Error: Sector/page table of file VFID xxx\|Xxx seems corrupted. | | -836 | LATCH ON PAGE(xxx\|xxx) TIMEDOUT | | -859 | LATCH ON PAGE(xxx\|xxx) ABORTED | | -890 | Partition failed. | | -891 | Appropriate partition does not exist. | | -976 | Internal error: Table size overflow (allocated size: xxx, accessed size: xxx) at file table page xxx\|xxx(volume xxx) | | -1075 | Descending index scan aborted because of lower priority on B+tree with index identifier: (vfid = (xxx, xxx), rt_pgid: xxx). | The following example shows how to make error numbers only -115 and -116, perform call-stack dump. ``` sql call_stack_dump_on_error= no call_stack_dump_activation_list=-115,-116 ``` The following example shows how to make error numbers -115, -116 and "DEFAULT" error numbers, perform call-stack dump. ``` sql call_stack_dump_on_error= no call_stack_dump_activation_list=-115,-116, DEFAULT ``` ### call_stack_dump_deactivation_list **call_stack_dump_deactivation_list** is a parameter to configure a certain error number for which a call stack is not to be dumped when you configure that a call stack will be dumped for any errors. Therefore, the **call_stack_dump_deactivation_list** parameter is effective only when **call_stack_dump_on_error** is set to **yes**. The following example shows how to configure the parameter so that call stacks will be dumped for any errors, except the ones whose numbers are -115 and -116. ``` sql call_stack_dump_on_error= yes call_stack_dump_deactivation_list=-115,-116 ``` ### call_stack_dump_on_error **call_stack_dump_on_error** is a parameter to configure whether or not to dump a call stack when an error occurs in the database server. If this parameter is set to **no**, a call stack for any errors is not dumped. If it is set to **yes**, a call stack for all errors is dumped. The default value is **no**. ### error_log **error_log** is a server/client parameter to configure the name of the error log file when an error occurs in the database server. The name of the error log file must be in the form of *\\_\\_\.err*. However, the naming rule of the error log file does not apply to errors for which the system cannot find the database server information. Therefore, error logs are recorded in the **coradb.err** file. The error log file **coradb.err** is stored in the **$CORADB/log/server** directory. ### error_log_level **error_log_level** is a server parameter to configure an error message to be stored based on severity. There are five different levels which range from **WARNING** (lowest level), to **FATAL** (highest level). The inclusion relation in messages is **FATAL** \< **ERROR** \< **SYNTAX** \< **NOTIFICATION** \< **WARNING**. The default is **NOTIFICATION**. If severity of error is **NOTIFICATION**, error messages with **NOTIFICATION**, **SYNTAX**, **ERROR** and **FATAL** levels are written to the log file. ### error_log_warning **error_log_warning** is a parameter to configure whether or not error messages with a severity level of **WARNING** are to be displayed. Its default value is **no**. For this reason, you must set **error_log_warning** to **yes** to store **WARNING** messages to an error log file. ### error_log_size **error_log_size** is a parameter to configure the maximum number of lines per an error log file. The default value is **512M**. If it reaches up to the specified number, the *\\_\\_\.err.bak* file is created. ## Concurrency/lock-related parameters The following are parameters related to concurrency control and locks of the database server. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |-------------------------------------|-------|---------|------------|---------| | [deadlock_detection_interval_in_secs](https://www.coradb.ai/manual/admin/config_logging.html#deadlock_detection_interval_in_secs) | float | 1.0 | 0.1 | | | [isolation_level](https://www.coradb.ai/manual/admin/config_logging.html#isolation_level) | int | 4 | 4 | 6 | | [lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#lock_escalation) | int | 100,000 | 5 | | | [lock_timeout](https://www.coradb.ai/manual/admin/config_logging.html#lock_timeout) | msec | -1(inf) | 0(no wait) | INT_MAX | | [rollback_on_lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#rollback_on_lock_escalation) | bool | no | | | ### deadlock_detection_interval_in_secs **deadlock_detection_interval_in_secs** is a parameter to configure the interval (in seconds) in which deadlocks are detected for stopped transactions. If a deadlock occurs, CoraDB resolves the problem by rolling back one of the transactions. The default value is 1 second and the minimum value is 0.1 second. This value is rounded up by 0.1 sec. unit. For example, if an input value is 0.12 seconds, the value is rounded up to 0.2 seconds. Note that deadlocks cannot be detected if the detection interval is too long. ### isolation_level **isolation_level** is a parameter to configure the isolation level of a transaction. The higher the isolation level, the less concurrency and the less interruption by other concurrent transactions. The **isolation_level** parameter can be configured to an integer value from 4 to 6, which represent isolation levels, or character strings. The default value is **READ COMMITTED**. For details about each isolation level and parameter values, see [Transaction isolation level](https://www.coradb.ai/manual/sql/transaction_isolation.html#transaction-isolation-level) and the following table. | Isolation level | isolation_level parameter value | |-----------------|-------------------------------------------------------------------------------------------| | SERIALIZABLE | "TRAN_SERIALIZABLE" or 6 | | REPEATABLE READ | "TRAN_REP_CLASS_REP_INSTANCE" or "TRAN_REP_READ" or 5 | | READ COMMITTED | "TRAN_REP_CLASS_COMMIT_INSTANCE" or "TRAN_READ_COMMITTED" or "TRAN_CURSOR_STABILITY" or 4 | - **TRAN_SERIALIZABLE** : This isolation level ensures the highest level of consistency. For details, see [SERIALIZABLE isolation level](https://www.coradb.ai/manual/sql/transaction_isolation.html#serializable-isolation-level). - **TRAN_REP_READ** : This isolation level can incur phantom read. For details, see [REPEATABLE READ isolation level](https://www.coradb.ai/manual/sql/transaction_isolation.html#repeatable-read-isolation-level). - **TRAN_READ_COMMITTED** : This isolation level can incur unrepeatable read. For details, see [READ COMMITTED isolation level](https://www.coradb.ai/manual/sql/transaction_isolation.html#read-committed-isolation-level). ### lock_escalation **lock_escalation** is a parameter to configure the maximum number of locks permitted before row level locking is extended to table level locking. The default value is **100,000**. If the value of the **lock_escalation** parameter is small, the overhead by memory lock management is small as well; however, the concurrency decreases. On the other hand, if the configured value is large, the overhead is large as well; however, the concurrency increases. ### lock_timeout **lock_timeout** is a client parameter to configure the lock waiting time. If the lock is not permitted within the specified time period, the given transaction is canceled, and an error message is returned. If the parameter is configured to **-1**, which is the default value, the waiting time is infinite until the lock is permitted. If it is configured to **0**, there is no waiting for locks. You can set a unit as s, min or h, which stands for seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied, and it is rounded up to seconds. For example, 1ms will be 1s, and 1001ms will be 2s. ### rollback_on_lock_escalation It specifies rolling back the transaction or not when the lock escalation occurs. The default is **no**. If this parameter is specified with **yes**, the error log is written without lock escalation on the lock-escalating time and this lock escalation request is failed with rolling back the transaction. If it is specified with **no**, the lock escalation is performed and the transaction is continued. When the lock escalation occurs, record locks are transformed into a table lock and lock-releasing time can take long, so other transaction's access to the table can be impossible. However, if you specify the value of **lock_escalation** parameter(it specifies the number of record locks occurring the lock escalation) bigger, the system can overuse the memory resource. ## Logging-related parameters The following are parameters related to logs used for database backup and restore. The types and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |---|---|---|---|---| | [adaptive_flush_control](https://www.coradb.ai/manual/admin/config_logging.html#adaptive_flush_control) | bool | yes | | | | [background_archiving](https://www.coradb.ai/manual/admin/config_logging.html#background_archiving) | bool | yes | | | | [checkpoint_every_size](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_every_size) | byte | 10,000 × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | 10 × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | | [checkpoint_interval](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_interval) | msec | 6min | 1min | 35,791,394min | | [checkpoint_sleep_msecs](https://www.coradb.ai/manual/admin/config_logging.html#checkpoint_sleep_msecs) | msec | 1 | 0 | | | [force_remove_log_archives](https://www.coradb.ai/manual/admin/config_logging.html#force_remove_log_archives) | bool | yes | | | | [log_buffer_size](https://www.coradb.ai/manual/admin/config_logging.html#log_buffer_size) | byte | 16k × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | 128 × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | INT_MAX × [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) | | [log_max_archives](https://www.coradb.ai/manual/admin/config_logging.html#log_max_archives) | int | INT_MAX | 0 | INT_MAX | | [log_trace_flush_time](https://www.coradb.ai/manual/admin/config_logging.html#log_trace_flush_time) | int | 0 | 0 | INT_MAX | | [max_flush_size_per_second](https://www.coradb.ai/manual/admin/config_logging.html#max_flush_size_per_second) | byte | 10,000 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 1 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | INT_MAX × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | [remove_log_archive_interval_in_secs](https://www.coradb.ai/manual/admin/config_logging.html#remove_log_archive_interval_in_secs) | sec | 0 | 0 | | | [sync_on_flush_size](https://www.coradb.ai/manual/admin/config_logging.html#sync_on_flush_size) | byte | 200 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 1 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | INT_MAX × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | [ddl_audit_log](https://www.coradb.ai/manual/admin/config_logging.html#ddl_audit_log) | bool | no | | | | [ddl_audit_log_size](https://www.coradb.ai/manual/admin/config_logging.html#ddl_audit_log_size) | byte | 10M | 10M | 2G | ### adaptive_flush_control **adaptive_flush_control** is a parameter used automatically to adjust the flush capacity at every 50 ms depending on the current status of the flushing operation. The default value is **yes**. That is, this capacity is increased if a large number of **INSERT** or **UPDATE** operations are concentrated at a certain point of time and the number of flushed pages reaches the **max_flush_size_per_second** parameter value; and is decreased otherwise. In the same way, you can distribute the I/O load by adjusting the flush capacity on a regular basis depending on the workload. ### background_archiving **background_archiving** is a parameter used to create temporary archive logs periodically at a specific time. It is useful when balancing disk I/O load which has been caused by archiving logs. The default is **yes**. ### checkpoint_every_size **checkpoint_every_size** is a parameter to configure checkpoint interval by log page. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is **10,000** \* [log_page_size](https://www.coradb.ai/manual/admin/config.html#lpg) (**156.25M** when log_page_size is 16K). You can distribute disk I/O overload at the checkpoint by specifying lower size in the **checkpoint_every_size** parameter, especially in the environment where **INSERT** / **UPDATE** are heavily loaded at a specific time. Checkpoint is a job to record every modified page in data buffers to database volumes (disk) at a specific point. Checkpoint can shrink a restore time after the database failure because this makes the transaction logs which have been generated previously than the checkpoint time needless when the restore is processed. However, an efficient checkpoint interval should be properly considered because this job can occur a lot of disk I/O. > **Note:** > There are three ways to run checkpoint in CoraDB. The following two ways are provided by the setting of coradb.conf. > > - **checkpoint_interval**: After the previous checkpoint is done, checkpoint is periodically processed at every time after the term of this parameter value. > - **checkpoint_every_size**: Checkpoint is periodically processed at every time after the transaction log size of this parameter value. > > If one condition on the above parameters is satisfied, checkpoint is processed. > > The following two ways are provided by a user's command. > > - If you run ";checkpoint" command in the corasql interpreter, which is run with a "DBA" user, checkpoint is processed. > > As a reference, if you run backup command during checkpoint, backup command is blocked until checkpoint is ended. ### checkpoint_interval **checkpoint_interval** is a parameter to configure execution period of checkpoint. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied, and it is rounded up to seconds. For example, 1ms will be 1s, and 1001ms will be 2s. The default value is **6min** and the minimum value is 1min. ### checkpoint_sleep_msecs **checkpoint_sleep_msecs** is a parameter to let the job which flushes a buffer's data into a disk process slowly. The default is **1** (millisecond). ### force_remove_log_archives **force_remove_log_archives** is a parameter to configure whether to allow the deletion of the files other than the recent log archive files whose number is specified by **log_max_archives**. The default value is **yes**. If the value is set to **yes**, the files will be deleted other than the recent log archive files for which the number is specified by **log_max_archives**. If it is set to **no**, the log archive files will not be deleted. Exceptionally. ### log_buffer_size **log_buffer_size** is a parameter to configure the size of log buffer to be cached in the memory. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is 16k \* [log_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**256M** when log_page_size is 16K). If the value of the **log_buffer_size** parameter is large, performance can be improved (due to the decrease in disk I/O) in an environment where transactions are long and numerous. Moreover, CoraDB Multiversion Concurrency Control system relies on log to access previous row versions and to vacuum invisible versions from database. It is recommended to configure an appropriate value considering the memory size and operations of the system where CoraDB is installed. - Required memory size = the size of log buffer (**log_buffer_size**) ### log_max_archives **log_max_archives** is a parameter to configure the maximum number of archive log files. The minimum value is 0 and default value is **INT_MAX** (2,147,483,647). Its operations can differ depending on the configuration of **force_remove_log_archives**. For example, when **log_max_archives** is 3 and **force_remove_log_archives** is **yes** in the coradb.conf file, the most recent three archive log files are recorded and when a fourth archiving log file is generated, the oldest archive log file is automatically deleted; the information about the deleted archive logs are recorded in the **\*\_lginf** file. However, if an active transaction still refers to an existing archive log file, the archive log file will not be deleted. That is, if a transaction starts at the point that the first archive log file is generated, and it is still active until the fifth archive log is generated, the first archive log file cannot be deleted. Also, if the information of archive logs is not applied to database volumes, these are not deleted. (Archive logs after which a checkpoint has occurred keep the information of modified pages of a data buffer; therefore, they are required to restore a database.) If you change the value of **log_max_archives** dynamically during database operation, changed value will be applied when a new log archive file is created. For example, if you change this value from 10 to 5, old 5 files will be deleted when a new log archive file is created. > **Note:** > ### log_trace_flush_time When the log flushing time takes more time than the time you set in this parameter, this event is recorded in the log of the database server. The example of written information is as below. ``` text 03/18/14 10:20:45.889 - LOG_FLUSH_THREAD_WAIT total flush count: 1 page(s) total flush time: 310 ms time waiting for log writer: 308 ms last log writer info time spent by log writer: 308 ms ``` - LOG_FLUSH_THREAD_WAIT: Event name - Total flush count: The number of flushed pages when the event occurs - Total flush time: Total spent time when the log is flushed - Time waiting for log writer: The time LFT(Log Flushing Thread) has been waiting for LWT(Log Writer Thread) - Last log writer info - client_name(pid)\> - Time spent by log writer: Time spend by LWT measured in LWT; in general, this value is the same as the value of "time waiting for log writer") ### max_flush_size_per_second **max_flush_size_per_second** is a parameter to configure the maximum flush capacity when the flushing operation is performed from a buffer to a disk. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is 10,000 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**156.25M** when db_page_size is 16K). That is, you can prevent concentration of I/O load at a certain point of time by configuring this parameter to control the maximum flush capacity per second. If a large number of **INSERT** or **UPDATE** operations are concentrated at a certain point of time, and the flush capacity reaches the maximum capacity set by this parameter, only log pages are flushed to the disk, and data pages are no longer flushed. Therefore, you must set an appropriate value for this parameter considering the workload of the service environment. ### remove_log_archive_interval_in_secs Archive logs which exceed the specified number in the **log_max_archives** are removed when checkpoint occurs. By the way, many archive logs can be removed at once frequently after being piled up when jobs such as data migration or big data batch processing are performed. If files are removed at once like these, I/O overhead of database server is rapidly risen; therefore, we need to decrease this burden. **remove_log_archive_interval_in_secs** parameter lets archive logs delete slowly to shrink this burden. The default is **0** (second). In the situations which jobs like big data batch processing occur frequently, it is recommended to set the deletion interval as a 60 seconds if the disk space is enough. ### sync_on_flush_size **sync_on_flush_size** is a parameter to configure the interval in pages between after data and log pages are flushed from buffer and before they are synchronized with FILE I/O of operating system. The default value is 200 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**3.125M** when db_page_size is 16K). That is, the CoraDB Server performs synchronization with the FILE I/O of the operating system whenever 200 pages have been flushed. This is also a parameter related to I/O load. ### ddl_audit_log **ddl_audit_log** is a parameter to turn on/off DDL logging facility. The default value is no. If this value is set to yes, all DDL executed will be logged into the logfile. The path of log files is $CORADB/log/ddl_audit, and refer to :doc:/admin/ddl_audit for each DDL AUDIT log file name and description of log files in detail. ### ddl_audit_log_size **ddl_audit_log_size** specifies the maximum size of the DDL AUDIT log file. If the ddl audit log file is larger than the specified size, that ddl audit log file is backed up with the name of .bak appended to the ddl audit log file, and new recording will be started with the file from the beginning of the file. You can set the size with a size unit as B, K, M, or G, which stand for bytes, kilobytes (KB), megabytes (MB), and gigabytes (GB) respectively. If you omit the size unit, bytes will be applied. The default is 10M, and it can be set up to 2G. ## Transaction processing-related parameters The following are parameters for improving transaction commit performance. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |--------------------------------|------|---------|-----|-----| | [async_commit](https://www.coradb.ai/manual/admin/config_logging.html#async_commit) | bool | no | | | | [group_commit_interval_in_msecs](https://www.coradb.ai/manual/admin/config_logging.html#group_commit_interval_in_msecs) | msec | 0 | 0 | | ### async_commit **async_commit** is a parameter used to activate the asynchronous commit functionality. If the parameter is set to **no**, which is the default value, the asynchronous commit is not performed; if it is set to **yes**, the asynchronous commit is executed. The asynchronous commit is a functionality that improves commit performance by completing the commit for the client before commit logs are flushed on the disk and having the log flush thread (LFT) perform log flushing in the background. Note that already committed transactions cannot be restored if a failure occurs on the database server before log flushing is performed. ### group_commit_interval_in_msecs **group_commit_interval_in_msecs** is a parameter to configure the interval (in milliseconds), at which the group commit is to be performed. If the parameter is configured to **0**, which is the default value, the group commit is not performed. The group commit is a functionality that improves commit performance by combining multiple commits that occurred in the specified time period into a group so that commit logs are flushed on the disk at once. --- # Utility, graph and other parameters Source: https://www.coradb.ai/manual/admin/config_other.html These parameters are set in **coradb.conf**. For how to set them, which ones can be changed while the server runs, and the full list of parameters, see [System parameters](https://www.coradb.ai/manual/admin/config.html). ## Utility-related parameters The following are parameters related to utilities used in CoraDB. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |------------------------------|------|---------|-----|-----| | [backup_volume_max_size_bytes](https://www.coradb.ai/manual/admin/config_other.html#backup_volume_max_size_bytes) | byte | 0 | 32K | | | [communication_histogram](https://www.coradb.ai/manual/admin/config_other.html#communication_histogram) | bool | no | | | | [compactdb_page_reclaim_only](https://www.coradb.ai/manual/admin/config_other.html#compactdb_page_reclaim_only) | int | 0 | | | | [corasql_history_num](https://www.coradb.ai/manual/admin/config_other.html#corasql_history_num) | int | 50 | 1 | 200 | ### backup_volume_max_size_bytes **backup_volume_max_size_bytes** is a parameter to configure the size of the backup volume file created by the **coradb backupdb** utility in byte unit. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is **0**, and the minimum value is 32K. If the parameter is configured to **0**, which is the default value, the created backup volume is not partitioned; if it is configured to a value greater than 0, the backup volume is partitioned as much as it is specified size. ### communication_histogram **communication_histogram** is a parameter associated with [Session commands](https://www.coradb.ai/manual/corasql.html#session-commands) "**;.h**" of the corasql interpreter and the default value is **no**. For details, see [Dumping corasql execution statistics information](https://www.coradb.ai/manual/corasql.html#corasql-execution-statistics). ### compactdb_page_reclaim_only **compactdb_page_reclaim_only** is a parameter to configure the **compactdb** utility, which compacts the storage of already deleted objects to reuse OIDs of the already assigned storage. Storage optimization with the **compactdb** utility can be divided into three steps. The optimization steps can be selected through the **compactdb_page_reclaim_only** parameter. If the parameter is configured to **0**, which is the default value, step 1, 2 and 3 are all performed, so the storage is optimized in data, table and file units. If it is configured to 1, step 1 is skipped to have the storage optimized in table and file units. If it is configured to 2, steps 1 and 2 are skipped to have the storage optimized only in file units. - Step 1: Optimizes the storage only in data unit. - Step 2: Optimizes the storage in table unit. - Step 3: Optimizes the storage in file (heap file) unit. ### corasql_history_num **corasql_history_num** is a parameter to configure the corasql interpreter and the number of SQL statements to be stored in the history of the corasql interpreter. The default value is **50**. ## Other parameters The following are other parameters. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |-------------------------------------|--------|------------------|--------------|-----------------------| | [access_ip_control](https://www.coradb.ai/manual/admin/config_other.html#access_ip_control) | bool | no | | | | [access_ip_control_file](https://www.coradb.ai/manual/admin/config_other.html#access_ip_control_file) | string | | | | | [agg_hash_respect_order](https://www.coradb.ai/manual/admin/config_other.html#agg_hash_respect_order) | bool | yes | | | | [auto_restart_server](https://www.coradb.ai/manual/admin/config_other.html#auto_restart_server) | bool | yes | | | | [enable_string_compression](https://www.coradb.ai/manual/admin/config_other.html#enable_string_compression) | bool | yes | | | | [index_scan_in_oid_order](https://www.coradb.ai/manual/admin/config_other.html#index_scan_in_oid_order) | bool | no | | | | [index_unfill_factor](https://www.coradb.ai/manual/admin/config_other.html#index_unfill_factor) | float | 0.05 | 0 | 0.5 | | [java_stored_procedure](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure) | bool | no | | | | [java_stored_procedure_port](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure_port) | int | 0 | 0 | 65535 | | [java_stored_procedure_jvm_options](https://www.coradb.ai/manual/admin/config_other.html#java_stored_procedure_jvm_options) | string | | | | | [multi_range_optimization_limit](https://www.coradb.ai/manual/admin/config_other.html#multi_range_optimization_limit) | int | 100 | 0 | 10,000 | | [optimizer_enable_merge_join](https://www.coradb.ai/manual/admin/config_other.html#optimizer_enable_merge_join) | bool | no | | | | [use_stat_estimation](https://www.coradb.ai/manual/admin/config_other.html#use_stat_estimation) | bool | no | | | | [pthread_scope_process](https://www.coradb.ai/manual/admin/config_other.html#pthread_scope_process) | bool | yes | | | | [server](https://www.coradb.ai/manual/admin/config_other.html#server) | string | | | | | [service](https://www.coradb.ai/manual/admin/config_other.html#service) | string | | | | | [session_state_timeout](https://www.coradb.ai/manual/admin/config_other.html#session_state_timeout) | sec | 21,600 (6 hours) | 60(1 minute) | 31,536,000 (1 year) | | [sort_limit_max_count](https://www.coradb.ai/manual/admin/config_other.html#sort_limit_max_count) | int | 1000 | 0 | INT_MAX | | [sql_trace_slow](https://www.coradb.ai/manual/admin/config_other.html#sql_trace_slow) | msec | -1(inf) | 0 | 86,400,000 (24 hours) | | [sql_trace_execution_plan](https://www.coradb.ai/manual/admin/config_other.html#sql_trace_execution_plan) | bool | no | | | | [use_orderby_sort_limit](https://www.coradb.ai/manual/admin/config_other.html#use_orderby_sort_limit) | bool | yes | | | | [data_buffer_neighbor_flush_pages](https://www.coradb.ai/manual/admin/config_other.html#data_buffer_neighbor_flush_pages) | int | 8 | 0 | 32 | | [data_buffer_neighbor_flush_nondirty](https://www.coradb.ai/manual/admin/config_other.html#data_buffer_neighbor_flush_nondirty) | bool | no | | | | [tde_keys_file_path](https://www.coradb.ai/manual/admin/config_other.html#tde_keys_file_path) | string | NULL | | | | [tde_default_algorithm](https://www.coradb.ai/manual/admin/config_other.html#tde_default_algorithm) | string | AES | | | ### access_ip_control **access_ip_control** is a parameter to configure whether to use feature limiting the IP addresses that allow server access. The default value is **no**. For details, see [Limiting database server access](https://www.coradb.ai/manual/admin/control_server.html#limiting-database-server-access). ### access_ip_control_file **access_ip_control_file** is a parameter to configure the file name in which the list of IP addresses allowed by servers is stored. If **access_ip_control** value is set to **yes**, database server allows the list of IP addresses only stored in the file specified by this parameter. For details, see [Limiting database server access](https://www.coradb.ai/manual/admin/control_server.html#limiting-database-server-access). ### agg_hash_respect_order **agg_hash_respect_order** is a parameter to configure whether the groups in an aggregate function will be returned ordered or not. The default is **yes**. As a reference, see [max_agg_hash_size](https://www.coradb.ai/manual/admin/config_resources.html#max_agg_hash_size). If all the groups (keys and accumulators) can fit into hash memory, then "agg_hash_respect_order=no" will skip sorting them before writing to output, so it is fair to assume that the order cannot be guaranteed in this case. However, when overflows occur, then a sort step must be performed and you will get the results in-order even with "agg_hash_respect_order=no". ### auto_restart_server **auto_restart_server** is a parameter to configure whether to restart the process when it stops due to fatal errors being occurred in database server process. If **auto_restart_server** value is set to **yes**, the server process automatically restarts when it has stopped due to errors; it does not restart in case it stops by following normal process (by using **STOP** command). ### enable_string_compression **enable_string_compression** is a parameter to configure whether string compression should be used when storing variable string type value into heap, index or list. If **enable_string_compression** value is set to **yes**, and the string is at least 255 bytes in size and the compressed string requires less size than original string, then the string is stored in compressed form. ### index_scan_in_oid_order **index_scan_in_oid_order** is a parameter to configure the result data to be retrieved in OID order after the index scan. If the parameter is set to **no**, which is the default value, results are retrieved in data order; if it is set to **yes**, they are retrieved in OID order. ### index_unfill_factor If there is no free space because index pages are full when the **INSERT** or **UPDATE** operation is executed after the first index is created, the split of index page nodes occurs. This substantially affects the performance by increasing the operation time. **index_unfill_factor** is a parameter to configure the percent of free space defined for each index page node when an index is created. The **index_unfill_factor** value is applied only when an index is created for the first time. The percent of free space defined for the page is not maintained dynamically. Its value ranges between 0 and 0.5. The default value is **0.05**. If an index is created without any free space for the index page node (**index_unfill_factor** is set to 0), the split of index page nodes occurs every time an additional insertion is made. This may degrade the performance. If the value of **index_unfill_factor** is large, a large amount of free space is available when an index is created. Therefore, better performance can be obtained because the split of index nodes does not occur for a relatively long period of time until the free space for the nodes is filled after the first index is created. If this value is small, the amount of free space for the nodes is small when an index is created. Therefore, it is likely that the index nodes are spilt by **INSERT** or **UPDATE** because free space for the index nodes is filled in a short period of time. ### java_stored_procedure **java_stored_procedure** is a parameter to configure whether to use Java stored procedures by running the Java Virtual Machine (JVM). If the parameter is set to **no**, which is the default value, JVM is not executed; if it is set to **yes**, JVM is executed so you can use Java stored procedures. Therefore, configure the parameter to yes if you plan to use Java stored procedures. ### java_stored_procedure_port **java_stored_procedure_port** is a parameter to configure the port number receiving a request that calls the java stored procedures from CAS. the value must be unique and smaller than 65,535. The default value of **java_stored_procedure_port** is **0** which means the port number is automatically allocated, typically from an ephemeral port range. The value configured in this parameter affects only **java_stored_procedure** is set to **yes**. Note that an error occurs if the parameter is configured in \[common\]. ``` text ..... [common] ..... # an error occurs. remove the following line. java_stored_procedure_port=4333 ..... [@testdb] ..... # the parameter is configured successfully for testdb java_stored_procedure_port=4334 ..... ``` ### java_stored_procedure_jvm_options **java_stored_procedure_jvm_options** is a parameter to configure Java Virtual Machine (JVM) and Java options on which Java stored procedures are executed. Each option string should be separated by spaces. For JVM options, there are three types of options; standard, non-standard and advanced options. non-standard and advanced options are not guaranteed to be supported on all VM implementations. The default is an empty string. If the parameter value configured in \[@\\], it overwrites the value specified in \[common\]. ``` text ..... [common] ..... java_stored_procedure_jvm_options="-Xms1024m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m" ..... [@testdb] ..... java_stored_procedure=yes # Note that -XX:PermSize=512m and -XX:MaxPermSize=512m will not be applied for testdb, Even though they specified in [common] section. java_stored_procedure_jvm_options="-Xms2048m -Xmx2048m" ..... ``` ### multi_range_optimization_limit If the number of rows specified by the **LIMIT** clause in the query, which has multiple ranges (col IN (?, ?, ... ,?)) and is available to use an index, is within the number specified in the **multi_range_optimization_limit** parameter, the optimization for the way of index sorting will be performed. The default value is **100**. For example, if a value for this parameter is set to 50, LIMIT 10 means that it is within the value specified by this parameter, so that the values that meet the conditions will be sorted to produce the result. If LIMIT is 60, it means that it exceeds the parameter configuration value, so that it gets and sorts out all values that meet the conditions. Depending on the setting value, the differences are made between collecting the result with on-the-fly sorting of the intermediate values and sorting the result values after collecting them, and the bigger value could make more unfavorable performance. ### optimizer_enable_merge_join **optimizer_enable_merge_join** is a parameter to specify whether to include sort merge join plan as a candidate of query plans or not. The default is **no**. Regarding sort merge join, see [Using SQL hint](https://www.coradb.ai/manual/sql/tuning_hints.html#using-sql-hint). ### use_stat_estimation **use_stat_estimation** is a parameter to specify whether to use the estimated information in calculating statistics or not. The default is no. The estimated information generated by the heap manager while processing DML is associated with the number of added objects. it is relatively accurate for the number of total objects, NOT for the number of distinct values. ### pthread_scope_process **pthread_scope_process** is a parameter to configure the contention scope of threads. It only applies to AIX systems. If the parameter is set to **no**, the contention scope becomes **PTHREAD_SCOPE_SYSTEM**; if it is set to **yes**, it becomes **PTHREAD_SCOPE_PROCESS**. The default value is **yes**. ### server **server** is a parameter used to register the name of database server process which will run automatically when CoraDB server starts. ### service **service** is a parameter to configure process that starts automatically when the CoraDB service starts. There are four types of processes: **server**, **broker**, **manager**. Three processes are usually registered as in **service=server,broker,manager**. - If the parameter is set to **server**, the database process specified by the **@server** parameter gets started. - If the parameter is set to **broker**, the broker process gets started. - If the parameter is set to **manager**, the manager process gets started. ### session_state_timeout **session_state_timeout** is a parameter used to define how long the CoraDB session data will be kept. The session data will be deleted when the driver terminates the connection or the session time expires. The session time will expire after the specified time if a client terminates abnormally. Custom variables defined by **SET** and **PREPARE** statements can be deleted by **DROP** / **DEALLOCATE** statements before session timeout. The default value is **21,600** seconds(6 hours), and this parameter's unit is second. ### sort_limit_max_count Regarding SORT-LIMIT optimization which can be applied when top-N rows are sorted by "ORDER BY ... LIMIT *N*" statement, this parameter specifies the LIMIT count to limit applying this optimization. When the value of *N* is smaller than a value of **sort_limit_max_count**, SORT-LIMIT optimization is applied. The default is 1000, the minimum is 0(which means that this optimization is disabled), and the maximum is INT_MAX. For more details, see [SORT-LIMIT optimization](https://www.coradb.ai/manual/sql/tuning_index_opt.html#sort-limit-optimization). ### sql_trace_slow **sql_trace_slow** is a parameter to configure the execution time of a query which will be judged as a long time execution. You can set a unit as ms, s, min or h, which stands for milliseconds, seconds, minutes or hours respectively. If you omit the unit, milliseconds(ms) will be applied. The default value is -1 and the maximum value is 86,400,000 msec (24 hour). -1 means that the infinite time, so any queries will not be judged as a long duration query. For details, see the below **sql_trace_execution_plan**. > **Note:** > The system parameter **sql_trace_slow** judges the query execution time based on the server, but the broker parameter **MAX_QUERY_TIMEOUT** judges the query execution time based on the broker. ### sql_trace_execution_plan **sql_trace_execution_plan** is a parameter to configure if the query plan of the long running query is written to the log or not. The default value is **no**. If it is set to yes, a long running SQL, a query plan and the output of coradb statdump command are written to the server error log file(located on $CORADB/log/server directory) and CAS log file(located on $CORADB/log/broker/sql_log directory) . If it is set to no, only a long running SQL is written to the server error log file and CAS log file, and this SQL is displayed when you execute **coradb statdump** command. For example, if you want to write the execution plan of the slow query to the log file, and specify the query which executes more than 5 seconds as the slow query, then configure the value of the **sql_trace_slow** parameter as 5000(ms) and configure the value of the **sql_trace_execution_plan** parameter as yes. But, on the server error log file, the related information is written only when the value of error_log_level is NOTIFICATION. ### use_orderby_sort_limit **use_orderby_sort_limit** is a parameter to configure whether to keep the intermediate result of sorting and merging process in the statement including the **ORDER BY ... LIMIT** *row_count* clause as many as *row_count*. If it is set to **yes**, you can decrease unnecessary comparing and merging processes because as many as intermediate results will be kept as the value of *row_count*. The default value is **yes**. ### vacuum_prefetch_log_mode **vacuum_prefetch_log_mode** is a parameter to configure the prefetch mode of log pages on behalf of vacuum. In mode 0, the vacuum master thread prefetch the required log pages in a shared buffer. In mode 1 (default), each vacuum worker prefetches the required log pages in its own buffer. Mode 0 also requires that **vacuum_prefetch_log_buffer_size** system parameter is configured, in mode 0 this parameter is ignored and each vacuum worker prefetches an entire vacuum log block (default 32 log pages). ### vacuum_prefetch_log_buffer_size **vacuum_prefetch_log_buffer_size** is a parameter to configure the log prefetch buffer size of vacuum (it is used only if **vacuum_prefetch_log_mode** is set to 0). ### data_buffer_neighbor_flush_pages **data_buffer_neighbor_flush_pages** is a parameter to control the number of neighbor pages to be flushed with background flush (victim candidates flushing). When is less or equal to 1, the neighbor flush feature is considered deactivated. ### data_buffer_neighbor_flush_nondirty **data_buffer_neighbor_flush_nondirty** is a parameter to control the flushing of non-dirty neighbor pages. When victim candidates pages are flushed, and neighbor flush is activated (**data_buffer_neighbor_flush_pages** is greater than 1), than single non-dirty pages which completes a chain of neighbor (dirty) pages are also flushed. ### tde_keys_file_path **tde_keys_file_path** is a parameter to configure the path of the key file for TDE. The key file's name is fixed as \\_keys, and the directory where the key file exists is designated. If this system parameter is not set, the key file is searched in the same location as the database volume. For a detailed description of the key file, see [File-based master key management](https://www.coradb.ai/manual/security.html#file-based-master-key-management). ### tde_default_algorithm **tde_default_algorithm** is a parameter that configures the default algorithm used when creating the TDE encryption table. Log and temporary data are always encrypted using the algorithm set with this parameter when they have to be encrypted. **AES** or **ARIA** can be set. For more information on encryption algorithms, refer to [Encryption algorithm](https://www.coradb.ai/manual/security.html#encryption-algorithm). ## Graph-related parameters The following are graph-related parameters for configuring graph database operations and performance. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |----------------------------------------|--------|---------|-----|-----| | [graph_query_rewrite_mode](https://www.coradb.ai/manual/admin/config_other.html#graph_query_rewrite_mode) | bool | no | | | | [graph_query_filter_mode](https://www.coradb.ai/manual/admin/config_other.html#graph_query_filter_mode) | string | NULL | | | | [concurrent_map_erase_threshold](https://www.coradb.ai/manual/admin/config_other.html#concurrent_map_erase_threshold) | float | 0.7 | 0.0 | 1.0 | | [graph_insert_dml_logging](https://www.coradb.ai/manual/admin/config_other.html#graph_insert_dml_logging) | bool | no | | | | [graph_deferred_load_threads](https://www.coradb.ai/manual/admin/config_other.html#graph_deferred_load_threads) | int | 0 | 0 | 128 | | [graph_edges_container_buckets_count](https://www.coradb.ai/manual/admin/config_other.html#graph_edges_container_buckets_count) | int | 1,009 | 37 | | | [graph_vertices_container_buckets_count](https://www.coradb.ai/manual/admin/config_other.html#graph_vertices_container_buckets_count) | int | 1,009 | 37 | | | [graph_use_dagger](https://www.coradb.ai/manual/admin/config_other.html#graph_use_dagger) | bool | yes | | | ### graph_query_rewrite_mode **graph_query_rewrite_mode** is a parameter to control whether graph query rewriting is enabled. When enabled, the system rewrites SELECT queries that use graph MATCH clauses to optimize them for graph operations. For example, queries like **SELECT a,b FROM MATCH ...** can be rewritten to **SELECT json_graph(a,b) FROM MATCH ...** to return results in a graph-optimized format. The default value is **no**. Set to **yes** to enable automatic query rewriting for graph queries. Only nodes and edges are allowed in SELECT clauses when this mode is enabled. ### graph_query_filter_mode **graph_query_filter_mode** is a parameter to determine which types of graph elements are included in query results. This parameter filters the output of graph queries to return only vertices, only edges, or both. The default value is **NULL** (equivalent to "all"). Valid values: - **null** or **"all"** - Output both vertices and edges - **"nodes"** or **"vertices"** - Output only vertices - **"edges"** - Output only edges Set to control the type of graph elements returned by queries. Useful for optimizing queries that only need specific types of graph elements. ### concurrent_map_erase_threshold **concurrent_map_erase_threshold** is a parameter to configure the threshold value for concurrent map erase operations in graph data structures. This parameter controls when the system triggers cleanup operations in concurrent hash maps used for storing graph objects. The value represents a ratio or percentage threshold. The default value is **0.7**. The allowable range is 0.0 to 1.0. Used internally by the in-memory objects container for managing concurrent access to graph data structures. Lower values trigger more frequent cleanup, while higher values allow more deleted entries to accumulate before cleanup. > **Note:** > This is a hidden parameter intended for internal tuning by advanced users or developers. ### graph_insert_dml_logging **graph_insert_dml_logging** is a parameter to control whether DML (Data Manipulation Language) operations for graph inserts are logged. When enabled, the system logs detailed information about INSERT operations on graph vertices and edges in the graph topology class. The default value is **no**. Enable for debugging or auditing graph insert operations. Keep disabled in production for better performance. > **Note:** > This parameter is fixed at startup and cannot be changed dynamically. ### graph_deferred_load_threads **graph_deferred_load_threads** is a parameter to specify the number of worker threads dedicated to deferred loading of graph data. Deferred loading allows graph elements to be loaded asynchronously, improving query response times for large graphs. When set to 0, deferred loading is disabled. The default value is **0**. The allowable range is 0 to 128. Set to a value greater than 0 to enable parallel deferred loading. The optimal value depends on your hardware (CPU cores) and workload. Start with a small value (e.g., 4-8) and tune based on performance metrics. ### graph_edges_container_buckets_count **graph_edges_container_buckets_count** is a parameter to configure the number of buckets in the hash table used for the edges container in shared graph structures. This affects the performance of edge lookups and insertions in the in-memory graph representation. The default value is **1,009**. The minimum value is **37**. Higher values reduce hash collisions but use more memory. The default (1,009) is a prime number optimized for balanced distribution. Increase for very large graphs with millions of edges. ### graph_vertices_container_buckets_count **graph_vertices_container_buckets_count** is a parameter to configure the number of buckets in the hash table used for the vertices container in shared graph structures. This affects the performance of vertex lookups and insertions in the in-memory graph representation. The default value is **1,009**. The minimum value is **37**. Higher values reduce hash collisions but use more memory. The default (1,009) is a prime number optimized for balanced distribution. Increase for very large graphs with millions of vertices. ### graph_use_dagger **graph_use_dagger** is a parameter to control whether to use the DAGGER algorithm for shortest path computations in graph queries. DAGGER is an optimized algorithm for finding shortest paths in graphs. The default value is **yes**. Keep enabled (yes) for optimal shortest path query performance. Disable only for debugging or comparison purposes. --- # Connection, memory, disk and thread parameters Source: https://www.coradb.ai/manual/admin/config_resources.html These parameters are set in **coradb.conf**. For how to set them, which ones can be changed while the server runs, and the full list of parameters, see [System parameters](https://www.coradb.ai/manual/admin/config.html). ## Connection-related parameters The following are parameters related to the database server. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |------------------|--------|---------|-----|-------| | [coradb_port_id](https://www.coradb.ai/manual/admin/config_resources.html#coradb_port_id) | int | 1,523 | 1 | | | [check_peer_alive](https://www.coradb.ai/manual/admin/config_resources.html#check_peer_alive) | string | both | | | | [db_hosts](https://www.coradb.ai/manual/admin/config_resources.html#db_hosts) | string | NULL | | | | [max_clients](https://www.coradb.ai/manual/admin/config_resources.html#max_clients) | int | 100 | 10 | 4,000 | | [tcp_keepalive](https://www.coradb.ai/manual/admin/config_resources.html#tcp_keepalive) | bool | yes | | | ### coradb_port_id **coradb_port_id** is a parameter to configure the port to be used by the master process. The default value is **1,523**. If the port 1,523 is already being used on the server where CoraDB is installed or it is blocked by a firewall, an error message, which means the master server is not connected because the master process cannot be running properly, is displayed. If such port conflict occurs, the administrator must change the value of **coradb_port_id** considering the server environment. ### check_peer_alive **check_peer_alive** is a parameter to decide whether you execute the function checking that the client/server processes work well. The default is **both**. The server process and the client process which connected with it wait each other's response. But if one of them cannot get the data for a long time(example: exceeding 5 sec), it will check or not if the other works well based on the configuration of check_peer_alive parameter. During this processes, if it is judged that the process doesn't work properly, it disconnect forcibly. The values and the working methods are as follows. - **both**: As the server process accesses to the client process by ECHO(7) port, it checks if the client process works well. The client process also does the same thing to the server process(The default value). - **server_only**: Only the server process checks whether the client process works well. - **client_only**: Only the client process checks whether the server process works well. - **none**: None of the server and client processes check whether the other process works well. Specially, if ECHO(7) port is blocked by the firewall configuration, each process can mistake that the other process was exited. Therefore, you should avoid this problem by setting this parameter's value as none. ### db_hosts **db_hosts** is a parameter to configure a list of the database server hosts to which clients can connect, and the connection order. The server host list consists of multiple server host names, and host names are separated by spaces or colons (:). Duplicate or non-existent names are ignored. The following example shows the values of the **db_hosts** parameter. In this example, connections are attempted in the order of **host1** \> **host2** \> **host3**. ``` text db_hosts="hosts1:hosts2:hosts3" ``` To connect to the server, the client first tries to connect to the specified server host referring to the database location file (**databases.txt**). If the connection fails, the client then tries to connect to the first one of the secondarily specified server hosts by referring to the value of the **db_hosts** parameter in the database configuration file (**coradb.conf**). ### max_clients **max_clients** is a parameter to configure the maximum number of clients (usually broker application processes (CAS)) which allow concurrent connections to the database server. The **max_clients** parameter refers to the number of concurrent transactions per database server process. The default value is **100**. To guarantee performance while increasing the number of concurrent users in CoraDB environment, you need to make the appropriate value of the **max_clients** (**coradb.conf**) parameter and the [MAX_NUM_APPL_SERVER](https://www.coradb.ai/manual/admin/config_broker.html#max_num_appl_server) (**coradb_broker.conf**) parameter. That is, you are required to configure the number of concurrent connections allowed by databases with the **max_clients** parameter. You should also configure the number of concurrent connections allowed by brokers with the **MAX_NUM_APPL_SERVER** parameter. For example, in the **coradb_broker.conf** file, two node of a broker where the **MAX_NUM_APPL_SERVER** value of \[%query_editor\] is 50 and the **MAX_NUM_APPL_SERVER** value of \[%BROKER1\] is 50 is trying to connect one database server, the concurrent connections (**max_clients** value) allowed by the database server can be configured as follows: Especially, the value must be greater than the sum specified in **MAX_NUM_APPL_SERVER** of every broker node which connects to the same database. Note that the memory usage is affected by the value specified in **max_clients**. That is, if the number of value is high, the memory usage will increase regardless of whether or not the clients actually access the database. > **Note:** > In Linux system, max_clients parameter is related to "ulimit -n" command, which specifies the maximum number of file descriptors which a process can use. File descriptor includes not only a file, but also a network socket. Therefore, the number of "ulimit -n" should be greater than the number of max_clients. ### tcp_keepalive **tcp_keepalive** is a parameter which specifies if you apply SO_KEEPALIVE option to TCP network protocol or not. The default is **yes**. ## Memory-related parameters The following are parameters related to the memory used by the database server or client. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |---|---|---|---|---| | [data_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#data_buffer_size) | byte | 32,768 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 1,024 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 2G(32bit), INT_MAX × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (64bit) | | [index_scan_oid_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#index_scan_oid_buffer_size) | byte | 4 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 0.05 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 16 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | | [max_agg_hash_size](https://www.coradb.ai/manual/admin/config_resources.html#max_agg_hash_size) | byte | 2,097,152(2M) | 32,768(32K) | 134,217,728(128MB) | | [max_hash_list_scan_size](https://www.coradb.ai/manual/admin/config_resources.html#max_hash_list_scan_size) | byte | 134,217,728 (128M) | 0 | 134,217,728 (128M) | | [sort_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#sort_buffer_size) | byte | 128 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 1 × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) | 2G(32bit), INT_MAX × [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (64bit) | | [temp_file_memory_size_in_pages](https://www.coradb.ai/manual/admin/config_resources.html#temp_file_memory_size_in_pages) | int | 4 | 0 | 20 | | [thread_stacksize](https://www.coradb.ai/manual/admin/config_resources.html#thread_stacksize) | byte | 1,048,576 | 65,536 | | ### data_buffer_size **data_buffer_size** is a parameter to configure the size of data buffer to be cached in the memory by the database server. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is 32,768 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**512M** when db_page_size is 16K), and the minimum value is 1,024 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**16M** when db_page_size is 16K). The maximum value in 64-bit CoraDB is INT_MAX \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg). Note that the maximum value in 32-bit CoraDB is **2G**. The greater the value of the **data_buffer_size** parameter, the more data pages to be cached in the buffer, thus providing the advantage of decreased disk I/O cost. However, if this parameter is too large, the buffer pool can be swapped out by the operating system because the system memory is excessively occupied. It is recommended to configure the **data_buffer_size** parameter in a way the required memory size is less than two-thirds of the system memory size. - Required memory size = data buffer size (**data_buffer_size**) ### index_scan_oid_buffer_size **index_scan_oid_buffer_size** is a parameter to configure the size of buffer where the OID list is to be temporarily stored during the index scan. You can set unit K, which stands for KB (kilobytes). If you omit the unit, bytes will be applied. The default value is 4 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**64K** when db_page_size is 16K), and the minimum value is 0.05 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (about **1K** when db_page_size is 16K). The size of the OID buffer tends to vary in proportion to the value of the **index_scan_oid_buffer_size** parameter and the page size set when the database was created. In addition, the bigger the size of such OID buffer, the more the index scan cost. You can set the value of the **index_scan_oid_buffer_size** by considering these factors. ### max_agg_hash_size **max_agg_hash_size** is a parameter to configure the maximum memory per transaction allocated for hashing the tuple groups in a query containing aggregation. The default is **2,097,152**(2M), the minimum size is 32,768(32K), and the maximum size is 134,217,728(128MB). If [NO_HASH_AGGREGATE](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-aggregate) hint is specified, hash aggregate evaluation will not be used. As a reference, see [agg_hash_respect_order](https://www.coradb.ai/manual/admin/config_other.html#agg_hash_respect_order). ### max_hash_list_scan_size **max_hash_list_scan_size** is a parameter to configure the maximum memory per transaction allocated for building hash table in a query containing subquerys. The default and maximum size is 128MB; the minimum is 0. If this parameter is set to 0 or If [NO_HASH_LIST_SCAN](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-list-scan) hint is specified, hash list scan will not be used. ### sort_buffer_size **sort_buffer_size** is a parameter to configure the size of buffer to be used when a query is processing sorting. The server assigns one sort buffer for each client's sorting-request, and releases the assigned buffer memory when sorting is complete. A sorting query includes not only SELECT sorting query, but also index-creating query. You can set a unit as B, K, M, G or T, which stand for bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The default value is 128 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**2M** when db_page_size is 16K), and the minimum value is 1 \* [db_page_size](https://www.coradb.ai/manual/admin/config.html#dpg) (**16K** when db_page_size is 16K). ### temp_file_memory_size_in_pages **temp_file_memory_size_in_pages** is a parameter to configure the number of buffer pages to cache temporary result of a query. The default value is **4** and the maximum value is 20. - Required memory size = the number of temporary memory buffer pages (**temp_file_memory_size_in_pages** \* **page size**) - The number of temporary memory buffer pages = the value of the **temp_file_memory_size_in_pages** parameter - Page size = the value of the page size specified by the **-s** option of the **coradb createdb** utility during the database creation The spaces to store the temporary result are as follows. - Cache buffer to store the temporary result (acquired by **temp_file_memory_size_in_pages** parameter) - Permanent volumes with the purpose of storing temporary data. - Temporary volumes If the previous space is exhausted, then the next space is used as the following order: Cache buffer for storing temporary result -\> Permanent volumes -\> Temporary volumes. ### thread_stacksize **thread_stacksize** is a parameter to configure the stack size of a thread. The default value is **1048576** bytes. The value of the **thread_stacksize** parameter must not exceed the stack size allowed by the operating system. ## Disk-related parameters The following are disk-related parameters for defining database volumes and storing files. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |-----------------------------|--------|---------|-----|--------| | [db_volume_size](https://www.coradb.ai/manual/admin/config_resources.html#db_volume_size) | byte | 512M | 0 | 20G | | [dont_reuse_heap_file](https://www.coradb.ai/manual/admin/config_resources.html#dont_reuse_heap_file) | bool | no | | | | [log_volume_size](https://www.coradb.ai/manual/admin/config_resources.html#log_volume_size) | byte | 512M | 20M | 4G | | [temp_file_max_size_in_pages](https://www.coradb.ai/manual/admin/config_resources.html#temp_file_max_size_in_pages) | int | -1 | | | | [temp_volume_path](https://www.coradb.ai/manual/admin/config_resources.html#temp_volume_path) | string | NULL | | | | [unfill_factor](https://www.coradb.ai/manual/admin/config_resources.html#unfill_factor) | float | 0.1 | 0.0 | 0.3 | | [volume_extension_path](https://www.coradb.ai/manual/admin/config_resources.html#volume_extension_path) | string | NULL | | | | [double_write_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#double_write_buffer_size) | byte | 2M | 0 | 32M | | [data_file_os_advise](https://www.coradb.ai/manual/admin/config_resources.html#data_file_os_advise) | int | 0 | 0 | 6 | | [max_values_unpaged_list](https://www.coradb.ai/manual/admin/config_resources.html#max_values_unpaged_list) | int | 2,048 | 0 | 32,768 | | [ro_data_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#ro_data_buffer_size) | byte | 512M | 0 | | | [ro_data_buffer_pages](https://www.coradb.ai/manual/admin/config_resources.html#ro_data_buffer_pages) | int | 32,768 | 0 | | ### db_volume_size **db_volume_size** is a parameter to configure the following values. You can set a unit as B, K, M, G or T, which stand for bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The default value is **512M**. - The default database volume size when **coradb createdb** and **coradb addvoldb** utility is used without **--db-volume-size** option. - The default size of volume that is added automatically when database is full. > **Note:** > The actual volume size will always be rounded up to a multiple of the size of 64 sectors. Sector size depends on page size, therefore 64 sectors size is 16M, 32M or 64M for page size 4k, 8k or 16k respectively. ### dont_reuse_heap_file **dont_reuse_heap_file** is a parameter to configure whether or not heap files, which are deleted when deleting the table (**DROP TABLE**), are to be reused when creating a new table (**CREATE TABLE**). If this parameter is set to no, the deleted heap files can be reused; if it is set to yes, the deleted heap files are not used when creating a new table. The default value is **no**. ### log_volume_size **log_volume_size** is a parameter to configure the default size of log volume file when the **coradb createdb** utility is used without **--log-volume-size** option. You can set a unit as B, K, M, G or T, which stand for bytes, kilobytes (KB), megabytes (MB), gigabytes (GB) and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The default value is **512M**. ### temp_file_max_size_in_pages **temp_file_max_size_in_pages** is a parameter to configure the maximum number of pages to which temporary volumes can be extended. By default, this value is **-1**, which means that temporary volumes can occupy an unlimited disk space. A positive value will set a limit to these values (exceeding it may show an error and cancel some big queries). If the parameter is configured to **0**, temporary volumes are not created automatically; the administrator must create permanent volumes with the purpose of storing temporary data by using the **coradb addvoldb** utility. For more details see [Temporary volume](https://www.coradb.ai/manual/intro.html#temporary-volume) ### temp_volume_path **temp_volume_path** is a parameter to configure the directory in which to create temporary volumes used for the execution of complex queries or sorting. The default value is the volume location configured during the database creation. ### unfill_factor **unfill_factor** is a parameter to configure the rate of disk space to be allocated in a heap page for data updates. The default value is **0.1**. That is, the rate of free space is configured to 10%. In principle, data in the table is inserted in physical order. However, if the size of the data increases due to updates and there is not enough space for storage in the given page, performance may degrade because updated data must be relocated to another page. To prevent such a problem, you can configure the rate of space for a heap page by using the **unfill_factor** parameter. The allowable maximum value is 0.3 (30%). In a database where data updates rarely occur, you can configure this parameter to 0.0 so that space will not be allocated in a heap page for data updates. If the value of the **unfill_factor** parameter is negative or greater than the maximum value, the default value (**0.1**) is used. ### volume_extension_path **volume_extension_path** is a parameter to configure the directory where automatically extended volumes are to be created. The default value is the volume location configured during the database creation. ### double_write_buffer_size **double_write_buffer_size** is a parameter to configure the memory and disk size of double writer buffer. Double write buffer protection against partial I/O writes can be disabled by setting this size to zero. By default, it is enabled and its size is 2M. ### data_file_os_advise **data_file_os_advise** is a UNIX-only parameter that may be used to boost I/O performance. The parameter value is converted into a *posix_fadvise()* flag (for details about the flags [see here](https://linux.die.net/man/2/posix_fadvise)). | Parameter value | posix_fadvise flag | |-----------------|-----------------------| | 0 | 0 | | 1 | POSIX_FADV_NORMAL | | 2 | POSIX_FADV_SEQUENTIAL | | 3 | POSIX_FADV_RANDOM | | 4 | POSIX_FADV_NOREUSE | | 5 | POSIX_FADV_WILLNEED | | 6 | POSIX_FADV_DONTNEED | > **Warning:** > Make sure posix_fadvise flags and how data is accessed are perfectly understood. The parameter can help improve performance but it can also degrade it if misused. In most scenarios it is best to use the default value. ### max_values_unpaged_list **max_values_unpaged_list** is a parameter to configure the maximum number of values that can be stored in an unpaged list during query execution. Unpaged lists are used for small result sets that can be kept entirely in memory without being paged to disk. When a list exceeds this threshold, it is converted to a paged list file. The default value is **2,048**. The maximum value is **32,768**. This parameter is used by the query executor and XASL generation to determine when to switch from in-memory lists to disk-based paged lists. Higher values keep more data in memory, improving performance for queries with moderately-sized result sets, but consume more memory. Lower values reduce memory usage but may cause more disk I/O. ### ro_data_buffer_size **ro_data_buffer_size** is a parameter to configure the size of the buffer pool for read-only data pages. This buffer is used to cache read-only data pages separately from the main data buffer, which can improve performance for read-intensive workloads. You can set a unit as B, K, M, G or T, which stand for bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) respectively. If you omit the unit, bytes will be applied. The default value is **512M** (equivalent to 32,768 pages with default page size). The parameter automatically validates that values are at least 1,024 bytes if non-zero. Set based on the size of your read-only data and available memory. Larger values improve read performance but consume more memory. Set to 0 to disable the read-only buffer. This parameter is preferred over **ro_data_buffer_pages** for specifying the buffer size using size units (e.g., ro_data_buffer_size=512M). ### ro_data_buffer_pages **ro_data_buffer_pages** is a parameter to configure the number of pages in the read-only data buffer pool. This is the legacy page-based specification of the read-only buffer size. The system internally converts this to bytes based on the page size. The default value is **32,768**. This parameter is deprecated and maintained for backward compatibility. It is recommended to use **ro_data_buffer_size** with size units instead of this parameter. ## Thread-related parameters Thread management can be configured by threads parameters. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |-----------------------------------|------|---------|-----|------| | [thread_connection_pooling](https://www.coradb.ai/manual/admin/config_resources.html#thread_connection_pooling) | bool | true | | | | [thread_connection_timeout_seconds](https://www.coradb.ai/manual/admin/config_resources.html#thread_connection_timeout_seconds) | int | 300 | -1 | 3600 | | [thread_worker_pooling](https://www.coradb.ai/manual/admin/config_resources.html#thread_worker_pooling) | bool | true | | | | [thread_worker_timeout_seconds](https://www.coradb.ai/manual/admin/config_resources.html#thread_worker_timeout_seconds) | int | 300 | -1 | 3600 | | [loaddb_worker_count](https://www.coradb.ai/manual/admin/config_resources.html#loaddb_worker_count) | bool | 8 | 2 | 64 | ### thread_connection_pooling If **thread_connection_pooling** parameter is true, all threads used for client connection management are pooled on server boot. ### thread_connection_timeout_seconds **thread_connection_timeout_seconds** is a parameter that configures wait time before stopping for threads handling connection management. After closing a connection, the thread will wait the value of the parameter expressed in seconds to be assigned a new connection. If no connection is assigned and the wait time expires, the thread stops. Another thread may be started the next time a connection comes. If parameter value is **-1**, threads never stop. They sleep until they are given a new assignment. ### thread_worker_pooling If **thread_worker_pooling** parameter is true, all threads used for client requests execution are pooled on server boot. ### thread_worker_timeout_seconds **thread_worker_timeout_seconds** is a parameter that configures wait time before stopping for threads handling client requests. After executing a request, the thread will wait the value of the parameter expressed in seconds to be assigned a request. If no client request is assigned and the wait time expires, the thread stops. Another thread may be started the next time a client request comes. If parameter value is **-1**, threads never stop. They sleep until they are given a new assignment. ### loaddb_worker_count **loaddb_worker_count** is a parameter that configures the maximum number of threads that can be dedicated for **loaddb** sessions. If a single **loaddb** session runs, it may use all threads. If multiple **loaddb** sessions run concurrently, the total number of threads of all sessions cannot exceed the parameter's value. --- # SQL statement, type, timezone and cache parameters Source: https://www.coradb.ai/manual/admin/config_sql.html These parameters are set in **coradb.conf**. For how to set them, which ones can be changed while the server runs, and the full list of parameters, see [System parameters](https://www.coradb.ai/manual/admin/config.html). ## Statement/type-related parameters The following are parameters related to SQL statements and data types supported by CoraDB. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |---------------------------------|--------|-----------|-------|------------| | [add_column_update_hard_default](https://www.coradb.ai/manual/admin/config_sql.html#add_column_update_hard_default) | bool | no | | | | [alter_table_change_type_strict](https://www.coradb.ai/manual/admin/config_sql.html#alter_table_change_type_strict) | bool | yes | | | | [allow_truncated_string](https://www.coradb.ai/manual/admin/config_sql.html#allow_truncated_string) | bool | no | | | | [ansi_quotes](https://www.coradb.ai/manual/admin/config_sql.html#ansi_quotes) | bool | yes | | | | [block_ddl_statement](https://www.coradb.ai/manual/admin/config_sql.html#block_ddl_statement) | bool | no | | | | [block_nowhere_statement](https://www.coradb.ai/manual/admin/config_sql.html#block_nowhere_statement) | bool | no | | | | [compat_numeric_division_scale](https://www.coradb.ai/manual/admin/config_sql.html#compat_numeric_division_scale) | bool | no | | | | [create_table_reuseoid](https://www.coradb.ai/manual/admin/config_sql.html#create_table_reuseoid) | bool | yes | | | | [cte_max_recursions](https://www.coradb.ai/manual/admin/config_sql.html#cte_max_recursions) | int | 2,000 | 2 | 1,000,000 | | [default_week_format](https://www.coradb.ai/manual/admin/config_sql.html#default_week_format) | int | 0 | | | | [group_concat_max_len](https://www.coradb.ai/manual/admin/config_sql.html#group_concat_max_len) | byte | 1,024 | 4 | 33,554,432 | | [intl_check_input_string](https://www.coradb.ai/manual/admin/config_sql.html#intl_check_input_string) | bool | no | | | | [intl_collation](https://www.coradb.ai/manual/admin/config_sql.html#intl_collation) | string | | | | | [intl_date_lang](https://www.coradb.ai/manual/admin/config_sql.html#intl_date_lang) | string | | | | | [intl_number_lang](https://www.coradb.ai/manual/admin/config_sql.html#intl_number_lang) | string | | | | | [json_max_array_idx](https://www.coradb.ai/manual/admin/config_sql.html#json_max_array_idx) | int | 65,536 | 1,024 | 1,048,576 | | [no_backslash_escapes](https://www.coradb.ai/manual/admin/config_sql.html#no_backslash_escapes) | bool | yes | | | | [only_full_group_by](https://www.coradb.ai/manual/admin/config_sql.html#only_full_group_by) | bool | no | | | | [oracle_style_empty_string](https://www.coradb.ai/manual/admin/config_sql.html#oracle_style_empty_string) | bool | no | | | | [pipes_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#pipes_as_concat) | bool | yes | | | | [plus_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#plus_as_concat) | bool | yes | | | | [require_like_escape_character](https://www.coradb.ai/manual/admin/config_sql.html#require_like_escape_character) | bool | no | | | | [return_null_on_function_errors](https://www.coradb.ai/manual/admin/config_sql.html#return_null_on_function_errors) | bool | no | | | | [string_max_size_bytes](https://www.coradb.ai/manual/admin/config_sql.html#string_max_size_bytes) | byte | 1,048,576 | 64 | 33,554,432 | | [unicode_input_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_input_normalization) | bool | no | | | | [unicode_output_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_output_normalization) | bool | no | | | | [update_use_attribute_references](https://www.coradb.ai/manual/admin/config_sql.html#update_use_attribute_references) | bool | no | | | ### add_column_update_hard_default **add_column_update_hard_default** is a parameter to configure whether or not to provide the hard default value as the input value for a column when you add a new column to the **ALTER TABLE ... ADD COLUMN** clause. When there is **NOT NULL** constraint and no **DEFAULT** constraint, if a value of this parameter is set to **yes**, the value of newly added column will be inserted as hard default value; if it is set to **no**, CoraDB returns an error. For the hard default for each type, see the [CHANGE/MODIFY clauses](https://www.coradb.ai/manual/sql/schema/table_stmt.html#changemodify-clauses) of the **ALTER TABLE** statement. ``` sql SET SYSTEM PARAMETERS 'add_column_update_hard_default=yes'; CREATE TABLE tbl (i int); INSERT INTO tbl VALUES (1),(2); ALTER TABLE tbl ADD COLUMN j INT NOT NULL; SELECT * FROM tbl; ``` ``` text i j ========================= 1 0 2 0 ``` ``` sql SET SYSTEM PARAMETERS 'add_column_update_hard_default=no'; CREATE TABLE tbl (i INT); INSERT INTO tbl VALUES (1),(2); ALTER TABLE tbl ADD COLUMN j INT NOT NULL; ``` ``` text ERROR: Cannot add NOT NULL constraint for attribute "j": there are existing NULL values for this attribute. ``` ### alter_table_change_type_strict **alter_table_change_type_strict** is a parameter to configure whether to allow the conversion of column values according to the type change, and the default value is **yes**. If a value for this parameter is set to **no**, the value may be changed when you change the column types or when you add **NOT NULL** constraints; if it is set to **yes**, the value does not change. For details, see CHANGE Clause in the [CHANGE/MODIFY clauses](https://www.coradb.ai/manual/sql/schema/table_stmt.html#changemodify-clauses). ### allow_truncated_string **allow_truncated_string** is a parameter to configure whether to allow the truncation of string values according to the string manipulation operations used in insert or update query, and the default value is **no**. If the value for this parameter is set to **no**, the string value is not allowed to be truncated when you do operation for any string related to insert or update query; however the string related to select query may be truncated regardless of this configuration. If it is set to **yes**, the string value may be truncated regardless of the type of (INSERT/UPDATE/SELECT) query. ### ansi_quotes **ansi_quotes** is a parameter used to enclose symbols and character string to handle identifiers. The default value is **yes**. If this parameter value is set to **yes**, double quotations are handled as identifier symbols and single quotations are handled as character string symbols. If it is set to **no**, both double and single quotations are handled as character string symbols. ### block_ddl_statement **block_ddl_statement** is a parameter used to limit the execution of DDL (Data Definition Language) statements by the client. If the parameter is set to **no**, the given client is allowed to execute DDL statements. If it is set to **yes**, the client is not permitted to execute DDL statements. The default value is **no**. ### block_nowhere_statement **block_nowhere_statement** is a parameter used to limit the execution of **UPDATE** / **DELETE** statements without a condition clause (**WHERE**) by the client. If the parameter is set to **no**, the given client is allowed to execute **UPDATE** / **DELETE** statements without a condition clause. If it is set to **yes**, the client is not permitted to execute **UPDATE** / **DELETE** statements without a condition clause. The default value is **no**. ### compat_numeric_division_scale **compat_numeric_division_scale** is a parameter to configure the scale to be displayed in the result (quotient) of a division operation. If the parameter is set to **no**, the scale of the quotient is 9, if it is set to **yes**, the scale is determined by that of the operand. The default value is **no**. ### create_table_reuseoid **create_table_reuseoid** is a parameter to specify whether to use the **REUSE_OID** or **DONT_REUSE_OID** option when creating a table without table option. If it is set to **yes**, the table is created with **REUSE_OID** option. The default value is **yes**. For detail, see [REUSE_OID](https://www.coradb.ai/manual/sql/schema/table_stmt.html#reuse_oid) and [DONT_REUSE_OID](https://www.coradb.ai/manual/sql/schema/table_stmt.html#dont_reuse_oid) . ### cte_max_recursions **cte_max_recursions** is a parameter to limit the maximum number of iterations when executing the recursive part of the CTE (Common Table Expressions) statement. This avoids infinite loop and potential issues produced by the size of temporary lists. ### default_week_format **default_week_format** is a parameter to configure default value for the *mode* attribute of the [WEEK](https://www.coradb.ai/manual/sql/function/datetime_fn.html#week) function. The default value is **0**. For details, see [WEEK](https://www.coradb.ai/manual/sql/function/datetime_fn.html#week). ### intl_check_input_string **intl_check_input_string** is a parameter to determine whether or not to check that string entered is correctly corresponded to character set used. The default value is **no**. If this value is **no** and character set is UTF-8 and incorrect data is enter which violate UTF-8 byte sequence, it can show abnormal behavior or database server and applications can be terminated abnormally. However, if it is guaranteed this problem does not happen, it has advantage in performance not to do it. UTF-8 and EUC-KR can be checked; ISO-8859-1 is one-byte encoding so it does not have to be checked because every byte is valid. ### group_concat_max_len **group_concat_max_len** is a parameter used to limit the return value size of the [GROUP_CONCAT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#group_concat) function. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is **1,024**. The minimum value is 4 and the maximum value is 33,554,432 bytes. This function is affected by **string_max_size_bytes** parameter; if the value of **group_concat_max_len** is greater than the value **string_max_size_bytes** and the result size of **GROUP_CONCAT** exceeds the value of **string_max_size_bytes**, an error occurs. ### intl_check_input_string **intl_check_input_string** is a parameter to determine whether or not to check that string entered is correctly corresponded to character set used. The default value is **no**. If this value is no and character set is UTF-8 and incorrect data is enter which violate UTF-8 byte sequence, it can show abnormal behavior or database server and applications can be terminated abnormally. However, if it is guaranteed this problem does not happen, it has advantage in performance not to do it. UTF-8 and EUC-KR can be checked; ISO-8859-1 is one-byte encoding so it does not have to be checked because every byte is valid. ### intl_collation **intl_collation** is a parameter which specifies a collation name about a specific application client. Specifying this parameter is the same as changing a collation of application client by using "SET NAMES" statement. Specifying a collation includes a charset. The following two statements behave the same. ``` sql SET NAMES utf8; SET SYSTEM PARAMETERS 'intl_collation=utf8_bin'; ``` For an available value of **intl_collation**, see [Collation](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-1). ### intl_date_lang **intl_date_lang** is a parameter used to input/output the values of **TIME**, **DATE**, **DATETIME**, and **TIMESTAMP**. If language name is omitted, it specifies a locale format of string of localized calendar (month, weekday, and AM/PM). The values allowed are as follows: Note that to use all values, locale library should be configured except built-in locale. For configuring locale, see [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html#locale-setting). | Language | Locale name of language | |------------|-------------------------| | English | en_US | | German | de_DE | | Spanish | es_ES | | French | fr_FR | | Italian | it_IT | | Japanese | ja_JP | | Cambodian | km_KH | | Korean | ko_KR | | Turkish | tr_TR | | Vietnamese | vi_VN | | Chinese | zh_CN | | Romanian | ro_RO | The function recognizing input string based on calendar format of specified language is as follows: - [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date) - [TO_TIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_time) - [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime) - [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp) - [STR_TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#str_to_date) The function outputting string based on calendar format of specified language is as follows: - [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) - [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) - [TIME_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#time_format) ### intl_number_lang **intl_number_lang** is a parameter used to specify locale applied when numeric format is assigned to input/output string in the function where a string is converted to number or number is converted to string. A delimiter and decimal symbol are used for numeric localization. In general, a comma and period are used; however, it can be changeable based on locale. For example, while number 1000.12 is written as 1,000.12 in most locale, it is written as 1.000,12 in tr_TR locale. The function recognizing input string based on calendar format of specified language is as follows: - [TO_NUMBER](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_number) The function outputting string based on calendar format of specified language is as follows: - [FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#format) - [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) ### json_max_array_idx **json_max_array_idx** is a parameter used by JSON functions to set a limit on the size of arrays after changes. If a very large index is fed to functions like **JSON_ARRAY_INSERT** by accident, the JSON document will occupy a lot of memory and disk space. Use this parameter to limit the risks. The limit is not applied to arrays generated by parsing strings. ### no_backslash_escapes **no_backslash_escapes** is a parameter to configure whether or not to use backslash (\\ as an escape character, and the default value is **yes**. If a value for this parameter is set to **no**, backslash (\\ will be used as an escape character; if it is set to **yes**, backslash (\\ will be used as a normal character. For example, if this value is set to **no**, "\n" means a newline character. For details, see [Escape special characters](https://www.coradb.ai/manual/sql/datatype_string.html#escape-special-characters). ### only_full_group_by **only_full_group_by** is a parameter to configure whether or not to use extended syntax about using **GROUP BY** statement. If this parameter value is set to **no**, an extended syntax is applied thus, a column that is not specified in the **GROUP BY** statement can be specified in the **SELECT** column list. If it is set to yes, a column that is only specified in the **GROUP BY** statement can be the **SELECT** column list. The default value is **no**. Therefore, specify the **only_full_group_by** parameter value to **yes** to execute queries by SQL standards. Because the extended syntax is not applied in this case, an error below is displayed. ``` text ERROR: Attributes exposed in aggregate queries must also appear in the group by clause. ``` ### oracle_style_empty_string **oracle_style_empty_string** is a parameter used to improve compatibility with other DBMS (Database Management Systems); it specifies to process empty string and **NULL** as the same value. The default is **no**. If the **oracle_style_empty_string** parameter is set to **no**, the character string is processed as a valid string; if it is set to **yes**, according to each function, the empty string is processed as **NULL** or **NULL** is processed as the empty string. > **Note:** > Other functions except below functions are not affected by **oracle_style_empty_string** parameter. > > - Functions processing an empty string and NULL into NULL when **oracle_style_empty_string=yes**. > - [ASCII](https://www.coradb.ai/manual/sql/function/string_fn.html#ascii) > - [CONCAT_WS](https://www.coradb.ai/manual/sql/function/string_fn.html#concat_ws) > - [ELT](https://www.coradb.ai/manual/sql/function/string_fn.html#elt) > - [FIELD](https://www.coradb.ai/manual/sql/function/string_fn.html#field) > - [FIND_IN_SET](https://www.coradb.ai/manual/sql/function/string_fn.html#find_in_set) > - [FROM_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#from_base64) > - [INSERT](https://www.coradb.ai/manual/sql/function/string_fn.html#insert) > - [INSTR](https://www.coradb.ai/manual/sql/function/string_fn.html#instr) > - [LOWER](https://www.coradb.ai/manual/sql/function/string_fn.html#fn-lower) > - [LEFT](https://www.coradb.ai/manual/sql/function/string_fn.html#left) > - [LOCATE](https://www.coradb.ai/manual/sql/function/string_fn.html#locate) > - [LPAD](https://www.coradb.ai/manual/sql/function/string_fn.html#lpad) > - [LTRIM](https://www.coradb.ai/manual/sql/function/string_fn.html#ltrim) > - [MID](https://www.coradb.ai/manual/sql/function/string_fn.html#mid) > - [POSITION](https://www.coradb.ai/manual/sql/function/string_fn.html#position) > - [REPEAT](https://www.coradb.ai/manual/sql/function/string_fn.html#repeat) > - [REVERSE](https://www.coradb.ai/manual/sql/function/string_fn.html#reverse) > - [RIGHT](https://www.coradb.ai/manual/sql/function/string_fn.html#right) > - [RPAD](https://www.coradb.ai/manual/sql/function/string_fn.html#rpad) > - [RTRIM](https://www.coradb.ai/manual/sql/function/string_fn.html#rtrim) > - [SPACE](https://www.coradb.ai/manual/sql/function/string_fn.html#space) > - [STRCMP](https://www.coradb.ai/manual/sql/function/string_fn.html#strcmp) > - [SUBSTR](https://www.coradb.ai/manual/sql/function/string_fn.html#substr) > - [SUBSTRING](https://www.coradb.ai/manual/sql/function/string_fn.html#substring) > - [SUBSTRING_INDEX](https://www.coradb.ai/manual/sql/function/string_fn.html#substring_index) > - [TO_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#to_base64) > - [TRANSLATE](https://www.coradb.ai/manual/sql/function/string_fn.html#translate) > - [TRIM](https://www.coradb.ai/manual/sql/function/string_fn.html#trim) > - [UPPER](https://www.coradb.ai/manual/sql/function/string_fn.html#fn-upper) > - Functions processing an empty string and NULL into an empty string when **oracle_style_empty_string=yes**. > - [CONCAT](https://www.coradb.ai/manual/sql/function/string_fn.html#concat) > - [REPLACE](https://www.coradb.ai/manual/sql/function/string_fn.html#replace) ### pipes_as_concat **pipes_as_concat** is a parameter to configure how to handle a double pipe symbol. The default value is **yes**. If this parameter value is set to **yes**, a double pipe symbol is handled as a concatenation operator if **no**, it is handled as the **OR** operator. ### plus_as_concat **plus_as_concat** is a parameter to configure the plus (+) operator, and the default value is **yes**. It is set in `coradb.conf`; it cannot be changed with **SET SYSTEM PARAMETERS**. If a value for this parameter is set to **yes**, the plus (+) operator will be interpreted as a concatenation operator; if it is set to **no**, the operator will be interpreted as a numeric operator. ``` sql -- plus_as_concat = yes SELECT '1'+'1'; ``` ``` text '1'+'1' ====================== '11' ``` ``` sql SELECT '1'+'a'; ``` ``` text '1'+'a' ====================== '1a' ``` ``` sql -- plus_as_concat = no SELECT '1'+'1'; ``` ``` text '1'+'1' ========================== 2.0 ``` ``` sql SELECT '1'+'a'; ``` ``` text ERROR: Cannot coerce 'a' to type double. ``` ### require_like_escape_character **require_like_escape_character** is parameter to configure whether or not to use an ESCAPE character in the **LIKE** clause, and the default value is **no**. If a value for this parameter is set to **yes** and a value for **no_backslash_escapes** is set to **no**, backslash (\\ will be used as an ESCAPE character in the strings of the LIKE clause, otherwise you should specify an ESCAPE character by using the **LIKE ... ESCAPE** clause. For details, see [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like). ### return_null_on_function_errors **return_null_on_function_errors** is a parameter used to define actions when errors occur in some SQL functions, and the default value is **no**. If a value for this parameter is set to **yes**, **NULL** is returned; if it is set to **no**, an error is returned when the error occurs in functions, and the related message is displayed. The following SQL functions are affected by this system parameter. **Date/time functions** - [ADDDATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-adddate) - [ADDTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#addtime) - [DATEDIFF](https://www.coradb.ai/manual/sql/function/datetime_fn.html#datediff) - [DAY](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-day) - [DAYOFMONTH](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-dayofmonth) - [DAYOFWEEK](https://www.coradb.ai/manual/sql/function/datetime_fn.html#dayofweek) - [DAYOFYEAR](https://www.coradb.ai/manual/sql/function/datetime_fn.html#dayofyear) - [FROM_DAYS](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_days) - [FROM_UNIXTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_unixtime) - [HOUR](https://www.coradb.ai/manual/sql/function/datetime_fn.html#hour) - [LAST_DAY](https://www.coradb.ai/manual/sql/function/datetime_fn.html#last_day) - [MAKEDATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#makedate) - [MAKETIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#maketime) - [MINUTE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#minute) - [MONTH](https://www.coradb.ai/manual/sql/function/datetime_fn.html#month) - [QUARTER](https://www.coradb.ai/manual/sql/function/datetime_fn.html#quarter) - [SEC_TO_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#sec_to_time) - [SECOND](https://www.coradb.ai/manual/sql/function/datetime_fn.html#second) - [TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#time) - [TIME_TO_SEC](https://www.coradb.ai/manual/sql/function/datetime_fn.html#time_to_sec) - [TIMEDIFF](https://www.coradb.ai/manual/sql/function/datetime_fn.html#timediff) - [TO_DAYS](https://www.coradb.ai/manual/sql/function/datetime_fn.html#to_days) - [WEEK](https://www.coradb.ai/manual/sql/function/datetime_fn.html#week) - [WEEKDAY](https://www.coradb.ai/manual/sql/function/datetime_fn.html#weekday) - [YEAR](https://www.coradb.ai/manual/sql/function/datetime_fn.html#year) **String functions** - [ASCII](https://www.coradb.ai/manual/sql/function/string_fn.html#ascii) - [BIN](https://www.coradb.ai/manual/sql/function/string_fn.html#bin) - [BIT_LENGTH](https://www.coradb.ai/manual/sql/function/string_fn.html#bit_length) - [CHR](https://www.coradb.ai/manual/sql/function/string_fn.html#chr) **Numeric functions** - [ABS](https://www.coradb.ai/manual/sql/function/numeric_fn.html#abs) - [ACOS](https://www.coradb.ai/manual/sql/function/numeric_fn.html#acos) - [ASIN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#asin) - [ATAN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#atan) - [ATAN2](https://www.coradb.ai/manual/sql/function/numeric_fn.html#atan2) - [CEIL](https://www.coradb.ai/manual/sql/function/numeric_fn.html#ceil) - [CONV](https://www.coradb.ai/manual/sql/function/numeric_fn.html#conv) - [COS](https://www.coradb.ai/manual/sql/function/numeric_fn.html#cos) - [COT](https://www.coradb.ai/manual/sql/function/numeric_fn.html#cot) - [DEGREES](https://www.coradb.ai/manual/sql/function/numeric_fn.html#degrees) - [EXP](https://www.coradb.ai/manual/sql/function/numeric_fn.html#exp) - [FLOOR](https://www.coradb.ai/manual/sql/function/numeric_fn.html#floor) - [LN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#fn-ln) - [LOG2](https://www.coradb.ai/manual/sql/function/numeric_fn.html#log2) - [LOG10](https://www.coradb.ai/manual/sql/function/numeric_fn.html#log10) - [MOD](https://www.coradb.ai/manual/sql/function/numeric_fn.html#mod) - [POW](https://www.coradb.ai/manual/sql/function/numeric_fn.html#fn-pow) - [RADIANS](https://www.coradb.ai/manual/sql/function/numeric_fn.html#radians) - [SIGN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#sign) - [SIN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#sin) - [SQRT](https://www.coradb.ai/manual/sql/function/numeric_fn.html#sqrt) - [TAN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#tan) - [TRUNC](https://www.coradb.ai/manual/sql/function/datetime_fn.html#trunc) - [WIDTH_BUCKET](https://www.coradb.ai/manual/sql/function/numeric_fn.html#width_bucket) ``` sql SET SYSTEM PARAMETERS 'return_null_on_function_errors=no'; SELECT YEAR('12:34:56'); ``` ``` text ERROR: Conversion error in time format. ``` ``` sql SET SYSTEM PARAMETERS 'return_null_on_function_errors=yes'; SELECT YEAR('12:34:56'); ``` ``` text year('12:34:56') ====================== NULL ``` ### string_max_size_bytes **string_max_size_bytes** is a parameter to define the maximum byte allowable in string functions or operators. You can set a unit as B, K, M, G or T, which stands for bytes, kilobytes(KB), megabytes(MB), gigabytes(GB) or terabytes(TB) respectively. If you omit the unit, bytes will be applied. The default value is **1,048,576**(1M). The minimum value is 64 and the maximum value is 33,554,432(32M). The functions and operators affected by this parameter are as follows: - [SPACE](https://www.coradb.ai/manual/sql/function/string_fn.html#space) - [CONCAT](https://www.coradb.ai/manual/sql/function/string_fn.html#concat) - [CONCAT_WS](https://www.coradb.ai/manual/sql/function/string_fn.html#concat_ws) - '**+**': Operand of string - [REPEAT](https://www.coradb.ai/manual/sql/function/string_fn.html#repeat) - [GROUP_CONCAT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#group_concat): This function is affected not only by **string_max_size_bytes** parameter, but also by **group_concat_max_len**. - [INSERT](https://www.coradb.ai/manual/sql/function/string_fn.html#insert) function ### unicode_input_normalization **unicode_input_normalization** is a parameter to determine whether or not to input unicode stored in system level or not. The default value is **no**. In general, unicode text can be stored in "fully composed" or "fully decomposed". When character 'Ä' has 00C4 (if it is encoded in UTF-8, it becomes 2 bytes of C3 84) which is only one code point. In "fully decomposed" mode, it has two code points/characters. It is 0041 (character "A") and 0308(COMBINING DIAERESIS). In case of UTF-8 encoding, it becomes 3 bytes of 41 CC 88. CoraDB can work with fully composed unicode. For clients which have fully decomposed texts, configure the value of **unicode_input_normalization** to yes so that it can be converted to fully composed mode; and then it can be reverted to fully decomposed mode. For normalization of unicode encapsulation of CoraDB, compatibility equivalence is not applied. In general, normalization of unicode is not possible to revert after composition, CoraDB supports revert for characters as many as possible, and it applies normalization of unicode encapsulation. The characteristics of CoraDB normalization are as follows: - In case of language specific, normalization does not depend on locale. If one or more locale can be used, this means every CAS/corasql process, not CoraDB server. The **unicode_input_normalization** system parameter determines whether composition of input codes by normalization in system level. The **unicode_output_normalization** system parameter determines whether composition of output codes by normalization in system level. - Collation and normalization does not have direct relationship. Even though the value of **unicode_input_normalization** is no, the string of extensible collation (utf8_de_exp, utf8_jap_exp, utf8_km_exp) is properly sorted fully decomposed mode, it is not intended; it is side-effect of UCA(Unicode Collation Algorithm). The extensible collation is implemented only with fully composed texts. - In CoraDB, composition and decomposition for normalization does not work separately. It is generally used when **unicode_input_normalization** and **unicode_output_normalization** are yes. In this case, codes entered from clients are stored in composed mode and output in decomposed mode. If the application client sends the decomposed text data into CoraDB, let CoraDB deal with the composed code, by setting **unicode_input_normalization** as **yes**. If the application client can deal with the decomposed text data only, let CoraDB always send the decomposed code, by setting **unicode_output_normalization** as **yes**. If the application client knows both of input and output, leave the setting **unicode_input_normalization** and **unicode_output_normalization** as **no**. For more details, see [An overview of globalization](https://www.coradb.ai/manual/sql/i18n.html). ### unicode_output_normalization **unicode_output_normalization** is a parameter to determine whether or not to output unicode stored in system level. The default value is **no**. For details, see the above **unicode_input_normalization** description. ### update_use_attribute_references **update_use_attribute_references** is a parameter whether a value X of a column to be updated in an **UPDATE** statement affects to another column's update which uses X. The default is **no**. The below result of an **UPDATE** statement is dependent on the value of **update_use_attribute_references** parameter. ``` sql CREATE TABLE tbl(a INT, b INT); INSERT INTO tbl values (10, NULL); UPDATE tbl SET a=1, b=a; ``` If this parameter's value is **yes**, the updated value of the column "b" will be "1" which is affected by "a=1". ``` sql SELECT * FROM tbl; ``` ``` text 1, 1 ``` If this parameter's value is **no**, the updated value of the column "b" will be "NULL", which is affected by the value of "a" stored in the record, not by "a=1". ``` sql SELECT * FROM tbl; ``` ``` text 1, NULL ``` ## Timezone parameter The following are the parameters related to timezone. The type and the value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |------------------------|--------|-----------------|-----|-----| | [server_timezone](https://www.coradb.ai/manual/admin/config_sql.html#server_timezone) | string | OS timezone | | | | [timezone](https://www.coradb.ai/manual/admin/config_sql.html#timezone) | string | server_timezone | | | | [tz_leap_second_support](https://www.coradb.ai/manual/admin/config_sql.html#tz_leap_second_support) | bool | no | | | ### timezone Specifies a timezone for a session. The default is a value of **server_timezone**. This value can be specified by a timezone offset (e.g. +01:00, +02) or a timezone region name (e.g. Asia/Seoul). This value can be changed during operating database. ### server_timezone Specifies a timezone for a server. The default is a OS timezone. To apply the changed value, database should be restarted. The timezone of operating system is read depending on the operating system and information found in operating system configuration files: - On Windows, the API tzset() function and tzname\[0\] variable are used to retrieve an Windows style timezone name. This name is translated into IANA/CoraDB style name using the CoraDB mapping data (the mapping file is %CORADB%\timezones\tzdata\windowsZones.xml). - On Linux, CoraDB attempts to read and parse the file "/etc/sysconfig/clock". If this file is not available, then the value of link "/etc/localtime" is read and used. - On AIX, the value of "TZ" operating system environment variable is used. On all operating systems, if the server_timezone is not specified, and the value for timezone from operating system cannot be read, then "Asia/Seoul" zone is used as server timezone. ### tz_leap_second_support Specifies to support a leap second or not as yes or no. The default is **no**. A leap second is a one-second adjustment that is occasionally applied to Coordinated Universal Time (UTC) in order to keep its time of day close to the mean solar time. To apply the changed value, database should be restarted. ## Query plan cache-related parameters The following are parameters related to the query plan cache functionality. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |-------------------------------|------|---------|-----|-----| | [max_plan_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_plan_cache_entries) | int | 1,000 | | | | [max_filter_pred_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_filter_pred_cache_entries) | int | 1,000 | | | ### max_plan_cache_entries **max_plan_cache_entries** is a parameter to configure the maximum number of query plans to be cached in the memory. If the **max_plan_cache_entries** parameter is configured to -1 or 0, generated query plans are not stored in the memory cache; if it is configured to an integer value equal to 0 or greater than 1, a specified number of query plans are cached in the memory. The following example shows how to cache up to 1,000 queries. ``` text max_plan_cache_entries=1000 ``` ### max_filter_pred_cache_entries **max_filter_pred_cache_entries** is a parameter used to specify the maximum number of filtered index expressions. The filtered index expressions are stored with them complied and can be immediately used in server. If it is not stored in cache, the process is required which filtered index expressions are fetched from database schema and interpreted. ## Query cache-related parameters The following are the parameters related to the query cache functionality. The type and value range for each parameter are as follows: | Parameter name | Type | Default | Min | Max | |---------------------------|------|---------|-----|---------| | [max_query_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_query_cache_entries) | int | 0 | 0 | INT_MAX | | [query_cache_size_in_pages](https://www.coradb.ai/manual/admin/config_sql.html#query_cache_size_in_pages) | int | 0 | 0 | INT_MAX | Both parameters are 0 by default, so the query cache is disabled. If either parameter is 0 or negative, the **QUERY_CACHE** hint has no effect; set both to positive values to enable it. ### max_query_cache_entries **max_query_cache_entries** is a parameter to configure the maximum number of query to be cached. When it is greater than 0 (and **query_cache_size_in_pages** is also greater than 0), up to that many query results are cached. The following example shows how to cache up to 500 queries. ``` text max_query_cache_entries=500 ``` ### query_cache_size_in_pages **query_cache_size_in_pages** is a parameter to configure the maximum page of result to be cached. When it is greater than 0 (and **max_query_cache_entries** is also greater than 0), cached results can use up to that many pages, stored as temporary files. The following example shows how to cache up to 4,000 pages. ``` text query_cache_size_in_pages=4000 ``` --- # Controlling CoraDB processes: coradb service, server, broker Source: https://www.coradb.ai/manual/admin/control.html CoraDB runs as several processes — the master, database servers, brokers with their CAS processes, the CoraDB Manager Server (CMS) and the Java SP server — all controlled with the **coradb** utility. This page gives the commands for each and describes the CoraDB service; the processes are described in detail on their own pages: [Database server](https://www.coradb.ai/manual/admin/control_server.html), [Broker](https://www.coradb.ai/manual/admin/control_broker.html), [CMS](https://www.coradb.ai/manual/admin/control_manager.html) and [Java SP server](https://www.coradb.ai/manual/admin/control_javasp.html). ## Controlling CoraDB service The following **coradb** utility syntax shows how to control services registered in the configuration file. One of the following can be specified in \. ``` bash coradb service : {start|stop|restart|status} ``` - start: start services. - stop: stop services. - restart: restart services. - status: check status. No additional options or arguments are required. ## Controlling database server The following **coradb** utility syntax shows how to control database server process. ``` bash coradb server [database_name] : {start|stop|restart|status} ``` One of the following can be specified in \: - start: start a database server process. - stop: stop a database server process. - restart: restart a database server process. - status: check status of a database server process. Every command can specify a database name (**\[database_name\]**) as an argument. If the database name is not specified, the **status** command displays the currently running database servers' information, and the commands except **status** refer to the database names in the **server** property of the **\[service\]** section of **coradb.conf**. ``` text # coradb.conf [service] ... server=e-commerce,testdb ... ``` ``` bash % coradb server start @ coradb server start: e-commerce This may take a long time depending on the amount of recovery works to do. CoraDB 1.0 ++ coradb server start: success @ coradb server start: testdb This may take a long time depending on the amount of recovery works to do. CoraDB 1.0 ++ coradb server start: success ``` ## Controlling broker The following **coradb** utility syntax shows how to control CoraDB broker process. ``` bash coradb broker : start |stop |restart |status [options] [broker_name_expr] |acl {status|reload} broker_name |on |off |reset broker_name |info ``` - start: start broker processes. - stop: stop broker processes. - restart: restart broker processes. - status: check status of broker processes. - acl: limit broker access. - on/off: enable/disable the specified broker. - reset: reset the connection to broker. - info: display the broker configuration information. ## Controlling CMS CMS runs on the database host and lets administration clients manage databases and brokers remotely. The following **coradb** utility syntax controls the CMS processes. ``` bash coradb manager : {start|stop|status} ``` - start: start CMS processes. - stop: stop CMS processes. - status: check the status of manager processes. ## Controlling CoraDB Java stored procedure server The following **coradb** utility syntax shows how to control CoraDB Java Stored Procedure server process. ``` bash coradb javasp [database_name] : {start|stop|restart|status} ``` One of the following can be specified in \: - start: start a Java Stored Procedure server process. - stop: stop a Java Stored Procedure server process. - restart: restart a Java Stored Procedure server process. - status: check status of a Java Stored Procedure server process. Every command can specify a database name (**\[database_name\]**) as an argument. If the database name is not specified, the command is executed by referring to the database names in the **server** property of the **\[service\]** section of **coradb.conf**. ``` text # coradb.conf [service] ... server=e-commerce,testdb ... ``` ``` bash % coradb javasp start @ coradb javasp start: e-commerce ++ coradb javasp start: success @ coradb javasp start: testdb ++ coradb javasp start: success ``` ## Registering services If you do not register any service, only master process is registered by default. It is convenient for you to view status of all related processes at a glance or start and stop the processes at once with the **coradb** **service** utility once it is registered as CoraDB service. - For details on CoraDB Java Stored Procedure server configuration, see [Configuring for CoraDB Java SP server](https://www.coradb.ai/manual/admin/control_javasp.html#configuring-for-coradb-java-sp-server). The following example shows how to register database server and broker as service in the **coradb.conf** file and enable databases ( *e-commerce* and *testdb* ) to start automatically at once when CoraDB server starts running. ``` text # coradb.conf ... [service] # The list of processes to be started automatically by 'coradb service start' command service=server,broker # The list of database servers in all by 'coradb service start' command. # This property is effective only when the above 'service' property contains 'server' or 'javasp' keyword. server=e-commerce,testdb ``` ## Starting services In Linux environment, you can enter the code below to start CoraDB after installation. If no server is registered in the configuration file, only master process (cora_master) runs by default. In the Windows environment, the code below is normally executed only if a user with system permission has logged in. An administrator or general user can start or stop the CoraDB server by clicking its icon on the taskbar tray. ``` bash % coradb service start @ coradb master start ++ coradb master start: success ``` The following message is returned if master process is already running. ``` bash % coradb service start @ coradb master start ++ coradb master is running. ``` The following message is returned if master process fails to run. The example shows that service fails to start due to conflicts of the **coradb_port_id** parameter value specified in the coradb.conf file. In such a case, you can resolve the problem by changing the port. If it fails to start even though no port is occupied by process, delete /tmp/CoraDB1523 file and then restart the process. ``` bash % coradb service start @ coradb master start cora_master: '/tmp/CoraDB1523' file for UNIX domain socket exist.... Operation not permitted ++ coradb master start: fail ``` After registering service as explained in [CoraDB services](https://www.coradb.ai/manual/admin/control.html#coradb-services), enter the code below to start the service. You can verify that database server process and broker as well as registered *e-commerce* and *testdb* are starting at once. ``` bash % coradb service start @ coradb master start ++ coradb master start: success @ coradb server start: e-commerce This may take a long time depending on the amount of restore works to do. CoraDB 1.0 ++ coradb server start: success @ coradb server start: testdb This may take a long time depending on the amount of recovery works to do. CoraDB 1.0 ++ coradb server start: success @ coradb broker start ++ coradb broker start: success ``` ## Stopping services Enter code below to stop CoraDB service. If no services are registered by a user, only master process stops and then restarts. ``` bash % coradb service stop @ coradb master stop ++ coradb master stop: success ``` Enter code below to stop registered CoraDB service. You can verify that server process, broker process, and master process as well as *e-commerce* and *testdb* stop at once. ``` bash % coradb service stop @ coradb server stop: e-commerce Server e-commerce notified of shutdown. This may take several minutes. Please wait. ++ coradb server stop: success @ coradb server stop: testdb Server testdb notified of shutdown. This may take several minutes. Please wait. ++ coradb server stop: success @ coradb broker stop ++ coradb broker stop: success @ coradb master stop ++ coradb master stop: success ``` ## Restarting services Enter code below to restart CoraDB service. If no services are registered by a user, only master process stops and then restarts. ``` bash % coradb service restart @ coradb master stop ++ coradb master stop: success @ coradb master start ++ coradb master start: success ``` Enter code below to restart registered CoraDB service. You can verify that server process, broker process, and master process as well as *e-commerce* and *testdb* stop and then restart at once. ``` bash % coradb service restart @ coradb server stop: e-commerce Server e-commerce notified of shutdown. This may take several minutes. Please wait. ++ coradb server stop: success @ coradb server stop: testdb Server testdb notified of shutdown. This may take several minutes. Please wait. ++ coradb server stop: success @ coradb broker stop ++ coradb broker stop: success @ coradb master stop ++ coradb master stop: success @ coradb master start ++ coradb master start: success @ coradb server start: e-commerce This may take a long time depending on the amount of recovery works to do. CoraDB 1.0 ++ coradb server start: success @ coradb server start: testdb This may take a long time depending on the amount of recovery works to do. CoraDB 1.0 ++ coradb server start: success @ coradb broker start ++ coradb broker start: success ``` ## Managing service status The following example shows how to check the status of master process and database server registered. ``` bash % coradb service status @ coradb master status ++ coradb master is running. @ coradb server status Server testdb (rel 1.0, pid 31059) Server e-commerce (rel 1.0, pid 30950) @ coradb broker status % query_editor ---------------------------------------- ID PID QPS LQS PSIZE STATUS ---------------------------------------- 1 15465 0 0 48032 IDLE 2 15466 0 0 48036 IDLE 3 15467 0 0 48036 IDLE 4 15468 0 0 48036 IDLE 5 15469 0 0 48032 IDLE % broker1 OFF @ coradb manager server status ++ coradb manager server is not running. ``` The following message is returned if master process has stopped. ``` bash % coradb service status @ coradb master status ++ coradb master is not running. ``` ## coradb utility logging CoraDB supports a logging feature about coradb utility's running result. **Logging contents** The following contents are written to the **\$CORADB/log/coradb_utility.log** file. - All commands through coradb utilities: only usage, version and parsing errors are not logged. - Execution results by coradb utilities: success/failure. - An error message when failure. **Log file size** A size of **coradb_utility.log** file is expanded by the size specified by **error_log_size** parameter in **coradb.conf**; if this size is enlarged as the specified size, it is backed up as the **coradb_utility.log.bak** file. **Log format** ``` text
__p__`. | | partition_type | VARCHAR(32) | `'HASH'`, `'RANGE'` or `'LIST'`. | | partition_expr | VARCHAR(2048) | Partitioning expression. | | partition_values | SEQUENCE | For a range partition, the lower and upper bound (**NULL** for **MINVALUE** and **MAXVALUE**); for a list partition, its values. | | comment | VARCHAR(1024) | Partition comment. | ```sql CREATE TABLE order_archive (id INT, order_date DATE, shipping_cost NUMERIC(10,2)) PARTITION BY RANGE (YEAR(order_date)) ( PARTITION before_2023 VALUES LESS THAN (2023), PARTITION before_2025 VALUES LESS THAN (2025), PARTITION after_2025 VALUES LESS THAN MAXVALUE ); SELECT partition_name, partition_class_name, partition_type, partition_expr, partition_values FROM db_partition WHERE class_name = 'order_archive' ORDER BY partition_name; ``` | partition_name | partition_class_name | partition_type | partition_expr | partition_values | |---|---|---|---|---| | after_2025 | order_archive\_\_p\_\_after_2025 | RANGE | year([order_date]) | {2025, NULL} | | before_2023 | order_archive\_\_p\_\_before_2023 | RANGE | year([order_date]) | {NULL, 2023} | | before_2025 | order_archive\_\_p\_\_before_2025 | RANGE | year([order_date]) | {2023, 2025} | See [Partitioning](https://www.coradb.ai/manual/sql/partition.html). ## DB_STORED_PROCEDURE Java stored functions and procedures. | Column | Type | Description | |---|---|---| | sp_name | VARCHAR(255) | Name. | | sp_type | VARCHAR(16) | `'FUNCTION'` or `'PROCEDURE'`. | | return_type | VARCHAR(16) | Return type; `'void'` for procedures, `'CURSOR'` for a cursor. | | arg_count | INTEGER | Number of arguments. | | lang | VARCHAR(16) | `'JAVA'`. | | target | VARCHAR(4096) | The Java method that is called. | | owner | VARCHAR(256) | Owner. | | comment | VARCHAR(1024) | Comment. | The stored functions of the current user: ```sql SELECT sp_name, target FROM db_stored_procedure WHERE sp_type = 'FUNCTION' AND owner = CURRENT_USER; ``` See [Java stored functions and procedures](https://www.coradb.ai/manual/sql/jsp.html). ## DB_STORED_PROCEDURE_ARGS Arguments of stored functions and procedures. | Column | Type | Description | |---|---|---| | sp_name | VARCHAR(255) | Name of the stored function or procedure. | | index_of | INTEGER | Position of the argument, from 0. | | arg_name | VARCHAR(256) | Argument name. | | data_type | VARCHAR(16) | Data type. | | mode | VARCHAR(6) | `'IN'`, `'OUT'` or `'INOUT'`. | | comment | VARCHAR(1024) | Argument comment. | The arguments of a stored procedure in order: ```sql SELECT index_of, arg_name, data_type, mode FROM db_stored_procedure_args WHERE sp_name = 'phone_info' ORDER BY index_of; ``` --- # Comments Source: https://www.coradb.ai/manual/sql/comment.html CoraDB ignores comments when it runs a statement. Three styles are available, and they can be mixed in one statement: | Style | Syntax | Extends | |---|---|---| | SQL | `-- comment` | To the end of the line | | C++ | `// comment` | To the end of the line | | C | `/* comment */` | To the closing `*/`, across lines if needed | ```sql SELECT name -- SQL-style comment FROM countries // C++-style comment WHERE /* C-style comment */ code = 'FRA'; ``` | name | |---| | France | A C-style comment can span several lines: ```sql /* Countries we ship to. Codes follow ISO 3166-1 alpha-3. */ SELECT code, name FROM countries; ``` C-style comments do not nest: the first `*/` ends the comment, whatever `/*` appeared before it. ## Hints A C-style comment that starts with a plus sign, `/*+ ... */`, is not ignored: it holds [optimizer hints](https://www.coradb.ai/manual/sql/tuning_hints.html#using-sql-hint) for the statement, such as `USE_IDX` or `ORDERED`. Write ordinary comments without the `+`. ```sql SELECT /*+ RECOMPILE */ COUNT(*) FROM orders WHERE order_date >= DATE'2025-12-01'; ``` ## See also - [Identifiers](https://www.coradb.ai/manual/sql/identifier.html) - [Using SQL hints](https://www.coradb.ai/manual/sql/tuning_hints.html#using-sql-hint) --- # Data types and implicit type conversion Source: https://www.coradb.ai/manual/sql/datatype.html CoraDB provides the following groups of data types. Each group is described on its own page. | Group | Types | Page | |---|---|---| | Numeric | SHORT/SMALLINT, INTEGER, BIGINT, NUMERIC/DECIMAL, FLOAT/REAL, DOUBLE | [Numeric types](https://www.coradb.ai/manual/sql/datatype_numeric.html) | | Date/time | DATE, TIME, TIMESTAMP, DATETIME, and the types WITH TIME ZONE / WITH LOCAL TIME ZONE | [Date/time types](https://www.coradb.ai/manual/sql/datatype_datetime.html) | | Strings | CHAR, VARCHAR/STRING, BIT, BIT VARYING, ENUM | [String types](https://www.coradb.ai/manual/sql/datatype_string.html) | | Large objects | BLOB, CLOB | [BLOB/CLOB types](https://www.coradb.ai/manual/sql/datatype_lob.html) | | Collections | SET, MULTISET, LIST/SEQUENCE | [Collection types](https://www.coradb.ai/manual/sql/datatype_collection.html) | | JSON | JSON | [JSON data type](https://www.coradb.ai/manual/sql/datatype_json.html) | | Graph | GRAPH_OBJECT, PATH | [Graph types](https://www.coradb.ai/manual/sql/datatype_graph.html) | To convert a value explicitly, use [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) or one of the other [type conversion functions](https://www.coradb.ai/manual/sql/function/typecast_fn.html). When an operation combines values of different types without a cast, CoraDB converts them as described below. ## Implicit type conversion An implicit type conversion is a conversion CoraDB applies on its own when an expression has a different type from the one the operation expects: a value assigned to a column, a function argument, or the operands of a comparison or arithmetic operator. General rules: - Collection types (**SET**, **MULTISET**, **LIST**/**SEQUENCE**) are never converted implicitly. Use **CAST**. - Converting **DATETIME** or **TIMESTAMP** (with or without time zone) to **DATE** or **TIME** drops part of the value. Converting **DATE** to **DATETIME** or **TIMESTAMP** sets the time to midnight (12:00:00 AM). - Values of the types with a time zone are stored as UTC. Converting them to a type without time zone, or the other way round, uses the session time zone. See [Date/time types](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types). - Converting a string or an exact numeric value to **FLOAT** or **DOUBLE** can lose precision: strings and exact types are decimal, floating-point types are binary. ### Conversion tables ✓ means that CoraDB converts the type in the row to the type in the column implicitly. An empty cell means that the conversion needs an explicit **CAST**, or is not possible. **Date/time targets** | From \ to | DATETIME | DATETIMELTZ | DATETIMETZ | DATE | TIME | TIMESTAMP | TIMESTAMPLTZ | TIMESTAMPTZ | |---|---|---|---|---|---|---|---|---| | **DATETIME** | — | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **DATETIMELTZ** | ✓ | — | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **DATETIMETZ** | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ | ✓ | | **DATE** | ✓ | ✓ | ✓ | — | | ✓ | ✓ | ✓ | | **TIME** | | | | | — | | | | | **TIMESTAMP** | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | | **TIMESTAMPLTZ** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | | **TIMESTAMPTZ** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | **DOUBLE** | | | | | ✓ | ✓ | ✓ | ✓ | | **FLOAT** | | | | | ✓ | ✓ | ✓ | ✓ | | **NUMERIC** | | | | | | ✓ | ✓ | ✓ | | **BIGINT** | | | | | ✓ | ✓ | ✓ | ✓ | | **INT** | | | | | ✓ | ✓ | ✓ | ✓ | | **SHORT** | | | | | ✓ | ✓ | ✓ | ✓ | | **BIT** | | | | | | | | | | **VARBIT** | | | | | | | | | | **CHAR** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **VARCHAR** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | **Numeric values converted to TIME or TIMESTAMP** - Integer and floating-point values can be converted to **TIME**. The number is taken as seconds, modulo 86,400 (one day): `CAST(90000 AS TIME)` is `01:00:00 AM`. **NUMERIC** values cannot be converted to **TIME**. - All numeric types, including **NUMERIC**, can be converted to **TIMESTAMP**, **TIMESTAMPLTZ** and **TIMESTAMPTZ**. The number is taken as seconds since 1970-01-01 00:00:00 UTC and cannot exceed 2,147,483,647. **Numeric, bit string and string targets** | From \ to | INT | SHORT | BIT | VARBIT | CHAR | VARCHAR | DOUBLE | FLOAT | NUMERIC | BIGINT | |---|---|---|---|---|---|---|---|---|---|---| | **DATETIME** | | | | | ✓ | ✓ | | | | | | **DATETIMELTZ** | | | | | ✓ | ✓ | | | | | | **DATETIMETZ** | | | | | ✓ | ✓ | | | | | | **DATE** | | | | | ✓ | ✓ | | | | | | **TIME** | | | | | ✓ | ✓ | | | | | | **TIMESTAMP** | | | | | ✓ | ✓ | | | | | | **TIMESTAMPLTZ** | | | | | ✓ | ✓ | | | | | | **TIMESTAMPTZ** | | | | | ✓ | ✓ | | | | | | **DOUBLE** | ✓ | ✓ | | | ✓ | ✓ | — | ✓ | ✓ | ✓ | | **FLOAT** | ✓ | ✓ | | | ✓ | ✓ | ✓ | — | ✓ | ✓ | | **NUMERIC** | ✓ | ✓ | | | ✓ | ✓ | ✓ | ✓ | — | ✓ | | **BIGINT** | ✓ | ✓ | | | ✓ | ✓ | ✓ | ✓ | ✓ | — | | **INT** | — | ✓ | | | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **SHORT** | ✓ | — | | | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **BIT** | | | — | ✓ | ✓ | ✓ | | | | | | **VARBIT** | | | ✓ | — | ✓ | ✓ | | | | | | **CHAR** | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ | ✓ | | **VARCHAR** | ✓ | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ | ✓ | ✓ | ### Conversion rules #### INSERT and UPDATE A value is converted to the type of the column it is assigned to, and rounded or rejected according to that type. Here a string is assigned to the **SHORT** column `units_in_stock` and to the **NUMERIC(10,2)** column `unit_price`: ```sql UPDATE product SET units_in_stock = '25', unit_price = '31.499' WHERE id = 1618; SELECT id, unit_price, units_in_stock FROM product WHERE id = 1618; ``` | id | unit_price | units_in_stock | |---|---|---| | 1618 | 31.50 | 25 | #### Functions When a function expects a given type and the argument can be converted to it, the argument is converted. **MOD** expects numbers, so the two strings are converted to **DOUBLE**: ```sql SELECT MOD('123', '2') AS m, TYPEOF(MOD('123', '2')) AS t; ``` | m | t | |---|---| | 1 | double | When a function accepts several types and receives a mix, all arguments are converted to the type with the highest priority in its group: - Date/time: **DATETIME** > **TIMESTAMP** > **DATE** > **TIME** - Approximate numeric: **DOUBLE** > **FLOAT** - Exact numeric: **NUMERIC** > **BIGINT** > **INT** > **SHORT** - String: **CHAR** > **VARCHAR** #### Comparison operations The operands of a comparison are converted as follows. | Operand 1 | Operand 2 | Conversion | Compared as | |---|---|---|---| | Numeric | Numeric | none | Number | | Numeric | String | Operand 2 to **DOUBLE** | Number | | Numeric | Date/time | Operand 1 to date/time | **TIME**/**TIMESTAMP** | | String | Numeric | Operand 1 to **DOUBLE** | Number | | String | String | none | string | | String | Date/time | Operand 1 to date/time | date/time | | Date/time | Numeric | Operand 2 to date/time | **TIME**/**TIMESTAMP** | | Date/time | String | Operand 2 to date/time | date/time | | Date/time | Date/time | To the type with the higher priority | date/time | For date/time and numeric operands, the [limits for numeric values converted to TIME or TIMESTAMP](https://www.coradb.ai/manual/sql/datatype.html#number-2-time) apply. **Exception: string column against a numeric or date/time value.** When operand 1 is a string *column* (or other non-constant expression) and operand 2 is a numeric or date/time *value* (a literal or a host variable), operand 2 is converted to a string and the comparison is a string comparison. The exception does not apply to the set operators (**IN**, **NOT IN**, **= ALL**, **= ANY**, **< ALL**, **< ANY**, **<= ALL**, **<= ANY**, **>= ALL**, **>= ANY**). Between a numeric value and a string literal, the string is converted to **DOUBLE**: ```sql SELECT ('2' <= 11) AS a, ('5' > 11) AS b, ('2010-01-01' < DATE'2010-02-02') AS c; ``` | a | b | c | |---|---|---| | 1 | 0 | 1 | An **INT** column compared with a string literal is compared as a number; 1,593 products have an ID below 1603.5: ```sql SELECT COUNT(*) AS n FROM product WHERE id < '1603.5'; ``` | n | |---| | 1593 | `city.postal_code` is a **STRING** column, so comparing it with numbers is a *string* comparison. `'10100'` and `'10785'` sort between `'1000'` and `'1100'`, while a numeric range would not include them: ```sql SELECT name, postal_code FROM city WHERE postal_code BETWEEN 1000 AND 1100 ORDER BY postal_code; ``` | name | postal_code | |---|---| | Buenos Aires | 1010 | | Torino | 10100 | | Berlin | 10785 | | Caracas | 1081 | The same happens with a numeric host variable, for example `WHERE postal_code BETWEEN ? AND ?` bound to 1000 and 1100. Compare a string column with a quoted string, or convert it explicitly, to get the comparison you intend. Comparing a **DATE** column with a string literal converts the string to a date, which is the usual way to filter on dates: ```sql SELECT COUNT(*) AS n FROM orders WHERE order_date >= '2025-12-01'; ``` | n | |---| | 95 | #### Range and set comparisons With the set operators the exception above does not apply, so a numeric column compared with a set of strings is compared numerically: ```sql SELECT id FROM orders WHERE id <= ALL {'3', '5'} ORDER BY id; ``` | id | |---| | 0 | | 1 | | 2 | | 3 | A string operand that cannot be converted to the other type raises an error. #### Arithmetic operations **Date/time operands.** When the operands of `-` are two different date/time types, the one with the lower priority is converted. Here the **DATE** is converted to **DATETIME**, so the result is in milliseconds: ```sql SELECT DATE'2002-01-01' - DATETIME'2001-02-02 12:00:00 AM' AS ms; ``` | ms | |---| | 28771200000 | **Numeric operands.** Operands of different numeric types are converted to the type with the higher priority. See [Coercion in expressions](https://www.coradb.ai/manual/sql/datatype_numeric.html#coercion-in-expressions). **Date/time and numeric operands.** With `+` or `-`, the numeric operand is converted to **BIGINT**, **INT** or **SHORT** and counts units of the date/time type: days for **DATE**, seconds for **TIME** and **TIMESTAMP**, milliseconds for **DATETIME**. **Date/time and string operands.** Only `+` and `-` are allowed. - With `+`, the string is converted to a **BIGINT** number of units (as above, fractions rounded) and the result has the date/time type. - With `-`, the string is converted to **DATETIME** (or to **TIME** when the other operand is a **TIME**) and the result is a **BIGINT** difference in milliseconds (seconds for **TIME**). ```sql SELECT DATE'2002-01-01' + '10' AS plus_days, DATE'2002-01-01' - '2001-01-01' AS diff_ms; ``` | plus_days | diff_ms | |---|---| | 2002-01-11 | 31536000000 | A string that is not a date/time cannot be subtracted: ```sql SELECT DATE'2002-01-01' - '10'; ``` ```text ERROR: Conversion error in timestamp format. ``` **Numeric and string operands.** The string is converted to **DOUBLE** and the result is **DOUBLE**: ```sql SELECT 4 + '5.2' AS a, TYPEOF(4 + '5.2') AS t; ``` | a | t | |---|---| | 9.2 | double | A string that looks like a date is *not* converted to a date in this case. Use a date literal instead: ```sql SELECT '2002-01-01' + 1; ``` ```text ERROR: Cannot coerce '2002-01-01' to type double. ``` ```sql SELECT DATE'2002-01-01' + 1 AS next_day; ``` | next_day | |---| | 2002-01-02 | **String operands.** `*`, `/` and `-` between two strings convert both to numbers and return a **DOUBLE**: ```sql SELECT '3' * '2' AS a, TYPEOF('3' * '2') AS t; ``` | a | t | |---|---| | 6 | double | `+` between two strings depends on the system parameter [plus_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#plus_as_concat): - `yes` (default): the strings are concatenated, so `'1' + '1'` is `'11'`. - `no`: if both strings can be converted to numbers they are added as **DOUBLE**, so `'1' + '1'` is `2`. ```sql SELECT '1' + '1' AS r; ``` | r | |---| | 11 | --- # Collection types: SET, MULTISET, LIST/SEQUENCE Source: https://www.coradb.ai/manual/sql/datatype_collection.html ## Collection types A collection column stores several values of the same element type in one column of one row. CoraDB has three collection types, which differ in how they treat duplicates and order: | Type | Duplicates | Order | Input | Stored | |---|---|---|---|---| | **SET** | Removed | Sorted | `{'c','c','c','b','b','a'}` | `{'a', 'b', 'c'}` | | **MULTISET** | Kept | Sorted | `{'c','c','c','b','b','a'}` | `{'a', 'b', 'b', 'c', 'c', 'c'}` | | **LIST** or **SEQUENCE** | Kept | As entered | `{'c','c','c','b','b','a'}` | `{'c', 'c', 'c', 'b', 'b', 'a'}` | A collection column is declared with the element type after the collection keyword, with or without parentheses: ```sql col_name SET VARCHAR(20) col_name MULTISET (VARCHAR(20)) col_name LIST SHORT col_name SEQUENCE (INT) ``` A collection value is written in braces, with the elements separated by commas: `{'running', 'shoes'}`, `{42, 40, 41}`. A literal in braces on its own is a **SEQUENCE**; it is converted to the column's type on **INSERT** or **UPDATE**, or with [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast): ```sql SELECT CAST({'c','c','c','b','b','a'} AS SET) AS s, CAST({'c','c','c','b','b','a'} AS MULTISET) AS m, CAST({'c','c','c','b','b','a'} AS LIST) AS l; ``` | s | m | l | |---|---|---| | {'a', 'b', 'c'} | {'a', 'b', 'b', 'c', 'c', 'c'} | {'c', 'c', 'c', 'b', 'b', 'a'} | **Restrictions** - Elements can be of any type except **BLOB** and **CLOB** (`Can not define 'set of clob' as a column type`). - A collection column cannot have a collation: `SET (STRING) COLLATE utf8_en_ci` is a syntax error. - A scalar value is not a collection: `INSERT INTO t VALUES ('')` into a **SET** column fails with `Casting '' to type set is not supported.` Write `{''}`. - Collections are never converted implicitly to other types. Use **CAST** between collection types. **Converting between collection types** Any collection type can be cast to any other. Converting to **SET** removes duplicates, and converting to **SET** or **MULTISET** sorts the elements. Converting a **SET** or **MULTISET** to **LIST** keeps the sorted order; the original input order of a **MULTISET** is not kept. ### Example The following table stores tags and available sizes for products of the e-commerce sample database: ```sql CREATE TABLE product_extra ( product_id INT PRIMARY KEY, tags SET VARCHAR(20), sizes LIST SHORT ); INSERT INTO product_extra VALUES (1618, {'running', 'shoes', 'running'}, {42, 40, 41, 40}); SELECT product_id, tags, sizes FROM product_extra; ``` | product_id | tags | sizes | |---|---|---| | 1618 | {'running', 'shoes'} | {42, 40, 41, 40} | The duplicate tag is removed by the **SET**; the **LIST** keeps the sizes as entered, duplicates included. Collections are queried with the containment operators, such as **IN** and **SUBSETEQ**, described in [Containment operators](https://www.coradb.ai/manual/sql/function/containment_op.html): ```sql SELECT product_id FROM product_extra WHERE 'shoes' IN tags; SELECT product_id FROM product_extra WHERE tags SUBSETEQ {'running', 'shoes', 'sale'}; ``` Both queries return product 1618. ### SET A **SET** holds distinct values, sorted. **NULL** and the empty string are values like any other: | Inserted into a **SET (CHAR(1))** column | Stored | |---|---| | `{'c','c','c','b','b','a'}` | `{'a', 'b', 'c'}` | | `{NULL}` | `{NULL}` | | `{''}` | `{' '}` (**CHAR(1)** pads the empty string to one space) | ### MULTISET A **MULTISET** keeps duplicates and sorts the elements. `{'c','c','c','b','b','a'}` is stored as `{'a', 'b', 'b', 'c', 'c', 'c'}`; cast to **SET** it is `{'a', 'b', 'c'}`. ### LIST/SEQUENCE A **LIST** (or **SEQUENCE**, the same type) keeps duplicates and the order in which the elements were entered. `{'c','c','c','b','b','a'}` is stored as is; cast to **SET** it is `{'a', 'b', 'c'}`, cast to **MULTISET** `{'a', 'b', 'b', 'c', 'c', 'c'}`. The [list functions](https://www.coradb.ai/manual/sql/function/list_fn.html) work on **LIST** values, and **TYPEOF** reports a **LIST** as `sequence`. --- # Date/time types: DATE, TIME, TIMESTAMP, DATETIME and time zones Source: https://www.coradb.ai/manual/sql/datatype_datetime.html ## Date/time types Date/time types store a date, a time of day, or both. CoraDB supports the following types: | Type | Bytes | Min | Max | Notes | |---|---|---|---|---| | **DATE** | 4 | 0001-01-01 | 9999-12-31 | | | **TIME** | 4 | 00:00:00 | 23:59:59 | | | **TIMESTAMP** | 4 | 1970-01-01 00:00:01 UTC | 2038-01-19 03:14:07 UTC | Stored as seconds since the Unix epoch, shown in the session time zone. | | **DATETIME** | 8 | 0001-01-01 00:00:00.000 | 9999-12-31 23:59:59.999 | Millisecond precision. | | **TIMESTAMPLTZ** | 4 | As **TIMESTAMP** | As **TIMESTAMP** | **TIMESTAMP WITH LOCAL TIME ZONE** | | **TIMESTAMPTZ** | 8 | As **TIMESTAMP** | As **TIMESTAMP** | **TIMESTAMP WITH TIME ZONE** | | **DATETIMELTZ** | 8 | 0001-01-01 00:00:00.000 UTC | 9999-12-31 23:59:59.999 UTC | **DATETIME WITH LOCAL TIME ZONE** | | **DATETIMETZ** | 12 | 0001-01-01 00:00:00.000 UTC | 9999-12-31 23:59:59.999 UTC | **DATETIME WITH TIME ZONE** | In the e-commerce sample database, `orders.order_date` and `orders.shipped_date` are **DATE** columns, and the `since` property of the graph edges (for example `likes.since`) is **DATETIME**. **Range and resolution** - Times use the 24-hour clock and dates follow the Gregorian calendar. A value that does not exist in either is rejected. - **TIMESTAMP** covers 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC. In a session at UTC+9 that is 1970-01-01 09:00:01 to 2038-01-19 12:14:07 local time. Use **DATETIME** for values outside this range or when you need milliseconds. - For the time zone types the limits apply to the value converted to UTC, so the local limits depend on the time zone. - **TIME** and **TIMESTAMP** have a resolution of one second, **DATE** of one day, **DATETIME** of one millisecond. Extra precision in the input is dropped. **Two-digit years** A two-digit year from 00 to 69 means 2000–2069, and 70 to 99 means 1970–1999. A year written with one, three or four digits is taken as is. ```sql SELECT DATE'00-10-31' AS a, DATE'70-10-31' AS b, DATE'0070-10-31' AS c; ``` | a | b | c | |---|---|---| | 2000-10-31 | 1970-10-31 | 0070-10-31 | **Zero dates** Zero is not a valid year, month or day, so `DATE'0000-10-31'` is an error (`Invalid date`). As an exception, a value whose fields are *all* zero is accepted: `DATE'0000-00-00'`, `TIMESTAMP'0000-00-00 00:00:00'`, `DATETIME'0000-00-00 00:00:00'` and the same for the time zone types. For **TIMESTAMP**, 1970-01-01 00:00:00 UTC is the same value as `TIMESTAMP'0000-00-00 00:00:00'`. - Date/time functions given an all-zero argument either return **NULL** or raise an error, depending on the system parameter [return_null_on_function_errors](https://www.coradb.ai/manual/admin/config_sql.html#return_null_on_function_errors) (default `no`: error). - Java cannot represent an all-zero date. JDBC handles it according to the `zeroDateTimeBehavior` connection property (raise an exception, return **NULL**, or return the minimum value); see [Configuration connection](https://www.coradb.ai/manual/api/jdbc.html#configuration-connection). **Display format** The result tables in this manual show dates and times in ISO form (`2008-10-31`, `13:15:45`, `2008-10-31 13:15:45`). CoraDB's own text form, used by corasql and by `CAST(... AS STRING)`, is `MM/DD/YYYY` for dates and `hh:mi:ss AM|PM` for times, for example `01:15:45 PM 10/31/2008`. Drivers return native date/time values that your application formats. Use [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) or [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) to choose a format in SQL. When the system parameter **intl_date_lang** is set, [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date), [TO_TIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_time), [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime), [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp), [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format), [TIME_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#time_format), [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) and [STR_TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#str_to_date) read and write month and day names in that locale. See [Statement/type-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters). **Explicit conversion** [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) converts between date/time types that share a field: | From \ to | DATE | TIME | DATETIME | TIMESTAMP | |---|---|---|---|---| | **DATE** | — | no | yes | yes | | **TIME** | no | — | no | no | | **DATETIME** | yes | yes | — | yes | | **TIMESTAMP** | yes | yes | yes | — | The time zone types follow the rules of their base type. Converting a **DATE** to **DATETIME** or **TIMESTAMP** sets the time to midnight; converting to **DATE** or **TIME** drops the other part: ```sql SELECT CAST(DATE'2011-04-20' AS DATETIME) AS a, CAST(DATETIME'2011-04-20 09:10:15.359' AS DATE) AS b, CAST(DATETIME'2011-04-20 09:10:15.359' AS TIME) AS c; ``` | a | b | c | |---|---|---| | 2011-04-20 00:00:00.000 | 2011-04-20 | 09:10:15 | `CAST(DATE'2011-04-20' AS TIME)` fails with `Cannot coerce date '2011-04-20' to type time`, and `CAST(TIME'09:10:15' AS DATETIME)` with `Casting time '09:10:15' to type datetime is not supported`. For implicit conversions see [Implicit type conversion](https://www.coradb.ai/manual/sql/datatype.html#implicit-type-conversion) and [Arithmetic operations and type casting of DATE/TIME data types](https://www.coradb.ai/manual/sql/function/arithmetic_op.html#arithmetic-operations-and-type-casting-of-datetime-data-types). > **Note:** > For the literal syntax of all date/time types, including the time zone types, see [Date/time literals](https://www.coradb.ai/manual/sql/literal.html#datetime). ### DATE **DATE** stores a year, month and day, from 0001-01-01 to 9999-12-31. ```sql DATE'mm/dd[/yyyy]' DATE'[yyyy-]mm-dd' ``` - All fields are integers. If the year is omitted, the current year is used. - [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date) converts a string in any format to a **DATE**. - A **DEFAULT** value can be declared for a column of this type, for example `DEFAULT SYS_DATE`. ```sql SELECT DATE'2008-10-31' AS a, DATE'10/31/2008' AS b, DATE'0000-00-00' AS c; ``` | a | b | c | |---|---|---| | 2008-10-31 | 2008-10-31 | 0000-00-00 | `DATE'10/31'` is October 31 of the current year. ### TIME **TIME** stores an hour, minute and second, from 00:00:00 to 23:59:59. ```sql TIME'hh:mi[:ss] [AM | PM]' ``` - All fields are integers. If the seconds are omitted they are 0. - Both 12-hour and 24-hour input is accepted. A 24-hour value may carry **PM** when it agrees with it (`13:15:45 PM`), but `TIME'13:15:45 AM'` is an error (`Invalid time`). - [TO_TIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_time) converts a string in any format to a **TIME**. - A **DEFAULT** value can be declared for a column of this type. ```sql SELECT TIME'00:00:00' AS a, TIME'1:15' AS b, TIME'13:15:45' AS c, TIME'01:15:45 PM' AS d; ``` | a | b | c | d | |---|---|---|---| | 00:00:00 | 01:15:00 | 13:15:45 | 13:15:45 | ### TIMESTAMP **TIMESTAMP** stores a date and a time to the second, from 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC. The value is kept as seconds since the Unix epoch and shown in the session time zone. ```sql TIMESTAMP'hh:mi[:ss] [AM|PM] mm/dd[/yyyy]' TIMESTAMP'hh:mi[:ss] [AM|PM] [yyyy-]mm-dd' TIMESTAMP'mm/dd[/yyyy] hh:mi[:ss] [AM|PM]' TIMESTAMP'[yyyy-]mm-dd hh:mi[:ss] [AM|PM]' ``` - The time can come before or after the date. If the year is omitted, the current year is used; if the time is omitted, it is midnight. - `SYS_TIMESTAMP` (also `SYSTIMESTAMP`, `CURRENT_TIMESTAMP`) returns the current timestamp, for example as a column **DEFAULT**. - [TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#timestamp) and [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp) convert strings to **TIMESTAMP**. - A value outside the range is an error: `TIMESTAMP'2099-10-31 01:15:45 PM'` fails with `Invalid utime`. ```sql SELECT TIMESTAMP'10/31/2008' AS a, TIMESTAMP'13:15:45 10/31/2008' AS b, TIMESTAMP'01:15:45 PM 2008-10-31' AS c, TIMESTAMP'2008-10-31 01:15:45 PM' AS d; ``` | a | b | c | d | |---|---|---|---| | 2008-10-31 00:00:00 | 2008-10-31 13:15:45 | 2008-10-31 13:15:45 | 2008-10-31 13:15:45 | ### DATETIME **DATETIME** stores a date and a time to the millisecond, from 0001-01-01 00:00:00.000 to 9999-12-31 23:59:59.999. It does not depend on the session time zone. ```sql DATETIME'hh:mi[:ss[.msec]] [AM|PM] mm/dd[/yyyy]' DATETIME'hh:mi[:ss[.msec]] [AM|PM] [yyyy-]mm-dd' DATETIME'mm/dd[/yyyy] hh:mi[:ss[.msec]] [AM|PM]' DATETIME'[yyyy-]mm-dd hh:mi[:ss[.msec]] [AM|PM]' ``` - The time can come before or after the date. If the year is omitted, the current year is used; if the time is omitted, it is midnight. - `SYS_DATETIME` (also `SYSDATETIME`, [CURRENT_DATETIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_datetime), [NOW](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-now)) returns the current date and time, for example as a column **DEFAULT**. - [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime) converts a string in any format to **DATETIME**. ```sql SELECT DATETIME'10/31/2008' AS a, DATETIME'13:15:45 10/31/2008' AS b, DATETIME'2008-10-31 13:15:45.123' AS c, DATETIME'2099-10-31 01:15:45 PM' AS d; ``` | a | b | c | d | |---|---|---|---| | 2008-10-31 00:00:00.000 | 2008-10-31 13:15:45.000 | 2008-10-31 13:15:45.123 | 2099-10-31 13:15:45.000 | ### Converting strings to date/time values #### Recommended formats When you convert a string with [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast), or with [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date), [TO_TIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_time), [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime) or [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp) without a format argument, write the string in one of these forms. They do not depend on the database locale. | Type | Formats | |---|---| | **DATE** | `YYYY-MM-DD`, `MM/DD/YYYY` | | **TIME** | `HH:MI:SS [AM\|PM]` | | **DATETIME** | `YYYY-MM-DD HH:MI:SS[.msec] [AM\|PM]`, `MM/DD/YYYY HH:MI:SS[.msec] [AM\|PM]`, or the time first: `HH:MI:SS[.msec] [AM\|PM] YYYY-MM-DD` | | **TIMESTAMP** | As **DATETIME**, without milliseconds | For example, `WHERE order_date >= '2025-12-01'` compares the **DATE** column with a date, because the string is converted to **DATE**. #### Other accepted formats **CAST** also accepts the following shorter forms. **DATE strings** - `[year sep] month sep day`: `2011-04-20`, or `04-20` for April 20 of the current year. - With `/` as the separator the order is `month/day[/year]`: `04/20/2011`, `04/20`. - Without separators: `YYYYMMDD`, `YYMMDD`, `YMMDD`, `MMDD` or `MDD`. The day always has two digits: `20110420` and `110420` are April 20, 2011; `420` is April 20 of the current year. **TIME strings** - `[hour]:min[:[sec]][.[msec]] [AM|PM]`: `09:10:15`, `09:10`, or `:10` (00:10:00). Milliseconds are accepted and dropped. - Without separators, the digits are read from the right as seconds, minutes and hours: `91015` is 09:10:15, `1015` is 00:10:15, and `15` or `10` is that many seconds. - A full date and time without separators (`20110420091015`) gives the time part. **DATETIME strings** - A date as above followed by an hour and optional minutes, seconds and milliseconds: `2011-04-20 09`, `04/20/2011 09`, `04-20 09`. - Without separators: `YYMMDDHHMI[SS[.msec]]` or `YYYYMMDDHHMISS[.msec]`, and `YYMMDDH` when the hour has one digit (`1104209` is 2011-04-20 09:00). The digits are matched to the patterns by length, so `201104200910.359` (12 digits) is read as `YYMMDDHHMISS`, that is 2020-11-04 20:09:10.359. - Time first, then date: `09:10:15.359 am 2011-04-20`, `:10 04/20`, `09 04-20`. In this form the time separator is always `:` and the date separator is `-` (`yyyy-mm-dd`) or `/` (`mm/dd/yyyy`). **Rules** - Milliseconds (*msec*) are kept only by **DATETIME**; digits after the third are ignored. **DATE**, **TIME** and **TIMESTAMP** drop them. - A date string without separators, or with any non-alphanumeric separator, is accepted, but the same separator must be used throughout. The date and the time are separated by a space. - The year can be omitted wherever the format allows; the current year is used. Two-digit years follow the 1970–2069 rule above. - Converting a date-only string to **DATETIME** sets the time to midnight. Converting a date-and-time string to **DATE** or **TIME** keeps only that part, but the other part must still be valid. - **AM**/**PM** must follow the time, separated by a space. The English markers are always accepted, as well as those of the server locale. ```sql SELECT CAST('91015' AS TIME) AS a, CAST('110420091035.359' AS DATETIME) AS b, CAST('110420091035.359' AS TIMESTAMP) AS c, CAST('20110420' AS DATE) AS d, CAST('2011-04-20 09:10:15' AS TIME) AS e; ``` | a | b | c | d | e | |---|---|---|---|---| | 09:10:15 | 2011-04-20 09:10:35.359 | 2011-04-20 09:10:35 | 2011-04-20 | 09:10:15 | ## Date/time types with time zone The time zone types carry time zone information in addition to the date and time. A time zone is written either as an IANA region name, optionally followed by the daylight-saving abbreviation (`Europe/Bucharest`, `Europe/Bucharest EEST`), or as an offset from UTC (`+09:00`). - **TZ** types (**DATETIMETZ**, **TIMESTAMPTZ**, also written *type* `WITH TIME ZONE`) store the value in UTC together with its time zone (the one written in the value, or the session time zone). They take 4 bytes more than the base type, and always print in their own time zone. - **LTZ** types (**DATETIMELTZ**, **TIMESTAMPLTZ**, also written *type* `WITH LOCAL TIME ZONE`) store the value in UTC only, and print it converted to the session time zone. | Type | Input | Stored | Output | |---|---|---|---| | **DATE**, **TIME**, **DATETIME** | Without time zone | The value as entered | As entered | | **DATETIMETZ** | With time zone | UTC + time zone | In the value's own time zone | | **DATETIMELTZ** | With time zone | UTC | In the session time zone | | **TIMESTAMP** | Without time zone | UTC (input read in the session time zone) | In the session time zone, without zone name | | **TIMESTAMPTZ** | With time zone | UTC + time zone | In the value's own time zone | | **TIMESTAMPLTZ** | With time zone | UTC | In the session time zone, with zone name | Range, resolution and literal formats are the same as for the base types. The session time zone is changed with `SET TIME ZONE`. The following stores the same wall-clock value, 2015-02-24 12:30, in each type while the session is at UTC+9, and reads it back at UTC+9, UTC+7 and in Europe/Bucharest (UTC+2 in February): ```sql SET TIME ZONE '+09:00'; CREATE TABLE tz_demo (a DATETIME, b DATETIMETZ, c DATETIMELTZ, d TIMESTAMP, e TIMESTAMPTZ, f TIMESTAMPLTZ); INSERT INTO tz_demo VALUES (DATETIME'2015-02-24 12:30', DATETIMETZ'2015-02-24 12:30', DATETIMELTZ'2015-02-24 12:30', TIMESTAMP'2015-02-24 12:30', TIMESTAMPTZ'2015-02-24 12:30', TIMESTAMPLTZ'2015-02-24 12:30'); SELECT * FROM tz_demo; SET TIME ZONE '+07:00'; SELECT * FROM tz_demo; SET TIME ZONE 'Europe/Bucharest'; SELECT * FROM tz_demo; ``` | Session | DATETIME | DATETIMETZ | DATETIMELTZ | TIMESTAMP | TIMESTAMPTZ | TIMESTAMPLTZ | |---|---|---|---|---|---|---| | +09:00 | 2015-02-24 12:30:00.000 | 2015-02-24 12:30:00.000 +09:00 | 2015-02-24 12:30:00.000 +09:00 | 2015-02-24 12:30:00 | 2015-02-24 12:30:00 +09:00 | 2015-02-24 12:30:00 +09:00 | | +07:00 | 2015-02-24 12:30:00.000 | 2015-02-24 12:30:00.000 +09:00 | 2015-02-24 10:30:00.000 +07:00 | 2015-02-24 10:30:00 | 2015-02-24 12:30:00 +09:00 | 2015-02-24 10:30:00 +07:00 | | Europe/Bucharest | 2015-02-24 12:30:00.000 | 2015-02-24 12:30:00.000 +09:00 | 2015-02-24 05:30:00.000 Europe/Bucharest EET | 2015-02-24 05:30:00 | 2015-02-24 12:30:00 +09:00 | 2015-02-24 05:30:00 Europe/Bucharest EET | **DATETIME** never changes, the **TZ** types keep the time zone they were stored with, and **TIMESTAMP** and the **LTZ** types follow the session. > **Note:** > **TIMESTAMP** is stored as seconds since 1970-01-01 00:00:00 UTC (the Unix epoch). If you come from a database whose **TIMESTAMP** keeps fractions of a second, the CoraDB equivalent is **DATETIME**. **Converting between types with and without time zone** | Conversion | Rule | |---|---| | String without time zone → **TIMESTAMP**, **TIMESTAMPLTZ**, **DATETIMELTZ** | Read in the session time zone, stored as UTC | | String without time zone → **TIMESTAMPTZ**, **DATETIMETZ** | Read in the session time zone, stored as UTC with the session time zone | | String without time zone → **DATETIME** | Stored as written | | String with time zone → **TIMESTAMPLTZ**, **DATETIMELTZ** | Converted from its time zone to UTC | | String with time zone → **TIMESTAMPTZ**, **DATETIMETZ** | Converted to UTC, its time zone is kept | | String with time zone → **TIMESTAMP**, **DATETIME** | Error: the base types do not accept a time zone | | **DATETIME** → **DATETIMETZ** | Read in the session time zone | | **DATETIMETZ** → **DATETIME** | Keeps the date and time of the value's own time zone | | **DATETIMELTZ**, **TIMESTAMPTZ**, **TIMESTAMPLTZ** → a type without time zone | The date and time in the session time zone | In a session at Asia/Seoul (UTC+9 all year), for a value written as 2026-07-01 12:00 in Europe/Bucharest (UTC+3 in summer): ```sql SET TIME ZONE 'Asia/Seoul'; SELECT CAST(DATETIMETZ'2026-07-01 12:00:00 Europe/Bucharest' AS DATETIME) AS tz_to_dt, CAST(DATETIMELTZ'2026-07-01 12:00:00 Europe/Bucharest' AS DATETIME) AS ltz_to_dt, CAST(DATETIME'2026-07-01 12:00:00' AS DATETIMETZ) AS dt_to_tz, CAST(TIMESTAMPTZ'2026-07-01 12:00:00 Europe/Bucharest' AS TIMESTAMP) AS tstz_to_ts; ``` | tz_to_dt | ltz_to_dt | dt_to_tz | tstz_to_ts | |---|---|---|---| | 2026-07-01 12:00:00.000 | 2026-07-01 18:00:00.000 | 2026-07-01 12:00:00.000 Asia/Seoul KST | 2026-07-01 18:00:00 | When a value is printed, **TIMESTAMP** and **DATETIME** never show a time zone, the **LTZ** types show the session time zone, and the **TZ** types show their own. ### Time zone configuration The following system parameters in `coradb.conf` control time zones. See [System parameters](https://www.coradb.ai/manual/admin/config.html#parameter-reference). | Parameter | Meaning | Default | |---|---|---| | [timezone](https://www.coradb.ai/manual/admin/config_sql.html#timezone) | Time zone of a session | The value of **server_timezone** | | [server_timezone](https://www.coradb.ai/manual/admin/config_sql.html#server_timezone) | Time zone of the server | The operating system's time zone | | [tz_leap_second_support](https://www.coradb.ai/manual/admin/config_sql.html#tz_leap_second_support) | Leap second support | `no` | A session changes its own time zone with `SET TIME ZONE 'Europe/Bucharest'` or `SET TIME ZONE '+02:00'`. ### Time zone functions - [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone): the server time zone. - [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone): the session time zone. - [FROM_TZ](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_tz): adds a time zone to a **DATETIME** value. - [NEW_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#new_time): converts a value from one time zone to another. - [TZ_OFFSET](https://www.coradb.ai/manual/sql/function/datetime_fn.html#tz_offset): the UTC offset of a time zone. ### Functions and operators on time zone types Every function and operator that accepts **DATETIME**, **TIMESTAMP** or **TIME** also accepts the corresponding time zone types, and the result keeps the time zone type. As with the base types, a number added to a **DATETIME** type counts milliseconds and a number added to a **TIMESTAMP** type counts seconds. In a session at Asia/Seoul: ```sql SET TIME ZONE 'Asia/Seoul'; SELECT DATETIMELTZ'09/01/2009 03:30:30 PM' + 1 AS a, TIMESTAMPTZ'09/01/2009 03:30:30 PM' - 1 AS b; ``` | a | b | |---|---| | 2009-09-01 15:30:30.001 Asia/Seoul KST | 2009-09-01 15:30:29 Asia/Seoul KST | An **LTZ** value is seen in the session time zone. 05:45 in Bucharest on 1986-10-15 (UTC+2 on that date) is 12:45 in Seoul, so [EXTRACT](https://www.coradb.ai/manual/sql/function/datetime_fn.html#extract) returns hour 5 for **DATETIMETZ** and hour 12 for **DATETIMELTZ**: ```sql SET TIME ZONE 'Asia/Seoul'; SELECT EXTRACT(HOUR FROM DATETIMETZ'10/15/1986 5:45:15.135 AM Europe/Bucharest') AS tz_hour, EXTRACT(HOUR FROM DATETIMELTZ'10/15/1986 5:45:15.135 AM Europe/Bucharest') AS ltz_hour; ``` | tz_hour | ltz_hour | |---|---| | 5 | 12 | ### Conversion functions for time zone types These functions convert between strings and date/time values, and understand time zone regions (`TZR`), daylight-saving abbreviations (`TZD`) and offsets (`TZH`, `TZM`): - [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) - [STR_TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#str_to_date) - [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) - [TO_DATETIME_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime_tz) - [TO_TIMESTAMP_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp_tz) ```sql SELECT DATE_FORMAT(DATETIMETZ'2012-02-02 10:10:10 Europe/Zurich CET', '%TZR %TZD %TZH %TZM') AS fmt, TO_DATETIME_TZ('2001-10-11 02:03:04 AM Europe/Bucharest EEST') AS dt, TO_TIMESTAMP_TZ('2001-10-11 02:03:04 AM Europe/Bucharest') AS ts; ``` | fmt | dt | ts | |---|---|---| | Europe/Zurich CET +01 00 | 2001-10-11 02:03:04.000 Europe/Bucharest EEST | 2001-10-11 02:03:04 Europe/Bucharest EEST | [TO_DATETIME_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime_tz) and [TO_TIMESTAMP_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp_tz) work like [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime) and [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp), except that the string can contain TZR, TZD, TZH and TZM information. ### IANA time zones CoraDB uses the region names of the IANA (Internet Assigned Numbers Authority) time zone database, which records the history of local time, UTC offsets and daylight-saving rules for locations around the world. It is updated whenever governments change these rules; its maintenance is described in [BCP 175](https://tools.ietf.org/html/rfc6557). See . CoraDB ships with a compiled time zone library. To use a newer version of the database, update the time zone data, compile the library and restart the database; see [Compiling timezone library](https://www.coradb.ai/manual/sql/i18n_timezone.html#compiling-timezone-library). --- # Graph types: GRAPH_OBJECT and PATH Source: https://www.coradb.ai/manual/sql/datatype_graph.html CoraDB has two data types for graph queries. Both are used together with [MATCH](https://www.coradb.ai/manual/graph/match.html) and the [graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html). | Type | Value | Created by | |---|---|---| | **PATH** | An ordered sequence of vertices and the edges between them | A path variable in a **MATCH** clause | | **GRAPH_OBJECT** | A reference to one vertex or edge, of any vertex or edge table | **CAST** of a vertex or edge | The examples use the e-commerce sample graph, in which customers *like* products (`likes` edges from `customer` to `product`). A path of two `likes` edges, matched without direction, leads from a product to a customer who liked it and on to another product that customer liked. ## Path type A **PATH** value is created by a *path variable* in a **MATCH** clause, written `path_variable = pattern`. It contains the vertices and edges matched by the pattern, in order. See [Path variables](https://www.coradb.ai/manual/graph/match.html#path-variables). - A path exists only within the query that matches it. It cannot be created with a literal, stored in a table column (`PATH is not defined`), or passed between queries. - Read its parts with [nodes()](https://www.coradb.ai/manual/sql/function/graph_fn.html#nodes) and [relationships()](https://www.coradb.ai/manual/sql/function/graph_fn.html#relationships), which return LISTs, and measure it with [path_size()](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_size). [path_comp()](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_comp) collects values from matching paths without a **FROM MATCH** clause. ```sql SELECT p2.name AS other_product, size(nodes(pth)) AS vertex_count, size(relationships(pth)) AS edge_count, path_size(pth) AS path_size FROM MATCH pth = (p1:product)-[l:likes{2,2}]-(p2:product) WHERE p1.name = 'Vegie-spread' AND p1 <> p2 ORDER BY 1 LIMIT 3; ``` | other_product | vertex_count | edge_count | path_size | |---|---|---|---| | Abominable Hoodie | 3 | 2 | 2 | | Aeon Capri | 3 | 2 | 2 | | Arcadio Gym Short | 3 | 2 | 2 | Each path has three vertices (product, customer, product) and two edges. ## Graph object type A **GRAPH_OBJECT** value refers to a vertex or an edge without fixing its table. It lets you handle the elements of a path, which can come from different vertex and edge tables, in one list. - A **GRAPH_OBJECT** is obtained with **CAST**: `CAST(v AS GRAPH_OBJECT)` for one element, or `CAST(nodes(pth) AS SEQUENCE(GRAPH_OBJECT))` for the vertices of a path. With [list_comp()](https://www.coradb.ai/manual/sql/function/list_fn.html#list_comp) each element can be cast separately. - Internally it is an object identifier (OID). Drivers return it as an opaque reference, and corasql prints it as an OID such as `(0|3585|1)`; OIDs differ from database to database. - Read the properties of the element with [property_of()](https://www.coradb.ai/manual/sql/function/information_fn.html#fn-property-of), giving the table the element belongs to. - A table column can be declared as **GRAPH_OBJECT**. It stores the reference, not a copy of the vertex or edge. The following query reads the first, second and last vertex of each path through **GRAPH_OBJECT** values, using the three ways to convert them: ```sql SELECT property_of(CAST(first(nodes(pth)) AS GRAPH_OBJECT), name, product) AS product, property_of(at(CAST(nodes(pth) AS SEQUENCE(GRAPH_OBJECT)), 1), company_name, customer) AS liked_by, property_of(last(list_comp(x IN nodes(pth) | CAST(x AS GRAPH_OBJECT))), name, product) AS also_liked FROM MATCH pth = (p1:product)-[l:likes{2,2}]-(p2:product) WHERE p1.name = 'Vegie-spread' AND p1 <> p2 ORDER BY 2, 3 LIMIT 2; ``` | product | liked_by | also_liked | |---|---|---| | Vegie-spread | Alvarado LLC | Lono Yoga Short | | Vegie-spread | Alvarado LLC | Neve Studio Dance Jacket | > **Note:** > `property_of()` must be given the table of the element at that position. In a path that mixes vertex tables (here `product`, `customer`, `product`), read each position with its own table rather than applying one table to every element. > **See also:** > - [MATCH](https://www.coradb.ai/manual/graph/match.html): graph patterns and path variables > - [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html): [nodes()](https://www.coradb.ai/manual/sql/function/graph_fn.html#nodes), [relationships()](https://www.coradb.ai/manual/sql/function/graph_fn.html#relationships), [path_size()](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_size), [path_comp()](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_comp) > - [List functions](https://www.coradb.ai/manual/sql/function/list_fn.html): [first()](https://www.coradb.ai/manual/sql/function/list_fn.html#first), [last()](https://www.coradb.ai/manual/sql/function/list_fn.html#last), [at()](https://www.coradb.ai/manual/sql/function/list_fn.html#at), [size()](https://www.coradb.ai/manual/sql/function/list_fn.html#size), [list_comp()](https://www.coradb.ai/manual/sql/function/list_fn.html#list_comp) > - [PROPERTY_OF](https://www.coradb.ai/manual/sql/function/information_fn.html#fn-property-of) --- # JSON data type Source: https://www.coradb.ai/manual/sql/datatype_json.html ## JSON data type The **JSON** data type stores JSON documents as defined by [RFC 7159](https://tools.ietf.org/html/rfc7159). Values are validated when they are stored and kept in a parsed form, so the [JSON functions](https://www.coradb.ai/manual/sql/function/json_fn.html) can access their parts without parsing the text again. ### Creating JSON values A string assigned to a **JSON** column is parsed automatically. A string can also be converted with [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) or written as a `JSON'…'` literal, and [JSON_OBJECT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_object) and [JSON_ARRAY](https://www.coradb.ai/manual/sql/function/json_fn.html#json_array) build JSON values from SQL values. ```sql CREATE TABLE product_spec (product_id INT, spec JSON); INSERT INTO product_spec VALUES (1618, '{"weight_g": 280, "colors": ["black", "white"]}'); SELECT product_id, spec, TYPEOF(spec) AS t, spec->>'$.colors[0]' AS first_color FROM product_spec; ``` | product_id | spec | t | first_color | |---|---|---|---| | 1618 | {"weight_g":280,"colors":["black","white"]} | json | black | ```sql SELECT CAST('{"a":1}' AS JSON) AS a, JSON'{"a":1}' AS b, TYPEOF(JSON'{"a":1}') AS t; ``` | a | b | t | |---|---|---| | {"a":1} | {"a":1} | json | JSON values are printed in compact form, without spaces between tokens. ### JSON validation A string that is not valid JSON is rejected: ```sql SELECT JSON'abc'; ``` ```text ERROR: Invalid JSON: 'abc'. ``` A **JSON** column can also be restricted with a [JSON Schema](https://json-schema.org/specification.html) (see [Understanding JSON Schema](https://json-schema.org/understanding-json-schema/index.html) for an introduction). Write the schema as a string after the type: ```sql CREATE TABLE product_spec ( product_id INT, spec JSON ('{"type": "object", "required": ["weight_g"], "properties": {"weight_g": {"type": "integer"}, "colors": {"type": "array", "items": {"type": "string"}}}}') ); -- passes the schema INSERT INTO product_spec VALUES (1618, '{"weight_g": 280, "colors": ["black", "white"]}'); -- "weight_g" is missing INSERT INTO product_spec VALUES (1619, '{"colors": ["red"]}'); ``` ```text ERROR: The provided JSON has been invalidated by the JSON schema (Invalid schema path: #, Keyword: required, Invalid provided JSON path: #) ``` [SHOW COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) shows the schema as part of the column type, for example `JSON('{"type": "object", …}')`. Casting a value to a **JSON** type with a schema also validates it. ### JSON value types A JSON value is an object, an array, or a scalar (string, number, `true`, `false` or `null`), as defined by [RFC 7159](https://tools.ietf.org/html/rfc7159#section-3). [JSON_TYPE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_type) returns the CoraDB name of the type: | JSON value | CoraDB JSON type | Description | |---|---|---| | Object | `JSON_OBJECT` | A set of key-value pairs | | Array | `JSON_ARRAY` | An ordered list of JSON values | | string | `STRING` | A quoted string | | Number | `INTEGER` | An integer that fits in 32 bits | | Number | `BIGINT` | An integer that fits in 64 bits | | Number | `DOUBLE` | Any other number: with a fraction, an exponent, or larger than 2^63 - 1 | | `true`, `false` | `BOOLEAN` | A boolean | | `null` | `JSON_NULL` | The JSON null value (not SQL **NULL**) | ```sql SELECT JSON_TYPE(JSON'{"a":1}') AS a, JSON_TYPE(JSON'[1,2]') AS b, JSON_TYPE(JSON'"x"') AS c, JSON_TYPE(JSON'5') AS d, JSON_TYPE(JSON'5000000000') AS e, JSON_TYPE(JSON'5.5') AS f, JSON_TYPE(JSON'true') AS g, JSON_TYPE(JSON'null') AS h; ``` | a | b | c | d | e | f | g | h | |---|---|---|---|---|---|---|---| | JSON_OBJECT | JSON_ARRAY | STRING | INTEGER | BIGINT | DOUBLE | BOOLEAN | JSON_NULL | ### JSON data conversions **To JSON.** Values of other types are converted to JSON explicitly with **CAST** or implicitly when stored in a **JSON** column or passed to a JSON function: | SQL type | Result | |---|---| | Any string type | Parsed as JSON text; the result can be of any JSON type | | **SHORT**, **INTEGER**, **BIGINT** | `INTEGER`, or `BIGINT` if the value does not fit in 32 bits | | **FLOAT**, **DOUBLE**, **NUMERIC** | `DOUBLE` | **From JSON.** | CoraDB JSON type | Can be converted to | |---|---| | `JSON_OBJECT`, `JSON_ARRAY` | A string with the JSON text | | `STRING` | Any type a string can be converted to; as a string, without the quotes | | `INTEGER`, `BIGINT`, `DOUBLE` | Any type the corresponding SQL number can be converted to | | `BOOLEAN` | `'true'` or `'false'` as a string; 1 or 0 as a number | | `JSON_NULL` | The string `'null'` | ```sql SELECT CAST(JSON'true' AS STRING) AS a, CAST(JSON'true' AS INT) AS b, CAST(JSON'"42"' AS INT) AS c, CAST(JSON'"abc"' AS STRING) AS d, CAST(JSON'null' AS STRING) AS e, JSON_TYPE(CAST(5.25 AS JSON)) AS f; ``` | a | b | c | d | e | f | |---|---|---|---|---|---| | true | 1 | 42 | abc | null | DOUBLE | ### JSON paths Most JSON functions take a *JSON path* (or a JSON pointer, below) that addresses a part of a document. A path starts with `$`, the root, followed by any number of tokens: ```text ::= $ [ ] ... ::= [ index ] -- array element, from 0 | . key_identifier -- object member | . "key string" -- object member, any key | .* -- every member of an object | [*] -- every element of an array | ** -- any sequence of keys and indexes, then the token ``` In `{"a":[0,1,2,{"b":5}]}`, the path `$.a[3].b` means "member `b` of element 3 of member `a` of the root" and addresses the value `5`. A key that is not a valid identifier is written in double quotes, with JSON escapes: `$."first name"`, or `$."\""` for a key that is a double quote. Paths with wildcards can match several values; functions such as [JSON_EXTRACT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_extract) then return them in an array: ```sql SELECT JSON_EXTRACT('{"a":[0,1,2,{"b":5}]}', '$.a[3].b') AS a, JSON_EXTRACT('{"a":[0,1,2,{"b":5}]}', '$.a[*]') AS b, JSON_EXTRACT('{"a":{"x":1},"b":{"x":2}}', '$.*.x') AS c, JSON_EXTRACT('{"a":{"x":1},"b":[{"x":2}]}', '$**.x') AS d; ``` | a | b | c | d | |---|---|---|---| | 5 | [0,1,2,{"b":5}] | [1,2] | [1,2] | Paths are interpreted in UTF-8. A path in another character set is converted to UTF-8 first. ### JSON pointers A *JSON pointer* ([RFC 6901](https://tools.ietf.org/html/rfc6901)) is an alternative way to write a path without wildcards. Each token is preceded by `/`, and an empty pointer is the root: ```text ::= [ / path_token ] ... [ /- ] ``` | JSON path | JSON pointer | |---|---| | `$.a[10].bb` | `/a/10/bb` | | `$` | (empty string) | The special last token `/-` addresses the position after the last element of an array, for example to append a value: `JSON_INSERT('[1,2]', '/-', 3)` returns `[1,2,3]`. ```sql SELECT JSON_EXTRACT('{"a":[0,1,2,{"b":5}]}', '/a/3/b') AS by_pointer, JSON_EXTRACT('{"a":1}', '') AS root; ``` | by_pointer | root | |---|---| | 5 | {"a":1} | Like paths, pointers are interpreted in UTF-8. --- # BLOB and CLOB types Source: https://www.coradb.ai/manual/sql/datatype_lob.html ## BLOB/CLOB data types **BLOB** (binary large object) and **CLOB** (character large object) store large values such as documents and images. CoraDB keeps LOB data *outside* the database volumes, in files on the database server's file system, and stores only a reference to the file, the *LOB locator*, in the row. | Type | Holds | SQL value form | Maximum size | |---|---|---|---| | **BLOB** | Binary data | Bit string | The largest file the file system allows | | **CLOB** | Character data | Character string | The largest file the file system allows | - LOB files are named `{table_name}_{unique_name}`, where *unique_name* is generated by the server, so the LOB files of many tables can share one directory. - The files are created, replaced and deleted by CoraDB together with the rows that reference them. Do not change them with other tools; CoraDB cannot keep them consistent with the database if you do. - Converting a LOB value to a bit or character string (and the reverse) is limited to 1 GB. ### Creating LOB columns **BLOB** and **CLOB** columns are created with **CREATE TABLE** or added with **ALTER TABLE**, like any other column. The following table stores a manual and an image for products of the e-commerce sample database: ```sql CREATE TABLE product_doc ( product_id INT PRIMARY KEY, manual CLOB, image BLOB ); ``` LOB columns have these restrictions: | Not allowed on a LOB column | Error | |---|---| | An index, or a **PRIMARY KEY**, **FOREIGN KEY** or **UNIQUE** constraint | `Cannot define index on domain "clob".` | | **NOT NULL** | `Set NOT NULL on blob typed column is not allowed.` | | A **DEFAULT** other than **NULL**, or **SHARED** | `Set DEFAULT or SHARED on blob typed column is not allowed.` | | Use as an element of a collection type | | ### Storing and updating LOB values A string or bit string assigned to a LOB column is converted automatically. The functions [CHAR_TO_CLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_clob) and [BIT_TO_BLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#bit_to_blob) make the conversion explicit. ```sql INSERT INTO product_doc VALUES (1618, CHAR_TO_CLOB('Gobi HeatTec Tee by Diadora. Breathable mesh.'), BIT_TO_BLOB(X'89504E47')); INSERT INTO product_doc VALUES (1619, CHAR_TO_CLOB('Hero Hoodie. Fleece lining, kangaroo pocket.'), NULL); INSERT INTO product_doc VALUES (1620, 'Plain string into CLOB', X'FFD8'); -- copy a LOB value from another row INSERT INTO product_doc (product_id, manual) SELECT 1621, manual FROM product_doc WHERE product_id = 1619; UPDATE product_doc SET manual = NULL WHERE product_id = 1621; UPDATE product_doc SET image = (SELECT image FROM product_doc WHERE product_id = 1618) WHERE product_id = 1619; DELETE FROM product_doc WHERE product_id = 1620; ``` What happens to the files: - **INSERT** of a non-NULL value creates a new file and stores its locator in the row. Copying a LOB value from another row creates a copy of the file. - **UPDATE** to a non-NULL value deletes the old file, if any, and creates a new one. **UPDATE** to **NULL** deletes the old file and stores **NULL**. - **DELETE** of a row deletes its LOB files, also when the row is deleted by a cascading foreign key. - **DROP TABLE** and **ALTER TABLE … DROP COLUMN** remove only the locators; the LOB files themselves are *not* deleted. To load a file that already exists on the server, use [CLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_from_file) or [BLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_from_file). ### Reading LOB values Convert a LOB value to a string or bit string with [CLOB_TO_CHAR](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_to_char), [BLOB_TO_BIT](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_to_bit) or [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) to work with its contents. [CLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_length) and [BLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_length) return the size without reading the data. ```sql SELECT product_id, CLOB_TO_CHAR(manual) AS manual_text, CLOB_LENGTH(manual) AS chars, BLOB_LENGTH(image) AS bytes, BLOB_TO_BIT(image) AS bits, image IS NULL AS no_image FROM product_doc ORDER BY product_id; ``` | product_id | manual_text | chars | bytes | bits | no_image | |---|---|---|---|---|---| | 1618 | Gobi HeatTec Tee by Diadora. Breathable mesh. | 45 | 4 | 0x89504e47 | 0 | | 1619 | Hero Hoodie. Fleece lining, kangaroo pocket. | 44 | NULL | NULL | 1 | | 1620 | Plain string into CLOB | 22 | 2 | 0xffd8 | 0 | | 1621 | Hero Hoodie. Fleece lining, kangaroo pocket. | 44 | NULL | NULL | 1 | (Values right after the four **INSERT** statements above; bit strings as drivers return them, in hexadecimal.) - Drivers return the data of a LOB column. corasql shows the locator (a `file:` path) instead; use **CLOB_TO_CHAR** to see the text. - **LIKE** works on a **CLOB** column directly. Other string functions need **CLOB_TO_CHAR** first. - A LOB column cannot be used in **ORDER BY** or **GROUP BY** (`product_doc.manual can not be an ORDER BY column`), nor with comparison operators, **IN** or **NOT IN** (`'=' operator is not defined on types clob and char`). Convert it first. - **IS NULL** checks whether the column has a locator. A **NULL** LOB value has no file. - If a LOB file is removed outside CoraDB, the locator points to nothing and the LOB functions return **NULL** for it. ```sql SELECT product_id FROM product_doc WHERE manual LIKE '%Hoodie%'; -- 1619, 1621 SELECT product_id, SUBSTRING(CLOB_TO_CHAR(manual), 1, 8) AS head FROM product_doc ORDER BY CLOB_TO_CHAR(manual); ``` ### Functions and operators for LOB [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) converts between LOB types and bit or character strings: ```sql CAST (bit_or_char_value AS { BLOB | CLOB }) CAST (clob_value AS { CHAR | VARCHAR }) CAST (blob_value AS { BIT | BIT VARYING }) ``` The LOB functions are described in [LOB functions](https://www.coradb.ai/manual/sql/function/lob_fn.html): | Function | Purpose | |---|---| | [CLOB_TO_CHAR](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_to_char) | **CLOB** to character string | | [BLOB_TO_BIT](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_to_bit) | **BLOB** to bit string | | [CHAR_TO_CLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_clob) | Character string to **CLOB** | | [BIT_TO_BLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#bit_to_blob) | Bit string to **BLOB** | | [CHAR_TO_BLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_blob) | Character string to **BLOB** (its bytes) | | [CLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_from_file) | **CLOB** from a file on the server | | [BLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_from_file) | **BLOB** from a file on the server | | [CLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_length) | Length of a **CLOB** in characters | | [BLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_length) | Length of a **BLOB** in bytes | ### LOB storage LOB files are stored on the local file system of the database server, in the *LOB base path* of the database: - By default, the `lob` directory under the directory of the database volumes. - Another directory if you give one with `--lob-base-path` (`-B`) when you create the database; CoraDB creates the directory if needed. See [createdb](https://www.coradb.ai/manual/admin/admin_utils.html#createdb). ```bash # LOB files in /lob coradb createdb image_db en_US # LOB files in /data/lob coradb createdb --lob-base-path="file:/data/lob" image_db en_US ``` `coradb spacedb` shows the LOB base path in its last line (`LOB space description file:/data/lob`). To move new LOB files to another directory, change the `lob-base-path` column of the database in `databases.txt` and restart the database server. LOB files already stored in the old directory remain readable. - Backup and restore cover the locators but **not** the LOB files. Back up the LOB directory separately, at the same point in time as the database. - [copydb](https://www.coradb.ai/manual/admin/admin_utils.html#copydb) copies LOB files only when asked to (`--copy-lob-path`, or `-B` for a new path); otherwise update `databases.txt` for the copy yourself. - If the LOB base path registered in `databases.txt` is removed, the server and the utilities cannot work with the database. ### Transactions and recovery Changes to LOB values are transactional: **COMMIT** and **ROLLBACK** keep each locator and its file consistent. ```sql -- with autocommit off INSERT INTO product_doc VALUES (2001, CHAR_TO_CLOB('Version 1'), NULL); COMMIT; UPDATE product_doc SET manual = CHAR_TO_CLOB('Version 2') WHERE product_id = 2001; ROLLBACK; SELECT CLOB_TO_CHAR(manual) FROM product_doc WHERE product_id = 2001; -- 'Version 1' ``` Keep in mind that the files themselves are outside the log: - If the server stops in the middle of a transaction that changed a LOB value, recovery rolls back the locator, which can then point to a file that no longer holds the old data. Reading it raises an error. - A driver reads LOB data when a row is fetched, not when the query runs. If another transaction updates the LOB value in between, the fetch can fail because the locator no longer matches its file. - After a point-in-time restore, locators and LOB files can be out of step for the same reason. --- # Numeric types: INTEGER, BIGINT, NUMERIC, DOUBLE Source: https://www.coradb.ai/manual/sql/datatype_numeric.html ## Numeric types CoraDB supports the following numeric data types for integers and real numbers. | Type | Bytes | Min | Max | Exact / approximate | |---|---|---|---|---| | **SHORT**, **SMALLINT** | 2 | -32,768 | 32,767 | Exact | | **INTEGER**, **INT** | 4 | -2,147,483,648 | 2,147,483,647 | Exact | | **BIGINT** | 8 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 | Exact | | **NUMERIC**, **DECIMAL**, **DEC** | 16 | Precision 1, scale 0 | Precision 38, scale 38 | Exact | | **FLOAT**, **REAL** | 4 | -3.402823466E+38 | 3.402823466E+38 | Approximate, 7 significant digits | | **DOUBLE**, **DOUBLE PRECISION** | 8 | -1.7976931348623157E+308 | 1.7976931348623157E+308 | Approximate, 15 significant digits | - **Exact** types (**SMALLINT**, **INT**, **BIGINT**, **NUMERIC**) store the value as entered (after rounding to the declared scale). Use them for money, quantities and anything that must add up exactly. - **Approximate** types (**FLOAT**, **DOUBLE**) follow IEEE 754 and keep only a fixed number of significant digits. Use them for measurements and scientific values, not for amounts that are compared for equality. - CoraDB has no **UNSIGNED** modifier. `INT UNSIGNED` is a syntax error. - Names that share a row in the table are synonyms. [SHOW COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) always reports the first name, and a **NUMERIC** column always with its precision and scale: ```sql CREATE TABLE num_types (s SMALLINT, r REAL, f10 FLOAT(10), d DOUBLE PRECISION, p DEC(6,2), q DECIMAL); SHOW COLUMNS FROM num_types; ``` | Field | Type | |---|---| | s | SHORT | | r | FLOAT | | f10 | DOUBLE | | d | DOUBLE | | p | NUMERIC(6,2) | | q | NUMERIC(15,0) | In the e-commerce sample database, `product.id` is **INTEGER**, `product.unit_price` is **NUMERIC(10,2)** and `product.units_in_stock` is **SHORT**. ### Precision and scale The **precision** of a numeric type is its number of significant digits. The **scale** is the number of digits after the decimal point and only applies to **NUMERIC**. - **SMALLINT**, **INTEGER** and **BIGINT** have scale 0 and a precision fixed by the system (5, 10 and 19). - **NUMERIC** has a precision from 1 to 38 and a scale from 0 up to the precision. - **FLOAT** has 7 significant digits, **DOUBLE** has 15. ### Numeric literals A numeric literal can carry a sign (`+` or `-`), a decimal point and an exponent (`1e3`, `2.5E-4`). Its type follows from how it is written: | Literal | Type | |---|---| | Integer that fits in **INTEGER** (`100`) | **INTEGER** | | Larger integer (`2147483648`) | **BIGINT** | | Number with a decimal point (`12.5`) | **NUMERIC** with the digits as written, here `numeric (3, 1)` | | Number with an exponent (`1e3`) | **DOUBLE** | ```sql SELECT TYPEOF(100) AS a, TYPEOF(2147483648) AS b, TYPEOF(12.5) AS c, TYPEOF(1e3) AS d; ``` | a | b | c | d | |---|---|---|---| | integer | bigint | Numeric (3, 1) | double | The maximum precision of a numeric literal is 255 digits. ### Coercion in expressions All numeric values can be compared and combined with each other. When the operands of an expression have different numeric types, CoraDB converts them to a common type first. In general the result takes the type that can hold both operands: integer types widen to a larger integer type, then to **NUMERIC**, and any **FLOAT** or **DOUBLE** operand makes the result approximate. Use [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) to pick the type yourself. The value of a product's stock is `unit_price * units_in_stock`, a **NUMERIC(10,2)** times a **SHORT**, so the result is an exact **NUMERIC** with two decimals. Dividing by 3 keeps **NUMERIC** with a scale of 9; converting the price to **DOUBLE** first gives an approximate floating-point result: ```sql SELECT id, unit_price, units_in_stock, unit_price * units_in_stock AS stock_value, TYPEOF(unit_price * units_in_stock) AS value_type, unit_price / 3 AS third_numeric, CAST(unit_price AS DOUBLE) / 3 AS third_double FROM product WHERE id IN (1618, 1620) ORDER BY id; ``` | id | unit_price | units_in_stock | stock_value | value_type | third_numeric | third_double | |---|---|---|---|---|---|---| | 1618 | 29.00 | 22 | 638.00 | Numeric (26, 2) | 9.666666667 | 9.666666666666666 | | 1620 | 49.00 | 4 | 196.00 | Numeric (26, 2) | 16.333333333 | 16.333333333333332 | How the precision and scale of a **NUMERIC** result are computed for each operator is described in [Arithmetic operations and type casting of numeric data types](https://www.coradb.ai/manual/sql/function/arithmetic_op.html#arithmetic-operations-and-type-casting-of-numeric-data-types). #### Integer overflow The product of two **INTEGER** values is an **INTEGER**, so a result above 2,147,483,647 is an error even though it would fit in a **BIGINT**: ```sql SELECT 100000000 * 1000000; ``` ```text ERROR: Data overflow on data type integer. ``` Cast one operand to **BIGINT** and the whole expression is computed as **BIGINT**: ```sql SELECT CAST(100000000 AS BIGINT) * 1000000 AS total; ``` | total | |---| | 100000000000000 | The same applies to aggregates over small integer columns: if a total may be large, cast the column to a wider type inside the aggregate, for example `SUM(CAST(units_in_stock AS BIGINT))`. ### INT/INTEGER **INTEGER** stores whole numbers from -2,147,483,648 to 2,147,483,647. **INTEGER** and **INT** are synonyms, and a **DEFAULT** value can be declared for a column of this type. A value with a fractional part is rounded half away from zero to the nearest integer when it is stored. A value outside the range is rejected. | Value stored in an **INT** column | Result | |---|---| | 8934 | 8934 | | 89.8 | 90 | | -89.5 | -90 | | 3458901122 | Error: `Cannot coerce 3458901122 to type integer.` | ### SHORT/SMALLINT **SMALLINT** stores whole numbers from -32,768 to 32,767. **SMALLINT** and **SHORT** are synonyms, and a **DEFAULT** value can be declared for a column of this type. Fractional values are rounded like **INTEGER**. | Value stored in a **SMALLINT** column | Result | |---|---| | 8934 | 8934 | | 34.5 | 35 | | -34.5 | -35 | | 89354 | Error: `Cannot coerce 89354 to type smallint.` | ### BIGINT **BIGINT** stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. A **DEFAULT** value can be declared for a column of this type. Fractional values are rounded like **INTEGER**. | Value stored in a **BIGINT** column | Result | |---|---| | 8934 | 8934 | | 89.1 | 89 | | 89.8 | 90 | | 3458901122 | 3458901122 | By range and precision, the exact types are ordered **SMALLINT** < **INTEGER** < **BIGINT** < **NUMERIC**. ### NUMERIC/DECIMAL **NUMERIC** stores fixed-point numbers with a declared precision *p* (total number of digits) and scale *s* (digits after the decimal point). **NUMERIC**, **DECIMAL** and **DEC** are synonyms. ```sql NUMERIC [(p [, s])] ``` - *p* is between 1 and 38. When omitted it is 15. - *s* is between 0 and *p*. When omitted it is 0, so `NUMERIC` without arguments is `NUMERIC(15,0)` and stores whole numbers. - The integer part of a value can have at most *p* - *s* digits. Extra decimals are rounded half away from zero to *s* places. - A **DEFAULT** value can be declared for a column of this type. | Declaration and value | Result | |---|---| | 12345.6789 in `NUMERIC` | 12346 | | 12345.6789 in `NUMERIC(8,2)` | 12345.68 | | 12345.6789 in `NUMERIC(4)` | Error: `Cannot coerce 12345.6789 to type numeric.` | | 0.12345678 in `NUMERIC(4,4)` | 0.1235 | | -0.123456789 in `NUMERIC(4,4)` | -0.1235 | | Declaring `NUMERIC(3, 4)` | Error: `Invalid combination of precision (3) and scale (4).` | The same rounding applies to [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast): ```sql SELECT CAST(12345.6789 AS NUMERIC(8,2)) AS a, CAST(-0.123456789 AS NUMERIC(4,4)) AS b; ``` | a | b | |---|---| | 12345.68 | -0.1235 | ### FLOAT/REAL **FLOAT** (or **REAL**) is a single-precision IEEE 754 floating-point number with 7 significant digits. Normalized values range from ±1.175494351E-38 to ±3.402823466E+38, plus 0; values closer to 0 are stored as denormalized numbers. ```sql FLOAT [(p)] ``` - *p* is between 1 and 38. When *p* is omitted or is 7 or less, the column is single-precision **FLOAT**. - When *p* is between 8 and 38, the column is created as **DOUBLE** (15 significant digits). - **FLOAT** and **REAL** are synonyms, and a **DEFAULT** value can be declared for a column of this type. Digits beyond the seventh are lost, so do not use **FLOAT** for values that must be exact, and avoid comparing **FLOAT** values for equality. ```sql SELECT CAST(16777217 AS FLOAT) AS a, CAST(16777.217 AS FLOAT) AS b, CAST(16777.217 AS DOUBLE) AS c; ``` | a | b | c | |---|---|---| | 1.677721e+7 | 16777.21 | 16777.217 | ### DOUBLE/DOUBLE PRECISION **DOUBLE** is a double-precision IEEE 754 floating-point number with 15 significant digits. Normalized values range from ±2.2250738585072014E-308 to ±1.7976931348623157E+308, plus 0; values closer to 0 are stored as denormalized numbers. **DOUBLE** takes no precision argument. - **DOUBLE** and **DOUBLE PRECISION** are synonyms, and a **DEFAULT** value can be declared for a column of this type. - Like **FLOAT**, **DOUBLE** stores an approximation: integers above 2^53 can no longer all be represented exactly. ```sql SELECT CAST(1234.56789 AS DOUBLE) AS a, CAST(9007199254740993 AS DOUBLE) AS b; ``` | a | b | |---|---| | 1234.56789 | 9007199254740992 | > **Note:** > The **MONETARY** type is still accepted for compatibility but is deprecated. Use **NUMERIC** with an explicit scale, for example `NUMERIC(10,2)` as in `product.unit_price`. --- # String types: CHAR, VARCHAR, BIT and ENUM Source: https://www.coradb.ai/manual/sql/datatype_string.html ## Character strings CoraDB has two character string types: | Type | Synonyms | Length *n* | Storage | |---|---|---|---| | **CHAR**(*n*) | **CHARACTER**(*n*) | 1 to 268,435,455 characters, default 1 | Always *n* characters, padded with spaces | | **VARCHAR**(*n*) | **CHAR VARYING**(*n*), **CHARACTER VARYING**(*n*) | 1 to 1,073,741,823 characters, default the maximum | The characters entered | | **STRING** | **VARCHAR**(1,073,741,823) | | | - *n* counts characters, not bytes. How many bytes a character takes depends on the character set; see [An overview of globalization](https://www.coradb.ai/manual/sql/i18n.html). - A **DEFAULT** value can be declared for columns of these types. - In the e-commerce sample database the text columns are **VARCHAR**, for example `product.name` is **VARCHAR(64)** and `city.postal_code` is **VARCHAR(32)**. [SHOW COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) reports **VARCHAR**(*n*) and **CHAR**(*n*) whatever synonym was used. - **NCHAR** and **NCHAR VARYING** are still accepted for compatibility. Use **CHAR** and **VARCHAR** instead. **Too long values.** A value longer than *n* is rejected by **INSERT** and **UPDATE** (`Cannot coerce 'pacesetter' to type char.`). If the system parameter [allow_truncated_string](https://www.coradb.ai/manual/admin/config_sql.html#allow_truncated_string) is `yes`, the value is truncated to *n* characters instead. **Character set and collation.** The character set defines how characters are encoded; the collation defines how strings are compared and sorted. Both come from the database locale and can be changed per value with the **CHARSET** introducer and the **COLLATE** modifier. See [An overview of globalization](https://www.coradb.ai/manual/sql/i18n.html). **Conversion.** **CHAR** and **VARCHAR** values of the same character set are converted into each other automatically, for example when a **CHAR**(5) value is inserted into a **CHAR**(10) column. Use [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) for explicit conversions. ### CHAR(n) **CHAR**(*n*) always holds *n* characters: a shorter value is padded with spaces on the right. Trailing spaces beyond *n* are dropped without error. | Value stored in | Result | |---|---| | `'pacesetter'` in **CHAR**(12) | `'pacesetter '` (10 characters + 2 spaces) | | `'pacesetter '` in **CHAR**(10) | `'pacesetter'` (the extra spaces are dropped) | | `'pacesetter'` in **CHAR**(4) | Error, or `'pace'` with **allow_truncated_string** = `yes` | | `'p '` in **CHAR** | `'p'` (default length 1) | | `''` in **CHAR**(10) | Ten spaces: `LENGTH` returns 10 | ### VARCHAR(n), STRING **VARCHAR**(*n*) stores the value as entered, including trailing spaces, up to *n* characters. **STRING** is **VARCHAR** with the maximum length. | Value stored in | Result | |---|---| | `'pacesetter'` in **VARCHAR**(12) | `'pacesetter'` (10 characters) | | `'pacesetter '` in **VARCHAR**(12) | `'pacesetter '` (11 characters) | | `'pacesetter'` in **VARCHAR**(4) | Error, or `'pace'` with **allow_truncated_string** = `yes` | | `'p '` in **STRING** | `'p '` | | `''` in **VARCHAR**(12) | An empty string: `LENGTH` returns 0 | **String compression** **VARCHAR** values of 255 bytes or more are compressed with the LZO1X algorithm before they are stored in heap, index or temporary files, and decompressed when read. A value is kept uncompressed if compression would not make it smaller. Compression adds 8 bytes (the compressed and the original size) and can be turned off with the system parameter [enable_string_compression](https://www.coradb.ai/manual/admin/config_other.html#enable_string_compression). To see whether a value is compressed, compare [DISK_SIZE](https://www.coradb.ai/manual/sql/function/information_fn.html#disk_size) with [OCTET_LENGTH](https://www.coradb.ai/manual/sql/function/string_fn.html#octet_length): ```sql SELECT OCTET_LENGTH(REPEAT('a', 1000)) AS octets, DISK_SIZE(REPEAT('a', 1000)) AS on_disk; ``` | octets | on_disk | |---|---| | 1000 | 24 | ### String literals - A string literal is enclosed in single quotes. To include a single quote, write it twice: `'''abcde''fghij'` is `'abcde'fghij`. - Double quotes enclose identifiers by default. If the system parameter [ansi_quotes](https://www.coradb.ai/manual/admin/config_sql.html#ansi_quotes) is `no`, double quotes enclose strings too. - Two literals separated only by white space (spaces, tabs, line breaks) are joined into one, as in ANSI SQL. - A single string token can be at most 16 KB long; longer values are built with functions such as [CONCAT](https://www.coradb.ai/manual/sql/function/string_fn.html#concat) or bound as parameters. ```sql SELECT 'abc' 'def' AS joined, '''abcde''fghij' AS quotes, 'say "hi"' AS dq; ``` | joined | quotes | dq | |---|---|---| | abcdef | 'abcde'fghij | say "hi" | ### Escape special characters There are two ways to escape special characters in a string literal. **With quotes** (always available) - Inside single quotes, write a single quote twice (`''`). Double quotes need no escaping. - When **ansi_quotes** is `no`, inside double quotes write a double quote twice (`""`); single quotes need no escaping. **With a backslash** (only when the system parameter [no_backslash_escapes](https://www.coradb.ai/manual/admin/config_sql.html#no_backslash_escapes) is `no`; the default is `yes`) | Sequence | Character | |---|---| | `\'` | Single quote | | `\"` | double quote | | `\n` | Newline (line feed) | | `\r` | Carriage return | | `\t` | Tab | | `\\` | Backslash | | `\%` | Percent sign, in **LIKE** patterns | | `\_` | Underscore, In **LIKE** patterns | Any other character after a backslash stands for itself (`\x` is `x`). `\%` and `\_` only matter in pattern matching such as [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like); elsewhere they are the two characters as written. With the default `no_backslash_escapes = yes` a backslash is an ordinary character, so `'\\'` is two characters long; with `no` it is one: ```sql SELECT LENGTH('\\') AS len; ``` | len | |---| | 2 | With `no_backslash_escapes = no`, `STRCMP('single quotes test('')', 'single quotes test(\')')` returns 0, because both literals contain the same string. With the default setting the second literal is unterminated and the statement is a syntax error. **Escaping LIKE wildcards.** To match a literal `%` or `_` with **LIKE**, declare an escape character with **ESCAPE**. Any character works; with the default setting a backslash can be used directly: ```sql SELECT ('aaa%' LIKE 'aaa#%' ESCAPE '#') AS a, ('aaabbb' LIKE 'aaa#%' ESCAPE '#') AS b, ('aaa%' LIKE 'aaa\%' ESCAPE '\') AS c; ``` | a | b | c | |---|---|---| | 1 | 0 | 1 | When **no_backslash_escapes** is `no`, the backslash in the **ESCAPE** clause must itself be escaped: `ESCAPE '\\'`. ### Trailing spaces in comparisons The padding spaces of a **CHAR** value are ignored when it is compared. Trailing spaces in a **VARCHAR** value or in a string literal are significant. | Comparison | Result | |---|---| | **CHAR** `'abc'` = **CHAR** `'abc '` | Equal: both are padded and the padding is ignored | | **VARCHAR** `'abc'` = **VARCHAR** `'abc '` | Not equal | | **CHAR**(5) `'abc'` = **VARCHAR** `'abc'` | Equal: the **CHAR** padding is ignored | | **CHAR**(5) `'abc'` = **VARCHAR** `'abc '` | Not equal: the **VARCHAR** spaces count | | Literal `'abc'` = literal `'abc '` | Not equal | ```sql SELECT (CAST('abc' AS CHAR(5)) = CAST('abc ' AS CHAR(7))) AS char_char, (CAST('abc' AS VARCHAR(5)) = CAST('abc ' AS VARCHAR(7))) AS varchar_varchar, (CAST('abc' AS CHAR(5)) = CAST('abc' AS VARCHAR(5))) AS char_varchar, ('abc' = 'abc ') AS literals; ``` | char_char | varchar_varchar | char_varchar | literals | |---|---|---|---| | 1 | 0 | 1 | 0 | Use [TRIM or RTRIM](https://www.coradb.ai/manual/sql/function/string_fn.html#trim) when user input may carry trailing spaces. ## Bit strings A bit string is a sequence of bits (0 and 1). CoraDB has two bit string types: | Type | Length *n* | |---|---| | **BIT**(*n*) | Fixed, 1 to 1, 073, 741, 823 bits, Default 1 | | **BIT VARYING**(*n*) | Variable, up to *n* bits, default 1,073,741,823 | Bit string literals are written in binary or hexadecimal: | Form | Example | Value | |---|---|---| | `B'…'` | `B'1010'` | 1010 | | `0b…` | `0b1010` | 1010 | | `X'…'` | `X'a'` | 1010 | | `0x…` | `0xA` | 1010 | Hexadecimal digits are case-insensitive: `X'4f'` and `X'4F'` are the same value. - Bits are filled from the left, and a shorter value is padded with 0 bits on the right when it is compared or stored in a **BIT**(*n*) column. `B'1'` therefore equals `B'10000000'`. Declare lengths and write values in multiples of 8 bits to avoid surprises. - A value longer than the declared length is rejected (`Cannot coerce X'aaa' to type bit`). - **BIT** and **BIT VARYING** values are compared with each other automatically. Use [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) for explicit conversions. - A **DEFAULT** value can be declared for columns of these types. Bit strings are shown in hexadecimal. CoraDB's text form (corasql, `CAST(... AS STRING)`) shows only the hex digits that hold the stored bits, so a 1-bit value `B'1'` is shown as `8`; drivers return the bytes, `0x80`. ### BIT(n) A **BIT**(*n*) value always has *n* bits; a shorter value is padded with 0 bits. ```sql CREATE TABLE bit_tbl (a1 BIT, a2 BIT(1), a3 BIT(8), a4 BIT VARYING); INSERT INTO bit_tbl VALUES (B'1', B'1', B'1', B'1'); INSERT INTO bit_tbl VALUES (0b1, 0b1, 0b1, 0b1); INSERT INTO bit_tbl (a3, a4) VALUES (B'1010', B'1010'); INSERT INTO bit_tbl (a3, a4) VALUES (0xaa, 0xaa); SELECT CAST(a1 AS STRING) a1, CAST(a2 AS STRING) a2, CAST(a3 AS STRING) a3, CAST(a4 AS STRING) a4, BIT_LENGTH(a4) a4_bits FROM bit_tbl; ``` | a1 | a2 | a3 | a4 | a4_bits | |---|---|---|---|---| | 8 | 8 | 80 | 8 | 1 | | 8 | 8 | 80 | 8 | 1 | | NULL | NULL | a0 | a | 4 | | NULL | NULL | aa | aa | 8 | `a3` is **BIT(8)**, so `B'1'` becomes `10000000` (`80`) and `B'1010'` becomes `10100000` (`a0`). ### BIT VARYING(n) A **BIT VARYING**(*n*) value keeps the number of bits it was given, up to *n*; it is not padded. ```sql CREATE TABLE bitvar_tbl (a1 BIT VARYING, a2 BIT VARYING(8)); INSERT INTO bitvar_tbl VALUES (B'1', B'1'); INSERT INTO bitvar_tbl VALUES (0b1010, 0b1010); INSERT INTO bitvar_tbl VALUES (0xaa, 0xaa); INSERT INTO bitvar_tbl (a1) VALUES (0xaaa); SELECT CAST(a1 AS STRING) a1, CAST(a2 AS STRING) a2, BIT_LENGTH(a1) a1_bits FROM bitvar_tbl; ``` | a1 | a2 | a1_bits | |---|---|---| | 8 | 8 | 1 | | a | a | 4 | | aa | aa | 8 | | aaa | NULL | 12 | `INSERT INTO bitvar_tbl (a2) VALUES (0xaaa)` fails, because 12 bits do not fit in **BIT VARYING(8)**. ## ENUM data type **ENUM** is an ordered set of distinct string constants, the *enum values*. A column of this type holds one of them (or **NULL**). ```sql ENUM ( 'value1' [, 'value2' ...] ) ``` - An **ENUM** has at most 512 values, and the values must be unique (`Duplicate values in enum type`). - Each value has an *index*: 1 for the first value, 2 for the second, and so on. Only the index is stored, in 2 bytes. - A **DEFAULT** value can be declared. - A value that is not in the set is rejected: `Cannot coerce 'c' to type enum`. The examples below use a shipment status column: ```sql CREATE TABLE shipment ( id INT, status ENUM ('pending', 'packed', 'shipped', 'delivered') DEFAULT 'pending' ); ``` | Value | Index | |---|---| | NULL | NULL | | 'pending' | 1 | | 'packed' | 2 | | 'shipped' | 3 | | 'delivered' | 4 | You can insert either the value or its index: ```sql INSERT INTO shipment (id, status) VALUES (1, 'shipped'), (2, 1), (3, 'delivered'), (4, 'packed'); INSERT INTO shipment (id) VALUES (5); -- DEFAULT 'pending' ``` In expressions an **ENUM** behaves as its index in a numeric context and as its value in a string context: ```sql SELECT id, status, status + 0 AS idx, CONCAT(status, '!') AS txt FROM shipment ORDER BY id; ``` | id | status | idx | txt | |---|---|---|---| | 1 | shipped | 3 | shipped! | | 2 | pending | 1 | pending! | | 3 | delivered | 4 | delivered! | | 4 | packed | 2 | packed! | | 5 | pending | 1 | pending! | When an **ENUM** is converted to another type, numeric types use the index and all other types use the value: | Target type | Uses | |---|---| | **SHORT**, **INTEGER**, **BIGINT**, **FLOAT**, **DOUBLE**, **NUMERIC** | Index | | **CHAR**, **VARCHAR**, **BIT**, **BIT VARYING**, **DATE**, **TIME**, **DATETIME**, **TIMESTAMP** | Value | ### ENUM comparisons In `=` and `IN` predicates of the form *enum_column* *operator* *constant*, CoraDB converts the constant to the **ENUM** type, so that an index can be used. A constant that cannot be converted makes the comparison false instead of raising an error. | Predicate | Matches | |---|---| | `status = 'packed'` | Row 4 | | `status = 2` | Row 4 (index 2 is `'packed'`) | | `status = 'lost'`, `status = 15`, `status = DATE'2010-01-01'` | Nothing, Without error | With every other [comparison operator](https://www.coradb.ai/manual/sql/function/comparison_op.html), the **ENUM** is converted to the type of the other operand. Two **ENUM** values are compared as strings. Only `=` and `IN` can use an index. | Predicate | Compared as | Matches | |---|---|---| | `status < 'q'` | Strings | `pending`, `delivered`, `packed`, `pending` (rows 2, 3, 4, 5) | | `status > 3` | Indexes | `delivered` (row 3) | | `status > DATE'2012-01-01'` | | Error: `Cannot coerce value of domain "enum" to domain "date".` | ### ENUM ordering **ENUM** values sort by index, that is in the order of the definition. To sort alphabetically, cast to **VARCHAR**: ```sql SELECT status FROM shipment ORDER BY status; SELECT status FROM shipment ORDER BY CAST(status AS VARCHAR); ``` | ORDER BY status | ORDER BY CAST(status AS VARCHAR) | |---|---| | pending | delivered | | pending | packed | | packed | pending | | shipped | pending | | delivered | shipped | ### Changing the values of an ENUM Every **ENUM** column has its own set of values; the type cannot be shared between columns. Comparing two **ENUM** columns compares their values as strings, even if both columns define the same set. [ALTER TABLE … CHANGE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#changemodify-clauses) can redefine the set. Existing rows are converted by value, not by index. Adding a value works: ```sql ALTER TABLE shipment CHANGE status status ENUM ('pending', 'packed', 'shipped', 'delivered', 'returned'); ``` Removing a value that is still used fails with the default configuration: ```sql ALTER TABLE shipment CHANGE status status ENUM ('pending', 'shipped', 'delivered'); ``` ```text ERROR: ALTER TABLE .. CHANGE : changing to new domain : cast failed, current configuration doesn't allow truncation or overflow. ``` Update the rows that use the value first, then change the column. ### ENUM in applications Drivers return **ENUM** values as strings. In JDBC: ```java Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT status FROM shipment"); while (rs.next()) { System.out.println(rs.getString(1)); } ``` In CCI, fetch the column with `CCI_A_TYPE_STR`: ```c req = cci_prepare(conn, "SELECT status FROM shipment", 0, &err); res = cci_execute(req, 0, 0, &err); while (cci_cursor(req, 1, CCI_CURSOR_CURRENT, &err) == CCI_ER_NO_ERROR) { char *data; int ind; cci_fetch(req, &err); cci_get_data(req, 1, CCI_A_TYPE_STR, &data, &ind); printf("%s\n", data); } ``` --- # Database administration statements Source: https://www.coradb.ai/manual/sql/db_admin.html These statements manage users, sessions and server settings from SQL: | Page | Statements | |---|---| | [Users & privileges](https://www.coradb.ai/manual/sql/authorization.html) | [CREATE USER](https://www.coradb.ai/manual/sql/authorization.html#create-user), [ALTER USER](https://www.coradb.ai/manual/sql/authorization.html#alter-user), [DROP USER](https://www.coradb.ai/manual/sql/authorization.html#drop-user), [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant), [REVOKE](https://www.coradb.ai/manual/sql/authorization.html#revoke), [ALTER … OWNER TO](https://www.coradb.ai/manual/sql/authorization.html#alter--owner-to) | | [SET](https://www.coradb.ai/manual/sql/query/set.html) | [SET SYSTEM PARAMETERS](https://www.coradb.ai/manual/sql/query/set.html#system-parameters), [Session variables](https://www.coradb.ai/manual/sql/query/set.html#user-defined-variables), [Other SET and GET statements](https://www.coradb.ai/manual/sql/query/set.html#other-set-and-get-statements) | | [SHOW](https://www.coradb.ai/manual/sql/query/show.html) | [SHOW TABLES](https://www.coradb.ai/manual/sql/query/show.html#show-tables), [SHOW COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns-describe), [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index), [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table), [SHOW GRANTS](https://www.coradb.ai/manual/sql/query/show.html#show-grants), [Diagnostics](https://www.coradb.ai/manual/sql/query/show.html#diagnostics) | | [KILL](https://www.coradb.ai/manual/sql/query/kill.html) | **KILL** a session or the query it is running | The [System catalog](https://www.coradb.ai/manual/sql/catalog.html) gives the same schema information as **SHOW** through queries, and the [coradb utilities](https://www.coradb.ai/manual/admin/admin_utils.html) cover administration tasks outside SQL, such as creating, backing up and checking databases. --- # Operators and functions Source: https://www.coradb.ai/manual/sql/function.html CoraDB provides operators and built-in functions for every data type. The examples on these pages run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) or on literal values, and show real results. ## Operators | Page | Contents | |---|---| | [Comparison operators](https://www.coradb.ai/manual/sql/function/comparison_op.html) | `=`, `<=>`, `<>`, `<`, `>`, `IS [NOT] NULL/TRUE/FALSE` | | [Logical operators](https://www.coradb.ai/manual/sql/function/logical_op.html) | `AND`, `OR`, `XOR`, `NOT` | | [Arithmetic operators](https://www.coradb.ai/manual/sql/function/arithmetic_op.html) | `+`, `-`, `*`, `/`, `DIV`, `MOD`, and arithmetic on dates | | [Set arithmetic operators](https://www.coradb.ai/manual/sql/function/set_op.html) | Union, difference and intersection of collection values | | [Statement set operators](https://www.coradb.ai/manual/sql/function/stmt_set_op.html) | `UNION`, `DIFFERENCE`/`EXCEPT`, `INTERSECTION`/`INTERSECT` of queries | | [Containment operators](https://www.coradb.ai/manual/sql/function/containment_op.html) | [SETEQ](https://www.coradb.ai/manual/sql/function/containment_op.html#seteq), [SUBSET](https://www.coradb.ai/manual/sql/function/containment_op.html#subset), [SUPERSET](https://www.coradb.ai/manual/sql/function/containment_op.html#superset) and related operators | | [Conditional expressions](https://www.coradb.ai/manual/sql/function/condition_op.html) | [ANY](https://www.coradb.ai/manual/sql/function/condition_op.html#any-some-all)/[ALL](https://www.coradb.ai/manual/sql/function/condition_op.html#any-some-all), [BETWEEN](https://www.coradb.ai/manual/sql/function/condition_op.html#between), [EXISTS](https://www.coradb.ai/manual/sql/function/condition_op.html#exists), [IN](https://www.coradb.ai/manual/sql/function/condition_op.html#in), `IS NULL`, [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like), [CASE](https://www.coradb.ai/manual/sql/function/condition_op.html#case) | | [List predicates](https://www.coradb.ai/manual/sql/function/predicate_fn.html) | [ALL](https://www.coradb.ai/manual/sql/function/predicate_fn.html#all), [ANY](https://www.coradb.ai/manual/sql/function/predicate_fn.html#any), [NONE](https://www.coradb.ai/manual/sql/function/predicate_fn.html#none), [SINGLE](https://www.coradb.ai/manual/sql/function/predicate_fn.html#single) over the elements of a list | ## Functions | Page | Contents | |---|---| | [String functions](https://www.coradb.ai/manual/sql/function/string_fn.html) | [CONCAT](https://www.coradb.ai/manual/sql/function/string_fn.html#concat), [SUBSTRING](https://www.coradb.ai/manual/sql/function/string_fn.html#substring), [REPLACE](https://www.coradb.ai/manual/sql/function/string_fn.html#replace), [TRIM](https://www.coradb.ai/manual/sql/function/string_fn.html#trim), [LPAD](https://www.coradb.ai/manual/sql/function/string_fn.html#lpad), [INSTR](https://www.coradb.ai/manual/sql/function/string_fn.html#instr), ... | | [Regular expressions](https://www.coradb.ai/manual/sql/function/regex_fn.html) | [REGEXP](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp-rlike), [REGEXP_LIKE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_like), [REGEXP_REPLACE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_replace), [REGEXP_SUBSTR](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_substr), ... | | [Numeric functions](https://www.coradb.ai/manual/sql/function/numeric_fn.html) | [ABS](https://www.coradb.ai/manual/sql/function/numeric_fn.html#abs), [ROUND](https://www.coradb.ai/manual/sql/function/numeric_fn.html#round), [TRUNC](https://www.coradb.ai/manual/sql/function/numeric_fn.html#trunc-truncate), [MOD](https://www.coradb.ai/manual/sql/function/numeric_fn.html#mod), [POWER](https://www.coradb.ai/manual/sql/function/numeric_fn.html#pow-power), [RAND](https://www.coradb.ai/manual/sql/function/numeric_fn.html#random-rand), [WIDTH_BUCKET](https://www.coradb.ai/manual/sql/function/numeric_fn.html#width_bucket), ... | | [Date/time functions](https://www.coradb.ai/manual/sql/function/datetime_fn.html) | [ADD_MONTHS](https://www.coradb.ai/manual/sql/function/datetime_fn.html#add_months), [DATEDIFF](https://www.coradb.ai/manual/sql/function/datetime_fn.html#datediff), [EXTRACT](https://www.coradb.ai/manual/sql/function/datetime_fn.html#extract), [LAST_DAY](https://www.coradb.ai/manual/sql/function/datetime_fn.html#last_day), [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_chardate_time), time zones, ... | | [BIT functions](https://www.coradb.ai/manual/sql/function/bit_fn.html) | [BIT_AND](https://www.coradb.ai/manual/sql/function/bit_fn.html#bit_and-bit_or-bit_xor), [BIT_COUNT](https://www.coradb.ai/manual/sql/function/bit_fn.html#bit_count), bitwise operators | | [Type conversion functions](https://www.coradb.ai/manual/sql/function/typecast_fn.html) | [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast), [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_chardate_time), [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date), [TO_NUMBER](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_number), [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format), ... | | [Aggregate and analytic functions](https://www.coradb.ai/manual/sql/function/analysis_fn.html) | [COUNT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#count), [SUM](https://www.coradb.ai/manual/sql/function/analysis_fn.html#sum), [AVG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#avg), [GROUP_CONCAT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#group_concat), [ROW_NUMBER](https://www.coradb.ai/manual/sql/function/analysis_fn.html#row_number), [RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#rank), [LAG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#lag), ... | | [JSON functions](https://www.coradb.ai/manual/sql/function/json_fn.html) | [JSON_OBJECT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_object), [JSON_EXTRACT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_extract), [JSON_TABLE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_table), ... | | [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html) | [NODES](https://www.coradb.ai/manual/sql/function/graph_fn.html#nodes), [RELATIONSHIPS](https://www.coradb.ai/manual/sql/function/graph_fn.html#relationships), [PATH_SIZE](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_size), [PATH_COMP](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_comp), [LABEL](https://www.coradb.ai/manual/sql/function/graph_fn.html#label) and the [JSON graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html#json-graph-functions) | | [List functions](https://www.coradb.ai/manual/sql/function/list_fn.html) | Functions on lists and sequences, such as [FIRST](https://www.coradb.ai/manual/sql/function/list_fn.html#first), [LAST](https://www.coradb.ai/manual/sql/function/list_fn.html#last), [LIST_COMP](https://www.coradb.ai/manual/sql/function/list_fn.html#list_comp) | | [Conditional functions](https://www.coradb.ai/manual/sql/function/condition_fn.html) | [COALESCE](https://www.coradb.ai/manual/sql/function/condition_fn.html#coalesce), [DECODE](https://www.coradb.ai/manual/sql/function/condition_fn.html#decode), [GREATEST](https://www.coradb.ai/manual/sql/function/condition_fn.html#greatest), [IF](https://www.coradb.ai/manual/sql/function/condition_fn.html#if), [NVL](https://www.coradb.ai/manual/sql/function/condition_fn.html#ifnull-nvl), [NULLIF](https://www.coradb.ai/manual/sql/function/condition_fn.html#nullif), ... | | [LOB functions](https://www.coradb.ai/manual/sql/function/lob_fn.html) | [CHAR_TO_CLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_clob-clob_to_char), [CLOB_TO_CHAR](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_clob-clob_to_char), [CHAR_TO_BLOB](https://www.coradb.ai/manual/sql/function/lob_fn.html#char_to_blob-bit_to_blob-blob_to_bit), [CLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_length-blob_length), [BLOB_LENGTH](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_length-blob_length), [CLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_from_file-blob_from_file), [BLOB_FROM_FILE](https://www.coradb.ai/manual/sql/function/lob_fn.html#clob_from_file-blob_from_file) | | [Click counter functions](https://www.coradb.ai/manual/sql/function/clickcounter_fn.html) | `INCR`, `DECR` | | [ROWNUM functions](https://www.coradb.ai/manual/sql/function/rownum_fn.html) | [ROWNUM](https://www.coradb.ai/manual/sql/function/rownum_fn.html#rownum-inst_num), [INST_NUM](https://www.coradb.ai/manual/sql/function/rownum_fn.html#rownum-inst_num), [ORDERBY_NUM](https://www.coradb.ai/manual/sql/function/rownum_fn.html#orderby_num), [GROUPBY_NUM](https://www.coradb.ai/manual/sql/function/rownum_fn.html#groupby_num) | | [Information functions](https://www.coradb.ai/manual/sql/function/information_fn.html) | [DATABASE](https://www.coradb.ai/manual/sql/function/information_fn.html#database-schema), [CURRENT_USER](https://www.coradb.ai/manual/sql/function/information_fn.html#current_user-user), [LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id), [VERSION](https://www.coradb.ai/manual/sql/function/information_fn.html#version), [LABEL](https://www.coradb.ai/manual/sql/function/information_fn.html#label), ... | | [Encryption functions](https://www.coradb.ai/manual/sql/function/encryption_fn.html) | [MD5](https://www.coradb.ai/manual/sql/function/encryption_fn.html#md5), [SHA1](https://www.coradb.ai/manual/sql/function/encryption_fn.html#sha1), [SHA2](https://www.coradb.ai/manual/sql/function/encryption_fn.html#sha2) | | [Other functions](https://www.coradb.ai/manual/sql/function/other_fn.html) | [SLEEP](https://www.coradb.ai/manual/sql/function/other_fn.html#sleep), [SYS_GUID](https://www.coradb.ai/manual/sql/function/other_fn.html#sys_guid) | When a function receives an argument that cannot be converted to the type it expects, it returns an error, or `NULL` if the [return_null_on_function_errors](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes`. --- # Aggregate and analytic functions: SUM, AVG, COUNT, RANK, LAG, PERCENTILE_CONT and more Source: https://www.coradb.ai/manual/sql/function/analysis_fn.html **Aggregate functions** compute one value from a group of rows: with `GROUP BY` there is one result row per group, without it one row for the whole result. **Analytic functions** (window functions) compute a value for every row from a group of related rows, the *window*, defined by an `OVER` clause; the rows themselves are not collapsed. Most functions on this page can be used both ways: | Function | Aggregate | Analytic | Description | |---|---|---|---| | [AVG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#avg) | ✓ | ✓ | Average | | [COUNT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#count) | ✓ | ✓ | Number of rows or values | | [CUME_DIST](https://www.coradb.ai/manual/sql/function/analysis_fn.html#cume_dist) | ✓ | ✓ | Cumulative distribution | | [DENSE_RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#dense_rank) | | ✓ | Rank without gaps | | [FIRST_VALUE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#first_value) | | ✓ | First value of the window | | [GROUP_CONCAT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#group_concat) | ✓ | | Values joined into a string | | [JSON_ARRAYAGG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#json_arrayagg) | ✓ | | Values as a JSON array | | [JSON_OBJECTAGG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#json_objectagg) | ✓ | | Key/value pairs as a JSON object | | [LAG](https://www.coradb.ai/manual/sql/function/analysis_fn.html#lag) | | ✓ | Value from a previous row | | [LAST_VALUE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#last_value) | | ✓ | Last value of the window | | [LEAD](https://www.coradb.ai/manual/sql/function/analysis_fn.html#lead) | | ✓ | Value from a following row | | [MAX](https://www.coradb.ai/manual/sql/function/analysis_fn.html#max-min), [MIN](https://www.coradb.ai/manual/sql/function/analysis_fn.html#max-min) | ✓ | ✓ | Largest and smallest value | | [MEDIAN](https://www.coradb.ai/manual/sql/function/analysis_fn.html#median) | ✓ | ✓ | Median | | [NTH_VALUE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#nth_value) | | ✓ | *N*-th value of the window | | [NTILE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#ntile) | | ✓ | Bucket number | | [PERCENT_RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#percent_rank) | ✓ | ✓ | Relative rank | | [PERCENTILE_CONT](https://www.coradb.ai/manual/sql/function/analysis_fn.html#percentile_cont), [PERCENTILE_DISC](https://www.coradb.ai/manual/sql/function/analysis_fn.html#percentile_disc) | ✓ | ✓ | Percentile (interpolated or actual value) | | [RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#rank) | | ✓ | Rank with gaps after ties | | [ROW_NUMBER](https://www.coradb.ai/manual/sql/function/analysis_fn.html#row_number) | | ✓ | Sequential row number | | [STDDEV](https://www.coradb.ai/manual/sql/function/analysis_fn.html#stddev-stddev_pop), [STDDEV_POP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#stddev-stddev_pop), [STDDEV_SAMP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#stddev_samp) | ✓ | ✓ | Standard deviation | | [SUM](https://www.coradb.ai/manual/sql/function/analysis_fn.html#sum) | ✓ | ✓ | Sum | | [VARIANCE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#variance-var_pop), [VAR_POP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#variance-var_pop), [VAR_SAMP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#var_samp) | ✓ | ✓ | Variance | The [list function COLLECT_LIST](https://www.coradb.ai/manual/sql/function/list_fn.html#collect_list) is also an aggregate function. ## Aggregate functions An aggregate function returns one value per group. **NULL** values are ignored, except by `COUNT(*)`. Most aggregate functions accept **DISTINCT** (or its synonyms **DISTINCTROW** and **UNIQUE**) to use each different value only once; **ALL**, the default, uses every value. The brands *Diadora* and *Rab* manufacture 9 and 11 products. Some statistics per brand: ```sql SELECT b.name AS brand, COUNT(*) AS products, AVG(p.unit_price) AS avg_price, MIN(p.unit_price) AS min_price, MAX(p.unit_price) AS max_price, SUM(p.units_in_stock) AS stock, MEDIAN(p.unit_price) AS median_price FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name IN ('Diadora', 'Rab') GROUP BY b.name ORDER BY b.name; ``` | brand | products | avg_price | min_price | max_price | stock | median_price | |---|---|---|---|---|---|---| | Diadora | 9 | 50.333333333333336 | 28.00 | 69.00 | 282 | 47 | | Rab | 11 | 47.18181818181818 | 16.00 | 70.00 | 511 | 42 | To filter groups, use [HAVING](https://www.coradb.ai/manual/sql/query/select.html#group-by--having-clause). ## Analytic functions ```sql function_name ( [argument_list] ) OVER ( [PARTITION BY expression [, expression] ...] [ORDER BY expression [ASC | DESC] [, ...]] ) ``` - **PARTITION BY** divides the rows into groups (partitions); the function is computed separately in each. Without it, all rows of the result form one partition. - **ORDER BY** sorts the rows inside each partition. Ranking and offset functions use this order. For aggregate functions used with `OVER`, an **ORDER BY** makes the result cumulative: each row's value covers the rows from the start of the partition up to the current row and its ties. Without **ORDER BY**, the value covers the whole partition. - A constant such as `1` in **PARTITION BY** or **ORDER BY** refers to a column of the select list by position; a constant expression such as `1+0` is ignored. Explicit window frames (`ROWS BETWEEN ...`, `RANGE BETWEEN ...`) are not supported. Every product of the two brands next to the average, the highest price and the number of products of its brand: ```sql SELECT b.name AS brand, p.name AS product, p.unit_price AS price, AVG(p.unit_price) OVER (PARTITION BY b.name) AS brand_avg, MAX(p.unit_price) OVER (PARTITION BY b.name) AS brand_max, COUNT(*) OVER (PARTITION BY b.name) AS brand_products FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name IN ('Diadora', 'Rab') ORDER BY b.name, p.unit_price DESC, p.name; ``` | brand | product | price | brand_avg | brand_max | brand_products | |---|---|---|---|---|---| | Diadora | Abominable Hoodie | 69.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Neve Studio Dance Jacket | 69.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Circe Hooded Ice Fleece | 68.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Helena Hooded Fleece | 55.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Kenobi Trail Jacket | 47.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Viktor LumaTech Pant | 46.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Beaumont Summit Kit | 42.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Gobi HeatTec Tee | 29.00 | 50.333333333333336 | 69.00 | 9 | | Diadora | Bess Yoga Short | 28.00 | 50.333333333333336 | 69.00 | 9 | | Rab | Teton Pullover Hoodie | 70.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Ajax Full-Zip Sweatshirt | 69.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Orestes Yoga Pant | 66.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Riona Full Zip Jacket | 60.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Proteus Fitness Jackshirt | 45.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Beaumont Summit Kit | 42.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Oslo Trek Hoodie | 42.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Stark Fundamental Hoodie | 42.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Strike Endurance Tee | 39.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Gabrielle Micro Sleeve Top | 28.00 | 47.18181818181818 | 70.00 | 11 | | Rab | Pursuit Lumaflex Tone Band | 16.00 | 47.18181818181818 | 70.00 | 11 | An analytic function can be applied to the result of a grouped query in a derived table. The orders of 2025 per month, with the previous and next month, a running total and the rank of each month: ```sql SELECT mon, orders, LAG(orders) OVER (ORDER BY mon) AS prev_month, orders - LAG(orders) OVER (ORDER BY mon) AS diff, LEAD(orders, 1, 0) OVER (ORDER BY mon) AS next_month, SUM(orders) OVER (ORDER BY mon) AS running_total, RANK() OVER (ORDER BY orders DESC) AS rnk FROM (SELECT MONTH(order_date) AS mon, COUNT(*) AS orders FROM orders WHERE YEAR(order_date) = 2025 GROUP BY MONTH(order_date)) t ORDER BY mon; ``` | mon | orders | prev_month | diff | next_month | running_total | rnk | |---|---|---|---|---|---|---| | 1 | 51 | NULL | NULL | 50 | 51 | 9 | | 2 | 50 | 51 | -1 | 46 | 101 | 10 | | 3 | 46 | 50 | -4 | 54 | 147 | 12 | | 4 | 54 | 46 | 8 | 56 | 201 | 8 | | 5 | 56 | 54 | 2 | 62 | 257 | 7 | | 6 | 62 | 56 | 6 | 50 | 319 | 6 | | 7 | 50 | 62 | -12 | 69 | 369 | 10 | | 8 | 69 | 50 | 19 | 67 | 438 | 4 | | 9 | 67 | 69 | -2 | 76 | 505 | 5 | | 10 | 76 | 67 | 9 | 110 | 581 | 3 | | 11 | 110 | 76 | 34 | 95 | 691 | 1 | | 12 | 95 | 110 | -15 | 0 | 786 | 2 | With an empty `OVER ()`, the window is the whole result. The share of each year in all orders: ```sql SELECT yr, orders, shipping, SUM(orders) OVER () AS all_orders, ROUND(100.0 * orders / SUM(orders) OVER (), 1) AS pct FROM (SELECT YEAR(order_date) AS yr, COUNT(*) AS orders, SUM(shipping_cost) AS shipping FROM orders GROUP BY YEAR(order_date)) t ORDER BY yr; ``` | yr | orders | shipping | all_orders | pct | |---|---|---|---|---| | 2021 | 416 | 6754.91 | 2910 | 14.3 | | 2022 | 482 | 7880.73 | 2910 | 16.6 | | 2023 | 551 | 9825.75 | 2910 | 18.9 | | 2024 | 675 | 11440.27 | 2910 | 23.2 | | 2025 | 786 | 13346.04 | 2910 | 27 | **CUME_DIST**, **DENSE_RANK**, **LAG**, **LEAD**, **NTILE**, **PERCENT_RANK**, **RANK** and **ROW_NUMBER** need an **ORDER BY** in the `OVER` clause; without it, an error is raised or the result has no defined order. Most examples below use the nine Diadora products; two of them share the highest price. ## AVG ```sql AVG ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) AVG ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) OVER ( analytic_clause ) ``` Returns the average of the non-**NULL** values of a numeric *expression*. **Return type:** DOUBLE See the [examples above](https://www.coradb.ai/manual/sql/function/analysis_fn.html#aggregate-functions). ## COUNT ```sql COUNT ( * ) COUNT ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) COUNT ( * ) OVER ( analytic_clause ) COUNT ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) OVER ( analytic_clause ) ``` `COUNT(*)` counts rows; `COUNT(expression)` counts the rows where *expression* is not **NULL**; `COUNT(DISTINCT expression)` counts the different non-**NULL** values. **Return type:** INTEGER ```sql SELECT COUNT(*) AS orders, COUNT(shipped_date) AS shipped, COUNT(DISTINCT customer_id) AS customers FROM orders; ``` | orders | shipped | customers | |---|---|---| | 2910 | 2901 | 650 | Nine orders have not been shipped yet: their `shipped_date` is **NULL**. ## CUME_DIST ```sql CUME_DIST ( expression [, expression] ... ) WITHIN GROUP ( ORDER BY ... ) CUME_DIST () OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The cumulative distribution: the fraction of rows that come before or together with the current row in the given order. The result is greater than 0 and at most 1. **Return type:** DOUBLE As an aggregate function, it returns the cumulative distribution that a hypothetical row with the given values would have in the group. As an analytic function, it returns the value for each row. See [PERCENT_RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#percent_rank) for the difference between the two. ```sql SELECT p.name AS product, p.unit_price AS price, CUME_DIST() OVER (ORDER BY p.unit_price) AS cume, PERCENT_RANK() OVER (ORDER BY p.unit_price) AS pct_rank, NTILE(3) OVER (ORDER BY p.unit_price DESC) AS tier FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora' ORDER BY p.unit_price DESC, p.name; ``` | product | price | cume | pct_rank | tier | |---|---|---|---|---| | Abominable Hoodie | 69.00 | 1 | 0.875 | 1 | | Neve Studio Dance Jacket | 69.00 | 1 | 0.875 | 1 | | Circe Hooded Ice Fleece | 68.00 | 0.7777777777777778 | 0.75 | 1 | | Helena Hooded Fleece | 55.00 | 0.6666666666666666 | 0.625 | 2 | | Kenobi Trail Jacket | 47.00 | 0.5555555555555556 | 0.5 | 2 | | Viktor LumaTech Pant | 46.00 | 0.4444444444444444 | 0.375 | 2 | | Beaumont Summit Kit | 42.00 | 0.3333333333333333 | 0.25 | 3 | | Gobi HeatTec Tee | 29.00 | 0.2222222222222222 | 0.125 | 3 | | Bess Yoga Short | 28.00 | 0.1111111111111111 | 0 | 3 | Where would a product priced at 50 fall among the Diadora products? ```sql SELECT CUME_DIST(50) WITHIN GROUP (ORDER BY p.unit_price) AS cume_50, PERCENT_RANK(50) WITHIN GROUP (ORDER BY p.unit_price) AS pct_rank_50 FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | cume_50 | pct_rank_50 | |---|---| | 0.6 | 0.5555555555555556 | With the hypothetical row there are 10 rows, and 6 of them are priced at 50 or less: 6/10 = 0.6. Five rows are cheaper: 5/9. ## DENSE_RANK ```sql DENSE_RANK () OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The rank of the row in its partition. Rows with equal values get the same rank, and the next rank follows without a gap (1, 1, 2, ...). **Return type:** INTEGER ```sql SELECT p.name AS product, p.unit_price AS price, RANK() OVER (ORDER BY p.unit_price DESC) AS rnk, DENSE_RANK() OVER (ORDER BY p.unit_price DESC) AS drnk, ROW_NUMBER() OVER (ORDER BY p.unit_price DESC, p.name) AS rn FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora' ORDER BY p.unit_price DESC, p.name; ``` | product | price | rnk | drnk | rn | |---|---|---|---|---| | Abominable Hoodie | 69.00 | 1 | 1 | 1 | | Neve Studio Dance Jacket | 69.00 | 1 | 1 | 2 | | Circe Hooded Ice Fleece | 68.00 | 3 | 2 | 3 | | Helena Hooded Fleece | 55.00 | 4 | 3 | 4 | | Kenobi Trail Jacket | 47.00 | 5 | 4 | 5 | | Viktor LumaTech Pant | 46.00 | 6 | 5 | 6 | | Beaumont Summit Kit | 42.00 | 7 | 6 | 7 | | Gobi HeatTec Tee | 29.00 | 8 | 7 | 8 | | Bess Yoga Short | 28.00 | 9 | 8 | 9 | ## FIRST_VALUE ```sql FIRST_VALUE ( expression ) [ {RESPECT | IGNORE} NULLS ] OVER ( analytic_clause ) ``` The value of *expression* in the first row of the window. With **IGNORE NULLS**, the first non-**NULL** value. The default is **RESPECT NULLS**. **Return type:** the type of *expression* ```sql SELECT p.name AS product, p.unit_price AS price, FIRST_VALUE(p.name) OVER (ORDER BY p.unit_price DESC, p.name) AS most_expensive, LAST_VALUE(p.name) OVER (ORDER BY p.unit_price DESC, p.name) AS last_so_far, NTH_VALUE(p.name, 2) OVER (ORDER BY p.unit_price DESC, p.name) AS second_one FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora' ORDER BY p.unit_price DESC, p.name; ``` | product | price | most_expensive | last_so_far | second_one | |---|---|---|---|---| | Abominable Hoodie | 69.00 | Abominable Hoodie | Abominable Hoodie | NULL | | Neve Studio Dance Jacket | 69.00 | Abominable Hoodie | Neve Studio Dance Jacket | Neve Studio Dance Jacket | | Circe Hooded Ice Fleece | 68.00 | Abominable Hoodie | Circe Hooded Ice Fleece | Neve Studio Dance Jacket | | Helena Hooded Fleece | 55.00 | Abominable Hoodie | Helena Hooded Fleece | Neve Studio Dance Jacket | | Kenobi Trail Jacket | 47.00 | Abominable Hoodie | Kenobi Trail Jacket | Neve Studio Dance Jacket | | Viktor LumaTech Pant | 46.00 | Abominable Hoodie | Viktor LumaTech Pant | Neve Studio Dance Jacket | | Beaumont Summit Kit | 42.00 | Abominable Hoodie | Beaumont Summit Kit | Neve Studio Dance Jacket | | Gobi HeatTec Tee | 29.00 | Abominable Hoodie | Gobi HeatTec Tee | Neve Studio Dance Jacket | | Bess Yoga Short | 28.00 | Abominable Hoodie | Bess Yoga Short | Neve Studio Dance Jacket | Because of the **ORDER BY**, the window of each row ends at the current row: **LAST_VALUE** returns the current row's value, and **NTH_VALUE**(..., 2) is **NULL** in the first row, whose window has only one row. **IGNORE NULLS** skips **NULL** values. Order 455 has not been shipped; `LAST_VALUE ... IGNORE NULLS` carries the last known shipping date forward: ```sql SELECT id, shipped_date, FIRST_VALUE(shipped_date) OVER (ORDER BY id DESC) AS fv, LAST_VALUE(shipped_date) IGNORE NULLS OVER (ORDER BY id) AS last_known FROM orders WHERE id BETWEEN 453 AND 457 ORDER BY id; ``` | id | shipped_date | fv | last_known | |---|---|---|---| | 453 | 2022-08-24 | 2023-11-04 | 2022-08-24 | | 454 | 2023-01-29 | 2023-11-04 | 2023-01-29 | | 455 | NULL | 2023-11-04 | 2023-01-29 | | 456 | 2025-01-04 | 2023-11-04 | 2025-01-04 | | 457 | 2023-11-04 | 2023-11-04 | 2023-11-04 | ## GROUP_CONCAT ```sql GROUP_CONCAT ( [DISTINCT] expression [ORDER BY {column | position} [ASC | DESC]] [SEPARATOR string] ) ``` An aggregate function that joins the non-**NULL** values of the group into one string, separated by *string* (a comma by default). It returns **NULL** if there are no non-**NULL** values. **Return type:** STRING The result is limited to [group_concat_max_len](https://www.coradb.ai/manual/admin/config_sql.html#group_concat_max_len) bytes (1,024 by default) and must also fit in [string_max_size_bytes](https://www.coradb.ai/manual/admin/config_sql.html#string_max_size_bytes). ```sql SELECT b.name AS brand, GROUP_CONCAT(p.name ORDER BY p.name SEPARATOR ', ') AS products FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name IN ('Diadora', 'Rab') GROUP BY b.name ORDER BY b.name; ``` | brand | products | |---|---| | Diadora | Abominable Hoodie, Beaumont Summit Kit, Bess Yoga Short, Circe Hooded Ice Fleece, Gobi HeatTec Tee, Helena Hooded Fleece, Kenobi Trail Jacket, Neve Studio Dance Jacket, Viktor LumaTech Pant | | Rab | Ajax Full-Zip Sweatshirt, Beaumont Summit Kit, Gabrielle Micro Sleeve Top, Orestes Yoga Pant, Oslo Trek Hoodie, Proteus Fitness Jackshirt, Pursuit Lumaflex Tone Band, Riona Full Zip Jacket, Stark Fundamental Hoodie, Strike Endurance Tee, Teton Pullover Hoodie | **DISTINCT** removes duplicates; here the two products priced at 69.00 give one value: ```sql SELECT GROUP_CONCAT(DISTINCT p.unit_price ORDER BY p.unit_price DESC) AS prices FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | prices | |---| | 69.00,68.00,55.00,47.00,46.00,42.00,29.00,28.00 | ## JSON_ARRAYAGG ```sql JSON_ARRAYAGG ( expression ) ``` An aggregate function that returns the values of the group as a JSON array. NUMERIC values become JSON doubles. **Return type:** JSON ## JSON_OBJECTAGG ```sql JSON_OBJECTAGG ( key, value ) ``` An aggregate function that returns a JSON object with one member per row, using *key* as the member name and *value* as its value. **Return type:** JSON ```sql SELECT JSON_ARRAYAGG(p.unit_price) AS prices, JSON_OBJECTAGG(p.name, p.units_in_stock) AS stock FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora' AND p.unit_price > 60; ``` | prices | stock | |---|---| | [69.0,68.0,69.0] | {"Abominable Hoodie":29,"Circe Hooded Ice Fleece":113,"Neve Studio Dance Jacket":22} | The order of the array elements is not defined. See also the [JSON functions](https://www.coradb.ai/manual/sql/function/json_fn.html). ## LAG ```sql LAG ( expression [, offset [, default]] ) OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The value of *expression* in the row *offset* rows before the current row (1 by default). If there is no such row, *default* is returned (**NULL** by default). **Return type:** the type of *expression* See the [monthly orders example](https://www.coradb.ai/manual/sql/function/analysis_fn.html#analytic-functions). ## LAST_VALUE ```sql LAST_VALUE ( expression ) [ {RESPECT | IGNORE} NULLS ] OVER ( analytic_clause ) ``` The value of *expression* in the last row of the window. With an **ORDER BY**, the window ends at the current row and its ties, so the result is usually the current row's value; without **ORDER BY**, it is the last row of the partition. With **IGNORE NULLS**, the last non-**NULL** value. **Return type:** the type of *expression* See the examples under [FIRST_VALUE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#first_value). ## LEAD ```sql LEAD ( expression [, offset [, default]] ) OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The value of *expression* in the row *offset* rows after the current row (1 by default). If there is no such row, *default* is returned (**NULL** by default). **Return type:** the type of *expression* See the [monthly orders example](https://www.coradb.ai/manual/sql/function/analysis_fn.html#analytic-functions): `LEAD(orders, 1, 0)` returns 0 for December. ## MAX, MIN ```sql MAX ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) MIN ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) MAX ( ... ) OVER ( analytic_clause ) MIN ( ... ) OVER ( analytic_clause ) ``` The largest and smallest non-**NULL** value of *expression*: a number, a string or a date/time value. **Return type:** the type of *expression* See the [examples above](https://www.coradb.ai/manual/sql/function/analysis_fn.html#aggregate-functions). ## MEDIAN ```sql MEDIAN ( expression ) MEDIAN ( expression ) OVER ( [PARTITION BY ...] ) ``` The median of the non-**NULL** values: the middle value, or the average of the two middle values for an even number of values. It is the same as `PERCENTILE_CONT(0.5)`. *expression* must be a number or a date/time value. **Return type:** DOUBLE, or a date/time type for date/time values Products of the two brands priced at 60 or more, with the median price and the 50th percentile within each brand: ```sql SELECT b.name AS brand, p.name AS product, p.unit_price AS price, MEDIAN(p.unit_price) OVER (PARTITION BY b.name) AS brand_median, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY p.unit_price) OVER (PARTITION BY b.name) AS p50_disc, RANK() OVER (PARTITION BY b.name ORDER BY p.unit_price DESC) AS rnk FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name IN ('Diadora', 'Rab') AND p.unit_price >= 60 ORDER BY b.name, p.unit_price DESC, p.name; ``` | brand | product | price | brand_median | p50_disc | rnk | |---|---|---|---|---|---| | Diadora | Abominable Hoodie | 69.00 | 69 | 69 | 1 | | Diadora | Neve Studio Dance Jacket | 69.00 | 69 | 69 | 1 | | Diadora | Circe Hooded Ice Fleece | 68.00 | 69 | 69 | 3 | | Rab | Teton Pullover Hoodie | 70.00 | 67.5 | 66 | 1 | | Rab | Ajax Full-Zip Sweatshirt | 69.00 | 67.5 | 66 | 2 | | Rab | Orestes Yoga Pant | 66.00 | 67.5 | 66 | 3 | | Rab | Riona Full Zip Jacket | 60.00 | 67.5 | 66 | 4 | For Rab, the median of 60, 66, 69 and 70 is the average of 66 and 69, 67.5; **PERCENTILE_DISC** returns the actual value 66. ## NTH_VALUE ```sql NTH_VALUE ( expression, N ) [ {RESPECT | IGNORE} NULLS ] OVER ( analytic_clause ) ``` The value of *expression* in the *N*-th row of the window, or **NULL** if the window has fewer than *N* rows. **Return type:** the type of *expression* See the examples under [FIRST_VALUE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#first_value). ## NTILE ```sql NTILE ( number_of_buckets ) OVER ( [PARTITION BY ...] ORDER BY ... ) ``` Divides the ordered rows of each partition into *number_of_buckets* groups of (nearly) equal size and returns the group number, from 1. When the rows do not divide evenly, the first groups get one row more. **Return type:** INTEGER **NTILE** makes groups with the same number of rows; [WIDTH_BUCKET](https://www.coradb.ai/manual/sql/function/numeric_fn.html#width_bucket) makes groups that cover equal ranges of values. See the `tier` column in the [CUME_DIST example](https://www.coradb.ai/manual/sql/function/analysis_fn.html#cume_dist): the nine products fall into three tiers of three. ## PERCENT_RANK ```sql PERCENT_RANK ( expression [, expression] ... ) WITHIN GROUP ( ORDER BY ... ) PERCENT_RANK () OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The relative rank of a row: `(RANK - 1) / (rows in the partition - 1)`, from 0 to 1. As an aggregate function, the relative rank that a hypothetical row with the given values would have. **Return type:** DOUBLE **CUME_DIST** counts the rows up to and including the current row, so its smallest value is above 0 and its largest is 1. **PERCENT_RANK** counts the rows before the current row, so the first row gets 0. See the [CUME_DIST examples](https://www.coradb.ai/manual/sql/function/analysis_fn.html#cume_dist). ## PERCENTILE_CONT ```sql PERCENTILE_CONT ( percentile ) WITHIN GROUP ( ORDER BY expression [ASC | DESC] ) [ OVER ( PARTITION BY ... ) ] ``` The value at *percentile* (from 0 to 1) of the ordered values, assuming a continuous distribution: if the position falls between two values, the result is interpolated between them. **NULL** values are ignored. **Return type:** DOUBLE ## PERCENTILE_DISC ```sql PERCENTILE_DISC ( percentile ) WITHIN GROUP ( ORDER BY expression [ASC | DESC] ) [ OVER ( PARTITION BY ... ) ] ``` The first value whose cumulative distribution is at least *percentile*: always one of the actual values. **Return type:** the type of *expression* ```sql SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY p.unit_price) AS p50_cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY p.unit_price) AS p50_disc, PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY p.unit_price) AS p25_cont, PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY p.unit_price) AS p25_disc FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | p50_cont | p50_disc | p25_cont | p25_disc | |---|---|---|---| | 47 | 47 | 42 | 42 | With nine values, the 50th and 25th percentiles fall exactly on the 5th and 3rd values, so both functions agree; the [MEDIAN example](https://www.coradb.ai/manual/sql/function/analysis_fn.html#median) shows a case where they differ. ## RANK ```sql RANK () OVER ( [PARTITION BY ...] ORDER BY ... ) ``` The rank of the row in its partition. Rows with equal values get the same rank, and the following ranks are skipped (1, 1, 3, ...). **Return type:** INTEGER See the [example under DENSE_RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#rank-example). ## ROW_NUMBER ```sql ROW_NUMBER () OVER ( [PARTITION BY ...] ORDER BY ... ) ``` A sequential number for each row in its partition, starting at 1. Rows with equal sort values get different numbers; add columns to the **ORDER BY** to make the numbering deterministic. **Return type:** INTEGER See the [example under DENSE_RANK](https://www.coradb.ai/manual/sql/function/analysis_fn.html#rank-example). ## STDDEV, STDDEV_POP ```sql STDDEV ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) STDDEV_POP ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) STDDEV ( ... ) OVER ( analytic_clause ) STDDEV_POP ( ... ) OVER ( analytic_clause ) ``` The population standard deviation: the square root of [VAR_POP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#variance-var_pop). **STDDEV** and **STDDEV_POP** are synonyms. **Return type:** DOUBLE ## STDDEV_SAMP ```sql STDDEV_SAMP ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) STDDEV_SAMP ( ... ) OVER ( analytic_clause ) ``` The sample standard deviation: the square root of [VAR_SAMP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#var_samp). **Return type:** DOUBLE ```sql SELECT STDDEV(p.unit_price) AS sd, STDDEV_POP(p.unit_price) AS sd_pop, STDDEV_SAMP(p.unit_price) AS sd_samp, VARIANCE(p.unit_price) AS var, VAR_POP(p.unit_price) AS var_pop, VAR_SAMP(p.unit_price) AS var_samp FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | sd | sd_pop | sd_samp | var | var_pop | var_samp | |---|---|---|---|---|---| | 15.216949614017759 | 15.216949614017759 | 16.140012391568973 | 231.5555555555552 | 231.5555555555552 | 260.5 | ## SUM ```sql SUM ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) SUM ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) OVER ( analytic_clause ) ``` The sum of the non-**NULL** values of a numeric *expression*. **Return type:** the type of *expression* > **Warning:** > The result has the type of the argument. A sum over a **SMALLINT** column (such as `units_in_stock`) is a **SMALLINT** and overflows above 32,767; cast the argument to a larger type, for example `SUM(CAST(units_in_stock AS INT))`. See the `stock` column in the [aggregate example](https://www.coradb.ai/manual/sql/function/analysis_fn.html#aggregate-functions), and the running total and `OVER ()` examples under [Analytic functions](https://www.coradb.ai/manual/sql/function/analysis_fn.html#analytic-functions). ## VARIANCE, VAR_POP ```sql VARIANCE ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) VAR_POP ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) VARIANCE ( ... ) OVER ( analytic_clause ) VAR_POP ( ... ) OVER ( analytic_clause ) ``` The population variance: the average of the squared differences from the mean, `SUM((x - AVG(x))²) / COUNT(x)`. **VARIANCE** and **VAR_POP** are synonyms. **Return type:** DOUBLE ## VAR_SAMP ```sql VAR_SAMP ( [DISTINCT | DISTINCTROW | UNIQUE | ALL] expression ) VAR_SAMP ( ... ) OVER ( analytic_clause ) ``` The sample variance: `SUM((x - AVG(x))²) / (COUNT(x) - 1)`. **Return type:** DOUBLE See the [example under STDDEV_SAMP](https://www.coradb.ai/manual/sql/function/analysis_fn.html#stddev_samp). ## See also - [GROUP BY ... HAVING](https://www.coradb.ai/manual/sql/query/select.html#group-by--having-clause) - [COLLECT_LIST and the list functions](https://www.coradb.ai/manual/sql/function/list_fn.html) - [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html) --- # Arithmetic operators Source: https://www.coradb.ai/manual/sql/function/arithmetic_op.html For arithmetic operators, there are binary operators for addition, subtraction, multiplication, or division, and unary operators to represent whether the number is positive or negative. The unary operators to represent the numbers' positive/negative status have higher priority over the binary operators. ```text ::= bit_string | character_string | numeric_value | date-time_value | collection_value | NULL ::= | ::= + | - | * | { / | DIV } | { % | MOD } ::= UNION | DIFFERENCE | { INTERSECT | INTERSECTION } ``` - \<*expression*\>: Declares the mathematical operation to be calculated. - \<*mathematical_operator*\>: A operator that performs an operation the arithmetic and the set operators are applicable. - \<*set_arithmetic_operator*\>: A set arithmetic operator that performs operations such as union, difference and intersection on collection type operands. - \<*arithmetic_operator*\>: An operator to perform the four fundamental arithmetic operations. The following table shows the arithmetic operators supported by CoraDB and their return values. **Arithmetic operators** | Arithmetic operator \| Description | | | Operator | Return value | |------------------------------------|-----|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|--------------| | **+** \| Addition | | | 1+2 | 3 | | **-** | | Subtraction | 1-2 | -1 | | **\*** | | Multiplication | 1\*2 | 2 | | **/** | | Division. Returns quotient. | 1/2.0 | 0.500000000 | | **DIV** | | Division. Returns quotient. | 1 DIV 2 | 0 | | **%** , **MOD** | | Division. Returns quotient. An operator must be an integer type, and it always returns integer. If an operand is real number, the **MOD** function can be used. | 1 % 2 1 MOD 2 | 1 | ## Arithmetic operations and type casting of numeric data types All numeric data types can be used for arithmetic operations. The result type of the operation differs depending on the data types of the operands and the type of the operation. The following table shows the result data types of addition/subtraction/multiplication for each operand type. **Result data type by operand type** | | INT | NUMERIC | FLOAT | DOUBLE | |-------------|---------------|--------------------------------------|--------|--------| | **INT** | INT or BIGINT | NUMERIC | FLOAT | DOUBLE | | **NUMERIC** | NUMERIC | NUMERIC (p and s are also converted) | DOUBLE | DOUBLE | | **FLOAT** | FLOAT | DOUBLE | FLOAT | DOUBLE | | **DOUBLE** | DOUBLE | DOUBLE | DOUBLE | DOUBLE | Note that the result type of the operation does not change if all operands are of the same data type but type casting occurs exceptionally in division operations. An error occurs when a denominator, i.e. a divisor, is 0. The following table shows the total number of digits (*p*) and the number of digits after the decimal point (*s*) of the operation results when all operands are of the **NUMERIC** type. **Result of NUMERIC type operation** | Operation | Maximum precision | Maximum scale | |------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------| | N(p1, s1) + N(p2, s2) | max(p1-s1, p2-s2)+max(s1, s2) +1 | Max(s1, s2) | | N(p1, s1) - N(p2, s2) | max(p1-s1, p2-s2)+max(s1, s2) | Max(s1, s2) | | N(p1, s1) \* N(p2, s2) | p1+p2+1 | s1+s2 | | N(p1, s1) / N(p2, s2) | Let Pt = p1+max(s1, s2) + s2 - s1 when s2 \> 0 and Pt = p1 in other cases; St = s1 when s1 \> s2 and s2 in other cases; \| The number of decimal places is min(9-St, 38-Pt) + St when St \< 9 and St in other cases. \| | | **Example** ```sql --int * int SELECT 123*123; ``` | 123*123 | |---| | 15129 | ```sql -- int * int returns overflow error SELECT (1234567890123*1234567890123); ``` ```text ERROR: Data overflow on data type bigint. ``` ```sql -- int * numeric returns numeric type SELECT (1234567890123*CAST(1234567890123 AS NUMERIC(15,2))); ``` | (1234567890123*CAST(1234567890123 AS NUMERIC(15,2))) | |---| | 1524157875322755800955129.00 | ```sql -- int * float returns float type SELECT (1234567890123*CAST(1234567890123 AS FLOAT)); ``` | (1234567890123*CAST(1234567890123 AS FLOAT)) | |---| | 1.524158e+24 | ```sql -- int * double returns double type SELECT (1234567890123*CAST(1234567890123 AS DOUBLE)); ``` | (1234567890123*CAST(1234567890123 AS DOUBLE)) | |---| | 1.524157875322755e+24 | ```sql -- numeric * numeric returns numeric type SELECT (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS NUMERIC(15,2))); ``` | (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS NUMERIC(15,2))) | |---| | 1524157875322755800955129.0000 | ```sql -- numeric * float returns double type SELECT (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS FLOAT)); ``` | (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS FLOAT)) | |---| | 1.524157954716582e+24 | ```sql -- numeric * double returns double type SELECT (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS DOUBLE)); ``` | (CAST(1234567890123 AS NUMERIC(15,2))*CAST(1234567890123 AS DOUBLE)) | |---| | 1.524157875322755e+24 | ```sql -- float * float returns float type SELECT (CAST(1234567890123 AS FLOAT)*CAST(1234567890123 AS FLOAT)); ``` | (CAST(1234567890123 AS FLOAT)*CAST(1234567890123 AS FLOAT)) | |---| | 1.524158e+24 | ```sql -- float * double returns float type SELECT (CAST(1234567890123 AS FLOAT)*CAST(1234567890123 AS DOUBLE)); ``` | (CAST(1234567890123 AS FLOAT)*CAST(1234567890123 AS DOUBLE)) | |---| | 1.524157954716582e+24 | ```sql -- double * double returns float type SELECT (CAST(1234567890123 AS DOUBLE)*CAST(1234567890123 AS DOUBLE)); ``` | (CAST(1234567890123 AS DOUBLE)*CAST(1234567890123 AS DOUBLE)) | |---| | 1.524157875322755e+24 | ```sql -- int / int returns int type without type conversion or rounding SELECT 100100/100000; ``` | 100100/100000 | |---| | 1 | ```sql -- int / int returns int type without type conversion or rounding SELECT 100100/200200; ``` | 100100/200200 | |---| | 0 | ```sql -- int / zero returns error SELECT 100100/(100100-100100); ``` ```text ERROR: Attempt to divide by zero. ``` ## Arithmetic operations and type casting of DATE/TIME data types If all operands are date/time type, only a subtraction operation is allowed and its return value is **BIGINT** . Note that the unit of the operation differs depending on the types of the operands. Both addition and subtraction operations are allowed in case of date/time and integer types In this case, operation units and return values are date/time data type. The following table shows operations allowed for each operand type, and their result types. **Allowable operation and result data type by operand type** | | **TIME** **(in seconds)** | **DATE** **(in day)** | **TIMESTAMP** **(in seconds)** | **DATETIME** **(in milliseconds)** | **INT** | |---------------|-----------------------------------------------------|-----------------------------------------------------|----------------------------------------------------------|---------------------------------------------------------|----------------------------------------------------------| | **TIME** | A subtraction is allowed. **BIGINT** | X | X | X | An addition and a subtraction are allowed. **TIME** | | **DATE** | X | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | An addition and a subtraction are allowed. **DATE** | | **TIMESTAMP** | X | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | An addition and a subtraction are allowed. **TIMESTAMP** | | **DATETIME** | X | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | A subtraction is allowed. **BIGINT** | An addition and a subtraction are allowed. **DATETIME** | | **INT** | An addition and a subtraction are allowed. **TIME** | An addition and a subtraction are allowed. **DATE** | An addition and a subtraction are allowed. **TIMESTAMP** | An addition and a subtraction are allowed. **DATETIME** | All operations are allowed. | > **Note:** > If any of the date/time arguments contains **NULL**, **NULL** is returned. **Example** Adding a number to a date/time value adds days to a `DATE`, seconds to a `TIME` and `TIMESTAMP`, and milliseconds to a `DATETIME`: ```sql SELECT TIME'23:59:55' + 10, DATE'2025-12-25' + 10, TIMESTAMP'2025-12-31 23:59:55' + 10, DATETIME'2025-12-31 23:59:59.995' + 10; ``` | TIME'23:59:55' + 10 | DATE'2025-12-25' + 10 | TIMESTAMP'2025-12-31 23:59:55' + 10 | DATETIME'2025-12-31 23:59:59.995' + 10 | |---|---|---|---| | 00:00:05 | 2026-01-04 | 2026-01-01 00:00:05 | 2026-01-01 00:00:00.005 | ```sql SELECT DATETIME '09/01/2009 03:30:30.001 pm'- TIMESTAMP '08/31/2009 03:30:30 pm'; ``` | DATETIME '09/01/2009 03:30:30.001 pm'- TIMESTAMP '08/31/2009 03:30:30 pm' | |---| | 86400001 | ```sql SELECT TIMESTAMP '09/01/2009 03:30:30 pm'- TIMESTAMP '08/31/2009 03:30:30 pm'; ``` | TIMESTAMP '09/01/2009 03:30:30 pm'- TIMESTAMP '08/31/2009 03:30:30 pm' | |---| | 86400 | ### Behavior related to timezone parameters TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONE data types stores internally UNIX epoch values (number of seconds elapsed from 1970). When leap second is used (tz_leap_second_support is set to yes, see [Timezone parameter](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter)), they may contain virtual date-time values. ```sql Virtual date-time Unix timestamp 2008-12-31 23:59:58 -> 79399951 2008-12-31 23:59:59 -> 79399952 2008-12-31 23:59:60 -> 79399953 -> not real date (introduced by leap second) 2009-01-01 00:00:00 -> 79399954 2009-01-01 00:00:01 -> 79399955 ``` Arithmetic operations with TIMESTAMP and TIMESTAMPLTZ values are performed directly on Unix epoch values, and epoch values that correspond to non-existing date/time values are allowed. With leap-second support enabled, the following comparison is therefore false, because it compares the Unix timestamps 79399952 and 79399953: ```sql SELECT TIMESTAMPLTZ'2008-12-31 23:59:59 UTC' = TIMESTAMPLTZ'2008-12-31 23:59:59 UTC' + 1; ``` When the same values are TIMESTAMPTZ, the result of the addition is adjusted to a valid date-time, so the two values are equal. Adding one second to `TIMESTAMPLTZ'2008-12-31 23:59:59 UTC'` is displayed as `11:59:59 PM 12/31/2008`, the closest real time, although its epoch value is one second later. Since '2008-12-31 23:59:60 UTC' corresponding to Unix timestamp value 79399953 is not a real date, the immediately preceding value is used. Internally, it is equivalent to the value ('2008-12-31 23:59:60 UTC'). TIMESTAMP WITH TIME ZONE data type contains both a UNIX timestamp and a timezone identifier. Arithmetic on TIMESTAMPTZ is also performed on UNIX timestamp part value, but is followed by an automatic adjusting operation. The presence of timezone identifier (which includes region, offset and daylight saving), requires the TIMESTAMPTZ object to be a valid date-time. The operation timestamptz'2008-12-31 23:59:59 UTC'+1 implies an automatic validation-conversion: instead of (79399953, UTC) which is not a valid date-time the value is automatically converted to (79399952,UTC) which corresponds to '2008-12-31 23:59:59 UTC'. After each arithmetic operation implying DATETIMETZ and TIMESTAMPTZ, CoraDB performs an automatic adjustment of result value which involves: - Adjusting the timezone identifier : adding a number of seconds to a date with timezone may lead to change of internally stored offset rule, daylight saving rule, hence the timezone identifier must be updated - Adjusting the Unix timestamp (only for TIMESTAMPTZ): virtual date-time values (when leap-second is enabled) are always converted to the immediately preceding Unix timestamp value. --- # Bit functions and operators Source: https://www.coradb.ai/manual/sql/function/bit_fn.html ## Bitwise operators Bitwise operators work on the bits of integer values. The operands must be integers (`BIT` values are not allowed); other numeric types are converted to `BIGINT`, and the result is a `BIGINT`. | Operator | Operation | Example | Result | |---|---|---|---:| | `&` | Bitwise AND | `17 & 3` | 1 | | `\|` | Bitwise OR | `17 \| 3` | 19 | | `^` | Bitwise XOR | `17 ^ 3` | 18 | | `~` | Bitwise NOT (unary): inverts every bit | `~17` | -18 | | `<<` | Shift left by the number of bits on the right | `17 << 3` | 136 | | `>>` | Shift right by the number of bits on the right | `17 >> 3` | 2 | ## BIT_AND, BIT_OR, BIT_XOR ```text BIT_AND(expr) BIT_OR(expr) BIT_XOR(expr) ``` Aggregate functions that combine the values of an integer expression over all rows with bitwise AND, OR or XOR. If no row qualifies, the result is `NULL`. **Return type:** BIGINT. The products with ids 1, 3 and 5 give the same results as the operators applied to those numbers: ```sql SELECT 1&3&5, BIT_AND(id), 1|3|5, BIT_OR(id), 1^3^5, BIT_XOR(id) FROM product WHERE id IN (1, 3, 5); ``` | 1&3&5 | bit_and(id) | 1\|3\|5 | bit_or(id) | 1^3^5 | bit_xor(id) | |---:|---:|---:|---:|---:|---:| | 1 | 1 | 7 | 7 | 7 | 7 | A typical use is combining flags stored as bits: `BIT_OR(flags)` tells which flags are set in at least one row, `BIT_AND(flags)` which are set in every row. ## BIT_COUNT ```text BIT_COUNT(expr) ``` Returns the number of bits set to 1 in an integer. It is not an aggregate function. **Return type:** INT. ```sql SELECT id, BIT_COUNT(id) FROM product WHERE id IN (1, 3, 5, 255) ORDER BY id; ``` | id | bit_count(id) | |---:|---:| | 1 | 1 | | 3 | 2 | | 5 | 2 | | 255 | 8 | --- # Click counter functions: INCR and DECR Source: https://www.coradb.ai/manual/sql/function/clickcounter_fn.html ```text INCR(column_name) DECR(column_name) SELECT ... FROM ... WHERE ... WITH {INCREMENT | DECREMENT} FOR column_name ``` `INCR` and `DECR` read a row and, in the same `SELECT`, add 1 to or subtract 1 from an integer column of that row. They are designed for *click counters*, such as the number of times a product page was viewed: one statement both shows the row and records the view, without a separate `UPDATE`. - The column must be `SMALLINT`, `INTEGER` or `BIGINT`. **Return type:** the type of the column. - The value returned is the value **before** the change. Write `INCR(col) + 1` to show the new value. - If the value is `NULL`, it stays `NULL`. - When the value would pass the maximum (or, for `DECR`, the minimum) of the type, it is reset to 0. - `WITH INCREMENT FOR column` (or `WITH DECREMENT FOR column`) after the `WHERE` clause changes the counter without listing the function in the select list. ```sql CREATE TABLE product_view (product_id INT PRIMARY KEY, views INT NOT NULL DEFAULT 0); INSERT INTO product_view (product_id) VALUES (1795), (123), (335); -- show the product and count the view SELECT p.name, INCR(v.views) FROM product_view v JOIN product p ON p.id = v.product_id WHERE v.product_id = 1795; ``` | name | views | |---|---:| | Balboa Persistence Tee | 0 | The stored value is now 1. The same with `WITH INCREMENT FOR` returns 1 and stores 2: ```sql SELECT product_id, views FROM product_view WHERE product_id = 1795 WITH INCREMENT FOR views; ``` > **Warning:** > - The change is made immediately and independently of the transaction: a `ROLLBACK` does not undo it. > - The `SELECT` must return exactly one row; otherwise it fails with `Query result contains more than a single tuple`. > - The functions work only in a top-level `SELECT`, not in a subquery or in `INSERT ... SELECT` or `UPDATE ... SET col = (SELECT ...)`. > - If several `INCR`/`DECR` calls are in one statement and one fails, none of them is applied. > - The change bypasses `UPDATE` triggers. A trigger that rejects updates on the table, for example, does not stop `INCR`. --- # Comparison operators Source: https://www.coradb.ai/manual/sql/function/comparison_op.html Comparison operators compare two values and return 1 (true), 0 (false) or `NULL` (unknown). ```text expression comparison_operator expression expression IS [NOT] {TRUE | FALSE | UNKNOWN | NULL} comparison_operator ::= = | <=> | <> | != | > | < | >= | <= ``` | Operator | Meaning | Example | Result | |---|---|---|---| | `=` | Equal. `NULL` if either operand is `NULL`. | `1 = 2`, `1 = NULL` | 0, NULL | | `<=>` | NULL-safe equal: like `=`, but two `NULL` values are equal and a `NULL` compared with a value is false, never `NULL`. | `1 <=> NULL`, `NULL <=> NULL` | 0, 1 | | `<>`, `!=` | Not equal. | `1 <> 2` | 1 | | `>`, `<`, `>=`, `<=` | Greater than, less than, greater or equal, less or equal. | `1 >= 2` | 0 | | `IS [NOT] TRUE`, `IS [NOT] FALSE` | Tests the truth value of the left operand. | `1 IS FALSE`, `1 IS NOT FALSE` | 0, 1 | | `IS [NOT] UNKNOWN`, `IS [NOT] NULL` | Tests whether the left operand is `NULL`. | `NULL IS UNKNOWN` | 1 | How values of each type are compared: - **Numbers**: values of different numeric types are converted to a common type first, so `1.000 = 1` is true. - **Character strings**: compared according to their collation. With the default `utf8_bin` collation, the comparison is case-sensitive. When two strings of different lengths are compared, the shorter one is padded with spaces for `CHAR` values. - **Strings and numbers**: the string is converted to a number, so `0.01 = '0.01'` is true. Prefer comparing values of the same type, which also lets the optimizer use indexes. - **Dates and times**: an earlier time is smaller. Values of different date/time types are converted to a common type; compare values of the same type to get the result you expect. - **Bit strings**: the shorter value is padded with zeros at the end. - **Collections**: `LIST` values are compared element by element in order; for `SET` and `MULTISET` values, use the [containment operators](https://www.coradb.ai/manual/sql/function/containment_op.html). - **NULL**: any comparison with `NULL` using `=`, `<>`, `<` and so on returns `NULL`. Use `IS NULL` or `<=>` instead. ```sql SELECT (1 <> 0), (1 = NULL), (1 <=> NULL), (NULL <=> NULL), (1.000 = 1), ('coradb' = 'CoraDB'), (0.01 = '0.01'), (1 IS NOT FALSE) FROM db_root; ``` | (1 <> 0) | (1 = NULL) | (1 <=> NULL) | (NULL <=> NULL) | (1.000 = 1) | ('coradb' = 'CoraDB') | (0.01 = '0.01') | (1 IS NOT FALSE) | |---|---|---|---|---|---|---|---| | 1 | NULL | 0 | 1 | 1 | 0 | 1 | 1 | `<=>` makes it easy to compare with a value that may be `NULL`. The nine unshipped orders: ```sql SELECT COUNT(*) FROM orders WHERE shipped_date <=> NULL; ``` | count(*) | |---| | 9 | ## See also - [Logical operators](https://www.coradb.ai/manual/sql/function/logical_op.html) - [Conditional expressions (BETWEEN, IN, LIKE, EXISTS, CASE, ...)](https://www.coradb.ai/manual/sql/function/condition_op.html) - [Conditional functions](https://www.coradb.ai/manual/sql/function/condition_fn.html): [NVL](https://www.coradb.ai/manual/sql/function/condition_fn.html#ifnull-nvl), [COALESCE](https://www.coradb.ai/manual/sql/function/condition_fn.html#coalesce), [NULLIF](https://www.coradb.ai/manual/sql/function/condition_fn.html#nullif) --- # Conditional functions Source: https://www.coradb.ai/manual/sql/function/condition_fn.html Conditional functions return one of their arguments depending on a condition, most often on whether a value is `NULL`. For the general `CASE` expression, see [Conditional expressions](https://www.coradb.ai/manual/sql/function/condition_op.html). > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. Order 455 has not shipped yet, so its `shipped_date` is `NULL`. ## Result type When the arguments that can be returned have different types, CoraDB converts them all to the type with the highest priority: - `CHAR` < `VARCHAR` - `BIT` < `VARBIT` - `SHORT` < `INT` < `BIGINT` < `NUMERIC` < `FLOAT` < `DOUBLE` - `DATE` < `TIMESTAMP` < `DATETIME` For example, `COALESCE(a, b, c, d)` with an `INT`, a `BIGINT`, a `SHORT` and a `FLOAT` argument returns a `FLOAT`. If the arguments cannot all be converted to one type (for example numbers and dates), they are converted to `VARCHAR`. `NUMERIC` results keep enough decimal places for every possible result. ## COALESCE ```text COALESCE(expression [, expression ...]) ``` Returns the first argument that is not `NULL`, or `NULL` if all are `NULL`. `COALESCE(a, b)` is the same as `CASE WHEN a IS NOT NULL THEN a ELSE b END`. **Return type:** the common type of the arguments (see [Result type](https://www.coradb.ai/manual/sql/function/condition_fn.html#result-type)). Show the shipping date, or the order date for orders that have not shipped: ```sql SELECT id, shipped_date, COALESCE(shipped_date, order_date) AS status_date FROM orders WHERE id IN (1, 455, 456) ORDER BY id; ``` | id | shipped_date | status_date | |---:|---|---| | 1 | 2025-10-20 | 2025-10-20 | | 455 | NULL | 2025-12-30 | | 456 | 2025-01-04 | 2025-01-04 | ```sql SELECT COALESCE(NULL, NULL, 'third', 'fourth'), COALESCE(NULL, 10, 2.5) FROM db_root; ``` | coalesce(null, null, 'third', 'fourth') | coalesce(null, 10, 2.5) | |---|---:| | third | 10.0 | ## DECODE ```text DECODE(expression, search, result [, search, result ...] [, default]) ``` Compares *expression* with each *search* value in turn and returns the *result* of the first one that is equal. Returns *default* if none matches, or `NULL` if there is no *default*. `DECODE(a, b, c, d, e, f)` is the same as: ```text CASE WHEN a = b THEN c WHEN a = d THEN e ELSE f END ``` *expression* and the *search* values must be comparable. **Return type:** the common type of the *result* and *default* values. ```sql SELECT product_id, discount_pct, DECODE(discount_pct, 0, 'full price', 25, 'quarter off', 'other') AS pricing FROM order_items WHERE order_id = 455 ORDER BY product_id; ``` | product_id | discount_pct | pricing | |---:|---:|---| | 123 | 0 | full price | | 335 | 0 | full price | | 1795 | 25 | quarter off | When the results are numbers with different scales, the result keeps all their decimal places. Without a default, a value that matches nothing returns `NULL`: ```sql SELECT DECODE(2, 1, 1, 2, 1.2345, 1.234567890), DECODE(3, 1, 'one', 2, 'two') FROM db_root; ``` | decode(2, 1, 1, 2, 1.2345, 1.234567890) | decode(3, 1, 'one', 2, 'two') | |---:|---| | 1.234500000 | NULL | If the results cannot be converted to a common type, the statement fails, for example `DECODE(a, 1, 'one', 2, 1.2345)` with `Cannot coerce 'one' to type double`. ## GREATEST ```text GREATEST(expression [, expression ...]) ``` Returns the greatest of its arguments, which must have comparable types. If any argument is `NULL`, the result is `NULL`. Unlike the aggregate [MAX](https://www.coradb.ai/manual/sql/function/analysis_fn.html#max), which compares the values of one column across rows, `GREATEST` compares several values in the same row. **Return type:** the common type of the arguments. ## LEAST ```text LEAST(expression [, expression ...]) ``` Returns the smallest of its arguments; otherwise like `GREATEST`. ```sql SELECT id, unit_price, units_in_stock, GREATEST(unit_price, units_in_stock) AS greatest_value, LEAST(unit_price, units_in_stock) AS least_value FROM product WHERE id IN (29, 123, 1795) ORDER BY id; ``` | id | unit_price | units_in_stock | greatest_value | least_value | |---:|---:|---:|---:|---:| | 29 | 123.79 | 0 | 123.79 | 0.00 | | 123 | 45.00 | 95 | 95.00 | 45.00 | | 1795 | 29.00 | 31 | 31.00 | 29.00 | The arguments can also be dates or strings: ```sql SELECT GREATEST(DATE'2025-01-31', DATE'2025-12-01'), LEAST('banana', 'apple', 'cherry'), GREATEST(1, NULL, 3) FROM db_root; ``` | greatest(date '2025-01-31', date '2025-12-01') | least('banana', 'apple', 'cherry') | greatest(1, null, 3) | |---|---|---| | 2025-12-01 | apple | NULL | ## IF ```text IF(condition, expression1, expression2) ``` Returns *expression1* if *condition* is true, and *expression2* if it is false or `NULL`. The two expressions must have the same type or a common type; if one of them is the `NULL` literal, the result has the type of the other. `IF(a, b, c)` is the same as `CASE WHEN a IS TRUE THEN b ELSE c END`. ```sql SELECT id, units_in_stock, IF(units_in_stock = 0, 'sold out', 'in stock') AS availability FROM product WHERE id IN (5, 1795) ORDER BY id; ``` | id | units_in_stock | availability | |---:|---:|---| | 5 | 0 | sold out | | 1795 | 31 | in stock | `IF` can also be used in a `WHERE` clause or any other place that takes an expression. ## IFNULL, NVL ```text IFNULL(expression1, expression2) NVL(expression1, expression2) ``` Return *expression1* if it is not `NULL`, otherwise *expression2*. The two functions are the same, and the same as `COALESCE(expression1, expression2)`. **Return type:** the common type of the arguments. ```sql SELECT id, shipped_date, NVL(shipped_date, DATE'2026-01-05') AS ship_or_planned, IFNULL(CAST(shipped_date AS VARCHAR), 'not shipped') AS ship_text FROM orders WHERE id IN (1, 455) ORDER BY id; ``` | id | shipped_date | ship_or_planned | ship_text | |---:|---|---|---| | 1 | 2025-10-20 | 2025-10-20 | 10/20/2025 | | 455 | NULL | 2026-01-05 | not shipped | A date and a string have no common type other than `VARCHAR`, which is why the date is cast explicitly in `ship_text`. ## NVL2 ```text NVL2(expression1, expression2, expression3) ``` Returns *expression2* if *expression1* is not `NULL`, and *expression3* if it is `NULL`. **Return type:** the common type of *expression2* and *expression3*. ```sql SELECT id, NVL2(shipped_date, 'shipped', 'pending') AS state FROM orders WHERE id IN (1, 455) ORDER BY id; ``` | id | state | |---:|---| | 1 | shipped | | 455 | pending | ## ISNULL ```text ISNULL(expression) ``` Returns 1 if *expression* is `NULL` and 0 otherwise, like the `expression IS NULL` predicate. **Return type:** INT. ```sql SELECT COUNT(*) FROM orders WHERE ISNULL(shipped_date); ``` | count(*) | |---:| | 9 | ## NULLIF ```text NULLIF(expression1, expression2) ``` Returns `NULL` if the two arguments are equal, and *expression1* otherwise. `NULLIF(a, b)` is the same as `CASE WHEN a = b THEN NULL ELSE a END`. It is useful to turn a placeholder value, such as 0 or an empty string, into `NULL`: ```sql SELECT product_id, NULLIF(discount_pct, 0) AS discount FROM order_items WHERE order_id = 455 ORDER BY product_id; ``` | product_id | discount | |---:|---:| | 123 | NULL | | 335 | NULL | | 1795 | 25 | The comparison follows the usual rules: `1` and `1.000` are equal, while `'A'` and `'a'` are different in a case-sensitive collation: ```sql SELECT ISNULL(NULL), ISNULL(0), NULLIF(1, 1.000), NULLIF('A', 'a'), NVL2(NULL, 1, 2) FROM db_root; ``` | isnull(null) | isnull(0) | nullif(1, 1.000) | nullif('A', 'a') | nvl2(null, 1, 2) | |---:|---:|---|---|---:| | 1 | 0 | NULL | A | 2 | ## See also - [Conditional expressions (CASE)](https://www.coradb.ai/manual/sql/function/condition_op.html) - [Comparison operators](https://www.coradb.ai/manual/sql/function/comparison_op.html) --- # Conditional expressions: ANY/ALL, BETWEEN, EXISTS, IN, IS NULL, LIKE and CASE Source: https://www.coradb.ai/manual/sql/function/condition_op.html Conditional expressions are the building blocks of `WHERE`, `HAVING` and `ON` clauses. Each one returns true, false or unknown (`NULL`); a row passes a condition only when it is true. The simple comparisons (`=`, `<>`, `<` and so on) are described in [Comparison operators](https://www.coradb.ai/manual/sql/function/comparison_op.html). > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. ## ANY, SOME, ALL ```text expression comparison_operator {ANY | SOME | ALL} {(subquery) | {value, ...} | collection_column} ``` - `ANY` and `SOME` (synonyms): true if the comparison is true for **at least one** value on the right. - `ALL`: true if the comparison is true for **every** value on the right. - The values can come from a subquery, a list in braces, or a collection column. `= ANY` is the same as `IN`: ```sql SELECT code, name FROM countries WHERE code = ANY {'FRA', 'DEU', 'ITA'} ORDER BY code; ``` | code | name | |---|---| | DEU | Germany | | FRA | France | | ITA | Italy | Products more expensive than every Lando product: ```sql SELECT id, name, unit_price FROM product WHERE unit_price > ALL (SELECT unit_price FROM product WHERE name LIKE 'Lando%') ORDER BY unit_price DESC; ``` | id | name | unit_price | |---:|---|---:| | 38 | Côte de Blaye | 263.50 | | 29 | Thüringer Rostbratwurst | 123.79 | A `NULL` among the values matters: `x > ALL {50, 100, NULL}` is never true (it is false or unknown), while `x > ANY {100, 200, NULL}` is true when `x` exceeds one of the other values. Against the product table the first finds 0 rows and the second 2. ## BETWEEN ```text expression [NOT] BETWEEN low AND high ``` True if *expression* is greater than or equal to *low* and less than or equal to *high*: `x BETWEEN a AND b` is the same as `x >= a AND x <= b`. It works for numbers, strings, and dates and times. ```sql SELECT id, name, unit_price FROM product WHERE unit_price BETWEEN 120 AND 300 ORDER BY id; ``` | id | name | unit_price | |---:|---|---:| | 29 | Thüringer Rostbratwurst | 123.79 | | 38 | Côte de Blaye | 263.50 | For strings, mind the upper bound: `name BETWEEN 'S' AND 'T'` includes names starting with S but not those starting with T (except `'T'` itself), because `'Thailand'` is greater than `'T'`: ```sql SELECT code, name FROM countries WHERE name BETWEEN 'S' AND 'T' ORDER BY code; ``` | code | name | |---|---| | CHE | Switzerland | | ESP | Spain | | SGP | Singapore | | SWE | Sweden | ## EXISTS ```text [NOT] EXISTS (subquery) ``` True if the subquery returns at least one row. The subquery's select list does not matter. `EXISTS` is often correlated with the outer query. The number of customers who never ordered: ```sql SELECT COUNT(*) FROM customer c WHERE NOT EXISTS (SELECT * FROM orders o WHERE o.customer_id = c.id); ``` | count(*) | |---:| | 350 | ## IN ```text expression [NOT] IN {(subquery) | (value, ...) | {value, ...}} ``` True if *expression* equals one of the values. `x IN (a, b)` is the same as `x = ANY {a, b}`. ```sql SELECT code, name FROM countries WHERE code IN ('FRA', 'DEU', 'ITA') ORDER BY code; ``` | code | name | |---|---| | DEU | Germany | | FRA | France | | ITA | Italy | `NOT IN` returns the other 22 countries. If the list contains `NULL`, however, `NOT IN` is never true: `code NOT IN ('FRA', NULL)` matches no row, because comparing with `NULL` is unknown. Make sure a subquery used with `NOT IN` cannot return `NULL`, or use `NOT EXISTS`. ## IS NULL ```text expression IS [NOT] NULL ``` True if *expression* is (not) `NULL`. Always use `IS NULL` to test for `NULL`: `shipped_date = NULL` is unknown for every row and selects nothing, while `shipped_date IS NULL` finds the nine unshipped orders. ```sql SELECT COUNT(*) FROM orders WHERE shipped_date IS NULL; ``` | count(*) | |---:| | 9 | ## LIKE ```text expression [NOT] LIKE pattern [ESCAPE escape_char] ``` Matches a string against a pattern: - `%` matches any sequence of characters, including none. - `_` matches exactly one character. - **ESCAPE** *escape_char*: a character that makes the next `%` or `_` in the pattern match itself. `LIKE` works on `CHAR` and `VARCHAR` values; whether it is case-sensitive depends on the collation (with the default `utf8_bin`, it is). Use `UPPER` or `LOWER` on both sides for a case-insensitive match, or a [function-based index](https://www.coradb.ai/manual/sql/tuning_special_index.html#function-based-index) to make that fast. ```sql SELECT name FROM brand WHERE name LIKE '____' ORDER BY name; ``` | name | |---| | Fila | | Head | | Hoka | | Keen | | Nike | | Puma | | Vans | | Zara | ```sql SELECT name FROM brand WHERE UPPER(name) LIKE '%A_O%' ORDER BY name; ``` | name | |---| | Alo Yoga | | Babolat | | Billabong | | Diadora | | Lacoste | | Patagonia | | Salomon | To find a literal `%`, escape it: ```sql SELECT 'Save 10% today' LIKE '%10!%%' ESCAPE '!', 'Save 10 today' LIKE '%10!%%' ESCAPE '!' FROM db_root; ``` | 'Save 10% today' like '%10!%%' escape '!' | 'Save 10 today' like '%10!%%' escape '!' | |---:|---:| | 1 | 0 | Whether a backslash acts as an escape character without an `ESCAPE` clause depends on the [no_backslash_escapes and require_like_escape_character](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameters. For more powerful patterns, see [Regular expressions](https://www.coradb.ai/manual/sql/function/regex_fn.html). ## CASE ```text CASE expression WHEN value THEN result [WHEN value THEN result ...] [ELSE result] END CASE WHEN condition THEN result [WHEN condition THEN result ...] [ELSE result] END ``` The first form compares *expression* with each *value*; the second evaluates each *condition*. The result of the first `WHEN` that matches is returned, or the `ELSE` result, or `NULL` if there is no `ELSE`. ```sql SELECT product_id, discount_pct, CASE discount_pct WHEN 0 THEN 'full price' WHEN 25 THEN 'quarter off' ELSE 'discounted' END AS pricing FROM order_items WHERE order_id = 455 ORDER BY product_id; ``` | product_id | discount_pct | pricing | |---:|---:|---| | 123 | 0 | full price | | 335 | 0 | full price | | 1795 | 25 | quarter off | ```sql SELECT id, unit_price, CASE WHEN unit_price >= 100 THEN 'premium' WHEN unit_price >= 30 THEN 'standard' ELSE 'budget' END AS tier FROM product WHERE id IN (29, 123, 335, 1795) ORDER BY id; ``` | id | unit_price | tier | |---:|---:|---| | 29 | 123.79 | premium | | 123 | 45.00 | standard | | 335 | 20.00 | budget | | 1795 | 29.00 | budget | All results must have the same type or a common type. If one result is a variable-length string, the result is a variable-length string; if the results are numbers of different types, the result keeps all their decimal places. The functions [DECODE, IF and NVL](https://www.coradb.ai/manual/sql/function/condition_fn.html) are shorter forms of common `CASE` expressions. ## See also - [Comparison operators](https://www.coradb.ai/manual/sql/function/comparison_op.html) - [Logical operators](https://www.coradb.ai/manual/sql/function/logical_op.html) - [List predicates ALL, ANY, NONE, SINGLE](https://www.coradb.ai/manual/sql/function/predicate_fn.html) --- # Containment operators Source: https://www.coradb.ai/manual/sql/function/containment_op.html Containment operators are used to check the containment relationship by performing comparison operation on operands of the collection data type. Collection data types or subqueries can be specified as operands. The operation returns **TRUE** or **FALSE** if there is a containment relationship between the two operands of identical/different/subset/proper subset. ```text ::= | | (or ) | | NULL ::= SETEQ | SETNEQ | SUPERSET | SUBSET | SUPERSETEQ | SUBSETEQ ``` - \<*collection_operand*\>: This expression that can be specified as an operand is a single SET-valued attribute, an arithmetic expression containing a SET operator or a SET value enclosed in braces. If the type is not specified, the SET value enclosed in braces is treated as a **LIST** type by default. Subqueries can be specified as operands. If a column which is not a collection type is searched, a collection data type keyword is required for the subquery like **SET** (*subquery*). The column retrieved by a subquery must return a single set so that it can be compared with the set of the other operands. If the element type of collection is an object, the OIDs, not its contents, are compared. For example, two objects with different OIDs are considered to be different even though they have the same attribute values. - **NULL**: Any of operands to be compared is **NULL**, **NULL** is returned. The description and return values about the containment operators supported by CoraDB are as follows: **Containment operators supported by CoraDB** | Containment operator | Description | Predicates | Return value | |----------------------|--------------------------------------------------------|--------------------------|--------------| | A **SETEQ** B | A = B: Elements in A and B are same each other. | {1,2} SETEQ {1,2,2} | 0 | | A **SETNEQ** B | A \<\> B: Elements in A and B are not same each other. | {1,2} SETNEQ {1,2,3} | 1 | | A **SUPERSET** B | A \> B: B is a proper subset of A. | {1,2} SUPERSET {1,2,3} | 0 | | A **SUBSET** B | A \< B: A is a proper subset of B. | {1,2} SUBSET {1,2,3} | 1 | | A **SUPERSETEQ** B | A \>= B: B is a subset of A. | {1,2} SUPERSETEQ {1,2,3} | 0 | | A **SUBSETEQ** B | A \<= B: A is a subset of B. | {1,2} SUBSETEQ {1,2,3} | 1 | The following table shows than possibility of operation by operand and type conversion if a containment operator is used. **Possibility of operation by operand** | | SET | MULTISET | LIST(=SEQUENCE) | |---------------------|--------------------|--------------------------------------------------------------|-----------------------------------------------------------------------------------------| | **SET** | Operation possible | Operation possible | Operation possible | | **MULTISET** | Operation possible | Operation possible | Operation possible (**LIST** is converted into **MULTISET**) | | **LIST(=SEQUENCE)** | Operation possible | Operation possible (**LIST** is converted into **MULTISET**) | Some operation possible (**SETEQ**, **SETNEQ**) Error occurs for the rest of operators. | ```sql --empty set is a subset of any set SELECT ({} SUBSETEQ (CAST ({3,1,2} AS SET))); ``` | ({} SUBSETEQ (CAST ({3,1,2} AS SET))) | |---| | 1 | ```sql --operation between set type and null returns null SELECT ((CAST ({3,1,2} AS SET)) SUBSETEQ NULL); ``` | ((CAST ({3,1,2} AS SET)) SUBSETEQ NULL) | |---| | NULL | ```sql --{1,2,3} seteq {1,2,3} returns true SELECT ((CAST ({3,1,2} AS SET)) SETEQ (CAST ({1,2,3,3} AS SET))); ``` | ((CAST ({3,1,2} AS SET)) SETEQ (CAST ({1,2,3,3} AS SET))) | |---| | 1 | ```sql --{1,2,3} seteq {1,2,3,3} returns false SELECT ((CAST ({3,1,2} AS SET)) SETEQ (CAST ({1,2,3,3} AS MULTISET))); ``` | ((CAST ({3,1,2} AS SET)) SETEQ (CAST ({1,2,3,3} AS MULTISET))) | |---| | 0 | ```sql --{1,2,3} setneq {1,2,3,3} returns true SELECT ((CAST ({3,1,2} AS SET)) SETNEQ (CAST ({1,2,3,3} AS MULTISET))); ``` | ((CAST ({3,1,2} AS SET)) SETNEQ (CAST ({1,2,3,3} AS MULTISET))) | |---| | 1 | ```sql --{1,2,3} subseteq {1,2,3,4} returns true SELECT ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS SET))); ``` | ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS SET))) | |---| | 1 | ```sql --{1,2,3} subseteq {1,2,3,4,4} returns true SELECT ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS MULTISET))); ``` | ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS MULTISET))) | |---| | 1 | ```sql --{1,2,3} subseteq {1,2,4,4,3} returns true SELECT ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS LIST))); ``` | ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,4,4,3} AS LIST))) | |---| | 0 | ```sql --{1,2,3} subseteq {1,2,3,4,4} returns true SELECT ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,3,4,4} AS LIST))); ``` | ((CAST ({3,1,2} AS SET)) SUBSETEQ (CAST ({1,2,3,4,4} AS LIST))) | |---| | 1 | ```sql --{3,1,2} seteq {3,1,2} returns true SELECT ((CAST ({3,1,2} AS LIST)) SETEQ (CAST ({3,1,2} AS LIST))); ``` | ((CAST ({3,1,2} AS LIST)) SETEQ (CAST ({3,1,2} AS LIST))) | |---| | 1 | ```sql --error occurs because LIST subseteq LIST is not supported SELECT ((CAST ({3,1,2} AS LIST)) SUBSETEQ (CAST ({3,1,2} AS LIST))); ``` ```text ERROR: ' subseteq ' operator is not defined on types sequence and sequence. ``` ## SETEQ The **SETEQ** operator returns **TRUE** if the first operand is the same as the second one. It can perform comparison operator for all collection data type. ```text collection_operand SETEQ collection_operand ``` ```sql --creating a table with SET type address column and LIST type zip_code column CREATE TABLE contain_tbl (id INT PRIMARY KEY, name CHAR(10), address SET VARCHAR(20), zip_code LIST INT); INSERT INTO contain_tbl VALUES(1, 'Kim', {'country', 'state'},{1, 2, 3}); INSERT INTO contain_tbl VALUES(2, 'Moy', {'country', 'state'},{3, 2, 1}); INSERT INTO contain_tbl VALUES(3, 'Jones', {'country', 'state', 'city'},{1,2,3,4}); INSERT INTO contain_tbl VALUES(4, 'Smith', {'country', 'state', 'city', 'street'},{1,2,3,4}); INSERT INTO contain_tbl VALUES(5, 'Kim', {'country', 'state', 'city', 'street'},{1,2,3,4}); INSERT INTO contain_tbl VALUES(6, 'Smith', {'country', 'state', 'city', 'street'},{1,2,3,5}); INSERT INTO contain_tbl VALUES(7, 'Brown', {'country', 'state', 'city', 'street'},{}); --selecting rows when two collection_operands are same in the WHERE clause SELECT id, name, address, zip_code FROM contain_tbl WHERE address SETEQ {'country','state', 'city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | ```sql --selecting rows when two collection_operands are same in the WHERE clause SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SETEQ {1,2,3}; ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | ## SETNEQ The **SETNEQ** operator returns **TRUE** (1) if a first operand is different from a second operand. A comparable operation can be performed for all collection data types. ```text collection_operand SETNEQ collection_operand ``` ```sql --selecting rows when two collection_operands are not same in the WHERE clause SELECT id, name, address, zip_code FROM contain_tbl WHERE address SETNEQ {'country','state', 'city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | | 2 | Moy | {'country', 'state'} | {3, 2, 1} | | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | | 7 | Brown | {'city', 'country', 'state', 'street'} | {} | ```sql --selecting rows when two collection_operands are not same in the WHERE clause SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SETNEQ {1,2,3}; ``` | id | name | address | zip_code | |---:|---|---|---| | 2 | Moy | {'country', 'state'} | {3, 2, 1} | | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | | 7 | Brown | {'city', 'country', 'state', 'street'} | {} | ## SUPERSET The **SUPERSET** operator returns **TRUE** (1) when a second operand is a proper subset of a first operand; that is, the first one is larger than the second one. If two operands are identical, **FALSE** (0) is returned. Note that **SUPERSET** is not supported if all operands are **LIST** type. ```text collection_operand SUPERSET collection_operand ``` ```sql --selecting rows when the first operand is a superset of the second operand and they are not same SELECT id, name, address, zip_code FROM contain_tbl WHERE address SUPERSET {'country','state','city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | | 7 | Brown | {'city', 'country', 'state', 'street'} | {} | ```sql --SUPERSET operator cannot be used for comparison between LIST and LIST type values SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUPERSET {1,2,3}; ``` ```text ERROR: ' superset ' operator is not defined on types sequence and sequence. ``` ```sql --Comparing operands with a SUPERSET operator after casting LIST type as SET type SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUPERSET (CAST ({1,2,3} AS SET)); ``` | id | name | address | zip_code | |---:|---|---|---| | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | ## SUPERSETEQ The **SUPERSETEQ** operator returns **TRUE** (1) when a second operand is a subset of a first operand; that is, the first one is identical to or larger than the second one. Note that **SUPERSETEQ** is not supported if an operand is **LIST** type. ```text collection_operand SUPERSETEQ collection_operand ``` ```sql --selecting rows when the first operand is a superset of the second operand SELECT id, name, address, zip_code FROM contain_tbl WHERE address SUPERSETEQ {'country','state','city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | | 7 | Brown | {'city', 'country', 'state', 'street'} | {} | ```sql --SUPERSETEQ operator cannot be used for comparison between LIST and LIST type values SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUPERSETEQ {1,2,3}; ``` ```text ERROR: ' superseteq ' operator is not defined on types sequence and sequence. ``` ```sql --Comparing operands with a SUPERSETEQ operator after casting LIST type as SET type SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUPERSETEQ (CAST ({1,2,3} AS SET)); ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | | 4 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 5 | Kim | {'city', 'country', 'state', 'street'} | {1, 2, 3, 4} | | 6 | Smith | {'city', 'country', 'state', 'street'} | {1, 2, 3, 5} | ## SUBSET The **SUBSET** operator returns **TRUE** (1) if the second operand contains all elements of the first operand. If the first and the second collection have the same elements, **FALSE** (0) is returned. Note that both operands are the **LIST** type, the **SUBSET** operation is not supported. ```text collection_operand SUBSET collection_operand ``` ```sql --selecting rows when the first operand is a subset of the second operand and they are not same SELECT id, name, address, zip_code FROM contain_tbl WHERE address SUBSET {'country','state','city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | | 2 | Moy | {'country', 'state'} | {3, 2, 1} | ```text ERROR: ' subset ' operator is not defined on types sequence and sequence. --Comparing operands with a SUBSET operator after casting LIST type as SET type SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUBSET (CAST ({1,2,3} AS SET)); ``` ```text id name address zip_code =============================================================================== 7 'Brown ' {'city', 'country', 'state', 'street'} {} ``` ## SUBSETEQ The **SUBSETEQ** operator returns **TRUE** (1) when a first operand is a subset of a second operand; that is, the second one is identical to or larger than the first one. Note that **SUBSETEQ** is not supported if an operand is **LIST** type. ```text collection_operand SUBSETEQ collection_operand ``` ```sql --selecting rows when the first operand is a subset of the second operand SELECT id, name, address, zip_code FROM contain_tbl WHERE address SUBSETEQ {'country','state','city'}; ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | | 2 | Moy | {'country', 'state'} | {3, 2, 1} | | 3 | Jones | {'city', 'country', 'state'} | {1, 2, 3, 4} | ```sql --SUBSETEQ operator cannot be used for comparison between LIST and LIST type values SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUBSETEQ {1,2,3}; ``` ```text ERROR: ' subseteq ' operator is not defined on types sequence and sequence. ``` ```sql --Comparing operands with a SUBSETEQ operator after casting LIST type as SET type SELECT id, name, address, zip_code FROM contain_tbl WHERE zip_code SUBSETEQ (CAST ({1,2,3} AS SET)); ``` | id | name | address | zip_code | |---:|---|---|---| | 1 | Kim | {'country', 'state'} | {1, 2, 3} | | 7 | Brown | {'city', 'country', 'state', 'street'} | {} | --- # Date/time functions: ADDDATE, DATEDIFF, EXTRACT, TRUNC, FROM_UNIXTIME and more Source: https://www.coradb.ai/manual/sql/function/datetime_fn.html > **Time zones in the examples:** > Functions that use the session time zone (the current date and time, Unix time, and the `...LTZ` types) give different results in different time zones. Their examples show the results for a session whose time zone is UTC, set with `SET TIME ZONE 'UTC';`. Examples that show the current date or time are sample output: your values depend on when you run them. ## ADDDATE, DATE_ADD ```sql ADDDATE (date, INTERVAL expr unit) ``` ```sql ADDDATE (date, days) ``` ```sql DATE_ADD (date, INTERVAL expr unit) ``` The **ADDDATE** function performs an addition or subtraction operation on a specific **DATE** value; **ADDDATE** and **DATE_ADD** are used interchangeably. The return value is a **DATE** or **DATETIME** type. The **DATETIME** type is returned in the following cases. - The first argument is a **DATETIME** or **TIMESTAMP** type - The first argument is a **DATE** type and the unit of **INTERVAL** value specified is less than the unit of day Therefore, to return value of **DATETIME** type, you should convert the value of first argument by using the **CAST** function. Even though the date resulting from the operation exceeds the last day of the month, the function returns a valid **DATE** value considering the last date of the month. If every input argument value of date and time is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. If the calculated value is between '0000-00-00 00:00:00' and '0001-01-01 00:00:00', a value having 0 for all arguments is returned in **DATE** or **DATETIME** type. Note that operation in JDBC program is determined by the configuration of zeroDateTimeBehavior, connection URL property. For more information about JDBC connection URL, please see [Configuration connection](https://www.coradb.ai/manual/api/jdbc.html#configuration-connection). **Parameters** - `date`: It is a **DATE**, **TIMETIME**, or **TIMESTAMP** expression that represents the start date. If an invalid **DATE** value such as '2006-07-00' is specified, an error is returned. - `expr`: It represents the interval value to be added to the start date. If a negative number is specified next to the **INTERVAL** keyword, the interval value is subtracted from the start date. - `unit`: It represents the unit of the interval value specified in the *expr* expression. See the following table to specify the format for the interpretation of the interval value. If the value of *expr* unit is less than the number requested in the *unit*, it is specified from the smallest unit. For example, if it is HOUR_SECOND, three values such as 'HOURS:MINUTES:SECONDS' are required. In the case, if only two values such as "1:1" are given, it is regarded as 'MINUTES:SECONDS'. **Return type:** **DATE** or **DATETIME** **Format of expr for unit** | unit value | expr format | Example | |--------------------|-------------------------------------------|--------------------------------------------------------------| | MILLISECOND | MILLISECONDS | ADDDATE(SYSDATE, INTERVAL 123 MILLISECOND) | | SECOND | SECONDS | ADDDATE(SYSDATE, INTERVAL 123 SECOND) | | MINUTE | MINUTES | ADDDATE(SYSDATE, INTERVAL 123 MINUTE) | | HOUR | HOURS | ADDDATE(SYSDATE, INTERVAL 123 HOUR) | | DAY | DAYS | ADDDATE(SYSDATE, INTERVAL 123 DAY) | | WEEK | WEEKS | ADDDATE(SYSDATE, INTERVAL 123 WEEK) | | MONTH | MONTHS | ADDDATE(SYSDATE, INTERVAL 12 MONTH) | | QUARTER | QUARTERS | ADDDATE(SYSDATE, INTERVAL 12 QUARTER) | | YEAR | YEARS | ADDDATE(SYSDATE, INTERVAL 12 YEAR) | | SECOND_MILLISECOND | 'SECONDS.MILLISECONDS' | ADDDATE(SYSDATE, INTERVAL '12.123' SECOND_MILLISECOND) | | MINUTE_MILLISECOND | 'MINUTES:SECONDS.MILLISECONDS' | ADDDATE(SYSDATE, INTERVAL '12:12.123' MINUTE_MILLISECOND) | | MINUTE_SECOND | 'MINUTES:SECONDS' | ADDDATE(SYSDATE, INTERVAL '12:12' MINUTE_SECOND) | | HOUR_MILLISECOND | 'HOURS:MINUTES:SECONDS.MILLISECONDS' | ADDDATE(SYSDATE, INTERVAL '12:12:12.123' HOUR_MILLISECOND) | | HOUR_SECOND | 'HOURS:MINUTES:SECONDS' | ADDDATE(SYSDATE, INTERVAL '12:12:12' HOUR_SECOND) | | HOUR_MINUTE | 'HOURS:MINUTES' | ADDDATE(SYSDATE, INTERVAL '12:12' HOUR_MINUTE) | | DAY_MILLISECOND | 'DAYS HOURS:MINUTES:SECONDS.MILLISECONDS' | ADDDATE(SYSDATE, INTERVAL '12 12:12:12.123' DAY_MILLISECOND) | | DAY_SECOND | 'DAYS HOURS:MINUTES:SECONDS' | ADDDATE(SYSDATE, INTERVAL '12 12:12:12' DAY_SECOND) | | DAY_MINUTE | 'DAYS HOURS:MINUTES' | ADDDATE(SYSDATE, INTERVAL '12 12:12' DAY_MINUTE) | | DAY_HOUR | 'DAYS HOURS' | ADDDATE(SYSDATE, INTERVAL '12 12' DAY_HOUR) | | YEAR_MONTH | 'YEARS-MONTHS' | ADDDATE(SYSDATE, INTERVAL '12-13' YEAR_MONTH) | The examples use order 0, placed on 2021-11-07: ```sql SELECT order_date, ADDDATE(order_date, INTERVAL 24 HOUR), ADDDATE(order_date, 1), ADDDATE(order_date, -1) FROM orders WHERE id = 0; ``` | order_date | ADDDATE(order_date, INTERVAL 24 HOUR) | ADDDATE(order_date, 1) | ADDDATE(order_date, -1) | |---|---|---|---| | 2021-11-07 | 2021-11-08 00:00:00.000 | 2021-11-08 | 2021-11-06 | Adding an **INTERVAL** to a **DATE** returns a **DATETIME**; adding a number of days returns a **DATE**. A negative number subtracts days. When the expression gives fewer fields than the unit, the missing leading fields are 0: `'1:20'` with **HOUR_SECOND** means 0 hours, 1 minute and 20 seconds. ```sql SELECT ADDDATE(DATETIME '2021-11-07 18:18:24.149', INTERVAL '1:20' HOUR_SECOND); ``` | ADDDATE(DATETIME '2021-11-07 18:18:24.149', INTERVAL '1:20' HOUR_SECOND) | |---| | 2021-11-07 18:19:44.149 | ```sql SELECT ADDDATE('0000-00-00', 1 ); ``` ```text ERROR: Attempt to use 'zero date'. ``` ```sql SELECT ADDDATE('0001-01-01 00:00:00', -1); ``` ```text ERROR: Conversion error in date format. ``` ## ADDTIME ```sql ADDTIME(expr1, expr2) ``` The **ADDTIME** function adds or subtracts a value of specific time. The first argument is **DATE**, **DATETIME**, **TIMESTAMP**, or **TIME** type and the second argument is **TIME**, **DATETIME**, or **TIMESTAMP** type. Time should be included in the second argument, and the date of the second argument is ignored. The return type for each argument type is follows: | First argument type | Second argument type | Return type | Note | |---------------------|------------------------------------------|-------------|----------------------------------------------------------| | TIME | TIME, DATETIME, TIMESTAMP | TIME | The result value must be equal to or less than 24 hours. | | DATE | TIME, DATETIME, TIMESTAMP | DATETIME | | | DATETIME | TIME, DATETIME, TIMESTAMP | DATETIME | | | date/time string | TIME, DATETIME, TIMESTAMP or time string | VARCHAR | The result string includes time. | **Parameters** - `expr1`: **DATE**, **DATETIME**, **TIME** or **TIMESTAMP** type - `expr2`: **DATETIME**, **TIMESTAMP**, **TIME** type or date/time string ```sql SELECT ADDTIME(datetime'2007-12-31 23:59:59', time'1:1:2'); ``` | ADDTIME(datetime'2007-12-31 23:59:59', time'1:1:2') | |---| | 2008-01-01 01:01:01.000 | ```sql SELECT ADDTIME(time'01:00:00', time'02:00:01'); ``` | ADDTIME(time'01:00:00', time'02:00:01') | |---| | 03:00:01 | ## ADD_MONTHS ```sql ADD_MONTHS ( date_argument , month ) ``` The **ADD_MONTHS** function adds a *month* value to the expression *date_argument* of **DATE** type, and it returns a **DATE** type value. If the day (*dd*) of the value specified as an argument exists within the month of the result value of the operation, it returns the given day (*dd*); otherwise returns the last day of the given month (*dd*). If the result value of the operation exceeds the expression range of the **DATE** type, it returns an error. **Parameters** - `date_argument`: Specifies an expression of **DATE** type. To specify a **TIMESTAMP** or **DATETIME** value, an explicit casting to **DATE** type is required. If the value is **NULL**, **NULL** is returned. - `month`: Specifies the number of the months to be added to the *date_argument*. Both positive and negative values can be specified. If the given value is not an integer type, conversion to an integer type by an implicit casting (rounding to the first place after the decimal point) is performed. If the value is **NULL**, **NULL** is returned. ```sql --it returns DATE type value by adding month to the first argument SELECT ADD_MONTHS(DATE '2008-12-25', 5), ADD_MONTHS(DATE '2008-12-25', -5); ``` | ADD_MONTHS(DATE '2008-12-25', 5) | ADD_MONTHS(DATE '2008-12-25', -5) | |---|---| | 2009-05-25 | 2008-07-25 | ```sql SELECT ADD_MONTHS(DATE '2008-12-31', 5.5), ADD_MONTHS(DATE '2008-12-31', -5.5); ``` | ADD_MONTHS(DATE '2008-12-31', 5.5) | ADD_MONTHS(DATE '2008-12-31', -5.5) | |---|---| | 2009-06-30 | 2008-06-30 | ```sql SELECT order_date, ADD_MONTHS(order_date, 5), LAST_DAY(order_date) FROM orders WHERE id = 0; ``` | order_date | ADD_MONTHS(order_date, 5) | LAST_DAY(order_date) | |---|---|---| | 2021-11-07 | 2022-04-07 | 2021-11-30 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT ADD_MONTHS (datetimeltz'2001-10-11 10:11:12', 1); ``` | ADD_MONTHS (datetimeltz'2001-10-11 10:11:12', 1) | |---| | 2001-11-11 | ```sql SELECT ADD_MONTHS (datetimetz'2001-10-11 10:11:12 Europe/Paris', 1); ``` | ADD_MONTHS (datetimetz'2001-10-11 10:11:12 Europe/Paris', 1) | |---| | 2001-11-11 | ```sql SELECT ADD_MONTHS (timestampltz'2001-10-11 10:11:12', 1); ``` | ADD_MONTHS (timestampltz'2001-10-11 10:11:12', 1) | |---| | 2001-11-11 | ```sql SELECT ADD_MONTHS (timestamptz'2001-10-11 10:11:12 Europe/Paris', 1); ``` | ADD_MONTHS (timestamptz'2001-10-11 10:11:12 Europe/Paris', 1) | |---| | 2001-11-11 | ## CURDATE, CURRENT_DATE ```sql CURDATE () ``` ```sql CURRENT_DATE () ``` ```sql CURRENT_DATE ``` **CURDATE** (), **CURRENT_DATE** and **CURRENT_DATE** () are used interchangeably and they return the current date of session as the **DATE** type (*MM*/*DD*/*YYYY* or *YYYY*-*MM*-*DD*). The unit is day. When the time zone of the current session is same as that of server, these functions are same as `SYS_DATE`, `SYSDATE`. Please refer `SYS_DATE`, `SYSDATE` and the following examples to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. If input every argument value of year, month, and day is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Return type:** DATE ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date in DATE type SELECT CURDATE(), CURRENT_DATE(), CURRENT_DATE, SYS_DATE, SYSDATE; CURRENT_DATE CURRENT_DATE CURRENT_DATE SYS_DATE SYS_DATE ======================================================================== 02/05/2016 02/05/2016 02/05/2016 02/05/2016 02/05/2016 ``` ```sql -- it returns the date 60 days added to the current date SELECT CURDATE()+60; CURRENT_DATE +60 =================== 04/05/2016 ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that CURDATE() and SYS_DATE returns different results SELECT CURDATE(), CURRENT_DATE(), CURRENT_DATE, SYS_DATE, SYSDATE; CURRENT_DATE CURRENT_DATE CURRENT_DATE SYS_DATE SYS_DATE ======================================================================== 02/04/2016 02/04/2016 02/04/2016 02/05/2016 02/05/2016 ``` ## CURRENT_DATETIME, NOW ```sql CURRENT_DATETIME () ``` ```sql CURRENT_DATETIME ``` ```sql NOW () ``` **CURRENT_DATETIME**, **CURRENT_DATETIME** () and **NOW** () are used interchangeably, and they return the current date and time of session in **DATETIME** type. The unit is millisecond. When the time zone of the current session is same as that of server, these functions are same as `SYS_DATETIME`, `SYSDATETIME`. Please also refer `SYS_DATETIME`, `SYSDATETIME` to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** DATETIME ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date and time in DATETIME type SELECT NOW(), SYS_DATETIME; CURRENT_DATETIME SYS_DATETIME ============================================================== 04:05:09.292 PM 02/05/2016 04:05:09.292 PM 02/05/2016 ``` ```sql -- it returns the timestamp value 1 hour added to the current sys_datetime value SELECT TO_CHAR(SYSDATETIME+3600*1000, 'YYYY-MM-DD HH24:MI'); to_char( SYS_DATETIME +3600*1000, 'YYYY-MM-DD HH24:MI') ====================== '2016-02-05 17:05' ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' set time zone 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that NOW() and SYS_DATETIME return different results SELECT NOW(), SYS_DATETIME; CURRENT_DATETIME SYS_DATETIME ============================================================== 11:08:57.041 PM 02/04/2016 04:08:57.041 PM 02/05/2016 ``` ## CURTIME, CURRENT_TIME ```sql CURTIME () ``` ```sql CURRENT_TIME ``` ```sql CURRENT_TIME () ``` **CURTIME** (), **CURRENT_TIME** and **CURRENT_TIME** () are used interchangeably and they return the current time of session as **TIME** type (*HH*:*MI*:*SS*). The unit is second. When the time zone of the current session is same as that of server, these functions are same as `SYS_TIME`, `SYSTIME`. Please also refer `SYS_TIME`, `SYSTIME` to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** TIME ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current time in TIME type SELECT CURTIME(), CURRENT_TIME(), CURRENT_TIME, SYS_TIME, SYSTIME; CURRENT_TIME CURRENT_TIME CURRENT_TIME SYS_TIME SYS_TIME ========================================================================== 04:22:54 PM 04:22:54 PM 04:22:54 PM 04:22:54 PM 04:22:54 PM ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'AMERICA/LOS_ANGELES'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that CURTIME() and SYS_TIME return different results SELECT CURTIME(), CURRENT_TIME(), CURRENT_TIME, SYS_TIME, SYSTIME; CURRENT_TIME CURRENT_TIME CURRENT_TIME SYS_TIME SYS_TIME ========================================================================== 11:23:16 PM 11:23:16 PM 11:23:16 PM 04:23:16 PM 04:23:16 PM ``` ## CURRENT_TIMESTAMP, LOCALTIME, LOCALTIMESTAMP ```sql CURRENT_TIMESTAMP ``` ```sql CURRENT_TIMESTAMP () ``` ```sql LOCALTIME ``` ```sql LOCALTIME () ``` ```sql LOCALTIMESTAMP ``` ```sql LOCALTIMESTAMP () ``` **CURRENT_TIMESTAMP**, **CURRENT_TIMESTAMP** (), **LOCALTIME**, **LOCALTIME** (), **LOCALTIMESTAMP** and **LOCALTIMESTAMP** () are used interchangeably and they return the current date and time of session as **TIMESTAMP** type. The unit is second. When the time zone of the current session is same as that of server, these functions are same as `SYS_TIMESTAMP`, `SYSTIMESTAMP`. Please also refer `SYS_TIMESTAMP`, `SYSTIMESTAMP` to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** TIMESTAMP ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date and time in TIMESTAMP type of session and server timezones. SELECT LOCALTIME, SYS_TIMESTAMP; CURRENT_TIMESTAMP SYS_TIMESTAMP ====================================================== 04:34:16 PM 02/05/2016 04:34:16 PM 02/05/2016 ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that LOCALTIME() and SYS_TIMESTAMP return different results SELECT LOCALTIME, SYS_TIMESTAMP; CURRENT_TIMESTAMP SYS_TIMESTAMP ====================================================== 11:34:37 PM 02/04/2016 04:34:37 PM 02/05/2016 ``` ## DATE ```sql DATE (date) ``` The **DATE** function extracts the date part from specified argument, and returns it as '*MM*/*DD*/*YYYY*' format string. Arguments that can be specified are **DATE**, **TIMESTAMP** and **DATETIME** types. The return value is a **VARCHAR** type. 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to date and time, string where 0 is specified for year, month, and day is returned. **Parameters** - `date`: **DATE**, **TIMESTAMP** or **DATETIME** can be specified. **Return type:** STRING ```sql SELECT DATE('2010-02-27 15:10:23'); ``` | DATE('2010-02-27 15:10:23') | |---| | 2010-02-27 | ```sql SELECT DATE(TIMESTAMP '2021-11-07 10:00:00'); ``` | DATE(TIMESTAMP '2021-11-07 10:00:00') | |---| | 11/07/2021 | **DATE** returns a string in the format `MM/DD/YYYY`. ```sql SELECT DATE('0000-00-00 00:00:00'); ``` | DATE('0000-00-00 00:00:00') | |---| | 0000-00-00 | ## DATEDIFF ```sql DATEDIFF (date1, date2) ``` The **DATEDIFF** function returns the difference between two arguments as an integer representing the number of days. Arguments that can be specified are **DATE**, **TIMESTAMP** and **DATETIME** types and its return value is only **INTEGER** type. If every input argument value of date and time is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Parameters** - `date1,date2`: Specifies the types that include date (**DATE**, **TIMESTAMP** or **DATETIME**) type or string that represents the value of corresponding type. If invalid string is specified, an error is returned. **Return type:** INT ```sql SELECT DATEDIFF('2010-2-28 23:59:59','2010-03-02'); ``` | DATEDIFF('2010-2-28 23:59:59','2010-03-02') | |---| | -2 | ```sql SELECT DATEDIFF('0000-00-00 00:00:00', '2010-2-28 23:59:59'); ``` ```text ERROR: Attempt to use 'zero date'. ``` The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT IF(DATEDIFF('2002-03-03 12:00:00 AM','1990-01-01 11:59:59 PM') = DATEDIFF(timestampltz'2002-03-03 12:00:00 AM',timestampltz'1990-01-01 11:59:59 PM'),'ok','nok'); ``` | IF(DATEDIFF('2002-03-03 12:00:00 AM','1990-01-01 11:59:59 PM') = DATEDIFF(timestampltz'2002-03-03 12:00:00 AM',timestampltz'1990-01-01 11:59:59 PM'),'ok','nok') | |---| | ok | ## DATE_SUB, SUBDATE ```sql DATE_SUB (date, INTERVAL expr unit) ``` ```sql SUBDATE(date, INTERVAL expr unit) ``` ```sql SUBDATE(date, days) ``` The functions **DATE_SUB** and **SUBDATE** () are used interchangeably and they perform an addition or subtraction operation on a specific **DATE** value. The value is returned in **DATE** or **DATETIME** type. If the date resulting from the operation exceeds the last day of the month, the function returns a valid **DATE** value considering the last date of the month. If every input argument value of date and time is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. If the calculated value is between '0000-00-00 00:00:00' and '0001-01-01 00:00:00', a value having 0 for all arguments is returned in **DATE** or **DATETIME** type. Note that operation in JDBC program is determined by the configuration of zeroDateTimeBehavior, connection URL property (see [Configuration connection](https://www.coradb.ai/manual/api/jdbc.html#configuration-connection) for details). **Parameters** - `date`: It is a **DATE** or **TIMESTAMP** expression that represents the start date. If an invalid **DATE** value such as '2006-07-00' is specified, **NULL** is returned. - `expr`: It represents the interval value to be subtracted from the start date. If a negative number is specified next to the **INTERVAL** keyword, the interval value is added to the start date. - `unit`: It represents the unit of the interval value specified in the *exp* expression. To check the expr argument for the unit value, see the table of [ADDDATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-adddate). **Return type:** DATE or DATETIME ```sql SELECT order_date, SUBDATE(order_date, 1), DATEDIFF(shipped_date, order_date) AS days_to_ship FROM orders WHERE id = 0; ``` | order_date | SUBDATE(order_date, 1) | days_to_ship | |---|---|---| | 2021-11-07 | 2021-11-06 | 2 | ```sql SELECT SUBDATE('0000-00-00 00:00:00', -50); ``` ```text ERROR: Attempt to use 'zero date'. ``` ```sql SELECT SUBDATE('0001-01-01 00:00:00', 10); ``` ```text ERROR: Conversion error in date format. ``` ## DAY, DAYOFMONTH ```sql DAY (date) ``` ```sql DAYOFMONTH (date) ``` The function **DAY** or **DAYOFMONTH** returns day in the range of 1 to 31 from the specified parameter. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to year, month, and day, 0 is returned as an exception. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT DAYOFMONTH('2010-09-09'); ``` | DAYOFMONTH('2010-09-09') | |---| | 9 | ```sql SELECT DAY('2010-09-09 19:49:29'); ``` | DAY('2010-09-09 19:49:29') | |---| | 9 | ```sql SELECT DAYOFMONTH('0000-00-00 00:00:00'); ``` | DAYOFMONTH('0000-00-00 00:00:00') | |---| | 0 | ## DAYOFWEEK ```sql DAYOFWEEK (date) ``` The **DAYOFWEEK** function returns a day in the range of 1 to 7 (1: Sunday, 2: Monday, ..., 7: Saturday) from the specified parameters. The day index is same as the ODBC standards. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. If every input argument value of year, month, and day is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT DAYOFWEEK('2010-09-09'); ``` | DAYOFWEEK('2010-09-09') | |---| | 5 | ```sql SELECT DAYOFWEEK('2010-09-09 19:49:29'); ``` | DAYOFWEEK('2010-09-09 19:49:29') | |---| | 5 | ```sql SELECT DAYOFWEEK('0000-00-00'); ``` ```text ERROR: Attempt to use 'zero date'. ``` ## DAYOFYEAR ```sql DAYOFYEAR (date) ``` The **DAYOFYEAR** function returns the day of a year in the range of 1 to 366. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** types; the value is returned in **INTEGER** type. If every input argument value of year, month, and day is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT DAYOFYEAR('2010-09-09'); ``` | DAYOFYEAR('2010-09-09') | |---| | 252 | ```sql SELECT DAYOFYEAR('2010-09-09 19:49:29'); ``` | DAYOFYEAR('2010-09-09 19:49:29') | |---| | 252 | ```sql SELECT DAYOFYEAR('0000-00-00'); ``` ```text ERROR: Attempt to use 'zero date'. ``` ## EXTRACT ```sql EXTRACT ( field FROM date-time_argument ) ``` The **EXTRACT** operator extracts the values from *date-time_argument* and then converts the value type into **INTEGER**. 0 is not allowed in the input argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to date and time, 0 is returned as an exception. **Parameters** - `field`: Specifies a value to be extracted from date-time expression. - `date-time_argument`: An expression that returns a value of date-time. This expression must be one of **TIME**, **DATE**, **TIMESTAMP**, or **DATETIME** types. If the value is **NULL**, **NULL** is returned. **Return type:** INT ```sql SELECT EXTRACT(MONTH FROM DATETIME '2008-12-25 10:30:20.123' ); ``` ```text 12 ``` ```sql SELECT EXTRACT(HOUR FROM DATETIME '2008-12-25 10:30:20.123' ); ``` ```text 10 ``` ```sql SELECT EXTRACT(MILLISECOND FROM DATETIME '2008-12-25 10:30:20.123' ); ``` ```text 123 ``` ```sql SELECT EXTRACT(MONTH FROM '0000-00-00 00:00:00'); ``` ```text 0 ``` The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT EXTRACT (MONTH FROM datetimetz'10/15/1986 5:45:15.135 am Europe/Bucharest'); ``` ```text 10 ``` ```sql SELECT EXTRACT (MONTH FROM datetimeltz'10/15/1986 5:45:15.135 am Europe/Bucharest'); ``` ```text 10 ``` ```sql SELECT EXTRACT (MONTH FROM timestampltz'10/15/1986 5:45:15 am Europe/Bucharest'); ``` ```text 10 ``` ```sql SELECT EXTRACT (MONTH FROM timestamptz'10/15/1986 5:45:15 am Europe/Bucharest'); ``` ```text 10 ``` ## FROM_DAYS ```sql FROM_DAYS (N) ``` The **FROM_DAYS** function returns a date value in **DATE** type if **INTEGER** type is inputted as an argument. It is not recommended to use the **FROM_DAYS** function for dates prior to the year 1582 because the function does not take dates prior to the introduction of the Gregorian Calendar into account. If a value in the range of 0 to 3,652,424 can be inputted as an argument. If a value in the range of 0 to 365 is inputted, 0 is returned. 3,652,424, which is the maximum value, means the last day of year 9999. **Parameters** - `N`: Integer in the range of 0 to 3,652,424 **Return type:** DATE ```sql SELECT FROM_DAYS(719528); ``` | FROM_DAYS(719528) | |---| | 1970-01-01 | ```sql SELECT FROM_DAYS('366'); ``` | FROM_DAYS('366') | |---| | 0001-01-03 | ```sql SELECT FROM_DAYS(3652424); ``` | FROM_DAYS(3652424) | |---| | 9999-12-31 | ```sql SELECT FROM_DAYS(0); ``` | FROM_DAYS(0) | |---| | 0000-00-00 | ## FROM_TZ ```sql FROM_TZ(datetime, timezone_string) ``` Converts date/time type without timezone as date/time type with timezone by adding timezone to DATETIME typed value. Input value's type is DATETIME, and the result value's type is DATETIMETZ. **Parameters** - `datetime`: DATETIME - `timezone_string`: String representing a timezone name or and offset '+05:00', 'Asia/Seoul'. **Return type:** DATETIMETZ ```sql SELECT FROM_TZ(datetime '10/10/2014 00:00:00 AM', 'Europe/Vienna'); ``` | FROM_TZ(datetime '10/10/2014 00:00:00 AM', 'Europe/Vienna') | |---| | 2014-10-10 00:00:00.000 Europe/Vienna CEST | ```sql SELECT FROM_TZ(datetime '10/10/2014 23:59:59 PM', '+03:25:25'); ``` | FROM_TZ(datetime '10/10/2014 23:59:59 PM', '+03:25:25') | |---| | 2014-10-10 23:59:59.000 +03:25:25 | For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). > **See also:** > [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone), [NEW_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#new_time), [TZ_OFFSET](https://www.coradb.ai/manual/sql/function/datetime_fn.html#tz_offset) ## FROM_UNIXTIME ```sql FROM_UNIXTIME ( unix_timestamp[, format] ) ``` The **FROM_UNIXTIME** function returns the string of the specified format in **VARCHAR** type if the argument *format* is specified; if the argument *format* is omitted, it returns a value of **TIMESTAMP** type. Specify the argument *unix_timestamp* as an **INTEGER** type that corresponds to the UNIX timestamp. The returned value is displayed in the current time zone. It displays the result according to the format that you specified, and the date/time format, *format* follows the Date/Time Format 2 table of [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format). The relation is not one of one-to-one correspondence between **TIMESTAMP** and UNIX timestamp so if you use [UNIX_TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#unix_timestamp) or **FROM_UNIXTIME** function, partial value could be lost. For details, see [UNIX_TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#unix_timestamp). 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to date and time, string where 0 is specified for every date and time value is returned. Note that operation in JDBC program is determined by the configuration of zeroDateTimeBehavior, connection URL property (see [Configuration connection](https://www.coradb.ai/manual/api/jdbc.html#configuration-connection) for details). **Parameters** - `unix_timestamp`: Positive integer - `format`: Time format. Follows the date/time format of the [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format). **Return type:** STRING, INT ```sql SELECT FROM_UNIXTIME(1234567890); ``` | FROM_UNIXTIME(1234567890) | |---| | 2009-02-13 23:31:30 | ```sql SELECT FROM_UNIXTIME('1000000000'); ``` | FROM_UNIXTIME('1000000000') | |---| | 2001-09-09 01:46:40 | ```sql SELECT FROM_UNIXTIME(1234567890,'%M %Y %W'); ``` | FROM_UNIXTIME(1234567890,'%M %Y %W') | |---| | February 2009 Friday | ```sql SELECT FROM_UNIXTIME('1234567890','%M %Y %W'); ``` | FROM_UNIXTIME('1234567890','%M %Y %W') | |---| | February 2009 Friday | ```sql SELECT FROM_UNIXTIME(0); ``` | FROM_UNIXTIME(0) | |---| | 0000-00-00 00:00:00 | ## HOUR ```sql HOUR (time) ``` The **HOUR** function extracts the hour from the specified parameter and then returns the value in integer. The type **TIME**, **TIMESTAMP** or **DATETIME** can be specified and a value is returned in the **INTEGER** type. **Parameters** - `time`: Time **Return type:** INT ```sql SELECT HOUR('12:34:56'); ``` | HOUR('12:34:56') | |---| | 12 | ```sql SELECT HOUR('2010-01-01 12:34:56'); ``` | HOUR('2010-01-01 12:34:56') | |---| | 12 | ```sql SELECT HOUR(datetime'2010-01-01 12:34:56'); ``` | HOUR(datetime'2010-01-01 12:34:56') | |---| | 12 | ## LAST_DAY ```sql LAST_DAY ( date_argument ) ``` The **LAST_DAY** function returns the last day of the given month as **DATE** type. If every input argument value of year, month, and day is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Parameters** - `date_argument`: Specifies an expression of **DATE** type. To specify a **TIMESTAMP** or **DATETIME** value, explicit casting to **DATE** is required. If the value is **NULL**, **NULL** is returned. **Return type:** DATE ```sql --it returns last day of the month in DATE type SELECT LAST_DAY(DATE '1980-02-01'), LAST_DAY(DATE '2010-02-01'); ``` | LAST_DAY(DATE '1980-02-01') | LAST_DAY(DATE '2010-02-01') | |---|---| | 1980-02-29 | 2010-02-28 | ```sql SELECT LAST_DAY('0000-00-00'); ``` ```text ERROR: Attempt to use 'zero date'. ``` ## MAKEDATE ```sql MAKEDATE (year, dayofyear) ``` The **MAKEDATE** function returns a date from the specified parameter. You can specify an **INTEGER** type corresponding to the day of the year in the range of 1 to 9999 as an argument; the value in the range of 1/1/1 to 12/31/9999 is returned in **DATE** type. If the day of the year has passed the corresponding year, it will become the next year. For example, MAKEDATE(1999, 366) will return 2000-01-01. However, if you input a value in the range of 0 to 69 as the year, it will be processed as the year 2000-2069, if it is a value in the range of 70 to 99, it will be processed as the year 1970-1999. If every value specified in *year* and *dayofyear* is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Parameters** - `year`: Year in the range of 1 to 9999 - `dayofyear`: If you input a value in the range of 0 to 99 in the argument, it is handled as an exception; *dayofyear* must be equal to or less than 3,615,902 and the return value of MAKEDATE(100, 3615902) is 9999/12/31. **Return type:** DATE ```sql SELECT MAKEDATE(2010,277); ``` | MAKEDATE(2010,277) | |---| | 2010-10-04 | ```sql SELECT MAKEDATE(10,277); ``` | MAKEDATE(10,277) | |---| | 2010-10-04 | ```sql SELECT MAKEDATE(70,277); ``` | MAKEDATE(70,277) | |---| | 1970-10-04 | ```sql SELECT MAKEDATE(100,3615902); ``` | MAKEDATE(100,3615902) | |---| | 9999-12-31 | ```sql SELECT MAKEDATE(9999,365); ``` | MAKEDATE(9999,365) | |---| | 9999-12-31 | ```sql SELECT MAKEDATE(0,0); ``` ```text ERROR: Conversion error in date format. ``` ## MAKETIME ```sql MAKETIME(hour, min, sec) ``` The **MAKETIME** function returns the hour from specified argument in the AM/PM format. You can specify the **INTEGER** types corresponding hours, minutes and seconds as arguments; the value is returned in **DATETIME**. **Parameters** - `hour`: An integer representing the hours in the range of 0 to 23 - `min`: An integer representing the minutes in the range of 0 to 59 - `sec`: An integer representing the minutes in the range of 0 to 59 **Return type:** DATETIME ```sql SELECT MAKETIME(13,34,4); ``` | MAKETIME(13,34,4) | |---| | 13:34:04 | ```sql SELECT MAKETIME('1','34','4'); ``` | MAKETIME('1','34','4') | |---| | 01:34:04 | ```sql SELECT MAKETIME(24,0,0); ``` ```text ERROR: Conversion error in time format. ``` ## MINUTE ```sql MINUTE (time) ``` The **MINUTE** function returns the minutes in the range of 0 to 59 from specified argument. You can specify the **TIME** , **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. **Parameters** - `time`: Time **Return type:** INT ```sql SELECT MINUTE('12:34:56'); ``` | MINUTE('12:34:56') | |---| | 34 | ```sql SELECT MINUTE('2010-01-01 12:34:56'); ``` | MINUTE('2010-01-01 12:34:56') | |---| | 34 | ```sql SELECT MINUTE('2010-01-01 12:34:56.7890'); ``` | MINUTE('2010-01-01 12:34:56.7890') | |---| | 34 | ## MONTH ```sql MONTH (date) ``` The **MONTH** function returns the month in the range of 1 to 12 from specified argument. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to date, 0 is returned as an exception. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT MONTH('2010-01-02'); ``` | MONTH('2010-01-02') | |---| | 1 | ```sql SELECT MONTH('2010-01-02 12:34:56'); ``` | MONTH('2010-01-02 12:34:56') | |---| | 1 | ```sql SELECT MONTH('2010-01-02 12:34:56.7890'); ``` | MONTH('2010-01-02 12:34:56.7890') | |---| | 1 | ```sql SELECT MONTH('0000-00-00'); ``` | MONTH('0000-00-00') | |---| | 0 | ## MONTHS_BETWEEN ```sql MONTHS_BETWEEN (date_argument, date_argument) ``` The **MONTHS_BETWEEN** function returns the difference between the given **DATE** value. The return value is **DOUBLE** type. An integer value is returned if the two dates specified as arguments are identical or are the last day of the given month; otherwise, a value obtained by dividing the day difference by 31 is returned. **Parameters** - `date_argument`: Specifies an expression of **DATE** type. **TIMESTAMP** or **DATETIME** value also can be used. If the value is **NULL**, **NULL** is returned. **Return type:** DOUBLE ```sql --it returns the negative months when the first argument is the previous date SELECT MONTHS_BETWEEN(DATE '2008-12-31', DATE '2010-6-30'); ``` | MONTHS_BETWEEN(DATE '2008-12-31', DATE '2010-6-30') | |---| | -18 | ```sql --it returns integer values when each date is the last date of the month SELECT MONTHS_BETWEEN(DATE '2010-6-30', DATE '2008-12-31'); ``` | MONTHS_BETWEEN(DATE '2010-6-30', DATE '2008-12-31') | |---| | 18 | ```sql SELECT order_date, MONTHS_BETWEEN(order_date, DATE '2021-01-01') FROM orders WHERE id = 0; ``` | order_date | MONTHS_BETWEEN(order_date, DATE '2021-01-01') | |---|---| | 2021-11-07 | 10.193548387096774 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT MONTHS_BETWEEN(datetimetz'2001-10-11 10:11:12 +02:00', datetimetz'2001-05-11 10:11:12 +03:00'); ``` | MONTHS_BETWEEN(datetimetz'2001-10-11 10:11:12 +02:00', datetimetz'2001-05-11 10:11:12 +03:00') | |---| | 5 | ## NEW_TIME ```sql NEW_TIME(src_datetime, src_timezone, dst_timezone) ``` Moves a date value from a timezone to the other timezone. The type of *src_datetime* is DATETIME or TIME, and the return value's type is the same with the *src_datetime*'s value. **Parameters** - `src_datetime`: input value of DATETIME or TIME - `src_timezone`: a region name of a source timezone - `dst_timezion`: a region name of a target timezone **Return type:** the same type with a *src_datetime*s type ```sql SELECT NEW_TIME(datetime '10/10/2014 10:10:10 AM', 'Europe/Vienna', 'Europe/Bucharest'); ``` | NEW_TIME(datetime '10/10/2014 10:10:10 AM', 'Europe/Vienna', 'Europe/Bucharest') | |---| | 2014-10-10 11:10:10.000 | TIME type only accept an offset timezone as an input argument; a region name is not allowed. ```sql SELECT NEW_TIME(time '10:10:10 PM', '+03:00', '+10:00'); ``` | NEW_TIME(time '10:10:10 PM', '+03:00', '+10:00') | |---| | 05:10:10 | To see the timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). > **See also:** > [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone), [FROM_TZ](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_tz), [TZ_OFFSET](https://www.coradb.ai/manual/sql/function/datetime_fn.html#tz_offset) ## QUARTER ```sql QUARTER (date) ``` The **QUARTER** function returns the quarter in the range of 1 to 4 from specified argument. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT QUARTER('2010-05-05'); ``` | QUARTER('2010-05-05') | |---| | 2 | ```sql SELECT QUARTER('2010-05-05 12:34:56'); ``` | QUARTER('2010-05-05 12:34:56') | |---| | 2 | ```sql SELECT QUARTER('2010-05-05 12:34:56.7890'); ``` | QUARTER('2010-05-05 12:34:56.7890') | |---| | 2 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT QUARTER('2008-04-01 01:02:03 Asia/Seoul'); ``` | QUARTER('2008-04-01 01:02:03 Asia/Seoul') | |---| | 2 | ```sql SELECT QUARTER(datetimetz'2003-12-31 01:02:03.1234 Europe/Paris'); ``` | QUARTER(datetimetz'2003-12-31 01:02:03.1234 Europe/Paris') | |---| | 4 | ## ROUND ```sql ROUND(date, fmt) ``` This function rounds date to the unit specified by the format string, *fmt*. It returns a value of DATE type. The format and its unit and the return value are as follows: | Format | Unit | Return value | |-----------------|---------|---------------------------------------------------------------------------------------| | 'yyyy' or 'yy' | year | A value rounded to year | | 'mm' or 'month' | month | A value rounded to month | | 'q' | quarter | A value rounded to quarter, one of 1/1, 4/1, 7/1, 10/1 | | 'day' | week | A value rounded to week, this Sunday of *date* week or the next Sunday of *date* week | | 'dd' | day | A value rounded to day | | 'hh' | hour | A value rounded to hour | | 'mi' | minute | A value rounded to minute | | 'ss' | second | A value rounded to second | **Parameters** - `date`: The value of **DATE**, **TIMESTAMP** or **DATETIME** - `fmt`: Specifies the format for the truncating unit. If omitted, "dd" is default. **Return type:** DATE ```sql SELECT ROUND(date'2012-10-26', 'yyyy'); ``` | ROUND(date'2012-10-26', 'yyyy') | |---| | 2013-01-01 | ```sql SELECT ROUND(timestamp'2012-10-26 12:10:10', 'mm'); ``` | ROUND(timestamp'2012-10-26 12:10:10', 'mm') | |---| | 2012-11-01 | ```sql SELECT ROUND(datetime'2012-12-26 12:10:10', 'dd'); ``` | ROUND(datetime'2012-12-26 12:10:10', 'dd') | |---| | 2012-12-27 | ```sql SELECT ROUND(datetime'2012-12-26 12:10:10', 'day'); ``` | ROUND(datetime'2012-12-26 12:10:10', 'day') | |---| | 2012-12-30 | ```sql SELECT ROUND(datetime'2012-08-26 12:10:10', 'q'); ``` | ROUND(datetime'2012-08-26 12:10:10', 'q') | |---| | 2012-10-01 | ```sql SELECT TRUNC(datetime'2012-08-26 12:10:10', 'q'); ``` | TRUNC(datetime'2012-08-26 12:10:10', 'q') | |---| | 2012-07-01 | ```sql SELECT ROUND(datetime'2012-02-28 23:10:00', 'hh'); ``` | ROUND(datetime'2012-02-28 23:10:00', 'hh') | |---| | 2012-02-28 | ```sql SELECT ROUND(datetime'2012-02-28 23:58:59', 'hh'); ``` | ROUND(datetime'2012-02-28 23:58:59', 'hh') | |---| | 2012-02-29 | ```sql SELECT ROUND(datetime'2012-02-28 23:59:59', 'mi'); ``` | ROUND(datetime'2012-02-28 23:59:59', 'mi') | |---| | 2012-02-29 | ```sql SELECT ROUND(datetime'2012-02-28 23:59:59.500', 'ss'); ``` | ROUND(datetime'2012-02-28 23:59:59.500', 'ss') | |---| | 2012-02-29 | In order to truncate date instead of rounding, please see [TRUNC(date, fmt)](https://www.coradb.ai/manual/sql/function/datetime_fn.html#trunc). ## SEC_TO_TIME ```sql SEC_TO_TIME (second) ``` The **SEC_TO_TIME** function returns the time including hours, minutes and seconds from specified argument. You can specify the **INTEGER** type in the range of 0 to 86,399; the value is returned in **TIME** type. **Parameters** - `second`: Seconds in the range of 0 to 86,399 **Return type:** TIME ```sql SELECT SEC_TO_TIME(82800); ``` | SEC_TO_TIME(82800) | |---| | 23:00:00 | ```sql SELECT SEC_TO_TIME('82800.3'); ``` | SEC_TO_TIME('82800.3') | |---| | 23:00:00 | ```sql SELECT SEC_TO_TIME(86399); ``` | SEC_TO_TIME(86399) | |---| | 23:59:59 | ## SECOND ```sql SECOND (time) ``` The **SECOND** function returns the seconds in the range of 0 to 59 from specified argument. You can specify the **TIME**, **TIMESTAMP** or **DATETIME**; the value is returned in **INTEGER** type. **Parameters** - `time`: Time **Return type:** INT ```sql SELECT SECOND('12:34:56'); ``` | SECOND('12:34:56') | |---| | 56 | ```sql SELECT SECOND('2010-01-01 12:34:56'); ``` | SECOND('2010-01-01 12:34:56') | |---| | 56 | ```sql SELECT SECOND('2010-01-01 12:34:56.7890'); ``` | SECOND('2010-01-01 12:34:56.7890') | |---| | 56 | ## SYS_DATE, SYSDATE ```sql SYS_DATE ``` ```sql SYSDATE ``` **SYS_DATE** and **SYSDATE** are used interchangeably and they return the current date of server as the **DATE** type (*MM*/*DD*/*YYYY* or *YYYY*-*MM*-*DD*). The unit is day. When the time zone of the current session is same as that of server, these functions are same as [CURDATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-curdate), [CURRENT_DATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_date) and `CURRENT_DATE`. Please also refer [CURDATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-curdate), [CURRENT_DATE](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_date) to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. If input every argument value of year, month, and day is 0, the return value is determined by the **return_null_on_function_errors** system parameter; if it is set to yes, then **NULL** is returned; if it is set to no, an error is returned. The default value is **no**. **Return type:** DATE ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date in DATE type SELECT CURDATE(), CURRENT_DATE(), CURRENT_DATE, SYS_DATE, SYSDATE; CURRENT_DATE CURRENT_DATE CURRENT_DATE SYS_DATE SYS_DATE ======================================================================== 02/05/2016 02/05/2016 02/05/2016 02/05/2016 02/05/2016 ``` ```sql -- it returns the date 60 days added to the current date SELECT CURDATE()+60; CURRENT_DATE +60 =================== 04/05/2016 ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that CURDATE() and SYS_DATE returns different results SELECT CURDATE(), CURRENT_DATE(), CURRENT_DATE, SYS_DATE, SYSDATE; CURRENT_DATE CURRENT_DATE CURRENT_DATE SYS_DATE SYS_DATE ======================================================================== 02/04/2016 02/04/2016 02/04/2016 02/05/2016 02/05/2016 ``` ## SYS_DATETIME, SYSDATETIME ```sql SYS_DATETIME ``` ```sql SYSDATETIME ``` **SYS_DATETIME** and **SYSDATETIME** are used interchangeably, and they return the current date and time of server in **DATETIME** type. The unit is millisecond. When the time zone of the current session is same as that of server, these functions are same as [CURRENT_DATETIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_datetime), `CURRENT_DATETIME`, [NOW](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-now). Please also refer [CURRENT_DATETIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_datetime), [NOW](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-now) to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** DATETIME ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date and time in DATETIME type SELECT NOW(), SYS_DATETIME; CURRENT_DATETIME SYS_DATETIME ============================================================== 04:05:09.292 PM 02/05/2016 04:05:09.292 PM 02/05/2016 ``` ```sql -- it returns the timestamp value 1 hour added to the current sys_datetime value SELECT TO_CHAR(SYSDATETIME+3600*1000, 'YYYY-MM-DD HH24:MI'); to_char( SYS_DATETIME +3600*1000, 'YYYY-MM-DD HH24:MI') ====================== '2016-02-05 17:05' ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that NOW() and SYS_DATETIME return different results SELECT NOW(), SYS_DATETIME; CURRENT_DATETIME SYS_DATETIME ============================================================== 11:08:57.041 PM 02/04/2016 04:08:57.041 PM 02/05/2016 ``` ## SYS_TIME, SYSTIME ```sql SYS_TIME ``` ```sql SYSTIME ``` **SYS_TIME** and **SYSTIME** are used interchangeably and they return the current time of server as **TIME** type (*HH*:*MI*:*SS*). The unit is second. When the time zone of the current session is same as that of server, these functions are same as [CURTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-curtime), `CURRENT_TIME`, [CURRENT_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_time). Please also refer [CURTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-curtime), [CURRENT_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_time) to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** TIME ```sql select dbtimezone(), sessiontimezone(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current time in TIME type SELECT CURTIME(), CURRENT_TIME(), CURRENT_TIME, SYS_TIME, SYSTIME; CURRENT_TIME CURRENT_TIME CURRENT_TIME SYS_TIME SYS_TIME ========================================================================== 04:22:54 PM 04:22:54 PM 04:22:54 PM 04:22:54 PM 04:22:54 PM ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; select dbtimezone(), sessiontimezone(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that CURTIME() and SYS_TIME return different results SELECT CURTIME(), CURRENT_TIME(), CURRENT_TIME, SYS_TIME, SYSTIME; CURRENT_TIME CURRENT_TIME CURRENT_TIME SYS_TIME SYS_TIME ========================================================================== 11:23:16 PM 11:23:16 PM 11:23:16 PM 04:23:16 PM 04:23:16 PM ``` ## SYS_TIMESTAMP, SYSTIMESTAMP ```sql SYS_TIMESTAMP ``` ```sql SYSTIMESTAMP ``` **SYS_TIMESTAMP** and **SYSTIMESTAMP** are used interchangeably and they return the current date and time of server as **TIMESTAMP** type. The unit is second. When the time zone of the current session is same as that of server, these functions are same as `CURRENT_TIMESTAMP`, [CURRENT_TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_timestamp), `LOCALTIME`, [LOCALTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-localtime), `LOCALTIMESTAMP`, [LOCALTIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-localtimestamp). Please also refer `CURRENT_TIMESTAMP`, [CURRENT_TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-current_timestamp), `LOCALTIME`, [LOCALTIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-localtime), `LOCALTIMESTAMP`, [LOCALTIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#fn-localtimestamp) to find a difference and [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone) for details of the functions. **Return type:** TIMESTAMP ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'Asia/Seoul' -- it returns the current date and time in TIMESTAMP type of session and server timezones. SELECT LOCALTIME, SYS_TIMESTAMP; CURRENT_TIMESTAMP SYS_TIMESTAMP ====================================================== 04:34:16 PM 02/05/2016 04:34:16 PM 02/05/2016 ``` ```sql -- change session time from 'Asia/Seoul' to 'America/Los_Angeles' SET TIME ZONE 'America/Los_Angeles'; SELECT DBTIMEZONE(), SESSIONTIMEZONE(); dbtimezone sessiontimezone ============================================ 'Asia/Seoul' 'America/Los_Angeles' -- Note that LOCALTIME() and SYS_TIMESTAMP return different results SELECT LOCALTIME, SYS_TIMESTAMP; CURRENT_TIMESTAMP SYS_TIMESTAMP ====================================================== 11:34:37 PM 02/04/2016 04:34:37 PM 02/05/2016 ``` ## TIME ```sql TIME (time) ``` The **TIME** function extracts the time part from specified argument and returns the **VARCHAR** type string in the 'HH:MI:SS' format. You can specify the **TIME**, **TIMESTAMP** and **DATETIME** types. **Parameters** - `time`: Time **Return type:** STRING ```sql SELECT TIME('12:34:56'); ``` | TIME('12:34:56') | |---| | 12:34:56 | ```sql SELECT TIME('2010-01-01 12:34:56'); ``` | TIME('2010-01-01 12:34:56') | |---| | 12:34:56 | ```sql SELECT TIME(datetime'2010-01-01 12:34:56'); ``` | TIME(datetime'2010-01-01 12:34:56') | |---| | 12:34:56 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT TIME(datetimeltz'2000-12-31 17:34:23.1234 -05:00'); ``` | TIME(datetimeltz'2000-12-31 17:34:23.1234 -05:00') | |---| | 22:34:23.123 | ```sql SELECT TIME(datetimetz'2000-12-31 17:34:23.1234 -05:00'); ``` | TIME(datetimetz'2000-12-31 17:34:23.1234 -05:00') | |---| | 17:34:23.123 | ## TIME_TO_SEC ```sql TIME_TO_SEC (time) ``` The **TIME_TO_SEC** function returns the seconds in the range of 0 to 86,399 from specified argument. You can specify the **TIME**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. **Parameters** - `time`: Time **Return type:** INT ```sql SELECT TIME_TO_SEC('23:00:00'); ``` | TIME_TO_SEC('23:00:00') | |---| | 82800 | ```sql SELECT TIME_TO_SEC('2010-10-04 23:00:00'); ``` | TIME_TO_SEC('2010-10-04 23:00:00') | |---| | 82800 | ```sql SELECT TIME_TO_SEC('2010-10-04 23:00:00.1234'); ``` | TIME_TO_SEC('2010-10-04 23:00:00.1234') | |---| | 82800 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ## TIMEDIFF ```sql TIMEDIFF (expr1, expr2) ``` The **TIMEDIFF** function returns the time difference between the two specified time arguments. You can enter a date/time type, the **TIME**, **DATE**, **TIMESTAMP** or **DATETIME** type and the data types of the two arguments must be identical. The **TIME** will be returned and the time difference between the two arguments must be in the range of 00:00:00 -23:59:59. If it exceeds the range, an error will be returned. **Parameters** - `expr1, expr2`: Time. The data types of the two arguments must be identical. **Return type:** TIME ```sql SELECT TIMEDIFF(time '17:18:19', time '12:05:52'); ``` | TIMEDIFF(time '17:18:19', time '12:05:52') | |---| | 05:12:27 | ```sql SELECT TIMEDIFF('17:18:19','12:05:52'); ``` | TIMEDIFF('17:18:19','12:05:52') | |---| | 05:12:27 | ```sql SELECT TIMEDIFF('2010-01-01 06:53:45', '2010-01-01 03:04:05'); ``` | TIMEDIFF('2010-01-01 06:53:45', '2010-01-01 03:04:05') | |---| | 03:49:40 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT TIMEDIFF (datetimeltz'2013-10-28 03:11:12 AM Asia/Seoul', datetimeltz'2013-10-27 04:11:12 AM Asia/Seoul'); ``` | TIMEDIFF (datetimeltz'2013-10-28 03:11:12 AM Asia/Seoul', datetimeltz'2013-10-27 04:11:12 AM Asia/Seoul') | |---| | 23:00:00 | ## TIMESTAMP ```sql TIMESTAMP (date [,time]) ``` The **TIMESTAMP** function converts a **DATE** or **TIMESTAMP** type expression to **DATETIME** type. If the **DATE** format string ('*YYYY-MM-DD*' or '*MM/DD/YYYY*') or **TIMESTAMP** format string ('*YYYY-MM-DD HH:MI:SS*' or '*HH:MI:SS MM/DD/ YYYY*') is specified as the first argument, the function returns it as **DATETIME**. If the **TIME** format string ('*HH:MI:SS*.*FF*') is specified as the second, the function adds it to the first argument and returns the result as a **DATETIME** type. If the second argument is not specified, **12:00:00.000 AM** is specified by default. **Parameters** - `date`: The format strings can be specified as follows: '*YYYY*-*MM*-*DD*', '*MM*/*DD*/*YYYY*', '*YYYY*-*MM*-*DD* *HH*:*MI*:*SS*.*FF*', '*HH*:*MI*:*SS*.*FF* *MM*/*DD*/*YYYY*'. - `time`: The format string can be specified as follows: '*HH*:*MI*:*SS*\[.*FF*\]'. **Return type:** DATETIME ```sql SELECT TIMESTAMP('2009-12-31'), TIMESTAMP('2009-12-31','12:00:00'); ``` | TIMESTAMP('2009-12-31') | TIMESTAMP('2009-12-31','12:00:00') | |---|---| | 2009-12-31 00:00:00.000 | 2009-12-31 12:00:00.000 | ```sql SELECT TIMESTAMP('2010-12-31 12:00:00','12:00:00'); ``` | TIMESTAMP('2010-12-31 12:00:00','12:00:00') | |---| | 2011-01-01 00:00:00.000 | ```sql SELECT TIMESTAMP('13:10:30 12/25/2008'); ``` | TIMESTAMP('13:10:30 12/25/2008') | |---| | 2008-12-25 13:10:30.000 | The following are examples of using timezone type values. For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ```sql SELECT TIMESTAMP(datetimetz'2010-12-31 12:00:00 America/New_York', '03:00'); ``` | TIMESTAMP(datetimetz'2010-12-31 12:00:00 America/New_York', '03:00') | |---| | 2010-12-31 15:00:00.000 | ```sql SET TIME ZONE 'UTC'; SELECT TIMESTAMP(datetimeltz'2010-12-31 12:00:00 America/New_York', '03:00'); ``` ```text 08:00:00.000 PM 12/31/2010 ``` ## TO_DAYS ```sql TO_DAYS (date) ``` The **TO_DAYS** function returns the number of days after year 0 in the rage of 366 to 3652424 from specified argument. You can specify **DATE** type; the value is returned in **INTEGER** type. It is not recommended to use the **TO_DAYS** function for dates prior to the year 1582, as the function does not take dates prior to the introduction of the Gregorian Calendar into account. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT TO_DAYS('2010-10-04'); ``` | TO_DAYS('2010-10-04') | |---| | 734414 | ```sql SELECT TO_DAYS('2010-10-04 12:34:56'); ``` | TO_DAYS('2010-10-04 12:34:56') | |---| | 734414 | ```sql SELECT TO_DAYS('2010-10-04 12:34:56.7890'); ``` | TO_DAYS('2010-10-04 12:34:56.7890') | |---| | 734414 | ```sql SELECT TO_DAYS('1-1-1'); ``` | TO_DAYS('1-1-1') | |---| | 366 | ```sql SELECT TO_DAYS('9999-12-31'); ``` | TO_DAYS('9999-12-31') | |---| | 3652424 | ## TRUNC ```sql TRUNC( date[, fmt] ) ``` This function truncates date to the unit specified by the format string, *fmt*. It returns a value of DATE type. The format and its unit and the return value are as follows: | Format | Unit | Return value | |-----------------|---------|---------------------------------------------------------------------| | 'yyyy' or 'yy' | year | The same year with Jan. 1st | | 'mm' or 'month' | month | The same month with 1st | | 'q' | quarter | The same quarter with one of Jan. 1st, Apr. 1st, Jul. 1st, Oct. 1st | | 'day' | week | Sunday of the same week(starting date of the week including *date*) | | 'dd' | day | The same date with *date* | **Parameters** - `date`: The value of **DATE**, **TIMESTAMP** or **DATETIME** - `fmt`: Specifies the format for the truncating unit. If omitted, "dd" is default. **Return type:** DATE ```sql SELECT TRUNC(date'2012-12-26', 'yyyy'); ``` | TRUNC(date'2012-12-26', 'yyyy') | |---| | 2012-01-01 | ```sql SELECT TRUNC(timestamp'2012-12-26 12:10:10', 'mm'); ``` | TRUNC(timestamp'2012-12-26 12:10:10', 'mm') | |---| | 2012-12-01 | ```sql SELECT TRUNC(datetime'2012-12-26 12:10:10', 'q'); ``` | TRUNC(datetime'2012-12-26 12:10:10', 'q') | |---| | 2012-10-01 | ```sql SELECT TRUNC(datetime'2012-12-26 12:10:10', 'dd'); ``` | TRUNC(datetime'2012-12-26 12:10:10', 'dd') | |---| | 2012-12-26 | ```sql // It returns the date of Sunday of the week which includes date'2012-12-26' SELECT TRUNC(datetime'2012-12-26 12:10:10', 'day'); ``` ```text 12/23/2012 ``` In order to round date instead of truncation, please see [ROUND(date, fmt)](https://www.coradb.ai/manual/sql/function/datetime_fn.html#round). ## TZ_OFFSET ```sql TZ_OFFSET(timezone_string) ``` This returns a timezone offset from a timezone offset or timezone region name (e.g. '-05:00', or 'Europe/Vienna'). **Parameters** - `timezone_string`: timezone offset of timezone region name. **Return type:** STRING ```sql SELECT TZ_OFFSET('+05:00'); ``` ```text '+05:00' ``` ```sql SELECT TZ_OFFSET('Asia/Seoul'); ``` ```text '+09:00' ``` For timezone related description, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). > **See also:** > [DBTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#dbtimezone), [SESSIONTIMEZONE](https://www.coradb.ai/manual/sql/function/information_fn.html#sessiontimezone), [FROM_TZ](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_tz), [NEW_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#new_time) ## UNIX_TIMESTAMP ```sql UNIX_TIMESTAMP ( [date] ) ``` The argument of the **UNIX_TIMESTAMP** function can be omitted. If it is omitted, the function returns the interval between '1970-01-01 00:00:00' UTC and the current system date/time in seconds as **INTEGER** type. If the date argument is specified, the function returns the interval between '1970-01-01 00:00:00' UTC and the specified date/time in seconds. 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is given in every argument value corresponding to date and time, 0 is returned as an exception. Argument of DATETIME type is considered in session timezone. **Parameters** - `date`: **DATE** type, **TIMESTAMP** type, **TIMESTAMPTZ** type, **TIMESTAMPLTZ** type, **DATETIME** type, **DATETIMETZ** type, **DATETIMELTZ** type, **DATE** format string ('*YYYY*-*MM*-*DD*' or '*MM*/*DD*/*YYYY*'), **TIMESTAMP** format string ('*YYYY*-*MM*-*DD* *HH*:*MI*:*SS*', '*HH*:*MI*:*SS* *MM*/*DD*/*YYYY*') or '*YYYYMMDD*' format string can be specified. **Return type:** INT ```sql SELECT UNIX_TIMESTAMP('1970-01-02'), UNIX_TIMESTAMP(); ``` ```text unix_timestamp('1970-01-02') unix_timestamp() ================================================== 54000 1270196737 ``` ```sql SELECT UNIX_TIMESTAMP ('0000-00-00 00:00:00'); ``` | UNIX_TIMESTAMP ('0000-00-00 00:00:00') | |---| | 0 | ```sql -- when used without argument, it returns the exact value at the moment of execution of each occurrence SELECT UNIX_TIMESTAMP(), SLEEP(1), UNIX_TIMESTAMP(); unix_timestamp() sleep(1) unix_timestamp() =================================================== 1454661297 0 1454661298 ``` ## UTC_DATE ```sql UTC_DATE () ``` The **UTC_DATE** function returns the UTC date in 'YYYY-MM-DD' format. **Return type:** STRING ```sql SELECT UTC_DATE(); ``` ```text utc_date() ============== 01/12/2011 ``` ## UTC_TIME ```sql UTC_TIME () ``` The **UTC_TIME** function returns the UTC time in 'HH:MI:SS' format. **Return type:** STRING ```sql SELECT UTC_TIME(); ``` ```text utc_time() ============== 10:35:52 AM ``` ## WEEK ```sql WEEK (date[, mode]) ``` The **WEEK** function returns the week in the range of 0 to 53 from specified argument. You can specify the **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. **Parameters** - `date`: Date - `mode`: Value in the range of 0 to 7 **Return type:** INT You can omit the second argument, *mode* and must input a value in the range of 0 to 7. You can set that a week starts from Sunday or Monday and the range of the return value is from 0 to 53 or 1 to 53 with this value. If you omit the *mode*, the system parameter, **default_week_format** value(default: 0) will be used. The *mode* value means as follows: | mode | Start day of the week | Range | The first week of the year | |------|-----------------------|-------|-------------------------------------------------------------------| | 0 | Sunday | 0~53 | The first week that Sunday is included in the year | | 1 | Monday | 0~53 | The first week that more than three days are included in the year | | 2 | Sunday | 1~53 | The first week in the year that includes a Sunday | | 3 | Monday | 1~53 | The first week in the year that includes more than three days | | 4 | Sunday | 0~53 | The first week in the year that includes more than three days | | 5 | Monday | 0~53 | The first week in the year that includes Monday | | 6 | Sunday | 1~53 | The first week in the year that includes more than three days | | 7 | Monday | 1~53 | The first week in the year that includes Monday | If the *mode* value is one of 0, 1, 4 or 5, and the date corresponds to the last week of the previous year, the **WEEK** function will return 0. The purpose is to see what nth of the year the week is so it returns 0 for the 52th week of the year 1999. ```sql SELECT YEAR('2000-01-01'), WEEK('2000-01-01',0); ``` | YEAR('2000-01-01') | WEEK('2000-01-01',0) | |---|---| | 2000 | 0 | To see what n-th the week is based on the year including the start day of the week, use 0, 2, 5 or 7 as the *mode* value. ```sql SELECT WEEK('2000-01-01',2); ``` | WEEK('2000-01-01',2) | |---| | 52 | ```sql SELECT WEEK('2010-04-05'); ``` | WEEK('2010-04-05') | |---| | 14 | ```sql SELECT WEEK('2010-04-05 12:34:56',2); ``` | WEEK('2010-04-05 12:34:56',2) | |---| | 14 | ```sql SELECT WEEK('2010-04-05 12:34:56.7890',4); ``` | WEEK('2010-04-05 12:34:56.7890',4) | |---| | 14 | ## WEEKDAY ```sql WEEKDAY (date) ``` The **WEEKDAY** function returns the day of week in the range of 0 to 6 (0: Monday, 1: Tuesday, ..., 6: Sunday) from the specified parameter. You can specify **DATE**, **TIMESTAMP**, **DATETIME** types as parameters and an **INTEGER** type will be returned. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT WEEKDAY('2010-09-09'); ``` | WEEKDAY('2010-09-09') | |---| | 3 | ```sql SELECT WEEKDAY('2010-09-09 13:16:00'); ``` | WEEKDAY('2010-09-09 13:16:00') | |---| | 3 | ## YEAR ```sql YEAR (date) ``` The **YEAR** function returns the year in the range of 1 to 9,999 from the specified parameter. You can specify **DATE**, **TIMESTAMP** or **DATETIME** type; the value is returned in **INTEGER** type. **Parameters** - `date`: Date **Return type:** INT ```sql SELECT YEAR('2010-10-04'); ``` | YEAR('2010-10-04') | |---| | 2010 | ```sql SELECT YEAR('2010-10-04 12:34:56'); ``` | YEAR('2010-10-04 12:34:56') | |---| | 2010 | ```sql SELECT YEAR('2010-10-04 12:34:56.7890'); ``` | YEAR('2010-10-04 12:34:56.7890') | |---| | 2010 | --- # Encryption functions Source: https://www.coradb.ai/manual/sql/function/encryption_fn.html ## MD5 ```sql MD5(string) ``` The **MD5** function returns the MD5 128-bit checksum for the input character string. The result value is displayed as a character string that is expressed in 32 hexadecimals, which you can use to create hash keys, for example. **Parameters** - `string`: Input string. If a value that is not a **VARCHAR** type is entered, it will be converted to **VARCHAR**. **Return type:** STRING The return value is a **VARCHAR** (32) type and if an input parameter is **NULL**, **NULL** will be returned. ```sql SELECT MD5('coradb'); ``` | MD5('coradb') | |---| | 5552398cf1d9a272c19f35befdd6665b | ```sql SELECT MD5(255); ``` | MD5(255) | |---| | fe131d7f5a6b38b23cc967316c13dae2 | ```sql SELECT MD5('01/01/2010'); ``` | MD5('01/01/2010') | |---| | 4a2f373c30426a1b8e9cf002ef0d4a58 | ```sql SELECT MD5(CAST('2010-01-01' as DATE)); ``` | MD5(CAST('2010-01-01' as DATE)) | |---| | 4a2f373c30426a1b8e9cf002ef0d4a58 | ## SHA1 ```sql SHA1(string) ``` The **SHA1** function calculates an SHA-1 160-bit checksum for the string, as described in RFC 3174 (Secure Hash Algorithm). **Parameters** - `string`: target string to be encrypted **Return type:** STRING The value is returned as a string of 40 hex digits, or NULL if the argument is NULL. ```sql SELECT SHA1('coradb'); ``` | SHA1('coradb') | |---| | FA4D432B09FA3736504EE74F25748631B0893AC3 | ## SHA2 ```sql SHA2(string, hash_length) ``` The **SHA2** function calculates the SHA-2 family of hash functions (SHA-224, SHA-256, SHA-384, and SHA-512). The first argument is the cleartext string to be hashed. The second argument indicates the desired bit length of the result, which must have a value of 224, 256, 384, 512, or 0 (which is equivalent to 256). **Parameters** - `string`: target string to be encrypted **Return type:** STRING If either argument is NULL or the hash length is not one of the permitted values, the return value is NULL. Otherwise, the function result is a hash value containing the desired number of bits. ```sql SELECT SHA2('coradb', 256); ``` | SHA2('coradb', 256) | |---| | 6F4FB46C02F8E726E8EFAE0A4DF9B64DE4BDED9FFD9AD7359D3E6D026B4A0FC6 | ```sql SELECT SHA2('coradb', 224); ``` | SHA2('coradb', 224) | |---| | 83E173EAF94A7BFD1324456447C8D5675E41DA843AFBA991D978C955 | --- # Graph functions Source: https://www.coradb.ai/manual/sql/function/graph_fn.html Graph functions work on the nodes, edges and paths matched by a [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern. Path functions take a **path variable** (`pth` in `MATCH pth = (a)-[...]-(b)`); element functions take a node or edge alias. | Function | Returns | |---|---| | [nodes(path)](https://www.coradb.ai/manual/sql/function/graph_fn.html#nodes) | LIST of the vertices of a path, in order | | [relationships(path)](https://www.coradb.ai/manual/sql/function/graph_fn.html#relationships) | LIST of the edges of a path, in order | | [path_size(path)](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_size) | Number of edges (hops) in a path | | [path_comp(pattern ...)](https://www.coradb.ai/manual/sql/function/graph_fn.html#path_comp) | LIST built from every match of an inline pattern | | [LABEL(element)](https://www.coradb.ai/manual/sql/function/graph_fn.html#label) | Name of the vertex or edge table of a node or edge | | [JSON_NODE_PROPERTIES(node)](https://www.coradb.ai/manual/sql/function/graph_fn.html#json_node_properties) / [JSON_EDGE_PROPERTIES(edge)](https://www.coradb.ai/manual/sql/function/graph_fn.html#json_edge_properties) | JSON with the element id and its columns | | [JSON_INFO(element)](https://www.coradb.ai/manual/sql/function/graph_fn.html#json_info) | JSON with id, label, columns and adjacency list | | [JSON_ADJACENCY_LIST(node)](https://www.coradb.ai/manual/sql/function/graph_fn.html#json_adjacency_list) | JSON array of the node's edges | | [JSON_GRAPH(elements...)](https://www.coradb.ai/manual/sql/function/graph_fn.html#json_graph) | JSON `{nodes, edges}` subgraph built from all matched rows (aggregate) | They are typically combined with the list functions [first()](https://www.coradb.ai/manual/sql/function/list_fn.html#first), [last()](https://www.coradb.ai/manual/sql/function/list_fn.html#last), [at()](https://www.coradb.ai/manual/sql/function/list_fn.html#fn-at), [size()](https://www.coradb.ai/manual/sql/function/list_fn.html#size) and [list_comp()](https://www.coradb.ai/manual/sql/function/list_fn.html#list_comp), and with [property_of()](https://www.coradb.ai/manual/sql/function/information_fn.html#fn-property-of), which reads a column of a node or edge taken from a list: ```sql property_of(element, column_name, vertex_or_edge_table) ``` The examples use the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). ## NODES ```sql nodes(path_variable) ``` Returns the vertices of a path as a LIST, from the first node to the last. The argument must be a path variable; a node alias, a scalar or NULL raises an error. **Return type:** LIST of vertices Products liked by a customer who also likes *Vegie-spread*. The path is product → customer → product, so position 0 is the start product, position 1 the customer and the last position the other product: ```sql SELECT property_of(first(nodes(pth)), name, product) AS product, property_of(at(nodes(pth), 1), company_name, customer) AS liked_by, property_of(last(nodes(pth)), name, product) AS also_liked FROM MATCH pth = (p1:product)-[l:likes{2,2}]-(p2:product) WHERE p1.name = 'Vegie-spread' AND p1 <> p2 ORDER BY 2, 3 LIMIT 5; ``` | product | liked_by | also_liked | |---|---|---| | Vegie-spread | Alvarado LLC | Lono Yoga Short | | Vegie-spread | Alvarado LLC | Neve Studio Dance Jacket | | Vegie-spread | Alvarado LLC | Zing Jump Rope | | Vegie-spread | Boyd Inc | Helena Hooded Fleece | | Vegie-spread | Brown Ltd | Balboa Persistence Tee | > **Note:** > `property_of()` must be given the table of the element at that position. In a path that mixes vertex tables, read each position separately instead of applying one table to every node with `list_comp()`. ## RELATIONSHIPS ```sql relationships(path_variable) ``` Returns the edges of a path as a LIST, in path order. The argument must be a path variable. **Return type:** LIST of edges When were the two likes that link *Vegie-spread* to each co-liked product made? ```sql SELECT p2.name AS other_product, property_of(first(relationships(pth)), since, likes) AS first_like_at, property_of(last(relationships(pth)), since, likes) AS second_like_at FROM MATCH pth = (p1:product)-[l:likes{2,2}]-(p2:product) WHERE p1.name = 'Vegie-spread' AND p1 <> p2 ORDER BY 1 LIMIT 3; ``` | other_product | first_like_at | second_like_at | |---|---|---| | Abominable Hoodie | 2023-08-21 19:51:12.000 | 2025-03-29 22:27:02.000 | | Aeon Capri | 2023-06-06 01:11:39.000 | 2024-08-03 17:54:24.000 | | Arcadio Gym Short | 2022-11-04 14:49:12.000 | 2023-12-06 02:07:47.000 | Use `ALL(... IN relationships(pth) WHERE ...)` / `NONE(...)` to test every edge of a path. Products co-liked with *Vegie-spread* where both likes date from 2022 or later: ```sql SELECT COUNT(DISTINCT p2.id) AS products FROM MATCH pth = (p1:product)-[l:likes{2,2}]-(p2:product) WHERE p1.name = 'Vegie-spread' AND p1 <> p2 AND ALL(r IN relationships(pth) WHERE property_of(r, since, likes) >= DATETIME'2022-01-01 00:00:00'); ``` | products | |---:| | 38 | ## PATH_SIZE ```sql path_size(path_variable) ``` Returns the number of edges in the path, the same value as `size(relationships(path))`. The number of nodes is one more. **Return type:** INT ```sql SELECT path_size(pth) AS path_size, size(nodes(pth)) AS nodes, size(relationships(pth)) AS edges FROM MATCH pth = ANY_SHORTEST (c1:customer)-[f:follows{1,6}]-(c2:customer) WHERE c1.id = 5 AND c2.id = 15; ``` | path_size | nodes | edges | |---:|---:|---:| | 6 | 7 | 6 | ## PATH_COMP ```sql path_comp( [, ...] [WHERE ] | [ORDER BY ]) ``` *Path comprehension*: matches the inline pattern, evaluates *expression* for every match and returns the values as one LIST. No `FROM MATCH` is needed. - *graph_pattern*: one or more patterns, written as in `MATCH`. A single node without an edge is not a valid pattern. - *condition*: optional filter on the matches. - *expression*: required; the value collected for each match. - *ordering*: optional order of the list (`ORDER BY 1` sorts by the expression). **Return type:** LIST All products liked by the customer *Hampton PLC*, alphabetically, in one value: ```sql SELECT path_comp((cu:customer)-[l:likes]->(p:product) WHERE cu.company_name = 'Hampton PLC' | p.name ORDER BY 1) AS liked_products; ``` | liked_products | |---| | {'Compete Track Tote', 'Daria Bikram Pant', 'Diana Tights', 'Hollister Backyard Sweatshirt', 'Nora Practice Tank'} | ## LABEL ```sql LABEL(node_or_edge) ``` Returns the name of the vertex table of a node, or of the edge table of an edge. Useful with edge alternatives such as `[r:likes|follows]` or with `UNION ALL` across relationship types. **Return type:** STRING ```sql SELECT LABEL(cu) AS node_label, LABEL(r) AS edge_label, ci.name FROM MATCH (cu:customer)-[r:resides_in]->(ci:city) WHERE cu.id = 5; ``` | node_label | edge_label | ci.name | |---|---|---| | customer | resides_in | Luleå | ## JSON graph functions These functions return JSON values, convenient for applications and for graph visualisation tools. Every node and edge is identified by its internal object id, written `"(volume|page|slot)"`; the id is stable for the life of the row but is not the `id` column. ### JSON_NODE_PROPERTIES, JSON_EDGE_PROPERTIES ```sql JSON_NODE_PROPERTIES(node) JSON_EDGE_PROPERTIES(edge) ``` Return `{"id": ..., "properties": {column: value, ...}}` for one node or edge. ```sql SELECT JSON_NODE_PROPERTIES(b) AS brand_props, JSON_EDGE_PROPERTIES(f) AS follow_props FROM MATCH (cu:customer)-[f:follows]->(b:brand) WHERE cu.id = 5; ``` ```json -- brand_props {"id":"(0|4545|57)","properties":{"id":57,"name":"Skechers"}} -- follow_props {"id":"(0|4993|5)","properties":{"since":"07:02:33.000 PM 06/03/2025"}} ``` ### JSON_ADJACENCY_LIST ```sql JSON_ADJACENCY_LIST(node) ``` Returns a JSON array with one entry per edge of the node: `edge_id`, the id of the node at the other end (`dest`) and the direction (`dir`: `"0"` outgoing, `"1"` incoming). ```sql SELECT JSON_ADJACENCY_LIST(b) AS neighbourhood FROM MATCH (b:brand) WHERE b.name = 'Lululemon'; ``` ```json [{"edge_id":"(0|4801|8)","dest":"(0|4161|8)","dir":"0"}, {"edge_id":"(0|4929|152)","dest":"(0|4481|132)","dir":"0"}, ... {"edge_id":"(0|4993|23)","dest":"(0|4289|15)","dir":"1"}, ...] ``` Lululemon has outgoing `located_at` and `manufactures` edges (`dir` 0) and incoming `follows` edges from customers (`dir` 1). ### JSON_INFO ```sql JSON_INFO(node_or_edge) ``` Returns everything about an element in one document: `id`, `properties`, `label` and `adj_list` (the adjacency list). ```sql SELECT JSON_INFO(s) AS supplier_info FROM MATCH (s:supplier) WHERE s.company_name = 'Exotic Liquids'; ``` ```json {"id":"(0|4609|1)", "properties":{"id":1,"phone":"(171) 555-2222","address":"49 Gilbert St.", "contact_title":"Purchasing Manager","contact_name":"Charlotte Cooper", "company_name":"Exotic Liquids"}, "label":"supplier", "adj_list":[{"edge_id":"(0|4737|1)","dest":"(0|4161|1)","dir":"0"}, ...]} ``` ### JSON_GRAPH ```sql JSON_GRAPH(element [, element ...]) ``` An **aggregate** function: collects the listed nodes and edges of all matched rows into one subgraph, `{"nodes": [...], "edges": [...]}`, without duplicates. Each node has `id`, `label` and `properties`; each edge has `id`, `startNodeId`, `endNodeId`, `label` and `properties`. The format can be fed directly to graph visualisation libraries. The customer *Hampton PLC*, the products it likes and the `likes` edges: ```sql SELECT JSON_GRAPH(cu, l, p) AS subgraph FROM MATCH (cu:customer)-[l:likes]->(p:product) WHERE cu.company_name = 'Hampton PLC'; ``` ```json {"nodes":[ {"id":"(0|4289|66)","label":"customer","properties":{"id":65,"company_name":"Hampton PLC", ...}}, {"id":"(0|4486|171)","label":"product","properties":{"id":1379,"name":"Hollister Backyard Sweatshirt","unit_price":52.0, ...}}, ...], "edges":[ {"id":"(0|5633|111)","startNodeId":"(0|4289|66)","endNodeId":"(0|4492|83)","label":"likes", "properties":{"since":"12:50:57.000 AM 09/28/2023"}}, ...]} ``` ## See also - [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html) - [Collection functions](https://www.coradb.ai/manual/sql/function/list_fn.html) - [JSON functions](https://www.coradb.ai/manual/sql/function/json_fn.html) - [Sample database: e-commerce](https://www.coradb.ai/manual/sample-database.html) --- # Information functions Source: https://www.coradb.ai/manual/sql/function/information_fn.html Information functions return facts about values, the session, the database and the server, rather than computing on data. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html), connected as `dba`. Results that depend on your server, such as time zones and the database list, will differ. ## CHARSET ```text CHARSET(expr) ``` Returns the character set of a string expression. **Return type:** VARCHAR. ## COLLATION ```text COLLATION(expr) ``` Returns the collation of a string expression. **Return type:** VARCHAR. ```sql SELECT CHARSET('abc'), CHARSET(_utf8'abc'), COLLATION('abc'), COLLATION(_utf8'abc') FROM db_root; ``` | charset('abc') | charset(_utf8'abc') | collation('abc') | collation(_utf8'abc') | |---|---|---|---| | utf8 | utf8 | utf8_bin | utf8_bin | ## COERCIBILITY ```text COERCIBILITY(expr) ``` Returns the collation coercibility level of an expression: when two expressions with different collations meet, the one with the lower level decides the collation of the result. For the levels, see [Collation coercibility](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-coercibility). **Return type:** INT. ```sql SELECT COERCIBILITY(USER()), COERCIBILITY('abc'), COERCIBILITY(name) FROM countries WHERE code = 'FRA'; ``` | coercibility( user() ) | coercibility('abc') | coercibility(name) | |---:|---:|---:| | 7 | 10 | 3 | A column (3) wins over a function result (7), which wins over a constant (10). ## CURRENT_USER, USER ```text CURRENT_USER USER ``` Pseudocolumns that return the name of the user of the current session. **Return type:** VARCHAR. ## USER(), SYSTEM_USER() ```text USER() SYSTEM_USER() ``` Return the current user name followed by a host name, as `user@host`. **Return type:** VARCHAR. ```sql SELECT CURRENT_USER, USER(), SYSTEM_USER() FROM db_root; ``` ```text DBA DBA@db-server-01 DBA@db-server-01 ``` The users of the database are listed in the `db_user` catalog view. ## DATABASE, SCHEMA ```text DATABASE() SCHEMA() ``` Return the name of the database the session is connected to. The two functions are the same. **Return type:** VARCHAR. ```sql SELECT DATABASE(), SCHEMA() FROM db_root; ``` | database() | schema() | |---|---| | e-commerce | e-commerce | ## DBTIMEZONE ```text DBTIMEZONE() ``` Returns the time zone of the database server, as an offset (`'-05:00'`) or a region name (`'Europe/Vienna'`). **Return type:** VARCHAR. ## SESSIONTIMEZONE ```text SESSIONTIMEZONE() ``` Returns the time zone of the current session, which applies to `TIMESTAMP WITH LOCAL TIME ZONE` and `DATETIME WITH LOCAL TIME ZONE` values. It is the server's time zone unless the session changed it. **Return type:** VARCHAR. ```sql SELECT DBTIMEZONE(), SESSIONTIMEZONE() FROM db_root; ``` ```text Europe/Bucharest Europe/Bucharest ``` See also [FROM_TZ](https://www.coradb.ai/manual/sql/function/datetime_fn.html#from_tz), [NEW_TIME](https://www.coradb.ai/manual/sql/function/datetime_fn.html#new_time), [TZ_OFFSET](https://www.coradb.ai/manual/sql/function/datetime_fn.html#tz_offset) and the [timezone parameters](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter). ## DEFAULT ```text DEFAULT DEFAULT(column_name) ``` `DEFAULT(column_name)` returns the default value defined for a column. If the column has no default, the result is `NULL`; for a `NOT NULL` or `PRIMARY KEY` column without a default, it is an error. The keyword `DEFAULT` on its own stands for the column's default value in `INSERT` and `UPDATE` statements. ```sql CREATE TABLE info_tbl (id INT DEFAULT 0, name VARCHAR(10)); INSERT INTO info_tbl VALUES (1, 'a'), (2, 'b'), (NULL, 'c'); SELECT id, DEFAULT(id) FROM info_tbl ORDER BY name; ``` | id | default(id) | |---:|---:| | 1 | 0 | | 2 | 0 | | NULL | 0 | ```sql UPDATE info_tbl SET id = DEFAULT WHERE id IS NULL; DELETE FROM info_tbl WHERE id = DEFAULT(id); INSERT INTO info_tbl VALUES (DEFAULT, 'd'); ``` ## DISK_SIZE ```text DISK_SIZE(expr) ``` Returns the number of bytes needed to store the value of *expr* in a table, taking [string compression](https://www.coradb.ai/manual/sql/datatype_string.html#string_compression) into account. Use it to estimate the storage a column needs. **Return type:** INT. ```sql SELECT DISK_SIZE(name), DISK_SIZE(description), DISK_SIZE(unit_price), DISK_SIZE(id) FROM product WHERE id = 1795; ``` | disk_size(name) | disk_size(description) | disk_size(unit_price) | disk_size(id) | |---:|---:|---:|---:| | 24 | 16 | 16 | 4 | For constants: `DISK_SIZE('abc')` is 7 and `DISK_SIZE(1)` is 4. ## INDEX_CARDINALITY ```text INDEX_CARDINALITY(table_name, index_name, key_pos) ``` Returns the number of distinct keys in an index, as recorded in the statistics. *key_pos* selects the key prefix: 0 counts distinct values of the first column, 1 of the first two columns, and so on. Run [UPDATE STATISTICS](https://www.coradb.ai/manual/sql/tuning.html) first for current figures. - *table_name*, *index_name*: strings. - *key_pos*: an integer, or a value that can be converted to one (`FLOAT` and `DOUBLE` values are rounded). **Return type:** INT. The result is `NULL` if an argument is `NULL`, if the table or index does not exist, or if *key_pos* is out of range. The primary key of `order_items` is `(order_id, product_id)`: ```sql SELECT INDEX_CARDINALITY('order_items', 'pk_order_items_order_id_product_id', 0), INDEX_CARDINALITY('order_items', 'pk_order_items_order_id_product_id', 1), INDEX_CARDINALITY('order_items', 'pk_order_items_order_id_product_id', 2) FROM db_root; ``` | index_cardinality(..., 0) | index_cardinality(..., 1) | index_cardinality(..., 2) | |---:|---:|---:| | 11230 | 11230 | NULL | ## INET_ATON ```text INET_ATON(ip_string) ``` Converts an IPv4 address `'a.b.c.d'` to the number a × 256³ + b × 256² + c × 256 + d. **Return type:** BIGINT. ## INET_NTOA ```text INET_NTOA(number) ``` Converts a number back to an IPv4 address string. **Return type:** VARCHAR. ```sql SELECT INET_ATON('192.168.0.10'), INET_NTOA(3232235530) FROM db_root; ``` | inet_aton('192.168.0.10') | inet_ntoa(3232235530) | |---:|---| | 3232235530 | 192.168.0.10 | ## LAST_INSERT_ID ```text LAST_INSERT_ID() ``` Returns the `AUTO_INCREMENT` value generated by the most recent successful `INSERT` of the session. **Return type:** NUMERIC(38,0). - After a multi-row `INSERT`, it returns the value generated for the **first** row. - A value you insert yourself is not reported; only generated values are. - A failed `INSERT` does not change it, but the `AUTO_INCREMENT` counter may still have advanced, so the next value can skip numbers. - A rollback does not reset it. - Each session has its own value. A value generated inside a trigger is not visible outside the trigger. ```sql CREATE TABLE ai (a INT PRIMARY KEY AUTO_INCREMENT, b INT UNIQUE); INSERT INTO ai VALUES (NULL, 1); SELECT LAST_INSERT_ID(); -- 1 INSERT INTO ai VALUES (NULL, 11), (NULL, 12), (NULL, 13); SELECT LAST_INSERT_ID(); -- 2, the first of 2, 3, 4 INSERT INTO ai VALUES (500, 20), (NULL, 21); SELECT LAST_INSERT_ID(); -- 5: 500 was given, not generated ``` See also [AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto-increment). ## ROW_COUNT ```text ROW_COUNT() ``` Returns the number of rows changed by the last `INSERT`, `UPDATE` or `DELETE` statement of the session. **Return type:** INT. ```sql CREATE TABLE rc (i INT); INSERT INTO rc VALUES (1), (2), (3), (4), (5), (6), (7); SELECT ROW_COUNT(); -- 7 UPDATE rc SET i = 0 WHERE i > 3; SELECT ROW_COUNT(); -- 4 DELETE FROM rc WHERE i = 0; SELECT ROW_COUNT(); -- 4 ``` ## LIST_DBS ```text LIST_DBS() ``` Returns the names of all databases in the database location file (`databases.txt`), separated by spaces. **Return type:** VARCHAR. ```sql SELECT LIST_DBS() FROM db_root; ``` ```text chinook e-commerce healthcare movie-lens nba2014-2015 northwind northwind-rel olympics1988-2004 sakila star-wars ``` ## VERSION ```text VERSION() ``` Returns the version of the CoraDB server, for example `1.0.0.1586`. **Return type:** VARCHAR. ## LABEL ```text LABEL(graph_element) ``` Returns the label of a vertex or edge, that is, the name of its vertex or edge table. Use it in [MATCH](https://www.coradb.ai/manual/graph/match.html) queries to tell which table a matched element belongs to. **Return type:** VARCHAR. ```sql SELECT LABEL(b), LABEL(m), LABEL(p) FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE p.id = 1795; ``` | label(b) | label(m) | label(p) | |---|---|---| | brand | manufactures | product | The argument must be a graph element; `LABEL('text')` is an error (`Incompatible argument type char, expected type is: object`). ## PROPERTY_OF ```text PROPERTY_OF(graph_element, property_name, table_name) ``` Returns one property (column) of a vertex or edge. It is mainly used with the path functions [NODES](https://www.coradb.ai/manual/sql/function/graph_fn.html), [RELATIONSHIPS](https://www.coradb.ai/manual/sql/function/graph_fn.html), [FIRST](https://www.coradb.ai/manual/sql/function/list_fn.html) and [LAST](https://www.coradb.ai/manual/sql/function/list_fn.html), which return graph elements rather than rows of a known table. - *graph_element*: a vertex or edge. - *property_name*: the column to return, written as an identifier. - *table_name*: the vertex or edge table that defines the column. When several tables have a column with that name, it says which one is meant. **Return type:** the type of the column. The first and last vertex of each path from customer 5 to the products it likes: ```sql SELECT PROPERTY_OF(FIRST(NODES(pth)), company_name, customer) AS customer, PROPERTY_OF(LAST(NODES(pth)), name, product) AS product FROM MATCH pth = (c:customer)-[:likes]->(p:product) WHERE c.id = 5 ORDER BY 2; ``` | customer | product | |---|---| | Brown, Roman and Allen | Circe Hooded Ice Fleece | | Brown, Roman and Allen | Sirop derable | | Brown, Roman and Allen | Sybil Running Short | ## See also - [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html) - [String functions](https://www.coradb.ai/manual/sql/function/string_fn.html) --- # JSON functions: JSON_EXTRACT, JSON_TABLE, JSON_SET and more Source: https://www.coradb.ai/manual/sql/function/json_fn.html CoraDB stores JSON in the [JSON data type](https://www.coradb.ai/manual/sql/datatype_json.html#json-data-type) and provides functions to build, read, search and change JSON values. A second group of functions returns vertices, edges and their neighborhoods as JSON, for graph queries. | Group | Functions | |---|---| | Create | [JSON_ARRAY](https://www.coradb.ai/manual/sql/function/json_fn.html#json_array), [JSON_OBJECT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_object), [JSON_QUOTE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_quote) | | Inspect | [JSON_KEYS](https://www.coradb.ai/manual/sql/function/json_fn.html#json_keys), [JSON_GET_ALL_PATHS](https://www.coradb.ai/manual/sql/function/json_fn.html#json_get_all_paths), [JSON_DEPTH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_depth), [JSON_LENGTH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_length), [JSON_VALID](https://www.coradb.ai/manual/sql/function/json_fn.html#json_valid), [JSON_TYPE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_type), [JSON_UNQUOTE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_unquote), [JSON_PRETTY](https://www.coradb.ai/manual/sql/function/json_fn.html#json_pretty) | | Search and extract | [JSON_SEARCH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_search), [JSON_EXTRACT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_extract), [->](https://www.coradb.ai/manual/sql/function/json_fn.html#arrow), [->>](https://www.coradb.ai/manual/sql/function/json_fn.html#double-arrow), [JSON_CONTAINS_PATH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_contains_path), [JSON_CONTAINS](https://www.coradb.ai/manual/sql/function/json_fn.html#json_contains) | | Modify | [JSON_MERGE_PATCH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_merge_patch), [JSON_MERGE_PRESERVE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_merge_preserve), [JSON_MERGE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_merge), [JSON_ARRAY_APPEND](https://www.coradb.ai/manual/sql/function/json_fn.html#json_array_append), [JSON_ARRAY_INSERT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_array_insert), [JSON_INSERT](https://www.coradb.ai/manual/sql/function/json_fn.html#json_insert), [JSON_SET](https://www.coradb.ai/manual/sql/function/json_fn.html#json_set), [JSON_REPLACE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_replace), [JSON_REMOVE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_remove) | | Rows from JSON | [JSON_TABLE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_table) | | Graph elements as JSON | [JSON_PROPERTIES](https://www.coradb.ai/manual/sql/function/json_fn.html#json_properties), [JSON_NODE_PROPERTIES](https://www.coradb.ai/manual/sql/function/json_fn.html#json_node_properties), [JSON_EDGE_PROPERTIES](https://www.coradb.ai/manual/sql/function/json_fn.html#json_edge_properties), [JSON_INFO](https://www.coradb.ai/manual/sql/function/json_fn.html#json_info), [JSON_GRAPH](https://www.coradb.ai/manual/sql/function/json_fn.html#json_graph), [JSON_ADJACENCY_LIST](https://www.coradb.ai/manual/sql/function/json_fn.html#json_adjacency_list), [JSON_TOPOLOGY_RECORD](https://www.coradb.ai/manual/sql/function/json_fn.html#json_topology_record), [JSON_GRAPH_HEAP_MEMORY_USAGE](https://www.coradb.ai/manual/sql/function/json_fn.html#json_graph_heap_memory_usage) | The aggregate functions [JSON_ARRAYAGG and JSON_OBJECTAGG](https://www.coradb.ai/manual/sql/function/analysis_fn.html) build JSON arrays and objects from groups of rows. ## Arguments The functions share these kinds of arguments: - *json_doc*: a JSON value, or a string that is parsed as JSON. - *val*: a JSON value, or a value that is converted to a JSON scalar. - *json key*: a string used as an object key. - *json path*: a path such as `'$.a[0]'`, following the rules in [JSON paths](https://www.coradb.ai/manual/sql/datatype_json.html#json-paths) and [JSON pointers](https://www.coradb.ai/manual/sql/datatype_json.html#json-pointers). How a *json_doc* and a *val* argument accept other SQL types: | Input type | As *json_doc* | As *val* | |---|---|---| | JSON | Used as is | Used as is | | String | Parsed as JSON | Converted to a JSON string | | SHORT, INTEGER | Conversion error | Converted to a JSON integer | | BIGINT | Conversion error | Converted to a JSON bigint | | FLOAT, DOUBLE, NUMERIC | Conversion error | Converted to a JSON double | | NULL | NULL | Converted to JSON `null` | | Other | Conversion error | Conversion error | String arguments are processed as UTF-8; strings in other character sets are converted first. > **How results are shown:** > The result tables on this page show each value as text, as `CAST(value AS STRING)` returns it. A JSON string scalar is therefore shown without its double quotes (`$.a[0]` rather than `"$.a[0]"`), while strings inside arrays and objects keep them. ## JSON_ARRAY ```sql JSON_ARRAY ([val1 [ , val2] ...]) ``` The **JSON_ARRAY** function returns a json array containing the given list (possibly empty) of values. ```sql SELECT JSON_ARRAY(); ``` | JSON_ARRAY() | |---| | [] | ```sql SELECT JSON_ARRAY(1, '1', json '{"a":4}', json '[1,2,3]'); ``` | JSON_ARRAY(1, '1', json '{"a":4}', json '[1,2,3]') | |---| | [1,"1",{"a":4},[1,2,3]] | ## JSON_OBJECT ```sql JSON_OBJECT ([key1, val1 [ , key2, val2] ...]) ``` The **JSON_OBJECT** function returns a json object containing the given list (possibly empty) of key-value pairs. ```sql SELECT JSON_OBJECT(); ``` | JSON_OBJECT() | |---| | {} | ```sql SELECT JSON_OBJECT('a', 1, 'b', '1', 'c', json '{"a":4}', 'd', json '[1,2,3]'); ``` | JSON_OBJECT('a', 1, 'b', '1', 'c', json '{"a":4}', 'd', json '[1,2,3]') | |---| | {"a":1,"b":"1","c":{"a":4},"d":[1,2,3]} | ## JSON_KEYS ```sql JSON_KEYS (json_doc [ , json path]) ``` The **JSON_KEYS** function returns a json array of all the object keys of the json object at the given path. Json null is returned if the path addresses a json element that is not a json object. If json path argument is missing, the keys are gathered from json root element. An error occurs if *json path* does not exist. Returns **NULL** if *json_doc* argument is **NULL**. ```sql SELECT JSON_KEYS('{}'); ``` | JSON_KEYS('{}') | |---| | [] | ```sql SELECT JSON_KEYS('"non-object"'); ``` | JSON_KEYS('"non-object"') | |---| | null | ```sql SELECT JSON_KEYS('{"a":1, "b":2, "c":{"d":1}}'); ``` | JSON_KEYS('{"a":1, "b":2, "c":{"d":1}}') | |---| | ["a","b","c"] | ## JSON_GET_ALL_PATHS ```sql JSON_GET_ALL_PATHS (json_doc) ``` Returns a JSON array with the path of every element of *json_doc*, including the root `$`. Object keys are written in double quotes (`$."a"`), and the paths of an element's children come before the path of the element itself. Returns **NULL** if the argument is **NULL**. ```sql SELECT JSON_GET_ALL_PATHS('[1, [2, 3]]'); ``` | JSON_GET_ALL_PATHS('[1, [2, 3]]') | |---| | ["$[0]","$[1][0]","$[1][1]","$[1]","$"] | ```sql SELECT JSON_GET_ALL_PATHS('{"a":["a","b"],"b":"a","c":{"d":1}}'); ``` | JSON_GET_ALL_PATHS('{"a":["a","b"],"b":"a","c":{"d":1}}') | |---| | `["$.\"a\"[0]","$.\"a\"[1]","$.\"a\"","$.\"b\"","$.\"c\".\"d\"","$.\"c\"","$"]` | A scalar has only the root path: ```sql SELECT JSON_GET_ALL_PATHS('"scalar"'); ``` | JSON_GET_ALL_PATHS('"scalar"') | |---| | ["$"] | ## JSON_DEPTH ```sql JSON_DEPTH (json_doc) ``` The **JSON_DEPTH** function returns the maximum depth of the json. Depth count starts at 1. The depth level is increased by one by non-empty json arrays or by non-empty json objects. Returns **NULL** if argument is **NULL**. ```sql SELECT JSON_DEPTH('"scalar"'); ``` | JSON_DEPTH('"scalar"') | |---| | 1 | ```sql SELECT JSON_DEPTH('[{"a":4}, 2]'); ``` | JSON_DEPTH('[{"a":4}, 2]') | |---| | 3 | Example of a deeper json: ```sql SELECT JSON_DEPTH('[{"a":[1,2,3,{"k":[4,5]}]},2,3,4,5,6,7]'); ``` | JSON_DEPTH('[{"a":[1,2,3,{"k":[4,5]}]},2,3,4,5,6,7]') | |---| | 6 | ## JSON_LENGTH ```sql JSON_LENGTH (json_doc [ , json path]) ``` The **JSON_LENGTH** function returns the length of the json element at the given path. If no path argument is given, the returned value is the length of the root json element. Returns **NULL** if any argument is **NULL** or if no element exists at the given path. ```sql SELECT JSON_LENGTH('"scalar"'); ``` | JSON_LENGTH('"scalar"') | |---| | 1 | ```sql SELECT JSON_LENGTH('[{"a":4}, 2]', '$.a'); ``` | JSON_LENGTH('[{"a":4}, 2]', '$.a') | |---| | NULL | ```sql SELECT JSON_LENGTH('[2, {"a":4, "b":4, "c":4}]', '$[1]'); ``` | JSON_LENGTH('[2, {"a":4, "b":4, "c":4}]', '$[1]') | |---| | 3 | ```sql SELECT JSON_LENGTH('[{"a":[1,2,3,{"k":[4,5,6,7,8]}]},2]'); ``` | JSON_LENGTH('[{"a":[1,2,3,{"k":[4,5,6,7,8]}]},2]') | |---| | 2 | ## JSON_VALID ```sql JSON_VALID (val) ``` The **JSON_VALID** function returns 1 if the given *val* argument is a valid json_doc, 0 otherwise. Returns **NULL** if argument is **NULL**. ```sql SELECT JSON_VALID('[{"a":4}, 2]'), JSON_VALID('{"wrong json object":'); ``` | JSON_VALID('[{"a":4}, 2]') | JSON_VALID('{"wrong json object":') | |---|---| | 1 | 0 | ## JSON_TYPE ```sql JSON_TYPE (json_doc) ``` The **JSON_TYPE** function returns the type of the *json_doc* argument as a string: `JSON_ARRAY`, `JSON_OBJECT`, `STRING`, `INTEGER`, `DOUBLE`, `BOOLEAN` or `JSON_NULL`. ```sql SELECT JSON_TYPE('[{"a":4}, 2]'), JSON_TYPE('{"a":4}'), JSON_TYPE('"aaa"'), JSON_TYPE('12'), JSON_TYPE('1.5'), JSON_TYPE('true'), JSON_TYPE('null'); ``` | JSON_TYPE('[{"a":4}, 2]') | JSON_TYPE('{"a":4}') | JSON_TYPE('"aaa"') | JSON_TYPE('12') | JSON_TYPE('1.5') | JSON_TYPE('true') | JSON_TYPE('null') | |---|---|---|---|---|---|---| | JSON_ARRAY | JSON_OBJECT | STRING | INTEGER | DOUBLE | BOOLEAN | JSON_NULL | ## JSON_QUOTE ```sql JSON_QUOTE (str) ``` Escapes quotes and special characters and surrounds the resulting string in quotes. Returns result as a json_string. Returns **NULL** if *str* argument is **NULL**. ```sql SELECT JSON_QUOTE ('simple'); ``` | JSON_QUOTE ('simple') | |---| | "simple" | ```sql SELECT JSON_QUOTE('"'); ``` | JSON_QUOTE('"') | |---| | `"\""` | ## JSON_UNQUOTE ```sql JSON_UNQUOTE (json_doc) ``` Unquotes a json_value's json string and returns the resulting string. Returns **NULL** if *json_doc* argument is **NULL**. Escape sequences such as `\"` and `\uXXXX` are decoded: ```sql SELECT JSON_UNQUOTE('"\""'); ``` | JSON_UNQUOTE('"\\""') | |---| | " | ## JSON_PRETTY ```sql JSON_PRETTY (json_doc) ``` Returns a string containing the *json_doc* pretty-printed. Returns **NULL** if *json_doc* argument is **NULL**. ```sql SELECT JSON_PRETTY('[{"a":"val1", "b":"val2", "c": [1, "elem2", 3, 4, {"key":"val"}]}]'); ``` ```json [ { "a": "val1", "b": "val2", "c": [ 1, "elem2", 3, 4, { "key": "val" } ] } ] ``` ## JSON_SEARCH ```sql JSON_SEARCH (json_doc, one/all, search_str [, escape_char [, json path] ...]) ``` Returns a json array of json paths or a single json path which contain json strings matching the given *search_str*. The matching is performed by applying the **LIKE** operator on internal json strings and *search_str*. Same rules apply for the *escape_char* and *search_str* of **JSON_SEARCH** as for their counter-parts from the **LIKE** operator. For further description of **LIKE**-related arguments rules refer to [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like). Using 'one' as one/all argument will cause the **JSON_SEARCH** to stop after the first match is found. On the other hand, 'all' will force **JSON_SEARCH** to gather all paths matching the given *search_str*. The given json paths determine filters on the returned paths, the resulting json paths's prefixes need to match at least one given json path argument. If no json path argument is given, **JSON_SEARCH** will execute the search starting from the root element. ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'one', 'a'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'one', 'a') | |---| | $.a[0] | ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a') | |---| | ["$.a[0]","$.b","$.c"] | ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.a', '$.b'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.a', '$.b') | |---| | ["$.a[0]","$.b"] | Wildcards can be used to define path filters as more general formats. Accepting only json paths that start with object key identifier: ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.*'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.*') | |---| | ["$.a[0]","$.b","$.c"] | Accepting only json paths that start with object key identifier and follow immediately with a json array index will filter out '\$.b', '\$.d.e\[0\]' matches: ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$.*[*]'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$.*[*]') | |---| | ["$.a[0]","$.c[0]"] | Accepting any paths that contain json array indexes will filter out '\$.b' ```sql SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$**[*]'); ``` | JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$**[*]') | |---| | ["$.a[0]","$.c[0]","$.d.e[0]"] | ## JSON_EXTRACT ```sql JSON_EXTRACT (json_doc, json path [, json path] ...) ``` Returns json elements from the *json_doc*, that are addressed by the given paths. If json path arguments contain wildcards, all elements that are addressed by a path compatible with the wildcards-containing json path are gathered in a resulting json array. A single json element is returned if no wildcards are used in the given json paths and a single element is found, otherwise the json elements found are wrapped in a json array. Raises an error if a json path is **NULL** or invalid or if *json_doc* argument is invalid. Returns **NULL** if no elements are found or if json_doc is **NULL**. ```sql SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a'); ``` | JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a') | |---| | ["a","b"] | ```sql SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a[*]'); ``` | JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a[*]') | |---| | ["a","b"] | Changing '.a' from previous query with '.\*' wildcards will also match '\$.c\[0\]'. This will match any json path that is exactly an object key identifier followed by an array index. ```sql SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.*[*]'); ``` | JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.*[*]') | |---| | ["a","b","a"] | The following json path will match all json paths that end with a json array index (matches all previous matched paths and, in addition, '\$.d.e\[0\]') ```sql SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$**[*]'); ``` | JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$**[*]') | |---| | ["a","b","a","a"] | ```sql SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.d**[*]'); ``` | JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.d**[*]') | |---| | ["a"] | ## -> operator ```sql column -> json_path ``` Short form of `JSON_EXTRACT(column, json_path)`. The left operand must be a column (of a table, a view or a derived table). It raises an error if *json_path* is **NULL** or invalid, and returns **NULL** when the column value is **NULL**. ## ->> operator ```sql column ->> json_path ``` Short form of `JSON_UNQUOTE(JSON_EXTRACT(column, json_path))`: it returns the value as a string, without the quotes of a JSON string. The e-commerce tables have no JSON column, so this example builds one in a derived table with JSON_OBJECT. Note that the NUMERIC price becomes a JSON double: ```sql SELECT t.j, t.j->'$.name' AS name_json, t.j->>'$.name' AS name_text, t.j->'$.price' AS price FROM (SELECT JSON_OBJECT('id', id, 'name', name, 'price', unit_price) AS j FROM product WHERE id < 3) t ORDER BY 1; ``` | j | name_json | name_text | price | |---|---|---|---| | {"id":1,"name":"Chai","price":18.0} | Chai | Chai | 18.0 | | {"id":2,"name":"Chang","price":19.0} | Chang | Chang | 19.0 | `name_json` is the JSON string `"Chai"` (shown without quotes, see the note at the top of the page); `name_text` is the plain string `Chai`. ## JSON_CONTAINS_PATH ```sql JSON_CONTAINS_PATH (json_doc, one/all, json path [, json path] ...) ``` The **JSON_CONTAINS_PATH** function verifies whether the given paths exist inside the *json_doc*. When one/all argument is 'all', all given paths must exist to return 1. Returns 0 otherwise. When one/all argument is 'one', it returns 1 if any given path exists. Returns 0 otherwise. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. ```sql SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]'); ``` | JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]') | |---| | 1 | ```sql SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]', '$.inexistent'); ``` | JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]', '$.inexistent') | |---| | 0 | The **JSON_CONTAINS_PATH** function supports wildcards inside json paths. ```sql SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'one', '$.inexistent', '$[*]."three"'); ``` | JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'one', '$.inexistent', '$[*]."three"') | |---| | 1 | ## JSON_CONTAINS ```sql JSON_CONTAINS (json_doc doc1, json_doc doc2 [, json path]) ``` The **JSON_CONTAINS** function verifies whether the *doc2* is contained inside the *doc1* at the optionally specified path. A json element contains another json element if the following recursive rules are satisfied: - A json scalar contains another json scalar if they have the same type (their **JSON_TYPE** () are equal) and are equal. As an exception, json integer can be compared and equal to json double (even if their **JSON_TYPE** () evaluation are different). - A json array contains a json scalar or a json object if any of json array's elements contains the json_nonarray. - A json array contains another json array if all the second json array's elements are contained in the first json array. - A json object contains another json object if, for every (*key2*, *value2*) pair in the second object, there exists a (*key1*, *value1*) pair in the first object with *key1* = *key2* and *value2* contained in *value1*. - Otherwise the json element is not contained. Returns whether *doc2* is contained in root json element of *doc1* if no json path argument is given. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. ```sql SELECT JSON_CONTAINS ('"simple"','"simple"'); ``` | JSON_CONTAINS ('"simple"','"simple"') | |---| | 1 | ```sql SELECT JSON_CONTAINS ('["a", "b"]','"b"'); ``` | JSON_CONTAINS ('["a", "b"]','"b"') | |---| | 1 | ```sql SELECT JSON_CONTAINS ('["a", "b1", ["a", "b2"]]','["b1", "b2"]'); ``` | JSON_CONTAINS ('["a", "b1", ["a", "b2"]]','["b1", "b2"]') | |---| | 1 | ```sql SELECT JSON_CONTAINS ('{"k1":["a", "b1"], "k2": ["a", "b2"]}','{"k1":"b1", "k2":"b2"}'); ``` | JSON_CONTAINS ('{"k1":["a", "b1"], "k2": ["a", "b2"]}','{"k1":"b1", "k2":"b2"}') | |---| | 1 | Note that json objects do not check containment the same way json arrays do. It is impossible to have a json element that is not a descendent of a json object contained in a sub-element of a json object. ```sql SELECT JSON_CONTAINS ('["a", "b1", ["a", {"k":"b2"}]]','["b1", "b2"]'); ``` | JSON_CONTAINS ('["a", "b1", ["a", {"k":"b2"}]]','["b1", "b2"]') | |---| | 0 | ```sql SELECT JSON_CONTAINS ('["a", "b1", ["a", {"k":["b2"]}]]','["b1", {"k":"b2"}]'); ``` | JSON_CONTAINS ('["a", "b1", ["a", {"k":["b2"]}]]','["b1", {"k":"b2"}]') | |---| | 1 | ## JSON_MERGE_PATCH ```sql JSON_MERGE_PATCH (json_doc, json_doc [, json_doc] ...) ``` The **JSON_MERGE_PATCH** function merges two or more json docs and returns the resulting merged json. **JSON_MERGE_PATCH** differs from **JSON_MERGE_PRESERVE** in that it will take the second argument when encountering merging conflicts. **JSON_MERGE_PATCH** is compliant with [RFC 7396](https://tools.ietf.org/html/rfc7396/). The merging of two json documents is performed with the following rules, recursively: - When two non-object jsons are merged, the result of the merge is the second value. - When a non-object json is merged with a json object, the result is the merge of an empty object with the second merging argument. - When two objects are merged, the resulting object consists of the following members: - All members from the first object that have no corresponding member with the same key in the second object. - All members from the second object that have no corresponding members with equal keys in the first object, having values not null. Members with null values from second object are ignored. - One member for each member in the first object that has a corresponding non-null valued member in the second object with the same key. Same key members that appear in both objects and the second object's member value is null, are ignored. The values of these pairs become the results of merging operations performed on the values of the members from the first and second object. Merge operations are executed serially when there are more than two arguments: the result of merging first two arguments is merged with third, this result is then merged with fourth and so on. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is not valid. ```sql SELECT JSON_MERGE_PATCH ('["a","b","c"]', '"scalar"'); ``` | JSON_MERGE_PATCH ('["a","b","c"]', '"scalar"') | |---| | scalar | The exception to the merge-patching, when the first argument is non-object and the second is an object. A merge operation is performed between an empty object and the second object argument. ```sql SELECT JSON_MERGE_PATCH ('["a"]', '{"a":null}'); ``` | JSON_MERGE_PATCH ('["a"]', '{"a":null}') | |---| | {} | Objects merging example, exemplifying the described object merging rules: ```sql SELECT JSON_MERGE_PATCH ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}'); ``` | JSON_MERGE_PATCH ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}') | |---| | {"a":null,"c":{},"d":"elem"} | ## JSON_MERGE_PRESERVE ```sql JSON_MERGE_PRESERVE (json_doc, json_doc [, json_doc] ...) ``` The **JSON_MERGE_PRESERVE** function merges two or more json docs and returns the resulting merged json. **JSON_MERGE_PRESERVE** differs from **JSON_MERGE_PATCH** in that it preserves both json elements on merging conflicts. The merging of two json documents is performed after the following rules, recursively: - When two json arrays are merged, they are concatenated. - When two non-array (scalar/object) json elements are merged and at most one of them is a json object, the result is an array containing the two json elements. - When a non-array json element is merged with a json array, the non-array is wrapped as a single element json array and then merged with the json array according to json array merging rules. - When two json objects are merged, all pairs that do not have a corresponding pair in the other json object are preserved. For matching keys, the values are always merged by applying the rules recursively. Merge operations are executed serially when there are more than two arguments: the result of merging first two arguments is merged with third, this result is then merged with fourth and so on. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is not valid. ```sql SELECT JSON_MERGE_PRESERVE ('"a"', '"b"'); ``` | JSON_MERGE_PRESERVE ('"a"', '"b"') | |---| | ["a","b"] | ```sql SELECT JSON_MERGE_PRESERVE ('["a","b","c"]', '"scalar"'); ``` | JSON_MERGE_PRESERVE ('["a","b","c"]', '"scalar"') | |---| | ["a","b","c","scalar"] | **JSON_MERGE_PRESERVE**, as opposed to **JSON_MERGE_PATCH**, will not drop and patch first argument's elements during merges and will gather them together. ```sql SELECT JSON_MERGE_PRESERVE ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}'); ``` | JSON_MERGE_PRESERVE ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}') | |---| | {"a":null,"c":["elem",{"k":null}],"b":null,"d":"elem"} | ## JSON_MERGE ```sql JSON_MERGE (json_doc, json_doc [, json_doc] ...) ``` **JSON_MERGE** is an alias for **JSON_MERGE_PRESERVE**. ## JSON_ARRAY_APPEND ```sql JSON_ARRAY_APPEND (json_doc, json path, json_val [, json path, json_val] ...) ``` The **JSON_ARRAY_APPEND** function returns a modified copy of the first argument. For each given \<*json path*, *json_val*\> pair, the function appends the value to the json array addressed by the corresponding path. The (*json path*, *json_val*) pairs are evaluated one by one, from left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated. If the json path points to a json array inside the *json_doc*, the *json_val* is appended at the end of the array. If the json path points to a non-array json element, the non-array gets wrapped as a single element json array containing the referred non-array element followed by the appending of the given *json_val*. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. ```sql SELECT JSON_ARRAY_APPEND ('{"a":[1,2]}','$.a','b'); ``` | JSON_ARRAY_APPEND ('{"a":[1,2]}','$.a','b') | |---| | {"a":[1,2,"b"]} | ```sql SELECT JSON_ARRAY_APPEND ('{"a":1}','$.a','b'); ``` | JSON_ARRAY_APPEND ('{"a":1}','$.a','b') | |---| | {"a":[1,"b"]} | ```sql SELECT JSON_ARRAY_APPEND ('{"a":[1,2]}', '$.a[0]', '1'); ``` | JSON_ARRAY_APPEND ('{"a":[1,2]}', '$.a[0]', '1') | |---| | {"a":[[1,"1"],2]} | ## JSON_ARRAY_INSERT ```sql JSON_ARRAY_INSERT (json_doc, json path, json_val [, json path, json_val] ...) ``` The **JSON_ARRAY_INSERT** function returns a modified copy of the first argument. For each given \<*json path*, *json_val*\> pair, the function inserts the value in the json array addressed by the corresponding path. The (*json path*, *json_val*) pairs are evaluated one by one, from left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated. The rules of the **JSON_ARRAY_INSERT** operation are the following: - If a json path addresses an element of a json_array, the given *json_val* is inserted at the specified index, shifting any following elements to the right. - If the json path points to an array index after the end of an array, the array is filled with nulls after end of the array until the specified index and the json_val is inserted at the specified index. - If the json path does not exist inside the *json_doc*, the last token of the json path is an array index and the json path without the last array index token would have pointed to an element inside the *json_doc*, the element found by the stripped json path is replaced with single element json array and the **JSON_ARRAY_INSERT** operation is performed with the original json path. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid or if a *json_path* does not address a cell of an array inside the *json_doc*. ```sql SELECT JSON_ARRAY_INSERT ('[0,1,2]', '$[0]', '1'); ``` | JSON_ARRAY_INSERT ('[0,1,2]', '$[0]', '1') | |---| | ["1",0,1,2] | ```sql SELECT JSON_ARRAY_INSERT ('[0,1,2]', '$[5]', '1'); ``` | JSON_ARRAY_INSERT ('[0,1,2]', '$[5]', '1') | |---| | [0,1,2,null,null,"1"] | Examples for **JSON_ARRAY_INSERT's** third rule. ```sql SELECT JSON_ARRAY_INSERT ('{"a":4}', '$[5]', '1'); ``` | JSON_ARRAY_INSERT ('{"a":4}', '$[5]', '1') | |---| | [{"a":4},null,null,null,null,"1"] | ```sql SELECT JSON_ARRAY_INSERT ('"a"', '$[5]', '1'); ``` | JSON_ARRAY_INSERT ('"a"', '$[5]', '1') | |---| | ["a",null,null,null,null,"1"] | ## JSON_INSERT ```sql JSON_INSERT (json_doc, json path, json_val [, json path, json_val] ...) ``` The **JSON_INSERT** function returns a modified copy of the first argument. For each given \<*json path*, *json_val*\> pair, the function inserts the value if no other value exists at the corresponding path. The insertion rules for **JSON_INSERT** are the following: The *json_val* is inserted if the json path addresses one of the following json values inside the *json_doc*: - An inexistent object member of an existing json object. A (*key*, *value*) pair is added to the json object with the key being json path's last element and the value being the *json_val*. - An array index past of an existing json array's end. The array is filled with nulls after the initial end of the array and the *json_val* is inserted at the specified index. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. Paths to existing elements inside the *json_doc* are ignored: ```sql SELECT JSON_INSERT ('{"a":1}','$.a','b'); ``` | JSON_INSERT ('{"a":1}','$.a','b') | |---| | {"a":1} | ```sql SELECT JSON_INSERT ('{"a":1}','$.b','1'); ``` | JSON_INSERT ('{"a":1}','$.b','1') | |---| | {"a":1,"b":"1"} | ```sql SELECT JSON_INSERT ('[0,1,2]','$[4]','1'); ``` | JSON_INSERT ('[0,1,2]','$[4]','1') | |---| | [0,1,2,null,"1"] | ## JSON_SET ```sql JSON_SET (json_doc, json path, json_val [, json path, json_val] ...) ``` The **JSON_SET** function returns a modified copy of the first argument. For each given \<*json path*, *json_val*\> pair, the function inserts or replaces the value at the corresponding path. Otherwise, the *json_val* is inserted if the json path addresses one of the following json values inside the *json_doc*: - An inexistent object member of an existing json object. A (*key*, *value*) pair is added to the json object with the key deduced from the json path and the value being the *json_val*. - An array index past of an existing json array's end. The array is filled with nulls after the initial end of the array and the *json_val* is inserted at the specified index. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. ```sql SELECT JSON_SET ('{"a":1}','$.a','b'); ``` | JSON_SET ('{"a":1}','$.a','b') | |---| | {"a":"b"} | ```sql SELECT JSON_SET ('{"a":1}','$.b','1'); ``` | JSON_SET ('{"a":1}','$.b','1') | |---| | {"a":1,"b":"1"} | ```sql SELECT JSON_SET ('[0,1,2]','$[4]','1'); ``` | JSON_SET ('[0,1,2]','$[4]','1') | |---| | [0,1,2,null,"1"] | ## JSON_REPLACE ```sql JSON_REPLACE (json_doc, json path, json_val [, json path, json_val] ...) ``` The **JSON_REPLACE** function returns a modified copy of the first argument. For each given \<*json path*, *json_val*\> pair, the function replaces the value only if another value is found at the corresponding path. If the *json_path* does not exist inside the *json_doc*, the (*json path*, *json_val*) pair is ignored and has no effect. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid. ```sql SELECT JSON_REPLACE ('{"a":1}','$.a','b'); ``` | JSON_REPLACE ('{"a":1}','$.a','b') | |---| | {"a":"b"} | No replacement is done if the *json path*\` does not exist inside the *json_doc*. ```sql SELECT JSON_REPLACE ('{"a":1}','$.b','1'); ``` | JSON_REPLACE ('{"a":1}','$.b','1') | |---| | {"a":1} | ```sql SELECT JSON_REPLACE ('[0,1,2]','$[4]','1'); ``` | JSON_REPLACE ('[0,1,2]','$[4]','1') | |---| | [0,1,2] | ## JSON_REMOVE ```sql JSON_REMOVE (json_doc, json path [, json path] ...) ``` The **JSON_REMOVE** function returns a modified copy of the first argument, by removing values from all given paths. The json path arguments are evaluated one by one, from left to right. The result produced by evaluating a json path becomes the value against which the next json path is evaluated. Returns **NULL** if any argument is **NULL**. An error occurs if any argument is invalid or if a path points to the root or if a path does not exist. ```sql SELECT JSON_REMOVE ('[0,1,2]','$[1]'); ``` | JSON_REMOVE ('[0,1,2]','$[1]') | |---| | [0,2] | ```sql SELECT JSON_REMOVE ('{"a":1,"b":2}','$.a'); ``` | JSON_REMOVE ('{"a":1,"b":2}','$.a') | |---| | {"b":2} | ## JSON_TABLE **JSON_TABLE** turns JSON into rows and columns that can be queried like a table, for example one row per element of a JSON array. ```text JSON_TABLE ( expr, path COLUMNS (column_list) ) [AS] alias column_list ::= column [, column] ... column ::= name FOR ORDINALITY | name type PATH string_path [on_empty] [on_error] | name type EXISTS PATH string_path | NESTED [PATH] string_path COLUMNS (column_list) on_empty ::= { NULL | ERROR | DEFAULT value } ON EMPTY on_error ::= { NULL | ERROR | DEFAULT value } ON ERROR ``` - *expr* is the JSON document: a constant, a column, or the result of a function. It can refer to columns of tables listed before JSON_TABLE in the `FROM` clause. - *path* selects the values that produce rows; each value found becomes one row. The alias is required. - The **COLUMNS** clause defines the output columns: - *name* **FOR ORDINALITY**: the row number within the current **COLUMNS** clause, starting at 1 (type INTEGER). - *name* *type* **PATH** *string_path*: the value at *string_path* (relative to the row's value), converted to *type*. If the path is missing, the **ON EMPTY** clause applies; if the value cannot be converted, the **ON ERROR** clause applies. The default for both is **NULL**; **ERROR** raises an error and **DEFAULT** *value* uses *value*. - *name* *type* **EXISTS PATH** *string_path*: 1 if the path exists, otherwise 0. - **NESTED** \[**PATH**\] *string_path* **COLUMNS** (...): expands the values found at *string_path* into further rows, combined with the parent row like a nested loop. The same rules apply recursively. Each element of `$.a` becomes a row. The second element, `[2,3]`, cannot be converted to INT, so the default **NULL ON ERROR** applies: ```sql SELECT * FROM JSON_TABLE('{"a":[1,[2,3]]}', '$.a[*]' COLUMNS (col INT PATH '$')) AS jt; ``` | col | |---| | 1 | | NULL | With **DEFAULT ... ON ERROR**, the default value replaces it: ```sql SELECT * FROM JSON_TABLE('{"a":[1,[2,3]]}', '$.a[*]' COLUMNS (col INT PATH '$' DEFAULT '-1' ON ERROR)) AS jt; ``` | col | |---| | 1 | | -1 | Missing paths, **ON EMPTY** and **EXISTS PATH**: ```sql SELECT * FROM JSON_TABLE('{"a":1}', '$' COLUMNS (col1 INT PATH '$.a', col2 INT PATH '$.b', col3 INT PATH '$.c' DEFAULT '0' ON EMPTY)) AS jt; ``` | col1 | col2 | col3 | |---|---|---| | 1 | NULL | 0 | ```sql SELECT * FROM JSON_TABLE('{"a":1,"b":[1]}', '$' COLUMNS (has_a INT EXISTS PATH '$.a', has_z INT EXISTS PATH '$.z')) AS jt; ``` | has_a | has_z | |---|---| | 1 | 0 | ### NESTED PATH Here `'$.*'` produces one parent row for each member value of the root object, and `NESTED PATH '$[*]'` expands each value that is an array. The nested ordinality column restarts at 1 for every parent row. The value `6` is not an array, so its nested columns are **NULL**: ```sql SELECT * FROM JSON_TABLE( '{"a":[1,2],"b":[3,4,5],"d":6,"c":[7]}', '$.*' COLUMNS (ord FOR ORDINALITY, col JSON PATH '$', NESTED PATH '$[*]' COLUMNS (nested_ord FOR ORDINALITY, nested_col JSON PATH '$')) ) AS jt; ``` | ord | col | nested_ord | nested_col | |---|---|---|---| | 1 | [1,2] | 1 | 1 | | 1 | [1,2] | 2 | 2 | | 2 | [3,4,5] | 1 | 3 | | 2 | [3,4,5] | 2 | 4 | | 2 | [3,4,5] | 3 | 5 | | 3 | 6 | NULL | NULL | | 4 | [7] | 1 | 7 | Sibling **NESTED PATH** clauses are processed one after the other: while one of them produces rows, the columns of the others are **NULL**. In the second parent row, `$.key1` is the scalar `6`, so `$.key1[*]` produces no rows: ```sql SELECT * FROM JSON_TABLE( '{"a":{"key1":[1,2], "key2":[3,4,5]},"b":{"key1":6, "key2":[7]}}', '$.*' COLUMNS (ord FOR ORDINALITY, col JSON PATH '$', NESTED PATH '$.key1[*]' COLUMNS (nested_ord1 FOR ORDINALITY, nested_col1 JSON PATH '$'), NESTED PATH '$.key2[*]' COLUMNS (nested_ord2 FOR ORDINALITY, nested_col2 JSON PATH '$')) ) AS jt; ``` | ord | col | nested_ord1 | nested_col1 | nested_ord2 | nested_col2 | |---|---|---|---|---|---| | 1 | {"key1":[1,2],"key2":[3,4,5]} | 1 | 1 | NULL | NULL | | 1 | {"key1":[1,2],"key2":[3,4,5]} | 2 | 2 | NULL | NULL | | 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 1 | 3 | | 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 2 | 4 | | 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 3 | 5 | | 2 | {"key1":6,"key2":[7]} | NULL | NULL | 1 | 7 | ### JSON_TABLE over table rows *expr* can use the columns of a table that comes before JSON_TABLE in the `FROM` clause; JSON_TABLE is then evaluated once per row: ```sql SELECT p.id, jt.* FROM product p, JSON_TABLE(JSON_OBJECT('name', p.name, 'stock', p.units_in_stock), '$' COLUMNS (name VARCHAR(64) PATH '$.name', stock INT PATH '$.stock', missing INT PATH '$.x' DEFAULT '0' ON EMPTY)) AS jt WHERE p.id < 3 ORDER BY p.id; ``` | id | name | stock | missing | |---|---|---|---| | 1 | Chai | 39 | 0 | | 2 | Chang | 17 | 0 | ## JSON functions for graph elements These functions return vertices and edges matched by a [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern as JSON. Their argument is a vertex or edge alias of the pattern; the result is **NULL** when the argument is **NULL**. Every vertex and edge is identified by its object identifier (OID), written as `(volume|page|slot)`. OIDs depend on how the data was loaded, so the identifiers in your database will differ from the ones shown below. The examples use product 1618 (*Gobi HeatTec Tee*), which is manufactured by the brand *Diadora*, belongs to a category and is available at a supplier. ## JSON_PROPERTIES ```sql JSON_PROPERTIES (vertex_or_edge) ``` Returns a JSON object with the OID of the element (`id`) and its column values (`properties`). NUMERIC values become JSON doubles; DATETIME values are written as strings. ```sql SELECT JSON_PROPERTIES(p) AS props FROM MATCH (p:product) WHERE p.id = 1618; ``` ```json {"id":"(0|4490|63)","properties":{"id":1618,"units_in_stock":22,"unit_price":29.0,"description":"Size XL, Black","name":"Gobi HeatTec Tee"}} ``` ## JSON_NODE_PROPERTIES ```sql JSON_NODE_PROPERTIES (vertex) ``` The same as [JSON_PROPERTIES](https://www.coradb.ai/manual/sql/function/json_fn.html#json_properties), for a vertex. ```sql SELECT JSON_NODE_PROPERTIES(b) AS v FROM MATCH (b:brand) WHERE b.name = 'Diadora'; ``` ```json {"id":"(0|4545|52)","properties":{"id":52,"name":"Diadora"}} ``` ## JSON_EDGE_PROPERTIES ```sql JSON_EDGE_PROPERTIES (edge) ``` The same as [JSON_PROPERTIES](https://www.coradb.ai/manual/sql/function/json_fn.html#json_properties), for an edge. ```sql SELECT JSON_EDGE_PROPERTIES(m) AS e FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE p.id = 1618; ``` ```json {"id":"(0|4931|461)","properties":{"since":"06:22:04.000 AM 02/28/2013"}} ``` ## JSON_INFO ```sql JSON_INFO (vertex_or_edge) ``` Returns the OID, the properties and the label (vertex or edge table name) of the element. For a vertex, `adj_list` also lists its edges, as [JSON_ADJACENCY_LIST](https://www.coradb.ai/manual/sql/function/json_fn.html#json_adjacency_list) does. ```sql SELECT JSON_INFO(m) AS i FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE p.id = 1618; ``` ```json {"id":"(0|4931|461)","properties":{"since":"06:22:04.000 AM 02/28/2013"},"label":"manufactures"} ``` The JSON functions combine with it. Diadora has 18 edges: 8 incoming `follows` edges from customers and 10 outgoing edges, 9 of which are `manufactures` edges to its products. ```sql SELECT JSON_EXTRACT(JSON_INFO(b), '$.label') AS kind, JSON_EXTRACT(JSON_INFO(b), '$.properties.name') AS brand_name, JSON_LENGTH(JSON_INFO(b), '$.adj_list') AS edges FROM MATCH (b:brand) WHERE b.name = 'Diadora'; ``` | kind | brand_name | edges | |---|---|---| | brand | Diadora | 18 | ## JSON_GRAPH ```sql JSON_GRAPH (element [, element] ...) ``` Returns the given vertices and edges as one graph document with a `nodes` array and an `edges` array. Each edge carries the OIDs of its start and end vertex. Combine it with [JSON_PRETTY](https://www.coradb.ai/manual/sql/function/json_fn.html#json_pretty) for readable output. ```sql SELECT JSON_PRETTY(JSON_GRAPH(b, m, p)) AS g FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE p.id = 1618; ``` ```json { "nodes": [ { "id": "(0|4490|63)", "label": "product", "properties": { "id": 1618, "units_in_stock": 22, "unit_price": 29.000000, "description": "Size XL, Black", "name": "Gobi HeatTec Tee" } }, { "id": "(0|4545|52)", "label": "brand", "properties": { "id": 52, "name": "Diadora" } } ], "edges": [ { "id": "(0|4931|461)", "startNodeId": "(0|4545|52)", "endNodeId": "(0|4490|63)", "label": "manufactures", "properties": { "since": "06:22:04.000 AM 02/28/2013" } } ] } ``` ## JSON_ADJACENCY_LIST ```sql JSON_ADJACENCY_LIST (vertex) ``` Returns all edges of a vertex as a JSON array. Each entry has the OID of the edge (`edge_id`), the OID of the vertex at the other end (`dest`) and the direction (`dir`): `"0"` for an outgoing edge, `"1"` for an incoming edge. ```sql SELECT JSON_ADJACENCY_LIST(p) AS adjacency FROM MATCH (p:product) WHERE p.id = 1618; ``` ```json [{"edge_id":"(0|5571|425)","dest":"(0|4609|6)","dir":"0"},{"edge_id":"(0|4677|331)","dest":"(0|4417|23)","dir":"0"},{"edge_id":"(0|4931|461)","dest":"(0|4545|52)","dir":"1"}] ``` The product has two outgoing edges (`available_at` to a supplier and `part_of` to a category) and one incoming edge (`manufactures` from Diadora). ## JSON_TOPOLOGY_RECORD ```sql JSON_TOPOLOGY_RECORD (vertex) ``` Returns the topology record that the graph engine keeps for a vertex: the vertex OID (`prop_oid`) and, for each edge, the edge and the adjacent vertex with their labels and visibility. ```sql SELECT JSON_TOPOLOGY_RECORD(p) AS topology FROM MATCH (p:product) WHERE p.id = 1618; ``` ```json {"prop_oid":"(0|4490|63)","list_adj":[{"edge":{"id":"(0|4677|331)","label":"part_of","visible":"yes"},"adj_node":{"id":"(0|4417|23)","label":"category","visible":"yes"}},{"edge":{"id":"(0|4931|461)","label":"manufactures","visible":"yes"},"adj_node":{"id":"(0|4545|52)","label":"brand","visible":"yes"}},{"edge":{"id":"(0|5571|425)","label":"available_at","visible":"yes"},"adj_node":{"id":"(0|4609|6)","label":"supplier","visible":"yes"}}]} ``` ## JSON_GRAPH_HEAP_MEMORY_USAGE ```sql JSON_GRAPH_HEAP_MEMORY_USAGE () ``` Returns statistics about the memory the server uses for the graph topology: the number of vertices and edges, page and container sizes, the size of the in-memory topology and its buffer distribution, and the read-only page buffer. The values depend on the server's state. ```sql SELECT JSON_EXTRACT(JSON_GRAPH_HEAP_MEMORY_USAGE(), '$.vertices.number_of_vertices') AS vertices, JSON_EXTRACT(JSON_GRAPH_HEAP_MEMORY_USAGE(), '$.edges.number_of_edges') AS edges; ``` | vertices | edges | |---|---| | 3397 | 12808 | The top-level members are `vertices`, `edges` and `ro_page_buffer`. ## See also - [JSON data type](https://www.coradb.ai/manual/sql/datatype_json.html#json-data-type) - [JSON_ARRAYAGG and JSON_OBJECTAGG](https://www.coradb.ai/manual/sql/function/analysis_fn.html) - [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html) --- # List functions: COLLECT_LIST, FIRST, LAST, AT, TAIL, SIZE, RANGE, LIST_COMP, REDUCE Source: https://www.coradb.ai/manual/sql/function/list_fn.html List functions build and process ordered collections (`SEQUENCE` values, also called lists). They work the same way in relational queries and in graph queries with [MATCH](https://www.coradb.ai/manual/graph/match.html), and they combine well with each other: `COLLECT_LIST` turns rows into a list, and the other functions read or transform it. | Function | Returns | |---|---| | [COLLECT_LIST](https://www.coradb.ai/manual/sql/function/list_fn.html#collect_list) | Aggregate: the values of a group of rows as one list | | [FIRST](https://www.coradb.ai/manual/sql/function/list_fn.html#first), [LAST](https://www.coradb.ai/manual/sql/function/list_fn.html#last) | The first or last element | | [AT](https://www.coradb.ai/manual/sql/function/list_fn.html#at) | The element at a zero-based position | | [TAIL](https://www.coradb.ai/manual/sql/function/list_fn.html#tail) | The list without its first element | | [SIZE](https://www.coradb.ai/manual/sql/function/list_fn.html#size) | The number of elements | | [RANGE](https://www.coradb.ai/manual/sql/function/list_fn.html#range) | A list of integers | | [LIST_COMP](https://www.coradb.ai/manual/sql/function/list_fn.html#list_comp) | A new list with an expression applied to every element | | [REDUCE](https://www.coradb.ai/manual/sql/function/list_fn.html#reduce) | One value computed from all elements | Collection literals are written in braces: `{1, 2, 3}`. In corasql, list results are displayed the same way. The graph examples use the brand **Diadora**, which manufactures nine products: ```sql SELECT collect_list(p.name ORDER BY p.name) AS product_names FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` ```text product_names ========================================================================== {'Abominable Hoodie', 'Beaumont Summit Kit', 'Bess Yoga Short', 'Circe Hooded Ice Fleece', 'Gobi HeatTec Tee', 'Helena Hooded Fleece', 'Kenobi Trail Jacket', 'Neve Studio Dance Jacket', 'Viktor LumaTech Pant'} ``` ## COLLECT_LIST ```sql COLLECT_LIST ( expression [ ORDER BY expression [ASC | DESC] ] ) ``` An aggregate function that returns the values of *expression* in a group of rows as one list. Like other aggregate functions it can be used with or without `GROUP BY`. - **NULL** values are skipped. If the group has no rows, or only **NULL** values, the result is **NULL**. - Without `ORDER BY` the order of the elements is not defined. The `ORDER BY` expression must be the aggregated expression itself (or its position, `1`): `COLLECT_LIST(p.name ORDER BY p.name)` is valid, `COLLECT_LIST(p.name ORDER BY p.unit_price)` is an error. **Return type:** SEQUENCE The products and quantities of the first four orders, one list per order: ```sql SELECT order_id, collect_list(product_id ORDER BY product_id) AS products, collect_list(quantity) AS quantities FROM order_items WHERE order_id < 4 GROUP BY order_id ORDER BY order_id; ``` | order_id | products | quantities | |---|---|---| | 0 | {123, 1274, 1379, 1634} | {1, 1, 1, 1} | | 1 | {1137} | {2} | | 2 | {1575, 1619} | {2, 4} | | 3 | {607, 1207, 1634} | {1, 1, 12} | The prices of Diadora's products, highest first: ```sql SELECT collect_list(p.unit_price ORDER BY p.unit_price DESC) AS prices FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | prices | |---| | {69.00, 69.00, 68.00, 55.00, 47.00, 46.00, 42.00, 29.00, 28.00} | NULL values are not collected. Customer 31 has three orders, but only two have been shipped: ```sql SELECT customer_id, collect_list(shipped_date ORDER BY shipped_date) AS shipped, COUNT(*) AS orders FROM orders WHERE customer_id = 31 GROUP BY customer_id; ``` | customer_id | shipped | orders | |---|---|---| | 31 | {2022-01-29, 2025-12-17} | 3 | ## FIRST ```sql FIRST ( list ) ``` Returns the first element of *list*. **Return type:** the type of the elements. ## LAST ```sql LAST ( list ) ``` Returns the last element of *list*. **Return type:** the type of the elements. > **Warning:** > `FIRST` and `LAST` of an empty list raise the error *Sequence index 0 is out of bounds*. Check the list with [SIZE](https://www.coradb.ai/manual/sql/function/list_fn.html#size) first if it can be empty. ```sql SELECT first({1, 2, 3}) AS a, last({1, 2, 3}) AS b; ``` | a | b | |---|---| | 1 | 3 | Combined with `COLLECT_LIST ... ORDER BY`, they return the extremes of a group, here Diadora's highest and lowest price: ```sql SELECT first(collect_list(p.unit_price ORDER BY p.unit_price DESC)) AS highest, last(collect_list(p.unit_price ORDER BY p.unit_price DESC)) AS lowest, size(collect_list(p.id)) AS products FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | highest | lowest | products | |---|---|---| | 69.00 | 28.00 | 9 | With `GROUP BY`, one value per group. For four brands, the number of products and the alphabetically first product name: ```sql SELECT b.name AS brand, size(collect_list(p.id)) AS products, first(collect_list(p.name ORDER BY p.name)) AS first_name FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name IN ('Diadora', 'Rab', 'Reebok', 'Wilson') GROUP BY b.name ORDER BY b.name; ``` | brand | products | first_name | |---|---|---| | Diadora | 9 | Abominable Hoodie | | Rab | 11 | Ajax Full-Zip Sweatshirt | | Reebok | 11 | Abominable Hoodie | | Wilson | 11 | Apollo Running Short | With a path variable, `FIRST(NODES(path))` and `LAST(NODES(path))` return the start and end vertex of a path; see [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html). ## AT ```sql AT ( list, index ) ``` Returns the element of *list* at position *index*. Positions start at **0**. An index that is negative or not smaller than the size of the list raises the error *Sequence index n is out of bounds*. **Return type:** the type of the element. ```sql SELECT AT({1, 2, 3}, 1) AS a, AT(AT({ {1, 2}, {3, 4}, {5, 6} }, 1), 0) AS b; ``` | a | b | |---|---| | 2 | 3 | The second call reads element 1 of the outer list, `{3, 4}`, and then its element 0. Diadora's third-highest price (position 2): ```sql SELECT AT(collect_list(p.unit_price ORDER BY p.unit_price DESC), 2) AS third_highest FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | third_highest | |---| | 68.00 | ## TAIL ```sql TAIL ( list ) ``` Returns *list* without its first element. For a list with one element or an empty list, it returns an empty list. Nest it to skip more elements: `TAIL(TAIL(list))` skips two. **Return type:** SEQUENCE ```sql SELECT TAIL({1, 2, 3}) AS a, TAIL({1}) AS b, TAIL(TAIL({ {1, 2}, {3, 4}, {5, 6} })) AS c; ``` | a | b | c | |---|---|---| | {2, 3} | {} | {{5, 6}} | ## SIZE ```sql SIZE ( list ) ``` Returns the number of elements in *list*, including duplicates and **NULL** elements. An empty list has size 0. For a list of lists, only the outer elements are counted. **Return type:** INTEGER ```sql SELECT size({2, 2, 3, 3}) AS a, size({{1, 2}, {3, 4}, {5, 6}}) AS b, size({}) AS c; ``` | a | b | c | |---|---|---| | 4 | 3 | 0 | ## RANGE ```sql RANGE ( start, end, step ) ``` Returns the integers from *start* to *end*, both included, in steps of *step*. A negative *step* counts down. If *step* points away from *end*, the result is an empty list; if *step* is larger than the distance, only *start* is returned. Non-integer arguments are rounded to the nearest integer. **Return type:** SEQUENCE of INTEGER ```sql SELECT range(1, 5, 1) AS a, range(5, 1, -1) AS b, range(1.5, 11, 3) AS c, range(1, 5, -1) AS d, range(-5, 5, 11) AS e; ``` | a | b | c | d | e | |---|---|---|---|---| | {1, 2, 3, 4, 5} | {5, 4, 3, 2, 1} | {2, 5, 8, 11} | {} | {-5} | In `c`, the start value 1.5 is rounded to 2. ## LIST_COMP ```sql LIST_COMP ( variable IN list | expression ) ``` List comprehension: evaluates *expression* once for every element of *list*, with *variable* standing for the element, and returns the results as a new list in the same order. An empty list gives an empty list. **Return type:** SEQUENCE ```sql SELECT list_comp(x IN {1, 2, 3} | x * 2) AS a, list_comp(x IN range(1, 5, 1) | x * x) AS b, list_comp(x IN {'a', 'bb', 'ccc'} | CHAR_LENGTH(x)) AS c; ``` | a | b | c | |---|---|---| | {2, 4, 6} | {1, 4, 9, 16, 25} | {1, 2, 3} | Diadora's prices with a 10% discount: ```sql SELECT list_comp(x IN collect_list(p.unit_price ORDER BY p.unit_price DESC) | ROUND(x * 0.9, 2)) AS sale_prices FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | sale_prices | |---| | {62.10, 62.10, 61.20, 49.50, 42.30, 41.40, 37.80, 26.10, 25.20} | ## REDUCE ```sql REDUCE ( accumulator = initial_value, variable IN list | expression ) ``` Folds *list* into one value. *accumulator* starts at *initial_value*; for every element, *expression* (which can use *accumulator* and *variable*) is evaluated and becomes the new value of *accumulator*. The final value is returned. For an empty list, the result is *initial_value*. If *expression* returns **NULL** for any element, the following steps start from **NULL**: with `v + x`, one **NULL** element makes the result **NULL**. **Return type:** the type of *expression*. ```sql SELECT reduce(v = 0, x IN {1, 2, 3, 4, 5} | v + x) AS a, reduce(v = 0, x IN {1, NULL, 3} | v + x) AS b; ``` | a | b | |---|---| | 15 | NULL | The units in stock of all Diadora products; the result matches `SUM`: ```sql SELECT reduce(v = 0, x IN collect_list(p.units_in_stock) | v + x) AS units, SUM(p.units_in_stock) AS check_sum FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE b.name = 'Diadora'; ``` | units | check_sum | |---|---| | 282 | 282 | ## See also - [Graph functions (NODES, RELATIONSHIPS, path comprehension)](https://www.coradb.ai/manual/sql/function/graph_fn.html) - [List predicates (ALL, ANY, NONE, SINGLE)](https://www.coradb.ai/manual/sql/function/predicate_fn.html) - [Aggregate and analytic functions](https://www.coradb.ai/manual/sql/function/analysis_fn.html) - [Collection data types](https://www.coradb.ai/manual/sql/datatype_collection.html#collection-types) --- # LOB functions Source: https://www.coradb.ai/manual/sql/function/lob_fn.html LOB functions convert values to and from the large object types `BLOB` (binary data) and `CLOB` (character data), read files into LOBs, and return LOB sizes. For how LOB values are stored, see [BLOB/CLOB](https://www.coradb.ai/manual/sql/datatype.html). The examples use a scratch table for product documents: ```sql CREATE TABLE product_doc (product_id INT PRIMARY KEY, manual CLOB, thumbnail BLOB); INSERT INTO product_doc VALUES (1795, CHAR_TO_CLOB('Machine wash cold. Do not bleach.'), BIT_TO_BLOB(X'89504E47')); INSERT INTO product_doc VALUES (123, 'Hand wash only.', CHAR_TO_BLOB('icon')); -- strings are converted to CLOB automatically SELECT product_id, CLOB_LENGTH(manual), CLOB_TO_CHAR(manual), BLOB_LENGTH(thumbnail), BLOB_TO_BIT(thumbnail) FROM product_doc ORDER BY product_id; ``` | product_id | clob_length(manual) | clob_to_char(manual) | blob_length(thumbnail) | blob_to_bit(thumbnail) | |---:|---:|---|---:|---| | 123 | 15 | Hand wash only. | 4 | 0x69636f6e | | 1795 | 33 | Machine wash cold. Do not bleach. | 4 | 0x89504e47 | ## CHAR_TO_CLOB, CLOB_TO_CHAR ```text CHAR_TO_CLOB(string) CLOB_TO_CHAR(clob [USING charset]) ``` `CHAR_TO_CLOB` converts a `CHAR` or `VARCHAR` value to `CLOB`. `CLOB_TO_CHAR` converts a `CLOB` value to `VARCHAR`; `USING` names the character set of the result (`utf8`, `euckr` or `iso88591`). ## CHAR_TO_BLOB, BIT_TO_BLOB, BLOB_TO_BIT ```text CHAR_TO_BLOB(string) BIT_TO_BLOB(bit_value) BLOB_TO_BIT(blob) ``` `CHAR_TO_BLOB` stores the bytes of a string as a `BLOB`; `BIT_TO_BLOB` converts a `BIT` or `BIT VARYING` value to `BLOB`; `BLOB_TO_BIT` converts a `BLOB` back to `BIT VARYING`. ## CLOB_LENGTH, BLOB_LENGTH ```text CLOB_LENGTH(clob) BLOB_LENGTH(blob) ``` Return the size of a LOB value, in bytes. **Return type:** BIGINT. ## CLOB_FROM_FILE, BLOB_FROM_FILE ```text CLOB_FROM_FILE(file_path) BLOB_FROM_FILE(file_path) ``` Read a file and return its contents as a `CLOB` or `BLOB`. *file_path* is a `VARCHAR`: a path on the machine where the server-side client process runs (the broker's CAS process, or corasql), optionally prefixed with `file:`. A relative path starts from that process's current working directory. Statements that call these functions are not stored in the query plan cache. ```sql INSERT INTO product_doc VALUES (335, CLOB_FROM_FILE('file:/data/manuals/335.txt'), BLOB_FROM_FILE('/data/thumbnails/335.png')); ``` --- # Logical operators Source: https://www.coradb.ai/manual/sql/function/logical_op.html Logical operators combine conditions. Their operands are boolean expressions or numbers: 0 is false, any other number is true, and `NULL` is unknown. The result is 1 (true), 0 (false) or `NULL`. | Operator | Result | |---|---| | `AND`, `&&` | True if both operands are true. | | `OR` | True if at least one operand is true. | | `XOR` | True if exactly one operand is true; `NULL` if either operand is `NULL`. | | `NOT`, `!` | True if the operand is false, and false if it is true. | `||` means `OR` only when the [pipes_as_concat](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `no`. By default it is `yes`, and `||` concatenates strings: `'a' || 'b'` returns `'ab'`. ## Truth table | a | b | A AND b | A OR b | A XOR b | NOT a | |---|---|---|---|---|---| | TRUE | TRUE | TRUE | TRUE | FALSE | FALSE | | TRUE | FALSE | FALSE | TRUE | TRUE | FALSE | | TRUE | NULL | NULL | TRUE | NULL | FALSE | | FALSE | TRUE | FALSE | TRUE | TRUE | TRUE | | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | | FALSE | NULL | FALSE | NULL | NULL | TRUE | | NULL | NULL | NULL | NULL | NULL | NULL | ```sql SELECT (1 AND NULL), (0 AND NULL), (1 OR NULL), (0 OR NULL), (1 XOR 0), (NOT NULL), (2 AND 3) FROM db_root; ``` | (1 AND NULL) | (0 AND NULL) | (1 OR NULL) | (0 OR NULL) | (1 XOR 0) | (NOT NULL) | (2 AND 3) | |---|---|---|---|---|---|---| | NULL | 0 | 1 | NULL | 1 | NULL | 1 | In a `WHERE` clause, a row is returned only when the condition is true; rows for which it is false or `NULL` are left out. ## See also - [Comparison operators](https://www.coradb.ai/manual/sql/function/comparison_op.html) - [Operators and functions overview](https://www.coradb.ai/manual/sql/function.html) --- # Numeric and mathematical functions Source: https://www.coradb.ai/manual/sql/function/numeric_fn.html ## ABS ```sql ABS (number_expr) ``` The **ABS** function returns the absolute value of a given number. The data type of the return value is the same as that of the argument. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_expr`: An operator which returns a numeric value **Return type:** same as that of the argument ```sql --it returns the absolute value of the argument SELECT ABS(12.3), ABS(-12.3), ABS(-12.3000), ABS(0.0); ``` | ABS(12.3) | ABS(-12.3) | ABS(-12.3000) | ABS(0.0) | |---|---|---|---| | 12.3 | 12.3 | 12.3000 | 0.0 | ## ACOS ```sql ACOS ( x ) ``` The **ACOS** function returns an arc cosine value of the argument. That is, it returns a value whose cosine is *x* in radian. The return value is a **DOUBLE** type. x must be a value between -1 and 1, inclusive. Otherwise, **NULL** is returned. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT ACOS(1), ACOS(0), ACOS(-1); ``` | ACOS(1) | ACOS(0) | ACOS(-1) | |---|---|---| | 0 | 1.570796326794896 | 3.141592653589793 | ## ASIN ```sql ASIN ( x ) ``` The **ASIN** function returns an arc sine value of the argument. That is, it returns a value whose sine is *x* in radian. The return value is a **DOUBLE** type. x must be a value between -1 and 1, inclusive. Otherwise, **NULL** is returned. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT ASIN(1), ASIN(0), ASIN(-1); ``` | ASIN(1) | ASIN(0) | ASIN(-1) | |---|---|---| | 1.570796326794896 | 0 | -1.570796326794896 | ## ATAN ```sql ATAN ( [y,] x ) ``` The **ATAN** function returns a value whose tangent is *x* in radian. The argument *y* can be omitted. If *y* is specified, the function calculates the arc tangent value of *y/x*. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x,y`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT ATAN(1), ATAN(-1), ATAN(1,-1); ``` | ATAN(1) | ATAN(-1) | ATAN(1,-1) | |---|---|---| | 0.7853981633974483 | -0.7853981633974483 | 2.356194490192345 | ## ATAN2 ```sql ATAN2 ( y, x ) ``` The **ATAN2** function returns the arc tangent value of *y/x* in radian. This function is working like the [ATAN](https://www.coradb.ai/manual/sql/function/numeric_fn.html#atan). Arguments *x* and *y* must be specified. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x,y`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT ATAN2(1,1), ATAN2(-1,-1), ATAN2(Pi(),0); ``` | ATAN2(1,1) | ATAN2(-1,-1) | ATAN2(Pi(),0) | |---|---|---| | 0.7853981633974483 | -2.356194490192345 | 1.570796326794896 | ## CEIL ```sql CEIL( number_operand ) ``` The **CEIL** function returns the smallest integer that is not less than its argument. The return value is determined based on the valid number of digits that are specified as the *number_operand* argument. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_operand`: An expression that returns a numeric value **Return type:** INT ```sql SELECT CEIL(34567.34567), CEIL(-34567.34567), CEIL(34567.1), CEIL(-34567.1); ``` | CEIL(34567.34567) | CEIL(-34567.34567) | CEIL(34567.1) | CEIL(-34567.1) | |---|---|---|---| | 34568.00000 | -34567.00000 | 34568.0 | -34567.0 | The result keeps the scale of the argument. ## CONV ```sql CONV (number,from_base,to_base) ``` The **CONV** function converts numbers between different number bases. This function returns a string representation of a converted number. The minimum value is 2 and the maximum value is 36. If *to_base* (representing the base to be returned) is negative, *number* is regarded as a signed number. Otherwise, it regarded as a unsigned number. When you input the string which cannot be transformed into the number to *from_base* or *to_base*, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number`: An input number - `from_base`: The base of an input number - `to_base`: The base of an returned value **Return type:** STRING ```sql SELECT CONV('f',16,2); ``` | CONV('f',16,2) | |---| | 1111 | ```sql SELECT CONV('6H',20,8); ``` | CONV('6H',20,8) | |---| | 211 | ```sql SELECT CONV(-30,10,-20); ``` | CONV(-30,10,-20) | |---| | -1A | ## COS ```sql COS ( x ) ``` The **COS** function returns a cosine value of the argument. The argument *x* must be a radian value. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT COS(pi()/6), COS(pi()/3), COS(pi()); ``` | COS(pi()/6) | COS(pi()/3) | COS(pi()) | |---|---|---| | 0.8660254037844387 | 0.5000000000000001 | -1 | ## COT ```sql COT ( x ) ``` The **COT** function returns the cotangent value of the argument *x*. That is, it returns a value whose tangent is *x* in radian. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT COT(1), COT(-1), COT(0); ``` | COT(1) | COT(-1) | COT(0) | |---|---|---| | 0.6420926159343306 | -0.6420926159343306 | NULL | ## CRC32 ```sql CRC32 ( string ) ``` The **CRC32** function returns a cyclic redundancy check value as 32-bit integer. When NULL is given as input, it returns NULL. **Parameters** - `string`: An expression that returns a string value **Return type:** INTEGER ```sql SELECT CRC32('coradb'); ``` | CRC32('coradb') | |---| | 248404764 | ## DEGREES ```sql DEGREES ( x ) ``` The **DEGREES** function returns the argument *x* specified in radian converted to a degree value. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT DEGREES(pi()/6), DEGREES(pi()/3), DEGREES (pi()); ``` | DEGREES(pi()/6) | DEGREES(pi()/3) | DEGREES (pi()) | |---|---|---| | 29.99999999999999 | 59.99999999999999 | 180 | ## DRANDOM, DRAND ```sql DRANDOM ( [seed] ) ``` ```sql DRAND ( [seed] ) ``` The function **DRANDOM** or **DRAND** returns a random double-precision floating point value in the range of between 0.0 and 1.0. A *seed* argument that is **INTEGER** type can be specified. It rounds up real numbers and an error is returned when it exceeds the range of **INTEGER**. When *seed* value is not given, the **DRAND** function performs the operation only once to produce only one random number regardless of the number of rows where the operation is output, but the **DRANDOM** function performs the operation every time the statement is repeated to produce a different random value for each row. Therefore, to output rows in a random order, you must use the **DRANDOM** function in the **ORDER BY** clause. To obtain a random integer value, use the [RANDOM](https://www.coradb.ai/manual/sql/function/numeric_fn.html#fn-random). **Parameters** - `seed`: seed value **Return type:** DOUBLE ```sql SELECT DRAND(), DRAND(1), DRAND(1.4); ``` ```text 0.2849646518006921 0.041630344771878214 0.041630344771878214 ``` The first value changes on every run. With a seed, the result is repeatable: `DRAND(1)` always returns the same number, and `1.4` is rounded to the seed `1`. `DRAND()` is evaluated once per statement, while `DRANDOM()` is evaluated for every row. Use `DRANDOM()` to sort rows in random order, for example to pick three random products: ```sql SELECT id, name FROM product ORDER BY DRANDOM() LIMIT 3; ``` ## EXP ```sql EXP( x ) ``` The **EXP** function returns e x (the base of natural logarithm) raised to a power. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An operator which returns a numeric value **Return type:** DOUBLE ```sql SELECT EXP(1), EXP(0); ``` | EXP(1) | EXP(0) | |---|---| | 2.718281828459045 | 1 | ```sql SELECT EXP(-1), EXP(2.00); ``` | EXP(-1) | EXP(2.00) | |---|---| | 0.3678794411714423 | 7.38905609893065 | ## FLOOR ```sql FLOOR( number_operand ) ``` The **FLOOR** function returns the largest integer that is not greater than its argument. The data type of the return value is the same as that of the argument. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_operand`: An operator which returns a numeric value **Return type:** same as that of the argument ```sql --it returns the largest integer less than or equal to the arguments SELECT FLOOR(34567.34567), FLOOR(-34567.34567); ``` | FLOOR(34567.34567) | FLOOR(-34567.34567) | |---|---| | 34567.00000 | -34568.00000 | ```sql SELECT FLOOR(34567), FLOOR(-34567); ``` | FLOOR(34567) | FLOOR(-34567) | |---|---| | 34567 | -34567 | ## HEX ```sql HEX(n) ``` The **HEX** function returns a hexadecimal string about the string which is specified as an argument; it returns a hexadecimal string of the number if a number is specified as an argument. If a number is specified as an argument, it returns a value like CONV(num, 10, 16). **Parameters** - `n`: A string or a number **Return type:** STRING ```sql SELECT HEX('ab'), HEX(128), CONV(HEX(128), 16, 10); ``` | HEX('ab') | HEX(128) | CONV(HEX(128), 16, 10) | |---|---|---| | 6162 | 80 | 128 | ## LN ```sql LN ( x ) ``` The **LN** function returns the natural log value (base = e) of an antilogarithm *x*. The return value is a **DOUBLE** type. If the antilogarithm is 0 or a negative number, an error is returned. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a positive number **Return type:** DOUBLE ```sql SELECT ln(1), ln(2.72); ``` | ln(1) | ln(2.72) | |---|---| | 0 | 1.000631880307906 | ## LOG2 ```sql LOG2 ( x ) ``` The **LOG2** function returns a log value whose antilogarithm is *x* and base is 2. The return value is a **DOUBLE** type. If the antilogarithm is 0 or a negative number, an error is returned. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a positive number **Return type:** DOUBLE ```sql SELECT log2(1), log2(8); ``` | log2(1) | log2(8) | |---|---| | 0 | 3 | ## LOG10 ```sql LOG10 ( x ) ``` The **LOG10** function returns the common log value of an antilogarithm *x*. The return value is a **DOUBLE** type. If the antilogarithm is 0 or a negative number, an error is returned. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a positive number **Return type:** DOUBLE ```sql SELECT log10(1), log10(1000); ``` | log10(1) | log10(1000) | |---|---| | 0 | 3 | ## MOD ```sql MOD (m, n) ``` The **MOD** function returns the remainder of the first parameter *m* divided by the second parameter *n*. If *n* is 0, *m* is returned without the division operation being performed. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. Note that if the dividend, the parameter m of the **MOD** function, is a negative number, the function operates differently from a typical operation (classical modulus) method. **Result of MOD** | m | n | MOD(m, n) | Classical modulus m-n\*FLOOR(m/n) | |-----|-----|-----------|-----------------------------------| | 11 | 4 | 3 | 3 | | 11 | -4 | 3 | -1 | | -11 | 4 | -3 | 1 | | -11 | -4 | -3 | -3 | | 11 | 0 | 11 | Divided by 0 error | **Parameters** - `m`: Represents a dividend. It is an expression that returns a numeric value. - `n`: Represents a divisor. It is an expression that returns a numeric value. **Return type:** INT ```sql --it returns the reminder of m divided by n SELECT MOD(11, 4), MOD(11, -4), MOD(-11, 4), MOD(-11, -4), MOD(11,0); ``` | MOD(11, 4) | MOD(11, -4) | MOD(-11, 4) | MOD(-11, -4) | MOD(11,0) | |---|---|---|---|---| | 3 | 3 | -3 | -3 | 11 | ```sql SELECT MOD(11.0, 4), MOD(11.000, 4), MOD(11, 4.0), MOD(11, 4.000); ``` | MOD(11.0, 4) | MOD(11.000, 4) | MOD(11, 4.0) | MOD(11, 4.000) | |---|---|---|---| | 3.0 | 3.000 | 3.0 | 3.000 | ## PI ```sql PI () ``` The **PI** function returns the ? value of type **DOUBLE**. **Return type:** DOUBLE ```sql SELECT PI(), PI()/2; ``` | PI() | PI()/2 | |---|---| | 3.141592653589793 | 1.570796326794896 | ## POW, POWER ```sql POW( x, y ) ``` ```sql POWER( x, y ) ``` The **POW** function returns *x* to the power of *y*. The functions **POW** and **POWER** are used interchangeably. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: It represents the base. It is an expression that returns a numeric value. An expression that returns a numeric value. - `y`: It represents the exponent. An expression that returns a numeric value. If the base is a negative number, an integer must specified as the exponent. **Return type:** DOUBLE ```sql SELECT POWER(2, 5), POWER(-2, 5), POWER(0, 0), POWER(1,0); ``` | POWER(2, 5) | POWER(-2, 5) | POWER(0, 0) | POWER(1,0) | |---|---|---|---| | 32 | -32 | 1 | 1 | ```sql --it returns an error when the negative base is powered by a non-int exponent SELECT POWER(-2, -5.1), POWER(-2, -5.1); ``` ```text ERROR: Argument of power() is out of range. ``` ## RADIANS ```sql RADIANS ( x ) ``` The **RADIANS** function returns the argument *x* specified in degrees converted to a radian value. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT RADIANS(90), RADIANS(180), RADIANS(360); ``` | RADIANS(90) | RADIANS(180) | RADIANS(360) | |---|---|---| | 1.570796326794896 | 3.141592653589793 | 6.283185307179586 | ## RANDOM, RAND ```sql RANDOM ( [seed] ) ``` ```sql RAND ( [seed] ) ``` The function **RANDOM** or **RAND** returns any integer value, which is greater than or equal to 0 and less than 2 31, and a *seed* argument that is **INTEGER** type can be specified. It rounds up real numbers and an error is returned when it exceeds the range of **INTEGER**. When *seed* value is not given, the **RAND** function performs the operation only once to produce only one random number regardless of the number of rows where the operation is output, but the **RANDOM** function performs the operation every time the statement is repeated to produce a different random value for each row. Therefore, to output rows in a random order, you must use the **RANDOM** function. To obtain a random real number, use the [DRANDOM](https://www.coradb.ai/manual/sql/function/numeric_fn.html#fn-drandom). **Parameters** - `seed`: **Return type:** INT ```sql SELECT RAND(), RAND(1), RAND(1.4); ``` ```text 1526981144 89400484 89400484 ``` The first value changes on every run; a seed makes the result repeatable. `RAND()` is evaluated once per statement, while `RANDOM()` is evaluated for every row. Use `RANDOM()` to sort rows in random order: ```sql SELECT id, name FROM product ORDER BY RANDOM() LIMIT 3; ``` ## ROUND ```sql ROUND ( number_operand, integer ) ``` The **ROUND** function returns the specified argument, *number_operand*, rounded to the number of places after the decimal point specified by the *integer*. If the *integer* argument is a negative number, it rounds to a place before the decimal point, that is, at the integer part. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_operand`: An expression that returns a numeric value - `integer`: Specifies the place to round to. If a positive integer *n* is specified, the number is represented to the nth place after the decimal point; if a negative integer *n* is specified, the number is rounded to the *n* th place before the decimal point. **Return type:** same type as the *number_operand* ```sql --it rounds a number to one decimal point when the second argument is omitted SELECT ROUND(34567.34567), ROUND(-34567.34567); ``` | ROUND(34567.34567) | ROUND(-34567.34567) | |---|---| | 34567.00000 | -34567.00000 | ```sql --it rounds a number to three decimal point SELECT ROUND(34567.34567, 3), ROUND(-34567.34567, 3) FROM db_root; ``` | ROUND(34567.34567, 3) | ROUND(-34567.34567, 3) | |---|---| | 34567.34600 | -34567.34600 | ```sql --it rounds a number three digit to the left of the decimal point SELECT ROUND(34567.34567, -3), ROUND(-34567.34567, -3); ``` | ROUND(34567.34567, -3) | ROUND(-34567.34567, -3) | |---|---| | 35000.00000 | -35000.00000 | ## SIGN ```sql SIGN (number_operand) ``` The **SIGN** function returns the sign of a given number. It returns 1 for a positive value, -1 for a negative value, and 0 for zero. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_operand`: An operator which returns a numeric value **Return type:** INT ```sql --it returns the sign of the argument SELECT SIGN(12.3), SIGN(-12.3), SIGN(0); ``` | SIGN(12.3) | SIGN(-12.3) | SIGN(0) | |---|---|---| | 1 | -1 | 0 | ## SIN ```sql SIN ( x ) ``` The **SIN** function returns a sine value of the parameter. The argument *x* must be a radian value. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT SIN(pi()/6), SIN(pi()/3), SIN(pi()); ``` | SIN(pi()/6) | SIN(pi()/3) | SIN(pi()) | |---|---|---| | 0.4999999999999999 | 0.8660254037844386 | 1.224646799147353e-16 | ## SQRT ```sql SQRT ( x ) ``` The **SQRT** function returns the square root of *x* as a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value. An error is returned if this value is a negative number. **Return type:** DOUBLE ```sql SELECT SQRT(4), SQRT(16.0); ``` | SQRT(4) | SQRT(16.0) | |---|---| | 2 | 4 | ## TAN ```sql TAN ( x ) ``` The **TAN** function returns a tangent value of the argument. The argument *x* must be a radian value. The return value is a **DOUBLE** type. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value **Return type:** DOUBLE ```sql SELECT TAN(pi()/6), TAN(pi()/3), TAN(pi()/4); ``` | TAN(pi()/6) | TAN(pi()/3) | TAN(pi()/4) | |---|---|---| | 0.5773502691896257 | 1.732050807568876 | 0.9999999999999999 | ## TRUNC, TRUNCATE ```sql TRUNC ( x[, dec] ) ``` ```sql TRUNCATE ( x, dec ) ``` The function **TRUNC** or **TRUNCATE** truncates the numbers of the specified argument *x* to the right of the *dec* position. If the *dec* argument is a negative number, it displays 0s to the *dec-* th position left to the decimal point. Note that the *dec* argument of the **TRUNC** function can be omitted, but that of the **TRUNCATE** function cannot be omitted. If the *dec* argument is a negative number, it displays 0s to the *dec* -th position left to the decimal point. The number of digits of the return value to be represented follows the argument *x*. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `x`: An expression that returns a numeric value - `dec`: The place to be truncated is specified. If a positive integer *n* is specified, the number is represented to the *n-*th place after the decimal point; if a negative integer *n* is specified, the number is truncated to the *n-*th place before the decimal point. It truncates to the first place after the decimal point if the *dec* argument is 0 or omitted. Note that the *dec* argument cannot be omitted in the **TRUNCATE** function. **Return type:** same type as the *x* ```sql --it returns a number truncated to 0 places SELECT TRUNC(34567.34567), TRUNCATE(34567.34567, 0); ``` | TRUNC(34567.34567) | TRUNCATE(34567.34567, 0) | |---|---| | 34567.00000 | 34567.00000 | ```sql --it returns a number truncated to three decimal places SELECT TRUNC(34567.34567, 3), TRUNC(-34567.34567, 3); ``` | TRUNC(34567.34567, 3) | TRUNC(-34567.34567, 3) | |---|---| | 34567.34500 | -34567.34500 | ```sql --it returns a number truncated to three digits left of the decimal point SELECT TRUNC(34567.34567, -3), TRUNC(-34567.34567, -3); ``` | TRUNC(34567.34567, -3) | TRUNC(-34567.34567, -3) | |---|---| | 34000.00000 | -34000.00000 | ## WIDTH_BUCKET ```sql WIDTH_BUCKET(expression, from, to, num_buckets) ``` **WIDTH_BUCKET** distributes the rows in an ordered partition into a specified number of buckets. The buckets are numbered, starting from one. That is, **WIDTH_BUCKET** function creates an equi-width histogram. The return value is an integer. When you input the string which cannot be transformed into the number, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. This function equally divides the range by the given number of buckets and assigns the bucket number to each bucket. That is, every interval (bucket) has the identical size. Note that [NTILE](https://www.coradb.ai/manual/sql/function/analysis_fn.html#ntile) function equally divides the number of rows by the given number of buckets and assigns the bucket number to each bucket. That is, every bucket has the same number of rows. *expression* is an input value to assign the bucket number. *from* and *to* should be numeric values, date/time values, or the string which can be converted to date/time value. *from* is included in the acceptable range, but *to* is beyond the range. For example, `WIDTH_BUCKET(score, 80, 50, 3)` (a descending range) returns > - 0 when the score is larger than 80, > - 1 for \[80, 70), > - 2 for \[70, 60), > - 3 for \[60, 50), > - and 4 when the score is 50 or smaller. **Parameters** - `expression`: an input value to assign the bucket number. It specifies a certain expression which returns the number. - `from`: a start value of the range, which is given to *expression*. It is included in the entire range. - `to`: an end value of the range, which is given to *expression*. It is not included in the entire range. - `num_buckets`: the number of buckets. The \#0 bucket and the \#(*num_buckets* + 1) bucket are created to include the contents beyond the range. **Return type:** INT The following example puts products into four price bands of 25.00 each between 0 and 100. Prices of 100 or more go to bucket 5 (*num_buckets* + 1): ```sql SELECT name, unit_price, WIDTH_BUCKET(unit_price, 0, 100, 4) AS price_band FROM product WHERE id IN (5, 29, 38, 123, 335, 1110, 1795) ORDER BY unit_price DESC; ``` | name | unit_price | price_band | |---|---:|---:| | Côte de Blaye | 263.50 | 5 | | Thüringer Rostbratwurst | 123.79 | 5 | | Ingrid Running Jacket | 84.00 | 4 | | Erika Running Short | 45.00 | 2 | | Balboa Persistence Tee | 29.00 | 2 | | Chef Antons Gumbo Mix | 21.35 | 1 | | Arcadio Gym Short | 20.00 | 1 | The range can also be made of dates. The year 2025 is split into four equal parts (of about 91 days, so the boundaries are not calendar quarters); orders from December 2024 fall before the range, in bucket 0: ```sql SELECT WIDTH_BUCKET(order_date, DATE'2025-01-01', DATE'2026-01-01', 4) AS bucket, MIN(order_date) AS first_day, MAX(order_date) AS last_day, COUNT(*) AS orders FROM orders WHERE order_date >= DATE'2024-12-01' GROUP BY 1 ORDER BY 1; ``` | bucket | first_day | last_day | orders | |---:|---|---|---:| | 0 | 2024-12-01 | 2024-12-31 | 94 | | 1 | 2025-01-01 | 2025-04-02 | 150 | | 2 | 2025-04-04 | 2025-07-02 | 173 | | 3 | 2025-07-03 | 2025-10-01 | 183 | | 4 | 2025-10-02 | 2025-12-31 | 280 | --- # Other functions Source: https://www.coradb.ai/manual/sql/function/other_fn.html ## BENCHMARK ```text BENCHMARK(count, expression) ``` Evaluates *expression* *count* times and returns the elapsed time in seconds. Use it to compare the cost of expressions and functions. *count* must be a positive integer; if it is **NULL**, the result is **NULL**. A subquery in *expression* may be evaluated only once and reused. **Return type:** DOUBLE. ```sql SELECT BENCHMARK(100000, SHA1('coradb')); -- for example 0.022481736 ``` ## SLEEP ```text SLEEP(seconds) ``` Pauses the statement for the given number of seconds, then returns 0. *seconds* is a `DOUBLE`, so fractions such as `0.5` are allowed. Use it to simulate slow work when testing timeouts or locking. **Return type:** INT. ```sql SELECT SLEEP(3); -- returns 0 after three seconds ``` ## SYS_GUID ```text SYS_GUID() ``` Returns a random 32-character hexadecimal string, different on every call. Use it as a globally unique identifier. **Return type:** VARCHAR. ```sql SELECT SYS_GUID(); ``` ```text 938210043A7B4455927A8697FB2571FF ``` --- # List predicates: ALL, ANY, NONE and SINGLE Source: https://www.coradb.ai/manual/sql/function/predicate_fn.html The list predicates test every element of a collection (a `SET`, `MULTISET` or `SEQUENCE` value) against a condition and return `1` (true) or `0` (false). They are useful on collection columns and on collections built from a subquery with `SEQUENCE(SELECT ...)`. ```sql ALL ( variable IN collection WHERE condition ) ANY ( variable IN collection WHERE condition ) NONE ( variable IN collection WHERE condition ) SINGLE ( variable IN collection WHERE condition ) ``` - *variable*: a name that stands for the current element inside *condition*. It is visible only inside the predicate. - *collection*: a collection literal such as `{1, 2, 3}`, a collection column, or `SEQUENCE(subquery)`. - *condition*: a Boolean expression, normally using *variable*. It can also refer to columns of the outer query. | Predicate | Returns 1 when | |---|---| | `ALL` | Every element satisfies the condition | | `ANY` | At least one element satisfies the condition | | `NONE` | No element satisfies the condition | | `SINGLE` | Exactly one element satisfies the condition | The result type is `INTEGER`, so a predicate can be used in the select list, in `WHERE` and `HAVING`, and anywhere else a Boolean expression is allowed. > **Empty collections and NULL elements:** > - On an empty collection, `ALL` and `NONE` return `1`; `ANY` and `SINGLE` return `0`. > - An element for which the condition is not true (including when it is `NULL` because the element is `NULL`) counts as **not satisfying** it. The predicates never return `NULL`: `ALL(x IN {3, NULL} WHERE x > 2)` is `0` and `NONE(x IN {1, NULL} WHERE x > 2)` is `1`. > - A collection literal made only of `NULL` values, or mixing `NULL` with constants, has no element type and is rejected (`Cannot coerce ... to type unknown data type`). Store such values in a typed collection column instead. ## ALL `ALL` returns `1` when every element satisfies the condition. ```sql SELECT ALL(x IN {1, 2, 3, 4} WHERE x > 2), ALL(x IN {3, 4, 5, 6} WHERE x > 2); ``` | ALL(x IN {1, 2, 3, 4} WHERE x > 2) | ALL(x IN {3, 4, 5, 6} WHERE x > 2) | |---|---| | 0 | 1 | Orders in which no line has a discount: ```sql SELECT COUNT(*) FROM orders o WHERE ALL(x IN SEQUENCE(SELECT discount_pct FROM order_items i WHERE i.order_id = o.id) WHERE x = 0); ``` | COUNT(*) | |---| | 927 | ## ANY `ANY` returns `1` when at least one element satisfies the condition. ```sql SELECT ANY(x IN {-1, 0, 1, 2} WHERE x > 2), ANY(x IN {3, 4, 5, 6} WHERE x > 2); ``` | ANY(x IN {-1, 0, 1, 2} WHERE x > 2) | ANY(x IN {3, 4, 5, 6} WHERE x > 2) | |---|---| | 0 | 1 | > **Warning:** > Inside a list predicate, `ANY` takes the form `ANY(variable IN collection WHERE condition)`. The comparison form `expression = ANY (subquery)` is a different construct, described in [Conditional expressions](https://www.coradb.ai/manual/sql/function/condition_op.html#any-some-all). ## NONE `NONE` returns `1` when no element satisfies the condition. It is the negation of `ANY`. ```sql SELECT NONE(x IN {1, 2, 3, 4} WHERE x > 2), NONE(x IN {-1, 0, 1, 2} WHERE x > 2); ``` | NONE(x IN {1, 2, 3, 4} WHERE x > 2) | NONE(x IN {-1, 0, 1, 2} WHERE x > 2) | |---|---| | 0 | 1 | ## SINGLE `SINGLE` returns `1` when exactly one element satisfies the condition, and `0` when none or more than one do. ```sql SELECT SINGLE(x IN {1, 2, 3, 4} WHERE x > 2), SINGLE(x IN {0, 1, 2, 3, -1} WHERE x > 2); ``` | SINGLE(x IN {1, 2, 3, 4} WHERE x > 2) | SINGLE(x IN {0, 1, 2, 3, -1} WHERE x > 2) | |---|---| | 0 | 1 | Orders that have exactly one line with a quantity of 10 or more: ```sql SELECT COUNT(*) FROM orders o WHERE SINGLE(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) WHERE x >= 10); ``` | COUNT(*) | |---| | 147 | ## All four on the same collections The quantities of the lines of the first eight orders, tested with each predicate: ```sql SELECT o.id, SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) AS quantities, ALL(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) WHERE x >= 2) AS all_ge_2, ANY(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) WHERE x >= 10) AS any_ge_10, NONE(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) WHERE x >= 10) AS none_ge_10, SINGLE(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.order_id = o.id) WHERE x = 1) AS single_eq_1 FROM orders o WHERE o.id < 8 ORDER BY o.id; ``` | id | quantities | all_ge_2 | any_ge_10 | none_ge_10 | single_eq_1 | |---|---|---|---|---|---| | 0 | {1, 1, 1, 1} | 0 | 0 | 1 | 0 | | 1 | {2} | 1 | 0 | 1 | 0 | | 2 | {2, 4} | 1 | 0 | 1 | 0 | | 3 | {1, 1, 12} | 0 | 1 | 0 | 0 | | 4 | {2, 7, 2} | 1 | 0 | 1 | 0 | | 5 | {2} | 1 | 0 | 1 | 0 | | 6 | {1, 4} | 0 | 0 | 1 | 1 | | 7 | {1, 1, 1, 9, 9, 1, 2} | 0 | 0 | 1 | 0 | ## Empty collections A collection built from a correlated subquery is empty when the subquery finds no rows. 288 products have never been ordered, so for them the collection of order quantities is empty, and `ALL` is true whatever the condition: ```sql SELECT COUNT(*) FROM product p WHERE ALL(x IN SEQUENCE(SELECT quantity FROM order_items i WHERE i.product_id = p.id) WHERE x >= 100); ``` | COUNT(*) | |---| | 288 | No order line has a quantity of 100 or more, so the 288 products counted are exactly the products that were never ordered. To exclude empty collections, add a condition such as `EXISTS (SELECT 1 FROM order_items i WHERE i.product_id = p.id)`. ## Collection columns and NULL elements With a table that stores a typed `SEQUENCE` column, the predicates read the column directly. The rows below show how `NULL` elements and an empty collection are handled: ```sql CREATE TABLE pred_demo (id INT PRIMARY KEY, s SEQUENCE(INT)); INSERT INTO pred_demo VALUES (1, {3, 4}), (2, {3, NULL}), (3, {1, NULL}), (4, {NULL, NULL}), (5, {}); SELECT id, s, ALL(x IN s WHERE x > 2) AS all_gt_2, ANY(x IN s WHERE x > 2) AS any_gt_2, NONE(x IN s WHERE x > 2) AS none_gt_2, SINGLE(x IN s WHERE x > 2) AS single_gt_2 FROM pred_demo ORDER BY id; ``` | id | s | all_gt_2 | any_gt_2 | none_gt_2 | single_gt_2 | |---|---|---|---|---|---| | 1 | {3, 4} | 1 | 1 | 0 | 0 | | 2 | {3, NULL} | 0 | 1 | 0 | 1 | | 3 | {1, NULL} | 0 | 0 | 1 | 0 | | 4 | {NULL, NULL} | 0 | 0 | 1 | 0 | | 5 | {} | 1 | 0 | 1 | 0 | ## See also - [Conditional expressions (ANY/ALL with subqueries, IN, EXISTS, ...)](https://www.coradb.ai/manual/sql/function/condition_op.html) - [Collection data types](https://www.coradb.ai/manual/sql/datatype_collection.html#collection-types) - [Containment operators (SUBSET, SUPERSET, ...)](https://www.coradb.ai/manual/sql/function/containment_op.html) - [List functions](https://www.coradb.ai/manual/sql/function/list_fn.html) --- # Regular expression functions: REGEXP, REGEXP_LIKE, REGEXP_REPLACE, REGEXP_SUBSTR Source: https://www.coradb.ai/manual/sql/function/regex_fn.html CoraDB matches strings against regular expressions with the **REGEXP** (or **RLIKE**) operator and five functions: | Function | Returns | |---|---| | [REGEXP, RLIKE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp-rlike) | 1 if the pattern matches anywhere in the string, otherwise 0 | | [REGEXP_LIKE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_like) | Same as REGEXP, as a function with a match type | | [REGEXP_COUNT](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_count) | The number of matches | | [REGEXP_INSTR](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_instr) | The position of a match | | [REGEXP_SUBSTR](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_substr) | The text of a match | | [REGEXP_REPLACE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_replace) | The string with matches replaced | Matching is **case-insensitive** by default. Use `REGEXP BINARY`, or the match type `'c'` of the functions, for case-sensitive matching. ## Pattern syntax Patterns follow the ECMAScript (JavaScript) regular expression grammar, implemented with the C++ `` library. Matching is done on characters, not bytes, so patterns work on multibyte UTF-8 text. Backslashes in patterns reach the regular expression engine unchanged as long as the [no_backslash_escapes](https://www.coradb.ai/manual/admin/config_sql.html#no_backslash_escapes) parameter is `yes` (the default): write `'\d+'`, not `'\\d+'`. > **Note:** > POSIX collating elements (`[.ch.]`), equivalence classes (`[=e=]`) and the word-boundary brackets `[[:<:]]` and `[[:>:]]` are not supported; use `\b` for word boundaries. The dot (`.`) does not match line terminators. ### Special characters | Characters | Matches | |---|---| | `.` | Any character except line terminators (LF, CR, LS, PS) | | `\t`, `\n`, `\v`, `\f`, `\r` | Tab, Line feed, Vertical tab, Form feed, Carriage return | | `\cletter` | The control character whose code is the code of *letter* modulo 32 | | `\xhh`, `\uhhhh` | The character with the hexadecimal code *hh* or *hhhh* | | `\0` | The null character | | `\num` | Back-reference: the text matched by group *num* | | `\d`, `\D` | A decimal digit (`[[:digit:]]`), any other character | | `\s`, `\S` | A whitespace character (`[[:space:]]`), any other character | | `\w`, `\W` | A letter, digit or underscore (`[_[:alnum:]]`), any other character | | `\character` | The *character* itself. Escape `^ $ \ . * + ? ( ) [ ] { } \|` to match them literally | | `[class]`, `[^class]` | A character in (or not in) the [character class](https://www.coradb.ai/manual/sql/function/regex_fn.html#character-classes) | ```sql SELECT ('coradb dbms' REGEXP '^c.*$'), REGEXP_COUNT('a1 b22 c333', '\d+'), REGEXP_REPLACE('hello coradb world', '\b(\w)\w*', '$1'); ``` | ('coradb dbms' REGEXP '^c.*$') | REGEXP_COUNT('a1 b22 c333', '\d+') | REGEXP_REPLACE('hello coradb world', '\b(\w)\w*', '$1') | |---|---|---| | 1 | 3 | h c w | ### Quantifiers | Quantifier | The preceding item is matched | |---|---| | `*` | 0 or more times | | `+` | 1 or more times | | `?` | 0 or 1 time | | `{n}` | Exactly *n* times | | `{n,}` | *n* or more times | | `{min,max}` | Between *min* and *max* times | ```sql SELECT ('Aaaapricot' REGEXP '^A+pricot'), ('Apricot' REGEXP '^Aa?pricot'), ('Aaapricot' REGEXP '^Aa?pricot'), ('coracora' REGEXP '^(cora)*$'), ('coradb' REGEXP '^(cora)*$'); ``` | ('Aaaapricot' REGEXP '^A+pricot') | ('Apricot' REGEXP '^Aa?pricot') | ('Aaapricot' REGEXP '^Aa?pricot') | ('coracora' REGEXP '^(cora)*$') | ('coradb' REGEXP '^(cora)*$') | |---|---|---|---|---| | 1 | 1 | 0 | 1 | 0 | Quantifiers are *greedy*: they take as many characters as possible. Add `?` after a quantifier to make it *lazy* (as few as possible): ```sql SELECT REGEXP_SUBSTR('aardvark', '(a+)'), REGEXP_SUBSTR('aardvark', '(a+?)'); ``` | REGEXP_SUBSTR('aardvark', '(a+)') | REGEXP_SUBSTR('aardvark', '(a+?)') | |---|---| | aa | a | ### Groups and back-references | Syntax | Meaning | |---|---| | `(subpattern)` | Group that captures the matched text | | `(?:subpattern)` | Group that does not capture | Captured groups are numbered by the position of their opening parenthesis. In the pattern, `\1`, `\2`, ... refer back to them; in the replacement string of REGEXP_REPLACE, use `$1`, `$2`, ... ```sql SELECT REGEXP_REPLACE('hello coradb', '([[:alnum:]]+)', '$1!'); ``` | REGEXP_REPLACE('hello coradb', '([[:alnum:]]+)', '$1!') | |---| | hello! coradb! | The group `([a-c]{3})` captures `abc`, and `\1` requires the same three letters again: ```sql SELECT REGEXP_SUBSTR('abckabcjabc', '([a-c]{3})k\1j\1'); ``` | REGEXP_SUBSTR('abckabcjabc', '([a-c]{3})k\1j\1') | |---| | abckabcjabc | ### Assertions Assertions test a position without consuming characters. | Syntax | True at a position | |---|---| | `^` | At the start of the string (or after a line terminator) | | `$` | At the end of the string (or before a line terminator) | | `\b` | Between a word character and a non-word character | | `\B` | Not at a word boundary | | `(?=subpattern)` | Followed by *subpattern* (positive lookahead) | | `(?!subpattern)` | Not followed by *subpattern* (negative lookahead) | ```sql SELECT REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?= sql)', 'CoraDB'), REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?! sql)', 'CoraDB'); ``` | REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?= sql)', 'CoraDB') | REGEXP_REPLACE('coradb dbms coradb sql coradb rdbms', 'coradb(?! sql)', 'CoraDB') | |---|---| | coradb dbms CoraDB sql coradb rdbms | CoraDB dbms coradb sql CoraDB rdbms | ### Alternatives `|` separates alternatives. The pattern matches if any alternative matches; inside a group, `|` separates alternatives of the group only. ```sql SELECT ('a' REGEXP 'a|b'), ('d' REGEXP 'a|b'), ('c' REGEXP 'a|b|c'); ``` | ('a' REGEXP 'a\|b') | ('d' REGEXP 'a\|b') | ('c' REGEXP 'a\|b\|c') | |---|---|---| | 1 | 0 | 1 | ### Character classes A class in square brackets matches one character: a list of characters (`[abc]`), a range (`[a-f]`, `[0-9]`), a named class (`[[:digit:]]`), or any mix of them. `[^...]` matches any character *not* in the class. | Named class | Characters | |---|---| | `[:alnum:]` | Letters and digits | | `[:alpha:]` | Letters | | `[:blank:]` | Space and tab | | `[:cntrl:]` | Control characters | | `[:digit:]`, `[:d:]` | Decimal digits | | `[:graph:]` | Characters with a visible representation | | `[:lower:]` | Lowercase letters | | `[:print:]` | Printable characters | | `[:punct:]` | Punctuation | | `[:space:]`, `[:s:]` | Whitespace | | `[:upper:]` | Uppercase letters | | `[:xdigit:]` | Hexadecimal digits | | `[:w:]` | Word characters (letters, digits, underscore) | A named class is only valid **inside** a bracket expression: `[[:alpha:]]` matches a letter, but `[:alpha:]` is a plain list of the characters `:`, `a`, `l`, `p` and `h`. ```sql SELECT ('d' REGEXP '[abc]'), ('adf' REGEXP '[a-f]'), ('strike' REGEXP '^[^a-dXYZ]+$'), REGEXP_SUBSTR('aas200gjb', '[0-9]+'), REGEXP_REPLACE('Côte de Blaye', '[[:alpha:]]+', '#'); ``` | ('d' REGEXP '[abc]') | ('adf' REGEXP '[a-f]') | ('strike' REGEXP '^[^a-dXYZ]+$') | REGEXP_SUBSTR('aas200gjb', '[0-9]+') | REGEXP_REPLACE('Côte de Blaye', '[[:alpha:]]+', '#') | |---|---|---|---|---| | 0 | 1 | 1 | 200 | # # # | `[[:alpha:]]` matches accented letters such as `ô` too, so *Côte* is replaced as one word. ## REGEXP, RLIKE ```sql expression REGEXP [BINARY] pattern expression RLIKE [BINARY] pattern expression NOT REGEXP [BINARY] pattern ``` Returns 1 if *pattern* matches any part of *expression*, 0 if it does not, and **NULL** if the pattern is **NULL**. **REGEXP** and **RLIKE** are synonyms. Matching is case-insensitive; with **BINARY** it is case-sensitive. Unlike [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like), which must match the whole value, REGEXP succeeds when the pattern matches anywhere. Anchor the pattern with `^` and `$` to match the whole value. > **Note:** > In a select list, put the REGEXP expression in parentheses: `SELECT ('abc' REGEXP 'b')`. In a `WHERE` clause, no parentheses are needed. ```sql SELECT ('ABC' REGEXP 'abc'), ('Tourtière' RLIKE 'tourti.re'), ('Tourtière' NOT REGEXP 'tourti.re'); ``` | ('ABC' REGEXP 'abc') | ('Tourtière' RLIKE 'tourti.re') | ('Tourtière' NOT REGEXP 'tourti.re') | |---|---|---| | 1 | 1 | 0 | All product names start with a capital letter. A case-insensitive match finds the names that start with A, B or C; with **BINARY**, the lowercase class `[a-c]` matches none of them: ```sql SELECT COUNT(DISTINCT name) FROM product WHERE name REGEXP '^[a-c]'; ``` | COUNT(DISTINCT name) | |---| | 56 | ```sql SELECT COUNT(DISTINCT name) FROM product WHERE name REGEXP BINARY '^[a-c]'; ``` | COUNT(DISTINCT name) | |---| | 0 | Product names that contain characters outside printable ASCII (the range from space to `~`): ```sql SELECT name FROM product WHERE name REGEXP '[^ -~]' ORDER BY name; ``` | name | |---| | Côte de Blaye | | Guaraná Fantástica | | Original Frankfurter Grüne Soße | | Pâte chinois | | Thüringer Rostbratwurst | | Tourtière | ## REGEXP_LIKE ```sql REGEXP_LIKE (string, pattern [, match_type]) ``` Returns 1 if *pattern* matches any part of *string*, otherwise 0. It is the function form of REGEXP. - *match_type*: `'i'` for case-insensitive matching (the default) or `'c'` for case-sensitive matching. Any other value is an error. If any argument is **NULL**, the result is **NULL**. An empty pattern matches nothing. **Return type:** INT ```sql SELECT REGEXP_LIKE('abbbbc', 'ab+c'), REGEXP_LIKE('abbbbc', 'AB+C'), REGEXP_LIKE('abbbbc', 'AB+C', 'c'), REGEXP_LIKE('abbbbc', ''); ``` | REGEXP_LIKE('abbbbc', 'ab+c') | REGEXP_LIKE('abbbbc', 'AB+C') | REGEXP_LIKE('abbbbc', 'AB+C', 'c') | REGEXP_LIKE('abbbbc', '') | |---|---|---|---| | 1 | 1 | 0 | 0 | The customer phone numbers are stored in several formats. REGEXP_LIKE finds the ones written as `(nnn)nnn-nnnn`: ```sql SELECT id, phone, REGEXP_LIKE(phone, '^[(][0-9]{3}[)][0-9]{3}-[0-9]{4}$') AS us_format FROM customer WHERE id < 6 ORDER BY id; ``` | id | phone | us_format | |---|---|---| | 0 | 001-800-310-4977 | 0 | | 1 | 122-213-1333 | 0 | | 2 | 7443494058 | 0 | | 3 | +1-435-097-0394 | 0 | | 4 | (352)927-2666 | 1 | | 5 | (461)755-7077 | 1 | ## REGEXP_COUNT ```sql REGEXP_COUNT (string, pattern [, position [, match_type]]) ``` Returns the number of times *pattern* matches in *string*. - *position*: the character position where the search starts (default 1). Zero or a negative value is an error. - *match_type*: `'i'` (default) or `'c'`, as for [REGEXP_LIKE](https://www.coradb.ai/manual/sql/function/regex_fn.html#regexp_like). If any argument is **NULL**, the result is **NULL**. An empty pattern returns 0. **Return type:** INT From position 3, the case-insensitive search finds `A`, `b`, `a`, `A` and `A`; the case-sensitive search finds only `b` and `a`: ```sql SELECT REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3), REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3, 'c'); ``` | REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3) | REGEXP_COUNT('ab123Ab111aAA', '[a-d]', 3, 'c') | |---|---| | 5 | 2 | ## REGEXP_INSTR ```sql REGEXP_INSTR (string, pattern [, position [, occurrence [, return_option [, match_type]]]]) ``` Returns the position of a match of *pattern* in *string*, or 0 if there is none. - *position*: where the search starts (default 1). Zero or a negative value is an error. - *occurrence*: which match to return (default 1). - *return_option*: `0` (default) returns the position of the first character of the match; `1` returns the position of the character after the match. - *match_type*: `'i'` (default) or `'c'`. If any argument is **NULL**, the result is **NULL**. Positions are counted in characters. **Return type:** INT ```sql SELECT REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 0), REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 1), REGEXP_INSTR('12345abcdeabcde', '[a-c]+', 1, 2); ``` | REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 0) | REGEXP_INSTR('12354abc5', '[[:alpha:]]+', 1, 1, 1) | REGEXP_INSTR('12345abcdeabcde', '[a-c]+', 1, 2) | |---|---|---| | 6 | 9 | 11 | The position of the first non-ASCII character in product names, and how many there are: ```sql SELECT name, REGEXP_INSTR(name, '[^ -~]') AS first_non_ascii, REGEXP_COUNT(name, '[^ -~]') AS non_ascii FROM product WHERE name REGEXP '[^ -~]' ORDER BY name; ``` | name | first_non_ascii | non_ascii | |---|---|---| | Côte de Blaye | 2 | 1 | | Guaraná Fantástica | 7 | 2 | | Original Frankfurter Grüne Soße | 24 | 2 | | Pâte chinois | 2 | 1 | | Thüringer Rostbratwurst | 3 | 1 | | Tourtière | 7 | 1 | ## REGEXP_REPLACE ```sql REGEXP_REPLACE (string, pattern, replacement [, position [, occurrence [, match_type]]]) ``` Returns *string* with the matches of *pattern* replaced by *replacement*. In *replacement*, `$1`, `$2`, ... insert the text captured by groups. - *position*: where the search starts (default 1). Zero or a negative value is an error. - *occurrence*: `0` (default) replaces every match; *n* replaces only the *n*-th match. - *match_type*: `'i'` (default) or `'c'`. If any argument is **NULL**, the result is **NULL**. An empty pattern leaves the string unchanged. **Return type:** STRING ```sql SELECT REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#'), REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#', 1, 0, 'c'), REGEXP_REPLACE('12345abcdeabcde', '[a-d]', '#', 1, 2); ``` | REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#') | REGEXP_REPLACE('12345abDEKBcde', '[a-d]', '#', 1, 0, 'c') | REGEXP_REPLACE('12345abcdeabcde', '[a-d]', '#', 1, 2) | |---|---|---| | 12345###EK###e | 12345##DEKB##e | 12345a#cdeabcde | Normalizing the customer phone numbers to digits only: ```sql SELECT id, phone, REGEXP_REPLACE(phone, '[^0-9]', '') AS digits FROM customer WHERE id < 6 ORDER BY id; ``` | id | phone | digits | |---|---|---| | 0 | 001-800-310-4977 | 0018003104977 | | 1 | 122-213-1333 | 1222131333 | | 2 | 7443494058 | 7443494058 | | 3 | +1-435-097-0394 | 14350970394 | | 4 | (352)927-2666 | 3529272666 | | 5 | (461)755-7077 | 4617557077 | ## REGEXP_SUBSTR ```sql REGEXP_SUBSTR (string, pattern [, position [, occurrence [, match_type]]]) ``` Returns the text of a match of *pattern* in *string*, or **NULL** if there is none. - *position*: where the search starts (default 1). Zero or a negative value is an error. - *occurrence*: which match to return (default 1). - *match_type*: `'i'` (default) or `'c'`. If any argument is **NULL**, the result is **NULL**. An empty pattern returns **NULL**. **Return type:** STRING ```sql SELECT REGEXP_SUBSTR('aas200gjb', '[0-9]+'); ``` | REGEXP_SUBSTR('aas200gjb', '[0-9]+') | |---| | 200 | ```sql SELECT REGEXP_SUBSTR('12345abcdeabcde', '[k-z]+'); ``` | REGEXP_SUBSTR('12345abcdeabcde', '[k-z]+') | |---| | NULL | The second comma-separated part of each customer address is the city: ```sql SELECT id, address, REGEXP_SUBSTR(address, '[^,]+', 1, 2) AS city FROM customer WHERE id < 4 ORDER BY id; ``` | id | address | city | |---|---|---| | 0 | 725 French Centers,Jonathanburgh, KY 91607 | Jonathanburgh | | 1 | 687 Griffin Estates,Bowmanton, NV 36334 | Bowmanton | | 2 | 454 Lisa Ramp Suite 214,North Charlesborough, VA 84416 | North Charlesborough | | 3 | 7023 Mcintosh Parkways,Scottfort, MS 56742 | Scottfort | The customer addresses end with a two-letter state code and a five-digit ZIP code. A lookahead extracts the state, and the case-sensitive match type keeps lowercase words out: ```sql SELECT id, REGEXP_SUBSTR(address, '[0-9]{5}$') AS zip, REGEXP_SUBSTR(address, '[A-Z]{2}(?= [0-9]{5}$)', 1, 1, 'c') AS state FROM customer WHERE id < 6 ORDER BY id; ``` | id | zip | state | |---|---|---| | 0 | 91607 | KY | | 1 | 36334 | NV | | 2 | 84416 | VA | | 3 | 56742 | MS | | 4 | 13968 | AE | | 5 | 11468 | WY | ## See also - [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like) - [String functions](https://www.coradb.ai/manual/sql/function/string_fn.html) - [no_backslash_escapes](https://www.coradb.ai/manual/admin/config_sql.html#no_backslash_escapes) --- # ROWNUM, INST_NUM, ORDERBY_NUM and GROUPBY_NUM Source: https://www.coradb.ai/manual/sql/function/rownum_fn.html These functions number the rows of a query result. They differ in **when** the numbering happens, which decides what a condition on them selects: | Function | Numbers the rows | Use in | |---|---|---| | `ROWNUM`, `INST_NUM()` | As they are read, **before** `GROUP BY` and `ORDER BY` | `SELECT` list, `WHERE` | | `ORDERBY_NUM()` | **after** `ORDER BY` | `SELECT` list, `FOR ORDERBY_NUM() ...` after `ORDER BY` | | `GROUPBY_NUM()` | **after** `GROUP BY` | `SELECT` list, `HAVING` | The numbers start at 1. **Return type:** BIGINT. In most cases [LIMIT](https://www.coradb.ai/manual/sql/query/select.html#limit-clause) is simpler, and the window function [ROW_NUMBER()](https://www.coradb.ai/manual/sql/function/analysis_fn.html#row_number) gives full control over numbering. The functions on this page remain useful for compatibility and for conditions on the row number. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). ## ROWNUM, INST_NUM ```text ROWNUM INST_NUM() ``` `ROWNUM` (a pseudocolumn) and `INST_NUM()` number rows in the order they are produced, before any sorting. A condition on `ROWNUM` in the `WHERE` clause therefore stops reading after the given number of rows. To take the first rows of a **sorted** result, sort in a subquery and number in the outer query. The four orders with the highest shipping cost: ```sql SELECT * FROM ( SELECT id, shipping_cost FROM orders ORDER BY shipping_cost DESC, id ) AS t WHERE ROWNUM < 5; ``` | id | shipping_cost | |---:|---:| | 2136 | 59.99 | | 2879 | 59.99 | | 1080 | 58.00 | | 1982 | 56.96 | `LIMIT` returns the same rows more simply: `SELECT id, shipping_cost FROM orders ORDER BY shipping_cost DESC, id LIMIT 4;`. A `ROWNUM` condition in the same query as the `ORDER BY` is applied **before** sorting: it picks the first four rows read, then sorts only those. ```sql SELECT ROWNUM, id, shipping_cost FROM orders WHERE ROWNUM < 5 ORDER BY shipping_cost DESC; ``` | rownum | id | shipping_cost | |---:|---:|---:| | 4 | 3 | 23.41 | | 3 | 2 | 12.74 | | 2 | 1 | 9.19 | | 1 | 0 | 0.00 | Notes: - `ROWNUM` belongs to the `SELECT` in which it appears; in a subquery it numbers the subquery's rows. - `ROWNUM` cannot be compared with a column or a correlated subquery. - In `INSERT ... SELECT`, `UPDATE` and `DELETE`, `ROWNUM` in the `WHERE` clause limits the number of rows processed. ## ORDERBY_NUM ```text ORDERBY_NUM() SELECT ... ORDER BY ... FOR ORDERBY_NUM() ``` `ORDERBY_NUM()` numbers the rows after sorting. In the `FOR` clause after `ORDER BY`, it selects a range of the sorted result. The orders ranked 3rd to 5th by shipping cost: ```sql SELECT ORDERBY_NUM(), id, shipping_cost FROM orders ORDER BY shipping_cost DESC, id FOR ORDERBY_NUM() BETWEEN 3 AND 5; ``` | orderby_num() | id | shipping_cost | |---:|---:|---:| | 3 | 1080 | 58.00 | | 4 | 1982 | 56.96 | | 5 | 2211 | 56.87 | The same rows with `LIMIT offset, count`: `... ORDER BY shipping_cost DESC, id LIMIT 2, 3;`. ## GROUPBY_NUM ```text GROUPBY_NUM() SELECT ... GROUP BY ... HAVING GROUPBY_NUM() ``` `GROUPBY_NUM()` numbers the groups after grouping. In `HAVING`, it selects some of the groups: ```sql SELECT GROUPBY_NUM(), customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING GROUPBY_NUM() BETWEEN 1 AND 3; ``` | groupby_num() | customer_id | count(*) | |---:|---:|---:| | 1 | 4 | 3 | | 2 | 5 | 2 | | 3 | 6 | 8 | A `ROWNUM` condition, in contrast, limits the rows **before** they are grouped. Only the first five orders read are counted here: ```sql SELECT customer_id, COUNT(*) FROM orders WHERE ROWNUM BETWEEN 1 AND 5 GROUP BY customer_id; ``` | customer_id | count(*) | |---:|---:| | 4 | 3 | | 5 | 2 | --- # Set arithmetic operators Source: https://www.coradb.ai/manual/sql/function/set_op.html ## SET, MULTISET, LIST To compute union, difference or intersection of collections types (**SET**, **MULTISET**, and **LIST (SEQUENCE)**), you can use +, -, or \* operators, respectively. ```text ::= collection_value | NULL ::= + (union) | - (difference) | * (intersection) ``` The following table shows a result data type by the operator if collection type is an operand. **Result data type by operand type** | | SET | MULTISET | LIST | |--------------------------|---------------------------------------|---------------------------------------|------------------------------------------| | **SET** | **+** , **-** , **\*** : **SET** | **+** , **-** , **\*** : **MULTISET** | **+** , **-** , **\*** : **MULTISET** | | **MULTISET** | **+** , **-** , **\*** : **MULTISET** | **+** , **-** , **\*** : **MULTISET** | **+** , **-** , **\*** : **MULTISET** | | **LIST** **(=SEQUENCE)** | **+, -,**\* : **MULTISET** | **+, -,**\* : **MULTISET** | **+** : **LIST** **-,**\* : **MULTISET** | The following are the examples which execute arithmetic operations with collection types. ```sql SELECT ((CAST ({3,3,3,2,2,1} AS SET))+(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS SET))+(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1, 2, 2, 3, 3, 3, 4} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS MULTISET))+(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS MULTISET))+(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1, 2, 2, 2, 3, 3, 3, 3, 3, 4} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS LIST))+(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS LIST))+(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1, 2, 2, 2, 3, 3, 3, 3, 3, 4} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS SET))-(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS SET))-(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS MULTISET))-(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS MULTISET))-(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1, 2, 3} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS LIST))-(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS LIST))-(CAST ({4,3,3,2} AS MULTISET))) | |---| | {1, 2, 3} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS SET))*(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS SET))*(CAST ({4,3,3,2} AS MULTISET))) | |---| | {2, 3} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS MULTISET))*(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS MULTISET))*(CAST ({4,3,3,2} AS MULTISET))) | |---| | {2, 3, 3} | ```sql SELECT ((CAST ({3,3,3,2,2,1} AS LIST))*(CAST ({4,3,3,2} AS MULTISET))); ``` | ((CAST ({3,3,3,2,2,1} AS LIST))*(CAST ({4,3,3,2} AS MULTISET))) | |---| | {2, 3, 3} | ### Assigning collection value to variable For a collection value to be assigned to a variable, the outer query must return a single row as a result. The following example shows how to assign a collection value to a variable. The outer query must return only a single row as follows: ```sql CREATE TABLE people ( ssn VARCHAR(10), name VARCHAR(255) ); INSERT INTO people VALUES ('1234', 'Ken'), ('5678', 'Dan'), ('9123', 'Jones'); SELECT SET(SELECT name FROM people WHERE ssn in {'1234', '5678'}) TO :name_group; ``` --- # Statement set operators: UNION, EXCEPT, INTERSECT Source: https://www.coradb.ai/manual/sql/function/stmt_set_op.html Statement set operators combine the results of two or more queries into one result. ```text query_term set_operator [DISTINCT | DISTINCTROW | UNIQUE | ALL] query_term [set_operator [...] query_term ...] [ORDER BY ...] [LIMIT ...] set_operator ::= UNION | DIFFERENCE | EXCEPT | INTERSECTION | INTERSECT ``` | Operator | Result | |---|---| | `UNION` | The rows returned by either query. | | `DIFFERENCE`, `EXCEPT` | The rows returned by the first query but not by the second. | | `INTERSECTION`, `INTERSECT` | The rows returned by both queries. | - By default (or with `DISTINCT`, `DISTINCTROW` or `UNIQUE`), duplicate rows are removed from the result. With `ALL`, they are kept: `UNION ALL` returns every row of both queries, and `EXCEPT ALL` and `INTERSECT ALL` count duplicates. - The queries must return the same number of columns, with compatible types. The column names of the result are those of the first query. - An `ORDER BY` or `LIMIT` at the end applies to the combined result. - `UNION ALL` is the cheapest, because it does not have to look for duplicates. Use it when duplicates are impossible or wanted. ## Examples The customers who ordered in December 2024 and in December 2025. Each query returns one row per order, so customers with several orders appear several times. `UNION` returns each customer who ordered in either month once; `UNION ALL` returns one row for each of the 94 + 95 orders: ```sql SELECT COUNT(*) FROM ( SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31' UNION SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31' ) t; ``` | count(*) | |---:| | 149 | ```sql SELECT COUNT(*) FROM ( SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31' UNION ALL SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31' ) t; ``` | count(*) | |---:| | 189 | The customers who ordered in both months: ```sql SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31' INTERSECT SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31' ORDER BY 1 LIMIT 5; ``` | customer_id | |---:| | 32 | | 129 | | 209 | | 223 | | 267 | There are 16 of them. The customers who ordered in December 2024 but not in December 2025: ```sql SELECT COUNT(*) FROM ( SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2024-12-01' AND DATE'2024-12-31' EXCEPT SELECT customer_id FROM orders WHERE order_date BETWEEN DATE'2025-12-01' AND DATE'2025-12-31' ) t; ``` | count(*) | |---:| | 67 | The queries can read different tables, as long as their columns match. Brand and category names that start with N: ```sql SELECT name FROM brand WHERE name LIKE 'N%' UNION SELECT name FROM category WHERE name LIKE 'N%' ORDER BY 1; ``` | name | |---| | New Balance | | New Luma Yoga Collection | | Nike | ## See also - [SELECT](https://www.coradb.ai/manual/sql/query/select.html) - [Set arithmetic operators](https://www.coradb.ai/manual/sql/function/set_op.html): the same operations on collection values --- # String functions: CONCAT, SUBSTR, REPLACE, TRIM, LPAD and more Source: https://www.coradb.ai/manual/sql/function/string_fn.html > **Note:** > In the string functions, if the value of **oracle_style_empty_string** parameter is yes, CoraDB does not separate an empty string and NULL; according to each function, CoraDB regards all of them as NULL or an empty string. For the detail description, see [oracle_style_empty_string](https://www.coradb.ai/manual/admin/config_sql.html#oracle_style_empty_string). ## Concatenation operator A concatenation operator gets a character string or bit string data type as an operand and returns a concatenated string. The plus sign (+) and double pipe symbol (\|\|) are provided as concatenation operators for character string data. If **NULL** is specified as an operand, a **NULL** value is returned. If **pipes_as_concat** that is a parameter related to SQL statement is set to **no** (default value: yes), a double pipe (\|\|) symbol is interpreted as an **OR** operator. If plus_as_concat is set to no (default value: yes), a plus (+) symbol is interpreted as a plus (+) operator. In such case, It is recommended to concatenate strings or bit strings, by using the **CONCAT** function. ```text + || ::= bit string | NULL ::= bit string | character string NULL ``` - \<*concat_operand1*\>: Left string after concatenation. String or bit string can be specified. - \<*concat_operand2*\>: Right string after concatenation. String or bit string can be specified. ```sql SELECT 'CoraDB' || ',' + '2008'; ``` | 'CoraDB' \|\| ',' + '2008' | |---| | CoraDB,2008 | ```sql SELECT 'coradb' || ',' || B'0010' ||B'0000' ||B'0000' ||B'1000'; ``` | 'coradb' \|\| ',' \|\| B'0010' \|\|B'0000' \|\|B'0000' \|\|B'1000' | |---| | coradb,2008 | Numbers are converted to strings when concatenated: ```sql SELECT EXTRACT(YEAR FROM DATE '2026-11-17') || EXTRACT(MONTH FROM DATE '2026-11-17'); ``` | EXTRACT(YEAR FROM DATE '2026-11-17') \|\| EXTRACT(MONTH FROM DATE '2026-11-17') | |---| | 202611 | ```sql SELECT 'CoraDB' || ',' + NULL; ``` | 'CoraDB' \|\| ',' + NULL | |---| | NULL | ## ASCII ```sql ASCII (str) ``` The **ASCII** function returns the ASCII code of the most left character in numeric value. If an input string is **NULL**, **NULL** is returned. This **ASCII** function supports single-byte character sets only. If a numeric value is entered, it is converted into character string and then the ASCII code of the most left character is returned. **Parameters** - `str`: Input string **Return type:** STRING ```sql SELECT ASCII('5'); ``` | ASCII('5') | |---| | 53 | ```sql SELECT ASCII('ab'); ``` | ASCII('ab') | |---| | 97 | ## BIN ```sql BIN (n) ``` The **BIN** function converts a **BIGINT** type number into binary string. If an input string is **NULL**, **NULL** is returned. When you input the string which cannot be transformed into **BIGINT**, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `n`: A **BIGINT** type number **Return type:** STRING ```sql SELECT BIN(12); ``` | BIN(12) | |---| | 1100 | ## BIT_LENGTH ```sql BIT_LENGTH (string) ``` The **BIT_LENGTH** function returns the length (bits) of a character string or bit string as an integer value. The return value of the **BIT_LENGTH** function may depend on the character set, because for the character string, the number of bytes taken up by a single character is different depending on the character set of the data input environment (in UTF-8, for example, `ô` takes 2 bytes, that is 16 bits). For details about character sets supported by CoraDB, see [Character strings](https://www.coradb.ai/manual/sql/datatype_string.html#character-strings). When you input the invalid value, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `string`: Specifies the character string or bit string whose number of bits is to be calculated. If this value is **NULL**, **NULL** is returned. **Return type:** INT ```sql SELECT BIT_LENGTH(''); ``` | BIT_LENGTH('') | |---| | 0 | ```sql SELECT BIT_LENGTH('CoraDB'); ``` | BIT_LENGTH('CoraDB') | |---| | 48 | ```sql -- 'ô' takes two bytes in UTF-8 SELECT BIT_LENGTH('Côte'); ``` | BIT_LENGTH('Côte') | |---| | 40 | ```sql SELECT BIT_LENGTH(B'010101010'); ``` | BIT_LENGTH(B'010101010') | |---| | 9 | The character, byte and bit lengths of the product names that contain non-ASCII letters: ```sql SELECT name, LENGTH(name) AS chars, OCTET_LENGTH(name) AS bytes, BIT_LENGTH(name) AS bits FROM product WHERE name REGEXP '[^ -~]' ORDER BY name; ``` | name | chars | bytes | bits | |---|---|---|---| | Côte de Blaye | 13 | 14 | 112 | | Guaraná Fantástica | 18 | 20 | 160 | | Original Frankfurter Grüne Soße | 31 | 33 | 264 | | Pâte chinois | 12 | 13 | 104 | | Thüringer Rostbratwurst | 23 | 24 | 192 | | Tourtière | 9 | 10 | 80 | ## CHAR_LENGTH, CHARACTER_LENGTH, LENGTHB, LENGTH ```sql CHAR_LENGTH (string) ``` ```sql CHARACTER_LENGTH (string) ``` ```sql LENGTHB (string) ``` ```sql LENGTH (string) ``` **CHAR_LENGTH**, **CHARACTER_LENGTH**, **LENGTHB**, and **LENGTH** are used interchangeably. The number of characters is returned as an integer. For details on character set supported by CoraDB, see [An overview of globalization](https://www.coradb.ai/manual/sql/i18n.html). **Parameters** - `string`: Specifies the string whose length will be calculated according to the number of characters. If the character string is **NULL**, **NULL** is returned. **Return type:** INT > **Note:** > - The length of each space character that is included in a character string is one byte. > - The length of empty quotes (") to represent a space character is 0. Note that in a **CHAR** (*n*) type, the length of a space character is *n*, and it is specified as 1 if n is omitted. ```sql SELECT LENGTH(''); ``` | LENGTH('') | |---| | 0 | ```sql SELECT LENGTH('CoraDB'); ``` | LENGTH('CoraDB') | |---| | 6 | ```sql SELECT LENGTH('Côte'); ``` | LENGTH('Côte') | |---| | 4 | A **CHAR**(*n*) value is padded with spaces to *n* characters, so its length is always *n*: ```sql SELECT LENGTH(CAST('a' AS CHAR(5))), LENGTH(CAST('é' AS CHAR(5))), OCTET_LENGTH(CAST('é' AS CHAR(5))); ``` | LENGTH(CAST('a' AS CHAR(5))) | LENGTH(CAST('é' AS CHAR(5))) | OCTET_LENGTH(CAST('é' AS CHAR(5))) | |---|---|---| | 5 | 5 | 6 | ## CHR ```sql CHR (number_operand [USING charset_name]) ``` The **CHR** function returns a character that corresponds to the return value of the expression specified as an argument. When you input the code value within invalid ranges, it returns an error if the value of **return_null_on_function_errors** in **coradb.conf** is no(the default), or returns NULL if it is yes. **Parameters** - `number_operand`: Specifies an expression that returns a numeric value. - `charset_name`: Characterset name. It supports utf8 and iso88591. **Return type:** STRING ```sql SELECT CHR(68) || CHR(68-2); ``` | CHR(68) \|\| CHR(68-2) | |---| | DB | To get a multibyte character, pass its code in the character set with **USING**. **HEX** and **CONV** go the other way: ```sql SELECT CHR(14909886 USING utf8), HEX('ま'), CONV('E381BE', 16, 10); ``` | CHR(14909886 USING utf8) | HEX('ま') | CONV('E381BE', 16, 10) | |---|---|---| | ま | E381BE | 14909886 | ## CONCAT ```sql CONCAT (string1, string2 [,string3 [, ... [, stringN]...]]) ``` The **CONCAT** function has at least one argument specified for it and returns a string as a result of concatenating all argument values. The number of parameters that can be specified is unlimited. Automatic type casting takes place if a non-string type is specified as the argument. If any of the arguments is specified as **NULL**, **NULL** is returned. If you want to insert separators between strings specified as arguments for concatenation, use the [CONCAT_WS](https://www.coradb.ai/manual/sql/function/string_fn.html#concat_ws) Function. **Parameters** - `strings`: character string **Return type:** STRING ```sql SELECT CONCAT('CoraDB', '2008' , 'R3.0'); ``` | CONCAT('CoraDB', '2008' , 'R3.0') | |---| | CoraDB2008R3.0 | ```sql --it returns null when null is specified for one of parameters SELECT CONCAT('CoraDB', '2008' , 'R3.0', NULL); ``` | CONCAT('CoraDB', '2008' , 'R3.0', NULL) | |---| | NULL | ```sql --it converts number types and then returns concatenated strings SELECT CONCAT(2008, 3.0); ``` | CONCAT(2008, 3.0) | |---| | 20083.0 | ## CONCAT_WS ```sql CONCAT_WS (string1, string2 [,string3 [, ... [, stringN]...]]) ``` The **CONCAT_WS** function has at least two arguments specified for it. The function uses the first argument value as the separator and returns the result. **Parameters** - `strings`: character string **Return type:** STRING ```sql SELECT CONCAT_WS(' ', 'CoraDB', '1.0', 'Manual'); ``` | CONCAT_WS(' ', 'CoraDB', '1.0', 'Manual') | |---| | CoraDB 1.0 Manual | ```sql --it returns strings even if null is specified for one of parameters SELECT CONCAT_WS(' ', 'CoraDB', '1.0', NULL, 'Manual'); ``` | CONCAT_WS(' ', 'CoraDB', '1.0', NULL, 'Manual') | |---| | CoraDB 1.0 Manual | ```sql --it converts number types and then returns concatenated strings with separator SELECT CONCAT_WS(' ',2008, 3.0); ``` | CONCAT_WS(' ',2008, 3.0) | |---| | 2008 3.0 | ## ELT ```sql ELT (N, string1, string2, ... ) ``` If *N* is 1, the **ELT** function returns *string1* and if *N* is 2, it returns *string2*. The return value is a **VARCHAR** type. You can add conditional expressions as needed. The maximum byte length of the character string is 33,554,432 and if this length is exceeded, **NULL** will be returned. If *N* is 0 or a negative number, an empty string will be returned. If *N* is greater than the number of this input character string, **NULL** will be returned as it is out of range. If *N* is a type that cannot be converted to an integer, an error will be returned. **Parameters** - `N`: A position of a string to return among the list of strings - `strings`: The list of strings **Return type:** STRING ```sql SELECT ELT(3,'string1','string2','string3'); ``` | ELT(3,'string1','string2','string3') | |---| | string3 | ```sql SELECT ELT('3','1/1/1','23:00:00','2001-03-04'); ``` | ELT('3','1/1/1','23:00:00','2001-03-04') | |---| | 2001-03-04 | ```sql SELECT ELT(-1, 'string1','string2','string3'); ``` | ELT(-1, 'string1','string2','string3') | |---| | NULL | ```sql SELECT ELT(4,'string1','string2','string3'); ``` | ELT(4,'string1','string2','string3') | |---| | NULL | ```sql SELECT ELT(3.2,'string1','string2','string3'); ``` | ELT(3.2,'string1','string2','string3') | |---| | string3 | A first argument that cannot be converted to a number is an error: ```sql SELECT ELT('a','string1','string2','string3'); ``` ```text ERROR: Cannot coerce 'a' to type bigint. ``` ## FIELD ```sql FIELD ( search_string, string1 [,string2 [, ... [, stringN]...]]) ``` The **FIELD** function returns the location index value (position) of a string of *string1*, *string2*. The function returns 0 if it does not have a parameter value which is the same as *search_string*. It returns 0 if *search_string* is **NULL** because it cannot perform the comparison operation with the other arguments. If all arguments specified for **FIELD** function are of string type, string comparison operation is performed: if all of them are of number type, numeric comparison operation is performed. If the type of one argument is different from that of another, a comparison operation is performed by casting each argument to the type of the first argument. If type casting fails during the comparison operation with each argument, the function considers the result of the comparison operation as **FALSE** and resumes the other operations. **Parameters** - `search_string`: A string pattern to search - `strings`: The list of strings to be searched **Return type:** INT ```sql SELECT FIELD('abc', 'a', 'ab', 'abc', 'abcd', 'abcde'); ``` | FIELD('abc', 'a', 'ab', 'abc', 'abcd', 'abcde') | |---| | 3 | ```sql --it returns 0 when no same string is found in the list SELECT FIELD('abc', 'a', 'ab', NULL); ``` | FIELD('abc', 'a', 'ab', NULL) | |---| | 0 | ```sql --it returns 0 when null is specified in the first parameter SELECT FIELD(NULL, 'a', 'ab', NULL); ``` | FIELD(NULL, 'a', 'ab', NULL) | |---| | 0 | ```sql SELECT FIELD('123', 1, 12, 123.0, 1234, 12345); ``` | FIELD('123', 1, 12, 123.0, 1234, 12345) | |---| | 0 | ```sql SELECT FIELD(123, 1, 12, '123.0', 1234, 12345); ``` | FIELD(123, 1, 12, '123.0', 1234, 12345) | |---| | 3 | ## FIND_IN_SET ```sql FIND_IN_SET (str, strlist) ``` The **FIND_IN_SET** function looks for the string *str* in the string list *strlist* and returns a position of *str* if it exists. A string list is a string composed of substrings separated by a comma (,). If *str* is not in *strlist* or *strlist* is an empty string, 0 is returned. If either argument is **NULL**, **NULL** is returned. This function does not work properly if *str* contains a comma (,). **Parameters** - `str`: A string to be searched - `strlist`: A group of strings separated by a comma **Return type:** INT ```sql SELECT FIND_IN_SET('b','a,b,c,d'); ``` | FIND_IN_SET('b','a,b,c,d') | |---| | 2 | ## FROM_BASE64 ```sql FROM_BASE64(str) ``` **FROM_BASE64** function returns the the decoded result as binary string from the input string encoded as base-64 rule, which is used in **TO_BASE64** function. If the input value is **NULL**, it returns **NULL. When you input the invalid base-64 string, it returns an error if the value of**return_null_on_function_errors\*\* in **coradb.conf** is no(the default); NULL if this value is yes. See [TO_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#to_base64) for more details on base-64 encoding rules. **Parameters** - `str`: Input string **Return type:** STRING ```sql SELECT TO_BASE64('abcd'), FROM_BASE64(TO_BASE64('abcd')); ``` | TO_BASE64('abcd') | FROM_BASE64(TO_BASE64('abcd')) | |---|---| | YWJjZA== | abcd | > **See also:** > [TO_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#to_base64) ## INSERT ```sql INSERT ( str, pos, len, string ) ``` The **INSERT** function inserts a partial character string as long as the length from the specific location of the input character string. The return value is a **VARCHAR** type. The maximum length of the character string is 33,554,432 and if this length is exceeded, **NULL** will be returned. **Parameters** - `str`: Input character string - `pos`: *str* location. Starts from 1. If *pos* is smaller than 1 or greater than the length of *string* + 1, the *string* will not be inserted and the *str* will be returned instead. - `len`: Length of *string* to insert *pos* of *str*. If *len* exceeds the length of the partial character string, insert as many values as *string* in the *pos* of the *str* . If *len* is a negative number, *str* will be the end of the character string. - `string`: Partial character string to insert to *str* **Return type:** STRING ```sql SELECT INSERT('coradb', 2, 2, 'dbsql'), INSERT('coradb', 3, 100, 'db'), INSERT('coradb', 7, 100, 'db'), INSERT('coradb', 3, -1, 'db'); ``` | INSERT('coradb', 2, 2, 'dbsql') | INSERT('coradb', 3, 100, 'db') | INSERT('coradb', 7, 100, 'db') | INSERT('coradb', 3, -1, 'db') | |---|---|---|---| | cdbsqladb | codb | coradbdb | codb | When *pos* is smaller than 1, *str* is returned unchanged: ```sql SELECT INSERT('coradb', 0, 3, 'db'), INSERT('coradb', -3, 3, 'db'); ``` | INSERT('coradb', 0, 3, 'db') | INSERT('coradb', -3, 3, 'db') | |---|---| | coradb | coradb | ## INSTR ```sql INSTR ( string , substring [, position] ) ``` The **INSTR** function, similarly to the **POSITION**, returns the position of a *substring* within *string*; the position. For the **INSTR** function, you can specify the starting position of the search for *substring* to make it possible to search for duplicate *substring*. **Parameters** - `string`: Specifies the input character string. - `substring`: Specifies the character string whose position is to be returned. - `position`: Optional. Represents the position of a *string* where the search begins in character unit. If omitted, the default value 1 is applied. The first position of the *string* is specified as 1. If the value is negative, the system counts backward from the end of the *string*. **Return type:** INT > **Note:** > ```sql --it returns position of the first 'b' SELECT INSTR ('12345abcdeabcde','b'); ``` | INSTR ('12345abcdeabcde','b') | |---| | 7 | ```sql -- it returns position of the first 'É' SELECT INSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 'É' ); ``` | INSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 'É' ) | |---| | 7 | ```sql -- it returns position of the second 'É' SELECT INSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 'É', 11 ); ``` | INSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 'É', 11 ) | |---| | 12 | ```sql --it returns position of the 'b' searching from the 8th position SELECT INSTR ('12345abcdeabcde','b', 8); ``` | INSTR ('12345abcdeabcde','b', 8) | |---| | 12 | ```sql --it returns position of the 'b' searching backwardly from the end SELECT INSTR ('12345abcdeabcde','b', -1); ``` | INSTR ('12345abcdeabcde','b', -1) | |---| | 12 | ```sql --it returns position of the 'b' searching backwardly from a specified position SELECT INSTR ('12345abcdeabcde','b', -8); ``` | INSTR ('12345abcdeabcde','b', -8) | |---| | 7 | ## LCASE, LOWER ```sql LCASE (string) ``` ```sql LOWER (string) ``` The functions **LCASE** and **LOWER** are used interchangeably. They convert uppercase characters included in string to lowercase characters. **Parameters** - `string`: Specifies the string in which uppercase characters are to be converted to lowercase. If the value is **NULL**, **NULL** is returned. **Return type:** STRING ```sql SELECT LOWER(''); ``` | LOWER('') | |---| | | ```sql SELECT LOWER(NULL); ``` | LOWER(NULL) | |---| | NULL | ```sql SELECT LOWER('CoraDB'); ``` | LOWER('CoraDB') | |---| | coradb | **LOWER** converts letters according to the collation of its argument. With the default collation (`utf8_bin`) and the English collations, only ASCII letters are converted. The Turkish collation `utf8_tr_cs` applies the Turkish rules for the dotted and dotless I: ```sql SELECT LOWER('ÀÉÎ'), LOWER('İSTANBUL' COLLATE utf8_tr_cs); ``` | LOWER('ÀÉÎ') | LOWER('İSTANBUL' COLLATE utf8_tr_cs) | |---|---| | ÀÉÎ | istanbul | For supporting collations in CoraDB, see [CoraDB collation](https://www.coradb.ai/manual/sql/i18n.html#coradb-collation). ## LEFT ```sql LEFT ( string , length ) ``` The **LEFT** function returns a length number of characters from the leftmost *string*. If any of the arguments is **NULL**, **NULL** is returned. If a value greater than the *length* of the *string* or a negative number is specified for a length, the entire string is returned. To extract a length number of characters from the rightmost string, use the [RIGHT](https://www.coradb.ai/manual/sql/function/string_fn.html#right). **Parameters** - `string`: Input string - `length`: The length of a string to be returned **Return type:** STRING ```sql SELECT LEFT('CoraDB', 3); ``` | LEFT('CoraDB', 3) | |---| | Cor | ```sql SELECT LEFT('CoraDB', 10); ``` | LEFT('CoraDB', 10) | |---| | CoraDB | ## LOCATE ```sql LOCATE ( substring, string [, position] ) ``` The **LOCATE** function returns the location index value of a *substring* within a character string. The third argument *position* can be omitted. If this argument is specified, the function searches for *substring* from the given position and returns the location index value of the first occurrence. If the *substring* cannot be found within the string, 0 is returned. The **LOCATE** function behaves like [POSITION](https://www.coradb.ai/manual/sql/function/string_fn.html#position). **Parameters** - `substring`: A string pattern to search - `string`: A whole string to be searched - `position`: Starting position of a whole string to be searched **Return type:** INT ```sql --it returns 1 when substring is empty space SELECT LOCATE ('', '12345abcdeabcde'); ``` | LOCATE ('', '12345abcdeabcde') | |---| | 1 | ```sql --it returns position of the first 'abc' SELECT LOCATE ('abc', '12345abcdeabcde'); ``` | LOCATE ('abc', '12345abcdeabcde') | |---| | 6 | ```sql --it returns position of the second 'abc' SELECT LOCATE ('abc', '12345abcdeabcde', 8); ``` | LOCATE ('abc', '12345abcdeabcde', 8) | |---| | 11 | ```sql --it returns 0 when no substring found in the string SELECT LOCATE ('ABC', '12345abcdeabcde'); ``` | LOCATE ('ABC', '12345abcdeabcde') | |---| | 0 | ## LPAD ```sql LPAD ( char1, n, [, char2 ] ) ``` The **LPAD** function pads the left side of a string until the string length reaches the specified value. **Parameters** - `char1`: Specifies the string to pad characters to. If *n* is smaller than the length of *char1*, padding is not performed, and *char1* is truncated to length n and then returned. If the value is **NULL**, **NULL** is returned. - `n`: Specifies the total length of *char1* in bytes. If the value is **NULL**, **NULL** is returned. - `char2`: Specifies the string to pad to the left until the length of *char1* reaches *n*. If it is not specified, empty characters (' ') are used as a default. If the value is **NULL**, **NULL** is returned. **Return type:** STRING > **Note:** > When the value is **NULL**, **NULL** is returned as its result. If *n* is smaller than the length of the string, the string is cut to *n* characters: ```sql SELECT LPAD('CoraDB', 3, '?'), LPAD('Côte', 3, '?'); ``` | LPAD('CoraDB', 3, '?') | LPAD('Côte', 3, '?') | |---|---| | Cor | Côt | ```sql --padding spaces on the left till char_length is 10 SELECT CONCAT('[', LPAD('CoraDB', 10), ']'); ``` | CONCAT('[', LPAD('CoraDB', 10), ']') | |---| | [ CoraDB] | ```sql --padding specific characters on the left till char_length is 10 SELECT LPAD ('CoraDB', 10, '?'); ``` | LPAD ('CoraDB', 10, '?') | |---| | ????CoraDB | ```sql --padding specific characters on the left till char_length is 10 SELECT LPAD ('Côte', 10, '?'); ``` | LPAD ('Côte', 10, '?') | |---| | ??????Côte | ```sql --padding 4 characters on the left SELECT LPAD ('Côte', LENGTH('Côte')+4, '?'); ``` | LPAD ('Côte', LENGTH('Côte')+4, '?') | |---| | ????Côte | ## LTRIM ```sql LTRIM ( string [, trim_string]) ``` The **LTRIM** function removes all specified characters from the left-hand side of a string. **Parameters** - `string`: Enters a string or string-type column to trim. If this value is **NULL**, **NULL** is returned. - `trim_string`: You can specify a specific string to be removed in the left side of *string*. If it is not specified, empty characters (' ') is automatically specified so that the empty characters in the left side are removed. **Return type:** STRING ```sql --trimming spaces on the left SELECT CONCAT('[', LTRIM(' Olympic '), ']'); ``` | CONCAT('[', LTRIM(' Olympic '), ']') | |---| | [Olympic ] | ```sql --If NULL is specified, it returns NULL SELECT LTRIM ('iiiiiOlympiciiiii', NULL); ``` | LTRIM ('iiiiiOlympiciiiii', NULL) | |---| | NULL | ```sql -- trimming specific strings on the left SELECT LTRIM ('iiiiiOlympiciiiii', 'i'); ``` | LTRIM ('iiiiiOlympiciiiii', 'i') | |---| | Olympiciiiii | ## MID ```sql MID ( string, position, substring_length ) ``` The **MID** function extracts a string with the length of *substring_length* from a *position* within the *string* and then returns it. If a negative number is specified as a *position* value, the *position* is calculated in a reverse direction from the end of the *string*. **substring_length** cannot be omitted. If a negative value is specified, the function considers this as 0 and returns an empty string. The **MID** function is working like the [SUBSTR](https://www.coradb.ai/manual/sql/function/string_fn.html#substr), but there are differences in that it cannot be used for bit strings, that the *substring_length* argument must be specified, and that it returns an empty string if a negative number is specified for *substring_length*. **Parameters** - `string`: Specifies an input character string. If this value is **NULL**, **NULL** is returned. - `position`: Specifies the starting position from which the string is to be extracted. The position of the first character is 1. It is considered to be 1 even if it is specified as 0. If the input value is **NULL**, **NULL** is returned. - `substring_length`: Specifies the length of the string to be extracted. If 0 or a negative number is specified, an empty string is returned; if **NULL** is specified, **NULL** is returned. **Return type:** STRING **MID**, **SUBSTR** and **SUBSTRING** differ for negative arguments: ```sql SELECT MID('12345abcdeabcde', 6, 4), SUBSTR('12345abcdeabcde', 6, 4), SUBSTRING('12345abcdeabcde', 6, 4); ``` | MID('12345abcdeabcde', 6, 4) | SUBSTR('12345abcdeabcde', 6, 4) | SUBSTRING('12345abcdeabcde', 6, 4) | |---|---|---| | abcd | abcd | abcd | A negative position counts from the end of the string for **MID** and **SUBSTR**: ```sql SELECT MID('12345abcdeabcde', -6, 4), SUBSTR('12345abcdeabcde', -6, 4); ``` | MID('12345abcdeabcde', -6, 4) | SUBSTR('12345abcdeabcde', -6, 4) | |---|---| | eabc | eabc | A negative length gives an empty string with **MID** and **NULL** with **SUBSTR**: ```sql SELECT CONCAT('[', MID('12345abcdeabcde', 6, -4), ']'), SUBSTR('12345abcdeabcde', 6, -4); ``` | CONCAT('[', MID('12345abcdeabcde', 6, -4), ']') | SUBSTR('12345abcdeabcde', 6, -4) | |---|---| | [] | NULL | ## OCTET_LENGTH ```sql OCTET_LENGTH ( string ) ``` The **OCTET_LENGTH** function returns the length (byte) of a character string or bit string as an integer. Therefore, it returns 1 (byte) if the length of the bit string is 8 bits, but 2 (bytes) if the length is 9 bits. **Parameters** - `string`: Specifies the character or bit string whose length is to be returned in bytes. If the value is **NULL**, **NULL** is returned. **Return type:** INT ```sql SELECT OCTET_LENGTH(''); ``` | OCTET_LENGTH('') | |---| | 0 | ```sql SELECT OCTET_LENGTH('CoraDB'); ``` | OCTET_LENGTH('CoraDB') | |---| | 6 | ```sql SELECT OCTET_LENGTH('Côte'); ``` | OCTET_LENGTH('Côte') | |---| | 5 | ```sql SELECT OCTET_LENGTH(B'010101010'); ``` | OCTET_LENGTH(B'010101010') | |---| | 2 | See also the product-name example under [BIT_LENGTH](https://www.coradb.ai/manual/sql/function/string_fn.html#bit_length). ## POSITION ```sql POSITION ( substring IN string ) ``` The **POSITION** function returns the position of a character string corresponding to *substring* within a character string corresponding to *string*. The return value is the position in characters, an integer greater than or equal to 0. The **POSITION** function is occasionally used in combination with other functions. For example, if you want to extract a certain string from another string, you can use the result of the **POSITION** function as an input to the **SUBSTRING** function. **Parameters** - `substring`: Specifies the character string whose position is to be returned. If the value is an empty character, 1 is returned. If the value is **NULL**, **NULL** is returned. **Return type:** INT ```sql --it returns 1 when substring is empty space SELECT POSITION ('' IN '12345abcdeabcde'); ``` | POSITION ('' IN '12345abcdeabcde') | |---| | 1 | ```sql --it returns position of the first 'b' SELECT POSITION ('b' IN '12345abcdeabcde'); ``` | POSITION ('b' IN '12345abcdeabcde') | |---| | 7 | ```sql -- it returns position of the first 'É' SELECT POSITION ('É' IN '12345ÀÉÎÕÜÀÉÎÕÜ'); ``` | POSITION ('É' IN '12345ÀÉÎÕÜÀÉÎÕÜ') | |---| | 7 | ```sql --it returns 0 when no substring found in the string SELECT POSITION ('f' IN '12345abcdeabcde'); ``` | POSITION ('f' IN '12345abcdeabcde') | |---| | 0 | ## REPEAT ```sql REPEAT( string, count ) ``` The **REPEAT** function returns the character string with a length equal to the number of repeated input character strings. The return value is a **VARCHAR** type. The maximum length of the character string is 33,554,432 and if it this length is exceeded, **NULL** will be returned. If one of the parameters is **NULL**, **NULL** will be returned. **Parameters** - `substring`: Character string - `count`: Repeat count. If you enter 0 or a negative number, an empty string will be returned and if you enter a non-numeric data type, an error will be returned. **Return type:** STRING ```sql SELECT REPEAT('coradb',3); ``` | REPEAT('coradb',3) | |---| | coradbcoradbcoradb | ```sql SELECT REPEAT('coradb',32000000); ``` ```text repeat('coradb', 32000000) ====================== NULL ``` ```sql SELECT REPEAT('coradb',-1); ``` | REPEAT('coradb',-1) | |---| | | ```sql SELECT REPEAT('coradb','a'); ``` ```text ERROR: Cannot coerce 'a' to type integer. ``` ## REPLACE ```sql REPLACE ( string, search_string [, replacement_string ] ) ``` The **REPLACE** function searches for a character string, *search_string*, within a given character string, *string*, and replaces it with a character string, *replacement_string*. If the string to be replaced, *replacement_string* is omitted, all *search_strings* retrieved from *string* are removed. If **NULL** is specified as an argument, **NULL** is returned. **Parameters** - `string`: Specifies the original string. If the value is **NULL**, **NULL** is returned. - `search_string`: Specifies the string to be searched. If the value is **NULL**, **NULL** is returned - `replacement_string`: Specifies the string to replace the *search_string*. If this value is omitted, *string* is returned with the *search_string* removed. If the value is **NULL**, **NULL** is returned. **Return type:** STRING ```sql SELECT REPLACE('12345abcdeabcde', 'abcde', 'ABCDE'), REPLACE('12345abcdeabcde', 'abcde'); ``` | REPLACE('12345abcdeabcde', 'abcde', 'ABCDE') | REPLACE('12345abcdeabcde', 'abcde') | |---|---| | 12345ABCDEABCDE | 12345 | Every occurrence is replaced; without *replace_string*, the occurrences are removed. If an argument is **NULL**, the result is **NULL**. Removing the dashes from customer phone numbers: ```sql SELECT id, phone, REPLACE(phone, '-', '') AS no_dashes FROM customer WHERE id < 4 ORDER BY id; ``` | id | phone | no_dashes | |---|---|---| | 0 | 001-800-310-4977 | 0018003104977 | | 1 | 122-213-1333 | 1222131333 | | 2 | 7443494058 | 7443494058 | | 3 | +1-435-097-0394 | +14350970394 | ## REVERSE ```sql REVERSE( string ) ``` The **REVERSE** function returns *string* converted in the reverse order. **Parameters** - `string`: Specifies an input character string. If the value is an empty string, empty value is returned. If the value is NULL, NULL is returned. **Return type:** STRING ```sql SELECT REVERSE('CoraDB'); ``` | REVERSE('CoraDB') | |---| | BDaroC | ## RIGHT ```sql RIGHT ( string , length ) ``` The **RIGHT** function returns a *length* number of characters from the rightmost *string*. If any of the arguments is **NULL**, **NULL** is returned. If a value greater than the length of the *string* or a negative number is specified for a *length*, the entire string is returned. To extract a length number of characters from the leftmost string, use the [LEFT](https://www.coradb.ai/manual/sql/function/string_fn.html#left). **Parameters** - `string`: Input string - `length`: The length of a string to be returned **Return type:** STRING ```sql SELECT RIGHT('CoraDB', 3); ``` | RIGHT('CoraDB', 3) | |---| | aDB | ```sql SELECT RIGHT ('CoraDB', 10); ``` | RIGHT ('CoraDB', 10) | |---| | CoraDB | ## RPAD ```sql RPAD( char1, n, [, char2 ] ) ``` The **RPAD** function pads the right side of a string until the string length reaches the specified value. **Parameters** - `char1`: Specifies the string to pad characters to. If *n* is smaller than the length of *char1*, padding is not performed, and *char1* is truncated to length *n* and then returned. If the value is **NULL**, **NULL** is specified. - `n`: Specifies the total length of *char1*. If the value is **NULL**, **NULL** is specified. - `char2`: Specifies the string to pad to the right until the length of *char1* reaches *n*. If it is not specified, empty characters (' ') are used as a default. If the value is **NULL**, **NULL** is returned. **Return type:** STRING > **Note:** > When the value is **NULL**, **NULL** is returned as its result. ```sql --it returns only 3 characters if not enough length is specified SELECT RPAD ('CoraDB', 3, '?'); ``` | RPAD ('CoraDB', 3, '?') | |---| | Cor | ```sql --on multi-byte charset, it returns the first character only with a right-padded space SELECT RPAD ('Côte', 3, '?'); ``` | RPAD ('Côte', 3, '?') | |---| | Côt | ```sql --padding spaces on the right till char_length is 10 SELECT CONCAT('[', RPAD('CoraDB', 10), ']'); ``` | CONCAT('[', RPAD('CoraDB', 10), ']') | |---| | [CoraDB ] | ```sql --padding specific characters on the right till char_length is 10 SELECT RPAD ('CoraDB', 10, '?'); ``` | RPAD ('CoraDB', 10, '?') | |---| | CoraDB???? | ```sql --padding specific characters on the right till char_length is 10 SELECT RPAD ('Côte', 10, '?'); ``` | RPAD ('Côte', 10, '?') | |---| | Côte?????? | ```sql --padding 4 characters on the right SELECT RPAD ('Côte', LENGTH('Côte')+4, '?'); ``` | RPAD ('Côte', LENGTH('Côte')+4, '?') | |---| | Côte???? | ## RTRIM ```sql RTRIM ( string [, trim_string]) ``` The **RTRIM** function removes specified characters from the right-hand side of a string. **Parameters** - `string`: Enters a string or string-type column to trim. If this value is **NULL**, **NULL** is returned. - `trim_string`: You can specify a specific string to be removed in the right side of *string*. If it is not specified, empty characters (' ') is automatically specified so that the empty characters in the right side are removed. **Return type:** STRING ```sql SELECT CONCAT('[', RTRIM(' Olympic '), ']'); ``` | CONCAT('[', RTRIM(' Olympic '), ']') | |---| | [ Olympic] | ```sql --If NULL is specified, it returns NULL SELECT RTRIM ('iiiiiOlympiciiiii', NULL); ``` | RTRIM ('iiiiiOlympiciiiii', NULL) | |---| | NULL | ```sql -- trimming specific strings on the right SELECT RTRIM ('iiiiiOlympiciiiii', 'i'); ``` | RTRIM ('iiiiiOlympiciiiii', 'i') | |---| | iiiiiOlympic | ## SPACE ```sql SPACE (N) ``` The **SPACE** function returns as many empty strings as the number specified. The return value is a **VARCHAR** type. **Parameters** - `N`: Space count. It cannot be greater than the value specified in the system parameter, **string_max_size_bytes** (default 1048576). If it exceeds the specified value, **NULL** will be returned. The maximum value is 33,554,432; if this length is exceeded, **NULL** will be returned. If you enter 0 or a negative number, an empty string will be returned; if you enter a type that can't be converted to a numeric value, an error will be returned. **Return type:** STRING ```sql SELECT CONCAT('[', SPACE(8), ']'); ``` | CONCAT('[', SPACE(8), ']') | |---| | [ ] | ```sql SELECT LENGTH(space(1048576)); ``` | LENGTH(space(1048576)) | |---| | 1048576 | ```sql SELECT LENGTH(space(1048577)); ``` | LENGTH(space(1048577)) | |---| | NULL | ```sql SELECT SPACE('aaa'); ``` ```text ERROR: Cannot coerce 'aaa' to type bigint. ``` ## STRCMP ```sql STRCMP( string1 , string2 ) ``` The **STRCMP** function compares two strings, *string1* and *string2*, and returns 0 if they are identical, 1 if *string1* is greater, or -1 if *string1* is smaller. If any of the parameters is **NULL**, **NULL** is returned. **Parameters** - `string1`: A string to be compared - `string2`: A string to be compared **Return type:** INT ```sql SELECT STRCMP('abc', 'abc'); ``` | STRCMP('abc', 'abc') | |---| | 0 | ```sql SELECT STRCMP ('acc', 'abc'); ``` | STRCMP ('acc', 'abc') | |---| | 1 | STRCMP follows the collation of its arguments. With the default, case-sensitive collation, uppercase letters sort before lowercase ones; with a case-insensitive collation such as `utf8_en_ci`, case is ignored: ```sql SELECT STRCMP('ABC', 'abc'), STRCMP('ABC' COLLATE utf8_en_ci, 'abc' COLLATE utf8_en_ci); ``` | STRCMP('ABC', 'abc') | STRCMP('ABC' COLLATE utf8_en_ci, 'abc' COLLATE utf8_en_ci) | |---|---| | -1 | 0 | ## SUBSTR ```sql SUBSTR ( string, position [, substring_length]) ``` The **SUBSTR** function extracts a character string with the length of *substring_length* from a position, *position*, within character string, *string*, and then returns it. > **Note:** > **Parameters** - `string`: Specifies the input character string. If the input value is **NULL**, **NULL** is returned. - `position`: Specifies the position from where the string is to be extracted in bytes. Even though the position of the first character is specified as 1 or a negative number, it is considered as 1. If a value greater than the string length or **NULL** is specified, **NULL** is returned. - `substring_length`: Specifies the length of the string to be extracted in bytes. If this argument is omitted, character strings between the given position, *position*, and the end of them are extracted. **NULL** cannot be specified as an argument value of this function. If 0 is specified, an empty string is returned; if a negative value is specified, **NULL** is returned. **Return type:** STRING ```sql --it returns empty string when substring_length is 0 SELECT SUBSTR('12345abcdeabcde',6, 0); ``` | SUBSTR('12345abcdeabcde',6, 0) | |---| | | ```sql --it returns 4-length substrings counting from the position SELECT SUBSTR('12345abcdeabcde', 6, 4), SUBSTR('12345abcdeabcde', -6, 4); ``` | SUBSTR('12345abcdeabcde', 6, 4) | SUBSTR('12345abcdeabcde', -6, 4) | |---|---| | abcd | eabc | ```sql --it returns substrings counting from the position to the end SELECT SUBSTR('12345abcdeabcde', 6), SUBSTR('12345abcdeabcde', -6); ``` | SUBSTR('12345abcdeabcde', 6) | SUBSTR('12345abcdeabcde', -6) | |---|---| | abcdeabcde | eabcde | ```sql -- it returns 4-length substrings counting from 11th position SELECT SUBSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 11 , 4); ``` | SUBSTR ('12345ÀÉÎÕÜÀÉÎÕÜ', 11 , 4) | |---| | ÀÉÎÕ | ## SUBSTRING ```sql SUBSTRING ( string, position [, substring_length]), ``` ```sql SUBSTRING ( string FROM position [FOR substring_length] ) ``` The **SUBSTRING** function, operating like **SUBSTR**, extracts a character string having the length of *substring_length* from a position, *position*, within character string, *string*, and returns it. If a negative number is specified as the *position* value, the **SUBSTRING** function treats it as 1 (so `SUBSTRING('12345abcdeabcde', -6, 4)` returns `1234`), while the **SUBSTR** function calculates the position from the end of the string. If a negative number is specified as the *substring_length* value, the **SUBSTRING** function handles it as if the argument were omitted, but the **SUBSTR** function returns **NULL**. **Parameters** - `string`: Specifies the input character string. If the input value is **NULL**, **NULL** is returned. - `position`: Specifies the position from where the string is to be extracted. If the position of the first character is specified as 0 or a negative number, it is considered as 1. If a value greater than the string length is specified, an empty string is returned. If **NULL**, **NULL** is returned. - `substring_length`: Specifies the length of the string to be extracted. If this argument is omitted, character strings between the given position, *position*, and the end of them are extracted. If 0 is specified, an empty string is returned; a negative value is ignored, as if the argument were omitted. **Return type:** STRING ```sql SELECT SUBSTRING('12345abcdeabcde', -6 ,4), SUBSTR('12345abcdeabcde', -6 ,4); ``` | SUBSTRING('12345abcdeabcde', -6 ,4) | SUBSTR('12345abcdeabcde', -6 ,4) | |---|---| | 1234 | eabc | ```sql SELECT SUBSTRING('12345abcdeabcde', 16), SUBSTR('12345abcdeabcde', 16); ``` | SUBSTRING('12345abcdeabcde', 16) | SUBSTR('12345abcdeabcde', 16) | |---|---| | | NULL | ```sql SELECT SUBSTRING('12345abcdeabcde', 6, -4), SUBSTR('12345abcdeabcde', 6, -4); ``` | SUBSTRING('12345abcdeabcde', 6, -4) | SUBSTR('12345abcdeabcde', 6, -4) | |---|---| | abcdeabcde | NULL | ## SUBSTRING_INDEX ```sql SUBSTRING_INDEX (string, delim, count) ``` The **SUBSTRING_INDEX** function counts the separators included in the partial character string and will return the partial character string before the *count*-th separator. The return value is a **VARCHAR** type. **Parameters** - `string`: Input character string. The maximum length is 33,554,432 and if this length is exceeded, **NULL** will be returned. - `delim`: Delimiter. It is case-sensitive. - `count`: Delimiter occurrence count. If you enter a positive number, it counts the character string from the left and if you enter a negative number, it counts it from the right. If it is 0, an empty string will be returned. If the type cannot be converted, an error will be returned. **Return type:** STRING ```sql SELECT SUBSTRING_INDEX('www.coradb.ai','.','2'); ``` | `SUBSTRING_INDEX('www.coradb.ai','.','2')` | |---| | `www.coradb` | ```sql SELECT SUBSTRING_INDEX('www.coradb.ai','.','2.3'); ``` | `SUBSTRING_INDEX('www.coradb.ai','.','2.3')` | |---| | `www.coradb` | ```sql SELECT SUBSTRING_INDEX('www.coradb.ai',':','2.3'); ``` | `SUBSTRING_INDEX('www.coradb.ai',':','2.3')` | |---| | `www.coradb.ai` | ```sql SELECT SUBSTRING_INDEX('www.coradb.ai','coradb',1); ``` | `SUBSTRING_INDEX('www.coradb.ai','coradb',1)` | |---| | `www.` | ```sql SELECT SUBSTRING_INDEX('www.coradb.ai','.',100); ``` | `SUBSTRING_INDEX('www.coradb.ai','.',100)` | |---| | `www.coradb.ai` | ## TO_BASE64 ```sql TO_BASE64(str) ``` Returns the result as the transformed base-64 string. If the input argument is not a string, it is changed into a string before it is transformed. If the input argument is **NULL**, it returns **NULL**. The base-64 encoded string can be decoded with [FROM_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#from_base64) function. **Parameters** - `str`: Input string **Return type:** STRING ```sql SELECT TO_BASE64('abcd'), FROM_BASE64(TO_BASE64('abcd')); ``` | TO_BASE64('abcd') | FROM_BASE64(TO_BASE64('abcd')) | |---|---| | YWJjZA== | abcd | The following is rules for [TO_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#to_base64) function and [FROM_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#from_base64). - The encoded character for the alphabet value 62 is '+'. - The encoded character for the alphabet value 63 is '/'. - The encoded result consists of character groups, and each group has 4 characters which can be printed out. The 3 bytes of the input data are encoded into 4 bytes. If the last group are not filled with 4 characters, '=' character is padded into that group and 4 characters are made. - To divide the long output into the several lines, a newline is added into each 76 encoded output characters. - Decoding process indicates newline, carriage return, tab, and space and ignore them. > **See also:** > [FROM_BASE64](https://www.coradb.ai/manual/sql/function/string_fn.html#from_base64) ## TRANSLATE ```sql TRANSLATE ( string, from_substring, to_substring ) ``` The **TRANSLATE** function replaces a character into the character specified in *to_substring* if the character exists in the specified *string*. Correspondence relationship is determined based on the order of characters specified in *from_substring* and *to_substring*. Any characters in *from_substring* that do not have one on one relationship to *to_substring* are all removed. This function is working like the [REPLACE](https://www.coradb.ai/manual/sql/function/string_fn.html#replace) but the argument of *to_substring* cannot be omitted in this function. **Parameters** - `string`: Specifies the original string. If the value is **NULL**, **NULL** is returned. - `from_substring`: Specifies the string to be retrieved. If the value is **NULL**, **NULL** is returned. - `to_substring`: Specifies the character string in the *from_substring* to be replaced. It cannot be omitted. If the value is **NULL**, **NULL** is returned. **Return type:** STRING ```sql --it returns NULL when an argument is specified with NULL value SELECT TRANSLATE('12345abcdeabcde','abcde', NULL); ``` | TRANSLATE('12345abcdeabcde','abcde', NULL) | |---| | NULL | ```sql --it translates 'a','b','c','d','e' into '1', '2', '3', '4', '5' respectively SELECT TRANSLATE('12345abcdeabcde', 'abcde', '12345'); ``` | TRANSLATE('12345abcdeabcde', 'abcde', '12345') | |---| | 123451234512345 | ```sql --it translates 'a','b','c' into '1', '2', '3' respectively and removes 'd's and 'e's SELECT TRANSLATE('12345abcdeabcde','abcde', '123'); ``` | TRANSLATE('12345abcdeabcde','abcde', '123') | |---| | 12345123123 | ```sql --it removes 'a's,'b's,'c's,'d's, and 'e's in the string SELECT TRANSLATE('12345abcdeabcde','abcde', ''); ``` | TRANSLATE('12345abcdeabcde','abcde', '') | |---| | 12345 | ```sql --it only translates 'a','b','c' into '3', '4', '5' respectively SELECT TRANSLATE('12345abcdeabcde','ABabc', '12345'); ``` | TRANSLATE('12345abcdeabcde','ABabc', '12345') | |---| | 12345345de345de | ## TRIM ```sql TRIM ( [ [ LEADING | TRAILING | BOTH ] [ trim_string ] FROM ] string ) ``` The **TRIM** function removes specific characters which are located before and after the string. **Parameters** - `trim_string`: Specifies a specific string to be removed that is in front of or at the back of the target string. If it is not specified, an empty character (' ') is automatically specified so that spaces in front of or at the back of the target string are removed. - `string`: Enters a string or string-type column to trim. If this value is **NULL**, **NULL** is returned. **Return type:** STRING - **\[LEADING\|TRAILING\|BOTH\]** : You can specify an option to trim a specified string that is in a certain position of the target string. If it is **LEADING**, trimming is performed in front of a character string if it is **TRAILING**, trimming is performed at the back of a character string if it is **BOTH**, trimming is performed in front and at the back of a character string. If the option is not specified, **BOTH** is specified by default. - The character string of *trim_string* and *string* should have the same character set. ```sql --trimming NULL returns NULL SELECT TRIM (NULL); ``` | TRIM (NULL) | |---| | NULL | ```sql --trimming spaces on both leading and trailing parts SELECT CONCAT('[', TRIM(' Olympic '), ']'); ``` | CONCAT('[', TRIM(' Olympic '), ']') | |---| | [Olympic] | ```sql SELECT TRIM('i' FROM 'iiiiiOlympiciiiii'), TRIM(LEADING 'i' FROM 'iiiiiOlympiciiiii'), TRIM(TRAILING 'i' FROM 'iiiiiOlympiciiiii'); ``` | TRIM('i' FROM 'iiiiiOlympiciiiii') | TRIM(LEADING 'i' FROM 'iiiiiOlympiciiiii') | TRIM(TRAILING 'i' FROM 'iiiiiOlympiciiiii') | |---|---|---| | Olympic | Olympiciiiii | iiiiiOlympic | ## UCASE, UPPER ```sql UCASE ( string ) ``` ```sql UPPER ( string ) ``` The function **UCASE** or **UPPER** converts lowercase characters that are included in a character string to uppercase characters. **Parameters** - `string`: Specifies the string in which lowercase characters are to be converted to uppercase. If the value is **NULL**, **NULL** is returned. **Return type:** STRING ```sql SELECT UPPER(''); ``` | UPPER('') | |---| | | ```sql SELECT UPPER(NULL); ``` | UPPER(NULL) | |---| | NULL | ```sql SELECT UPPER('CoraDB'); ``` | UPPER('CoraDB') | |---| | CORADB | **UPPER** converts letters according to the collation of its argument, as described for [LOWER](https://www.coradb.ai/manual/sql/function/string_fn.html#lcase-lower): ```sql SELECT UPPER('àéî'), UPPER('istanbul'), UPPER('istanbul' COLLATE utf8_tr_cs); ``` | UPPER('àéî') | UPPER('istanbul') | UPPER('istanbul' COLLATE utf8_tr_cs) | |---|---|---| | àéî | ISTANBUL | İSTANBUL | Regarding collations which CoraDB supports, see [CoraDB collation](https://www.coradb.ai/manual/sql/i18n.html#coradb-collation). --- # Data type conversion functions: CAST, TO_CHAR, TO_DATE, TO_NUMBER, DATE_FORMAT Source: https://www.coradb.ai/manual/sql/function/typecast_fn.html ## CAST ```sql CAST (cast_operand AS cast_target) ``` The **CAST** operator can be used to explicitly cast one data type to another in the **SELECT** statement. A query list or a value expression in the **WHERE** clause can be cast to another data type. **Parameters** - `cast_operand`: Declares the value to cast to a different data type. - `cast_target`: Specifies the type to cast to. **Return type:** cast_target Depending on the situation, data type can be automatically converted without using the **CAST** operator. For details, see [Implicit type conversion](https://www.coradb.ai/manual/sql/datatype.html#implicit-type-conversion). See [CASTing a string to date/time type](https://www.coradb.ai/manual/sql/datatype_datetime.html#casting-a-string-to-datetime-type) regarding to convert the string of date/time type into date/time type. The following table shows a summary of explicit type conversions (casts) using the **CAST** operator in CoraDB. | From \ To | EN | AN | VC | FC | VB | FB | ENUM | BLOB | CLOB | D | T | UT | UTZ | DT | DTZ | S | MS | SQ | |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| | **EN** | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | Yes | Yes | No | No | No | No | No | | **AN** | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | Yes | Yes | No | No | No | No | No | | **VC** | Yes | Yes | Yes(*) | Yes(*) | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **FC** | Yes | Yes | Yes(*) | Yes(*) | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **VB** | No | No | Yes | Yes | Yes | Yes | No | Yes | Yes | No | No | No | No | No | No | No | No | No | | **FB** | No | No | Yes | Yes | Yes | Yes | No | Yes | Yes | No | No | No | No | No | No | No | No | No | | **ENUM** | No | No | Yes | Yes | No | No | Yes | No | No | No | No | No | No | No | No | No | No | No | | **BLOB** | No | No | No | No | Yes | Yes | Yes | Yes | No | No | No | No | No | No | No | No | No | No | | **CLOB** | No | No | Yes | Yes | No | No | Yes | No | Yes | No | No | No | No | No | No | No | No | No | | **D** | No | No | Yes | Yes | No | No | No | No | No | Yes | No | Yes | Yes | Yes | Yes | No | No | No | | **T** | No | No | Yes | Yes | No | No | No | No | No | No | Yes | No | No | No | No | No | No | No | | **UT** | No | No | Yes | Yes | No | No | No | No | No | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **UTZ** | No | No | Yes | Yes | No | No | No | No | No | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **DT** | No | No | Yes | Yes | No | No | No | No | No | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **DTZ** | No | No | Yes | Yes | No | No | No | No | No | Yes | Yes | Yes | Yes | Yes | Yes | No | No | No | | **S** | No | No | No | No | No | No | No | No | No | No | No | No | No | No | No | Yes | Yes | Yes | | **MS** | No | No | No | No | No | No | No | No | No | No | No | No | No | No | No | Yes | Yes | Yes | | **SQ** | No | No | No | No | No | No | No | No | No | No | No | No | No | No | No | Yes | Yes | Yes | (*): TheCAST*\* operation is allowed only when the value expression and the data type to be cast have the same character set. - **Data type key** - **EN**: Exact numeric data type (**INTEGER**, **SMALLINT**, **BIGINT**, **NUMERIC**, **DECIMAL**) - **AN**: Approximate numeric data type (**FLOAT/REAL**, **DOUBLE**) - **VC**: Variable-length character string (**VARCHAR** (*n*)) - **FC**: Fixed-length character string (**CHAR** (*n*)) - **VB**: Variable-length bit string (**BIT VARYING** (*n*)) - **FB**: Fixed-length bit string (**BIT** (*n*)) - **ENUM**: **ENUM** type - **BLOB**: Binary data that is stored outside DB - **CLOB**: String data that is stored inside DB - **D**: **DATE** - **T**: **TIME** - **DT**: **DATETIME** - **DTZ**: **DATETIME WITH TIME ZONE** and **DATETIME WITH LOCAL TIME ZONE** data types - **UT**: **TIMESTAMP** - **UTZ**: **TIMESTAMP WITH TIME ZONE** and **TIMESTAMP WITH LOCAL TIME ZONE** data types - **S**: **SET** - **MS**: **MULTISET** - **SQ**: **LIST** (= **SEQUENCE**) ```sql --operation after casting character as INT type returns 2 SELECT (1+CAST ('1' AS INT)); ``` | (1+CAST ('1' AS INT)) | |---| | 2 | ```sql --cannot cast the string which is out of range as SMALLINT SELECT (1+CAST('1234567890' AS SMALLINT)); ``` ```text ERROR: Data overflow on data type "smallint". ``` ```sql --operation after casting returns 1+1234567890 SELECT (1+CAST('1234567890' AS INT)); ``` | (1+CAST('1234567890' AS INT)) | |---| | 1234567891 | ```sql --'1234.567890' is casted to 1235 after rounding up SELECT (1+CAST('1234.567890' AS INT)); ``` | (1+CAST('1234.567890' AS INT)) | |---| | 1236 | ```sql --'1234.567890' is casted to string containing only first 5 letters. SELECT (CAST('1234.567890' AS CHAR(5))); ``` | (CAST('1234.567890' AS CHAR(5))) | |---| | 1234. | ```sql --numeric type can be casted to CHAR type only when enough length is specified SELECT (CAST(1234.567890 AS CHAR(5))); ``` ```text ERROR: Data overflow on data type "character". ``` ```sql --numeric type can be casted to CHAR type only when enough length is specified SELECT (CAST(1234.567890 AS CHAR(11))); ``` | (CAST(1234.567890 AS CHAR(11))) | |---| | 1234.567890 | ```sql --numeric type can be casted to CHAR type only when enough length is specified SELECT (CAST(1234.567890 AS VARCHAR)); ``` | (CAST(1234.567890 AS VARCHAR)) | |---| | 1234.567890 | ```sql --string can be casted to time/date types only when its literal is correctly specified SELECT (CAST('2008-12-25 10:30:20' AS TIMESTAMP)); ``` | (CAST('2008-12-25 10:30:20' AS TIMESTAMP)) | |---| | 2008-12-25 10:30:20 | ```sql SELECT (CAST('10:30:20' AS TIME)); ``` | (CAST('10:30:20' AS TIME)) | |---| | 10:30:20 | ```sql --string can be casted to TIME type when its literal is same as TIME's. SELECT (CAST('2008-12-25 10:30:20' AS TIME)); ``` | (CAST('2008-12-25 10:30:20' AS TIME)) | |---| | 10:30:20 | ```sql --string can be casted to TIME type after specifying its type of the string SELECT (CAST(TIMESTAMP'2008-12-25 10:30:20' AS TIME)); ``` | (CAST(TIMESTAMP'2008-12-25 10:30:20' AS TIME)) | |---| | 10:30:20 | A string cast to **BLOB** is stored as the bytes of its characters. [BLOB_TO_BIT](https://www.coradb.ai/manual/sql/function/lob_fn.html#blob_to_bit) shows them: ```sql SELECT CAST(BLOB_TO_BIT(CAST('1A' AS BLOB)) AS VARCHAR(100)), BLOB_LENGTH(CAST('abcde' AS BLOB)); ``` | CAST(BLOB_TO_BIT(CAST('1A' AS BLOB)) AS VARCHAR(100)) | BLOB_LENGTH(CAST('abcde' AS BLOB)) | |---|---| | 3141 | 5 | A bit string cast to a character string gives its hexadecimal digits: ```sql SELECT CAST(B'11010000' AS VARCHAR(10)); ``` | CAST(B'11010000' AS VARCHAR(10)) | |---| | d0 | A number cast to **TIMESTAMP** is taken as a Unix time (seconds since 1970-01-01 00:00:00 UTC) and shown in the session time zone. In a session whose time zone is UTC: ```sql SET TIME ZONE 'UTC'; SELECT CAST(1 AS TIMESTAMP), CAST(1.2F AS TIMESTAMP); ``` ```text cast(1 as timestamp) cast(1.2F as timestamp) =============================================== 1970-01-01 00:00:01 1970-01-01 00:00:01 ``` Numbers cannot be cast to **DATETIME**, and date/time values cannot be cast to numbers; use [UNIX_TIMESTAMP](https://www.coradb.ai/manual/sql/function/datetime_fn.html#unix_timestamp) for the opposite conversion: ```sql SELECT CAST(1 AS DATETIME); SELECT CAST(TIMESTAMP'1970-01-01 00:00:01' AS INT); ``` ```text ERROR: Cannot coerce 1 to type datetime. ERROR: Cannot coerce timestamp '1970-01-01 00:00:01' to type integer. ``` > **Note:** > - **CAST** is allowed only between data types having the same character set. > - If you cast an approximate data type(FLOAT, DOUBLE) to integer type, the number is rounded to zero decimal places. > - If you cast an exact numeric data type(NUMERIC) to integer type, the number is rounded to zero decimal places. > - If you cast a numeric data type to string character type, it should be longer than the length of significant figures + decimal point. An error occurs otherwise. > - If you cast a character string type *A* to a character string type *B*, B should be longer than the *A*. The end of character string is truncated otherwise. > - If you cast a character string type *A* to a date-time date type *B*, it is converted only when literal of *A* and *B* type match one another. An error occurs otherwise. > - You must explicitly do type casting for numeric data stored in a character string so that an arithmetic operation can be performed. ## DATE_FORMAT ```sql DATE_FORMAT (date, format) ``` The **DATE_FORMAT** function converts the value of date/time data type which include a date to specified date/time format and then return the value with the **VARCHAR** data type. For the format parameter to assign, refer to [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) table of the [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format). The [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) table is used in [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format), [TIME_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#time_format), and [STR_TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#str_to_date) functions. **Parameters** - `date`: A value of DATE, TIMESTAMP, DATETIME, DATETIMETZ, DATETIMELTZ, TIMESTAMPTZ, or TIMESTAMP. - `format`: Specifies the output format. The format specifier starting with '%' is used. **Return type:** STRING When the *format* argument is assigned, the string is interpreted according to the specified language. At that time, the language specified as the **intl_date_lang** system parameter is applied. If the **intl_date_lang** value is not set, the language specified when creating DB is applied. For example, when the language is "de_DE" and the format is "%d %M %Y", the string "3 Oktober 2009" is interpreted as the DATE type of "2009-10-03". When the specified *format* argument does not correspond to the given string, an error is returned. In the following [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) table, the month/day, date, and AM/PM in characters are different by language. **Date/time format 2** | format value | Meaning | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| | %a | Weekday, English abbreviation (Sun, ... , Sat) | | %b | Month, English abbreviation (Jan, ... , Dec) | | %c | Month (1, ... , 12) | | %D | Day of the month, English ordinal number (1st, 2nd, 3rd, ...) | | %d | Day of the month, two-digit number (01, ... , 31) | | %e | Day of the month (1, ... , 31) | | %f | Microseconds, three-digit number (000, ... , 999) | | %H | Hour, 24-hour based, number with at least two--digit (00, ... , 23, ... , 100, ... ) | | %h | Hour, 12-hour based two-digit number (01, ... , 12) | | %I | Hour, 12-hour based two-digit number (01, ... , 12) | | %i | Minutes, two-digit number (00, ... , 59) | | %j | Day of year, three-digit number (001, ... , 366) | | %k | Hour, 24-hour based, number with at least one-digit (0, ... , 23, ... , 100, ... ) | | %l | Hour, 12-hour based (1, ... , 12) | | %M | Month, English string (January, ... , December) | | %m | Month, two-digit number (01, ... , 12) | | %p | AM or PM | | %r | Time, 12-hour based, hour:minute:second (hh:mi:ss AM or hh:mi:ss PM) | | %S | Seconds, two-digit number (00, ... , 59) | | %s | Seconds, two-digit number (00, ... , 59) | | %T | Time, 24-hour based, hour:minute:second (hh:mi:ss) | | %U | Week, two-digit number, week number of the year with Sunday being the first day Week (00, ... , 53) | | %u | Week, two-digit number, week number of the year with Monday being the first day (00, ... , 53) | | %V | Week, two-digit number, week number of the year with Sunday being the first day Week (00, ... , 53) (Available to use in combination with %X) | | %v | Week, two-digit number, week number of the year with Monday being the first day (00, ... , 53) (Available to use in combination with %x) | | %W | Weekday, English string (Sunday, ... , Saturday) | | %w | Day of the week, number index (0=Sunday, ... , 6=Saturday) | | %X | Year, four-digit number calculated as the week number with Sunday being the first day of the week (0000, ... , 9999) (Available to use in combination with %V) | | %x | Year, four-digit number calculated as the week number with Monday being the first day of the week (0000, ... , 9999) (Available to use in combination with %v) | | %Y | Year, four-digit number (0001, ... , 9999) | | %y | Year, two-digit number (00, 01, ... , 99) | | %% | Output the special character "%" as a string | | %x | Output an arbitrary character x as a string out of English letters that are not used as format specifiers. | | %TZR | Time zone region information. e.g. US/Pacific. | | %TZD | Daylight saving information. e.g. KST, KT, EET | | %TZH | Timezone hour offset. e.g. +09, -09 | | %TZM | Timezone minute offset. e.g. +00, +30 | > **Note:** > %TZR, %TZD, %TZH, %TZM can be used only in timezone types. > **Note:** > **A format specifying a number after TZD** > > See *A format specifying a number after TZD*. The following example shows the case when the system parameter **intl_date_lang** is "en_US". ```sql SELECT DATE_FORMAT(datetime'2009-10-04 22:23:00', '%W %M %Y'); ``` | DATE_FORMAT(datetime'2009-10-04 22:23:00', '%W %M %Y') | |---| | Sunday October 2009 | ```sql SELECT DATE_FORMAT(datetime'2007-10-04 22:23:00', '%H:%i:%s'); ``` | DATE_FORMAT(datetime'2007-10-04 22:23:00', '%H:%i:%s') | |---| | 22:23:00 | ```sql SELECT DATE_FORMAT(datetime'1900-10-04 22:23:00', '%D %y %a %d %m %b %j'); ``` | DATE_FORMAT(datetime'1900-10-04 22:23:00', '%D %y %a %d %m %b %j') | |---| | 4th 00 Thu 04 10 Oct 277 | ```sql SELECT DATE_FORMAT(date'1999-01-01', '%X %V'); ``` | DATE_FORMAT(date'1999-01-01', '%X %V') | |---| | 1998 52 | With **intl_date_lang** set to Turkish (`tr_TR`), the names of days and months are Turkish: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT DATE_FORMAT(datetime'2009-10-04 22:23:00', '%W %M %Y'), DATE_FORMAT(datetime'1900-10-04 22:23:00', '%D %y %a %d %m %b %j'); ``` ```text Pazar Ekim 2009 4 00 Pe 04 10 Ekm 277 ``` ```sql SELECT DATE_FORMAT(datetime'1900-10-04 22:23:00', '%D %y %a %d %m %b %j'); ``` | DATE_FORMAT(datetime'1900-10-04 22:23:00', '%D %y %a %d %m %b %j') | |---| | 4th 00 Thu 04 10 Oct 277 | The following example outputs the value of DATETIMETZ type which includes timezone information as the desired format. ```sql SELECT DATE_FORMAT(datetimetz'2012-02-02 10:10:10 Europe/Zurich CET', '%TZR %TZD %TZH %TZM'); ``` | DATE_FORMAT(datetimetz'2012-02-02 10:10:10 Europe/Zurich CET', '%TZR %TZD %TZH %TZM') | |---| | Europe/Zurich CET +01 00 | ## FORMAT ```sql FORMAT ( x , dec ) ``` The **FORMAT** function displays the number *x* by using digit grouping symbol as a thousands separator, so that its format becomes '#,###,###.#####' and performs rounding after the decimal point symbol to express as many as *dec* digits after it. The return value is a **VARCHAR** type. **Parameters** - `x`: An expression that returns a numeric value - `dec`: the number of digits of fractional parts **Return type:** STRING Thousands separator symbol and decimal point symbol is output in the format according to the specified language. The language is specified by the **intl_number_lang** system parameter. If the value of **intl_number_lang** is not set, the language specified when creating DB is applied. For example, when the language is one of the European languages, such as "de_DE" or "fr_FR", "." is interpreted as the thousands separator and "," as the decimal point symbol (see [Default output of number by language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-number-format) of the [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char)). The following example shows command execution by setting the value of the **intl_number_lang system** parameter to "en_US". ```sql SELECT FORMAT(12000.123456, 3), FORMAT(12000.123456, 0); ``` | FORMAT(12000.123456, 3) | FORMAT(12000.123456, 0) | |---|---| | 12,000.123 | 12,000 | With **intl_number_lang** set to Turkish (`tr_TR`), "." is the thousands separator and "," the decimal point: ```sql SET SYSTEM PARAMETERS 'intl_number_lang="tr_TR"'; SELECT FORMAT(12000.123456, 3), FORMAT(12000.123456, 0); ``` ```text 12.000,123 12.000 ``` ## STR_TO_DATE ```sql STR_TO_DATE (string, format) ``` The **STR_TO_DATE** function converts the given character string to a date/time value by interpreting it according to the specified format and operates in the opposite way to the [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) function. The return value is determined by the date/time part included in the character string. **Parameters** - `string`: String. - `format`: Specifies the format to interpret the character string. You should use character strings including % for the format specifiers. See [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) table of [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) function. **Return type:** DATETIME, DATE, TIME, DATETIMETZ For the *format* argument to assign, see [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) table of the [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format). If *string* is invalid date/time value or *format* is invalid, it returns an error. When the *format* argument is assigned, the *string* is interpreted according to the specified language. At that time, the language specified as the **intl_date_lang** system parameter is applied. If the **intl_date_lang** value is not set, the language specified when creating DB is applied. For example, when the language is "de_DE" and the *format* is "%d %M %Y", the string "3 Oktober 2009" is interpreted as the **DATE** type of "2009-10-03". If the *format* argument does not correspond to the given *string*, an error is returned. 0 is not allowed in the argument value corresponding to year, month, and day; however, if 0 is inputted in every argument value corresponding to date and time, the value of **DATE** or **DATETIME** type that has 0 for every date and time value is returned as an exception. Note that operation in JDBC program is determined by the configuration of zeroDateTimeBehavior, connection URL property. For more information about zeroDateTimeBehavior, please see [Configuration connection](https://www.coradb.ai/manual/api/jdbc.html#configuration-connection). The following example shows the case when the system parameter **intl_date_lang** is "en_US". ```sql SET SYSTEM PARAMETERS 'intl_date_lang="en_US"'; SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y'); ``` ```text 05/01/2013 ``` ```sql SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y'); ``` | STR_TO_DATE('May 1, 2013','%M %d,%Y') | |---| | 2013-05-01 | ```sql SELECT STR_TO_DATE('13:30:17','%H:%i'); ``` | STR_TO_DATE('13:30:17','%H:%i') | |---| | 13:30:00 | ```sql SELECT STR_TO_DATE('09:30:17 PM','%r'); ``` | STR_TO_DATE('09:30:17 PM','%r') | |---| | 21:30:17 | ```sql SELECT STR_TO_DATE('0,0,0000','%d,%m,%Y'); ``` | STR_TO_DATE('0,0,0000','%d,%m,%Y') | |---| | 0000-00-00 | With **intl_date_lang** set to `tr_TR`, the Turkish month name *Ekim* is read as October: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT STR_TO_DATE('3 Ekim 2009', '%d %M %Y'); ``` ```text 10/03/2009 ``` The following example shows which converts a date/time string with timezone information into DATETIMETZ type value. ```sql SELECT STR_TO_DATE('2001-10-11 02:03:04 AM Europe/Bucharest EEST', '%Y-%m-%d %h:%i:%s %p %TZR %TZD'); ``` | STR_TO_DATE('2001-10-11 02:03:04 AM Europe/Bucharest EEST', '%Y-%m-%d %h:%i:%s %p %TZR %TZD') | |---| | 2001-10-11 02:03:04.000 Europe/Bucharest EEST | ## TIME_FORMAT ```sql TIME_FORMAT (time, format) ``` The **TIME_FORMAT** function converts the date/time data type value including time value into a string of specified date/time format, and returns the value with the **VARCHAR** data type. **Parameters** - `time`: A value of a type with time. (TIME, TIMESTAMP, DATETIME, TIMESTAMPTZ or DATETIMETZ) - `format`: Specifies the output format. Use a string that contains '%' as a specifier. See the table [Date/time format 2](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format2) of [DATE_FORMAT](https://www.coradb.ai/manual/sql/function/typecast_fn.html#date_format) function. **Return type:** STRING When the *format* argument is assigned, the time is output according to the specified language. At this time, the language specified as the **intl_date_lang** system parameter is applied. If **intl_date_lang** system parameter is not set, the language specified when creating DB is applied. For example, when the language is set to "de_DE" and the format is "%h:%i:%s %p", "08:46:53 PM" is output as "08:46:53 Nachm.". When the *format* argument specified does not correspond to the given string, an error is returned. The following example shows the case when the system parameter **intl_date_lang** is "en_US". ```sql SET SYSTEM PARAMETERS 'intl_date_lang="en_US"'; SELECT TIME_FORMAT(time'22:23:00', '%H %i %s'); ``` ```text '22 23 00' ``` ```sql SELECT TIME_FORMAT(time'23:59:00', '%H %h %i %s %f'); ``` | TIME_FORMAT(time'23:59:00', '%H %h %i %s %f') | |---| | 23 11 59 00 000 | ```sql SELECT TIME_FORMAT(time'20:46:53', '%h:%i:%s %p'); ``` | TIME_FORMAT(time'20:46:53', '%h:%i:%s %p') | |---| | 08:46:53 PM | The following outputs the value with a timezone information into a specified format string. ```sql SELECT TIME_FORMAT(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST', '%h:%i:%s %p %TZR %TZD'); ``` | TIME_FORMAT(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST', '%h:%i:%s %p %TZR %TZD') | |---| | 02:03:04 AM Europe/Bucharest EEST | ## TO_CHAR(date_time) ```sql TO_CHAR ( date_time [, format[, date_lang_string_literal ]] ) ``` The **TO_CHAR** (date_time) function converts the value of date/time types (**TIME**, **DATE**, **TIMESTAMP**, **DATETIME**) to a string depending on the table [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1) and then returns the value. The type of the return value is **VARCHAR**. **Parameters** - `date_time`: A value of date/time type. (TIME, DATE, TIMESTAMP, DATETIME, DATETIMETZ, DATETIMELTZ, TIMESTAMPTZ, TIMESTAMPLTZ) - `format`: A format of return value. - `date_lang_string_literal`: Specifies a language applied to a return value. **Return type:** STRING When the *format* argument is specified, the *date_time* is output according to the specified language (see the [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1) table). A language is defined by the *date_lang_string_literal*. If *date_lang_string_literal* is omitted, the language specified by the *intl_date_lang* parameter is applied; if the value of *intl_date_lang* is not specified, the language specified when creating DB is applied. For example, when the language is set to "de_DE" and the format is "HH:MI:SS:AM", "08:46:53 PM" is output as "08:46:53 Nachm.". When the *format* argument specified does not correspond to the given *string*, an error is returned. When the *format* argument is omitted, the *date_time* is output as a string according to the default output format of the "en_US"(see the following table [Default date/time output format for each language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-datetime-format)). **Default date/time output format for each language** | LANG | DATE | TIME | TIMESTAMP | DATETIME | TIMESTAMP WITH TIME ZONE | DATETIME WITH TIME ZONE | |-------|--------------|---------------|--------------------------|-----------------------------|------------------------------|---------------------------------| | en_US | 'MM/DD/YYYY' | 'HH:MI:SS AM' | 'HH:MI:SS AM MM/DD/YYYY' | 'HH:MI:SS.FF AM MM/DD/YYYY' | 'HH:MI:SS AM MM/DD/YYYY TZR' | 'HH:MI:SS.FF AM MM/DD/YYYY TZR' | | de_DE | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD.MM.YYYY TZR' | 'HH24:MI:SS.FF DD.MM.YYYY TZR' | | es_ES | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD/MM/YYYY TZR' | 'HH24:MI:SS.FF DD/MM/YYYY TZR' | | fr_FR | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD/MM/YYYY TZR' | 'HH24:MI:SS.FF DD/MM/YYYY TZR' | | it_IT | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD/MM/YYYY TZR' | 'HH24:MI:SS.FF DD/MM/YYYY TZR' | | ja_JP | 'YYYY/MM/DD' | 'HH24:MI:SS' | 'HH24:MI:SS YYYY/MM/DD' | 'HH24:MI:SS.FF YYYY/MM/DD' | 'HH24:MI:SS YYYY/MM/DD TZR' | 'HH24:MI:SS.FF YYYY/MM/DD TZR' | | km_KH | 'DD/MM/YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD/MM/YYYY' | 'HH24:MI:SS.FF DD/MM/YYYY' | 'HH24:MI:SS DD/MM/YYYY TZR' | 'HH24:MI:SS.FF DD/MM/YYYY TZR' | | ko_KR | 'YYYY.MM.DD' | 'HH24:MI:SS' | 'HH24:MI:SS YYYY.MM.DD' | 'HH24:MI:SS.FF YYYY.MM.DD' | 'HH24:MI:SS YYYY.MM.DD TZR' | 'HH24:MI:SS.FF YYYY.MM.DD TZR' | | tr_TR | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD.MM.YYYY TZR' | 'HH24:MI:SS.FF DD.MM.YYYY TZR' | | vi_VN | 'DD/MM/YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD/MM/YYYY' | 'HH24:MI:SS.FF DD/MM/YYYY' | 'HH24:MI:SS DD/MM/YYYY TZR' | 'HH24:MI:SS.FF DD/MM/YYYY TZR' | | zh_CN | 'YYYY-MM-DD' | 'HH24:MI:SS' | 'HH24:MI:SS YYYY-MM-DD' | 'HH24:MI:SS.FF YYYY-MM-DD' | 'HH24:MI:SS YYYY-MM-DD TZR' | 'HH24:MI:SS.FF YYYY-MM-DD TZR' | | ro_RO | 'DD.MM.YYYY' | 'HH24:MI:SS' | 'HH24:MI:SS DD.MM.YYYY' | 'HH24:MI:SS.FF DD.MM.YYYY' | 'HH24:MI:SS DD.MM.YYYY TZR' | 'HH24:MI:SS.FF DD.MM.YYYY TZR' | **Date/time format 1** | Format element | Description | |----------------------|---------------------------------------------------------------------------| | **CC** | Century | | **YYYY** , **YY** | Year with 4 numbers, Year with 2 numbers | | **Q** | Quarter (1, 2, 3, 4; January - March = 1) | | **MM** | Month (01-12; January = 01) *Note: MI represents the minute of hour.* | | **MONTH** | Month in characters | | **MON** | Abbreviated month name | | **DD** | Day (1 - 31) | | **DAY** | Day of the week in characters | | **DY** | Abbreviated day of the week | | **D** or **d** | Day of the week in numbers (1 - 7) | | **AM** or **PM** | AM/PM | | **A.M.** or **P.M.** | AM/PM with periods | | **HH** or **HH12** | Hour (1 -12) | | **HH24** | Hour (0 - 23) | | **MI** | Minute (0 - 59) | | **SS** | Second (0 - 59) | | **FF** | Millisecond (0-999) | | \- / , . ; : "text" | Punctuation and quotation marks are represented as they are in the result | | **TZD** | Daylight saving information. e.g. KST, KT, EET | | **TZH** | Timezone hour offset. e.g. +09, -09 | | **TZM** | Timezone minute offset. e.g. +00, +30 | > **Note:** > TZR, TZD, TZH, TZM can be used only in timezone types. > **Note:** > **A format to specify a number after "TZD"** > > A number can be added after "TZD". This format is from TZD2 to TZD11; When you use a general character as a separator of a string, this format can be used. > > > ```sql > > SELECT STR_TO_DATE('09:30:17 20140307XEESTXEurope/Bucharest','%h:%i:%s %Y%d%mX%TZD4X%TZR'); > > ``` > > > > ```text > > 09:30:17.000 AM 07/03/2014 Europe/Bucharest EEST > > ``` > > > > When you use a general character, 'X', as a separator to separate each value, TZD value's string length is variable; therefore, it is confused to separate TZD value and a separator. In this case, TZD values' length should be specified. **Example of date_lang_string_literal** | **Format element** | **date_lang_string_literal** | | |--------------------|------------------------------|-------------| | | **'en_US'** | **'ko_KR'** | | **MONTH** | JANUARY | 1월 | | **MON** | JAN | 1 | | **DAY** | MONDAY | 월요일 | | **DY** | MON | 월 | | **Month** | January | 1월 | | **Mon** | Jan | 1 | | **Day** | Monday | 월요일 | | **Dy** | Mon | 월 | | **month** | january | 1월 | | **mon** | jan | 1 | | **day** | monday | 월요일 | | **Dy** | mon | 월 | | **AM** | AM | 오전 | | **Am** | Am | 오전 | | **am** | am | 오전 | | **A.M.** | A.M. | 오후 | | **A.m.** | A.m. | 오전 | | **a.m.** | a.m. | 오전 | | **PM** | PM | 오후 | | **Pm** | Pm | 오후 | | **pm** | pm | 오후 | | **P.M.** | P.M. | 오후 | | **P.m.** | P.m. | 오후 | | **p.m.** | p.m. | 오후 | **Example of format digits of return value** | Format element | en_US digits | ko_KR digits | |---|---|---| | **MONTH(Month, month)** | 9 | 4 | | **MON(Mon, mon)** | 3 | 2 | | **DAY(Day, day)** | 9 | 6 | | **DY(Dy, dy)** | 3 | 2 | | **HH12, HH24** | 2 | 2 | | "text" | The length of the text | The length of the text | | Other formats | Same as the length of the format | Same as the length of the format | Formatting order dates: ```sql SELECT id, TO_CHAR(order_date, 'DD, DY, MON, YYYY') AS d1, TO_CHAR(order_date, 'Day, DD Month YYYY') AS d2 FROM orders WHERE id < 3 ORDER BY id; ``` | id | d1 | d2 | |---|---|---| | 0 | 07, SUN, NOV, 2021 | Sunday , 07 November 2021 | | 1 | 19, SUN, OCT, 2025 | Sunday , 19 October 2025 | | 2 | 05, MON, SEP, 2022 | Monday , 05 September 2022 | Day and month names are padded to the length of the longest name. A **DATETIME** value, the date since when a brand has manufactured a product: ```sql SELECT TO_CHAR(m.since, 'HH12:MI:SS:FF pm, YYYY-MM-DD-DAY') AS s1, TO_CHAR(m.since, 'HH24:MI, DD, MONTH, YYYY') AS s2 FROM MATCH (b:brand)-[m:manufactures]->(p:product) WHERE p.id = 1618; ``` | s1 | s2 | |---|---| | 06:22:04:000 am, 2013-02-28-THURSDAY | 06:22, 28, FEBRUARY , 2013 | ```sql SELECT TO_CHAR(TIMESTAMP'2009-10-04 22:23:00', 'Day Month yyyy'); ``` | TO_CHAR(TIMESTAMP'2009-10-04 22:23:00', 'Day Month yyyy') | |---| | Sunday October 2009 | The third argument selects the language of the names: ```sql SELECT TO_CHAR(order_date, 'Day Month YYYY', 'tr_TR') AS tr, TO_CHAR(order_date, 'Day Month YYYY') AS en FROM orders WHERE id = 0; ``` | tr | en | |---|---| | Pazar Kasım 2021 | Sunday November 2021 | > **Note:** > - The language can be set with the **intl_date_lang** parameter or with the third argument of **TO_CHAR**. Only languages whose locale is available in the database can be used; the examples on this page use `tr_TR` (Turkish). Asking for an unavailable language is a syntax error. > > - If the first argument is zerodate and the second argument has a literal like 'Month', 'Day', then TO_CHAR function returns NULL. > > ```sql > SELECT TO_CHAR(timestamp '0000-00-00 00:00:00', 'Month Day YYYY'); > ``` > > | TO_CHAR(timestamp '0000-00-00 00:00:00', 'Month Day YYYY') | > |---| > | NULL | The following is an example to output date/time type with timezone in TO_CHAR function. If you don't define a format, it outputs as the following format ```sql SELECT TO_CHAR(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST'); ``` | TO_CHAR(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST') | |---| | 2001-10-11 02:03:04.000 Europe/Bucharest EEST | If you define a format, it outputs as the defined format. ```sql SELECT TO_CHAR(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST', 'MM/DD/YYYY HH24:MI TZR TZD TZH TZM'); ``` | TO_CHAR(datetimetz'2001-10-11 02:03:04 AM Europe/Bucharest EEST', 'MM/DD/YYYY HH24:MI TZR TZD TZH TZM') | |---| | 10/11/2001 02:03 Europe/Bucharest EEST +03 00 | ## TO_CHAR(number) ```sql TO_CHAR(number[, format[, number_lang_string_literal ] ]) ``` The **TO_CHAR** function converts a numeric data type to a character string according to [Number format](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-number-format) and returns it. The type of the return value is **VARCHAR** . **Parameters** - `number`: Specifies an expression that returns numeric data type string. If the input value is **NULL**, **NULL** is returned. If the input value is character type, the character itself is returned. - `format`: Specifies a format of return value. If format is not specified, all significant figures are returned as character string by default. If the value is **NULL**, **NULL** is returned. - `number_lang_string_literal`: Specifies the language to be applied to the input value. **Return type:** STRING If *format* argument is specified, *number* is converted into a character string according to a specified language. At this time, the language is defined by the *number_lang_string_literal* argument. If *number_lang_string_literal* is omitted, the language specified by **intl_number_lang** system parameter is applied; if **intl_number_lang** is not set, the language specified when creating DB is applied. For example, if the language is one of the European languages, such as "de_DE" or "fr_FR", "." is printed out as a thousands separator and "," is printed out as a decimal point. If the *format* argument does not correspond to the given string, the function returns an error. If *format* argument is omitted, *number* is converted into a character string according to the default format of a specified language (see the table [Default output of number for each language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-number-format)). **Number format** | Format element | Example | Description | |---|---|---| | **9** | 9999 | The number of 9's represents the number of significant figures to be returned. If the number of significant figures specified in the format is not sufficient, only the decimal part is rounded. If it is less than the number of digits in an integer, # is outputted. If the number of significant figures specified in the format is sufficient, the part preceding the integer part is filled with space characters and the decimal part is filled with 0. | | **0** | 0999 | If the number of significant figures specified in the format is sufficient, the part preceding the integer part is filled with 0, not space characters before the value is returned. | | **S** | S9999 | Outputs the negative/positive sign in the specified position. These signs can be used only at the beginning of character string. | | **C** | C9999 | Returns the ISO currency code at the specified position. | | **,** (comma) | 9,999 | Returns a comma (",") at the specified position. Multiple commas are allowed in the format. | | **.** (decimal point) | 9.999 | Returns a decimal point (".") at the specified position, separating the integer part from the fractional part. Only one decimal point is allowed in the format. See [Default output of number for each language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-number-format). | | **EEEE** | 9.99EEEE | Returns a scientific notation number. | **Default output of number for each language** | Language | Locale | Digit grouping symbol | Decimal symbol | Example | |---|---|---|---|---| | English | en_US | ,(comma) | .(period) | 123,456,789.012 | | Korean | ko_KR | ,(comma) | .(period) | 123,456,789.012 | | Turkish | tr_TR | .(period) | ,(comma) | 123.456.789,012 | The results below are shown in quotes, because number formats pad the result with leading spaces. With the default number language (`en_US`): ```sql SELECT TO_CHAR(12345, 'S999999'), TO_CHAR(12345, 'S099999'), TO_CHAR(1234567, '9,999,999,999'), TO_CHAR(1234567, '9.999.999.999'); ``` ```text ' +12345' '+012345' ' 1,234,567' '#############' ``` A format that is too short for the number, or that uses the wrong separators for the language, produces `#` characters. ```sql SELECT TO_CHAR(123.4567, '99'), TO_CHAR(123.4567, '999.99999'), TO_CHAR(123.4567, '99999.999'), TO_CHAR(1.234567, '99.999EEEE'); ``` ```text '##' '123.45670' ' 123.457' '1.235E+00' ``` With the Turkish number format (`tr_TR`), "." groups thousands and "," is the decimal point. The language can be given as the third argument, or set for the session with **intl_number_lang**: ```sql SELECT TO_CHAR(1234567, '9.999.999.999', 'tr_TR'), TO_CHAR(123.4567, '999,99999', 'tr_TR'), TO_CHAR(1.234567, '99,999EEEE', 'tr_TR'); ``` ```text ' 1.234.567' '123,45670' '1,235E+00' ``` ```sql SET SYSTEM PARAMETERS 'intl_number_lang="tr_TR"'; SELECT TO_CHAR(123.4567); ``` ```text '123,4567' ``` ## TO_DATE ```sql TO_DATE(string [,format [,date_lang_string_literal]]) ``` The **TO_DATE** function interprets a character string based on the date format given as an argument, converts it to a **DATE** type value, and returns it. For the format, see [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). **Parameters** - `string`: A character string - `format`: Specifies a format of return value to be converted as **DATE** type. See [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). If the value is **NULL**, **NULL** is returned. - `date_lang_string_literal`: Specifies the language for the input value to be applied. **Return type:** DATE When the *format* argument is specified, the *string* is interpreted according to the specified language. At this time, the language is set by *date_lang_string_literal* argument. If *date_lang_string_literal* argument is not set, the language is specified by the **intl_date_lang** system parameter; if the value of **intl_date_lang** is not set, the language is applied by the language specified when creating DB. For example, when a language is "de_DE" and *string* is "12.mai.2012", and *format* is "DD.mon.YYYY", it is interpreted as May 12th, 2012.When the *format* parameter specified does not correspond to the given *string*, an error is returned. When the *format* argument is omitted, *string* is interpreted as the CoraDB default format (refer to [Recommended format for strings in date/time type](https://www.coradb.ai/manual/sql/datatype_datetime.html#recommended-format-for-strings-in-datetime-type)) and if it fails, *string* is interpreted as the language format (see the table [Default output format of language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-datetime-format) in the [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char)) by **intl_date_lang**. If the value of **intl_date_lang** is not set, the language is applied by the language specified when creating DB. For example, when a language is "de_DE", the acceptable strings for **DATE** type are "MM/DD/YYYY", CoraDB default format and "DD.MM.YYYY", "de_DE" default format. The following example shows the query executed by the locale specified when creating DB to "en_US.utf8". ```sql --selecting a date type value casted from a string in the specified format SELECT TO_DATE('12/25/2008'); ``` | TO_DATE('12/25/2008') | |---| | 2008-12-25 | ```sql SELECT TO_DATE('25/12/2008', 'DD/MM/YYYY'); ``` | TO_DATE('25/12/2008', 'DD/MM/YYYY') | |---| | 2008-12-25 | ```sql SELECT TO_DATE('081225', 'YYMMDD'); ``` | TO_DATE('081225', 'YYMMDD') | |---| | 2008-12-25 | ```sql SELECT TO_DATE('2008-12-25', 'YYYY-MM-DD'); ``` | TO_DATE('2008-12-25', 'YYYY-MM-DD') | |---| | 2008-12-25 | With **intl_date_lang** set to `tr_TR`, the Turkish default format `DD.MM.YYYY` is accepted. The third argument gives the language for month names: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT TO_DATE('25.12.2012'); SELECT TO_DATE('12/EKM/2012', 'DD/MON/YYYY', 'tr_TR'); ``` ```text 12/25/2012 10/12/2012 ``` ## TO_DATETIME ```sql TO_DATETIME (string [,format [,date_lang_string_literal]]) ``` The **TO_DATETIME** function interprets a character string based on the date-time format given as an argument, converts it to a **DATETIME** type value, and returns it. For the format, see [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). **Parameters** - `string`: A character string - `format`: Specifies a format of return value to be converted as **DATETIME** type. See the table, [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). If the value is **NULL**, **NULL** is returned. - `date_lang_string_literal`: Specifies the language for the input value to be applied. **Return type:** DATETIME When the *format* argument is specified, the *string* is interpreted according to the specified language. For example, when a language is "de_DE" and *string* is "12/mai/2012 12:10:00 Nachm." and *format* is "DD/MON/YYYY HH:MI:SS AM", it is interpreted as May 12th, 2012 12:10:00 PM. At this time, the language is set by *date_lang_string_literal* argument. If *date_lang_string_literal* argument is not set, the language is specified by the **intl_date_lang** system parameter; if the value of **intl_date_lang** is not set, the language is specified by the language specified when creating DB. When the *format* parameter specified does not correspond to the given *string*, an error is returned. When the *format* argument is omitted, *string* is interpreted as the CoraDB default format (refer to [Recommended format for strings in date/time type](https://www.coradb.ai/manual/sql/datatype_datetime.html#recommended-format-for-strings-in-datetime-type)) and if it fails, *string* is interpreted as the language format (see the table [Default output format of language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-datetime-format) in the [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char)) by **intl_date_lang**. If the value of **intl_date_lang** is not set, the language is applied by the language specified when creating DB. For example, when a language is "de_DE", the acceptable strings for **DATETIME** type are "HH:MI:SS.FF AM MM/DD/YYYY", CoraDB default format and "HH24:MI:SS.FF DD.MM.YYYY", "de_DE" default format. The following examples run in a database created with the en_US locale. ```sql --selecting a datetime type value casted from a string in the specified format SELECT TO_DATETIME('13:10:30 12/25/2008'); ``` | TO_DATETIME('13:10:30 12/25/2008') | |---| | 2008-12-25 13:10:30.000 | ```sql SELECT TO_DATETIME('08-Dec-25 13:10:30.999', 'YY-Mon-DD HH24:MI:SS.FF'); ``` | TO_DATETIME('08-Dec-25 13:10:30.999', 'YY-Mon-DD HH24:MI:SS.FF') | |---| | 2008-12-25 13:10:30.999 | ```sql SELECT TO_DATETIME('DATE: 12-25-2008 TIME: 13:10:30.999', '"DATE:" MM-DD-YYYY "TIME:" HH24:MI:SS.FF'); ``` | TO_DATETIME('DATE: 12-25-2008 TIME: 13:10:30.999', '"DATE:" MM-DD-YYYY "TIME:" HH24:MI:SS.FF') | |---| | 2008-12-25 13:10:30.999 | With **intl_date_lang** set to `tr_TR`: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT TO_DATETIME('13:10:30.999 25.12.2012'); SELECT TO_DATETIME('12/EKM/2012 10:23:00 PM', 'DD/MON/YYYY HH:MI:SS AM', 'tr_TR'); ``` ```text 01:10:30.999 PM 12/25/2012 10:23:00.000 PM 10/12/2012 ``` ## TO_DATETIME_TZ ```sql TO_DATETIME_TZ (string [,format [,date_lang_string_literal]]) ``` **TO_DATETIME_TZ** function is the same as [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime) function except that this function can include a timezone information on this input string. **Return type:** DATETIMETZ ```sql SELECT TO_DATETIME_TZ('13:10:30 Asia/Seoul 12/25/2008', 'HH24:MI:SS TZR MM/DD/YYYY'); ``` | TO_DATETIME_TZ('13:10:30 Asia/Seoul 12/25/2008', 'HH24:MI:SS TZR MM/DD/YYYY') | |---| | 2008-12-25 13:10:30.000 Asia/Seoul KST | ## TO_NUMBER ```sql TO_NUMBER(string [, format ]) ``` The **TO_NUMBER** function interprets a character string based on the number format given as an argument, converts it to a **NUMERIC** type value, and returns it. **Parameters** - `string`: Specifies an expression that returns character string. If the value is **NULL**, **NULL** is returned. - `format`: Specifies a format of return value to be converted as **NUMBER** type. See [Number format](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-number-format). If it is omitted, NUMERIC(38,0) value is returned. **Return type:** NUMERIC When the *format* argument is assigned, the string is interpreted according to the specified language. At this time, the language is specified by the **intl_number_lang** system parameter. If the value of **intl_number_lang** is not set, the language specified when creating DB is applied. For example, when the language is one of the European languages, such as "de_DE" and "fr_FR", "." is interpreted as the cipher identifier and "," as the decimal point symbol. When the format parameter specified does not correspond to the given string, an error is returned. If the *format* argument is omitted, string is interpreted according to the default output format set by **intl_number_lang** (see [Default output of number for each language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-number-format)). When the **intl_number_lang** is not set, the language specified when creating DB is applied. The following example shows execution of the database by setting the value of system parameter **intl_number_lang** as "en_US". ```sql SET SYSTEM PARAMETERS 'intl_number_lang="en_US"'; --selecting a number casted from a string in the specified format SELECT TO_NUMBER('-1234'); ``` ```text -1234 ``` ```sql SELECT TO_NUMBER('12345','999999'); ``` | TO_NUMBER('12345','999999') | |---| | 12345 | ```sql SELECT TO_NUMBER('12,345.67','99,999.999'); ``` | TO_NUMBER('12,345.67','99,999.999') | |---| | 12345.670 | ```sql SELECT TO_NUMBER('12345.67','99999.999'); ``` | TO_NUMBER('12345.67','99999.999') | |---| | 12345.670 | With **intl_number_lang** set to `tr_TR`, "." groups thousands and "," is the decimal point: ```sql SET SYSTEM PARAMETERS 'intl_number_lang="tr_TR"'; SELECT TO_NUMBER('12.345,67', '99.999,999'); ``` ```text 12345.670 ``` ## TO_TIME ```sql TO_TIME (string [,format [,date_lang_string_literal]]) ``` The **TO_TIME** function interprets a character string based on the time format given as an argument, converts it to a **TIME** type value, and returns it. For the format, see [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). **Parameters** - `string`: Specifies an expression that returns character string. If the value is **NULL**, **NULL** is returned. - `format`: Specifies a format of return value to be converted as **TIME** type. See [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). If the value is **NULL**, **NULL** is returned. - `date_lang_string_literal`: Specifies the language for the input value to be applied. **Return type:** TIME When the *format* argument is specified, the *string* is interpreted according to the specified language. At this time, the language is set by *date_lang_string_literal* argument. If *date_lang_string_literal* argument is not set, the language is specified by the **intl_date_lang** system parameter; if the value of **intl_date_lang** is not set, the language specified when creating DB is applied. When the *format* parameter does not correspond to the given *string*, an error is returned. For example, when a language is "de_DE" and *string* is "10:23:00 Nachm.", and *format* is "HH/MI/SS/AM, it is interpreted as 10:23:00 PM. When the *format* argument is omitted, *string* is interpreted as the CoraDB default format (refer to [Recommended format for strings in date/time type](https://www.coradb.ai/manual/sql/datatype_datetime.html#recommended-format-for-strings-in-datetime-type)) and if it fails, *string* is interpreted as the language format (see the table [Default output format of language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-datetime-format) in the [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char)) by **intl_date_lang**. If the value of **intl_date_lang** is not set, the language is applied by the language specified when creating DB. For example, when a language is "de_DE", the acceptable strings for **TIME** type are "HH:MI:SS AM", CoraDB default format and "HH24:MI:SS", "de_DE" default format. The following example shows execution of the database by setting the value of system parameter **intl_date_lang** as "en_US". ```sql SET SYSTEM PARAMETERS 'intl_date_lang="en_US"'; --selecting a time type value casted from a string in the specified format SELECT TO_TIME ('13:10:30'); ``` ```text 01:10:30 PM ``` ```sql SELECT TO_TIME('HOUR: 13 MINUTE: 10 SECOND: 30', '"HOUR:" HH24 "MINUTE:" MI "SECOND:" SS'); ``` | TO_TIME('HOUR: 13 MINUTE: 10 SECOND: 30', '"HOUR:" HH24 "MINUTE:" MI "SECOND:" SS') | |---| | 13:10:30 | ```sql SELECT TO_TIME ('13:10:30', 'HH24:MI:SS'); ``` | TO_TIME ('13:10:30', 'HH24:MI:SS') | |---| | 13:10:30 | ```sql SELECT TO_TIME ('13:10:30', 'HH12:MI:SS'); ``` ```text ERROR: Conversion error in date format. ``` With **intl_date_lang** set to `tr_TR`, the Turkish default format `HH24:MI:SS` is accepted: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT TO_TIME('13:10:30'); ``` ```text 01:10:30 PM ``` ## TO_TIMESTAMP ```sql TO_TIMESTAMP(string [, format [,date_lang_string_literal]]) ``` The **TO_TIMESTAMP** function interprets a character string based on the time format given as an argument, converts it to a **TIMESTAMP** type value, and returns it. For the format, see [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). **Parameters** - `string`: Specifies an expression that returns character string. If the value is **NULL**, **NULL** is returned. - `format`: Specifies a format of return value to be converted as **TIMESTAMP** type. See [Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1). If the value is **NULL**, **NULL** is returned. - `date_lang_string_literal`: Specifies the language for the input value to be applied. **Return type:** TIMESTAMP When the *format* argument is specified, the *string* is interpreted according to the specified language. The language is set by *date_lang_string_literal* argument. If *date_lang_string_literal* argument is not set, the language is specified by the **intl_date_lang** system parameter; if the value of **intl_date_lang** is not set, the language specified when creating DB is applied. For example, when a language is "de_DE" and *string* is "12/mai/2012 12:10:00 Nachm.", and *format* is "DD/MON/YYYY HH:MI:SS AM", it is interpreted as May 12th, 2012, 12:10:00 AM. When the *format* parameter specified does not correspond to the given string, an error is returned. When the *format* argument is omitted, *string* is interpreted as the CoraDB default format(refer to [Recommended format for strings in date/time type](https://www.coradb.ai/manual/sql/datatype_datetime.html#recommended-format-for-strings-in-datetime-type)) and if it fails, *string* is interpreted as the language format (see the table [Default output format of language](https://www.coradb.ai/manual/sql/function/typecast_fn.html#tochar-default-datetime-format) in the [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char)) by **intl_date_lang**. If the value of **intl_date_lang** is not set, the language is applied by the language specified when creating DB. For example, when a language is "de_DE", the acceptable strings for **TIMESTAMP** type are "HH:MI:SS AM MM/DD/YYYY", CoraDB default format and "HH24:MI:SS DD.MM.YYYY", "de_DE" default format. The following example shows execution of the database by setting the value of system parameter **intl_date_lang** as "en_US". ```sql SET SYSTEM PARAMETERS 'intl_date_lang="en_US"'; --selecting a timestamp type value casted from a string in the specified format SELECT TO_TIMESTAMP('13:10:30 12/25/2008'); ``` ```text 01:10:30 PM 12/25/2008 ``` ```sql SELECT TO_TIMESTAMP('08-Dec-25 13:10:30', 'YY-Mon-DD HH24:MI:SS'); ``` | TO_TIMESTAMP('08-Dec-25 13:10:30', 'YY-Mon-DD HH24:MI:SS') | |---| | 2008-12-25 13:10:30 | ```sql SELECT TO_TIMESTAMP('YEAR: 2008 DATE: 12-25 TIME: 13:10:30', '"YEAR:" YYYY "DATE:" MM-DD "TIME:" HH24:MI:SS'); ``` | TO_TIMESTAMP('YEAR: 2008 DATE: 12-25 TIME: 13:10:30', '"YEAR:" YYYY "DATE:" MM-DD "TIME:" HH24:MI:SS') | |---| | 2008-12-25 13:10:30 | With **intl_date_lang** set to `tr_TR`, the Turkish default format `HH24:MI:SS DD.MM.YYYY` is accepted: ```sql SET SYSTEM PARAMETERS 'intl_date_lang="tr_TR"'; SELECT TO_TIMESTAMP('13:10:30 25.12.2008'); ``` ```text 01:10:30 PM 12/25/2008 ``` If the string contains only a time, the date part is the first day of the current month: `TO_TIMESTAMP('10:23:00 PM', 'HH12:MI:SS AM')` run in November 2026 returns `10:23:00 PM 11/01/2026`. ## TO_TIMESTAMP_TZ ```sql TO_TIMESTAMP_TZ(string [, format [,date_lang_string_literal]]) **TO_TIMESTAMP_TZ** function is the same as `TO_TIMESTAMP <#to_timestamp>`__ function except that this function can include a timezone information on this input string. :rtype: TIMESTAMPTZ ``` ```sql SELECT TO_TIMESTAMP_TZ('13:10:30 Asia/Seoul 12/25/2008', 'HH24:MI:SS TZR MM/DD/YYYY'); ``` | TO_TIMESTAMP_TZ('13:10:30 Asia/Seoul 12/25/2008', 'HH24:MI:SS TZR MM/DD/YYYY') | |---| | 2008-12-25 13:10:30 Asia/Seoul KST | --- # Relational and graph in one query Source: https://www.coradb.ai/manual/sql/hybrid.html CoraDB is one database engine for relational and graph data, not two engines side by side. A graph is stored in **vertex tables** (nodes) and **edge tables** (relationships), and these are tables like any other. That means: - Vertex and edge tables can be read and changed with ordinary SQL; - A `MATCH` graph pattern is just another source in the `FROM` clause of a `SELECT`, so one statement can traverse the graph and join relational tables, then filter, group, sort and aggregate the result; - Inserts and updates of rows, nodes and edges take part in the same transaction. The examples below run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html): `orders` and `order_items` are relational tables, `customer`, `product`, `category`, `brand` and `city` are vertex tables, and `likes`, `follows`, `part_of` and `resides_in` are edge tables. The relational tables refer to vertices through ordinary foreign keys (`orders.customer_id` → `customer.id`, `order_items.product_id` → `product.id`). ## Vertex tables are tables A vertex table can be queried without any graph syntax. The products that cost more than 100: ```sql SELECT name, unit_price, units_in_stock FROM product WHERE unit_price > 100 ORDER BY unit_price DESC LIMIT 3; ``` | name | unit_price | units_in_stock | |---|---|---| | Côte de Blaye | 263.50 | 17 | | Thüringer Rostbratwurst | 123.79 | 0 | It also joins relational tables like any table. The customers with the most orders (`customer` is a vertex table, `orders` a relational table): ```sql SELECT c.company_name AS customer, COUNT(*) AS orders FROM orders o JOIN customer c ON c.id = o.customer_id GROUP BY c.id, c.company_name ORDER BY orders DESC, customer LIMIT 3; ``` | customer | orders | |---|---| | Mayer, Carroll and Owens | 40 | | Young and Sons | 40 | | Kelly Ltd | 39 | ## A graph pattern next to tables in FROM A `MATCH` pattern can be listed in the `FROM` clause together with relational tables and joined to them in `WHERE`. The best-selling categories: the graph says which category a product belongs to (`part_of` edge), the relational `order_items` table says how many units were sold: ```sql SELECT cat.name AS category, SUM(oi.quantity) AS units_sold FROM MATCH (p:product)-[:part_of]->(cat:category), order_items oi WHERE oi.product_id = p.id GROUP BY cat.name ORDER BY units_sold DESC LIMIT 5; ``` | category | units_sold | |---|---| | Shorts | 6528 | | Tees | 6232 | | Erin Recommends | 5843 | | Hoodies & Sweatshirts | 5779 | | Jackets | 5394 | ## JOIN … ON with a graph pattern The pattern can also be the right side of a `JOIN`. The cities with the most orders: `orders` is joined to the customers of the `resides_in` pattern, which gives each customer's city: ```sql SELECT ci.name AS city, COUNT(*) AS orders, SUM(o.shipping_cost) AS shipping FROM orders o JOIN MATCH (c:customer)-[:resides_in]->(ci:city) ON c.id = o.customer_id GROUP BY ci.name ORDER BY orders DESC LIMIT 5; ``` | city | orders | shipping | |---|---|---| | Portland | 113 | 1924.59 | | San Francisco | 103 | 1804.23 | | Elgin | 102 | 1760.51 | | London | 102 | 1576.63 | | Kirkland | 101 | 1797.71 | ## Graph signals and purchases together Edges often record behaviour (a customer *likes* a product, *follows* a brand) while relational tables record transactions. One query can compare them. The customers who bought the most of the products they like: ```sql SELECT c.company_name AS customer, COUNT(DISTINCT p.id) AS liked_and_bought FROM MATCH (c:customer)-[:likes]->(p:product), orders o, order_items oi WHERE o.customer_id = c.id AND oi.order_id = o.id AND oi.product_id = p.id GROUP BY c.company_name ORDER BY liked_and_bought DESC, customer LIMIT 3; ``` | customer | liked_and_bought | |---|---| | Harris, Hernandez and Hancock | 3 | | Moore-Anderson | 3 | | Simpson-Atkins | 3 | ## Relational results as input for a graph query A common table expression can compute a relational result first and feed it to a pattern. The Nike followers who order the most: ```sql WITH spend AS ( SELECT customer_id, COUNT(*) AS orders, SUM(shipping_cost) AS shipping FROM orders GROUP BY customer_id ) SELECT c.company_name AS customer, s.orders, s.shipping FROM MATCH (c:customer)-[:follows]->(b:brand), spend s WHERE b.name = 'Nike' AND s.customer_id = c.id ORDER BY s.orders DESC, customer LIMIT 5; ``` | customer | orders | shipping | |---|---|---| | Mayer, Carroll and Owens | 40 | 653.14 | | Kelly Ltd | 39 | 638.48 | | Smith-Williams | 25 | 442.54 | | Murphy, Nelson and Donovan | 20 | 292.04 | | Murray Ltd | 20 | 383.64 | ## Rows, nodes and edges in one transaction Changes to relational tables, vertex tables and edge tables are ordinary DML in the same transaction: they are committed or rolled back together. An order, its order line and a new *likes* edge: ```sql INSERT INTO orders (id, customer_id, order_date, shipping_cost, ship_address) VALUES (90001, 1, DATE '2026-11-19', 4.90, '12 Main Street, Portland'); INSERT INTO order_items (order_id, product_id, quantity, discount_pct) VALUES (90001, 5, 1, 0); INSERT EDGE FROM (SELECT c FROM customer c WHERE c.id = 1) TO (SELECT p FROM product p WHERE p.id = 5) INTO likes VALUES (DATETIME '2026-11-19 10:00:00'); COMMIT; ``` Before the `COMMIT`, the same session already sees all three changes, in one query: ```sql SELECT c.company_name AS customer, p.name AS product, l.since, oi.quantity FROM MATCH (c:customer)-[l:likes]->(p:product), order_items oi WHERE c.id = 1 AND p.id = 5 AND oi.order_id = 90001 AND oi.product_id = p.id; ``` | customer | product | l.since | quantity | |---|---|---|---| | Woodward, Brown and Morton | Chef Antons Gumbo Mix | 2026-11-19 10:00:00.000 | 1 | A `ROLLBACK` instead of the `COMMIT` removes the order, the order line and the edge together. ## See also - [SELECT](https://www.coradb.ai/manual/sql/query/select.html): the full syntax of the statement that hosts `MATCH`. - [MATCH clause (graph patterns)](https://www.coradb.ai/manual/graph/match.html): node and edge patterns, directions, variable-length and shortest paths, path variables. - [Graph functions](https://www.coradb.ai/manual/sql/function/graph_fn.html): `NODES`, `RELATIONSHIPS`, `LABEL` and the JSON graph functions. - [Graph types](https://www.coradb.ai/manual/sql/datatype_graph.html) and [CREATE VERTEX / EDGE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html). - [Tutorial: tables and graphs in one database](https://www.coradb.ai/manual/graph/graph_getting_started.html). --- # Globalization: charsets, collations and locales Source: https://www.coradb.ai/manual/sql/i18n.html Globalization covers *internationalization* (supporting many languages and regions) and *localization* (adapting to the language and conventions of one region). In CoraDB it is controlled by three settings: | Setting | Decides | Set by | |---|---|---| | **Charset** (character set) | How characters are stored as bytes: ISO-8859-1, UTF-8 or EUC-KR | The database locale; per column, literal or expression with **CHARSET** | | **Collation** | How strings are compared and sorted, and which casing rules apply | The database locale; per column, table or expression with **COLLATE** | | **Locale** | Language and region: default charset and collation, month and day names, number format | `coradb createdb `, for example `en_US.utf8` | | Topic | Page | |---|---| | Concepts, available collations, configuration guide | This page | | Charset and collation of columns, tables, literals and expressions | [Charset and collation rules](https://www.coradb.ai/manual/sql/i18n_collation.html) | | Installing locales and custom collations (LDML) | [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html) | | Time zone parameters and the time zone library | [Time zone setting](https://www.coradb.ai/manual/sql/i18n_timezone.html) | The e-commerce sample database uses the UTF-8 charset with the binary collation `utf8_bin`: ```sql SELECT CHARSET('a') AS cs, COLLATION('a') AS co; ``` | cs | co | |---|---| | utf8 | utf8_bin | ## Character data Strings are stored in **CHAR**, **VARCHAR** (**STRING**) and **ENUM** columns, each with a charset and a collation. The **charset** controls how characters are stored as bytes. CoraDB supports ISO-8859-1, UTF-8 and EUC-KR. UTF-8 covers Unicode code points up to 10FFFF, encoded in one to four bytes. The character "Ç", for example, is one byte (C7) in ISO-8859-1 and two bytes (C3 87) in UTF-8, and does not exist in EUC-KR: ```sql SELECT HEX(_utf8'Ç') AS utf8_bytes, LENGTH(_utf8'Ç') AS chars, OCTET_LENGTH(_utf8'Ç') AS bytes; ``` | utf8_bytes | chars | bytes | |---|---|---| | C387 | 1 | 2 | The **collation** decides how strings compare: whether `'ABC'` and `'abc'` are equal (case-insensitive) or different (case-sensitive), how they sort, how **LIKE** matches, and the ranges of index scans. In CoraDB every collation belongs to one charset: `utf8_en_ci` and `iso88591_en_ci` are both case-insensitive, but for different charsets. A literal with a collation therefore also gets that collation's charset: `'a' COLLATE iso88591_en_ci` means `_iso88591'a' COLLATE iso88591_en_ci`. ```sql SELECT ('ABC' = 'abc') AS bin, ('ABC' COLLATE utf8_en_ci = 'abc') AS ci; ``` | bin | ci | |---|---| | 0 | 1 | **CHAR** values are padded to their length. The padding character is a space (ASCII 32, U+0020), except in EUC-KR, where it is the two-byte character A1 A1. ## Related terms - **Character set**: A group of encoded symbols (giving a specific number to a certain symbol) - **Collation**: A set of rules for comparison of characters in the character set and for sorting data - **Locale**: A set of parameters that defines any special variant preferences such as number format, calendar format (month and day in characters), date/time format, and collation depending on the operator's language and country. Locale defines the linguistic localization. Character set of locale defines how the month in characters and other data are encoded. A locale identifier consists of at least a language identifier and a region identifier, and it is expressed as language\[\_territory\]\[.codeset\] (For example, Australian English using UTF-8 encoding is written as en_AU.UTF-8). - **Unicode normalization**: The specification by the Unicode character encoding standard where some sequences of code points represent essentially the same character. When normalization is enabled, CoraDB uses Normalization Form C (NFC, composed) for input and Normalization Form D (NFD, decomposed) for output, but it does not apply canonical equivalence. For example, canonical equivalence is applied in general NFC rule so codepoint 212A (Kelvin K) is converted to codepoint 4B (ASCII code uppercase K). Since CoraDB does not perform the conversion by using the canonical equivalence rule to make normalization algorithm quicker and easier, it does not perform reverse-conversion, too. - **Canonical equivalence**: A basic equivalence between characters or sequences of characters, which cannot be visually distinguished when they are correctly rendered. For example, let's see 'Å' ('A' with an angstrom). 'Å' (Unicode U + 212B) and Latin 'A' (Unicode U + 00C5) have same A and different codepoints, however, the decomposed result is 'A' and U+030A, so it is canonical equivalence. - **Compatibility equivalence**: A weaker equivalence between characters or sequences of characters that represent the same abstract character. For example, let's see number '2' (Unicode U + 0032) and superscript '²'(Unicode U + 00B2). '²' is a different format of number '2', however, it is visually distinguished and has a different meaning, so it is not canonical equivalence. When normalizing '2²' with NFC, '2²' is maintained since it uses canonical equivalence. However, with NFKC, '²' is decomposed to '2' which is compatibility equivalence and then it can be recomposed to '22'. Unicode normalization of CoraDB does not apply the compatibility equivalence rule. For explanation on Unicode normalization, see [Unicode normalization](https://www.coradb.ai/manual/sql/i18n_collation.html#unicode-normalization). For more details, see . Normalization is off by default ([unicode_input_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_input_normalization) and [unicode_output_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_output_normalization) are `no`). ## Locale attributes Locale is defined by following attributes. - **Charset (codeset)**: How bytes are interpreted into single characters (Unicode codepoints) - **Collations**: Among all collations defined in locale of [LDML(UNICODE Locale Data Markup Language)](http://www.unicode.org/reports/tr35/) file, the last one is the default collation. Locale data may contain several collations. - **Alphabet (casing rules)**: One locale data may have up 2 alphabets, one for identifier and one for user data. One locale data can have two types of alphabets. - **Calendar**: Names of weekdays, months, day periods (AM/PM) - **Numbering settings**: Symbols for digit grouping - **Text conversion data**: For corasql conversion. Option. - **Unicode normalization data**: Data converted by normalizing several characters with the same shape into one based on a specified rule. After normalization, characters with the same shape will have the same code value even though the locale is different. Each locale can activate/deactivate the normalization functionality. > **Note:** > Generally, locale supports a variety of character sets. However, CoraDB locale supports both ISO and UTF-8 character sets for English and Korean. The other operator-defined locales using the LDML file support the UTF-8 character set only. ## Collation properties A collation is an assembly of information which defines an order for characters and strings. In CoraDB, collation has the following properties. - **Strength**: This is a measure of how "different" basic comparable items (characters) are. This affects selectivity. In LDML files, collation strength is configurable and has four levels. For example a Case insensitive collation should be set with level = "secondary" (2) or "primary" (1). - Whether it supports or not **expansions** and **contractions** Each column has a collation, so when applying [LOWER](https://www.coradb.ai/manual/sql/function/string_fn.html#fn-lower), [UPPER](https://www.coradb.ai/manual/sql/function/string_fn.html#fn-upper) functions the casing rules of locale which defines the collation's default language is used. Depending on collation properties some CoraDB optimizations may be disabled for some collations: - **LIKE** rewrite: is disabled for collations which maps several different character to the same weight (case insensitive collations for example) and for collations with expansions. - Covering index scan: disabled for collations which maps several different character to the same weight (see [Covering index](https://www.coradb.ai/manual/sql/tuning_index_opt.html#covering-index)). For more information, see [Collation settings impacting CoraDB features](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-settings-impacting-coradb-features) . ## Collation naming rules The collation name in CoraDB follows the conversion: ``` text ____... ``` - \: The full charset name as used by CoraDB. iso88591, utf8, euckr. - \: a region/language specific. The language code is expected as two characters; en, de, es, fr, it, ja, km, ko, tr, vi, zh, ro. "gen" if it does not address a specific language, but a more general sorting rule. - \\_\\_...: They have the following meaning. Most of them apply only to LDML collations. - ci: case insensitive In LDML, can be obtained using the settings: strength="secondary" caseLevel="off" caseFirst="off". - cs: case sensitive; By default all collations are case sensitive. In LDML, can be obtained using at least: strength="tertiary". - bin: it means that the sorting order under such collation is almost the same with the order of codepoints; If memory (byte) comparison is used, then almost the same result is obtained. Space character and EUC double-byte padding character are always sorted as zero in "bin" collation. No collations with such setting are currently configured in LDML (they are already available as built-in), but a similar one can be obtained using the maximum setting strength="quaternary" or strength="identical". - ai: accent insensitive; this means that 'Á' is sorted the same as 'A'. Due to particularities of the UCA based algorithms, an accent insensitive collation is also a case insensitive collation. In LDML, can be obtained using: strength="primary". - uca: this signals a UCA based collation; this is used only to differentiate such collations from similar built-in variants. All LDML collations are based on UCA, but in order to keep shorter names only two collations ( 'utf8_ko_cs_uca' , 'utf8_tr_cs_uca' ) have this description in their names, in order to differentiate them from 'utf8_ko_cs' and 'utf8_tr_cs' collations. - exp: this collations use a full-word matching/compare algorithm, contrary to the rest of collations which use character-by-character compare. This collation uses a more complex algorithm, with multiple passes which is much slower, but may prove useful for alphabetical sorts. In LDML, the [Expansion](https://www.coradb.ai/manual/sql/i18n_collation.html#expansion) needs to be explicit by adding CoraDBExpansions="use". - ab: accent backwards; it is particularity of French-Canadian sorting, where level 2 of UCA (used to store accents weights) is compared from end of string towards the beginning. This setting requires the [expansion](https://www.coradb.ai/manual/sql/i18n_collation.html#expansion) setting. The "backwards" setting allows for the following sorting: - Normal Accent Ordering: cote \< coté \< côte \< côté - Backward Accent Ordering: cote \< côte \< coté \< côté - cbm: contraction boundary match; it is a particularity of collations with [Expansion](https://www.coradb.ai/manual/sql/i18n_collation.html#expansion) and [Contraction](https://www.coradb.ai/manual/sql/i18n_collation.html#contraction) and refers to how it behaves at string matching when a [Contraction](https://www.coradb.ai/manual/sql/i18n_collation.html#contraction) is found. Suppose the collation has defined the [Contraction](https://www.coradb.ai/manual/sql/i18n_collation.html#contraction) "ch"; then normally, the pattern "bac" will not match the string"bachxxx" But when the collation is configured to allow "matching the characters starting a contraction", the above matching will return a positive. Only one collation is configured in this manner - 'utf8_ja_exp_cbm' - Japanese sorting requires a lot of contractions. The collation names are not dynamically generated. They are user defined (configured in LDML), and should reflect the settings of the collation. The name of collation influences the internal numeric id of the collation. For instance, in CoraDB only 256 collations are allowed, and the numeric IDs are assigned as: - 0 -31: built-in collations (for these collations the name and id are hard-coded) - 32 - 46: LDML collations having "gen" as "language" part - 47 - 255: the rest of LDML collations Only the nine built-in collations plus `binary` are available in a new installation. The LDML collations in the table below become available after you compile the locales: copy `coradb_locales.all.txt` in `$CORADB/conf` to `coradb_locales.txt` and run the `make_locale` script (`.sh` on Linux, `.bat` on Windows); see [Step 2: compiling locale](https://www.coradb.ai/manual/sql/i18n_locale.html#step-2-compiling-locale). To add newly compiled collations to an existing database, run `coradb synccolldb `; see [Synchronization of database collations with system collations](https://www.coradb.ai/manual/sql/i18n_locale.html#synchronization-of-database-collations-with-system-collations). With all locales compiled, CoraDB has the following collations. The collations of a database are listed by `SHOW COLLATION` or the `db_collation` catalog view; see [Viewing collation information](https://www.coradb.ai/manual/sql/i18n_collation.html#viewing-collation-information). ### CoraDB collation | Collation | Locale for casing | Character range | |-------------------|-----------------------------------------------------------------------|-------------------------------------------| | iso88591_bin | en_US - English | ASCII + ISO88591 (C0-FE, except D7, F7) | | iso88591_en_cs | en_US - English | ASCII + ISO88591 (C0-FE, except D7, F7) | | iso88591_en_ci | en_US - English | ASCII + ISO88591 (C0-FE, except D7, F7) | | utf8_bin | en_US - English | ASCII | | euckr_bin | ko_KR - Korean, same as en_US - English | ASCII | | utf8_en_cs | en_US - English | ASCII | | utf8_en_ci | en_US - English | ASCII | | utf8_tr_cs | tr_TR - Turkish | Turkish alphabet | | utf8_ko_cs | ko_KR - Korean, same as en_US - English | ASCII | | utf8_gen | de_DE - German, generic Unicode casing customized with German rules | All Unicode codepoints in range 0000-FFFF | | utf8_gen_ai_ci | de_DE - German, generic Unicode casing customized with German rules | All Unicode codepoints in range 0000-FFFF | | utf8_gen_ci | de_DE - German, generic Unicode casing customized with German rules | All Unicode codepoints in range 0000-FFFF | | utf8_de_exp_ai_ci | de_DE - German, generic Unicode casing customized with German rules | All Unicode codepoints in range 0000-FFFF | | utf8_de_exp | de_DE - German, generic Unicode casing customized with German rules | All Unicode codepoints in range 0000-FFFF | | utf8_ro_cs | ro_RO - Romanian, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_es_cs | es_ES - Spanish, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_fr_exp_ab | fr_FR - French, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_ja_exp | ja_JP - Japanese, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_ja_exp_cbm | ja_JP - Japanese, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_km_exp | km_KH - Cambodian, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_ko_cs_uca | ko_KR - Korean, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | utf8_tr_cs_uca | tr_TR - Turkish, generic Unicode casing customized with Turkish rules | All Unicode codepoints in range 0000-FFFF | | utf8_vi_cs | vi_VN - Vietnamese, same as generic Unicode casing | All Unicode codepoints in range 0000-FFFF | | binary | None (invariant to casing operations) | Any byte value (zero is nul-terminator) | The Turkish casing rules changes the casing for character i,I,ı,İ. The German casing rules changes the casing for ß. The nine collations iso88591_bin, iso88591_en_cs, iso88591_en_ci, utf8_bin, euckr_bin, utf8_en_cs, utf8_en_ci, utf8_tr_cs and utf8_ko_cs, and `binary`, are built in and available without running `make_locale`. If a collation is included in more than one locale (.ldml) file, the locale for casing (default locale of collation) is the locale in which it is first included. The order of loading is the locales order from $CORADB/conf/coradb_locales.txt. The above locale casing for collations utf8_gen, utf8_gen_ci, utf8_gen_ai_ci, assumes the default order (alphabetical) in coradb_locales.txt, so the default locale for all generic LDML collations is de_DE (German). ## Configuration guide for characters Database designers should take into account character data properties when designing the database structure. The following is the summarized guide when configuring aspects related to CoraDB character data. ### Locale - By default, en_US gives best performance. If you have a plan to use only English, this is recommended. - A **CHAR** column reserves the maximum bytes per character: 4 in UTF-8 and 3 in EUC-KR, so UTF-8 multiplies its storage by 4. - If user string literals have different charset and collation from system, query strings will grow as the string literals are decorated with them. - If localized (non-ASCII) characters will be used for identifiers, then use an .utf8 locale - Once established the UTF-8 charset for DB, it is best to use a LDML locale (this ensures that identifier names containing most Unicode characters are correctly cased) than a system locale. - Setting a locale affects also conversion functions(intl_date_lang, intl_number_lang). - When you set the locale during creating DB, there should be no concern on charset and collation of string-literals or user tables columns; all of them can be changed at run-time (with [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) in queries) or ALTER .. CHANGE for a permanent change. ### CHAR and VARCHAR - Generally, use VARCHAR if there are large variations in actual number of characters in user data. - CHAR type is fixed length type. Therefore, Even if you store only English character in CHAR type, it requires 4 bytes storage in UTF-8 and 3 bytes in EUC-KR. - The precision of columns refers to the number of characters (glyphs). - After choosing precision, charset and collation should be set according to most used scenarios. ### Choosing charset - Even if your text contains non-ASCII character, use utf8 or euckr charsets only if application requires character counting, inserting, replacing. - For CHAR data, the main concern should be storage requirement (4x or utf8, 3x for euckr). - For both CHAR and VARCHAR data, there is some overhead when inserting/updating data: counting the precision (number of characters) of each instance is more consuming for non-ISO charsets. - In queries, charset of expressions may be converted using [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) operator. ### Choosing collation - If no collation dependent operations are performed (string searching, sorting, comparisons, casing), then choose the bin collation for that charset or binary collation - Collation may be easily overridden using [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) operator, and [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier) if charset is unchanged between original charset of expression and the new collation. - Collation controls also the casing rules of strings - Collations with expansions are slower, but are more flexible and they perform whole-word sorting ### Normalization - If your client applications send text data to CoraDB in decomposed form, then configure **unicode_input_normalization** = yes, so that CoraDB re-composes it and handles it in composed form - If your client can handle data only in decomposed form, than set **unicode_output_normalization** = yes, so that CoraDB always sends in decomposed form. - If the client "knows" both forms, then leave **unicode_output_normalization** = no ### CAST vs COLLATE - When building statements, the [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) operator is more costly than [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier) (even more when charset conversion occurs). - [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier) does not add an additional execution operator; using [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier) should enhance execution speed over using [CAST](https://www.coradb.ai/manual/sql/function/typecast_fn.html#cast) operator. - [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier) can be used only when charset is not changed ## Remarks - Query plans printing: collation is not displayed in plans for results with late binding. - Only the Unicode code-points in range 0000-FFFF (Basic Multilingual Plan) are normalized. - Some locales use space character as separator for digit grouping (thousands, millions, ..). Space is allowed but not working properly in some cases of localized conversion from string to number. --- # Charset and collation of columns, tables and expressions Source: https://www.coradb.ai/manual/sql/i18n_collation.html Every string value in CoraDB has a charset and a collation. This page explains where they come from and how CoraDB chooses between them when values with different settings meet. For the concepts and the list of collations, see [Globalization](https://www.coradb.ai/manual/sql/i18n.html). ## Collation A collation defines how characters and strings are compared and sorted. The charset and collation of a value are determined as follows: | Value | Charset and collation | |---|---| | Column | Its **CHARSET** / **COLLATE** modifiers, otherwise those of its table, otherwise those of the database | | Table | Its **CHARSET** / **COLLATE** clauses, otherwise those of the database | | String literal | Its charset introducer or **COLLATE** modifier, otherwise those set by **SET NAMES**, otherwise those of the database | | Expression | Inferred from its arguments by [coercibility](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-coercibility) | The database charset comes from the locale given to `coradb createdb`; the database collation is always the *bin* collation of that charset (`utf8_bin` for a UTF-8 database such as the e-commerce sample). ## Charset and collation of column Charsets and collations apply to the string types **CHAR**, **VARCHAR** (**STRING**) and **ENUM**. ### Charset The supported charsets are: | Charset | Name in SQL | Notes | |---|---|---| | ISO-8859-1 | `iso88591` | One byte per character | | UTF-8 | `utf8` | One to four bytes per character, code points 0 to 10FFFF | | EUC-KR | `euckr` | For backward compatibility only; not recommended | | binary | `binary` | Raw bytes, no character semantics | ### String check Input strings are assumed to be in the database charset, unless **SET NAMES** or a charset introducer says otherwise (see [Charset and collation of string literals](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collation-of-string-literals)). CoraDB does not check by default that UTF-8 and EUC-KR input is correctly encoded; invalid input can lead to undefined behavior. Turn checking on with the system parameter [intl_check_input_string](https://www.coradb.ai/manual/admin/config_sql.html#intl_check_input_string) if your clients may send invalid data, and leave it off for better performance if they do not. ISO-8859-1 needs no check, because every byte is a valid character. ### Charset conversion When a modifier or collation inference requires it, values are converted from one charset to another. Conversion translates characters (transcoding) and is not reversible. A character that does not exist in the destination charset is replaced with `?`; this also applies when converting binary data. Bytes 80–A0, which are not valid ISO-8859-1 characters, become `?` when converted to UTF-8. | Source \ destination | binary | ISO-8859-1 | UTF-8 | EUC-KR | |---|---|---|---|---| | **binary** | no change | No change: same bytes and length | Bytes kept, each character validated, invalid ones become `?` | Bytes kept, each character validated, invalid ones become `?` | | **ISO-8859-1** | no change | no change | Converted; byte size grows, no loss | Converted; byte size grows, no loss | | **UTF-8** | Bytes kept; character length grows | Converted; byte size may shrink, characters may be lost | no change | Converted; byte size may shrink, characters may be lost | | **EUC-KR** | Bytes kept; character length grows | Converted; byte size may shrink, characters may be lost | Converted; byte size may grow, no loss | no change | The precision (number of characters) is kept and the byte size changes. Converting UTF-8 or EUC-KR to ISO-8859-1 can truncate data. ### Collation The collations of a database are listed in the [db_collation](https://www.coradb.ai/manual/sql/catalog_views.html#db_collation) catalog view and by [SHOW COLLATION](https://www.coradb.ai/manual/sql/query/show.html#show-collation). The built-in collations, available without compiling locales, are: ```sql SELECT coll_id, coll_name, charset_name, is_builtin, has_expansions, contractions, uca_strength FROM db_collation WHERE is_builtin = 'Yes' ORDER BY coll_id; ``` | coll_id | coll_name | charset_name | is_builtin | has_expansions | contractions | uca_strength | |---|---|---|---|---|---|---| | 0 | iso88591_bin | iso88591 | Yes | No | 0 | Not applicable | | 1 | utf8_bin | utf8 | Yes | No | 0 | Not applicable | | 2 | iso88591_en_cs | iso88591 | Yes | No | 0 | Not applicable | | 3 | iso88591_en_ci | iso88591 | Yes | No | 0 | Not applicable | | 4 | utf8_en_cs | utf8 | Yes | No | 0 | Not applicable | | 5 | utf8_en_ci | utf8 | Yes | No | 0 | Not applicable | | 6 | utf8_tr_cs | utf8 | Yes | No | 0 | Not applicable | | 7 | utf8_ko_cs | utf8 | Yes | No | 0 | Not applicable | | 8 | euckr_bin | euckr | Yes | No | 0 | Not applicable | | 9 | binary | binary | Yes | No | 0 | Not applicable | Every collation belongs to one charset, so a charset and a collation that do not match cannot be combined. With only **COLLATE**, the charset is the collation's charset; with only **CHARSET**, the collation is the charset's *bin* collation: `iso88591_bin`, `utf8_bin`, `euckr_bin` or `binary` (`binary` is both a charset and its collation). ### CHARSET and COLLATE modifier ```sql data_type [ { CHARACTER_SET | CHARSET } charset_name ] [ COLLATE collation_name ] ``` The names can be written as identifiers or string literals. Examples: ```sql CREATE TABLE note (txt VARCHAR(100) CHARSET utf8); ALTER TABLE note CHANGE txt txt CHAR(10) COLLATE utf8_en_cs; -- charset utf8 from the collation -- sort case-insensitively without changing the column SELECT name FROM city ORDER BY CAST(name AS VARCHAR(32) COLLATE utf8_en_ci); SELECT name FROM city ORDER BY name COLLATE utf8_en_ci; ``` **COLLATE** on an expression is cheaper than **CAST**, but it can only change the collation within the same charset; **CAST** can also convert the charset. ### How to determine collation among columns with different collation When the arguments of an operator or function have different collations, CoraDB must choose one. If it cannot, the statement fails: ```sql CREATE TABLE coll_t ( s1 STRING COLLATE utf8_en_cs, s2 STRING COLLATE utf8_tr_cs, s3 STRING COLLATE utf8_en_ci, s4 STRING COLLATE utf8_bin ); SELECT s1 FROM coll_t WHERE s1 > s2; ``` ```text ERROR: '>' requires arguments with compatible collations. ``` The choice is based on *collation coercibility*: how readily a value gives up its collation. Lower numbers win. 1. The argument with the lowest coercibility determines the collation; arguments with higher coercibility are converted to it. 2. If arguments with the same coercibility have different collations, the collation cannot be resolved and an error is raised, with one exception: two host or session variables (coercibility 11) with the same charset, one of them with a *bin* collation, use the other's collation. See [Session and host variables](https://www.coradb.ai/manual/sql/i18n_collation.html#comparison-between-session-and-or-host-variables). | Coercibility | Argument | |---|---| | -1 | Expression whose arguments are all host variables (decided at execution) | | 0 | Operand with a **COLLATE** modifier | | 1 | Column with a non-*bin*, non-binary collation | | 2 | Column with the binary collation | | 3 | Column with a *bin* collation (`iso88591_bin`, `utf8_bin`, `euckr_bin`) | | 4 | SELECT value or expression with a non-*bin*, non-binary collation | | 5 | SELECT value or expression with the binary collation | | 6 | SELECT value or expression with a *bin* collation | | 7 | Special functions: **SYSTEM_USER**, **DATABASE**, **SCHEMA**, **VERSION** | | 8 | String literal with a non-*bin*, non-binary collation | | 9 | String literal with the binary collation | | 10 | String literal with a *bin* collation | | 11 | Host variable, session variable | [COERCIBILITY](https://www.coradb.ai/manual/sql/function/information_fn.html#coercibility) returns the value for an expression: ```sql SELECT COERCIBILITY(s1), COERCIBILITY(s4), COERCIBILITY(CONCAT(s1, '')), COERCIBILITY(CONCAT(s4, '')), COERCIBILITY('a'), COERCIBILITY('a' COLLATE utf8_en_ci), COERCIBILITY(_binary'a'), COERCIBILITY(DATABASE()) FROM coll_t; -- 1, 3, 4, 6, 10, 0, 9, 7 ``` **Resolving conflicts.** With the table above: | Condition | Result | |---|---| | `s1 > s2` | Error: two columns (1 and 1) with different collations | | `s1 > CAST(s2 AS STRING COLLATE utf8_en_cs)` | Compared with utf8_en_cs | | `s1 > CAST(s2 AS STRING COLLATE utf8_tr_cs)` | The **CAST** is an expression (4), so it is converted to s1's utf8_en_cs | | `s1 > CONCAT(s2, '')` | Expression (4) is converted to s1's collation (1) | | `s1 > s4` | s4 has a *bin* collation (3), so utf8_en_cs is used | | `s1 > 'abc'` | The literal (10) takes s1's collation | | `s1 > s2 + s3` | Error: `'+' requires arguments with compatible collations.` (s2 and s3, both 1) | Numbers and dates that are converted to strings always take the other string's collation. A column with an ISO-8859-1 *bin* collation compared with a UTF-8 column is converted to UTF-8, at some cost. **Expressions with only host variables.** The coercibility of `UPPER(?)` is not known before execution, so `COERCIBILITY` returns -1. If all arguments have coercibility 11 and different collations, the common collation is resolved at run time instead of raising an error: ```sql PREPARE st FROM 'SELECT COLLATION(UPPER(?)), COERCIBILITY(UPPER(?))'; EXECUTE st USING 'a', 'a'; -- utf8_bin, -1 PREPARE st1 FROM 'SELECT INSERT(?, 2, 2, ?)'; EXECUTE st1 USING _utf8'abcd', _binary'ef'; -- 'aefd' ``` **Session and host variables.** When a host variable and a session variable with the same charset are compared and one has a *bin* collation, the other's collation is used: ```sql SET NAMES utf8; SET @v1 = 'a'; -- utf8_bin PREPARE stmt FROM 'SELECT COLLATION(?), COLLATION(@v1), ? = @v1'; SET NAMES utf8 COLLATE utf8_en_ci; EXECUTE stmt USING 'A', 'A'; -- utf8_en_ci, utf8_bin, 1: compared case-insensitively SET NAMES utf8 COLLATE utf8_en_cs; EXECUTE stmt USING 'A', 'A'; -- utf8_en_cs, utf8_bin, 0 ``` If neither has a *bin* collation and the collations differ (for example `@v1` set under `utf8_en_ci` and the parameter under `utf8_en_cs`), the comparison fails with `Context requires compatible collations.` ### Charset and collation of an ENUM type column An **ENUM** column takes the charset and collation of its table or database, not those of its value literals: in the e-commerce database, `ENUM(_iso88591'a', _iso88591'b')` is still a `utf8_bin` column. Give the column or the table a **COLLATE** clause to change it: ```sql CREATE TABLE t (e ENUM ('a', 'b') COLLATE utf8_en_ci); CREATE TABLE t (e ENUM ('a', 'b')) COLLATE utf8_en_ci; ``` ## Charset and collation of tables ```sql CREATE TABLE table_name ( column_definitions ) [ CHARSET charset_name ] [ COLLATE collation_name ]; ``` Columns without their own settings use the table's; a table without settings uses the database's. A column that specifies only a charset gets that charset's *bin* collation, regardless of the table collation: ```sql CREATE TABLE note (col STRING CHARSET utf8, c2 STRING) COLLATE utf8_en_ci; SHOW FULL COLUMNS FROM note; ``` | Field | Type | Collation | |---|---|---| | col | VARCHAR(1073741823) | utf8_bin | | c2 | VARCHAR(1073741823) | utf8_en_ci | ## Charset and collation of string literals The charset and collation of a string literal are taken from the first that applies: 1. Its [charset introducer](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-introducer) or [COLLATE modifier](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collate-modifier); 2. The last [SET NAMES](https://www.coradb.ai/manual/sql/i18n_collation.html#set-names-statement) of the session; 3. The database charset and its *bin* collation. ### SET NAMES statement **SET NAMES** sets the charset and collation of the string literals sent by the client in this session. ```sql SET NAMES [ charset_name ] [ COLLATE collation_name ]; ``` - *charset_name*: `iso88591`, `utf8`, `euckr` or `binary`. - *collation_name*: any collation of that charset (see `db_collation`); without it, the charset's *bin* collation. An incompatible pair is an error. **SET NAMES** sets the session value of the system parameter [intl_collation](https://www.coradb.ai/manual/admin/config_sql.html#intl_collation): `SET NAMES utf8` is the same as `SET SYSTEM PARAMETERS 'intl_collation=utf8_bin'`. ### Charset introducer A *charset introducer*, the charset name with a leading underscore, gives one literal a charset; a **COLLATE** modifier gives it a collation: ```sql [ _utf8 | _iso88591 | _euckr | _binary ] 'string' [ COLLATE collation_name ] ``` - With an introducer and no **COLLATE**: the client collation if the introducer matches the client charset (from **SET NAMES**), otherwise the introducer's *bin* collation. - With **COLLATE** and no introducer: the collation's charset. - An introducer only labels the bytes as written; it does not convert them. `_iso88591'Ç'` sent from a UTF-8 client contains the two UTF-8 bytes C3 87. ```sql SELECT 'coradb', _utf8'coradb', _utf8'coradb' COLLATE utf8_en_cs; SET NAMES utf8 COLLATE utf8_en_ci; SELECT 'a' COLLATE utf8_en_cs; -- the COLLATE modifier overrides SET NAMES ``` ## Charset and collation of expressions The charset and collation of an expression are inferred from its arguments by [coercibility](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-coercibility): ```sql SELECT COLLATION(CONCAT(s1, s4)) FROM coll_t; -- utf8_en_cs: the column with coercibility 1 wins over 3 ``` All string matching functions (**LIKE**, **REPLACE**, **INSTR**, **POSITION**, **LOCATE**, **SUBSTRING_INDEX**, **FIND_IN_SET**, …) and comparison operators use the collation. ## Charset and collation of system data The system charset is the charset of the database locale; the system collation is always its *bin* collation (`iso88591_bin`, `euckr_bin` or `utf8_bin`). It applies to identifiers and to the values in the system catalog. ## Impact of charset specified when creating DB The locale given when the database is created also determines: - Which characters identifiers can contain and how they are cased (the *alphabet*); - The default language of date/string and number/string conversion functions; - The console conversion in corasql. ### Casing and identifiers Identifiers are case-insensitive. Table, column, session variable, trigger and stored procedure names are stored in lower case; user and group names in upper case. - ISO-8859-1 and EUC-KR casing is built in; EUC-KR cases only ASCII characters. - The built-in UTF-8 locales (`en_US.utf8`, `ko_KR.utf8`, `tr_TR.utf8`) case only their own letters: ASCII, plus Turkish letters for `tr_TR.utf8`. Other characters are allowed in identifiers but are not converted: `CREATE TABLE ÈABC` creates a table named `Èabc`. - LDML locales (compiled with `make_locale`) case all Unicode characters up to FFFF: with `es_ES.utf8`, `CREATE TABLE ÈABC` creates `èabc`. Some languages have special casing rules: in Turkish, `LOWER('I')` is `ı` (dotless i) and `UPPER('i')` is `İ`; in German, `UPPER('ß')` is `SS`. Such locales have two alphabets: one with the special rules for user data and one without them for identifiers, so that identifiers stay compatible between databases with different locales. With the built-in `utf8_tr_cs` collation: ```sql SELECT UPPER(_utf8'istanbul' COLLATE utf8_tr_cs), UPPER(_utf8'istanbul' COLLATE utf8_en_cs), LOWER('I' COLLATE utf8_tr_cs); -- İSTANBUL, ISTANBUL, ı ``` ## String literal input and output Strings reach CoraDB through the CCI API, the language drivers (JDBC, Python, Node.js, …) and corasql. CoraDB treats the bytes between quotes as raw data; the client is responsible for telling which charset they are in, through the connection settings, **SET NAMES** or charset introducers. ### Text conversion for corasql corasql can convert between the console's encoding and the database charset. A locale's LDML file may declare the console encoding it supports, for example for `tr_TR.utf8`: ```xml ``` If the console uses one of these encodings (`chcp 28599` on Windows, `export LANG=tr_TR.iso88599` on Linux), corasql converts input from ISO-8859-9 to UTF-8 and output back. At input, everything is converted if it contains characters that need it; at output, only the result data. Locales without this tag (for example `km_KH.utf8`) have no console conversion. **Example: French.** Enable `fr_FR` in `coradb_locales.txt`, compile the locales (see [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html#locale-setting)) and create the database with `fr_FR.utf8`. Then either set the console to UTF-8 (`LANG=fr_FR.utf8` on Linux), which accepts any character, or to ISO-8859-15 (`LANG=fr_FR.iso885915` on Linux, `chcp 28605` on Windows) with the matching `linux_charset="iso885915"` or `windows_codepage="28605"` in the LDML tag. **Example: Romanian.** Enable `ro_RO`, compile, create the database with `ro_RO.utf8`. Use a UTF-8 console, or ISO-8859-2 (`LANG=ro_RO.iso88592`, `linux_charset="iso88592"`) on Linux, or codepage 1250 (`chcp 1250`, `windows_codepage="1250"`) on Windows. Codepage 1250 lacks some ISO-8859-2 characters, and typing S and T with comma below on Windows requires the Romanian (legacy) keyboard. ### Unicode normalization A glyph can be written in different ways in Unicode. "Ä" is one code point in composed form (00C4, UTF-8 bytes C3 84) and two in decomposed form (0041 0308, UTF-8 bytes 41 CC 88). CoraDB can convert decomposed input to composed form and composed output to decomposed form; normalization does not depend on the locale. - [unicode_input_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_input_normalization) = `yes` composes input. - [unicode_output_normalization](https://www.coradb.ai/manual/admin/config_sql.html#unicode_output_normalization) = `yes` decomposes output. Enable both for clients that only handle decomposed text. Enable only input normalization for clients that send both forms but accept composed output. Only code points 0000–FFFF are normalized. ## Contraction and expansion of collation LDML collations of the UTF-8 charset can define *contractions* and *expansions*. They change the results of comparisons and therefore affect several features; see [Collation settings impacting CoraDB features](https://www.coradb.ai/manual/sql/i18n_collation.html#collation-settings-impacting-coradb-features). The collations are based on the Unicode Collation Algorithm and its default table, DUCET (). Each code point has one or more *collation elements* of four weights, one per comparison level (base letter, accent, case, tie-breaker). The Korean letter kiyeok, for example: ```text 1100 ; [.313B.0020.0002.1100] # HANGUL CHOSEONG KIYEOK ``` CoraDB uses code points 0000–FFFF only. ### Contraction A *contraction* is a sequence of code points that sorts as one letter. In traditional Spanish sorting, "ch" is a letter after "c": all words starting with "ch" come after all other words starting with "c". Contractions work with and without expansions; the collation stores a table of contractions. ### Expansion An *expansion* is a code point with more than one collation element, so that it compares like a sequence of letters: "æ" like "ae", or in German "Ä" like "AE". Expansions are enabled in a collation's LDML definition with `CoraDBExpansions="use"`; collations with expansions have `exp` in their name. - **Without expansions**, every code point gets a single weight per level and strings are compared character by character. With DUCET weights, "Ar" and "Är" are equal at primary strength and "Ar" < "Är" at secondary and tertiary strength. - **With expansions**, the collation elements of all characters are concatenated and the lists are compared level by level, which is slower but gives whole-word ordering. If "Ä" expands to "A" + "E" (German), then "Ar" > "Är", because R sorts after E at the first level. **Accent ordering.** In Canadian French sorting (`utf8_fr_exp_ab`, which requires expansions), accents are compared from the end of the string: - Normal accent ordering: cote < coté < côte < côté - Backward accent ordering: cote < côte < coté < côté ## Operations requiring collation and charset ### Charset Functions that work on characters need the charset; [OCTET_LENGTH](https://www.coradb.ai/manual/sql/function/string_fn.html#octet_length) and [BIT_LENGTH](https://www.coradb.ai/manual/sql/function/string_fn.html#bit_length) do not, because they count bytes. The same character can take a different number of bytes: ```sql SELECT OCTET_LENGTH(_utf8'È'), LENGTH(_utf8'È'); -- 2, 1 ``` ### Collation Functions and operators that compare or match strings need the collation: comparisons, **STRCMP**, **POSITION**, **LIKE**, **REPLACE**, **INSTR**, **LOCATE**, **SUBSTRING_INDEX**, **FIND_IN_SET**, **ORDER BY**, **GROUP BY**, **DISTINCT** and others. **UPPER** and **LOWER** use the user alphabet of the collation's default locale: - The locale in the name: `utf8_tr_cs` → `tr_TR.utf8`, `iso88591_en_ci` → `en_US` (ISO-8859-1); - The *bin* collations: `iso88591_bin` → `en_US` (ISO-8859-1), `utf8_bin` → `en_US.utf8` (ASCII only), `euckr_bin` → `ko_KR.euckr` (ASCII only); - Generic LDML collations (`utf8_gen`, `utf8_gen_ci`, `utf8_gen_ai_ci`): the first locale in `$CORADB/conf/coradb_locales.txt` that contains them, `de_DE` in the default alphabetical order. ### Charset conversion Converting a value to another charset keeps its precision (number of characters); the byte size may change. Converting UTF-8 or EUC-KR to ISO-8859-1 keeps the precision and may truncate data. In a database created with an ISO-8859-1 locale, for example, a UTF-8 client that inserts `'Ç'` (two bytes in UTF-8) into a **CHAR(1)** column stores a converted or truncated value, because the column holds one ISO-8859-1 byte. ## Collation settings impacting CoraDB features ### LIKE conditional optimization For a collation without expansions, every character has one weight, so a prefix pattern can be turned into a range that an index can use: ```text s LIKE 'abc%' → s >= 'abc' AND s < 'abd' ``` For collations with expansions, or that give several characters the same weight (case- or accent-insensitive collations), the range is not exact. CoraDB then keeps the **LIKE** condition after the range, as a filter: ```text s LIKE 'abc%' → s >= 'abc' AND s < 'abd' AND s LIKE 'abc%' ``` ### Index covering In a collation that does not distinguish 'abc' and 'ABC', an index stores only one of the values (whichever was inserted first). A [covering index](https://www.coradb.ai/manual/sql/tuning_index_opt.html#covering-index) would then return the wrong spelling, so covering index scans are not used for such collations. In LDML, collations with `strength="tertiary"` or `"quaternary"` distinguish case; quaternary needs more memory and is slower. ### Summary of CoraDB features for each collation | Collation | LIKE kept after rewrite to a range | Index covering | |---|---|---| | iso88591_bin | no | yes | | iso88591_en_cs | no | yes | | iso88591_en_ci | yes | no | | utf8_bin | no | yes | | euckr_bin | no | yes | | utf8_en_cs | no | yes | | utf8_en_ci | yes | no | | utf8_tr_cs | no | yes | | utf8_ko_cs | no | yes | | utf8_gen | no | yes | | utf8_gen_ai_ci | yes | no | | utf8_gen_ci | yes | no | | utf8_de_exp_ai_ci | yes | no | | utf8_de_exp | yes | no | | utf8_ro_cs | no | yes | | utf8_es_cs | no | yes | | utf8_fr_exp_ab | yes | no | | utf8_ja_exp | yes | no | | utf8_ja_exp_cbm | yes | no | | utf8_km_exp | yes | no | | utf8_ko_cs_uca | no | yes | | utf8_tr_cs_uca | no | yes | | utf8_vi_cs | no | yes | | binary | no | yes | ## Viewing collation information - [CHARSET](https://www.coradb.ai/manual/sql/function/information_fn.html#charset), [COLLATION](https://www.coradb.ai/manual/sql/function/information_fn.html#collation) and [COERCIBILITY](https://www.coradb.ai/manual/sql/function/information_fn.html#coercibility) return the charset, collation and coercibility of an expression. - The [db_collation](https://www.coradb.ai/manual/sql/catalog_views.html#db_collation) catalog view and [SHOW COLLATION](https://www.coradb.ai/manual/sql/query/show.html#show-collation) list the collations of the database. - [SHOW FULL COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) shows the collation of each column. ## Using i18n characters with JDBC The CoraDB JDBC driver returns string values as Java `String` objects (UTF-16), converted from the charset that the server sends with each value: the charset of the column or expression, or the system charset. Values with the **binary** charset are not converted; they are returned as `coradb.jdbc.driver.CORADBBinaryString` objects, which wrap the bytes. `CORADBResultSetMetaData.getColumnCharset()` tells which case applies. A table with a UTF-8 column and a binary column: ```sql CREATE TABLE label (txt VARCHAR(10) CHARSET utf8, raw VARCHAR(10) CHARSET binary); ``` Inserting a string and raw bytes: ```java PreparedStatement st = conn.prepareStatement("INSERT INTO label VALUES (?, ?)"); st.setObject(1, "abc"); st.setObject(2, new CORADBBinaryString(new byte[] { (byte) 161, (byte) 224 })); st.executeUpdate(); ``` Reading them back, as text or as bytes depending on the column charset: ```java Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT txt, raw FROM label"); CORADBResultSetMetaData md = (CORADBResultSetMetaData) rs.getMetaData(); while (rs.next()) { for (int j = 1; j <= md.getColumnCount(); j++) { if ("BINARY".equals(md.getColumnCharset(j))) { byte[] bytes = ((CORADBBinaryString) rs.getObject(j)).getBytes(); System.out.println(java.util.HexFormat.of().formatHex(bytes)); } else { System.out.println(rs.getString(j)); } } } ``` --- # Locale setting and custom locales Source: https://www.coradb.ai/manual/sql/i18n_locale.html ## Files for locale setting CoraDB uses following directories and files to set the locales. - **\$CORADB/conf/coradb_locales.txt** file: A configuration file containing the list of locales to be supported - **\$CORADB/conf/coradb_locales.all.txt** file: A configuration file template with the same structure as **coradb_locales.txt**. Contains the entire list of all the locales that the current version of CoraDB is capable of supporting without any efforts from the end user's side. - **\$CORADB/locales/data** directory: This contains files required to generate locale data. - **\$CORADB/locales/loclib** directory: contains a C header file, **locale_lib_common.h** and OS dependent makefile which are used in the process of creating / generating locales shared libraries. - **\$CORADB/locales/data/ducet.txt** file: Text file containing default universal collation information (codepoints, contractions and expansions, to be more specific) and their weights, as standardized by The Unicode Consortium, which is the starting point for the creation of collations. For more information, see . - **\$CORADB/locales/data/unicodedata.txt** file: Text file containing information about each Unicode codepoint regarding casing, decomposition, normalization etc. CoraDB uses this to determine casing. For more information, see . - **\$CORADB/locales/data/ldml** directory: common_collations.xml and XML files, name with the convention coradb_\<*locale_name*\>.xml. common_collations.xml file contains shared collation information in all locale files, and each coradb_\<*locale_name*\>.xml file contains a locale information for the supported language. - **\$CORADB/locales/data/codepages** directory: contains codepage console conversion for single byte codepages(8859-1.txt , 8859-15.txt, 8859-9.txt) and codepage console conversion for double byte codepages(CP1258.txt , CP923.txt, CP936.txt , CP949.txt). - **\$CORADB/bin/make_locale.sh** (Linux) or **%CORADB%\bin\make_locale_x64.bat** (Windows): A script file used to generate shared libraries for locale data - **\$CORADB/lib** directory: Shared libraries for generated locales will be stored here. ## Locale setting When you want to use a charset and collation of a specific language, the charset should be identical with a database which will be created newly. Supported CoraDB charsets are ISO-8859-1, EUC-KR and UTF-8 and the charset to be used is specified when creating a database. For example, when you created a database with a locale ko_KR.utf8, you can use collations starting with "utf8\_" like utf8_ja_exp. However, if you set the locale as ko_KR.euckr, you cannot use all collations which are related with other charset (see [CoraDB collation](https://www.coradb.ai/manual/sql/i18n.html#coradb-collation)). The following is an example which used utf8_ja_exp after creating a database with en_US.utf8. 1. cd \$CORADB/conf 2. cp coradb_locales.all.txt coradb_locales.txt 3. make_locale.sh # compile all configured locales 4. coradb createdb testdb en_US.utf8 5. coradb server start testdb 6. corasql -u dba testdb 7. Run below query on corasql ```sql SET NAMES utf8; CREATE TABLE t1 (i1 INT , s1 VARCHAR(20) COLLATE utf8_ja_exp, a INT, b VARCHAR(20) COLLATE utf8_ja_exp); INSERT INTO t1 VALUES (1, 'いイ基盤',1,'いイ 繭'); ``` For more details, see the following. ## Step 1: selecting a locale Configure locales to use on **\$CORADB/conf/coradb_locales.txt**. You can select all or some of locales which are supported. CoraDB supports locales as follows: en_US, de_DE, es_ES, fr_FR, it_IT, ja_JP, km_KH, ko_KR, tr_TR, vi_VN, zh_CN, ro_RO. The language and country for each locale are shown in the following table. | Locale name | Language - country | |---|---| | en_US | English - U.S.A. | | de_DE | German - Germany | | es_ES | Spanish - Spain | | fr_FR | French - France | | it_IT | Italian - Italy | | ja_JP | Japanese - Japan | | km_KH | Khmer - Cambodia | | ko_KR | Korean - Korea | | tr_TR | Turkish - Turkey | | vi_VN | Vietnamese - Vietnam | | zh_CN | Chinese - China | | ro_RO | Romanian - Romania | > **Note:** > The LDML files for the supported locales are named coradb_\<*locale_name*\>.xml and they can be found in the **\$CORADB/locales/data/ldml** directory. If only a subset of these locales are to be supported by CoraDB, one must make sure their corresponding LDML files are present in the **\$CORADB/locales/data/ldml** folder. A locale cannot be used by CoraDB, unless it has an entry in **coradb_locales.txt file** and it has a corresponding coradb_\<*locale_name*\>.xml. > > Locale libraries are generated according to the contents of **\$CORADB/conf/coradb_locales.txt** configuration file. This file contains the language codes of the wanted locales (all user defined locales are generated with UTF-8 charset). Also, in this file can be configured the file paths for each locale LDML file and libraries can be optionally configured. > > ```text > > ko_KR /home/CoraDB/locales/data/ldml/coradb_ko_KR.xml /home/CoraDB/lib/libcoradb_ko_KR.so > ``` > > By default, the LDML files are found in **\$CORADB/locales/data/ldml** and the locale libraries in **\$CORADB/lib**; the filenames for LDML are formatted like: coradb_\<*lang_name*\>.ldml. > > The filenames for libraries: libcoradb_\<*lang_name*\>.dll (.so for Linux). ## Step 2: compiling locale Once the requirements described above are met, the locales can be compiled. Regarding the embedded locales in CoraDB, they can be used without compiling user locale library, so they can be used by skipping the step 2. But there are differences between the embedded locale and the library locale. Regarding this, see [Built-in locale and library locale](https://www.coradb.ai/manual/sql/i18n_locale.html#built-in-locale-and-library-locale). To compile the locale libraries, one must use the **make_locale** (**.bat** for Windows and **.sh** for Linux) utility script from command console. The file is delivered in **\$CORADB/bin** folder so it should be resolved by **\$PATH** environment variable. Here **\$CORADB, \$PATH** are the environment variables of Linux, **%CORADB%**, **%PATH%** are the environment variables of Windows. > **Note:** > On Windows, the script (`make_locale_x64.bat`) needs Microsoft Visual Studio with the C++ tools; it looks for Visual Studio 2017, 2015, 2010, 2008 and 2005, in that order. On Linux it needs gcc. `make_locale.sh -h` shows the usage. ```text make_locale.sh [options] [locale] options ::= [-t 64] [-m debug|release] locale ::= de_DE | es_ES | fr_FR | it_IT | ja_JP | km_KH | ko_KR | tr_TR | vi_VN | zh_CN | ro_RO ``` - *options* - **-t**: target machine; only 64-bit (`64`, `x64`, `x86_64`, `64bit`) is supported, and it is the default. - **-m**: Selects release or debug. In general, release is selected (default value: release). The debug mode is provided for developers who would like to write the locale library themselves. Selects release or debug. In general, release is selected (default value: release). The debug mode is provided for developers who would like to write the locale library themselves. - *locale*: The locale name of the library to build. If *locale* is not specified, the build includes data from all configured locales. In this case, library file is stored in **\$CORADB/lib** directory with the name of **libcoradb_all_locales.so** (**.dll** for Windows). To create user defined locale shared libraries, two choices are available: - Creating a single lib with all locales to be supported. ```text make_locale.sh # build and pack all configured locales (64-bit, release) ``` - Creating one lib for each locale to be supported. ```text make_locale.sh -m release ko_KR # one library for ko_KR only ``` The first choice is recommended. In this scenario, some data may be shared among locales. If you choose the first one, a lib supporting all locales has less than 15 MB; in the second one, consider for each locale library from 1 MB to more than 5 MB. Also the first one is recommended because it has no runtime overhead during restarting the servers when you choose the second one. > **Warning:** > **Limitations and rules** > > - Do not change the contents of **\$CORADB/conf/coradb_locales.txt** after locales generation; once the locales libraries are generated, the contents of **\$CORADB/conf/coradb_locales.txt** should not be changed (order of languages within the file must also be preserved). During locale compiling, the generic collation uses the first one as default locale; changing the order may cause different results with casing for such collation ([utf8_gen]()\*). > - Do not change the contents for **\$CORADB/locales/data/\*.txt** files. > **Note:** > **Procedure of executing make_locale.sh(.bat) script** > > The processing in **make_locale.sh(.bat)** script > > 1. Reads the **.ldml** file corresponding to a language, along with some other installed common data files like **\$CORADB/locales/data/ducet.txt**, **\$CORADB/locales/data/unicodedata.txt**, and **\$CORADB/locales/data/codepages/\*.txt** > 2. After processing of raw data, it writes in a temporary **\$CORADB/locales/loclib/locale.c** file C constants values and arrays consisting of locales data. > 3. The temporary file **locale.c** is passed to the platform compiler to build a **.dll/.so** file. This step assumes that the machines has an installed C/C++ compiler and linker. Currently, only the MS Visual Studio for Windows and gcc for Linux compilers are supported. > 4. Temporary files are removed. ## Step 3: setting CoraDB to use a specific locale Only one locale can be selected as the default locale when you create DB. In addition to the possibility of specifying a default locale, one can override the default calendar settings with the calendar settings from another locale, using the **intl_date_lang** system parameter. - The locale will be in the format: \<*locale_name*\>.\[**utf8** \| **iso**\] (for example `tr_TR.utf8`, `en_US.iso88591`, `ko_KR.utf8`) - **intl_date_lang**: \<*locale_name*\>. The possible values for \<*locale_name*\> are listed on [Step 1: selecting a locale](https://www.coradb.ai/manual/sql/i18n_locale.html#step-1-selecting-a-locale). > **Note:** > **Setting the month/day in characters, AM/PM, and number format** > > For the function that inputs and outputs the day/time, you can set the month/day in characters, AM/PM, and number format by the locale in the **intl_date_lang** system parameter. > > Also for the function that converts a string to numbers or the numbers to a string, you can set the string format by the locale in **intl_number_lang** system parameter. ### Built-in locale and library locale Regarding the embedded locales in CoraDB, they can be used without compiling user locale library, so they can be used by skipping the step 2. But there are two differences between the embedded locale and the library locale. - Embedded(built-in) locale(and collation) are not aware of Unicode data For instance, casing (lower, upper) of (Á, á) is not available in embedded locales. The LDML locales provide data for Unicode codepoints up to 65535. - Also, the embedded collations deals only with ASCII range, or in case of 'utf8_tr_cs' - only ASCII and letters from Turkish alphabet. Embedded UTF-8 locales are not Unicode compatible, while compiled (LDML) locales are. Currently, the built-in locales which can be set during creating DB are as follows: - en_US.iso88591 - en_US.utf8 - ko_KR.utf8 - ko_KR.euckr - ko_KR.iso88591: Will have Romanized Korean names for month, day names. - tr_TR.utf8 - tr_TR.iso88591: Will have Romanized Turkish names for month, day names. The order stated above is important; if no charset is defined while creating DB, the charset is the charset of the locale shown first. For example, if the locale is set as ko_KR(e.g. coradb createdb testdb ko_KR), the charset is specified as ko_KR.utf8, the first locale among the ko_KR in the above list. Locales of the other languages except the built-in locales should end with **.utf8**. For example, specify the locale as de_DE.utf8 for German. The names of month and day for ko_KR.iso88591 and tr_TR.iso88591 should be Romanized. For example, "일요일" for Korean (Sunday in English) is Romanized to "Iryoil". Providing ISO-8859-1 characters only is required. For more information, see [The month/day in Korean and Turkish characters for ISO-8859-1 charset](https://www.coradb.ai/manual/sql/i18n_locale.html#the-monthday-in-korean-and-turkish-characters-for-iso-8859-1-charset). ### The month/day in Korean and Turkish characters for ISO-8859-1 charset In Korean or Turkish which have charset UTF-8 or in Korean which have charset EUC-KR, the month/day in characters and AM/PM are encoded according to the country. However, for ISO-8859-1 charset, if the month/day in characters and AM/PM in Korean or Turkish is used as its original encoding, an unexpected behavior may occur in the server process because of its complex expression. Therefore, the name should be Romanized. The default charset of CoraDB is ISO-8859-1 and the charset can be used for Korean and Turkish. The Romanized output format is as follows: **Day in characters** | Day in characters long/short format | Long/short romanized Korean | Long/short romanized Turkish | |-------------------------------------|-----------------------------|------------------------------| | Sunday / Sun | Iryoil / Il | Pazar / Pz | | Monday / Mon | Woryoil / Wol | Pazartesi / Pt | | Tuesday / Tue | Hwayoil / Hwa | Sali / Sa | | Wednesday / Wed | Suyoil / Su | Carsamba / Ca | | Thursday / Thu | Mogyoil / Mok | Persembe / Pe | | Friday / Fri | Geumyoil / Geum | Cuma / Cu | | Saturday / Sat | Toyoil / To | Cumartesi / Ct | **Month in characters** | Month in characters long/short format | Long/short romanized Korean (not classified) | Long/short romanized Turkish | |---------------------------------------|----------------------------------------------|------------------------------| | January / Jan | 1wol | Ocak / Ock | | February / Feb | 2wol | Subat / Sbt | | March / Mar | 3wol | Mart / Mrt | | April / Apr | 4wol | Nisan / Nsn | | May / May | 5wol | Mayis / Mys | | June / Jun | 6wol | Haziran / Hzr | | July / Jul | 7wol | Temmuz / Tmz | | August / Aug | 8wol | Agustos / Ags | | September / Sep | 9wol | Eylul / Eyl | | October / Oct | 10wol | Ekim / Ekm | | November / Nov | 11wol | Kasim / Ksm | | December / Dec | 12wol | Aralik / Arl | **AM/PM in characters** | AM/PM in characters long/short format | Romanized in Korean | Romanized in Turkish | |---------------------------------------|---------------------|----------------------| | AM | ojeon | AM | | PM | ohu | PM | ## Step 4: creating a database with the selected locale setting When issuing the command "**coradb createdb** \<*db_name*\> \<*locale_name.charset*\>", a database will be created using the settings in the variables described above. Once the database is created a locale setting which was given to the database cannot be changed. The charset and locale name are stored in "**db_root**" system catalog table. ## Step 5 (optional): manually verifying the locale file The contents of locales libraries may be displayed in human readable form using the **dumplocale** CoraDB utility. Execute **coradb dumplocale -h** to output the usage. The used syntax is as follows. ```bash coradb dumplocale [options] [language-string] options ::= -i|--input-file -d|--calendar -n|--numeric {-a |--alphabet=}{l|lower|u|upper|both} -c|--codepoint-order -w|--weight-order {-s|--start-value} {-e|--end-value} -k -z language-string ::= de_DE|es_ES|fr_FR|it_IT|ja_JP|km_KH|ko_KR|tr_TR|vi_VN|zh_CN|ro_RO ``` - **dumplocale**: A command which dumps the contents of locale shared library previously generated using LDML input file. - *language-string*: One of de_DE, es_ES, fr_FR, it_IT, ja_JP, km_KH, ko_KR, tr_TR, vi_VN, zh_CN and ro_RO. Configures the locale language to dump the locale shared library. If it's not set, all languages which are configured on **coradb_locales.txt** are given. The following are \[options\] for **coradb dumplocale**. **-i, --input-file=FILE** The name of the locale shared library file (\< *shared_lib*\>) created previously. It includes the directory path. **-d, --calendar** Dumps the calendar and date/time data. Default value: No **-n, --numeric** Dumps the number data. Default value: No **-a, --alphabet=l\|lower\|u\|upper\|both** Dumps the alphabet and case data. Default value: No **--identifier-alphabet=l\|lower\|u\|upper** Dumps the alphabet and case data for the identifier. Default value: No **-c, --codepoint-order** Dumps the collation data sorted by the codepoint value. Default value: No (displayed data: cp, char, weight, next-cp, char and weight) **-w, --weight-order** Dumps the collation data sorted by the weight value. Default value: No (displayed data: weight, cp, char) **-s, --start-value=CODEPOINT** Specifies the dump scope. Starting codepoint for **-a, --identifier-alphabet, -c, -w** options. Default value: 0 **-e, --end-value=CODEPOINT** Specifies the dump scope. Ending codepoint for **-a, --identifier-alphabet, -c, -w** options. Default value: Max value read from the locale shared library. **-k, --console-conversion** Dumps the data of console conversion. Default value: No **-z, --normalization** Dumps the normalization data. Default value: No The following example shows how to dump the calendar, number formatting, alphabet and case data, alphabet and case data for the identifier, collation sorting based on the codepoint order, collation sorting based on the weight, and the data in ko_KR locale into ko_KR_dump.txt by normalizing: ```bash % coradb dumplocale -d -n -a both -c -w -z ko_KR > ko_KR_dump.txt ``` It is highly recommended to redirect the console output to a file, as it can be very big data, and seeking information could prove to be difficult. ## Step 6: starting CoraDB-Related processes All CoraDB-related processes should be started in an identical environmental setting. The CoraDB server, the broker, CAS, and corasql should use the locale binary file of an identical version. For example, master server. There is no check on the compatibility of the locale used by server and CAS (client) process, so the user should make sure the LDML files used are the same. Locale library loading is one of the first steps in CoraDB start-up. Locale (collation) information is required for initializing databases structures (indexes depends on collation). This process is performed by each CoraDB process which requires locale information: server, CAS, corasql, createdb, copydb, unload, load DB. The process of loading a locale library is as follows. - If no lib path is provided, CoraDB will try to load \$CORADB/lib/libcoradb_\<*lang_name*\>.so file; if this file is not found, then CoraDB assumes all locales are found in a single library: **\$CORADB/lib/libcoradb_all_locales.so**. - If suitable locale library cannot be found or any other error occurs during loading, the CoraDB process stops. - If collations between the database and the locale library are different, the CoraDB process cannot start. To include the newly changed collations of the locale library, firstly synchronize the database collation with the system collation by running **coradb synccolldb** command. Next, update from the existing database to the wanted collations of schemas and data. For more details, see [Synchronization of database collations with system collations](https://www.coradb.ai/manual/sql/i18n_locale.html#synchronization-of-database-collations-with-system-collations). ## Synchronization of database collations with system collations CoraDB's normal operation requires that the system collation and the database collation must be the same. The system locale means that the locale which include built-in locales and library locales created through coradb_locales.txt (see [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html#locale-setting)), and it includes the system collation information. The database collation information is stored on the **\_db_collation** system catalog table. **coradb synccolldb** utility checks if the database collation is the same with the system collation, and synchronize into the system collation if they are different. However, note that this utility doesn't transform the data itself stored on the database. This utility can be used when the existing database collation should be changed after the system locale is changed. However, there are operations which the user have to do manually. The user should do this operations before the synchronization. These operations can be done by running corasql with coradb_synccolldb_\<*database_name*\>.sql file, which is created by **coradb synccolldb -c**. - Change collation using ALTER TABLE .. MODIFY statement. - Remove any views, indexes, triggers or partitions containing the collation. Run synchronization with **coradb synccolldb**. After then, do the following operations. - Recreate views, indexes, triggers, or partitions - Update application statements to use new collations This utility should work only in offline mode. **synccolldb** syntax is as follows. ```bash coradb synccolldb [options] database_name ``` - **coradb**: An integrated utility for the CoraDB service and database management. - **synccolldb**: A command to synchronize collations of a database with collations from the system(according to contents of locales libraries and \$CORADB/conf/coradb_locales.txt). - *database_name*: A database name to be synchronized with collations from the system. If \[options\] is omitted, **synccolldb** checks the collation differences between the system and the database, synchronize the database collation with the system collation, and create the coradb_synccolldb_\<*database_name*\>.sql file including the queries of objects to be dropped before the synchronization. The following are \[options\] which are used on **coradb synccolldb**. **-c, --check-only** This option prints out the collation information which is different between the database collation and the system collation. **-f, --force-only** This option doesn't ask when updating the database collation with the system collation. The following shows that how it works when the system collation and the database collation are different. Firstly, make locale library about ko_KR locale. ```bash $ echo ko_KR > $CORADB/conf/coradb_locales.txt $ make_locale.sh ``` Next, create the database. ```bash $ coradb createdb --db-volume-size=20M --log-volume-size=20M xdb en_US ``` Create a schema. At this time, specify the needed collation in each table. ```bash $ corasql -S -u dba xdb -i in.sql ``` ```sql CREATE TABLE dept(depname STRING PRIMARY KEY) COLLATE utf8_ko_cs_uca; CREATE TABLE emp(eid INT PRIMARY KEY, depname STRING,address STRING) COLLATE utf8_ko_cs_uca; ALTER TABLE emp ADD CONSTRAINT FOREIGN KEY (depname) REFERENCES dept(depname); ``` Change the locale setting of the system. If you do not any values on **coradb_locales.txt**, the database consider that only built-in locales exist ```bash $ echo "" > $CORADB/conf/coradb_locales.txt ``` Check the difference between system and database by running **coradb synccolldb -c** command. ```bash $ coradb synccolldb -c xdb ---------------------------------------- ---------------------------------------- Collation 'utf8_ko_cs_uca' (Id: 133) not found in database or changed in new system configuration. ---------------------------------------- ---------------------------------------- Collation 'utf8_gen_ci' (Id: 44) not found in database or changed in new system configuration. ---------------------------------------- ---------------------------------------- Collation 'utf8_gen_ai_ci' (Id: 37) not found in database or changed in new system configuration. ---------------------------------------- ---------------------------------------- Collation 'utf8_gen' (Id: 32) not found in database or changed in new system configuration. ---------------------------------------- ---------------------------------------- There are 4 collations in database which are not configured or are changed compared to system collations. Synchronization of system collation into database is required. Run 'coradb synccolldb -f xdb' ``` If the indexes exist, firstly you should remove the indexes, and change the collation of each table, then recreate the indexes directly. The process to remove indexes and change the collation of tables can be executed by using coradb_synccolldb_xdb.sql file which was created by **synccolldb** command. On the below example, a foreign key is the index which you should recreate. ```bash $ cat coradb_synccolldb_xdb.sql ALTER TABLE [dept] COLLATE utf8_bin; ALTER TABLE [emp] COLLATE utf8_bin; ALTER TABLE [emp] DROP FOREIGN KEY [fk_emp_depname]; ALTER TABLE [dept] MODIFY [depname] VARCHAR(1073741823) COLLATE utf8_bin; ALTER TABLE [emp] MODIFY [address] VARCHAR(1073741823) COLLATE utf8_bin; ALTER TABLE [emp] MODIFY [depname] VARCHAR(1073741823) COLLATE utf8_bin; $ corasql -S -u dba -i coradb_synccolldb_xdb.sql xdb ``` Removing the obsolete collations by executing the above coradb_synccolldb_xdb.sql script file must be performed before forcing the synchronization of system collations into database. Run **coradb synccolldb** command. If the option is omitted, the message is shown to ask to run this command or not; if the **-f** option is given, the synchronization is run without checking message. ```bash $ coradb synccolldb xdb Updating system collations may cause corruption of database. Continue (y/n) ? Contents of '_db_collation' system table was updated with new system collations. ``` Recreate the dropped foreign key. ```bash $ corasql -S -u dba xdb ALTER TABLE emp ADD CONSTRAINT FOREIGN KEY fk_emp_depname(depname) REFERENCES dept(depname); ``` > **Note:** > In CoraDB, collations are identified by the ID number on the CoraDB server, and its range is from 0 to 255. LDML file is compiled with shared library, which offers the mapping information between the ID and the collation(name, attribute). > > - The system collation is the collation which is loaded from the locale library, by the CoraDB server and the CAS module. > - The database collation is the collation which is stored into the **\_db_collation** system table. ## Guide for adding locales and collations Most new locales and/or collations can be added by user simply by adding (or changing) a new (existing) LDML file. The LDML files format used by CoraDB are derived from generic Unicode Locale Data Markup Language (). The tags and attributes which are specific only to CoraDB can be easily identified (they contain a "coradb" into the naming). The best approach to add a new locale is to copy existing LDML file and tweak various setting until desired results are obtained. The filename must be formatted like coradb_\<*language*\>.xml and be placed in the folder **\$CORADB/locales/data/ldml**. The \<*language*\> part should be a ASCII string (normally five characters) in IETF format (). After creating the LDML file, the \<*language*\> part string must be added into CoraDB configuration file **\$CORADB/conf/coradb_locales.txt**. Note that the order in this file is the order of generating (compiling) locale library and loading locales at start-up. The **make_locale** script must be used to compile the new added locale and add its data into the CoraDB locales library (locale in **\$CORADB/lib/**). The LDML file is expected in UTF-8 encoding, and it is not possible to add more than one locale into the same LDML file. Adding a new locale in LDML file requires: - To specify calendar information (CoraDB date formats, name of months and week days in various forms, names for AM/PM day periods). CoraDB supports only Gregorian calendar (generic LDML specifies other calendar types which are not supported by CoraDB). - To specify number settings (digit grouping symbols) - Providing an alphabet (set of rules for how letters are upper-cased and lower-cased) - Optionally, some collations can be added - Also optionally, console conversion rules for Windows corasql application can be defined ### LDML calendar information - The first part consists in providing default CoraDB formats for **DATE**, **DATETIME**, **TIME**, **TIMESTAMP**, **DATETIME WITH TIME ZONE** and **TIMESTAMP WITH TIME ZONE** data type conversion to/from string. This formats are used by functions [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date), [TO_TIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_time), [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime), [TO_TIMESTAMP](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp), [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char), [TO_DATETIME_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime_tz), [TO_TIMESTAMP_TZ](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_timestamp_tz). The formats elements allowed depend on data type and are the ones used for [TO_CHAR](https://www.coradb.ai/manual/sql/function/typecast_fn.html#fn-to_char) function ([Date/time format 1](https://www.coradb.ai/manual/sql/function/typecast_fn.html#datetime-format1)). Only ASCII characters are allowed in the format strings. The allowed size are 30 bytes (characters) for **DATE** and **TIME** formats, 48 characters for **DATETIME** and **TIMESTAMP** formats and 70 characters for **DATETIME WITH TIME ZONE** and **TIMESTAMP WITH TIME ZONE**. - The \ requires to specify the names for months in both long form and abbreviated form. The allowed size are 15 (or 60 bytes) for abbreviated form and 25 characters (or 100 bytes) for normal form. - The \ requires week day names in both long and abbreviated form. The allowed size are 10 characters (or 40 bytes) for abbreviated form and 15 characters (or 60 bytes) for full day name. - The \ sub-tree requires to define the string for AM/PM format variants (according to type attribute). The allowed size is 10 characters (or 40 bytes). The months and week-days names (in both long and abbreviated form) must be specified in Camel case format (first letter upper case, the rest in lower case). CoraDB checks only the maximum allowed size in bytes; the size in characters is computed only for full-width UTF-8 characters (4 bytes), so it would be possible to set a month name having 100 ASCII-only characters (the 25 characters limit is when each character from month name is encoded on 4 bytes in UTF-8). ### LDML numbers information - The \ tag defines the characters used as symbols for splitting decimal part from integer part in numbers and for grouping the digits. CoraDB expects only ASCII characters for these symbols. Empty of space character is not allowed. CoraDB performs grouping for 3 digits. | Currency ISO symbol | Meaning | |---|---| | USD | Dollar sign | | JPY | Japanese yen | | GBP | British pound | | KRW | Korean won | | TRY | Turkish lira | | KHR | Cambodian riel | | CNY | Chinese renminbi | | INR | Indian rupee | | RUB | Russian ruble | | AUD | Australian dollar | | CAD | Canadian dollar | | BRL | Brasilian real | | RON | Romanian leu | | EUR | Euro | | CHF | Swiss franc | | DKK | Danish krone | | NOK | Norwegian krone | | BGN | Bulgarian lev | | VND | Vietnamese dong | | CZK | Czech koruna | | PLN | Polish zloty | | SEK | Swedish krona | | HRK | Croatian kuna | | RSD | Serbian dinar | ### LDML alphabet These allow to define casing rules for alphabet of the locale. The 'CoraDBAlphabetMode' attribute defines the primary source of data for characters. Normally, this should be set to "UNICODEDATAFILE", values which instructs CoraDB to use the Unicode data file (**\$CORADB/locales/data/unicodedata.txt**). This file must not be modified, any customization on certain characters should be done in LDML file. If such value is configured, all Unicode characters up to codepoint 65535 are loaded with casing information. The other allowed value for `CoraDBAlphabetMode` is "ASCII" which will lead to only ASCII character can be lower case, upper case or case-insensitive compare in matching functions. This does not affect CoraDB's ability to support all UTF-8 4 bytes encoded Unicode characters, it just limits the casing ability for characters not included. The casing rules are optional and apply on top of the primary source of character information (UNICODEDATAFILE or ASCII). CoraDB allows to define upper casing rules (\ tag) and lower casing rules (\ tag).Each of upper and lower casing rules set consists for pairs of source-destination (\ = source, \ = destination). For instance, the following defines a rule that each character "A" is lower cased to "aa" (two character "a"). ```xml A aa ``` ### LDML console conversion In Windows, the console does not support UTF-8 encoding, so CoraDB allows to translate characters from their UTF-8 encoding to a desired encoding. After configuring console conversion for a locale, the user must set prior to starting corasql application the codepage of the console using 'chcp' command (the codepage argument must match the 'windows_codepage' attribute in LDML). Conversion will work bidirectionally (input and output in corasql), but is only limited to Unicode characters which can be converted in the configured codepage. The \ element is optional and allows to instruct corasql how to print (in which character encoding) the text in interactive command. The 'type' attribute defines the conversion scheme. The allowed values are: - ISO: is a generic scheme in which the destination codepage is a single byte charset - ISO88591: is a predefined single byte scheme for ISO-8859-1 charset (the 'file' attribute is not required, is ignored) - ISO88599: is a predefined single byte scheme for ISO-8859-9 charset (also the 'file' attribute is not required) - DBCS: Double Byte Code-Set; it is a generic scheme in which the destination codepage is a double byte charset The 'windows_codepage' is the value for Windows codepage which CoraDB automatically activates console conversion. The 'linux_charset' is corresponding value for charset part in **LANG** environment variable from UNIX system. It is recommended to use native CoraDB charset in Linux console. The 'file' attribute is required only for "ISO" and "DBCS" values of 'type' attribute and is the file containing the translation information (**\$CORADB/locales/data/codepages/**). ### LDML collation Configuring a collation is the most complex task for adding LDML locale in CoraDB. Only collation having UTF-8 codeset can be configured. CoraDB allows to configure most constructs specified by UCA - Unicode Collation Algorithm () including contractions and expansions, but the properties for the collation are mostly controlled via the 'settings' attribute. A LDML file can contain multiple collations. Collations can be included from external file using the 'include' tag. The 'validSubLocales' attribute of 'collations' tag is a filter allowing to control locale compilation when external collations (from external files) are included. Its values can be either a list of locales or "\*" in which case the collations in sub-tree are added in all locales from which the file is included. One collation is defined using the 'collation' tag and its sub-tree. The 'type' attribute indicates the name for the collation as it will be added in CoraDB. The 'settings' tag defines the properties of the collation: - 'id' is the (internal) numeric identifier used by CoraDB. It is integer value in range (32 - 255) and is optional, but is strongly recommended that an explicit unassigned values is set. Please see [Collation naming rules](https://www.coradb.ai/manual/sql/i18n.html#collation-naming-rules). - 'strength' is a measure of how strings compare. See [Collation properties](https://www.coradb.ai/manual/sql/i18n.html#collation-properties). The allowed values are - "quaternary": different graphic symbols of the same character compare differently, but different Unicode codepoints may compare equal. - "tertiary": graphic symbols of the same character are equal, case-sensitive collation. - "secondary": case insensitive collation, characters with accents compare different - "primary": accents are ignored, all characters compare as the base character. - 'caseLevel': special setting to enable case sensitive compare for collations having strength \< tertiary. Valid values are "on" or "off". - 'caseFirst': order of casing. Valid values are "lower", "upper" and "off". The "upper" values means upper case letters are ordered before the corresponding lower case letter. - 'CoraDBMaxWeights': it is the number of codepoints (or last codepoint + 1) which are customized in the collation. Maximum value is 65536. Increasing this value increases the size of collation data. - 'DUCETContractions': valid values are "use" or "ignore". When "use" - enable CoraDB to use in the collation the contractions defined by DUCET file (\$CORADB/locales/data/ducet.txt) or ignoring them. - 'TailoringContractions': same as previous but refers to the contractions defined or derived from explicit collation rules. Enabling contractions leads to a more complex collation (slower string compares). - 'CoraDBExpansions': allowed values are "use" or "ignore" (default) and refers to usage of collation expansions from both the DUCET file and tailoring rules; This has the most influence on collation properties. Enabling it will result in a compare with multiple passes (up to collation strength) when comparing strings. Also it greatly increases collation data, with the benefit of obtaining a more "natural" sort order. See [Expansion](https://www.coradb.ai/manual/sql/i18n_collation.html#expansion). - 'backwards': "on" or "off": used to obtain "french" order by performing an end-to-start compare on secondary level (for accents). It has effect only when 'CoraDBExpansions' are enabled. - 'MatchContractionBoundary': "true" or "false". This is used in collation having expansions and contractions to configure behavior at string matching when a contraction is found. The main data for a collation is loaded from the DUCET file. After this step, the collation may be customized using "tailoring rules". These are the "\" (LDML) and "\" (CoraDB specific). The 'coradbrules' tag is optional and can be used to explicitly set weight values for a codepoint or a range of codepoints. The coradbrules apply after loading the primary collation data from DUCET file and before applying the UCA rules (from '\' tag). Each of these rule is enclosed in '\' tag. If the rule refers to only one Unicode codepoint, then a '\' tag is provided which contains the hexadecimal value of codepoint. All available CoraDB collations contain this coradb-rule: ```xml 20 [0.0.0.0] ``` This rule says that weight values (UCA defines four weight values per collation element) of the codepoints starting with 20 (which is ASCII space character) are all set to zero. Since there is no '\' tag, the only codepoint affected is 20. In CoraDB, space character compares as zero. The allowed tags inside of a '\' rule are: - '\': rule to set the weights for single codepoint. - '\': rule to set the weights for single character. Similar to previous one, but instead of codepoint it expects a Unicode character (in UTF-8 encoding). - '\': rule to set the weights for a range of codepoints. This is the starting codepoint. - '\': rule to set the weights for a range of characters. This is the starting character. In this context, the order of characters is given by their Unicode codepoints. - '\': end codepoint for a range rule. - '\': end character for a range rule. - '\': weight values to set (single value). The weight values are expected in hexadecimal. Each collation element has four values which are delimited by point and enclosed by square brackets(\[\]). There can be up to 10 collation elements. - '\': starting weight values to set for a range. Optionally, there is 'step' attribute of this tag, which sets the increasing step after each codepoint. By default the step is \[0001.0000.0000.0000\], which means that after setting the first weight values for the starting codepoint, one value is added to primary level weight and set to the next codepoint in range, and the process is repeated until end codepoint. Examples: ```xml 0 20 [0.0.0.0] 30 39 [30.0.0.0][30.0.0.0] ``` The Rule 1, sets for codepoints ranging from 0 to 20 (including) the weight values 0. The Rule 2, sets for codepoints ranging from 30 to 39 (which are the digits), a set of two collation elements with increasing weights; In this example, codepoint 39 (character "9") will have the weights with two collation elements \[39.0.0.0\]\[39.0.0.0\]. The '\' tag is also optional but is according to LDML and UCA specifications. The meanings of sub-ordinates tags are - '\': anchor collation element. It defines the reference to which subsequent rules (up to next ``) are tailored. It can be a single characters or multiple characters in which case is either a contraction or an expansion. By default, all the tailoring rules after the anchor are sort "after" (element from first rule is after the anchor, element from second rule sorts after element in first rule); if the optional attribute "before" is present, then only the first rule after the \ sorts before the anchor, while the second and the following rules resumes the normal "after" sort (element in second rule sorts after element in first rule). - '\': the character comes after (or before, if the anchor had the `before` attribute) the previously tailored one at primary level. - '\': the character comes after (or before, if the anchor had the `before` attribute) the previously tailored one at secondary level. - '\': the character comes after (or before, if the anchor had the `before` attribute) the previously tailored one at tertiary level. - '\': the character sorts identically to previous one - '\', '\', '\', '\': same as '\', '\', '\', '\' but applies to a range of characters - '\': specifies the expansion character - '\': specifies the second character of expansion. - '\': specifies the context in which a rule applies. A variant to specify contractions and expansions. For more information on UCA tailoring with LDML rules see . **Footnotes** [^1]: glyph: an element for the shape of a character; a graphic symbol which indicates a shape or a form for a character. Because a glyph specifies the shape which is shown, several glyphs about one character can exist. [^2]: glyph: an element for the shape of a character; a graphic symbol which indicates a shape or a form for a character. Because a glyph specifies the shape which is shown, several glyphs about one character can exist. --- # Time zone setting and time zone library Source: https://www.coradb.ai/manual/sql/i18n_timezone.html ## Timezone setting Two system parameters control time zones (see [Time zone parameters](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter)): | Parameter | Applies to | Default | |---|---|---| | [timezone](https://www.coradb.ai/manual/admin/config_sql.html#timezone) | A session | The value of **server_timezone** | | [server_timezone](https://www.coradb.ai/manual/admin/config_sql.html#server_timezone) | The database server | The operating system's time zone | A session changes its own time zone with **SET TIME ZONE** or by setting the parameter: ```sql SET TIME ZONE 'Europe/Bucharest'; SET TIME ZONE '+02:00'; SET SYSTEM PARAMETERS 'timezone=Europe/Bucharest'; ``` The session time zone affects the types **TIMESTAMP**, **TIMESTAMPLTZ** and **DATETIMELTZ**, the conversion of values without time zone to the time zone types, and functions such as **SYS_DATETIME**. See [Date/time types with time zone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone) and [Time zone functions](https://www.coradb.ai/manual/sql/datatype_datetime.html#time-zone-functions). Time zones written as region names (`Europe/Bucharest`) need the time zone library, which contains the IANA time zone database. A library is installed with CoraDB. Because governments change offsets and daylight-saving rules, update the library from time to time as described below. Offsets such as `+02:00` do not need the library. ## Compiling timezone library To update the time zone library with the latest IANA data, stop the CoraDB service, then: ### Windows 1. Download the latest *Time Zone Data* (`tzdata*.tar.gz`) from . 2. Extract it into `%CORADB%\timezones\tzdata`. 3. Run `make_tz_x64.bat` from `%CORADB%\bin`. It creates `libcoradb_timezones.dll` in `%CORADB%\lib`. ```text make_tz_x64.bat ``` The script needs Microsoft Visual Studio with the C++ tools, like `make_locale`. ### Linux 1. Download the latest *Time Zone Data* from . 2. Extract it into `$CORADB/timezones/tzdata`. 3. Run `make_tz.sh`. It creates `libcoradb_timezones.so` in `$CORADB/lib`. ```text make_tz.sh ``` `make_tz.sh -h` shows the options: `-t` target (64-bit), `-m release|debug`, and `-g new|extend`. On Windows the corresponding arguments are `/release`, `/debug`, `/new` and `/extend`. ### Timezone library and database compatibility The library contains an MD5 checksum of its time zone data. Every database stores the checksum of the library it was created with, in the `timezone_checksum` column of `db_root`. A database cannot be used with a library whose checksum differs: after rebuilding the library with new data, either create new databases, or use the *extend* mode, which keeps existing databases usable: 1. It builds a library that merges the old and the new data: regions that no longer exist in the new data are kept, so that values stored in the database remain valid. 2. It updates values stored in the databases where a changed offset or daylight-saving rule makes the old encoding wrong, and stores the new checksum. ```text make_tz.sh -g extend # Linux make_tz_x64.bat /extend # Windows ``` The extend mode processes every database listed in `databases.txt` (in `$CORADB_DATABASES`), by running `coradb gen_tz -g extend ` for each. If one fails, the script stops, and databases already processed may need to be restored from backup. Take a backup before you start. When several users share one CoraDB installation, the extend can only update the databases that the user running it can access and that are listed in that user's `databases.txt`. Either give that user access to all database directories and the same `CORADB_DATABASES`, or run the extend once per user: 1. Back up the time zone library and `databases.txt`; 2. Remove from `databases.txt` all databases except the current user's; 3. Run the extend; 4. Restore `databases.txt` and, for all users except the last, the time zone library. ### Usage of timezone data types with JDBC The JDBC driver takes all time zone information from the CoraDB server. Java and CoraDB both use IANA data, but region names and rules may differ between versions, so do not mix Java's time zone handling with CoraDB's. Values of all time zone types are returned as `coradb.sql.CORADBTimestamptz` objects. To insert one: ```java String datetime = "2000-01-01 01:02:03.123"; CORADBTimestamptz tz = CORADBTimestamptz.valueOf(datetime, true, "Europe/Kiev"); // true: DATETIME precision PreparedStatement ps = conn.prepareStatement("INSERT INTO event_log VALUES (?)"); ps.setObject(1, tz); ps.executeUpdate(); ``` To read one: ```java ResultSet rs = conn.createStatement().executeQuery("SELECT happened_at FROM event_log"); while (rs.next()) { CORADBTimestamptz value = (CORADBTimestamptz) rs.getObject(1); System.out.println(value); } ``` A `CORADBTimestamptz` stores its local date and time as if they were UTC, in milliseconds like `java.util.Date`, and keeps the time zone separately. `getTime()` therefore returns the wall-clock value encoded as UTC, while `getUnixTime()` returns the real moment, in seconds since the Unix epoch, taking the time zone into account: ```java CORADBTimestamptz tz = CORADBTimestamptz.valueOf("2000-01-01 01:02:03.123", true, "Asia/Seoul"); System.out.println(tz.getTime()); System.out.println(tz.getUnixTime()); ``` --- # Identifiers Source: https://www.coradb.ai/manual/sql/identifier.html Identifiers are the names you give to database objects: tables, vertex and edge tables, columns, indexes, constraints, views, serials, triggers, stored procedures and users. ## Rules for plain identifiers A name written without quotes must follow these rules: - It starts with a letter, an underscore (`_`) or a number sign (`#`). It cannot start with a digit. - The other characters can be letters, digits, `_` and `#`. - Letters can be any Unicode letters, not only `A`–`Z`: `preț_produs` is a valid name. - It cannot contain spaces or operator characters (`+ - * / % || ! < > = | ^ & ~`). - It cannot be a [reserved word](https://www.coradb.ai/manual/sql/keyword.html). ```text identifier ::= first_character [ other_character ... ] first_character ::= letter | _ | # other_character ::= letter | digit | _ | # ``` Valid names: ```text order_items ssn# _staging #tmp_orders preț_produs ``` Invalid names, unless quoted: ```text 2fer -- starts with a digit low cost -- contains a space price+tax -- contains an operator character order -- reserved word ``` Using a reserved word as a plain name is a syntax error: ```sql SELECT order FROM orders; ``` ```text ERROR: Syntax error: unexpected 'order' ``` ## Case-insensitivity Identifiers are not case-sensitive: `Mixed_Case`, `mixed_case` and `MIXED_CASE` are the same table. CoraDB stores and displays names in lowercase. This also applies to quoted names. ## Quoted identifiers Enclose a name in double quotes (`"`), square brackets (`[ ]`) or backticks (`` ` ``) to use a name that the rules above would not allow, such as a reserved word, a name with spaces or a name starting with another symbol. The three forms are interchangeable: ```sql CREATE TABLE "low cost" ("select" INT, [position] INT, `order` INT, "@lowcost" INT); INSERT INTO "low cost" VALUES (1, 2, 3, 4); SELECT "select", [position], `order`, "@lowcost" FROM [low cost]; ``` | select | position | order | @lowcost | |---:|---:|---:|---:| | 1 | 2 | 3 | 4 | A reserved word used as a column name does not need quotes when it is qualified with the table name or alias: ```sql SELECT t.select, t.position FROM "low cost" t; ``` You also need quotes for names that contain a hyphen, such as the database name in the result column of [SHOW TABLES](https://www.coradb.ai/manual/sql/query/show.html#show-tables) on the e-commerce database: `[Tables_in_e-commerce]`. > **Note:** > Double quotes delimit identifiers only while the [ansi_quotes](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes` (the default). When it is set to `no` in `coradb.conf`, text in double quotes is a character string, as in single quotes; use brackets or backticks for identifiers then. The parameter cannot be changed with `SET SYSTEM PARAMETERS`. Quoting identifiers that do not need it is harmless, but quoted names are harder to read and type. Prefer plain names in `snake_case` that avoid reserved words. ## Maximum length The maximum length of a name is counted in bytes, not characters. In UTF-8, letters outside the ASCII range take 2 to 4 bytes, so a name made of such letters can hold fewer characters. | Object | Maximum length | |---|---| | Database | 17 bytes | | Table, vertex table, edge table, view | 254 bytes | | Column | 254 bytes | | Index, constraint | 254 bytes | | Serial | 254 bytes | | Trigger | 254 bytes | | Java stored procedure | 254 bytes | > **Warning:** > A longer table name is not rejected: CoraDB shortens it to 254 bytes. Keep names well below the limit. The names CoraDB generates for constraints, such as `pk_
_` for a primary key or `fk_
_` for a foreign key, are subject to the same limit. With long table and column names, give such constraints an explicit, shorter name. ## See also - [Reserved words](https://www.coradb.ai/manual/sql/keyword.html) - [Literals](https://www.coradb.ai/manual/sql/literal.html) - [Comments](https://www.coradb.ai/manual/sql/comment.html) --- # Java stored functions and procedures Source: https://www.coradb.ai/manual/sql/jsp.html CoraDB stored functions and procedures are written in Java. They run in a Java virtual machine (JVM) hosted by the CoraDB *Java SP server*, can use SQL through a server-side JDBC connection, and are called from SQL statements, from the **CALL** statement or from applications through JDBC. - A **stored function** returns a value and can be used in expressions, for example in a **SELECT** list. - A **stored procedure** returns no value; it can return results through **OUT** parameters. Java is the only language for stored functions and procedures. ## Enabling the Java SP server 1. Set the server parameter [java_stored_procedure](https://www.coradb.ai/manual/admin/config_other.html) to `yes` in `coradb.conf` (the default is `no`) and restart the database server. 2. Start the Java SP server for the database and check its status: ```bash coradb javasp start e-commerce coradb javasp status e-commerce ``` `status` shows the process ID, port and JVM options of the server. See [CoraDB Java stored procedure server](https://www.coradb.ai/manual/admin/control_javasp.html) for the `javasp` commands and [Configuring for CoraDB Java SP server](https://www.coradb.ai/manual/admin/control_javasp.html#configuring-for-coradb-java-sp-server) for its settings. Calling a Java stored function while the server is not running fails with `Java VM is not running.` ## Writing a Java stored function The whole workflow, for a function that returns the total of an order of the e-commerce database: **1. Write and compile the Java class.** The methods called from SQL must be `public static`. ```java public class OrderSp { public static BigDecimal orderTotal(int orderId) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:default:connection:"); PreparedStatement ps = conn.prepareStatement( "SELECT SUM(p.unit_price * oi.quantity * (100 - oi.discount_pct) / 100) " + "FROM order_items oi JOIN product p ON p.id = oi.product_id WHERE oi.order_id = ?"); ps.setInt(1, orderId); ResultSet rs = ps.executeQuery(); BigDecimal total = rs.next() ? rs.getBigDecimal(1) : null; rs.close(); ps.close(); return total; } } ``` ```bash javac OrderSp.java ``` **2. Load the class into the database** with [loadjava](https://www.coradb.ai/manual/sql/jsp.html#loadjava-utility): ```bash loadjava e-commerce OrderSp.class ``` **3. Publish it** with a call specification: ```sql CREATE FUNCTION order_total(p_order_id INT) RETURN NUMERIC(12,2) AS LANGUAGE JAVA NAME 'OrderSp.orderTotal(int) return java.math.BigDecimal'; ``` **4. Call it**: ```sql SELECT id, order_total(id) FROM orders WHERE customer_id = 102; ``` ## Server-side JDBC Inside a stored function or procedure, connect to the calling database with the URL `jdbc:default:connection:`: ```java Connection conn = DriverManager.getConnection("jdbc:default:connection:"); ``` This connection belongs to the transaction of the caller. Its statements are committed or rolled back with that transaction, and `conn.commit()` and `conn.rollback()` inside the Java method have no effect. A stored procedure can also open an ordinary JDBC connection to another database (URL `jdbc:coradb:host:port:database:user:password:`; see [JDBC driver](https://www.coradb.ai/manual/api/jdbc.html)). Such a connection is a separate transaction: commit and close it explicitly in the Java code. `System.getProperty("coradb.server.version")` returns the CoraDB version when the code runs inside the Java SP server, and **NULL** elsewhere; use it to check where a class is running. ## loadjava utility **loadjava** copies a compiled Java class or a JAR file into the database's Java directory, from where the Java SP server loads it. ```bash loadjava [-y | --overwrite] database_name java_class_or_jar_file ``` - `-y`, `--overwrite`: overwrite a file of the same name without asking. Without it, **loadjava** asks before overwriting. ## Publishing: CREATE FUNCTION and CREATE PROCEDURE A loaded class is called from SQL only after it is published with a *call specification*, which names the Java method and maps its parameters and return value to SQL types. ```sql CREATE [OR REPLACE] FUNCTION function_name [ ( parameter [, parameter ...] ) ] RETURN sql_type { IS | AS } LANGUAGE JAVA NAME 'class_name.method_name ( [java_type [, java_type ...]] ) return java_type' [ COMMENT 'comment' ]; CREATE [OR REPLACE] PROCEDURE procedure_name [ ( parameter [, parameter ...] ) ] { IS | AS } LANGUAGE JAVA NAME 'class_name.method_name ( [java_type [, java_type ...]] )' [ COMMENT 'comment' ]; parameter ::= parameter_name [ IN | OUT | IN OUT | INOUT ] sql_type [ COMMENT 'comment' ] ``` - **OR REPLACE** replaces an existing function or procedure of the same name. - Names of stored functions and procedures are not case-sensitive. A name can have up to 254 bytes, and a function or procedure up to 64 parameters. - Parameters are **IN** by default. An **OUT** or **INOUT** (**IN OUT**) parameter is passed to Java as an array of length 1; the Java method returns its value in the first element. - Java types are written with their full names (`java.lang.String`, `java.math.BigDecimal`), primitive types as is (`int`, `short`). - CoraDB does not check the call specification against the Java class when it is published; a mismatch shows up when the function is called. The SQL return type of the call specification determines the type of the result. ```sql CREATE OR REPLACE FUNCTION order_total(p_order_id INT COMMENT 'order id') RETURN NUMERIC(12,2) IS LANGUAGE JAVA NAME 'OrderSp.orderTotal(int) return java.math.BigDecimal' COMMENT 'sum of order lines'; CREATE PROCEDURE add_order_item(p_order_id INT, p_product_id INT, p_quantity SHORT) AS LANGUAGE JAVA NAME 'OrderSp.addOrderItem(int, int, short)'; CREATE PROCEDURE stock_of(p_product_id IN INT, p_units OUT INT) AS LANGUAGE JAVA NAME 'OrderSp.stockOf(int, java.lang.Integer[])'; ``` ### Data type mapping | SQL type | Java types | |---|---| | CHAR, VARCHAR | `java.lang.String`, `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`, `java.lang.Byte`, `java.lang.Short`, `java.lang.Integer`, `java.lang.Long`, `java.lang.Float`, `java.lang.Double`, `java.math.BigDecimal`, `byte`, `short`, `int`, `long`, `float`, `double` | | NUMERIC, SHORT, INT, BIGINT, FLOAT, DOUBLE | `java.lang.Byte`, `java.lang.Short`, `java.lang.Integer`, `java.lang.Long`, `java.lang.Float`, `java.lang.Double`, `java.math.BigDecimal`, `java.lang.String`, `byte`, `short`, `int`, `long`, `float`, `double` | | DATE, TIME, TIMESTAMP, DATETIME | `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`, `java.lang.String` | | SET, MULTISET, LIST (SEQUENCE) | `java.lang.Object[]`, arrays of primitive types, `java.lang.Integer[]`, … | | OBJECT | `coradb.sql.CORADBOID` | | CURSOR (return type only) | `java.sql.ResultSet` | ### Listing stored functions and procedures [db_stored_procedure](https://www.coradb.ai/manual/sql/catalog_views.html#db_stored_procedure) and [db_stored_procedure_args](https://www.coradb.ai/manual/sql/catalog_views.html#db_stored_procedure_args) list the published functions and procedures and their parameters, with their comments: ```sql SELECT sp_name, sp_type, return_type, arg_count, target, comment FROM db_stored_procedure ORDER BY sp_name; ``` | sp_name | sp_type | return_type | arg_count | target | comment | |---|---|---|---|---|---| | add_order_item | PROCEDURE | void | 3 | OrderSp.addOrderItem(int, int, short) | NULL | | order_total | FUNCTION | NUMERIC | 1 | OrderSp.orderTotal(int) return java.math.BigDecimal | Sum of order lines | | stock_of | PROCEDURE | void | 2 | OrderSp.stockOf(int, java.lang.Integer[]) | NULL | ```sql SELECT sp_name, index_of, arg_name, data_type, mode, comment FROM db_stored_procedure_args ORDER BY sp_name, index_of; ``` | sp_name | index_of | arg_name | data_type | mode | comment | |---|---|---|---|---|---| | add_order_item | 0 | p_order_id | INTEGER | IN | NULL | | add_order_item | 1 | p_product_id | INTEGER | IN | NULL | | add_order_item | 2 | p_quantity | SHORT | IN | NULL | | order_total | 0 | p_order_id | INTEGER | IN | order id | | stock_of | 0 | p_product_id | INTEGER | IN | NULL | | stock_of | 1 | p_units | INTEGER | OUT | NULL | ### DROP FUNCTION and DROP PROCEDURE ```sql DROP FUNCTION function_name [, function_name ...]; DROP PROCEDURE procedure_name [, procedure_name ...]; ``` ```sql DROP FUNCTION order_total; DROP PROCEDURE add_order_item, stock_of; ``` A stored function or procedure can be dropped by its owner and by **DBA** and the members of the **DBA** group. Its owner can be changed with [ALTER FUNCTION … OWNER TO](https://www.coradb.ai/manual/sql/authorization.html#alter--owner). ## Calling stored functions and procedures ### From SQL A stored function can be used wherever an expression is allowed: ```sql SELECT order_total(1); SELECT id, order_date, order_total(id) AS total FROM orders WHERE customer_id = 102; ``` ### With CALL ```sql CALL procedure_name ( [argument [, argument ...]] ); CALL function_name ( [argument [, argument ...]] ) INTO :variable; ``` ```sql CALL add_order_item(1, 1618, 2); -- adds 2 x Gobi HeatTec Tee to order 1 CALL order_total(1) INTO :total; ``` Arguments are literals or session variables (`:name`). A variable passed to an **OUT** or **INOUT** parameter receives its value: ```sql CALL stock_of(1618, :units); SELECT :units; ``` **CALL** is also used for [methods](https://www.coradb.ai/manual/sql/method.html). Without **ON** *target*, CoraDB first looks for a stored function or procedure of that name and then for a method. Calling a name that is neither fails with: ```text ERROR: Stored procedure/function 'deposit' does not exist. ``` when the call has no arguments, and, when it has arguments (which could be a method call on the first argument), with: ```text ERROR: Methods require an object as their target. ``` An argument of **CALL** cannot be another **CALL** or a subquery. If the Java code throws an exception, it is written to the `_java.log` file. To print exceptions on the console instead, set the handler in `$CORADB/java/logging.properties` to `java.util.logging.ConsoleHandler`. ### From a Java application Applications call stored functions and procedures through a JDBC `CallableStatement`: ```java public class AddItem { public static void main(String[] args) throws Exception { Connection conn = DriverManager.getConnection("jdbc:coradb:localhost:33000:e-commerce:::", "dba", ""); conn.setAutoCommit(false); CallableStatement cs = conn.prepareCall("CALL add_order_item(?, ?, ?)"); cs.setInt(1, 1); cs.setInt(2, 1618); cs.setShort(3, (short) 2); cs.executeUpdate(); cs.close(); CallableStatement fn = conn.prepareCall("? = CALL order_total(?)"); fn.registerOutParameter(1, Types.NUMERIC); fn.setInt(2, 1); fn.execute(); System.out.println("total: " + fn.getBigDecimal(1)); fn.close(); conn.commit(); conn.close(); } } ``` The procedure behind `add_order_item` uses the server-side connection, so its insert is part of the application's transaction and is committed by `conn.commit()`: ```java public static void addOrderItem(int orderId, int productId, short quantity) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:default:connection:"); PreparedStatement ps = conn.prepareStatement( "INSERT INTO order_items (order_id, product_id, quantity, discount_pct) VALUES (?, ?, ?, 0)"); ps.setInt(1, orderId); ps.setInt(2, productId); ps.setShort(3, quantity); ps.executeUpdate(); ps.close(); } ``` ## Cautions ### Precision of return values and OUT parameters CoraDB converts the value returned by Java (or put into an **OUT** parameter) to the SQL type of the call specification, but does not apply its length or precision. A function declared `RETURN CHAR(5)` that returns an 11-character Java string returns all 11 characters; limit the length in the Java code if needed. ### Returning a ResultSet A function that returns a `java.sql.ResultSet` is declared with the return type **CURSOR**. Before returning the result set, cast it to `CORADBResultSet` and call `setReturnable()`: ```sql CREATE FUNCTION low_stock(p_limit INT) RETURN CURSOR AS LANGUAGE JAVA NAME 'OrderSp.lowStock(int) return java.sql.ResultSet'; ``` ```java public static ResultSet lowStock(int limit) throws SQLException { Connection conn = DriverManager.getConnection("jdbc:default:connection:"); PreparedStatement ps = conn.prepareStatement( "SELECT id, name, units_in_stock FROM product WHERE units_in_stock < ? ORDER BY units_in_stock"); ps.setInt(1, limit); ResultSet rs = ps.executeQuery(); ((CORADBResultSet) rs).setReturnable(); return rs; } ``` The caller registers the result as `Types.JAVA_OBJECT` and casts it back to `ResultSet`. Such a function can be called only through a JDBC `CallableStatement`, and a result set cannot be passed as an **IN** argument. ```java CallableStatement cs = conn.prepareCall("? = CALL low_stock(?)"); cs.registerOutParameter(1, Types.JAVA_OBJECT); cs.setInt(2, 5); cs.execute(); ResultSet rs = (ResultSet) cs.getObject(1); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getShort(3)); } rs.close(); ``` ### Collection parameters A collection (**SET**, **MULTISET**, **LIST**) parameter is passed as a Java array. For an **OUT** or **INOUT** collection, the array is wrapped in another array of length 1 (a two-dimensional array), and the method replaces its first element with the new collection: ```sql CREATE PROCEDURE add_tag(tags IN OUT SET, tag STRING) AS LANGUAGE JAVA NAME 'TagSp.addTag(java.lang.Object[][], java.lang.String)'; ``` ```java public static void addTag(Object[][] tags, String tag) { java.util.List list = new java.util.ArrayList<>(); if (tags[0] != null) { list.addAll(java.util.Arrays.asList(tags[0])); } list.add(tag); tags[0] = list.toArray(); } ``` ### Object parameters Object references are passed as `coradb.sql.CORADBOID` values; use the OIDs that the server passes in or that queries return, and declare **OUT** and **INOUT** object parameters as `CORADBOID[]`. Only tables created with **DONT_REUSE_OID** have referable objects. --- # Reserved words Source: https://www.coradb.ai/manual/sql/keyword.html Reserved words have a fixed meaning in CoraDB SQL: they name statements, clauses, operators, functions and data types. A reserved word cannot be used on its own as the name of a table, column, index, view, user-defined variable or other object. ```sql CREATE TABLE shipment (size INT, position INT); ``` ```text ERROR: Syntax error: unexpected 'size' ``` To use a reserved word as a name anyway, quote it with double quotes, square brackets or backticks (see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html#quoted-identifiers)): ```sql CREATE TABLE shipment ("size" INT, [position] INT); ``` A reserved word used as a column name can be written without quotes when it is qualified with a table name or alias, for example `s.size`. The same rules apply to user-defined variables: `@limit` and `@last` are syntax errors, while `@row_limit` and `@last_day` are fine. Many other keywords, such as `NAME`, `STATUS`, `COMMENT`, `PASSWORD`, `RANK`, `OFFSET`, `PATH`, `START`, `TEXT`, `WEEK`, `DIRECTED` and `UNDIRECTED`, are **not** reserved and can be used as names without quotes. ## List of reserved words CoraDB has 393 reserved words. They are not case-sensitive. | | Reserved words | |---|---| | **A** | `ABSOLUTE`, `ACCESS`, `ACTION`, `ADD`, `ADD_MONTHS`, `AES`, `AFTER`, `AGGREGATE_ARR`, `ALL`, `ALLOCATE`, `ALL_SHORTEST`, `ALTER`, `AND`, `ANY`, `ANY_SHORTEST`, `ARE`, `ARIA`, `AS`, `ASC`, `ASSERTION`, `ASYNC`, `AT`, `ATTACH`, `ATTRIBUTE`, `AVG` | | **B** | `BEFORE`, `BENCHMARK`, `BETWEEN`, `BIGINT`, `BINARY`, `BIT`, `BIT_LENGTH`, `BLOB`, `BOOLEAN`, `BOTH`, `BREADTH`, `BY` | | **C** | `CALL`, `CASCADE`, `CASCADED`, `CASE`, `CAST`, `CATALOG`, `CHANGE`, `CHAR`, `CHARACTER`, `CHECK`, `CLASS`, `CLASSES`, `CLOB`, `COALESCE`, `COLLATE`, `COLUMN`, `COMMIT`, `CONNECT`, `CONNECTION`, `CONNECT_BY_ISCYCLE`, `CONNECT_BY_ISLEAF`, `CONNECT_BY_ROOT`, `CONSTRAINT`, `CONSTRAINTS`, `CONTINUE`, `CONVERT`, `CORRESPONDING`, `COUNT`, `CREATE`, `CROSS`, `CURRENT`, `CURRENT_DATE`, `CURRENT_DATETIME`, `CURRENT_TIME`, `CURRENT_TIMESTAMP`, `CURRENT_USER`, `CURSOR`, `CYCLE` | | **D** | `DATA`, `DATABASE`, `DATE`, `DATETIME`, `DATETIMELTZ`, `DATETIMETZ`, `DAY`, `DAY_HOUR`, `DAY_MILLISECOND`, `DAY_MINUTE`, `DAY_SECOND`, `DBTIMEZONE`, `DEALLOCATE`, `DEC`, `DECIMAL`, `DECLARE`, `DEFAULT`, `DEFERRABLE`, `DEFERRED`, `DELETE`, `DEPTH`, `DESC`, `DESCRIBE`, `DESCRIPTOR`, `DIAGNOSTICS`, `DIFFERENCE`, `DISCONNECT`, `DISTINCT`, `DISTINCTROW`, `DIV`, `DO`, `DOMAIN`, `DOUBLE`, `DROP`, `DUPLICATE` | | **E** | `EACH`, `EDGE`, `ELSE`, `ELSEIF`, `EMPTY`, `ENCRYPT`, `END`, `ENUM`, `EQUALS`, `ERROR`, `ESCAPE`, `EVALUATE`, `EXCEPT`, `EXCEPTION`, `EXEC`, `EXECUTE`, `EXISTS`, `EXTERNAL`, `EXTRACT` | | **F** | `FALSE`, `FETCH`, `FILE`, `FIRST`, `FLOAT`, `FOR`, `FORCE`, `FOREIGN`, `FOUND`, `FROM`, `FULL`, `FUNCTION` | | **G** | `GENERAL`, `GET`, `GLOBAL`, `GO`, `GOTO`, `GRANT`, `GRAPH`, `GROUP` | | **H** | `HAVING`, `HORIZONTAL_COUNT`, `HOUR`, `HOUR_MILLISECOND`, `HOUR_MINUTE`, `HOUR_SECOND` | | **I** | `IDENTITY`, `IF`, `IGNORE`, `IMMEDIATE`, `IN`, `INDEX`, `INDICATOR`, `INHERIT`, `INITIALLY`, `INNER`, `INOUT`, `INPUT`, `INSERT`, `INT`, `INTEGER`, `INTERSECT`, `INTERSECTION`, `INTERVAL`, `INTO`, `IS`, `ISOLATION` | | **J** | `JOIN`, `JSON` | | **K** | `KEY`, `KEYLIMIT`, `KILL` | | **L** | `LABEL`, `LABELS`, `LANGUAGE`, `LAST`, `LEADING`, `LEAVE`, `LEFT`, `LESS`, `LEVEL`, `LIKE`, `LIMIT`, `LIST`, `LOCAL`, `LOCALTIME`, `LOCALTIMESTAMP`, `LOCAL_TRANSACTION_ID`, `LOOP`, `LOWER` | | **M** | `MATCH`, `MATCHED`, `MAX`, `MEDIUMINT`, `MERGE`, `METHOD`, `MILLISECOND`, `MIN`, `MINUTE`, `MINUTE_MILLISECOND`, `MINUTE_SECOND`, `MOD`, `MODIFY`, `MODULE`, `MONETARY`, `MONTH`, `MULTISET`, `MULTISET_OF` | | **N** | `NA`, `NAMES`, `NATIONAL`, `NATURAL`, `NCHAR`, `NESTED`, `NEXT`, `NO`, `NONE`, `NOT`, `NULL`, `NULLIF`, `NUMERIC` | | **O** | `OBJECT`, `OCTET_LENGTH`, `OF`, `OFF`, `ON`, `ONLINE`, `ONLY`, `OPTIMIZATION`, `OPTION`, `OPTIONAL`, `OR`, `ORDER`, `ORDINALITY`, `OUT`, `OUTER`, `OUTPUT`, `OVER`, `OVERLAPS` | | **P** | `PARALLEL`, `PARAMETERS`, `PARTIAL`, `PARTITION`, `POSITION`, `PRECISION`, `PREPARE`, `PRESERVE`, `PRIMARY`, `PRIOR`, `PRIVILEGES`, `PROCEDURE`, `PROMOTE` | | **Q** | `QUERY` | | **R** | `READ`, `REAL`, `REBUILD`, `RECURSIVE`, `REF`, `REFERENCES`, `REFERENCING`, `REGEXP`, `RELATIVE`, `RENAME`, `REPLACE`, `RESIGNAL`, `RESTRICT`, `RETURN`, `RETURNS`, `REVOKE`, `RIGHT`, `RLIKE`, `ROLE`, `ROLLBACK`, `ROLLUP`, `ROUTINE`, `ROW`, `ROWNUM`, `ROWS` | | **S** | `SAVEPOINT`, `SCHEMA`, `SCROLL`, `SEARCH`, `SECOND`, `SECOND_MILLISECOND`, `SECTION`, `SELECT`, `SENSITIVE`, `SEQUENCE`, `SEQUENCE_OF`, `SERIALIZABLE`, `SESSION`, `SESSIONTIMEZONE`, `SESSION_USER`, `SET`, `SETEQ`, `SETNEQ`, `SET_OF`, `SHARED`, `SHORT`, `SIBLINGS`, `SIMILAR`, `SIZE`, `SMALLINT`, `SOME`, `SQL`, `SQLCODE`, `SQLERROR`, `SQLEXCEPTION`, `SQLSTATE`, `SQLWARNING`, `STATISTICS`, `STRING`, `SUBCLASS`, `SUBSET`, `SUBSETEQ`, `SUBSTRING`, `SUM`, `SUPERCLASS`, `SUPERSET`, `SUPERSETEQ`, `SYSDATE`, `SYSDATETIME`, `SYSTEM_USER`, `SYSTIME`, `SYSTIMESTAMP`, `SYS_CONNECT_BY_PATH`, `SYS_DATE`, `SYS_DATETIME`, `SYS_TIME`, `SYS_TIMESTAMP` | | **T** | `TABLE`, `TAIL`, `TEMPORARY`, `THEN`, `TIME`, `TIMESTAMP`, `TIMESTAMPLTZ`, `TIMESTAMPTZ`, `TIMEZONE`, `TIMEZONES`, `TIMEZONE_HOUR`, `TIMEZONE_MINUTE`, `TINYINT`, `TO`, `TRAILING`, `TRANSACTION`, `TRANSLATE`, `TRANSLATION`, `TRIGGER`, `TRIM`, `TRUE`, `TRUNCATE` | | **U** | `UNDER`, `UNION`, `UNIQUE`, `UNKNOWN`, `UPDATE`, `UPPER`, `USAGE`, `USE`, `USER`, `USING`, `UTIME` | | **V** | `VACUUM`, `VALUE`, `VALUES`, `VARCHAR`, `VARIABLE`, `VARYING`, `VCLASS`, `VERTEX`, `VIEW` | | **W** | `WHEN`, `WHENEVER`, `WHERE`, `WHILE`, `WITH`, `WITHOUT`, `WORK`, `WRITE` | | **X** | `XOR` | | **Y** | `YEAR`, `YEAR_MONTH` | | **Z** | `ZONE` | > **Tip:** > When you design a schema, avoid reserved words and words that look like SQL keywords. Names such as `order_date`, `item_size` or `user_name` never need quotes. --- # Literals Source: https://www.coradb.ai/manual/sql/literal.html A literal is a constant value written directly in a statement, such as `42`, `'France'` or `DATE'2025-12-31'`. This page shows how to write each kind and which data type it produces. The examples select from `db_root`, a system table with exactly one row. ## Numbers - An **exact** number is written with digits and an optional decimal point. It becomes an `INTEGER`, a `BIGINT` or a `NUMERIC`, depending on its size and whether it has decimals. - An **approximate** number uses scientific notation, with `E` followed by the power of 10. It becomes a `DOUBLE`. - A `+` or `-` sign can precede the number and the exponent. ```sql SELECT TYPEOF(10), TYPEOF(123456789012), TYPEOF(1234234324234.23), TYPEOF(1.2345E15), TYPEOF(-1.2345E-15) FROM db_root; ``` | typeof(10) | typeof(123456789012) | typeof(1234234324234.23) | typeof(1.2345E15) | typeof(-1.2345E-15) | |---|---|---|---|---| | integer | bigint | Numeric (15, 2) | double | double | ## Dates and times Write the type name in front of a quoted string. The type name is not case-sensitive. With these literals you do not need conversion functions such as [TO_DATE](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_date) or [TO_DATETIME](https://www.coradb.ai/manual/sql/function/typecast_fn.html#to_datetime). | Literal | Accepted formats | Example | |---|---|---| | `DATE` | `'YYYY-MM-DD'`, `'MM/DD/YYYY'` | `DATE'2025-12-31'` | | `TIME` | `'HH:MI:SS'`, `'HH:MI:SS AM'`, `'HH:MI:SS PM'` | `TIME'14:30:05'` | | `DATETIME` | `'YYYY-MM-DD HH:MI:SS[.msec] [AM\|PM]'`, `'MM/DD/YYYY HH:MI:SS[.msec] [AM\|PM]'` | `DATETIME'2025-12-31 14:30:05.123'` | | `TIMESTAMP` | `'YYYY-MM-DD HH:MI:SS [AM\|PM]'`, `'MM/DD/YYYY HH:MI:SS [AM\|PM]'` | `TIMESTAMP'2025-12-31 14:30:05'` | `msec` is milliseconds, up to three digits. ```sql SELECT DATE'2025-12-31', DATE'12/31/2025', TIME'02:30:05 PM', DATETIME'12/31/2025 02:30:05.123 PM' FROM db_root; ``` | date '2025-12-31' | date '12/31/2025' | time '02:30:05 PM' | datetime '12/31/2025 02:30:05.123 PM' | |---|---|---|---| | 2025-12-31 | 2025-12-31 | 14:30:05 | 2025-12-31 14:30:05.123 | The e-commerce examples throughout this manual use the ISO form, for example `WHERE order_date >= DATE'2025-12-01'`. ### Dates and times with a time zone The time zone types take the same formats, followed by a time zone: an offset such as `+02:00` or `+02`, or a region name such as `Europe/Bucharest` (see [SHOW TIMEZONES](https://www.coradb.ai/manual/sql/query/show.html#show-timezones)). | Literal | Same as | Stores | |---|---|---| | `DATETIMETZ'...'` | `DATETIME WITH TIME ZONE '...'` | The time and its time zone. | | `DATETIMELTZ'...'` | `DATETIME WITH LOCAL TIME ZONE '...'` | The time in UTC; it is shown in the session's time zone. | | `TIMESTAMPTZ'...'` | `TIMESTAMP WITH TIME ZONE '...'` | The time and its time zone. | | `TIMESTAMPLTZ'...'` | `TIMESTAMP WITH LOCAL TIME ZONE '...'` | The time in UTC; it is shown in the session's time zone. | ```text DATETIMETZ'2025-12-31 14:30:05 +02:00' DATETIMETZ'2025-12-31 14:30:05 Europe/Bucharest' TIMESTAMPTZ'12/31/2025 02:30:05 PM Europe/Bucharest' DATETIME WITH LOCAL TIME ZONE '2025-12-31 14:30:05 +02:00' ``` For how the time zone types behave, see [Date/time types with timezone](https://www.coradb.ai/manual/sql/datatype_datetime.html#datetime-types-with-timezone). ## Bit strings A bit string can be written in binary or in hexadecimal: - Binary: `B'...'` with the digits `0` and `1` in quotes, or `0b` followed by the digits. - Hexadecimal: `X'...'` with hexadecimal digits in quotes, or `0x` followed by the digits. Binary values are padded with zeros on the right to a multiple of 8 bits, and hexadecimal values to a multiple of 2 digits. All the comparisons below are true: ```sql SELECT B'10100000' = X'a0', 0b10100000 = 0xA0, B'1' = X'80', X'a' = X'a0' FROM db_root; ``` | B'10100000'=X'a0' | B'10100000'=X'A0' | B'1'=X'80' | X'a'=X'a0' | |---:|---:|---:|---:| | 1 | 1 | 1 | 1 | ## Character strings Enclose a character string in single quotes. To include a single quote, write it twice: ```sql SELECT 'It''s shipped' FROM db_root; ``` | 'It''s shipped' | |---| | It's shipped | A backslash is an ordinary character by default, so `'C:\temp'` is stored as written. Backslash escape sequences such as `\n` are available only when the [no_backslash_escapes](https://www.coradb.ai/manual/admin/config.html) parameter is set to `no`; see [Escape special characters](https://www.coradb.ai/manual/sql/datatype_string.html#escape-special-characters). Double quotes enclose identifiers, not strings (see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html#quoted-identifiers)). A character set introducer can precede a string and a `COLLATE` clause can follow it, for example `_utf8'Blaye' COLLATE utf8_en_ci`. See [Charset introducer](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-introducer). ## Collections Values of the collection types `SET`, `MULTISET` and `LIST` (also called `SEQUENCE`) are written as elements in braces: ```text {'c', 'c', 'b', 'a'} ``` A brace literal on its own is a `LIST` (`SEQUENCE`), which keeps duplicates and order. Stored in a `SET` column, `{'c', 'c', 'b', 'a'}` becomes `{'a', 'b', 'c'}`: duplicates are removed and the elements sorted. See [Collection types](https://www.coradb.ai/manual/sql/datatype_collection.html#collection-types). ## NULL `NULL` (or `null`) means that there is no value. It is neither `0` nor the empty string `''`. Comparing anything with `NULL` using `=` gives `NULL`, not true or false; use `IS NULL` instead: ```sql SELECT NULL IS NULL, NULL = 0, '' IS NULL FROM db_root; ``` | null is null | null=0 | '' is null | |---:|---:|---:| | 1 | NULL | 0 | ## See also - [Data types](https://www.coradb.ai/manual/sql/datatype.html) - [Identifiers](https://www.coradb.ai/manual/sql/identifier.html) - [Type conversion functions](https://www.coradb.ai/manual/sql/function/typecast_fn.html) --- # Methods and the CALL statement Source: https://www.coradb.ai/manual/sql/method.html A *method* is a function attached to a table. Methods are written in C, loaded dynamically when they are first called, and run with the **CALL** statement; the value they return is passed back to the caller. The system classes `db_user`, `db_authorization` and `db_authorizations` provide the methods used for [user and privilege management](https://www.coradb.ai/manual/sql/authorization.html#user-authorization-management-method); [DB_METHOD](https://www.coradb.ai/manual/sql/catalog_views.html#db_method) lists all methods. For server-side logic written by users, [Java stored functions and procedures](https://www.coradb.ai/manual/sql/jsp.html) are usually the better choice. ## Method types - A **class method** is called on the table itself (the class object). It typically creates or looks up rows, or reads and updates [class attributes](https://www.coradb.ai/manual/sql/oodb.html#class-attribute-and-method). `find_user` is a class method of `db_user`. - An **instance method** is called on one row (an instance). It typically computes or updates values of that row. `set_password` is an instance method of `db_user`, called on a user object. Subclasses inherit the class and instance methods of their superclasses. Name conflicts between methods are resolved like those between columns; see [Table inheritance](https://www.coradb.ai/manual/sql/oodb.html#class-conflict-resolution). ## CALL ```sql CALL method_name ( [ argument [, argument ...] ] ) ON call_target [ { TO | INTO } variable ]; CALL method_name ( call_target [, argument ...] ) [ { TO | INTO } variable ]; call_target ::= CLASS table_name | object_expression ``` - *method_name* is a method of the target's table or a system method. Methods without arguments are called with empty parentheses. - To call a class method, put **CLASS** before the table name: `ON CLASS db_user`. - To call an instance method, give an expression that evaluates to a row object, typically a session variable that received the object from an earlier call. In the second form, the object is the first argument. - **TO** or **INTO** stores the returned value in a session variable, which can be used as a target or argument of later calls and read in queries such as `SELECT variable FROM db_root`. - A method call can be the target or an argument of another call. ```sql -- class method: look up a user and keep the object in u CALL find_user ('dba') ON CLASS db_user INTO u; SELECT u.name FROM db_root; -- DBA -- instance method, both forms CALL add_user ('user_5', '') ON CLASS db_user TO v; CALL set_password ('abc') ON v; CALL set_password (v, 'abc'); ``` --- # Table inheritance: UNDER, INHERIT and superclasses Source: https://www.coradb.ai/manual/sql/oodb.html A CoraDB table can be created as a *subclass* of one or more existing tables, its *superclasses*. The subclass inherits all their columns, constraints such as primary keys, and methods, and can add columns of its own. This is called *inheritance*; in this page a table is also called a *class* and a column an *attribute*, the terms used by the catalog. ```sql CREATE TABLE b2b_order UNDER orders (po_number VARCHAR(20)); ``` `b2b_order` has the six columns of `orders` followed by `po_number` (see [DB_ATTRIBUTE](https://www.coradb.ai/manual/sql/catalog_views.html#db_attribute), whose `from_class_name` shows where each column comes from). The primary key `pk_orders_id` and the foreign key on `customer_id` are inherited too: the primary key index is shared, so an `id` must be unique across `orders` and `b2b_order` together. - A subclass name must be unique and its superclasses must exist. - Encryption (TDE) of a table is not inherited; see [Table encryption (TDE)](https://www.coradb.ai/manual/sql/schema/table_stmt.html#table-encryption-tde). - Inheritance is available for ordinary tables. Vertex and edge tables of a graph are not part of it. ## Querying a hierarchy By default a query on a table reads only that table's rows. **ALL** includes the rows of all its subclasses, **ONLY** states the default explicitly, and **ALL** … **(EXCEPT** … **)** leaves out some subclasses: ```sql INSERT INTO b2b_order (id, customer_id, shipping_cost, ship_address, order_date, po_number) VALUES (90001, 102, 12.50, '1 Main St', DATE'2026-11-01', 'PO-7781'); SELECT COUNT(*) FROM orders; -- 2910 SELECT COUNT(*) FROM ONLY orders; -- 2910 SELECT COUNT(*) FROM ALL orders; -- 2911 SELECT COUNT(*) FROM ALL orders (EXCEPT b2b_order); -- 2910 ``` A query through a superclass can use only the columns the superclass defines; read `po_number` from `b2b_order` itself. **UPDATE** and **DELETE** accept **ALL** in the same way. ## Class attributes A *class attribute* belongs to the table itself rather than to its rows, and has one value per table. It is declared with **CLASS ATTRIBUTE** before the column list and read and changed with **SELECT … FROM CLASS** and **UPDATE CLASS**: ```sql CREATE TABLE promo CLASS ATTRIBUTE (active_count INT) (code VARCHAR(16), pct SHORT); UPDATE CLASS promo SET active_count = 3; SELECT active_count FROM CLASS promo; -- 3 ``` A subclass inherits the class attribute but stores its own value: after `CREATE TABLE promo_vip UNDER promo`, `UPDATE CLASS promo_vip SET active_count = 7` leaves `promo` at 3. A class attribute can have the same name as a column of the same table. ## Column order - A table without superclasses has its columns in the order of the **CREATE TABLE** statement. - In a subclass, the inherited columns come first, in the order of their superclass, followed by the subclass's own columns. With several superclasses, the superclasses are taken in the order of the **UNDER** clause. - A column that reaches the subclass through several paths from the same original table is inherited once. - A column renamed with **INHERIT** … **AS** keeps the position of the original column. ## Multiple inheritance and the INHERIT clause A table can have several superclasses. If two of them have a column (or method) with the same name, the subclass cannot have both under that name; **CREATE TABLE** then fails until the conflict is resolved with **INHERIT**: ```sql CREATE TABLE contact_info (name VARCHAR(40), phone VARCHAR(20)); CREATE TABLE shipping_info (name VARCHAR(60), ship_address VARCHAR(128)); CREATE TABLE partner UNDER contact_info, shipping_info; ``` ```text ERROR: Name conflict on attribute "name" with classes "contact_info" and "shipping_info". ``` ```sql INHERIT resolution [, resolution ...] resolution ::= { column_name | method_name } OF superclass_name [ AS alias ] ``` **INHERIT** names the superclass whose column is inherited. With **AS**, a second column of the same name is inherited too, under another name: ```sql CREATE TABLE partner UNDER contact_info, shipping_info INHERIT name OF contact_info; ALTER TABLE partner INHERIT name OF shipping_info AS ship_name; SELECT attr_name, from_class_name, from_attr_name, prec FROM db_attribute WHERE class_name = 'partner' ORDER BY def_order; ``` | attr_name | from_class_name | from_attr_name | prec | |---|---|---|---| | name | contact_info | NULL | 40 | | phone | contact_info | NULL | 20 | | ship_name | shipping_info | name | 60 | | ship_address | shipping_info | NULL | 128 | The **INHERIT** clause can follow **CREATE TABLE … UNDER**, **ALTER TABLE … ADD SUPERCLASS**, **ALTER TABLE … DROP SUPERCLASS**, or stand alone in **ALTER TABLE**. ### Compatible domains Two inherited columns with the same name must have compatible types, even when **INHERIT** picks one of them: ```sql CREATE TABLE p1 (phone INT); CREATE TABLE p2 (phone VARCHAR(20)); CREATE TABLE p3 UNDER p1, p2 INHERIT phone OF p2; ``` ```text ERROR: Class "p3" has incompatible domains for "phone", inherited from classes "p2" and "p1". ``` When the two columns are object references to tables of the same hierarchy, the subclass inherits the one whose type is lower in the hierarchy (the more specific one). ## ADD SUPERCLASS ```sql ALTER TABLE table_name ADD SUPERCLASS superclass_name [, superclass_name ...] [ INHERIT resolution [, resolution ...] ]; ``` Adding a superclass to an existing table adds the superclass's columns to it: ```sql CREATE TABLE vendor (vendor_code VARCHAR(10)); ALTER TABLE vendor ADD SUPERCLASS contact_info; -- vendor: name, phone (from contact_info), vendor_code ``` ## DROP SUPERCLASS ```sql ALTER TABLE table_name DROP SUPERCLASS superclass_name [, superclass_name ...] [ INHERIT resolution [, resolution ...] ]; ``` Dropping a superclass removes the columns inherited from it (`ALTER TABLE vendor DROP SUPERCLASS contact_info` leaves `vendor` with `vendor_code` only). If a column chosen with **INHERIT** came from the dropped superclass and another superclass has a column of the same name, name the replacement in the same statement: ```sql CREATE TABLE a_tbl (a INT PRIMARY KEY, b INT); CREATE TABLE b_tbl (a INT PRIMARY KEY, b INT, c INT); CREATE TABLE c_tbl (b INT PRIMARY KEY, d INT); CREATE TABLE a_b_c UNDER a_tbl, b_tbl, c_tbl INHERIT a OF b_tbl, b OF b_tbl; -- a_b_c: a, b, c (from b_tbl), d (from c_tbl) ALTER TABLE a_b_c DROP SUPERCLASS b_tbl INHERIT b OF a_tbl; -- a_b_c: a, b (from a_tbl), d (from c_tbl) ``` `a` needs no clause here, because after `b_tbl` is gone only `a_tbl` provides it. ## Schema changes in a hierarchy Changes to a superclass propagate to all its subclasses. The following changes can create or remove name conflicts in subclasses: - Adding or dropping a column or method - Adding or dropping a superclass - Dropping a table CoraDB keeps the schema consistent by resolving such conflicts in the subclasses: - A column or method defined in a subclass takes precedence over an inherited one with the same name. - A resolution chosen with **INHERIT** is kept as long as it remains valid. When it becomes invalid, for example because the chosen column was dropped, CoraDB picks another column of the same name from the remaining superclasses. - When a column added to a superclass has the same name as a column a subclass already inherits from another superclass, CoraDB resolves the conflict automatically. In the following example, `partner` then inherits `ship_address` from `contact_info`, its first superclass, instead of `shipping_info`: ```sql CREATE TABLE partner UNDER contact_info, shipping_info INHERIT name OF contact_info; ALTER TABLE contact_info ADD ATTRIBUTE ship_address VARCHAR(128); ``` Check `db_attribute.from_class_name` after such changes, and use `ALTER TABLE … INHERIT … OF …` to choose a different source. - A change in a subclass never changes its superclasses. - A table can be dropped even if columns of other tables use it as their type; those columns then refer to the general type `object`. Because automatic resolutions depend on the order of superclasses and the history of changes, avoid reusing the same column names across superclasses of one table, and resolve conflicts explicitly with **INHERIT** when they cannot be avoided. ### Schema invariants CoraDB preserves these properties of the schema across every change: - **Class hierarchy**: the tables form a directed acyclic graph with the system class `object` at its root. A table cannot be its own superclass, directly or indirectly, and a table without superclasses is a direct subclass of `object`. - **Names**: table names are unique, and the names of columns and methods are unique within a table. **INHERIT … AS** gives an inherited column a new name to keep this rule. - **Inheritance**: a subclass inherits every column and method of its superclasses, except where a name conflict is resolved. A column inherited from the same original table through several paths is inherited once; columns with the same name but different origins need a resolution. - **Domains**: the type of an inherited object-reference column can be narrowed in a subclass to a subclass of the original type, and widened again, but not beyond the superclass's type. --- # Table partitioning: RANGE, HASH and LIST Source: https://www.coradb.ai/manual/sql/partition.html *Partitioning* divides one table into several physical parts, the *partitions*, each holding the rows whose *partitioning key* falls into its range or list, or hashes to it. Applications keep using the table as before: **INSERT**, **UPDATE**, **DELETE** and **SELECT** statements name the partitioned table, and CoraDB places and finds the rows in the right partitions. Partitioning helps with large tables: - **Faster queries.** A query that filters on the partitioning key only reads the partitions that can contain matching rows ([partition pruning](https://www.coradb.ai/manual/sql/partition.html#partition-pruning)). - **Easier data management.** Old data can be removed by dropping a partition, or detached as its own table by promoting it, instead of deleting rows one by one. - **Smaller indexes.** Every index is local to its partition, which also spreads I/O. How it works: - Each partition is stored as a table of its own, a subclass of the partitioned table, named `
__p__`. - **INSERT** puts each row into the partition that matches its key. A row that matches no partition is rejected with `Appropriate partition does not exist.` - **UPDATE** moves a row to another partition when its key changes. - The partitions of a table are listed in the catalog view [db_partition](https://www.coradb.ai/manual/sql/catalog_views.html#db_partition) and shown by **SHOW CREATE TABLE**. Partitioning pays off for large tables; what "large" means depends on the application and its queries. Choose [range](https://www.coradb.ai/manual/sql/partition.html#range-partitioning), [list](https://www.coradb.ai/manual/sql/partition.html#list-partitioning) or [hash](https://www.coradb.ai/manual/sql/partition.html#hash-partitioning) partitioning by how the table is queried and how its data is distributed, and read the [notes](https://www.coradb.ai/manual/sql/partition.html#notes-on-partitioning) below. ## Partitioning key The partitioning key is a column, or an expression on one column, whose value decides the partition of each row. - It uses exactly one column of the table (`Only one column can be specified as partition column.`). - The column must be of type **CHAR**, **VARCHAR**, **SMALLINT**, **INT**, **BIGINT**, **DATE**, **TIME**, **TIMESTAMP** or **DATETIME** (`Unsupported partition column type.` otherwise, for example for **NUMERIC**). - The expression cannot contain aggregate or analytic functions, logical or comparison operators, or any of these: **CASE**, **CHARSET**, **CHR**, **COALESCE**, **DECODE**, **DECR**, **INCR**, **DRAND**, **DRANDOM**, **GREATEST**, **LEAST**, **IF**, **IFNULL**, **INSTR**, **NVL**, **NVL2**, **ROWNUM**, **INST_NUM**, **USER**, **PRIOR**, **WIDTH_BUCKET**, **SERIAL_CURRENT_VALUE**, **SERIAL_NEXT_VALUE** (`Invalid partition definition.`). - The expression can be at most 1,024 bytes long. - The partitioning column must be part of every unique index, including the primary key; see [Indexes on partitioned tables](https://www.coradb.ai/manual/sql/partition.html#indexes-on-partitioned-tables). A typical key is `YEAR(order_date)` for an orders table. ## Range partitioning Range partitioning assigns each partition a continuous, non-overlapping range of key values. It suits data that is naturally divided into intervals, such as order dates, and it gives the best [pruning](https://www.coradb.ai/manual/sql/partition.html#partition-pruning), because both range and equality conditions can be used. ```sql CREATE TABLE table_name ( ... ) PARTITION BY RANGE ( partitioning_key ) ( PARTITION partition_name VALUES LESS THAN ( range_value | MAXVALUE ) [COMMENT 'comment'], ... ); ALTER TABLE table_name PARTITION BY RANGE ( partitioning_key ) ( ... ); ``` - A partition holds the rows whose key is less than its *range_value* and at least the *range_value* of the previous partition. CoraDB sorts the partitions by *range_value*. - **MAXVALUE** gives the last partition no upper limit. - A row whose key is **NULL** goes to the partition with the smallest range. - **ALTER TABLE … PARTITION BY** partitions an existing table. The following table keeps an archive of e-commerce orders by year: ```sql CREATE TABLE order_archive ( id INT, customer_id INT, order_date DATE, shipping_cost NUMERIC(10,2) ) PARTITION BY RANGE (YEAR(order_date)) ( PARTITION before_2023 VALUES LESS THAN (2023) COMMENT 'orders 2021-2022', PARTITION y2023 VALUES LESS THAN (2024), PARTITION y2024 VALUES LESS THAN (2025) ); INSERT INTO order_archive SELECT id, customer_id, order_date, shipping_cost FROM orders WHERE order_date < DATE'2025-01-01'; -- 2,124 rows ``` | Partition | Range of YEAR(order_date) | Rows | |---|---|---| | before_2023 | Below 2023 | 898 | | y2023 | 2023 | 551 | | y2024 | 2024 | 675 | Orders from 2025 have no partition yet, so `INSERT INTO order_archive … WHERE order_date >= DATE'2025-01-01'` fails with `Appropriate partition does not exist.` until a partition is [added](https://www.coradb.ai/manual/sql/partition.html#adding-partitions). ## Hash partitioning Hash partitioning spreads rows over a fixed number of partitions by a hash of the key. It suits keys for which ranges or lists have no meaning, such as customer IDs; with evenly distributed key values, the partitions are about the same size. Pruning works only for equality conditions (`=`, **IN**), so hash partitioning helps mainly when most queries look up single key values. ```sql CREATE TABLE table_name ( ... ) PARTITION BY HASH ( partitioning_key ) PARTITIONS number_of_partitions; ALTER TABLE table_name PARTITION BY HASH ( partitioning_key ) PARTITIONS number_of_partitions; ``` Partitions are named `p0`, `p1`, and so on. A row whose key is **NULL** goes to the first partition. Comments cannot be given to hash partitions. ```sql CREATE TABLE customer_h ( id INT PRIMARY KEY, company_name VARCHAR(64) ) PARTITION BY HASH (id) PARTITIONS 4; INSERT INTO customer_h SELECT id, company_name FROM customer; -- 1,000 rows, about 250 per partition ``` ## List partitioning List partitioning assigns each partition an explicit list of key values. The lists must not overlap. It suits keys with a small set of meaningful values, such as country codes. As with hash partitioning, pruning works only for equality conditions. ```sql CREATE TABLE table_name ( ... ) PARTITION BY LIST ( partitioning_key ) ( PARTITION partition_name VALUES IN ( value [, value ...] ) [COMMENT 'comment'], ... ); ALTER TABLE table_name PARTITION BY LIST ( partitioning_key ) ( ... ); ``` ```sql CREATE TABLE city_l (id INT, name VARCHAR(32), country_code VARCHAR(8)) PARTITION BY LIST (country_code) ( PARTITION europe VALUES IN ('AUT','BEL','CHE','DEU','DNK','ESP','FIN','FRA','GBR','IRL','ITA','NLD','NOR','POL','PRT','SWE') COMMENT 'EU, UK, CH, NO', PARTITION americas VALUES IN ('ARG','BRA','CAN','MEX','USA','VEN'), PARTITION asia_pacific VALUES IN ('AUS','JPN','SGP') ); INSERT INTO city_l SELECT id, name, country_code FROM city; -- europe 70, americas 40, asia_pacific 5 ``` A key value that is in no list is rejected, and **NULL** is no exception: to accept **NULL** keys, include `NULL` in one of the lists, for example `VALUES IN ('AUS','JPN','SGP', NULL)`. ### Partition comments Range and list partitions can have a comment (`COMMENT '…'` after the partition definition); hash partitions cannot. Comments are shown by **SHOW CREATE TABLE** and in [db_partition](https://www.coradb.ai/manual/sql/catalog_views.html#db_partition): ```sql SELECT partition_name, partition_class_name, partition_type, comment FROM db_partition WHERE class_name = 'order_archive' ORDER BY partition_name; ``` For the table above: | partition_name | partition_class_name | partition_type | comment | |---|---|---|---| | before_2023 | order_archive__p__before_2023 | RANGE | orders 2021-2022 | | y2023 | order_archive__p__y2023 | RANGE | NULL | | y2024 | order_archive__p__y2024 | RANGE | NULL | In corasql, the session command `;schema order_archive` shows the partitions as well. ## Partition pruning *Partition pruning* limits a query to the partitions that can contain matching rows. CoraDB examines the **WHERE** clause when the query is executed and skips every partition for which the condition is always false. This reduces disk I/O and the number of rows processed. Pruning happens only when: - The partitioning key expression appears in the **WHERE** clause exactly as it was defined, not wrapped in another expression; - For range partitioning, it is used in a range condition (`<`, `>`, **BETWEEN**, …) or an equality condition (`=`, **IN**); - For list and hash partitioning, it is used in an equality condition. With `order_archive` partitioned by `YEAR(order_date)` (one partition per year 2021–2025, 2,910 rows in all), [SHOW TRACE](https://www.coradb.ai/manual/sql/tuning_plan.html#query-profiling) shows how many rows each query reads: ```sql SET TRACE ON; SELECT COUNT(*) FROM order_archive WHERE YEAR(order_date) >= 2024; SHOW TRACE; ``` ```text Trace Statistics: SELECT (time: 0, fetch: 14, ioread: 0) SCAN (table: order_archive), (heap time: 0, fetch: 7, ioread: 0, readrows: 1461, rows: 1461) ``` Only the partitions for 2024 and 2025 are read (1,461 rows). The same filter written on the column itself does not use the key expression, so all partitions are read: ```sql SELECT COUNT(*) FROM order_archive WHERE order_date >= DATE'2024-01-01'; SHOW TRACE; ``` ```text SCAN (table: order_archive), (heap time: 0, fetch: 13, ioread: 0, readrows: 2910, rows: 1461) ``` More cases: | Condition | Partitions read | Rows read | |---|---|---| | `YEAR(order_date) = 2023` | y2023 | 551 | | `YEAR(order_date) BETWEEN 2022 AND 2023` | y2022, y2023 | 1,033 | | `order_date = DATE'2023-06-01'` | All: the key expression is not used | 2,910 | | `YEAR(order_date) + 1 = 2024` | All: the key is wrapped in another expression | 2,910 | | `YEAR(order_date) <> 2023` | All: no usable condition | 2,910 | Pruning is done at execution time, so the query plan does not show which partitions are skipped. ### Accessing a partition directly A partition can be queried on its own, either through the **PARTITION** clause or by the name of its table: ```sql SELECT COUNT(*) FROM order_archive PARTITION (y2023); -- 551 SELECT COUNT(*) FROM order_archive__p__y2023; -- 551 ``` The query then sees only that partition, regardless of its **WHERE** clause, and an **INSERT** or **UPDATE** fails if the row does not belong to the partition. This can be useful for optimizations that are not available on partitioned tables (see [Restrictions](https://www.coradb.ai/manual/sql/partition.html#restrictions-on-partitioned-tables)), but applications that name partitions lose the main benefit of partitioning: that partitions can be reorganized without changing the application. Inserting through a partition brings no performance gain. ## Partitioning management Partitions are managed with clauses of **ALTER TABLE**: | Task | Clause | Range | List | Hash | |---|---|---|---|---| | [Add partitions](https://www.coradb.ai/manual/sql/partition.html#adding-partitions) | **ADD PARTITION** | ✓ | ✓ | ✓ (number of partitions) | | [Drop partitions and their data](https://www.coradb.ai/manual/sql/partition.html#dropping-partitions) | **DROP PARTITION** | ✓ | ✓ | | | [Split or merge partitions](https://www.coradb.ai/manual/sql/partition.html#partition-reorganization) | **REORGANIZE PARTITION** | ✓ | ✓ | | | [Reduce the number of partitions](https://www.coradb.ai/manual/sql/partition.html#hash-partitioning-reorganization) | **COALESCE PARTITION** | | | ✓ | | [Turn partitions into tables](https://www.coradb.ai/manual/sql/partition.html#partition-promotion) | **PROMOTE PARTITION** | ✓ | ✓ | | | [Remove partitioning](https://www.coradb.ai/manual/sql/partition.html#modifying-a-partitioned-table-into-a-regular-table) | **REMOVE PARTITIONING** | ✓ | ✓ | ✓ | These statements move data between partitions where needed, which can take a long time on large tables. Plan them accordingly. ### Adding partitions ```sql ALTER TABLE table_name ADD PARTITION ( partition_definition [, partition_definition ...] ); ``` ```sql ALTER TABLE order_archive ADD PARTITION ( PARTITION y2025 VALUES LESS THAN (2026), PARTITION later VALUES LESS THAN MAXVALUE ); INSERT INTO order_archive SELECT id, customer_id, order_date, shipping_cost FROM orders WHERE order_date >= DATE'2025-01-01'; -- 786 rows, all in y2025 ``` - The table must already be partitioned. - For range partitioning, new ranges must be above all existing ones (`Partition addition is to set with a bigger range than the existing.`). Once a partition has **MAXVALUE**, use [REORGANIZE PARTITION](https://www.coradb.ai/manual/sql/partition.html#partition-reorganization) to split it instead. - For hash partitioning, see [Hash partitioning reorganization](https://www.coradb.ai/manual/sql/partition.html#hash-partitioning-reorganization). ### Dropping partitions ```sql ALTER TABLE table_name DROP PARTITION partition_name [, partition_name ...]; ``` ```sql ALTER TABLE order_archive DROP PARTITION later; ``` - All rows in a dropped partition are deleted; the number of deleted rows is not reported. To keep the data, [reorganize](https://www.coradb.ai/manual/sql/partition.html#partition-reorganization) or [promote](https://www.coradb.ai/manual/sql/partition.html#partition-promotion) the partition instead; to delete rows but keep the partition, use **DELETE**. - At least one partition must remain. - Not available for hash partitioning (`Invalid partition requests.`); use **COALESCE PARTITION**. ### Partition reorganization **REORGANIZE PARTITION** splits one partition into several or merges several into one. Rows are moved to match the new definitions. ```sql ALTER TABLE table_name REORGANIZE PARTITION partition_name [, partition_name ...] INTO ( partition_definition [, partition_definition ...] ); ``` Split `before_2023` into one partition per year, then merge them again: ```sql ALTER TABLE order_archive REORGANIZE PARTITION before_2023 INTO ( PARTITION y2021 VALUES LESS THAN (2022), -- 416 rows PARTITION y2022 VALUES LESS THAN (2023) -- 482 rows ); ALTER TABLE order_archive REORGANIZE PARTITION y2021, y2022 INTO ( PARTITION before_2023 VALUES LESS THAN (2023) ); ``` Split the American cities of `city_l`: ```sql ALTER TABLE city_l REORGANIZE PARTITION americas INTO ( PARTITION north_america VALUES IN ('CAN','MEX','USA'), -- 25 rows PARTITION south_america VALUES IN ('ARG','BRA','VEN') -- 15 rows ); ``` - Only range and list partitions can be reorganized, and the partitioning method cannot be changed. - For range partitioning, only adjacent partitions can be merged. ### Hash partitioning reorganization The partitions of a hash-partitioned table cannot be named individually; you can only change their number. No data is lost, but all rows are redistributed, because the hash function changes with the number of partitions. ```sql ALTER TABLE table_name COALESCE PARTITION number_to_remove; ALTER TABLE table_name ADD PARTITION PARTITIONS number_to_add; ``` ```sql ALTER TABLE customer_h COALESCE PARTITION 1; -- 4 → 3 partitions ALTER TABLE customer_h ADD PARTITION PARTITIONS 3; -- 3 → 6 partitions, still 1,000 rows ``` ### Partition promotion **PROMOTE PARTITION** detaches range or list partitions and turns them into regular tables, named like the partition tables (`
__p__`). This is useful for historical data that is rarely used: the partitioned table becomes smaller, and the old data stays available. Promotion cannot be undone. ```sql ALTER TABLE table_name PROMOTE PARTITION partition_name [, partition_name ...]; ``` ```sql ALTER TABLE order_archive PROMOTE PARTITION before_2023; SELECT COUNT(*) FROM order_archive__p__before_2023; -- 898: now a regular table SELECT COUNT(*) FROM order_archive; -- 2,012: 2023 to 2025 only ``` The promoted table keeps its data and ordinary indexes. It does not keep primary keys, foreign keys, unique indexes, **AUTO_INCREMENT** attributes and serials, triggers, methods, or inheritance relationships. Hash partitions cannot be promoted. ### Removing partitioning **REMOVE PARTITIONING** turns a partitioned table back into a regular table. All rows are moved from the partitions into the table, which can take a long time. ```sql ALTER TABLE order_archive REMOVE PARTITIONING; ``` ## Indexes on partitioned tables All indexes on a partitioned table are *local*: each partition has its own part of every index. Local indexes are smaller, which makes inserts faster, and transactions working on different partitions use different index structures. A scan of a partition never reads index entries of other partitions. To keep unique indexes local, the partitioning column must be part of the primary key and of every unique index: ```sql CREATE TABLE customer_h (id INT PRIMARY KEY, company_name VARCHAR(64)) PARTITION BY HASH (id) PARTITIONS 4; CREATE UNIQUE INDEX u_customer_h_name ON customer_h (company_name); ``` ```text ERROR: Partition key attributes must be present in the index key. ``` `CREATE UNIQUE INDEX u_customer_h_name ON customer_h (company_name, id)` is accepted. ## Notes on partitioning ### Statistics on partitioned tables CoraDB keeps statistics for each partition. The statistics of the partitioned table are the average of its partitions' statistics, which suits the common case of a query that is pruned to one partition. See [Updating statistics](https://www.coradb.ai/manual/sql/tuning.html). ### Restrictions on partitioned tables - A table can have at most 1,024 partitions (`Invalid partition size.` for more). - Partitions cannot take part in inheritance: no table can inherit from a partition, and a partition inherits only from its partitioned table. - These optimizations are not used on partitioned tables: skipping **ORDER BY** ([Optimizing ORDER BY clause](https://www.coradb.ai/manual/sql/tuning_index_opt.html#optimizing-order-by-clause)), skipping **GROUP BY** ([Optimizing GROUP BY clause](https://www.coradb.ai/manual/sql/tuning_index_opt.html#optimizing-group-by-clause)), multiple key ranges ([Multiple key ranges optimization](https://www.coradb.ai/manual/sql/tuning_index_opt.html#multiple-key-ranges-optimization)), and index join. ### Partitioning key, character set and collation The values in partition definitions must use the character set of the key column: ```sql CREATE TABLE t (c CHAR(50) COLLATE utf8_bin) PARTITION BY LIST (c) ( PARTITION p0 VALUES IN (_utf8'x'), PARTITION p1 VALUES IN (_iso88591'y') ); ``` ```text ERROR: Invalid codeset '_iso88591' for partition value. Expecting '_utf8' codeset. ``` Key values are compared with the collation of the key column. In a case-insensitive collation `'test'` and `'TEST'` are the same value, so they cannot be in different partitions: ```sql CREATE TABLE t (c STRING) COLLATE utf8_en_ci PARTITION BY LIST (c) ( PARTITION p0 VALUES IN ('test'), PARTITION p1 VALUES IN ('TEST') ); ``` ```text ERROR: Partition definition is duplicated. 'p1' ``` --- # Data manipulation statements (DML) Source: https://www.coradb.ai/manual/sql/query.html Data manipulation statements read and change the rows stored in tables. In CoraDB they work on relational tables and on the vertex and edge tables of a graph alike; graph data can also be queried with [MATCH](https://www.coradb.ai/manual/graph/match.html) patterns inside a `SELECT`. All examples in this section use the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). ## Reading data | Statement | What it does | |---|---| | [SELECT](https://www.coradb.ai/manual/sql/query/select.html) | Returns rows from tables, views, subqueries and graph patterns. | | [WITH (CTE)](https://www.coradb.ai/manual/sql/query/cte.html) | Names intermediate results for one statement; `WITH RECURSIVE` builds rows step by step. | | [Hierarchical queries](https://www.coradb.ai/manual/sql/query/hq.html) | Walks tree-structured data with `START WITH ... CONNECT BY`. | ## Changing data | Statement | What it does | |---|---| | [INSERT](https://www.coradb.ai/manual/sql/query/insert.html) | Adds rows from values or a query; `ON DUPLICATE KEY UPDATE` turns a conflicting insert into an update. `INSERT VERTEX` and `INSERT EDGE` add graph data. | | [UPDATE](https://www.coradb.ai/manual/sql/query/update.html) | Changes column values in one table or, through a join, in several tables. | | [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html) | Inserts rows, first deleting any existing row with the same primary key or unique value. | | [DELETE](https://www.coradb.ai/manual/sql/query/delete.html) | Removes the rows that match a condition, from one or several tables. | | [MERGE](https://www.coradb.ai/manual/sql/query/merge.html) | Updates, deletes or inserts target rows depending on whether they match a source. | | [TRUNCATE](https://www.coradb.ai/manual/sql/query/truncate.html) | Removes every row of a table and resets its `AUTO_INCREMENT` counter. | ## Other statements | Statement | What it does | |---|---| | [PREPARE, EXECUTE, DEALLOCATE](https://www.coradb.ai/manual/sql/query/prepare.html) | Compiles a statement once and runs it with different parameter values. | | [DO](https://www.coradb.ai/manual/sql/query/do.html) | Evaluates an expression without returning a result. | Changes made by these statements become permanent when the transaction commits. See [Transactions](https://www.coradb.ai/manual/sql/transaction.html) for commit, rollback and isolation levels. --- # Common table expressions (WITH) Source: https://www.coradb.ai/manual/sql/query/cte.html A common table expression (CTE) is a named subquery defined at the start of a statement with the **WITH** clause. The rest of the statement can refer to it like a table, as many times as needed. CTEs break a long query into readable steps, let one step build on another, and, with **RECURSIVE**, generate rows by repeating a query on its own output. A CTE exists only for the statement that defines it. > **Try it yourself:** > Every example on this page runs on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html), and the results shown are the real output. Connect with `corasql -u dba e-commerce` and paste any query. ## Syntax ```text WITH [RECURSIVE] cte_name [(column_name, ...)] AS () [, cte_name [(column_name, ...)] AS () ...] ``` - *cte_name*: the name the statement uses to refer to the CTE. Names must be unique within one `WITH` clause. - *column_name*: optional names for the CTE's columns. Their number must match the subquery's columns. - *subquery*: the query that defines the CTE. It can refer to CTEs defined earlier in the same `WITH` clause. - **RECURSIVE**: allows a CTE to refer to itself (see [Recursive CTEs](https://www.coradb.ai/manual/sql/query/cte.html#recursive-ctes)). - *statement*: the statement that uses the CTEs: a `SELECT`, or one of the statements listed in [CTEs in other statements](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements). ## Chaining CTEs Each CTE can build on the ones before it. The query below first computes the value of every 2025 order, then sums those values per customer, and finally joins the totals with the customer names: ```sql WITH order_totals AS ( SELECT o.id, o.customer_id, SUM(oi.quantity * p.unit_price * (100 - oi.discount_pct) / 100) AS total FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN product p ON p.id = oi.product_id WHERE o.order_date BETWEEN DATE'2025-01-01' AND DATE'2025-12-31' GROUP BY o.id, o.customer_id), customer_totals AS ( SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent FROM order_totals GROUP BY customer_id) SELECT c.company_name, ct.orders, ct.spent FROM customer_totals ct JOIN customer c ON c.id = ct.customer_id ORDER BY ct.spent DESC LIMIT 5; ``` | company_name | orders | spent | |---|---:|---:| | Young and Sons | 13 | 6938.50 | | Mayer, Carroll and Owens | 11 | 5252.00 | | Price, Whitney and Carr | 8 | 5242.55 | | Johnson and Sons | 7 | 4773.24 | | Gallagher-Cohen | 8 | 4497.20 | A statement can also use several independent CTEs side by side: ```sql WITH frequent AS ( SELECT customer_id FROM orders GROUP BY customer_id HAVING COUNT(*) >= 39), last_orders AS ( SELECT customer_id, MAX(order_date) AS last_order FROM orders GROUP BY customer_id) SELECT f.customer_id, l.last_order FROM frequent f JOIN last_orders l ON l.customer_id = f.customer_id ORDER BY f.customer_id; ``` | customer_id | last_order | |---:|---| | 440 | 2025-12-27 | | 444 | 2025-09-06 | | 812 | 2025-12-10 | ## CTE column names Name the CTE's columns after its name. The list must have as many names as the subquery has columns. The CTE below, which reads graph data through the `part_of` edges, returns each category with its number of products and highest price: ```sql WITH category_prices (category, products, top_price) AS ( SELECT c.name, COUNT(*), MAX(p.unit_price) FROM MATCH (p:product)-[:part_of]->(c:category) GROUP BY c.name) SELECT * FROM category_prices ORDER BY top_price DESC LIMIT 3; ``` | category | products | top_price | |---|---:|---:| | Beverages | 12 | 263.50 | | Meat/Poultry | 6 | 123.79 | | Jackets | 362 | 99.00 | Without a column list, the columns take the names of the subquery's select list. Expressions without an alias are named after their text, which is awkward to refer to: ```sql WITH category_prices AS ( SELECT c.name, COUNT(*), MAX(p.unit_price) FROM MATCH (p:product)-[:part_of]->(c:category) GROUP BY c.name) SELECT * FROM category_prices ORDER BY 3 DESC LIMIT 3; ``` | name | count(*) | max(p.unit_price) | |---|---:|---:| | Beverages | 12 | 263.50 | | Meat/Poultry | 6 | 123.79 | | Jackets | 362 | 99.00 | ## Recursive CTEs With **WITH RECURSIVE**, a CTE can refer to itself. A recursive CTE has two parts joined by `UNION ALL`: - The **non-recursive part**, which produces the starting rows; - The **recursive part**, which refers to the CTE by name and produces new rows from the rows of the previous step. CoraDB evaluates it like this: 1. Run the non-recursive part and add its rows to the result. 2. Run the recursive part on the rows produced by the previous step and add the new rows to the result. 3. Repeat step 2 until a step produces no rows, or until the [maximum number of recursions](https://www.coradb.ai/manual/sql/query/cte.html#limiting-recursion) is reached. A common use is generating a series, such as one row per month. Joined with `orders` through a `LEFT JOIN`, the series gives a monthly report that includes every month, even one without orders: ```sql WITH RECURSIVE months (month_start) AS ( SELECT DATE'2025-01-01' UNION ALL SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01') SELECT m.month_start, COUNT(o.id) AS orders FROM months m LEFT JOIN orders o ON o.order_date >= m.month_start AND o.order_date < ADD_MONTHS(m.month_start, 1) GROUP BY m.month_start ORDER BY m.month_start; ``` | month_start | orders | |---|---:| | 2025-01-01 | 51 | | 2025-02-01 | 50 | | 2025-03-01 | 46 | | 2025-04-01 | 54 | | 2025-05-01 | 56 | | 2025-06-01 | 62 | | 2025-07-01 | 50 | | 2025-08-01 | 69 | | 2025-09-01 | 67 | | 2025-10-01 | 76 | | 2025-11-01 | 110 | | 2025-12-01 | 95 | For hierarchies stored in a single table (an employee and their manager, a part and its assembly), recursive CTEs work the same way: the non-recursive part selects the top rows and the recursive part joins the table to the CTE. For data stored as a graph, a [MATCH](https://www.coradb.ai/manual/graph/match.html) path pattern is usually simpler. The recursive part must refer to the CTE directly in its `FROM` clause. Referring to it inside a nested subquery is an error: ```sql WITH RECURSIVE n (x) AS ( SELECT 1 UNION ALL SELECT * FROM (SELECT n.x + 1 FROM n WHERE n.x < 5)) SELECT * FROM n; ``` ```text ERROR: Recursive CTE 'n' must be referenced directly in its recursive query. ``` ### Limiting recursion A recursive CTE whose recursive part never stops producing rows would run forever. The [cte_max_recursions](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter stops it after a number of steps: the default is 2,000, the minimum 2 and the maximum 1,000,000. Set it for your session with [SET SYSTEM PARAMETERS](https://www.coradb.ai/manual/sql/query/set.html): ```sql SET SYSTEM PARAMETERS 'cte_max_recursions=5'; WITH RECURSIVE months (month_start) AS ( SELECT DATE'2025-01-01' UNION ALL SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01') SELECT COUNT(*) FROM months; ``` ```text ERROR: Maximum recursions 5 reached executing CTE. ``` > **Warning:** > Even below the recursion limit, a recursive CTE whose steps produce many rows can grow very large and use a lot of temporary disk space. Make sure the recursive part converges quickly. ## Restrictions Two CTEs in the same `WITH` clause cannot have the same name: ```sql WITH big_orders AS (SELECT id FROM orders WHERE shipping_cost > 30), big_orders AS (SELECT id FROM orders WHERE shipping_cost > 40) SELECT COUNT(*) FROM big_orders; ``` ```text ERROR: CTE name ambiguity, there are more than one CTEs with the same name: 'big_orders'. ``` A CTE cannot contain its own `WITH` clause. Define all CTEs at the same level instead: ```sql WITH recent AS ( WITH december AS (SELECT id FROM orders WHERE order_date >= DATE'2025-12-01') SELECT * FROM december) SELECT COUNT(*) FROM recent; ``` ```text ERROR: Nested WITH clauses are not supported. ``` ## CTEs in other statements Besides `SELECT`, a `WITH` clause can be used in `CREATE TABLE ... AS SELECT`, `INSERT ... SELECT`, `REPLACE ... SELECT`, `UPDATE` and `DELETE`. These examples change data; to keep the sample database unchanged, start corasql with `--no-auto-commit` and finish with `ROLLBACK;`. In **CREATE TABLE ... AS**, the `WITH` clause comes after `AS`: ```sql CREATE TABLE monthly_orders AS WITH RECURSIVE months (month_start) AS ( SELECT DATE'2025-10-01' UNION ALL SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2025-12-01') SELECT m.month_start, COUNT(o.id) AS orders FROM months m LEFT JOIN orders o ON o.order_date >= m.month_start AND o.order_date < ADD_MONTHS(m.month_start, 1) GROUP BY m.month_start; SELECT * FROM monthly_orders ORDER BY 1; ``` | month_start | orders | |---|---:| | 2025-10-01 | 76 | | 2025-11-01 | 110 | | 2025-12-01 | 95 | In **INSERT** and **REPLACE**, it comes before the `SELECT`: ```sql INSERT INTO monthly_orders WITH RECURSIVE months (month_start) AS ( SELECT DATE'2026-01-01' UNION ALL SELECT ADD_MONTHS(month_start, 1) FROM months WHERE month_start < DATE'2026-02-01') SELECT month_start, 0 FROM months; ``` ```text 2 rows affected. ``` In **UPDATE** and **DELETE**, the `WITH` clause comes first and the CTE can be joined or used in subqueries. Add 25 units of stock to every product that has sold at least 150 units: ```sql WITH best_sellers AS ( SELECT product_id, SUM(quantity) AS sold FROM order_items GROUP BY product_id) UPDATE product p JOIN best_sellers b ON p.id = b.product_id SET p.units_in_stock = p.units_in_stock + 25 WHERE b.sold >= 150; ``` ```text 26 rows affected. ``` Remove the months that are later than the last order: ```sql WITH last_sale AS (SELECT MAX(order_date) AS last_day FROM orders) DELETE FROM monthly_orders WHERE month_start > (SELECT last_day FROM last_sale); ``` ```text 2 rows affected. ``` ## See also - [SELECT](https://www.coradb.ai/manual/sql/query/select.html) - [Hierarchical queries](https://www.coradb.ai/manual/sql/query/hq.html): `CONNECT BY` for tree-structured data - [MATCH](https://www.coradb.ai/manual/graph/match.html): path patterns over graph data --- # DELETE statement Source: https://www.coradb.ai/manual/sql/query/delete.html The **DELETE** statement removes rows from one or more tables. A [WHERE clause](https://www.coradb.ai/manual/sql/query/select.html#where-clause) selects the rows to remove; without one, every row of the table is deleted. To empty a whole table quickly, use [TRUNCATE](https://www.coradb.ai/manual/sql/query/truncate.html) instead. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was. ## Syntax ```text -- one table DELETE [FROM] table_name [WHERE ] [LIMIT row_count] -- several tables, FROM form DELETE table_name [, table_name ...] FROM [WHERE ] -- several tables, USING form DELETE FROM table_name [, table_name ...] USING [WHERE ] ``` - *table_name*: the table to delete rows from. With a single table, the `FROM` keyword is optional. In the multi-table forms, list the tables (or their aliases) whose rows are deleted. - *table_specifications*: the tables to read, written like the `FROM` clause of a [SELECT](https://www.coradb.ai/manual/sql/query/select.html), including joins. Aliases are defined here and can be used in the rest of the statement. - *search_condition*: only rows that satisfy the condition are deleted. - *row_count*: the maximum number of rows to delete. It can be an unsigned integer, a host variable or a simple expression. `LIMIT` is allowed only when one table is involved. ## Deleting from one table Order 455 has three lines: ```sql SELECT order_id, product_id, quantity, discount_pct FROM order_items WHERE order_id = 455 ORDER BY product_id; ``` | order_id | product_id | quantity | discount_pct | |---:|---:|---:|---:| | 455 | 123 | 4 | 0 | | 455 | 335 | 1 | 0 | | 455 | 1795 | 1 | 25 | Remove one of them: ```sql DELETE FROM order_items WHERE order_id = 455 AND product_id = 1795; ``` ```text 1 row affected. ``` ## Limiting the number of deleted rows `LIMIT` caps how many of the matching rows are deleted. There are 2,758 single-unit lines without a discount; the statement below deletes only five of them: ```sql DELETE FROM order_items WHERE discount_pct = 0 AND quantity = 1 LIMIT 5; ``` ```text 5 rows affected. ``` Without `ORDER BY`, which matching rows are removed is not defined, so use `LIMIT` for batch clean-up jobs rather than to pick specific rows. ## Foreign keys A row that other rows still reference through a foreign key cannot be deleted. Order 455 still has lines in `order_items`, which references `orders`: ```sql DELETE FROM orders WHERE id = 455; ``` ```text ERROR: Update/Delete operations are restricted by the foreign key 'fk_order_items_order_id'. ``` Delete the referencing rows first, then the parent row, as shown in the next section. The behavior depends on the `ON DELETE` action of the foreign key; see [FOREIGN KEY constraint](https://www.coradb.ai/manual/sql/schema/table_stmt.html#foreign-key-constraint). ## Deleting from several tables The multi-table forms read rows through a join and delete from the tables you list. Nine orders have not shipped yet, and together they have 29 lines. Remove the lines first: ```sql DELETE oi FROM order_items oi INNER JOIN orders o ON oi.order_id = o.id WHERE o.shipped_date IS NULL; ``` ```text 29 rows affected. ``` Then the orders themselves: ```sql DELETE FROM orders WHERE shipped_date IS NULL; ``` ```text 9 rows affected. ``` The `USING` form expresses the same join in a different order. This statement deletes the same 29 lines as the first one: ```sql DELETE FROM oi USING order_items oi, orders o WHERE oi.order_id = o.id AND o.shipped_date IS NULL; ``` ```text 29 rows affected. ``` Listing both tables in one statement does not get around the foreign key. CoraDB checks the constraint while it deletes, so deleting orders and their lines together fails: ```sql DELETE oi, o FROM orders o INNER JOIN order_items oi ON oi.order_id = o.id WHERE o.shipped_date IS NULL; ``` ```text ERROR: Update/Delete operations are restricted by the foreign key 'fk_order_items_order_id'. ``` > **Note:** > Table aliases can be defined only inside *table_specifications*. Elsewhere in the statement, refer to the tables by those aliases. ## Deleting vertices and edges `DELETE VERTEX FROM` and `DELETE EDGE FROM` remove rows of [vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge); a plain `DELETE FROM` works too. Deleting a vertex also deletes the edges connected to it, so no edge is left pointing to a missing vertex. ```sql CREATE VERTEX TABLE warehouse (id INT PRIMARY KEY, name VARCHAR(64)); CREATE EDGE TABLE stocks (quantity INT); INSERT VERTEX INTO warehouse VALUES (1, 'Bucharest DC'), (2, 'Cluj DC'); INSERT EDGE FROM (SELECT warehouse FROM warehouse WHERE id = 1) TO (SELECT product FROM product WHERE id = 1795) INTO stocks VALUES (40); INSERT EDGE FROM (SELECT warehouse FROM warehouse WHERE id = 2) TO (SELECT product FROM product WHERE id = 1795) INTO stocks VALUES (25); DELETE EDGE FROM stocks WHERE quantity = 25; -- 1 edge left DELETE VERTEX FROM warehouse WHERE id = 1; -- also deletes its edge: 0 edges left ``` ## See also - [TRUNCATE](https://www.coradb.ai/manual/sql/query/truncate.html): empty a table - [UPDATE](https://www.coradb.ai/manual/sql/query/update.html) - [WITH (CTE)](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements): use a common table expression in a DELETE - [Transactions](https://www.coradb.ai/manual/sql/transaction.html) --- # DO statement Source: https://www.coradb.ai/manual/sql/query/do.html The **DO** statement evaluates an expression and discards the result. Use it to check that an expression is valid (an invalid one returns an error) or to call a function only for its side effects. Because no result set is built and sent back, `DO` is slightly cheaper than the equivalent `SELECT`. ## Syntax ```text DO expression ``` - *expression*: any expression, including a subquery that returns one value. ## Examples ```sql DO 1 + 1; DO SYSDATE + 1; DO (SELECT COUNT(*) FROM orders); ``` Each statement succeeds and returns nothing. An expression that cannot be evaluated is reported as an error, just as it would be in a `SELECT`. ## See also - [SELECT](https://www.coradb.ai/manual/sql/query/select.html) - [Operators and functions](https://www.coradb.ai/manual/sql/function.html) --- # Hierarchical queries (CONNECT BY) Source: https://www.coradb.ai/manual/sql/query/hq.html A hierarchical query returns the rows of a table that stores a tree, such as categories and subcategories, employees and managers, or parts and assemblies, in tree order. Each row points to its parent through a column; the **START WITH** clause chooses the root rows and the **CONNECT BY** clause says how a child row relates to its parent. CoraDB also offers two other ways to walk connected data: [recursive CTEs](https://www.coradb.ai/manual/sql/query/cte.html#recursive-ctes) (standard SQL) and, for data stored as vertices and edges, [MATCH path patterns](https://www.coradb.ai/manual/graph/match.html). ## Syntax ```text SELECT column_list FROM table_joins | tables [WHERE join_conditions and/or filtering_conditions] [START WITH condition] CONNECT BY [NOCYCLE] condition [ORDER SIBLINGS BY col [ASC | DESC], ... | ORDER BY ...] ``` The two clauses can also be written in the order `CONNECT BY ... START WITH ...`. - **START WITH** *condition*: the rows that satisfy the condition are the roots of the hierarchy. If you omit `START WITH`, or no row satisfies it, **every** row is a root, and the subtree below each row is returned. - **CONNECT BY** *condition*: the parent-child relationship. It is tested for pairs of rows; inside it, **PRIOR** marks the expression that is taken from the parent row. `CONNECT BY PRIOR id = parent_id` means "a row is a child of the row whose `id` equals its `parent_id`". - **NOCYCLE**: continue when the data contains a loop instead of failing (see [Cycles](https://www.coradb.ai/manual/sql/query/hq.html#cycles)). - **ORDER SIBLINGS BY**: sort the children of each parent while keeping the tree order (see [Ordering](https://www.coradb.ai/manual/sql/query/hq.html#ordering)). ## Example data The e-commerce categories have no built-in hierarchy, so the examples on this page add one in a scratch table: `category_tree` stores, for each category id, the id of its parent category. Joined with `category`, it gives three small trees: **Men** (with *Tops* and *Bottoms*), **Gear** and **Sale**. ```sql CREATE TABLE category_tree (category_id INT PRIMARY KEY, parent_id INT); INSERT INTO category_tree VALUES (9, NULL), (10, 9), (11, 10), (14, 10), (23, 10), (27, 10), (15, 9), (16, 15), (21, 15), (28, NULL), (31, 28), (29, 28), (30, 28), (32, NULL), (26, 32), (22, 32); ``` > **Try it yourself:** > Run the statements above in `corasql --no-auto-commit -u dba e-commerce`, try the queries, and finish with `ROLLBACK;` to remove the table again. ## START WITH and CONNECT BY Start from the top-level categories and follow the parent-child links. The [LEVEL](https://www.coradb.ai/manual/sql/query/hq.html#level) pseudocolumn gives the depth of each row: ```sql SELECT t.category_id, t.parent_id, c.name, LEVEL FROM category_tree t JOIN category c ON c.id = t.category_id START WITH t.parent_id IS NULL CONNECT BY PRIOR t.category_id = t.parent_id ORDER SIBLINGS BY c.name; ``` | category_id | parent_id | name | level | |---:|---:|---|---:| | 28 | NULL | Gear | 1 | | 31 | 28 | Bags | 2 | | 29 | 28 | Fitness Equipment | 2 | | 30 | 28 | Watches | 2 | | 9 | NULL | Men | 1 | | 15 | 9 | Bottoms | 2 | | 16 | 15 | Pants | 3 | | 21 | 15 | Shorts | 3 | | 10 | 9 | Tops | 2 | | 11 | 10 | Hoodies & Sweatshirts | 3 | | 14 | 10 | Jackets | 3 | | 27 | 10 | Tanks | 3 | | 23 | 10 | Tees | 3 | | 32 | NULL | Sale | 1 | | 26 | 32 | Men Sale | 2 | | 22 | 32 | Women Sale | 2 | Without `START WITH`, every row becomes a root and the query returns each row once for every root above it: 35 rows instead of 16. *Tees*, for example, appears three times: as a root, under *Tops* and under *Men*. ### Joins and WHERE When the `FROM` clause joins tables, as above, CoraDB evaluates the join first, then builds the hierarchy with `START WITH` and `CONNECT BY`, and applies the other `WHERE` conditions last, to the rows of the finished tree. A row removed by `WHERE` therefore does not remove its children: ```sql SELECT c.name, LEVEL FROM category_tree t JOIN category c ON c.id = t.category_id WHERE c.name <> 'Tops' START WITH t.category_id = 9 CONNECT BY PRIOR t.category_id = t.parent_id ORDER SIBLINGS BY c.name; ``` | name | level | |---|---:| | Men | 1 | | Bottoms | 2 | | Pants | 3 | | Shorts | 3 | | Hoodies & Sweatshirts | 3 | | Jackets | 3 | | Tanks | 3 | | Tees | 3 | *Tops* is gone, but its four children are still there at level 3. To leave out a whole subtree, put the condition in `CONNECT BY` instead. Write join conditions in the `ON` clause of the join rather than in `WHERE`, so that they cannot be mistaken for filters. ## Ordering: ORDER SIBLINGS BY A plain `ORDER BY` sorts the result as a flat list and loses the tree order. **ORDER SIBLINGS BY** keeps every child below its parent and sorts only the children of the same parent, as in the examples above, where the siblings are listed by name. ```text ORDER SIBLINGS BY col_1 [ASC | DESC] [, col_2 [ASC | DESC] ...] ``` ## Pseudocolumns ### LEVEL `LEVEL` is the depth of the row in the tree: 1 for a root, 2 for its children, and so on. It can be used in the select list, `WHERE`, `ORDER BY`, `GROUP BY ... HAVING` and in aggregate functions. List only the second level: ```sql SELECT c.name, LEVEL FROM category_tree t JOIN category c ON c.id = t.category_id WHERE LEVEL = 2 START WITH t.parent_id IS NULL CONNECT BY PRIOR t.category_id = t.parent_id ORDER BY c.name; ``` | name | level | |---|---:| | Bags | 2 | | Bottoms | 2 | | Fitness Equipment | 2 | | Men Sale | 2 | | Tops | 2 | | Watches | 2 | | Women Sale | 2 | `LEVEL` in the `CONNECT BY` condition is a quick way to generate a number of rows from the one-row system table `db_root`: ```sql SELECT LEVEL FROM db_root CONNECT BY LEVEL <= 5; ``` | level | |---:| | 1 | | 2 | | 3 | | 4 | | 5 | The same trick produces a series of dates, for example the first week of December 2025: ```sql SELECT TO_CHAR(DATE'2025-12-01' + LEVEL - 1, 'YYYY-MM-DD') AS order_day FROM db_root CONNECT BY LEVEL <= 7; ``` | order_day | |---| | 2025-12-01 | | 2025-12-02 | | 2025-12-03 | | 2025-12-04 | | 2025-12-05 | | 2025-12-06 | | 2025-12-07 | ### CONNECT_BY_ISLEAF `CONNECT_BY_ISLEAF` is 1 when the row has no children in the result, and 0 otherwise. It appears in the example in [Operators and functions](https://www.coradb.ai/manual/sql/query/hq.html#operators-and-functions) below. ### CONNECT_BY_ISCYCLE `CONNECT_BY_ISCYCLE` is 1 when the row has a child that is also one of its ancestors, that is, where a loop was cut, and 0 otherwise. It is available only with `NOCYCLE`; see [Cycles](https://www.coradb.ai/manual/sql/query/hq.html#cycles). ## Operators and functions - **PRIOR** *expr*: the value of *expr* in the parent row, `NULL` for a root. Besides `CONNECT BY`, it can be used in the select list, `WHERE` and `ORDER BY`. - **CONNECT_BY_ROOT** *expr*: the value of *expr* in the root row of the current tree. It can be used in the select list, `WHERE` and `ORDER BY`. - **SYS_CONNECT_BY_PATH**(*column*, *separator*): the path from the root to the current row, made of the column's values, each preceded by the separator. Both arguments must be character strings. The query below shows all of them for the *Men* tree: ```sql SELECT c.name, CONNECT_BY_ISLEAF AS is_leaf, CONNECT_BY_ROOT c.name AS root, PRIOR c.name AS parent, SYS_CONNECT_BY_PATH(c.name, '/') AS path FROM category_tree t JOIN category c ON c.id = t.category_id START WITH t.category_id = 9 CONNECT BY PRIOR t.category_id = t.parent_id ORDER SIBLINGS BY c.name; ``` | name | is_leaf | root | parent | path | |---|---:|---|---|---| | Men | 0 | Men | NULL | /Men | | Bottoms | 0 | Men | Men | /Men/Bottoms | | Pants | 1 | Men | Bottoms | /Men/Bottoms/Pants | | Shorts | 1 | Men | Bottoms | /Men/Bottoms/Shorts | | Tops | 0 | Men | Men | /Men/Tops | | Hoodies & Sweatshirts | 1 | Men | Tops | /Men/Tops/Hoodies & Sweatshirts | | Jackets | 1 | Men | Tops | /Men/Tops/Jackets | | Tanks | 1 | Men | Tops | /Men/Tops/Tanks | | Tees | 1 | Men | Tops | /Men/Tops/Tees | ## Cycles: NOCYCLE If the data contains a loop, following the links would never end. Make *Men* a child of *Tees*, which is itself below *Men*: ```sql UPDATE category_tree SET parent_id = 23 WHERE category_id = 9; ``` Without `NOCYCLE`, CoraDB detects the loop and cancels the query: ```sql SELECT c.name FROM category_tree t JOIN category c ON c.id = t.category_id START WITH t.category_id = 9 CONNECT BY PRIOR t.category_id = t.parent_id; ``` ```text ERROR: CONNECT BY loop in user data. ``` With `NOCYCLE`, CoraDB stops following a branch when it would come back to a row that is already on the current path, and returns the rest. `CONNECT_BY_ISCYCLE` marks the row where the loop was cut: ```sql SELECT c.name, LEVEL, CONNECT_BY_ISCYCLE AS is_cycle, SYS_CONNECT_BY_PATH(c.name, '/') AS path FROM category_tree t JOIN category c ON c.id = t.category_id START WITH t.category_id = 9 CONNECT BY NOCYCLE PRIOR t.category_id = t.parent_id ORDER SIBLINGS BY c.name; ``` | name | level | is_cycle | path | |---|---:|---:|---| | Men | 1 | 0 | /Men | | Bottoms | 2 | 0 | /Men/Bottoms | | Pants | 3 | 0 | /Men/Bottoms/Pants | | Shorts | 3 | 0 | /Men/Bottoms/Shorts | | Tops | 2 | 0 | /Men/Tops | | Hoodies & Sweatshirts | 3 | 0 | /Men/Tops/Hoodies & Sweatshirts | | Jackets | 3 | 0 | /Men/Tops/Jackets | | Tanks | 3 | 0 | /Men/Tops/Tanks | | Tees | 3 | 1 | /Men/Tops/Tees | ## Performance A `CONNECT BY` query does extra work for every row (cycle detection and the pseudocolumns). When it returns most of a table, a query that joins the table to itself a fixed number of times can be faster. When it returns a small subtree of a large table, `START WITH ... CONNECT BY` is usually faster, especially with an index on the parent column, because only the rows below the roots are visited. ## See also - [WITH RECURSIVE](https://www.coradb.ai/manual/sql/query/cte.html#recursive-ctes) - [MATCH](https://www.coradb.ai/manual/graph/match.html): variable-length paths over graph data - [SELECT](https://www.coradb.ai/manual/sql/query/select.html) --- # INSERT statement Source: https://www.coradb.ai/manual/sql/query/insert.html The **INSERT** statement adds new rows to a table. CoraDB supports three ways to supply the values, plus two forms for graph data: - **INSERT ... VALUES** and **INSERT ... SET** insert values you write in the statement. - **INSERT ... SELECT** inserts the result of a query. - **INSERT VERTEX** adds rows to a vertex table and **INSERT EDGE** connects two vertices through an edge table. Any of the relational forms can end with **ON DUPLICATE KEY UPDATE** to update the existing row instead of failing when the new row would duplicate a primary key or unique value. To replace the existing row instead, see [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html). > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was. ## Syntax ```text INSERT [INTO] table_name [(column_name, ...)] {VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...] [ON DUPLICATE KEY UPDATE column_name = expr, ...] INSERT [INTO] table_name DEFAULT [VALUES] INSERT [INTO] table_name SET column_name = {expr | DEFAULT} [, column_name = {expr | DEFAULT} ...] [ON DUPLICATE KEY UPDATE column_name = expr, ...] INSERT [INTO] table_name [(column_name, ...)] [ON DUPLICATE KEY UPDATE column_name = expr, ...] INSERT VERTEX [INTO] table_name [(column_name, ...)] {VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...] INSERT [DIRECTED | UNDIRECTED] EDGE FROM () TO () [INTO] table_name [(column_name, ...)] VALUES ({expr | DEFAULT}, ...) ``` - *table_name*: the table to insert into. - *column_name*: the columns that receive values. If you omit the list, you must give a value for every column, in the order the columns were defined. Columns left out of the list get their default value, or `NULL` if they have none. - *expr* | **DEFAULT**: the value for each column, in the order of the column list. An expression can be a subquery that returns one value. `DEFAULT` stores the column's default value. - **DEFAULT VALUES**: insert one row made only of default values. - *select_statement*: a query whose rows are inserted; its columns must match the column list. ## INSERT ... VALUES Insert one row, with a value for every column: ```sql INSERT INTO countries VALUES ('ROU', 'Romania'); ``` Name the columns explicitly and insert several rows at once: ```sql INSERT INTO countries (code, name) VALUES ('BGR', 'Bulgaria'), ('HUN', 'Hungary'); ``` ```text 2 rows affected. ``` ## INSERT ... SET `SET` names each column next to its value, which reads well for single rows: ```sql INSERT INTO countries SET code = 'GRC', name = 'Greece'; SELECT code, name FROM countries WHERE code IN ('BGR', 'GRC', 'HUN', 'ROU') ORDER BY code; ``` | code | name | |---|---| | BGR | Bulgaria | | GRC | Greece | | HUN | Hungary | | ROU | Romania | ## Default values and AUTO_INCREMENT The next examples use a small table for customer support tickets. `id` is generated automatically, and `status` and `priority` have defaults: ```sql CREATE TABLE support_ticket ( id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, subject VARCHAR(100) NOT NULL, status VARCHAR(10) DEFAULT 'open', priority INT DEFAULT 3 ); ``` Leave out the columns you want filled in for you, pass `NULL` to an `AUTO_INCREMENT` column, or write `DEFAULT` explicitly: ```sql INSERT INTO support_ticket (customer_id, subject) VALUES (5, 'Wrong size delivered'); INSERT INTO support_ticket (customer_id, subject, priority) VALUES (15, 'Refund request', 1); INSERT INTO support_ticket VALUES (NULL, 42, 'Damaged parcel', 'pending', DEFAULT); INSERT INTO support_ticket SET customer_id = 5, subject = 'Invoice copy', priority = priority + 1; SELECT * FROM support_ticket ORDER BY id; ``` | id | customer_id | subject | status | priority | |---:|---:|---|---|---:| | 1 | 5 | Wrong size delivered | open | 3 | | 2 | 15 | Refund request | open | 1 | | 3 | 42 | Damaged parcel | pending | 3 | | 4 | 5 | Invoice copy | open | 4 | In the last statement, `priority + 1` uses the default value 3, because `priority` had not been assigned yet. [LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id) returns the value generated for the last row inserted in your session: ```sql SELECT LAST_INSERT_ID(); ``` ```text 4 ``` A table where every column has a default can take a row with no values at all: ```sql CREATE TABLE visit_log (visited_at DATETIME DEFAULT SYSDATETIME, page VARCHAR(64) DEFAULT 'home'); INSERT INTO visit_log DEFAULT VALUES; ``` ### Evaluation order in SET The assignments of `INSERT ... SET` are evaluated from left to right. An expression can use a column assigned earlier in the same statement; a column not assigned yet has its default value, or `NULL` if it has no default: ```sql INSERT INTO support_ticket SET customer_id = 9, subject = 'Late delivery', priority = customer_id - 7; INSERT INTO support_ticket SET priority = customer_id + 1, customer_id = 12, subject = 'Address change'; SELECT id, customer_id, priority FROM support_ticket WHERE id > 4 ORDER BY id; ``` | id | customer_id | priority | |---:|---:|---:| | 5 | 9 | 2 | | 6 | 12 | NULL | In the second statement `customer_id` was still unassigned (and has no default) when `priority` was computed, so `priority` is `NULL`. ### Subqueries in VALUES A value can be a subquery that returns a single value: ```sql INSERT INTO support_ticket (customer_id, subject) VALUES ((SELECT customer_id FROM orders WHERE id = 455), 'Order 455 not shipped'); SELECT id, customer_id, subject FROM support_ticket WHERE id = 7; ``` | id | customer_id | subject | |---:|---:|---| | 7 | 458 | Order 455 not shipped | ## INSERT ... SELECT Use a query instead of `VALUES` to insert many rows at once. Copy all 2021 orders into an archive table with the same structure as `orders`: ```sql CREATE TABLE order_archive LIKE orders; INSERT INTO order_archive SELECT * FROM orders WHERE order_date < DATE'2022-01-01'; SELECT COUNT(*), MIN(order_date), MAX(order_date) FROM order_archive; ``` | count(*) | min(order_date) | max(order_date) | |---:|---|---| | 416 | 2021-01-01 | 2021-12-31 | The query can be any `SELECT`, including joins, aggregates and [common table expressions](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements). ## ON DUPLICATE KEY UPDATE Inserting a row whose primary key or unique value already exists fails: ```sql INSERT INTO countries VALUES ('FRA', 'France'); ``` ```text ERROR: Operation would have caused one or more unique constraint violations. INDEX pk_countries_code ... key: 'FRA' ``` With **ON DUPLICATE KEY UPDATE**, CoraDB updates the existing row instead: ```sql INSERT INTO countries VALUES ('FRA', 'French Republic') ON DUPLICATE KEY UPDATE name = 'French Republic'; SELECT code, name FROM countries WHERE code = 'FRA'; ``` | code | name | |---|---| | FRA | French Republic | The affected-row count tells you what happened: 1 for each row inserted and 2 for each existing row updated. The statement above reports 2. The clause works with `SET` and `SELECT` as well: ```sql INSERT INTO countries SET code = 'ESP', name = 'Spain' ON DUPLICATE KEY UPDATE name = 'Kingdom of Spain'; INSERT INTO countries (code, name) SELECT 'ITA', 'Italy' FROM db_root ON DUPLICATE KEY UPDATE name = 'Italian Republic'; SELECT code, name FROM countries WHERE code IN ('ESP', 'ITA') ORDER BY code; ``` | code | name | |---|---| | ESP | Kingdom of Spain | | ITA | Italian Republic | > **Note:** > - If a table has several unique constraints (a primary key and a unique index, or several unique indexes), a new row can collide with different rows through different constraints. Avoid `ON DUPLICATE KEY UPDATE` on such tables. > - When the insert turns into an update, an `AUTO_INCREMENT` value that was already generated for the attempted insert is not given back. ## INSERT VERTEX Rows of a [vertex table](https://www.coradb.ai/manual/graph/graph_getting_started.html) are inserted like any other row. `INSERT VERTEX` makes the intent explicit; a plain `INSERT` works the same way. In the e-commerce database, `product` is a vertex table: ```sql INSERT VERTEX INTO product (id, name, description, unit_price, units_in_stock) VALUES (3001, 'Speedgoat Trail Shoe', 'Size 42, Blue', 155.00, 12); INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (3002, 'Speedgoat Trail Shoe', 'Size 43, Blue', 155.00, 8); ``` ## INSERT EDGE An edge connects two existing vertices. Edges are inserted only with `INSERT EDGE`: the `FROM` and `TO` subqueries each select **one** vertex, and `VALUES` gives the edge's own columns. A subquery selects a vertex by naming the vertex table in its select list, as in `SELECT brand FROM brand WHERE ...`. Connect the new shoe to its brand and to a category: ```sql INSERT EDGE FROM (SELECT brand FROM brand WHERE name = 'Hoka') TO (SELECT product FROM product WHERE id = 3001) INTO manufactures VALUES (SYSDATETIME); INSERT EDGE FROM (SELECT product FROM product WHERE id = 3001) TO (SELECT category FROM category WHERE name = 'Gear') INTO part_of VALUES (SYSDATETIME); ``` The new vertex and edges can be read back with [MATCH](https://www.coradb.ai/manual/graph/match.html): ```sql SELECT b.name AS brand, p.name AS product, c.name AS category FROM MATCH (b:brand)-[:manufactures]->(p:product), (p:product)-[:part_of]->(c:category) WHERE p.id = 3001; ``` | brand | product | category | |---|---|---| | Hoka | Speedgoat Trail Shoe | Gear | ### Directed and undirected edges An edge is directed by default (`INSERT EDGE` and `INSERT DIRECTED EDGE` are the same). `INSERT UNDIRECTED EDGE` creates a connection that is followed in both directions. In the e-commerce schema, `follows` connects customers: ```sql INSERT UNDIRECTED EDGE FROM (SELECT customer FROM customer WHERE id = 5) TO (SELECT customer FROM customer WHERE id = 15) INTO follows VALUES (DATETIME'2026-01-10 09:30:00'); SELECT a.id, b.id, f.since FROM MATCH (a:customer)-[f:follows]->(b:customer); ``` | a.id | b.id | f.since | |---:|---:|---| | 5 | 15 | 2026-01-10 09:30:00.000 | | 15 | 5 | 2026-01-10 09:30:00.000 | One edge was inserted, and it is matched from either end. ### Errors to expect - A plain `INSERT` into an edge table is rejected with `From/to edges must be specified when inserting into an edge table`. - If the `FROM` or `TO` subquery returns more than one row, the statement fails with `Query result contains more than a single tuple`. There are several *Erika Running Short* products (one per size and color), so this fails: ```sql INSERT EDGE FROM (SELECT customer FROM customer WHERE id = 5) TO (SELECT product FROM product WHERE name = 'Erika Running Short') INTO likes VALUES (SYSDATETIME); ``` - If a subquery returns no row (for example, a category name that does not exist), the statement fails because there is no vertex to connect. ## See also - [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html): replace a row that has the same key - [MERGE](https://www.coradb.ai/manual/sql/query/merge.html): insert or update rows from another table - [Graph getting started](https://www.coradb.ai/manual/graph/graph_getting_started.html) and [MATCH](https://www.coradb.ai/manual/graph/match.html) - [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#create-table): defaults, `AUTO_INCREMENT` and constraints --- # KILL statement Source: https://www.coradb.ai/manual/sql/query/kill.html The **KILL** statement stops work done by another session: either the statement it is running, or its whole transaction and connection. It is the SQL counterpart of the [coradb killtran](https://www.coradb.ai/manual/admin/admin_transactions.html#killtran) utility. ## Syntax ```text KILL [TRANSACTION | QUERY] tran_index [, tran_index ...] ``` - **KILL TRANSACTION** *tran_index* (the default, same as `KILL` without a modifier): rolls back the transaction with that index and closes its connection. - **KILL QUERY** *tran_index*: cancels only the statement the transaction is currently running. The transaction and the connection stay open. - *tran_index*: the transaction index of the session to stop. Several indexes can be listed, separated by commas. Users in the `DBA` group can stop any transaction; other users can stop only their own. ## Finding the transaction index Every connected client has a transaction index. List them with the [coradb tranlist](https://www.coradb.ai/manual/admin/admin_transactions.html#tranlist) utility, or in SQL with [SHOW TRANSACTION TABLES](https://www.coradb.ai/manual/sql/query/show.html#show-transaction-tables), whose `Tran_index` column holds the index and whose `Client_db_user`, `Client_program`, `Client_host` and `Query_start_time` columns help identify the session. ## Examples Cancel the statement that transaction 2 is running, without closing its connection: ```sql KILL QUERY 2; ``` End transaction 2 and close its connection; its uncommitted changes are rolled back: ```sql KILL TRANSACTION 2; ``` `KILL` reports no error when no transaction has the given index, so check the index with `tranlist` or `SHOW TRANSACTION TABLES` first. > **Warning:** > `KILL TRANSACTION` rolls back all uncommitted work of that session. Make sure you have the right index, especially when application servers keep many connections open. ## See also - [Transactions](https://www.coradb.ai/manual/sql/transaction.html) - [coradb tranlist and coradb killtran](https://www.coradb.ai/manual/admin/admin_transactions.html#tranlist) --- # MERGE statement Source: https://www.coradb.ai/manual/sql/query/merge.html The **MERGE** statement compares the rows of a source (a table, a view or a subquery) with a target table and, in one statement, updates the target rows that have a match, optionally deletes some of them, and inserts the source rows that have none. It is the usual way to keep a summary or staging table in step with other data. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was. ## Syntax ```text MERGE [] INTO [[AS] ] USING [[AS] ] ON [] [] ::= WHEN MATCHED THEN UPDATE SET column = expr [, column = expr ...] [WHERE ] [DELETE WHERE ] ::= WHEN NOT MATCHED THEN INSERT [(column_list)] VALUES (expr_list) [WHERE ] ::= /*+ [USE_UPDATE_IDX (index_list)] [USE_INSERT_IDX (index_list)] */ ``` - *target*: the table that is updated, deleted from or inserted into. - *source*: where the rows come from: a table, a view or a subquery in parentheses. - *join_condition*: how a source row is matched with a target row, usually by key. - **WHEN MATCHED THEN UPDATE**: runs for every target row that matches a source row. - *expr* can use columns of the source and the target, or `DEFAULT` (not when the target is a view). Aggregate functions are not allowed here; aggregate in the source query instead. - *update_condition*: update only the matched rows for which it is true. - **DELETE WHERE** *delete_condition*: after the update, delete the updated rows for which the condition is true. The condition sees the **new** values. - **WHEN NOT MATCHED THEN INSERT**: runs for every source row with no matching target row. - *insert_condition*: insert only the source rows for which it is true. It can use source columns. - You can give either clause, or both in any order. - *merge_hint*: index hints, described [below](https://www.coradb.ai/manual/sql/query/merge.html#index-hints). `UPDATE`, `DELETE` and `INSERT` triggers on the target fire for the rows each clause changes. You need `SELECT` permission on the source and `UPDATE`, `DELETE` or `INSERT` permission on the target for the clauses you use. ## Example: maintaining a VIP customer list `vip_customer` keeps, for a few customers, how many orders they placed and when they last ordered. The stored figures are out of date: ```sql CREATE TABLE vip_customer ( customer_id INT PRIMARY KEY, orders_count INT NOT NULL, last_order DATE ); INSERT INTO vip_customer VALUES (5, 1, DATE'2024-01-15'), (15, 1, DATE'2024-01-15'), (42, 3, DATE'2024-05-20'); ``` The `MERGE` below refreshes the list from the `orders` table: - Customers already in the list get their current order count and last order date; - Customers who end up with fewer than three orders are dropped; - Customers not yet in the list are added if they placed at least 39 orders. ```sql MERGE INTO vip_customer t USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order FROM orders GROUP BY customer_id) s ON (t.customer_id = s.customer_id) WHEN MATCHED THEN UPDATE SET t.orders_count = s.n, t.last_order = s.last_order DELETE WHERE t.orders_count < 3 WHEN NOT MATCHED THEN INSERT VALUES (s.customer_id, s.n, s.last_order) WHERE s.n >= 39; SELECT * FROM vip_customer ORDER BY customer_id; ``` | customer_id | orders_count | last_order | |---:|---:|---| | 15 | 4 | 2025-09-03 | | 42 | 3 | 2024-05-20 | | 440 | 40 | 2025-12-27 | | 444 | 39 | 2025-09-06 | | 812 | 40 | 2025-12-10 | What happened to each row: - **15** matched and was updated to 4 orders, so it stays. - **5** matched and was updated to 2 orders. `DELETE WHERE` checks the updated value, 2 is below 3, so the row was deleted. - **42** has no orders, so there is no source row for it and it was left as it was. - **440, 444, 812** had no row in the list and placed at least 39 orders, so they were inserted. Customers with fewer orders were skipped by the `WHERE` of the insert clause. The statement reports 5 affected rows: two updates (one of which was then deleted) and three inserts. ## Using only one clause Each clause is optional. Insert the most active customers without touching existing rows: ```sql MERGE INTO vip_customer t USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order FROM orders GROUP BY customer_id) s ON (t.customer_id = s.customer_id) WHEN NOT MATCHED THEN INSERT (customer_id, orders_count, last_order) VALUES (s.customer_id, s.n, s.last_order) WHERE s.n >= 39; ``` ## Index hints `USE_UPDATE_IDX` names the indexes to use when matching rows for the update clause, and `USE_INSERT_IDX` the indexes to use for the insert clause. Both apply to the join condition. Use the index names of the target table; a primary key's index is named `pk_
_`: ```sql MERGE /*+ USE_UPDATE_IDX(pk_vip_customer_customer_id) */ INTO vip_customer t USING (SELECT customer_id, COUNT(*) AS n, MAX(order_date) AS last_order FROM orders GROUP BY customer_id) s ON (t.customer_id = s.customer_id) WHEN MATCHED THEN UPDATE SET t.orders_count = s.n, t.last_order = s.last_order; ``` For hints in general, see [Using SQL hint](https://www.coradb.ai/manual/sql/tuning_hints.html#using-sql-hint). ## See also - [INSERT ... ON DUPLICATE KEY UPDATE](https://www.coradb.ai/manual/sql/query/insert.html#on-duplicate-key-update): upsert from literal values - [UPDATE](https://www.coradb.ai/manual/sql/query/update.html#updating-several-tables): update from a join - [REPLACE](https://www.coradb.ai/manual/sql/query/replace.html) --- # Prepared statements: PREPARE, EXECUTE, DEALLOCATE Source: https://www.coradb.ai/manual/sql/query/prepare.html A prepared statement is an SQL statement that is compiled once and then run as often as needed, with different values bound to its `?` placeholders. Applications normally prepare statements through their driver (for example `PreparedStatement` in [JDBC](https://www.coradb.ai/manual/api/jdbc.html) or `prepare()` in the [PHP](https://www.coradb.ai/manual/api/php.html), [Python](https://www.coradb.ai/manual/api/python.html), [Node.js](https://www.coradb.ai/manual/api/node_js.html) and [ADO.NET](https://www.coradb.ai/manual/api/adodotnet.html) drivers). The same can be done in SQL with three statements: ```text PREPARE stmt_name FROM 'preparable_stmt' EXECUTE stmt_name [USING value [, value] ...] {DEALLOCATE | DROP} PREPARE stmt_name ``` > **Note:** > - SQL-level `PREPARE` is meant for interactive use in the [corasql interpreter](https://www.coradb.ai/manual/corasql.html). In applications, use the prepared statements of your driver. > - A connection can hold at most 20 SQL-level prepared statements, because they are kept in the database server's memory. Driver-level prepared statements are limited by the broker parameter [MAX_PREPARED_STMT_COUNT](https://www.coradb.ai/manual/admin/config_broker.html#max_prepared_stmt_count). ## PREPARE ```text PREPARE stmt_name FROM 'preparable_stmt' ``` - *stmt_name*: the name used to run or drop the statement later. If a prepared statement with this name already exists in the session, it is replaced. If preparing fails, any existing statement with that name is dropped as well. - *preparable_stmt*: exactly one SQL statement, as a string. Use `?` (without quotes) for each value to bind at execution time. Prepare a product search with two parameters, a minimum price and a row count: ```sql PREPARE by_price FROM 'SELECT id, name, unit_price FROM product WHERE unit_price > ? ORDER BY unit_price DESC LIMIT ?'; ``` Prepared statements belong to the session: they live until you drop them or the connection ends. The session also keeps your [user-defined variables](https://www.coradb.ai/manual/sql/query/set.html), the last generated `AUTO_INCREMENT` value ([LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id)) and the row count of the last statement ([ROW_COUNT](https://www.coradb.ai/manual/sql/function/information_fn.html#row_count)). An idle session expires after `session_state_timeout` seconds (see [Other parameters](https://www.coradb.ai/manual/admin/config_other.html#other-parameters)). ## EXECUTE ```text EXECUTE stmt_name [USING value [, value] ...] ``` - *stmt_name*: the prepared statement to run. An error is returned if it does not exist. - *value*: the values for the `?` placeholders, in order. The number of values must match the number of placeholders. A value can be a literal or a user-defined variable. ```sql EXECUTE by_price USING 90, 3; ``` | id | name | unit_price | |---:|---|---:| | 38 | Côte de Blaye | 263.50 | | 29 | Thüringer Rostbratwurst | 123.79 | | 454 | Lando Gym Jacket | 99.00 | The same statement with values taken from user-defined variables: ```sql SET @min_price = 120, @max_rows = 2; EXECUTE by_price USING @min_price, @max_rows; ``` | id | name | unit_price | |---:|---|---:| | 38 | Côte de Blaye | 263.50 | | 29 | Thüringer Rostbratwurst | 123.79 | The type of a placeholder is decided by how it is used and by the value you bind. When two string values are bound to `? + ?`, `+` concatenates them: ```sql PREPARE st FROM 'SELECT ? + ?'; EXECUTE st USING 'a', 'b'; ``` ```text ab ``` ## DEALLOCATE PREPARE / DROP PREPARE ```text {DEALLOCATE | DROP} PREPARE stmt_name ``` Both forms drop a prepared statement and free its memory on the server. Statements that are not dropped explicitly are dropped when the session ends. ```sql DEALLOCATE PREPARE by_price; DROP PREPARE st; ``` ## See also - [SET](https://www.coradb.ai/manual/sql/query/set.html): user-defined variables - [Drivers & APIs](https://www.coradb.ai/manual/api.html) --- # REPLACE statement Source: https://www.coradb.ai/manual/sql/query/replace.html The **REPLACE** statement works like [INSERT](https://www.coradb.ai/manual/sql/query/insert.html), with one difference: when a new row would duplicate a **PRIMARY KEY** or **UNIQUE** value, CoraDB deletes the existing row and inserts the new one instead of returning an error. When there is no conflict, `REPLACE` simply inserts. Because the old row is deleted, columns you do not give a value for get their default value, not the value they had before. To change only some columns of an existing row, use [INSERT ... ON DUPLICATE KEY UPDATE](https://www.coradb.ai/manual/sql/query/insert.html#on-duplicate-key-update) instead. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was. ## Syntax ```text REPLACE [INTO] table_name [(column_name, ...)] {VALUES | VALUE} ({expr | DEFAULT}, ...) [, ({expr | DEFAULT}, ...) ...] REPLACE [INTO] table_name SET column_name = {expr | DEFAULT} [, column_name = {expr | DEFAULT} ...] REPLACE [INTO] table_name [(column_name, ...)] ``` - *table_name*: the table to write to. - *column_name*: the columns that receive values. Without a list, give a value for every column in table order. - *expr* | **DEFAULT**: the value for each column, or `DEFAULT` for the column's default value. - *select_statement*: a query whose rows are written to the table. ## Examples Make a working copy of three countries: ```sql CREATE TABLE country_copy LIKE countries; INSERT INTO country_copy SELECT * FROM countries WHERE code IN ('DEU', 'FRA', 'ITA'); SELECT * FROM country_copy ORDER BY code; ``` | code | name | |---|---| | DEU | Germany | | FRA | France | | ITA | Italy | `DEU` already exists and is replaced; `ESP` is new and is inserted: ```sql REPLACE INTO country_copy VALUES ('DEU', 'Federal Republic of Germany'), ('ESP', 'Spain'); ``` ```text 3 rows affected. ``` The count includes the deleted row: 2 for `DEU` (one deleted, one inserted) and 1 for `ESP`. The `SET` form works the same way: ```sql REPLACE INTO country_copy SET code = 'ITA', name = 'Italian Republic'; SELECT * FROM country_copy ORDER BY code; ``` | code | name | |---|---| | DEU | Federal Republic of Germany | | ESP | Spain | | FRA | France | | ITA | Italian Republic | With a query as the source, every returned row either replaces a matching row or is added: ```sql REPLACE INTO country_copy (code, name) SELECT code, UPPER(name) FROM countries WHERE code IN ('FRA', 'PRT'); SELECT * FROM country_copy ORDER BY code; ``` | code | name | |---|---| | DEU | Federal Republic of Germany | | ESP | Spain | | FRA | FRANCE | | ITA | Italian Republic | | PRT | PORTUGAL | ## Things to keep in mind - `REPLACE` has to look up every new row in the table's primary key and unique indexes. On a table without a primary key or unique index it behaves like `INSERT`, so use `INSERT` there. - A replaced row is deleted, so foreign keys that reference it are checked as for a [DELETE](https://www.coradb.ai/manual/sql/query/delete.html#foreign-keys). Cities reference `countries`, so replacing a country that has cities fails, while `ON DUPLICATE KEY UPDATE` succeeds: ```sql REPLACE INTO countries VALUES ('DEU', 'Federal Republic of Germany'); ``` ```text ERROR: Update/Delete operations are restricted by the foreign key 'fk_city_country_code'. ``` ## See also - [INSERT ... ON DUPLICATE KEY UPDATE](https://www.coradb.ai/manual/sql/query/insert.html#on-duplicate-key-update) - [MERGE](https://www.coradb.ai/manual/sql/query/merge.html) --- # SELECT statement Source: https://www.coradb.ai/manual/sql/query/select.html The **SELECT** statement retrieves rows from one or more tables, views, derived tables or graph patterns. In CoraDB the same statement queries relational tables and graph data: vertex and edge tables can be read like ordinary tables, or traversed with a [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern in the `FROM` clause. > **Try it yourself:** > Every example on this page runs on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html), and the results shown are the real output. Connect with `corasql -u dba e-commerce` and paste any query. ## Syntax ```sql SELECT [ ] [{TO | INTO} ] [FROM ] [WHERE ] [GROUP BY {col_name | expr} [ASC | DESC], ... [WITH ROLLUP]] [HAVING ] [ORDER BY {col_name | expr} [ASC | DESC], ... [NULLS {FIRST | LAST}]] [LIMIT [offset,] row_count] [USING INDEX { index_name [, index_name, ...] | NONE }] [FOR UPDATE [OF ]] ::= ALL | DISTINCT | DISTINCTROW | UNIQUE ::= * | | *, ::= [:] identifier, [:] identifier, ... ::= [ {, } ... | ... | ... ] ::= [] | [] | | TABLE ( ) | MATCH [, ...] ::= [AS] [()] ::= [ONLY] | ALL [ EXCEPT ] ::= CLASS ::= [INNER | {LEFT | RIGHT} [OUTER]] JOIN ON ::= { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } ``` - *qualifier*: when omitted, **ALL** is used. - **ALL**: returns every row. - **DISTINCT**: returns only unique rows. **DISTINCT**, **DISTINCTROW** and **UNIQUE** are synonyms. - *select_expressions*: - `*` returns all columns of the tables in the `FROM` clause; *table_name*`.*` returns all columns of one table. - *expression_comma_list*: column names, path expressions (*tbl_name.col_name*), variables, arithmetic and function expressions, including aggregate functions such as **AVG**, **COUNT**, **MAX**, **MIN** and **SUM**. Use `AS` to give an expression an alias; aliases can be used in `GROUP BY`, `HAVING` and `ORDER BY`. Column positions start at 1. - *variable_comma_list*: stores the selected values in session variables (`TO :var` or `INTO :var`). - *single_table_spec*: with class inheritance, `ONLY` reads just the named super class, `ALL` reads it and its subclasses, and `EXCEPT` excludes the listed subclasses. See [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html). ### Basic examples Return each distinct contact title used by customers (the first five, alphabetically): ```sql SELECT DISTINCT contact_title FROM customer ORDER BY contact_title LIMIT 5; ``` | contact_title | |---| | Account Manager | | Accounts Payable Clerk | | Buyer | | CEO | | Category Manager | `customer` is a vertex table, yet it is queried here like any relational table. Give columns an alias and sort by the alias: ```sql SELECT id AS order_no, order_date AS placed_on FROM orders ORDER BY placed_on DESC, order_no LIMIT 5; ``` | order_no | placed_on | |---:|---| | 376 | 2025-12-31 | | 1127 | 2025-12-31 | | 1446 | 2025-12-31 | | 1634 | 2025-12-31 | | 1888 | 2025-12-31 | Build a value from several columns: ```sql SELECT CONCAT(name, ' (', code, ')') AS country FROM countries ORDER BY country LIMIT 5; ``` | country | |---| | Argentina (ARG) | | Australia (AUS) | | Austria (AUT) | | Belgium (BEL) | | Brazil (BRA) | ## FROM clause The **FROM** clause names the sources the rows are read from: tables, views, vertex and edge tables, subqueries (derived tables) and graph patterns. When no table is needed, `FROM` can be omitted. ```sql SELECT 1 + 1 AS sum_value; ``` | sum_value | |---:| | 2 | ### Derived table A subquery in the `FROM` clause creates a *derived table*: its result is treated as a table for the rest of the query. A derived table must have a correlation name (alias). Derived tables are also used to access the individual elements of a collection-typed column, each element becoming a row. ### Subquery derived table ```sql FROM (subquery) [AS] [derived_table_name [(column_name [{, column_name } ... ])]] ``` - The number of *column_name* entries must match the number of columns returned by the *subquery*. - *derived_table_name* can be omitted. Average number of lines per order, computed from a derived table that first counts the lines of each order: ```sql SELECT AVG(lines) AS avg_lines_per_order FROM (SELECT order_id, COUNT(*) FROM order_items GROUP BY order_id) AS t(order_id, lines); ``` | avg_lines_per_order | |---:| | 3.841580756013746 | A derived table can also be correlated with the outer query. The following query lists orders whose shipping cost is more than three times the average shipping cost of the same customer: ```sql SELECT o.id, o.customer_id, o.shipping_cost FROM orders o WHERE o.shipping_cost > (SELECT AVG(s) * 3 FROM (SELECT shipping_cost FROM orders WHERE customer_id = o.customer_id) AS t(s)) ORDER BY o.shipping_cost DESC, o.id LIMIT 5; ``` | id | customer_id | shipping_cost | |---:|---:|---:| | 1080 | 460 | 58.00 | | 1675 | 855 | 50.57 | | 995 | 634 | 50.52 | | 1643 | 830 | 48.30 | | 2884 | 877 | 41.90 | ## WHERE clause The **WHERE** clause keeps only the rows for which *search_condition* is true. A condition that evaluates to **NULL** (unknown) does not select the row. ```sql WHERE ::= | | | | | | | | [NOT] MATCH ``` The predicates are described in detail here: - [Simple comparison expression](https://www.coradb.ai/manual/sql/function/comparison_op.html) - [BETWEEN](https://www.coradb.ai/manual/sql/function/condition_op.html#between) - [EXISTS](https://www.coradb.ai/manual/sql/function/condition_op.html#exists) - [IN](https://www.coradb.ai/manual/sql/function/condition_op.html#in) - [IS NULL](https://www.coradb.ai/manual/sql/function/condition_op.html#is-null) - [LIKE](https://www.coradb.ai/manual/sql/function/condition_op.html#like) - [ANY/SOME/ALL quantifiers](https://www.coradb.ai/manual/sql/function/condition_op.html#any-some-all) - [MATCH as a predicate](https://www.coradb.ai/manual/graph/match.html#match-as-a-predicate) Combine conditions with **AND**, **OR** and **NOT**. They are evaluated in this order: | Priority | Operator | Meaning | |---:|---|---| | 1 | `()` | Expressions in parentheses are evaluated first. | | 2 | **NOT** | Negates the result of the expression. | | 3 | **AND** | All conditions must be true. | | 4 | **OR** | At least one condition must be true. | Orders placed in December 2025 that are either not shipped yet or were shipped for free: ```sql SELECT id, order_date, shipped_date, shipping_cost FROM orders WHERE order_date >= DATE'2025-12-01' AND (shipped_date IS NULL OR shipping_cost = 0) ORDER BY id LIMIT 5; ``` | id | order_date | shipped_date | shipping_cost | |---:|---|---|---:| | 175 | 2025-12-22 | 2025-12-25 | 0.00 | | 455 | 2025-12-30 | NULL | 12.35 | | 547 | 2025-12-14 | 2025-12-15 | 0.00 | | 707 | 2025-12-28 | 2026-01-03 | 0.00 | | 782 | 2025-12-12 | 2025-12-14 | 0.00 | ## GROUP BY ... HAVING clause **GROUP BY** groups the rows that have the same values in the listed columns or expressions, so that aggregate functions are computed per group. **HAVING** then filters the groups. ```sql SELECT ... GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP] [HAVING ] ``` - *col_name* | *expr* | *position*: one or more columns, expressions, aliases or column positions, separated by commas. - **ASC** | **DESC**: sort order of the groups; **ASC** is the default. - *search_condition*: the `HAVING` condition can refer to grouping columns, their aliases and aggregate functions. - **WITH ROLLUP**: adds subtotal rows for each level of grouping and a grand total row. In those rows the rolled-up columns are **NULL**. > **Note:** > The SQL standard does not allow a column in the select list that is neither grouped nor aggregated (a *hidden column*). CoraDB accepts such columns by default. Set the **only_full_group_by** parameter to **yes** to enforce the standard behaviour; see [Statement/type-related parameters](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters). Orders per year: ```sql SELECT EXTRACT(YEAR FROM order_date) AS yr, COUNT(*) AS orders FROM orders GROUP BY yr ORDER BY yr; ``` | yr | orders | |---:|---:| | 2021 | 416 | | 2022 | 482 | | 2023 | 551 | | 2024 | 675 | | 2025 | 786 | `WHERE` filters rows *before* grouping, `HAVING` filters groups *after* it. Customers with at least five orders in 2025, and what they paid for shipping: ```sql SELECT customer_id, COUNT(*) AS orders, SUM(shipping_cost) AS shipping FROM orders WHERE order_date >= DATE'2025-01-01' GROUP BY customer_id HAVING COUNT(*) >= 5 ORDER BY orders DESC, customer_id LIMIT 5; ``` | customer_id | orders | shipping | |---:|---:|---:| | 812 | 13 | 153.64 | | 440 | 11 | 183.69 | | 391 | 10 | 124.04 | | 75 | 8 | 119.41 | | 342 | 8 | 154.15 | **WITH ROLLUP** adds a subtotal per year and a grand total: ```sql SELECT EXTRACT(YEAR FROM order_date) AS yr, QUARTER(order_date) AS q, COUNT(*) AS orders FROM orders WHERE order_date >= DATE'2024-01-01' GROUP BY yr, q WITH ROLLUP; ``` | yr | q | orders | |---:|---:|---:| | 2024 | 1 | 125 | | 2024 | 2 | 132 | | 2024 | 3 | 152 | | 2024 | 4 | 266 | | NULL | NULL | 675 | | 2025 | 1 | 147 | | 2025 | 2 | 172 | | 2025 | 3 | 186 | | 2025 | 4 | 281 | | NULL | NULL | 786 | | NULL | NULL | 1461 | ## ORDER BY clause **ORDER BY** sorts the result. Without it, the order of the rows is not guaranteed. ```sql SELECT ... ORDER BY {col_name | expr | position} [ASC | DESC], ... [NULLS {FIRST | LAST}] ``` - *col_name* | *expr* | *position*: columns, expressions, aliases or column positions. A column that is not in the select list can also be used. - **ASC** | **DESC**: ascending (default) or descending order. - **NULLS FIRST** | **NULLS LAST**: where NULL values go. By default NULLs come first with `ASC` and last with `DESC`. Most recently shipped orders, with the orders that are not shipped yet (NULL `shipped_date`) on top: ```sql SELECT id, order_date, shipped_date FROM orders ORDER BY shipped_date DESC NULLS FIRST, id LIMIT 5; ``` | id | order_date | shipped_date | |---:|---|---| | 455 | 2025-12-30 | NULL | | 933 | 2025-12-30 | NULL | | 1325 | 2025-12-30 | NULL | | 1421 | 2025-12-27 | NULL | | 1634 | 2025-12-31 | NULL | > **GROUP BY uses the column, not the alias:** > When an alias has the same name as a column, `GROUP BY name` refers to the **column**. In `SELECT a, NVL(b, 2) AS b FROM t1 GROUP BY a, b`, the rows are grouped by the column `b`, not by `NVL(b, 2)`. Use a distinct alias (or repeat the expression) to group by the expression. ## LIMIT clause **LIMIT** restricts the number of rows returned, optionally after skipping *offset* rows. ```sql LIMIT {[offset,] row_count | row_count [OFFSET offset]} ::= ::= ``` - *offset*: number of rows to skip; the first row has offset 0 (default). - *row_count*: maximum number of rows to return. - Both can be unsigned integers, host variables (`?`) or simple expressions such as `? * ?`, so `LIMIT` works in [prepared statements](https://www.coradb.ai/manual/sql/query/prepare.html). - `INST_NUM()` and `ROWNUM` cannot be used in the `WHERE` clause of a query with `LIMIT`, and `LIMIT` cannot be combined with `HAVING GROUPBY_NUM()`. The 11th to 15th most recent orders (a typical "page 3" with five rows per page): ```sql SELECT id, order_date FROM orders ORDER BY order_date DESC, id LIMIT 5 OFFSET 10; -- same as LIMIT 10, 5 ``` | id | order_date | |---:|---| | 414 | 2025-12-29 | | 832 | 2025-12-29 | | 1208 | 2025-12-29 | | 517 | 2025-12-28 | | 707 | 2025-12-28 | With a prepared statement: ```sql PREPARE recent_orders FROM 'SELECT id, order_date FROM orders ORDER BY order_date DESC, id LIMIT ?, ?'; EXECUTE recent_orders USING 10, 5; ``` ## Join query A join combines rows from two or more tables (or views, derived tables and graph patterns). The *join condition* compares columns of the joined sources; only combinations that satisfy it are returned. A join with `=` is an *equi-join*, a join without a condition is a *cartesian product*, and joining a table to itself is a *self join* (use aliases to tell the two copies apart). ```sql FROM [{, | { | }} ...] ::= [INNER | {LEFT | RIGHT} [OUTER]] JOIN ON ::= { CROSS JOIN | NATURAL [ LEFT | RIGHT ] JOIN } ``` - **[INNER] JOIN**: returns only rows that satisfy the join condition. - **{LEFT | RIGHT} [OUTER] JOIN**: also returns the rows of the left (or right) source that have no match, with **NULL** for the other side. CoraDB does not support `FULL OUTER JOIN`. - **CROSS JOIN**: every combination of rows, without a condition. - **NATURAL [LEFT | RIGHT] JOIN**: joins on all columns that have the same name in both sources. ### Inner join `INNER` can be omitted, and the inner join can also be written with a comma and a `WHERE` condition. Orders placed on the last day of 2025, with the customer's company name (the `customer` vertex table is joined like a relational table): ```sql SELECT o.id, o.order_date, cu.company_name FROM orders o INNER JOIN customer cu ON cu.id = o.customer_id WHERE o.order_date = DATE'2025-12-31' ORDER BY o.id; ``` | id | order_date | company_name | |---:|---|---| | 376 | 2025-12-31 | Reyes, Farmer and West | | 1127 | 2025-12-31 | Owens, Mathis and Romero | | 1446 | 2025-12-31 | Harris-Jones | | 1634 | 2025-12-31 | Anderson-Meyer | | 1888 | 2025-12-31 | Price, Whitney and Carr | ### Outer join An outer join keeps the rows of one side even when they have no match. Customers that never ordered appear with an order count of 0: ```sql SELECT cu.company_name, COUNT(o.id) AS orders FROM customer cu LEFT OUTER JOIN orders o ON o.customer_id = cu.id GROUP BY cu.id, cu.company_name ORDER BY orders, cu.company_name LIMIT 5; ``` | company_name | orders | |---|---:| | Adams, Pena and Hansen | 0 | | Adams-Barnes | 0 | | Adams-Greer | 0 | | Adams-Obrien | 0 | | Alexander LLC | 0 | The tables are joined in the order they appear in the `FROM` clause, so write outer joins with the table order in mind. A `RIGHT OUTER JOIN` can always be rewritten as a `LEFT OUTER JOIN` by swapping the two tables. **Conditions in `ON` and in `WHERE` mean different things.** In an outer join, a condition in `ON` only decides which rows match; every row of the preserved side is still returned. A condition in `WHERE` is applied *after* the join and removes rows: ```sql -- condition in ON: all 1000 customers are kept, 2025 orders are attached when they exist SELECT COUNT(*) AS rows_returned FROM customer cu LEFT OUTER JOIN orders o ON o.customer_id = cu.id AND o.order_date >= DATE'2025-01-01'; -- condition in WHERE: only rows with a 2025 order remain SELECT COUNT(*) AS rows_returned FROM customer cu LEFT OUTER JOIN orders o ON o.customer_id = cu.id WHERE o.order_date >= DATE'2025-01-01'; ``` | query | rows_returned | |---|---:| | Condition in `ON` | 1394 | | Condition in `WHERE` | 786 | CoraDB also accepts the Oracle-style `(+)` notation in the `WHERE` clause. It is not ISO/ANSI SQL and can be ambiguous, so prefer `LEFT | RIGHT OUTER JOIN`. Both queries below count the 350 customers without orders: ```sql SELECT COUNT(*) AS customers_without_orders FROM customer cu LEFT OUTER JOIN orders o ON o.customer_id = cu.id WHERE o.id IS NULL; SELECT COUNT(*) AS customers_without_orders FROM customer cu, orders o WHERE cu.id = o.customer_id(+) AND o.id IS NULL; ``` | customers_without_orders | |---:| | 350 | Path expressions that include subqueries and sub-columns cannot be used in the join condition of an outer join. ### Cross join A cross join returns the cartesian product of the two sources. `CROSS JOIN` can be replaced by a comma. ```sql SELECT COUNT(*) AS combinations FROM countries CROSS JOIN category; -- 25 countries x 32 categories ``` | combinations | |---:| | 800 | ### Natural join A natural join uses all columns with the same name as the join condition. Here both derived tables have a `customer_id` column: ```sql SELECT c.customer_id, c.company_name, o.n AS orders FROM (SELECT id AS customer_id, company_name FROM customer) c NATURAL JOIN (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) o ORDER BY o.n DESC, c.customer_id LIMIT 3; ``` | customer_id | company_name | orders | |---:|---|---:| | 440 | Mayer, Carroll and Owens | 40 | | 812 | Young and Sons | 40 | | 444 | Kelly Ltd | 39 | This is the same as `INNER JOIN ... ON c.customer_id = o.customer_id`. `NATURAL LEFT JOIN` and `NATURAL RIGHT JOIN` are the outer-join equivalents. With `SELECT *`, both `customer_id` columns are returned, so qualify the column in `ORDER BY`. ### Joining graph patterns and tables A [MATCH](https://www.coradb.ai/manual/graph/match.html) pattern is a table specification too, so graph patterns can be joined with relational tables in the same `FROM` clause. London customers with the most orders: ```sql SELECT cu.company_name, COUNT(o.id) AS orders FROM MATCH (cu:customer)-[:resides_in]->(ci:city), orders o WHERE o.customer_id = cu.id AND ci.name = 'London' GROUP BY cu.company_name ORDER BY orders DESC, cu.company_name LIMIT 3; ``` | cu.company_name | orders | |---|---:| | Hicks-Marshall | 15 | | Jordan, Smith and Bartlett | 15 | | Hernandez, Wilson and Johnson | 10 | `MATCH` patterns also work with `INNER`, `LEFT` and `RIGHT [OUTER] JOIN ... ON`. See [Joining MATCH patterns](https://www.coradb.ai/manual/graph/match.html#joining-match-patterns-and-tables). ## Subquery A subquery can be used wherever an expression is allowed, for example in the select list or in the `WHERE` clause. Used as a value, it must return a single column. Subqueries are *single-row* or *multiple-row*. ### Single-row subquery A single-row subquery returns one column of one row. If it returns no row, its value is **NULL**; if it returns more than one row, an error is raised. ```sql SELECT o.id, o.order_date, (SELECT cu.company_name FROM customer cu WHERE cu.id = o.customer_id) AS customer FROM orders o ORDER BY o.id LIMIT 5; ``` | id | order_date | customer | |---:|---|---| | 0 | 2021-11-07 | Peterson-Williams | | 1 | 2025-10-19 | Hicks Group | | 2 | 2022-09-05 | Doyle, Mcdonald and Lowery | | 3 | 2023-12-27 | Washington LLC | | 4 | 2024-09-20 | Davidson, Jefferson and Mack | ### Multiple-row subquery A multiple-row subquery returns one column of several rows. With the `SET`, `MULTISET` or `LIST` keyword, the rows become a collection value. Use `ORDER BY` inside the subquery to control the order of a `LIST`. ```sql SELECT c.name, LIST(SELECT ci.name FROM city ci WHERE ci.country_code = c.code ORDER BY ci.name) AS cities FROM countries c WHERE c.code IN ('AUT', 'BEL') ORDER BY c.name; ``` | name | cities | |---|---| | Austria | {'Graz', 'Salzburg'} | | Belgium | {'Bruxelles', 'Charleroi'} | Multiple-row subqueries can be used wherever a collection value is allowed, but not where a collection *constant* is required, such as the `DEFAULT` value of a column. ## MATCH `MATCH` queries graph patterns over vertex tables and edge tables (created with `CREATE VERTEX TABLE` and `CREATE EDGE TABLE`). It is used in the `FROM` clause, and as a predicate in `WHERE`: ```sql SELECT ... FROM MATCH [ =] [ANY_SHORTEST | ALL_SHORTEST] [, ...] ``` Brands with the most followers: ```sql SELECT b.name, COUNT(cu) AS followers FROM MATCH (cu:customer)-[:follows]->(b:brand) GROUP BY b.name ORDER BY followers DESC, b.name LIMIT 5; ``` | b.name | followers | |---|---:| | Nike | 209 | | Adidas | 132 | | Puma | 94 | | Reebok | 83 | | Under Armour | 76 | The full syntax (directions, variable-length paths, shortest paths, path variables, `MATCH` predicates and joins) is described in [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html); [Relational and graph in one query](https://www.coradb.ai/manual/sql/hybrid.html) shows more ways to combine patterns with tables. ## VALUES The **VALUES** clause returns the rows written in the statement. It is a short way to write a `UNION ALL` of constant rows, and it can be used as a derived table. All rows must have the same number of values. ```sql VALUES (expression[, ...])[, ...] ``` ```sql VALUES (1 AS id, 'standard' AS shipping), (2, 'express'), (3, 'pickup'); ``` | id | shipping | |---:|---| | 1 | standard | | 2 | express | | 3 | pickup | This is equivalent to: ```sql SELECT 1 AS id, 'standard' AS shipping UNION ALL SELECT 2, 'express' UNION ALL SELECT 3, 'pickup'; ``` As a derived table, joined with a real table: ```sql SELECT t.code, c.name FROM (VALUES ('FRA'), ('DEU'), ('ITA')) AS t(code) INNER JOIN countries c ON c.code = t.code ORDER BY c.name; ``` | code | name | |---|---| | FRA | France | | DEU | Germany | | ITA | Italy | `VALUES` with several rows is also used in [INSERT](https://www.coradb.ai/manual/sql/query/insert.html). ## FOR UPDATE **FOR UPDATE** locks the rows returned by the `SELECT` (with an exclusive `X_LOCK`) so that the transaction can update or delete them later without another transaction changing them first. ```sql SELECT ... [FOR UPDATE [OF ]] ::= [, , ... ] ::= table_name | view_name ``` - *spec_name_comma_list*: the tables or views of the `FROM` clause whose rows are locked. Without `OF`, all tables and views of the `FROM` clause are locked. > **Restrictions:** > - `FOR UPDATE` cannot be used inside a subquery (it can reference subqueries). > - It cannot be used with `GROUP BY`, `DISTINCT` or aggregate functions. > - It cannot reference a `UNION`. Lock the orders that still have to be shipped, then mark them as shipped in the same transaction: ```sql SELECT id, shipped_date FROM orders WHERE shipped_date IS NULL ORDER BY id FOR UPDATE; UPDATE orders SET shipped_date = SYSDATE WHERE shipped_date IS NULL; COMMIT; ``` Other forms: ```sql SELECT * FROM orders o INNER JOIN order_items oi ON oi.order_id = o.id WHERE o.shipped_date IS NULL FOR UPDATE OF o; -- lock only the orders rows SELECT * FROM orders o INNER JOIN (SELECT * FROM order_items WHERE quantity > 5) big ON big.order_id = o.id WHERE o.shipped_date IS NULL FOR UPDATE; -- a derived table can be referenced ``` ## See also - [MATCH clause: graph queries in SELECT](https://www.coradb.ai/manual/graph/match.html) - [Common table expressions (WITH)](https://www.coradb.ai/manual/sql/query/cte.html) - [Hierarchical queries](https://www.coradb.ai/manual/sql/query/hq.html) - [UNION, DIFFERENCE, INTERSECTION](https://www.coradb.ai/manual/sql/function/stmt_set_op.html) - [Aggregate & analytic functions](https://www.coradb.ai/manual/sql/function/analysis_fn.html) - [Query optimization: statistics, plans and hints](https://www.coradb.ai/manual/sql/tuning.html) --- # SET statement (session variables) Source: https://www.coradb.ai/manual/sql/query/set.html The **SET** statement has two uses: changing the value of a system parameter, and assigning user-defined variables that keep a value for the rest of your session. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. Connect with `corasql -u dba e-commerce`; variables and parameter changes last only until you disconnect. ## System parameters ```text SET SYSTEM PARAMETERS 'parameter_name=value [; parameter_name=value ...]' ``` Only some parameters can be changed while the database is running; which ones, and whether a change applies to your session or to the whole server, is listed in [Using SQL statements](https://www.coradb.ai/manual/admin/config.html#with-sql) of the configuration chapter. Set several parameters at once by separating them with semicolons: ```sql SET SYSTEM PARAMETERS 'cte_max_recursions=100; lock_timeout=10'; ``` Use `DEFAULT` as the value to go back to the parameter's default: ```sql SET SYSTEM PARAMETERS 'lock_timeout=DEFAULT; cte_max_recursions=DEFAULT'; ``` ## User-defined variables A user-defined variable is a name that starts with `@` and holds one value for the rest of your session (connection). Variables are private to the session that created them and disappear when it ends. ```text SET @name = expression [, @name = expression ...] SET @name := expression [, ...] -- inside another statement @name := expression {DEALLOCATE | DROP} VARIABLE @name [, @name ...] ``` - Names are made of letters, digits and underscores, and are not case-sensitive: `@V1` and `@v1` are the same variable. - A name cannot be a [reserved word](https://www.coradb.ai/manual/sql/keyword.html): `@limit` or `@last` is a syntax error. Choose names such as `@max_rows` or `@last_day`. - In `SET`, both `=` and `:=` assign. Inside other statements, use `:=`, because `=` is the comparison operator there. - Reading a variable that was never set, or was dropped, is an error: `Session variable '@v1' not defined.` ### Assigning and using variables Store a value, then use it in a later query: ```sql SET @min_price = 120; SELECT id, name, unit_price FROM product WHERE unit_price > @min_price ORDER BY unit_price DESC; ``` | id | name | unit_price | |---:|---|---:| | 38 | Côte de Blaye | 263.50 | | 29 | Thüringer Rostbratwurst | 123.79 | Capture a query result with `:=` and reuse it. The last order date is stored in `@last_day`, and the next query counts the orders of that day: ```sql SELECT @last_day := MAX(order_date) FROM orders; SELECT COUNT(*) FROM orders WHERE order_date = @last_day; ``` ```text 5 ``` Variables are also a convenient way to pass values to [prepared statements](https://www.coradb.ai/manual/sql/query/prepare.html#execute-statement): ```sql SET @min_price = 120, @max_rows = 2; PREPARE by_price FROM 'SELECT id, name FROM product WHERE unit_price > ? LIMIT ?'; EXECUTE by_price USING @min_price, @max_rows; ``` ### Assigning in every row An assignment in the select list runs once per row, so a variable can number the rows of a result. The five latest orders of customer 440: ```sql SET @n = 0; SELECT @n := @n + 1 AS row_no, id, order_date FROM orders WHERE customer_id = 440 ORDER BY order_date DESC LIMIT 5; ``` | row_no | id | order_date | |---:|---:|---| | 1 | 1651 | 2025-12-27 | | 2 | 462 | 2025-12-15 | | 3 | 2544 | 2025-11-16 | | 4 | 1611 | 2025-11-13 | | 5 | 1831 | 2025-11-03 | For numbering rows, the window function [ROW_NUMBER()](https://www.coradb.ai/manual/sql/function/analysis_fn.html#row_number) is usually the clearer choice. When a statement both assigns and reads the same variable in different clauses (for example, assigns it in the select list and reads it in `HAVING`), the order of evaluation is not guaranteed. ### Variable types A variable takes the type of the value assigned to it, and assigning a new value can change the type: ```sql SET @v1 = 1, @v2 = CAST(1 AS BIGINT), @v3 = '123', @v4 = DATE'2025-12-01'; SELECT TYPEOF(@v1), TYPEOF(@v2), TYPEOF(@v3), TYPEOF(@v4); ``` | typeof(@v1) | typeof(@v2) | typeof(@v3) | typeof(@v4) | |---|---|---|---| | integer | bigint | character (-1) | character varying (1073741823) | Variables can hold `SHORT`, `INTEGER`, `BIGINT`, `FLOAT`, `DOUBLE`, `NUMERIC`, `CHAR`, `VARCHAR`, `BIT` and `BIT VARYING` values. Values of other types are converted to `VARCHAR`; that is why the date in `@v4` is stored as a character string. Comparisons such as `order_date = @last_day` above still work, because the string is converted back to a date for the comparison. ### Dropping variables `DEALLOCATE VARIABLE` and `DROP VARIABLE` are the same statement: ```sql DEALLOCATE VARIABLE @v1, @v2; DROP VARIABLE @v3, @v4; ``` > **Note:** > The session also keeps your [prepared statements](https://www.coradb.ai/manual/sql/query/prepare.html), the last generated `AUTO_INCREMENT` value ([LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id)) and the row count of the last statement ([ROW_COUNT](https://www.coradb.ai/manual/sql/function/information_fn.html#row_count)). An idle session expires after `session_state_timeout` seconds. ## Other SET and GET statements Several other statements start with **SET** and change a setting of the current session; most have a **GET** counterpart that reads the setting, optionally into a host variable with `INTO :variable` (or `TO :variable`): | Statement | Reads with | Described in | |---|---|---| | `SET TRANSACTION ISOLATION LEVEL level` | `GET TRANSACTION ISOLATION LEVEL` | [Isolation levels](https://www.coradb.ai/manual/sql/transaction_isolation.html) | | `SET TRANSACTION LOCK TIMEOUT { INFINITE \| OFF \| seconds }` | `GET TRANSACTION LOCK TIMEOUT` | [Locking & deadlocks](https://www.coradb.ai/manual/sql/transaction_locking.html) | | `SET OPTIMIZATION LEVEL level` | `GET OPTIMIZATION LEVEL` | [Query plans](https://www.coradb.ai/manual/sql/tuning_plan.html#viewing-query-plan) | | `SET TRACE { ON \| OFF } [ OUTPUT { TEXT \| JSON } ]` | `SHOW TRACE` | [Query profiling](https://www.coradb.ai/manual/sql/tuning_plan.html#query-profiling) | | `SET TRIGGER TRACE { ON \| OFF }` | `GET TRIGGER TRACE` | [Triggers](https://www.coradb.ai/manual/sql/trigger.html#viewing-trigger-execution-log) | | `SET TRIGGER [MAXIMUM] DEPTH count` | `GET TRIGGER [MAXIMUM] DEPTH` | [Triggers](https://www.coradb.ai/manual/sql/trigger.html#limiting-nested-trigger) | | `SET NAMES charset [COLLATE collation]` | | [SET NAMES](https://www.coradb.ai/manual/sql/i18n_collation.html#set-names-statement) | | | `GET STATISTICS 'item' OF table` | [Statistics](https://www.coradb.ai/manual/sql/tuning.html#get-statistics) | ```sql SET TRANSACTION LOCK TIMEOUT 5; GET TRANSACTION LOCK TIMEOUT INTO :lt; GET TRANSACTION ISOLATION LEVEL INTO :iso; SELECT :lt, :iso; -- 5, 4 (4 = READ COMMITTED) ``` **SET OPTIMIZATION COST** and **GET OPTIMIZATION COST** adjust and read internal cost settings of the optimizer, for diagnosis only; leave them at their defaults. ## See also - [System parameters](https://www.coradb.ai/manual/admin/config.html) - [Prepared statements](https://www.coradb.ai/manual/sql/query/prepare.html) --- # SHOW statements Source: https://www.coradb.ai/manual/sql/query/show.html **SHOW** statements return information about the database itself: its tables and their columns, indexes and definitions, user permissions, the supported collations and time zones, and, for administrators, the internal state of the server. Their results are ordinary result sets, so most of them accept `LIKE` or `WHERE` to filter the rows. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. Connect with `corasql -u dba e-commerce`. For statements that return many columns, switch corasql to one-column-per-line output with the `;line on` session command. ## SHOW TABLES Lists the tables of the current database. ```text SHOW [FULL] TABLES [LIKE 'pattern' | WHERE expr] ``` - The result column is named `Tables_in_`. - **FULL** adds a `Table_type` column: `BASE TABLE` for a relational table, `VERTEX TABLE` and `EDGE TABLE` for graph tables, and `VIEW` for a view. - **LIKE** filters on the table name; **WHERE** can use both columns. ```sql SHOW FULL TABLES LIKE '%o%'; ``` | Tables_in_e-commerce | Table_type | |---|---| | category | VERTEX TABLE | | countries | BASE TABLE | | customer | VERTEX TABLE | | follows | EDGE TABLE | | located_at | EDGE TABLE | | located_in | EDGE TABLE | | order_items | BASE TABLE | | orders | BASE TABLE | | part_of | EDGE TABLE | | product | VERTEX TABLE | List only the vertex tables: ```sql SHOW FULL TABLES WHERE table_type = 'VERTEX TABLE'; ``` | Tables_in_e-commerce | Table_type | |---|---| | brand | VERTEX TABLE | | category | VERTEX TABLE | | city | VERTEX TABLE | | customer | VERTEX TABLE | | product | VERTEX TABLE | | supplier | VERTEX TABLE | The database name `e-commerce` contains a hyphen, so the name column must be written in brackets when you use it in `WHERE`: ```sql SHOW FULL TABLES WHERE table_type = 'BASE TABLE' AND [Tables_in_e-commerce] LIKE 'order%'; ``` | Tables_in_e-commerce | Table_type | |---|---| | order_items | BASE TABLE | | orders | BASE TABLE | ## SHOW COLUMNS, DESCRIBE Lists the columns of a table or view. ```text SHOW [FULL] {COLUMNS | FIELDS} {FROM | IN} table_name [LIKE 'pattern' | WHERE expr] {DESCRIBE | DESC | EXPLAIN} table_name ``` `SHOW FIELDS` is a synonym of `SHOW COLUMNS`. `DESCRIBE`, its short form `DESC` and `EXPLAIN` *table_name* return the same columns as `SHOW COLUMNS`, without the `LIKE` and `WHERE` options. | Column | Description | |---|---| | Field | Column name. | | Type | Data type. | | Collation | Collation of a character column (with `FULL` only). | | Null | `YES` if the column accepts `NULL`, `NO` otherwise. | | Key | `PRI` if the column is (part of) the primary key, `UNI` if it is the first column of a unique index, `MUL` if it is the first column of a non-unique index; empty otherwise. When several apply, the first in this order is shown. | | Default | Default value of the column. | | Extra | Additional information, such as `auto_increment`. | | Comment | Column comment (with `FULL` only). | ```sql SHOW COLUMNS FROM orders; ``` | Field | Type | Null | Key | Default | Extra | |---|---|---|---|---|---| | id | INTEGER | NO | PRI | NULL | | | customer_id | INTEGER | NO | MUL | NULL | | | shipped_date | DATE | YES | MUL | NULL | | | shipping_cost | NUMERIC(10,2) | NO | | NULL | | | ship_address | VARCHAR(128) | NO | | NULL | | | order_date | DATE | NO | MUL | NULL | | ```sql DESC countries; ``` | Field | Type | Null | Key | Default | Extra | |---|---|---|---|---|---| | code | VARCHAR(8) | NO | PRI | NULL | | | name | VARCHAR(32) | NO | | NULL | | ## SHOW INDEX Lists the indexes of a table, one row per indexed column. ```text SHOW {INDEX | INDEXES | KEYS} {FROM | IN} table_name ``` | Column | Description | |---|---| | Table | Table name. | | Non_unique | 0 if the index cannot contain duplicate values, 1 if it can. | | Key_name | Index name. | | Seq_in_index | Position of the column in the index, starting at 1. | | Column_name | Column name. | | Collation | Sort order of the column in the index: `A` (ascending), `D` (descending) or `NULL`. | | Cardinality | Approximate number of distinct values in the index. The higher it is, the more selective the index. | | Sub_part | Number of characters indexed when only a prefix of the column is indexed, as in `CREATE INDEX ... (name(7))`; `NULL` when the whole column is indexed. | | Packed | How the key is packed; always `NULL`. | | Null | `YES` if the column accepts `NULL`, `NO` otherwise. | | Index_type | Index structure; always `BTREE`. | | Func | The expression of a function-based index, otherwise `NULL`. | | Comment | Index comment. | | Visible | `YES` if the optimizer can use the index, `NO` if it is invisible. | | Shared | 1 for a [shared index](https://www.coradb.ai/manual/sql/tuning_special_index.html#shared-index) (one index structure shared by a table and its subclasses), 0 otherwise. | ```sql SHOW INDEX FROM order_items; ``` | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Func | Comment | Visible | Shared | |---|---:|---|---:|---|---|---:|---|---|---|---|---|---|---|---:| | order_items | 1 | fk_order_items_order_id | 1 | order_id | A | 2914 | NULL | NULL | NO | BTREE | NULL | NULL | YES | 0 | | order_items | 1 | fk_order_items_product_id | 1 | product_id | A | 1832 | NULL | NULL | NO | BTREE | NULL | NULL | YES | 0 | | order_items | 0 | pk_order_items_order_id_product_id | 1 | order_id | A | 11230 | NULL | NULL | NO | BTREE | NULL | NULL | YES | 0 | | order_items | 0 | pk_order_items_order_id_product_id | 2 | product_id | A | 11230 | NULL | NULL | NO | BTREE | NULL | NULL | YES | 0 | ## SHOW CREATE TABLE Returns the statement that would create the table as it is now. ```text SHOW CREATE TABLE table_name ``` ```sql SHOW CREATE TABLE countries; ``` | TABLE | CREATE TABLE | |---|---| | countries | `CREATE TABLE [countries] ([code] CHARACTER VARYING(8) NOT NULL, [name] CHARACTER VARYING(32) NOT NULL, CONSTRAINT [pk_countries_code] PRIMARY KEY ([code])) REUSE_OID, COLLATE utf8_bin` | For a vertex or edge table the statement starts with `CREATE GRAPH VERTEX TABLE` or `CREATE GRAPH EDGE TABLE`: ```sql SHOW CREATE TABLE product; ``` | TABLE | CREATE TABLE | |---|---| | product | `CREATE GRAPH VERTEX TABLE [product] ([id] INTEGER NOT NULL, [name] CHARACTER VARYING(64) NOT NULL, [description] CHARACTER VARYING(32) NOT NULL, [unit_price] NUMERIC(10,2) NOT NULL, [units_in_stock] SMALLINT NOT NULL, CONSTRAINT [pk_product_id] PRIMARY KEY ([id]), INDEX [idx_product_name] ([name])) DONT_REUSE_OID, COLLATE utf8_bin` | The statement is rebuilt from the catalog, not stored as you typed it: names are in lowercase and enclosed in brackets, types use their full names (`CHARACTER VARYING` for `VARCHAR`), and the table options in effect, such as `REUSE_OID` and the collation, are always written out. ## SHOW CREATE VIEW Returns the query that defines a view. ```text SHOW CREATE VIEW view_name ``` ```sql CREATE VIEW low_stock AS SELECT id, name, units_in_stock FROM product WHERE units_in_stock < 5; SHOW CREATE VIEW low_stock; ``` | View | Create view | |---|---| | low_stock | `create view [low_stock] as select [product].[id], [product].[name], [product].[units_in_stock] from [product] [product] where [product].[units_in_stock]<5` | ## SHOW GRANTS Lists the permissions granted to a user. ```text SHOW GRANTS FOR user_name ``` ```sql CREATE USER report_reader; GRANT SELECT ON orders TO report_reader; GRANT SELECT, UPDATE ON order_items TO report_reader; SHOW GRANTS FOR report_reader; ``` | Grants for REPORT_READER | |---| | GRANT SELECT ON orders TO REPORT_READER | | GRANT SELECT, UPDATE ON order_items TO REPORT_READER | See [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant) for the permissions you can give. ## SHOW COLLATION Lists the collations available in the database. ```text SHOW COLLATION [LIKE 'pattern'] ``` | Column | Description | |---|---| | Collation | Collation name. | | Charset | Character set of the collation. | | Id | Collation ID. | | Built_in | `Yes` for the collations built into CoraDB, which cannot be added or removed; `No` for collations added to the database. | | Expansions | Whether the collation uses expansions. See [Expansion](https://www.coradb.ai/manual/sql/i18n_collation.html#expansion). | | Strength | Number of levels considered when comparing characters. See [Collation properties](https://www.coradb.ai/manual/sql/i18n.html#collation-properties). | ```sql SHOW COLLATION LIKE 'utf8_en%'; ``` | Collation | Charset | Id | Built_in | Expansions | Strength | |---|---|---:|---|---|---| | utf8_en_ci | utf8 | 5 | Yes | No | Not applicable | | utf8_en_cs | utf8 | 4 | Yes | No | Not applicable | A database lists only the built-in collations unless locale-specific collations have been added to it; see [Internationalization](https://www.coradb.ai/manual/sql/i18n.html). ## SHOW TIMEZONES Lists the time zone regions CoraDB knows. ```text SHOW [FULL] TIMEZONES [LIKE 'pattern'] ``` Without `FULL`, the result has one column, `timezone_region`. With `FULL` it has four: | Column | Description | |---|---| | timezone_region | Region name, such as `Europe/Paris`. | | region_offset | Offset from UTC without daylight saving time. | | dst_offset | Daylight saving offset in effect now. `NULL` if the region has no daylight saving rules at all; `+00:00` if it has rules but none applies today. | | dst_abbreviation | Abbreviation of the time currently in effect, such as `CET`. `NULL` if the region has no daylight saving rules. | The offsets and abbreviations are those in effect at the current date and time. `LIKE` filters on `timezone_region`. ```sql SHOW FULL TIMEZONES LIKE 'Europe/B%'; ``` | timezone_region | region_offset | dst_offset | dst_abbreviation | |---|---|---|---| | Europe/Belfast | +00:00 | +00:00 | GMT | | Europe/Belgrade | +01:00 | +00:00 | CET | | Europe/Berlin | +01:00 | +00:00 | CET | | Europe/Bratislava | +01:00 | +00:00 | CET | | Europe/Brussels | +01:00 | +00:00 | CET | | Europe/Bucharest | +02:00 | +00:00 | EET | | Europe/Budapest | +01:00 | +00:00 | CET | | Europe/Busingen | +01:00 | +00:00 | CET | ## SHOW ACCESS STATUS Shows when each database user last logged in, and from where. Only the `DBA` user can run it. ```text SHOW ACCESS STATUS [LIKE 'pattern' | WHERE expr] ``` | Column | Description | |---|---| | user_name | Database user. | | last_access_time | Time of the user's last login, `NULL` if the user never logged in. | | last_access_host | Host the user last connected from. | | program_name | Client program used, for example `corasql` or a broker process such as `broker1_cora_cas_1`. | ```sql SHOW ACCESS STATUS WHERE user_name = 'DBA'; ``` ## SHOW EXEC STATISTICS Shows execution statistics collected for your session. Collection is off by default: set the session variable `@collect_exec_stats` to 1 to start it and to 0 to stop it. ```text SHOW EXEC STATISTICS [ALL] ``` - Without `ALL`, the result has four rows with data page statistics: `data_page_fetches`, `data_page_dirties`, `data_page_ioreads` and `data_page_iowrites`. - With `ALL`, it lists every statistic the server collects. For their meaning, see [statdump](https://www.coradb.ai/manual/admin/admin_statdump.html#statdump). ```sql SET @collect_exec_stats = 1; SELECT COUNT(*) FROM order_items WHERE discount_pct > 0; SHOW EXEC STATISTICS; ``` | variable | value | |---|---:| | data_page_fetches | 44 | | data_page_dirties | 0 | | data_page_ioreads | 0 | | data_page_iowrites | 0 | The values depend on what the server already had in memory, so you will see different numbers. ## Diagnostics The following statements show the internal state of database volumes, logs, tables, indexes and server threads. They are meant for administrators and for CoraDB support when analyzing performance or storage problems. Their output depends on the server and changes all the time; the examples show excerpts of real output in corasql's `;line on` format. Some statements return additional columns that are reserved for internal use; they are not listed in the tables below. ### SHOW VOLUME HEADER Shows the header of a database volume. ```text SHOW VOLUME HEADER OF volume_id ``` | Column | Type | Description | |---|---|---| | Volume_id | INT | Volume identifier | | Magic_symbol | VARCHAR(100) | Magic value for for a volume file | | Io_page_size | INT | Size of DB volume | | Purpose | VARCHAR(32) | Volume purposes, 'Permanent data purpose' or 'Temporary data purpose' | | Type | VARCHAR(32) | Volume type, 'Permanent Volume' or 'Temporary Volume' | | Sector_size_in_pages | INT | Size of sector in pages | | Num_total_sectors | INT | Total number of sectors | | Num_free_sectors | INT | Number of free sectors | | Num_max_sectors | INT | Maximum number of sectors | | Hint_alloc_sector | INT | Hint for next sector to be allocated | | Sector_alloc_table_size_in_pages | INT | Size of sector allocation table in page | | Sector_alloc_table_first_page | INT | First page of sector allocation table | | Last_system_page | INT | Last system page | | Creation_time | DATETIME | Database creation time | | Db_charset | INT | Charset number of database | | Checkpoint_lsa | VARCHAR(64) | Lowest log sequence address to start the recovery process of this volume | | Boot_hfid | VARCHAR(64) | System Heap file for booting purposes and multi volumes | | Full_name | VARCHAR(255) | The full path of volume | | Next_volume_id | INT | Next volume identifier | | Next_vol_full_name | VARCHAR(255) | The full path of next volume | | Remarks | VARCHAR(64) | Volume remarks | ```sql SHOW VOLUME HEADER OF 0; ``` ```text <00001> Volume_id : 0 Magic_symbol : 'MAGIC SYMBOL = CORADB/Volume at disk location = 32' Io_page_size : 16384 Purpose : 'Permanent data purpose' Type : 'Permanent Volume' Sector_size_in_pages: 64 Num_total_sectors : 512 Num_free_sectors : 418 ... Creation_time : 05:50:05.000 PM 08/06/2026 Db_charset : 5 ... Full_name : '/home/qa/CORADB/databases/e-commerce/e-commerce' Next_volume_id : -1 ``` ### SHOW LOG HEADER Shows the header of the active log. Without `OF`, the header kept in the server's memory is shown; with `OF` *file_name*, the header stored in that log file. ```text SHOW LOG HEADER [OF file_name] ``` | Column | Type | Description | |---|---|---| | Volume_id | INT | Volume identifier | | Magic_symbol | VARCHAR(32) | Magic value for log file | | Magic_symbol_location | INT | Magic symbol location from log page | | Creation_time | DATETIME | Database creation time | | Release | VARCHAR(32) | CoraDB Release version | | Compatibility_disk_version | VARCHAR(32) | Compatibility of the database against the current release of CoraDB | | Db_page_size | INT | Size of pages in the database | | Log_page_size | INT | Size of log pages in the database | | Shutdown | INT | Was the log shutdown | | Next_trans_id | INT | Next transaction identifier | | Num_avg_trans | INT | Number of average transactions | | Num_avg_locks | INT | Average number of object locks | | Num_active_log_pages | INT | Number of pages in the active log portion | | Db_charset | INT | Charset number of database | | First_active_log_page | BIGINT | Logical pageid at physical location 1 in active log | | Current_append | VARCHAR(64) | Current append location | | Checkpoint | VARCHAR(64) | Lowest log sequence address to start the recovery process | | Next_archive_page_id | BIGINT | Next logical page to archive | | Active_physical_page_id | INT | Physical location of logical page to archive | | Next_archive_num | INT | Next log archive number | | Last_archive_num_for_syscrashes | INT | Last log archive needed for system crashes | | Last_deleted_archive_num | INT | Last deleted archive number | | Backup_lsa_level0 | VARCHAR(64) | LSA of backup level 0 | | Backup_lsa_level1 | VARCHAR(64) | LSA of backup level 1 | | Backup_lsa_level2 | VARCHAR(64) | LSA of backup level 2 | | Log_prefix | VARCHAR(256) | Log prefix name | | Has_logging_been_skipped | INT | Whether or not logging skipped | | Perm_status | VARCHAR(64) | Reserved for future expansion | | Backup_info_level0 | VARCHAR(128) | Detail information of backup level 0. currently only backup start-time is used | | Backup_info_level1 | VARCHAR(128) | Detail information of backup level 1. currently only backup start-time is used | | Backup_info_level2 | VARCHAR(128) | Detail information of backup level 2. currently only backup start-time is used | | Eof_lsa | VARCHAR(64) | EOF LSA | | Smallest_lsa_at_last_checkpoint | VARCHAR(64) | The smallest LSA of the last checkpoint, can be NULL LSA | | Next_mvcc_id | BIGINT | The next MVCCID will be used for the next transaction | | Mvcc_op_log_lsa | VARCHAR(32) | The LSA used to link log entries for MVCC operation | | Last_block_oldest_mvcc_id | BIGINT | Used to find the oldest MVCCID in a block of log data, can be NULL | | Last_block_newest_mvcc_id | BIGINT | Used to find the newest MVCCID in a block of log data, can be NULL | ```sql SHOW LOG HEADER; ``` ```text <00001> Volume_id : -2 Magic_symbol : 'CORADB/LogActive' Magic_symbol_location : 16 Creation_time : 05:50:05.000 PM 08/06/2026 Release : '1.0.0' Compatibility_disk_version: '11' Db_page_size : 16384 Log_page_size : 16384 Shutdown : 0 ... Log_prefix : 'e-commerce' ... ``` ### SHOW ARCHIVE LOG HEADER Shows the header of an archive log file. Give the full path of the file, because a relative name is resolved from the server's working directory. ```text SHOW ARCHIVE LOG HEADER OF file_name ``` | Column | Type | Description | |---|---|---| | Volume_id | INT | Identifier of log volume | | Magic_symbol | VARCHAR(32) | Magic value for file/magic Unix utility | | Magic_symbol_location | INT | Magic symbol location from log page | | Creation_time | DATETIME | Database creation time | | Next_trans_id | BIGINT | Next transaction identifier | | Num_pages | INT | Number of pages in the archive log | | First_page_id | BIGINT | Logical page id at physical location 1 in archive log | | Archive_num | INT | The archive log number | ```sql SHOW ARCHIVE LOG HEADER OF '/home/qa/CORADB/databases/e-commerce/e-commerce_lgar006'; ``` The result has one row with the columns listed above. ### SHOW HEAP HEADER Shows the header page of a table's heap file, where its rows are stored. For a partitioned table, `ALL` shows the header of the table and of each partition. ```text SHOW [ALL] HEAP HEADER OF table_name ``` | Column | Type | Description | |---|---|---| | Table_name | VARCHAR(256) | Table name | | Class_oid | VARCHAR(64) | Format: (volidslotid) | | Volume_id | INT | Volume identifier where the file reside | | File_id | INT | File identifier | | Header_page_id | INT | First page identifier (the header page) | | Overflow_vfid | VARCHAR(64) | Overflow file identifier (if any) | | Next_vpid | VARCHAR(64) | Next page (i.e., the 2nd page of heap file) | | Unfill_space | INT | Stop inserting when page has run below this. leave it for updates | | Estimates_num_pages | BIGINT | Estimation of number of heap pages. | | Estimates_num_recs | BIGINT | Estimation of number of objects in heap | | Estimates_avg_rec_len | INT | Estimation total length of records | | Estimates_num_high_best | INT | Number of pages in the best array that we believe have at least HEAP_DROP_FREE_SPACE. When this number goes to zero and there are at least other HEAP_NUM_BEST_SPACESTATS best pages, we look for them | | Estimates_num_others_high_best | INT | Total of other believed known best pages, which are not included in the best array and we believe they have at least HEAP_DROP_FREE_SPACE | | Estimates_head | INT | Head of best circular array | | Estimates_best_list | VARCHAR(512) | Format: '((best\[0\].vpid.volidbest\[9\].vpid.pageid), best\[9\].freespace)' | | Estimates_num_second_best | INT | Number of second best hints. The hints are in "second_best" array. They are used when finding new best pages. | | Estimates_head_second_best | INT | Index of head of second best hints. A new second best hint will be stored on this index. | | Estimates_tail_second_best | INT | Tail of the second best list | | Estimates_num_substitutions | INT | Number of page substitutions. This will be used to insert a new second best page into second best hints. | | Estimates_second_best_list | VARCHAR(512) | Format: '(second_best\[0\].vpid.volidsecond_best\[9\].vpid.pageid)' | | Estimates_last_vpid | VARCHAR(64) | Format: '(volid\ | pageid)' | | Estimates_full_search_vpid | VARCHAR(64) | Format: '(volid\ | pageid)' | ```sql SHOW HEAP HEADER OF orders; ``` ```text <00001> Table_name : 'orders' Class_oid : '(0|202|9)' Volume_id : 0 File_id : 3776 Header_page_id : 3777 Overflow_vfid : '(-1|-1)' Next_vpid : '(0|3778)' Unfill_space : 1634 Estimates_num_pages : 23 Estimates_num_recs : 2914 Estimates_avg_rec_len: 107 ... ``` ### SHOW HEAP CAPACITY Shows how much space a table's heap file uses. For a partitioned table, `ALL` shows the table and each partition. ```text SHOW [ALL] HEAP CAPACITY OF table_name ``` | Column | Type | Description | |---|---|---| | Table_name | VARCHAR(256) | Table name | | Class_oid | VARCHAR(64) | Heap file descriptor | | Volume_id | INT | Volume identifier where the file reside | | File_id | INT | File identifier | | Header_page_id | INT | First page identifier (the header page) | | Num_recs | BIGINT | Total Number of objects | | Num_relocated_recs | BIGINT | Number of relocated records | | Num_overflowed_recs | BIGINT | Number of big records | | Num_pages | BIGINT | Total number of heap pages | | Avg_rec_len | INT | Average object length | | Avg_free_space_per_page | INT | Average free space per page | | Avg_free_space_per_page_except_last_page | INT | Average free space per page without taking in consideration last page | | Avg_overhead_per_page | INT | Average overhead per page | | Repr_id | INT | Currently cached catalog column info | | Num_total_attrs | INT | Total number of columns | | Num_fixed_width_attrs | INT | Number of the fixed width columns | | Num_variable_width_attrs | INT | Number of variable width columns | | Num_shared_attrs | INT | Number of shared columns | | Num_class_attrs | INT | Number of table columns | | Total_size_fixed_width_attrs | INT | Total size of the fixed width columns | ```sql SHOW HEAP CAPACITY OF orders; ``` ```text <00001> Table_name : 'orders' Class_oid : '(0|202|9)' Volume_id : 0 File_id : 3776 Header_page_id : 3777 Num_recs : 2910 Num_relocated_recs : 0 Num_overflowed_recs : 0 Num_pages : 23 Avg_rec_len : 106 Avg_free_space_per_page : 2219 Avg_free_space_per_page_except_last_page: 1781 Avg_overhead_per_page : 510 Repr_id : 2 Num_total_attrs : 6 Num_fixed_width_attrs : 5 Num_variable_width_attrs : 1 Num_shared_attrs : 0 Num_class_attrs : 0 Total_size_fixed_width_attrs : 32 ``` ### SHOW SLOTTED PAGE HEADER Shows the header of a slotted page, the page format used for table rows. Identify the page by volume and page number, for example the `Header_page_id` returned by `SHOW HEAP HEADER`. ```text SHOW SLOTTED PAGE HEADER {WHERE | OF} VOLUME = volume_num AND PAGE = page_num ``` | Column | Type | Description | |---|---|---| | Volume_id | INT | Volume id of the page | | Page_id | INT | Page id of the page | | Num_slots | INT | Number of allocated slots for the page | | Num_records | INT | Number of records on page | | Anchor_type | VARCHAR(32) | One of flowing: ANCHORED, ANCHORED_DONT_REUSE_SLOTS, UNANCHORED_ANY_SEQUENCE, UNANCHORED_KEEP_SEQUENCE | | Alignment | VARCHAR(8) | Alignment for records, one of flowing: CHAR, SHORT, INT, DOUBLE | | Total_free_area | INT | Total free space on page | | Contiguous_free_area | INT | Contiguous free space on page | | Free_space_offset | INT | Byte offset from the beginning of the page to the first free byte area on the page | | Need_update_best_hint | INT | True if saving is need for recovery (undo) | | Is_saving | INT | True if we should update best pages hint for this page. | | Flags | INT | Flag value of the page | ```sql SHOW SLOTTED PAGE HEADER OF VOLUME = 0 AND PAGE = 3777; ``` ```text <00001> Volume_id : 0 Page_id : 3777 Num_slots : 130 Num_records : 130 Anchor_type : 'ANCHORED_DONT_REUSE_SLOTS' Alignment : 'INT' Total_free_area : 1676 Contiguous_free_area : 1620 Free_space_offset : 14204 Need_update_best_hint: 0 Is_saving : 1 Flags : 0 ``` ### SHOW SLOTTED PAGE SLOTS Shows every slot of a slotted page, one row per slot. ```text SHOW SLOTTED PAGE SLOTS {WHERE | OF} VOLUME = volume_num AND PAGE = page_num ``` | Column | Type | Description | |---|---|---| | Volume_id | INT | Volume id of the page | | Page_id | INT | Page id of the page | | Slot_id | INT | The slot id | | Offset | INT | Byte offset from the beginning of the page to the beginning of the record | | Type | VARCHAR(32) | Record type, one of flowing: REC_UNKNOWN, REC_ASSIGN_ADDRESS, REC_HOME, REC_NEWHOME, REC_RELOCATION, REC_BIGONE, REC_MARKDELETED, REC_DELETED_WILL_REUSE | | Length | INT | Length of record | | Waste | INT | Whether or not wasted | ```sql SHOW SLOTTED PAGE SLOTS OF VOLUME = 0 AND PAGE = 3777; ``` | Volume_id | Page_id | Slot_id | Offset | Type | Length | Waste | |---:|---:|---:|---:|---|---:|---:| | 0 | 3777 | 0 | 32 | HOME | 296 | 0 | | 0 | 3777 | 1 | 328 | HOME | 108 | 0 | | 0 | 3777 | 2 | 436 | HOME | 112 | 0 | | … | | | | | | | The page holds 130 slots; only the first three are shown. ### SHOW INDEX HEADER Shows the header page of an index. With `ALL` and no index name, it shows the headers of all indexes of the table. ```text SHOW INDEX HEADER OF table_name.index_name SHOW ALL INDEXES HEADER OF table_name ``` | Column | Type | Description | |---|---|---| | Table_name | VARCHAR(256) | Table name | | Index_name | VARCHAR(256) | Index name | | Btid | VARCHAR(64) | BTID (volidroot_pageid) | | Node_level | INT | Node level (1 for LEAF, 2 or more for NON_LEAF) | | Max_key_len | INT | Maximum key length for the subtree | | Num_oids | INT | Number of OIDs stored in the Btree | | Num_nulls | INT | Number of NULLs (they aren't stored) | | Num_keys | INT | Number of unique keys in the Btree | | Topclass_oid | VARCHAR(64) | Topclass oid or NULL OID (non unique index)(volidslotid) | | Unique | INT | Unique or non-unique | | Overflow_vfid | VARCHAR(32) | VFID (volid\ | fileid) | | Key_type | VARCHAR(256) | Type name | | Columns | VARCHAR(256) | The list of columns which consists of the index | ```sql SHOW INDEX HEADER OF orders.idx_orders_order_date; ``` ```text <00001> Table_name : 'orders' Index_name : 'idx_orders_order_date' Btid : '(0|5824|5825)' Node_level : 2 Max_key_len : 4 Num_oids : -1 Num_nulls : -1 Num_keys : -1 Topclass_oid : '(0|202|9)' Unique : 0 Overflow_vfid: '(-1|-1)' Key_type : 'date' Columns : 'order_date' ``` ### SHOW INDEX CAPACITY Shows how much space an index uses and how its keys are distributed. With `ALL` and no index name, it shows every index of the table. ```text SHOW INDEX CAPACITY OF table_name.index_name SHOW ALL INDEXES CAPACITY OF table_name ``` | Column | Type | Description | |---|---|---| | Table_name | VARCHAR(256) | Table name | | Index_name | VARCHAR(256) | Index name | | Btid | VARCHAR(64) | BTID (volidroot_pageid) | | Num_distinct_key | INT | Distinct key count (in leaf pages) | | Total_value | INT | Total number of values stored in tree | | Avg_num_value_per_key | INT | Average number of values (OIDs) per key | | Num_leaf_page | INT | Leaf page count | | Num_non_leaf_page | INT | NonLeaf page count | | Num_total_page | INT | Total page count | | Height | INT | Height of the tree | | Avg_key_len | INT | Average key length | | Avg_rec_len | INT | Average page record length | | Total_space | VARCHAR(64) | Total space occupied by index | | Total_used_space | VARCHAR(64) | Total used space in index | | Total_free_space | VARCHAR(64) | Total free space in index | | Avg_num_page_key | INT | Average page key count (in leaf pages) | | Avg_page_free_space | VARCHAR(64) | Average page free space | ```sql SHOW ALL INDEXES CAPACITY OF order_items; ``` | Index_name | Num_distinct_key | Total_value | Num_total_page | Height | Total_space | Total_used_space | Total_free_space | |---|---:|---:|---:|---:|---|---|---| | fk_order_items_order_id | 2926 | 11195 | 10 | 2 | 159.6K | 111.1K | 48.5K | | fk_order_items_product_id | 1827 | 11179 | 8 | 2 | 127.7K | 90.4K | 37.2K | | pk_order_items_order_id_product_id | 11221 | 11221 | 23 | 2 | 367.1K | 264.9K | 102.2K | A selection of the columns is shown. ### SHOW CRITICAL SECTIONS Shows every critical section of the database server: the internal locks that protect shared server structures, with their current holders and waiters and the accumulated wait times. Long waits on one section point to contention. ```text SHOW CRITICAL SECTIONS ``` | Column | Type | Description | |---|---|---| | Index | INT | The index of CS | | Name | VARCHAR(32) | The name of CS | | Num_holders | VARCHAR(16) | The number of CS holders. This has one of these values: 'N readers', '1 writer', 'none' | | Num_waiting_readers | INT | The number of waiting readers | | Num_waiting_writers | INT | The number of waiting writers | | Owner_thread_index | INT | The thread index of CS owner writer, NULL if no owner | | Owner_tran_index | INT | Transaction index of CS owner writer, NULL if no owner | | Total_enter_count | BIGINT | Total count of enterers | | Total_waiter_count | BIGINT | Total count of waiters | | Waiting_promoter_thread_index | INT | The thread index of waiting promoter, NULL if no waiting promoter | | Max_waiting_msecs | NUMERIC(10,3) | Maximum waiting time (millisecond) | | Total_waiting_msecs | NUMERIC(10,3) | Total waiting time (millisecond) | ```sql SHOW CRITICAL SECTIONS; ``` | Index | Name | Num_holders | Num_waiting_readers | Num_waiting_writers | Total_enter_count | Total_waiter_count | Max_waiting_msecs | Total_waiting_msecs | |---:|---|---|---:|---:|---:|---:|---:|---:| | 0 | WFG | none | 0 | 0 | 0 | 0 | 0.000 | 0.000 | | 1 | LOG | none | 0 | 0 | 214651 | 83 | 868.587 | 3747.675 | | 2 | LOCATOR_CLASSNAME_TABLE | none | 0 | 0 | 504436 | 0 | 0.175 | 63.067 | | … | | | | | | | | | A selection of the columns and the first three of the 17 rows are shown. ### SHOW TRANSACTION TABLES Shows the transaction descriptors of all active transactions, one row per transaction: who is connected, from which program and host, the transaction state, and how long its current query has been running. Use it to find the `Tran_index` for [KILL](https://www.coradb.ai/manual/sql/query/kill.html). The rows are not a consistent snapshot; values can change while they are read. ```text SHOW {TRAN | TRANSACTION} TABLES [WHERE expr] ``` | Column | Type | Description | |---|---|---| | Tran_index | INT | Index on the transaction table or NULL for unassigned transaction descriptor slot | | Tran_id | INT | Transaction Identifier | | Is_loose_end | INT | 0 for Ordinary transactions, 1 for loose-end transactions | | State | VARCHAR(64) | State of the transaction. One of the following: 'TRAN_RECOVERY', 'TRAN_ACTIVE', 'TRAN_UNACTIVE_COMMITTED', 'TRAN_UNACTIVE_WILL_COMMIT', 'TRAN_UNACTIVE_COMMITTED_WITH_POSTPONE', 'TRAN_UNACTIVE_ABORTED', 'TRAN_UNACTIVE_UNILATERALLY_ABORTED', 'TRAN_UNACTIVE_2PC_PREPARE', 'TRAN_UNACTIVE_2PC_COLLECTING_PARTICIPANT_VOTES', 'TRAN_UNACTIVE_2PC_ABORT_DECISION', 'TRAN_UNACTIVE_2PC_COMMIT_DECISION', 'TRAN_UNACTIVE_COMMITTED_INFORMING_PARTICIPANTS', 'TRAN_UNACTIVE_ABORTED_INFORMING_PARTICIPANTS','TRAN_STATE_UNKNOWN' | | Isolation | VARCHAR(64) | Isolation level of the transaction. One of the following: 'SERIALIZABLE', 'REPEATABLE READ', 'COMMITTED READ', 'TRAN_UNKNOWN_ISOLATION' | | Wait_msecs | INT | Wait until this number of milliseconds for locks. | | Head_lsa | VARCHAR(64) | First log address of transaction. | | Tail_lsa | VARCHAR(64) | Last log record address of transaction. | | Undo_next_lsa | VARCHAR(64) | Next log record address of transaction for UNDO purposes. | | Postpone_next_lsa | VARCHAR(64) | Next address of a postpone record to be executed. | | Savepoint_lsa | VARCHAR(64) | Address of last save-point. | | Topop_lsa | VARCHAR(64) | Address of last top operation. | | Tail_top_result_lsa | VARCHAR(64) | Address of last partial abort/commit. | | Client_id | INT | Unique identifier of client application bind to transaction. | | Client_type | VARCHAR(40) | Type of client, for example 'SYSTEM_INTERNAL', 'DEFAULT', 'corasql' or 'BROKER' | | Client_info | VARCHAR(256) | General information of client application. | | Client_db_user | VARCHAR(40) | Current login database account from client application. | | Client_program | VARCHAR(256) | Program name of client application. | | Client_login_user | VARCHAR(16) | Current login user of OS which running the client application. | | Client_host | VARCHAR(64) | Host name of client application. | | Client_pid | INT | Process id of client application. | | Topop_depth | INT | Depth of nested top operation. | | Num_unique_btrees | INT | Number of unique btrees contained in unique_stat_info array. | | Max_unique_btrees | INT | Size of unique_stat_info_array. | | Interrupt | INT | The flag of whether or not interrupt current transaction. 0 for No, 1 for Yes. | | Num_transient_classnames | INT | Number of transient classnames by this transaction. | | First_save_entry | VARCHAR(20) | First save entry for the transaction, display address pointer as 0x12345678 or NULL for 0x00000000. | | Tran_unique_stats | VARCHAR(20) | Local statistical info for multiple row. display address pointer as 0x12345678 or NULL for 0x00000000. | | Modified_class_list | VARCHAR(20) | List of dirty classes, display address pointer as 0x12345678 or NULL for 0x00000000. | | Num_temp_files | INT | Number of temporary files. | | Waiting_for_res | VARCHAR(20) | Waiting resource. Just display address pointer as 0x12345678 or NULL for 0x00000000. | | Has_deadlock_priority | INT | Whether or not have deadlock priority. 0 for No, 1 for Yes. | | Query_timeout | DATETIME | A query should be executed before query_timeout time or NULL for waiting until query complete. | | Query_start_time | DATETIME | Current query start time or NULL for query completed. | | Tran_start_time | DATETIME | Current transaction start time or NULL for transaction completed. | | Xasl_id | VARCHAR(64) | Vpid:(volidpageid) or NULL for query completed. | | Disable_modifications | INT | Disable modification if greater than zero. | | Abort_reason | VARCHAR(40) | Reason of transaction aborted. One of the following: 'NORMAL', 'ABORT_DUE_TO_DEADLOCK', 'ABORT_DUE_ROLLBACK_ON_ESCALATION' | ```sql SHOW TRANSACTION TABLES WHERE client_type = 'BROKER'; ``` ```text <00001> Tran_index : 1 Tran_id : 1176992 Is_loose_end : 0 State : 'ACTIVE' Isolation : 'COMMITTED READ' Wait_msecs : -1 ... Client_type : 'BROKER' Client_info : '' Client_db_user : 'DBA' Client_program : 'broker1_cora_cas_1' Client_login_user: 'root' ... Query_start_time : 01:18:09.334 AM 11/18/2026 Tran_start_time : 01:18:09.334 AM 11/18/2026 ... ``` ### SHOW THREADS Shows the server's threads, sorted by `Index`: worker threads that run client requests and the server's own daemon threads. For a thread that waits for a lock, the `Lockwait_*` columns show what it waits for. The rows are not a consistent snapshot. In standalone mode (`corasql -S`) the result is empty. ```text SHOW THREADS [WHERE expr] ``` | Column | Type | Description | |---|---|---| | Index | INT | Thread entry index. | | Jobq_index | INT | Job queue index only for worker threads. NULL for non-worker threads. | | Thread_id | BIGINT | Thread id. | | Tran_index | INT | Transaction index to which this thread belongs. If no related tran index, NULL. | | Type | VARCHAR(8) | Thread type. One of the following: 'MASTER', 'SERVER', 'WORKER', 'DAEMON', 'VACUUM_MASTER', 'VACUUM_WORKER', 'NONE', 'UNKNOWN'. | | Status | VARCHAR(8) | Thread status. One of the following: 'DEAD', 'FREE', 'RUN', 'WAIT', 'CHECK'. | | Resume_status | VARCHAR(32) | Resume status. One of the following: 'RESUME_NONE', 'RESUME_DUE_TO_INTERRUPT', 'RESUME_DUE_TO_SHUTDOWN', 'PGBUF_SUSPENDED', 'PGBUF_RESUMED', 'JOB_QUEUE_SUSPENDED', 'JOB_QUEUE_RESUMED', 'CSECT_READER_SUSPENDED', 'CSECT_READER_RESUMED', 'CSECT_WRITER_SUSPENDED', 'CSECT_WRITER_RESUMED', 'CSECT_PROMOTER_SUSPENDED', 'CSECT_PROMOTER_RESUMED', 'CSS_QUEUE_SUSPENDED', 'CSS_QUEUE_RESUMED', 'QMGR_ACTIVE_QRY_SUSPENDED', 'QMGR_ACTIVE_QRY_RESUMED', 'QMGR_MEMBUF_PAGE_SUSPENDED', 'QMGR_MEMBUF_PAGE_RESUMED', 'HEAP_CLSREPR_SUSPENDED', 'HEAP_CLSREPR_RESUMED', 'LOCK_SUSPENDED', 'LOCK_RESUMED', 'LOGWR_SUSPENDED', 'LOGWR_RESUMED' | | Net_request | VARCHAR(64) | The net request name in net_requests array, such as: 'LC_ASSIGN_OID'. If not request name, shows NULL | | Conn_client_id | INT | Client id whom this thread is responding, if no client id, shows NULL | | Conn_request_id | INT | Request id which this thread is processing, if no request id, shows NULL | | Conn_index | INT | Connection index, if not connection index, shows NULL | | Last_error_code | INT | Last error code | | Last_error_msg | VARCHAR(256) | Last error message, if message length is more than 256, it will be truncated, If no error message, shows NULL | | Private_heap_id | VARCHAR(20) | The address of id of thread private memory allocator, such as: 0x12345678. If no related heap id, shows NULL. | | Query_entry | VARCHAR(20) | The address of the QMGR_QUERY_ENTRY\*, such as: 0x12345678, if no related QMGR_QUERY_ENTRY, shows NULL. | | Interrupted | INT | 0 or 1, is this request/transaction interrupted | | Shutdown | INT | 0 or 1, is server going down? | | Check_interrupt | INT | 0 or 1 | | Wait_for_latch_promote | INT | 0 or 1, whether this thread is waiting for latch promotion. | | Lockwait_blocked_mode | VARCHAR(24) | Lockwait blocked mode. One of the following: 'NULL_LOCK', 'IS_LOCK', 'S_LOCK', 'IS_LOCK', 'IX_LOCK', 'SIX_LOCK', 'X_LOCK', 'SCH_M_LOCK', 'UNKNOWN' | | Lockwait_start_time | DATETIME | Start blocked time, if not in blocked state, shows NULL | | Lockwait_msecs | INT | Time in milliseconds, if not in blocked state, shows NULL | | Lockwait_state | VARCHAR(24) | The lock wait state such as: 'SUSPENDED', 'RESUMED', 'RESUMED_ABORTED_FIRST', 'RESUMED_ABORTED_OTHER', 'RESUMED_DEADLOCK_TIMEOUT', 'RESUMED_TIMEOUT', 'RESUMED_INTERRUPT'. If not in blocked state, shows NULL | | Next_wait_thread_index | INT | The next wait thread index, if not exist, shows NULL | | Next_tran_wait_thread_index | INT | The next wait thread index in lock manager, if not exist, shows NULL | | Next_worker_thread_index | INT | The next worker thread index in css_Job_queue.worker_thrd_list, if not exist, shows NULL | ```sql SHOW THREADS WHERE status <> 'FREE' AND type = 'WORKER'; ``` ```text <00001> Index : 1 Jobq_index : NULL Thread_id : 0 Tran_index : NULL Type : 'WORKER' Status : 'DEAD' Resume_status: 'RESUME_NONE' ... ``` ### SHOW JOB QUEUES Shows the job queues of the server's worker threads, with how many workers are busy. In standalone mode the result is empty. ```text SHOW JOB QUEUES ``` | Column | Type | Description | |---|---|---| | Jobq_index | INT | The index of job queue | | Num_total_workers | INT | Total number of work threads of the queue | | Num_busy_workers | INT | The number of busy worker threads of the queue | | Num_connection_workers | INT | The number of connection worker threads of the queue | ```sql SHOW JOB QUEUES; ``` | Jobq_index | Num_total_workers | Num_busy_workers | Num_connection_workers | |---:|---:|---:|---:| | 0 | 13 | 0 | 0 | | 1 | 13 | 1 | 0 | | 2 | 13 | 0 | 0 | | … | | | | The first three of the eight queues are shown. ### SHOW PAGE BUFFER STATUS Shows the state of the data page buffer pool: hit rate, how the pages are used, and read and write rates. A hit rate well below 100% under normal load suggests that the buffer (`data_buffer_size`) is too small for the working set. ```text SHOW PAGE BUFFER STATUS ``` | Column | Type | Description | |---|---|---| | Hit_rate | NUMERIC(13,10) | The buffer pool hit rate (since the last printout) | | Num_hit | BIGINT | The number of buffer hits (since the last printout) | | Num_page_request | BIGINT | The number of page requests (since the last printout) | | Pool_size | INT | Buffer pool size in pages | | Page_size | INT | Data page size | | Free_pages | INT | The number of free pages in the buffer pool | | Victim_candidate_pages | INT | The number of victim candidate pages in the cold LRU area | | Clean_pages | INT | The number of clean pages in the buffer pool | | Dirty_pages | INT | The number of dirty pages in the buffer pool | | Num_index_pages | INT | The number of index pages in the buffer pool | | Num_data_pages | INT | The number of data pages in the buffer pool | | Num_system_pages | INT | The number of system pages in the buffer pool | | Num_temp_pages | INT | The number of temp pages in the buffer pool | | Num_pages_created | BIGINT | The number of pages created in the buffer pool (since the last printout) | | Num_pages_written | BIGINT | The number of pages written to disk in the buffer pool (since the last printout) | | Pages_written_rate | NUMERIC(20,10) | The number of pages written per second (since the last printout) | | Num_pages_read | BIGINT | The number of pages read from disk in the buffer pool (since the last printout) | | Pages_read_rate | NUMERIC(20,10) | The number of pages read per second (since the last printout) | | Num_flusher_waiting_threads | INT | The number of waiting threads for flusher | ```sql SHOW PAGE BUFFER STATUS; ``` ```text <00001> Hit_rate : 99.9963850819 Num_hit : 10566939 Num_page_request : 10567321 Pool_size : 32768 Page_size : 16392 Free_pages : 32272 Victim_candidate_pages: 3 Clean_pages : 32748 Dirty_pages : 20 Num_index_pages : 103 Num_data_pages : 197 Num_system_pages : 108 Num_temp_pages : 66 ... ``` ## See also - [Catalog views](https://www.coradb.ai/manual/sql/catalog.html): query the same metadata with `SELECT` - [KILL](https://www.coradb.ai/manual/sql/query/kill.html) - [Database administration utilities](https://www.coradb.ai/manual/admin/admin_utils.html) --- # TRUNCATE statement Source: https://www.coradb.ai/manual/sql/query/truncate.html The **TRUNCATE** statement deletes every row of a table. CoraDB first drops the table's indexes and constraints internally, removes the rows and then rebuilds them, so `TRUNCATE` is much faster than `DELETE FROM table_name` without a `WHERE` clause on large tables. It also resets the table's `AUTO_INCREMENT` counter to its starting value. ## Syntax ```text TRUNCATE [TABLE] table_name ``` - *table_name*: the table to empty. To run `TRUNCATE` you need the `ALTER`, `INDEX` and `DELETE` permissions on the table (see [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant)). ## Example The example uses a scratch table, so it does not change any of the sample data: ```sql CREATE TABLE support_ticket ( id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, subject VARCHAR(100) NOT NULL, status VARCHAR(10) DEFAULT 'open' ); INSERT INTO support_ticket (customer_id, subject) VALUES (5, 'Wrong size delivered'), (15, 'Refund request'), (42, 'Damaged parcel'); SELECT id, customer_id, subject FROM support_ticket; ``` | id | customer_id | subject | |---:|---:|---| | 1 | 5 | Wrong size delivered | | 2 | 15 | Refund request | | 3 | 42 | Damaged parcel | After `TRUNCATE`, numbering starts again from 1: ```sql TRUNCATE TABLE support_ticket; INSERT INTO support_ticket (customer_id, subject) VALUES (7, 'Missing invoice'); SELECT id, customer_id, subject FROM support_ticket; ``` | id | customer_id | subject | |---:|---:|---| | 1 | 7 | Missing invoice | With `DELETE FROM support_ticket` the new row would have received id 4. ## Foreign keys If other tables reference the table through a foreign key, `TRUNCATE` follows the foreign key's `ON DELETE` action: - `RESTRICT` or `NO ACTION` (the default): the statement fails while referencing rows exist. - `CASCADE`: the referencing rows are deleted as well. ```sql CREATE TABLE ticket_note ( id INT AUTO_INCREMENT PRIMARY KEY, ticket_id INT NOT NULL, note VARCHAR(200), FOREIGN KEY (ticket_id) REFERENCES support_ticket (id) ); INSERT INTO ticket_note (ticket_id, note) VALUES (1, 'Customer sent photos'); TRUNCATE TABLE support_ticket; ``` ```text ERROR: Update/Delete operations are restricted by the foreign key 'fk_ticket_note_ticket_id'. ``` Had the foreign key been declared with `ON DELETE CASCADE`, the same `TRUNCATE` would have emptied `ticket_note` too. > **Warning:** > `TRUNCATE` removes every row. Check the table name before you run it, especially with auto-commit on. ## See also - [DELETE](https://www.coradb.ai/manual/sql/query/delete.html): remove selected rows - [FOREIGN KEY constraint](https://www.coradb.ai/manual/sql/schema/table_stmt.html#foreign-key-constraint) - [AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto-increment) --- # UPDATE statement Source: https://www.coradb.ai/manual/sql/query/update.html The **UPDATE** statement changes column values in existing rows. The `SET` clause names the columns and their new values; a [WHERE clause](https://www.coradb.ai/manual/sql/query/select.html#where-clause) selects the rows to change. Without `WHERE`, every row is updated. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. They change data, so start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to leave the database as it was. ## Syntax ```text -- one table (or view) UPDATE table_name SET column_name = { | DEFAULT} [, column_name = { | DEFAULT} ...] [WHERE ] [ORDER BY {col_name | } [ASC | DESC], ...] [LIMIT row_count] -- several tables UPDATE SET column_name = { | DEFAULT} [, column_name = { | DEFAULT} ...] [WHERE ] ``` - *table_name*: the table or updatable view to change. - *table_specifications*: the tables to read, written like the `FROM` clause of a [SELECT](https://www.coradb.ai/manual/sql/query/select.html), including joins. Columns of any of these tables can be updated. - *column_name*: the column to change. In a multi-table update, qualify it with the table name or alias. - *expr* | **DEFAULT**: the new value. It can be any expression, including a subquery that returns one value, or `DEFAULT` for the column's default value. - *search_condition*: only rows that satisfy the condition are updated. - `ORDER BY` and `LIMIT` (one table only): the order in which rows are updated and the maximum number of rows to update. *row_count* can be an unsigned integer, a host variable or a simple expression. ## Updating one table Product 1795 sells for 29.00 and has 31 units in stock. Raise the price and take one unit out of stock: ```sql UPDATE product SET unit_price = 32.50, units_in_stock = units_in_stock - 1 WHERE id = 1795; SELECT id, name, unit_price, units_in_stock FROM product WHERE id = 1795; ``` | id | name | unit_price | units_in_stock | |---:|---|---:|---:| | 1795 | Balboa Persistence Tee | 32.50 | 30 | Every unshipped order gets a shipping date: ```sql UPDATE orders SET shipped_date = DATE'2026-01-05' WHERE shipped_date IS NULL; ``` ```text 9 rows affected. ``` ## Using a subquery for the new value A subquery in `SET` must return a single value. Here, order 455 is charged the average shipping cost of all shipped orders: ```sql UPDATE orders SET shipping_cost = (SELECT AVG(shipping_cost) FROM orders WHERE shipped_date IS NOT NULL) WHERE id = 455; SELECT shipping_cost FROM orders WHERE id = 455; ``` | shipping_cost | |---:| | 16.94 | ## ORDER BY and LIMIT With one table, `ORDER BY` decides the order in which rows are updated and `LIMIT` caps the number of rows. Restock only the three most expensive products that are sold out: ```sql UPDATE product SET units_in_stock = 100 WHERE units_in_stock = 0 ORDER BY unit_price DESC LIMIT 3; SELECT id, name, unit_price, units_in_stock FROM product WHERE units_in_stock = 100 ORDER BY unit_price DESC; ``` | id | name | unit_price | units_in_stock | |---:|---|---:|---:| | 29 | Thüringer Rostbratwurst | 123.79 | 100 | | 1110 | Ingrid Running Jacket | 84.00 | 100 | | 159 | Juno Jacket | 77.00 | 100 | The update order also matters when the table has [triggers](https://www.coradb.ai/manual/sql/trigger.html): row-level triggers fire in the order the rows are updated. ## Restoring default values `DEFAULT` sets a column back to its default value. The example uses a small table for support tickets: ```sql CREATE TABLE support_ticket ( id INT AUTO_INCREMENT PRIMARY KEY, customer_id INT NOT NULL, subject VARCHAR(100) NOT NULL, status VARCHAR(10) DEFAULT 'open', priority INT DEFAULT 3 ); INSERT INTO support_ticket (customer_id, subject, status, priority) VALUES (5, 'Wrong size delivered', 'closed', 1); UPDATE support_ticket SET status = DEFAULT, priority = DEFAULT WHERE id = 1; SELECT * FROM support_ticket; ``` | id | customer_id | subject | status | priority | |---:|---:|---|---|---:| | 1 | 5 | Wrong size delivered | open | 3 | ## Referring to other columns in SET By default, a column referenced on the right side of `SET` has the value stored in the row before the update, even if the same statement assigns it a new value. Continuing with the ticket above (priority 3): ```sql UPDATE support_ticket SET priority = 1, status = priority; SELECT * FROM support_ticket; ``` | id | customer_id | subject | status | priority | |---:|---:|---|---|---:| | 1 | 5 | Wrong size delivered | 3 | 1 | `status` received the old priority, 3, not the new value 1. The [update_use_attribute_references](https://www.coradb.ai/manual/admin/config_sql.html#update_use_attribute_references) parameter changes this: when it is `yes`, assignments are applied from left to right and later assignments see the new values (here, `status` would be `1`). The default is `no`. ## Updating several tables In a multi-table update, the tables are joined as in a `SELECT` and the `SET` clause can change columns of any of them. Give a 10% discount on every undiscounted line of the product *Erika Running Short*, using the product name from the `product` table: ```sql UPDATE order_items oi INNER JOIN product p ON oi.product_id = p.id SET oi.discount_pct = 10 WHERE p.name = 'Erika Running Short' AND oi.discount_pct = 0; ``` ```text 518 rows affected. ``` Change an order and its lines in one statement: ```sql UPDATE orders o INNER JOIN order_items oi ON oi.order_id = o.id SET o.shipping_cost = 0, oi.discount_pct = 5 WHERE o.id = 455; SELECT o.shipping_cost, oi.product_id, oi.discount_pct FROM orders o JOIN order_items oi ON oi.order_id = o.id WHERE o.id = 455 ORDER BY oi.product_id; ``` | shipping_cost | product_id | discount_pct | |---:|---:|---:| | 0.00 | 123 | 5 | | 0.00 | 335 | 5 | | 0.00 | 1795 | 5 | When one row of the updated table joins several rows of another table, it is updated once, with the values from the first joined row found. Write the join so that each updated row matches one row, or aggregate first in a [CTE](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements). For more on joins, see [Join query](https://www.coradb.ai/manual/sql/query/select.html#join-query). ## Updating through a view An updatable view can be the target of an `UPDATE`; the change is applied to the underlying table. The view below lists products that are almost sold out: ```sql CREATE VIEW low_stock AS SELECT id, name, units_in_stock FROM product WHERE units_in_stock < 5; UPDATE low_stock SET units_in_stock = 5 WHERE id = 5; SELECT id, name, units_in_stock FROM product WHERE id = 5; ``` | id | name | units_in_stock | |---:|---|---:| | 5 | Chef Antons Gumbo Mix | 5 | If a view cannot be updated, CoraDB rejects the statement with `Vclass is not updatable`. See [CREATE VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html#create-view). ## Updating vertices and edges Rows of [vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge) are updated with the same statement. Writing `UPDATE VERTEX` or `UPDATE EDGE` makes the intent explicit; the rest of the syntax is unchanged. Updating an edge changes its properties, not the vertices it connects. ```sql UPDATE VERTEX product SET units_in_stock = units_in_stock + 10 WHERE id = 1795; UPDATE EDGE likes SET since = SYSDATETIME WHERE since < DATETIME'2020-01-01 00:00:00'; ``` ## See also - [INSERT](https://www.coradb.ai/manual/sql/query/insert.html) and [ON DUPLICATE KEY UPDATE](https://www.coradb.ai/manual/sql/query/insert.html#on-duplicate-key-update) - [MERGE](https://www.coradb.ai/manual/sql/query/merge.html): update or insert in one statement - [DELETE](https://www.coradb.ai/manual/sql/query/delete.html) - [Transactions](https://www.coradb.ai/manual/sql/transaction.html) --- # Data definition statements (DDL) Source: https://www.coradb.ai/manual/sql/schema.html Data definition statements create, change and remove the objects that hold and organize data. In CoraDB, they are part of the transaction: a `CREATE TABLE` or `ALTER TABLE` can be rolled back like an `INSERT`. | Statements | Objects | |---|---| | [CREATE, ALTER, DROP and RENAME TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html) | Tables, their columns and constraints, and the [vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge) of a graph. | | [CREATE, ALTER and DROP INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html) | Indexes, including unique, filtered, function-based and invisible indexes. | | [CREATE, ALTER, DROP and RENAME VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html) | Views (named queries). | | [CREATE, ALTER and DROP SERIAL](https://www.coradb.ai/manual/sql/schema/serial_stmt.html) | Serials (sequence number generators). | Related statements are described elsewhere: [partitioning](https://www.coradb.ai/manual/sql/partition.html), [triggers](https://www.coradb.ai/manual/sql/trigger.html), [users and permissions](https://www.coradb.ai/manual/sql/authorization.html), [stored procedures](https://www.coradb.ai/manual/sql/jsp.html) and [class inheritance](https://www.coradb.ai/manual/sql/oodb.html). --- # CREATE, ALTER and DROP INDEX Source: https://www.coradb.ai/manual/sql/schema/index_stmt.html An index lets CoraDB find rows by the values of one or more columns without reading the whole table. CoraDB indexes are B+trees. Primary keys, unique constraints and foreign keys create their indexes automatically; this page covers the indexes you create yourself. How the optimizer uses indexes, and how to steer it, is explained in [Query optimization](https://www.coradb.ai/manual/sql/tuning.html). > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). Start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove the indexes again. ## CREATE INDEX ```text CREATE [UNIQUE] INDEX index_name ON table_name [WITH ONLINE [PARALLEL thread_count] | INVISIBLE | VISIBLE] [COMMENT 'comment'] ::= (column_name [ASC | DESC] [, column_name [ASC | DESC] ...]) [WHERE ] | (function_name (argument_list)) ``` - **UNIQUE**: no two rows can have the same key. `NULL` values do not count as duplicates. - *index_name*: required, and unique within the table; see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html). - *column_name*: one or more columns. In a composite index, the order of the columns matters: the index can be searched by its first column, its first two columns, and so on. - **ASC** | **DESC**: the order of the column in the index (default `ASC`). - **WHERE** *filter_predicate*: a [filtered index](https://www.coradb.ai/manual/sql/tuning_special_index.html#filtered-index) contains only the rows that satisfy the predicate. Several conditions must be combined with `AND`. - *function_name*(*argument_list*): a [function-based index](https://www.coradb.ai/manual/sql/tuning_special_index.html#function-based-index) stores the result of an expression, so queries that filter on the same expression can use it. - **WITH ONLINE**: build the index while other transactions keep changing the table (see [Online index creation](https://www.coradb.ai/manual/sql/schema/index_stmt.html#online-index-creation)). - **INVISIBLE**: create the index without letting the optimizer use it yet. `VISIBLE` is the default. - **COMMENT**: a description of the index. A descending index on product prices, and a composite index on a customer's orders, newest first: ```sql CREATE INDEX idx_product_price ON product (unit_price DESC); CREATE INDEX idx_orders_customer_date ON orders (customer_id, order_date DESC) COMMENT 'orders of a customer, newest first'; ``` A filtered index that contains only unshipped orders, and a function-based index for case-insensitive searches on company names: ```sql CREATE INDEX idx_orders_unshipped ON orders (customer_id, order_date) WHERE shipped_date IS NULL; CREATE INDEX idx_customer_lower_name ON customer (LOWER(company_name)); ``` A unique index rejects duplicates, like a `UNIQUE` constraint: ```sql CREATE UNIQUE INDEX uq_countries_name ON countries (name); INSERT INTO countries VALUES ('XXX', 'France'); ``` ```text ERROR: Operation would have caused one or more unique constraint violations. INDEX uq_countries_name ... key: 'France' ``` Two indexes on the same columns with the same definition are not allowed: CoraDB reports `Index "..." already defined for class "..."`. Index comments and visibility are listed by [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) and in the `db_index` catalog view: ```sql SELECT index_name, is_unique, comment FROM db_index WHERE class_name = 'orders' ORDER BY index_name; ``` | index_name | is_unique | comment | |---|---|---| | fk_orders_customer_id | NO | NULL | | idx_orders_customer_date | NO | Orders of a customer, newest first | | idx_orders_order_date | NO | NULL | | idx_orders_shipped_date | NO | NULL | | idx_orders_unshipped | NO | NULL | | pk_orders_id | YES | NULL | > **Warning:** > Do not change the session or server time zone, or the leap-second setting (see [Timezone parameter](https://www.coradb.ai/manual/admin/config_sql.html#timezone-parameter)), in a database that has indexes or function-based indexes on `TIMESTAMP`, `TIMESTAMP WITH LOCAL TIME ZONE` or `DATETIME WITH LOCAL TIME ZONE` columns: the stored keys would no longer match. ### Online index creation A normal `CREATE INDEX` locks the table against changes until the index is built. `WITH ONLINE` keeps the table writable: ```sql CREATE INDEX idx_order_items_discount ON order_items (discount_pct) WITH ONLINE PARALLEL 4; ``` The build has three stages: 1. The index is added to the schema with the status *online building*, under an exclusive schema lock that is then lowered so that other transactions can write to the table. 2. The table is scanned in batches; the batches are sorted and loaded into the index. Changes committed by other transactions in the meantime are applied to the index as well. `PARALLEL` *n* uses *n* threads to sort and load the batches (the table scan itself uses one thread). 3. The lock is raised again and the index status becomes normal. While the build runs, other sessions see the index in [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) with `Visible = NO` and in `;schema` with the note `IN PROGRESS`. For a `UNIQUE` index, other transactions may commit rows that violate uniqueness during the build; the violation is detected at the end and the index creation fails with a unique constraint error. In standalone mode (`corasql -S`), `WITH ONLINE` is ignored and a normal index is created. ### Invisible indexes An invisible index is maintained like any other, but the optimizer ignores it. Use this to measure the effect of an index before relying on it, or to check what happens without an index before dropping it. ```sql CREATE INDEX idx_city_postal ON city (postal_code) INVISIBLE; ALTER INDEX idx_city_postal ON city VISIBLE; ``` ## ALTER INDEX ```text ALTER INDEX index_name ON table_name [COMMENT 'comment'] REBUILD ALTER INDEX index_name ON table_name COMMENT 'comment' ALTER INDEX index_name ON table_name {VISIBLE | INVISIBLE} ``` - **REBUILD**: drop and recreate the index with the same definition, for example after many deletes. Column names given after the table name are ignored. - **COMMENT** without `REBUILD`: change only the comment. - **VISIBLE** | **INVISIBLE**: let the optimizer use the index, or not. ```sql ALTER INDEX idx_product_price ON product COMMENT 'price lookups' REBUILD; ALTER INDEX idx_product_price ON product COMMENT 'price lookups, highest first'; ALTER INDEX idx_city_postal ON city INVISIBLE; ``` An index cannot be renamed; drop it and create it again under the new name. ## DROP INDEX ```text DROP INDEX index_name ON table_name ``` ```sql DROP INDEX idx_product_price ON product; ``` The table name is required. Indexes that belong to a constraint (primary key, unique, foreign key) are removed with [ALTER TABLE ... DROP CONSTRAINT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#drop-constraint-drop-index-drop-primary-key-and-drop-foreign-key-clauses); a unique index created with `CREATE UNIQUE INDEX` can be dropped with either statement. ## See also - [Query optimization](https://www.coradb.ai/manual/sql/tuning.html): query plans, index hints, covering indexes and other index techniques - [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#constraints): constraints and the indexes they create - [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) --- # CREATE, ALTER and DROP SERIAL Source: https://www.coradb.ai/manual/sql/schema/serial_stmt.html A serial (a *sequence* in other databases) generates unique numbers, such as invoice or ticket numbers. Unlike an [AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto-increment) column, a serial is an object of its own: it is not tied to a table and can feed several tables. Numbers are handed out safely to many sessions at once. Do not expect a serial to be free of gaps: cached numbers, for example, are lost when the server stops. - Any user, including `PUBLIC`, can create a serial. Once it exists, every user can read its numbers. - Only its owner and `DBA` can change or drop a serial. A serial owned by `PUBLIC` can be changed by everyone. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html). Start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove the serials again. ## CREATE SERIAL ```text CREATE SERIAL serial_name [START WITH initial_value] [INCREMENT BY interval] [MINVALUE min | NOMINVALUE] [MAXVALUE max | NOMAXVALUE] [CYCLE | NOCYCLE] [CACHE cached_count | NOCACHE] [COMMENT 'comment'] ``` - *serial_name*: see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html). - **START WITH**: the first number. Default: `MINVALUE` for an ascending serial, `MAXVALUE` for a descending one. - **INCREMENT BY**: the step, any integer except 0 (default 1). A negative step makes a descending serial. Its absolute value must be smaller than `MAXVALUE - MINVALUE`. - **MINVALUE** / **NOMINVALUE**: the lowest number. `NOMINVALUE` (the default) means 1 for an ascending serial and -1036 for a descending one. - **MAXVALUE** / **NOMAXVALUE**: the highest number. `NOMAXVALUE` (the default) means 1037 for an ascending serial and -1 for a descending one. - **CYCLE**: after the last number, start again from `MINVALUE` (ascending) or `MAXVALUE` (descending). With **NOCYCLE** (the default), asking for a number past the limit fails with `Next value exceeds MAX(MIN) value.` - **CACHE** *n*: keep the next *n* numbers in memory, which is faster under heavy use. Numbers still in the cache when the server stops are lost, leaving a gap. **NOCACHE** (the default) writes every number to disk. - **COMMENT**: a description of the serial. All values can have up to 38 digits. ```sql CREATE SERIAL invoice_seq START WITH 10000 INCREMENT BY 2 MAXVALUE 20000 CACHE 3 COMMENT 'invoice numbers'; SELECT name, current_val, increment_val, max_val, min_val, cyclic, started, cached_num, comment FROM db_serial WHERE name = 'invoice_seq'; ``` | name | current_val | increment_val | max_val | min_val | cyclic | started | cached_num | comment | |---|---:|---:|---:|---:|---:|---:|---:|---| | invoice_seq | 10000 | 2 | 20000 | 10000 | 0 | 0 | 3 | invoice numbers | The `db_serial` catalog view lists all serials. It is read-only; use `ALTER SERIAL` to change a serial. ## Using a serial ```text serial_name.NEXT_VALUE -- or serial_name.NEXTVAL serial_name.CURRENT_VALUE -- or serial_name.CURRVAL ``` - **NEXT_VALUE** advances the serial and returns the new number. The first call after `CREATE SERIAL` returns the start value. - **CURRENT_VALUE** returns the current number without advancing. ```sql CREATE TABLE invoice (invoice_no INT PRIMARY KEY, order_id INT NOT NULL); INSERT INTO invoice VALUES (invoice_seq.NEXT_VALUE, 455); INSERT INTO invoice VALUES (invoice_seq.NEXT_VALUE, 456); INSERT INTO invoice VALUES (invoice_seq.NEXTVAL, 457); SELECT * FROM invoice ORDER BY invoice_no; ``` | invoice_no | order_id | |---:|---:| | 10000 | 455 | | 10002 | 456 | | 10004 | 457 | ```sql SELECT invoice_seq.CURRENT_VALUE; -- 10004 ``` Each reference to `NEXT_VALUE` advances the serial, even within one statement: `SELECT s.NEXT_VALUE, s.NEXT_VALUE` returns two different numbers. ### CYCLE A countdown from 3 to 1 that starts over: ```sql CREATE SERIAL countdown START WITH 3 INCREMENT BY -1 MINVALUE 1 MAXVALUE 3 CYCLE; -- successive countdown.NEXT_VALUE calls return 3, 2, 1, 3, 2, ... ``` ### SERIAL_CURRENT_VALUE and SERIAL_NEXT_VALUE ```text SERIAL_CURRENT_VALUE(serial_name) SERIAL_NEXT_VALUE(serial_name, count) ``` Both return `NUMERIC(38,0)`. - `SERIAL_CURRENT_VALUE(s)` is the same as `s.CURRENT_VALUE`. - `SERIAL_NEXT_VALUE(s, count)` reserves *count* numbers in one call and returns the **last** of them. `SERIAL_NEXT_VALUE(s, 1)` is the same as `s.NEXT_VALUE`. Reserving a block of numbers at once is much faster than calling `NEXT_VALUE` repeatedly. The first reserved number is *last* − (*count* − 1) × *increment*: ```sql CREATE SERIAL batch_seq START WITH 101; SELECT SERIAL_CURRENT_VALUE(batch_seq); -- 101 SELECT SERIAL_NEXT_VALUE(batch_seq, 10); -- 110: numbers 101 to 110 are yours SELECT SERIAL_NEXT_VALUE(batch_seq, 10); -- 120: numbers 111 to 120 ``` ## ALTER SERIAL ```text ALTER SERIAL serial_name [INCREMENT BY interval] [START WITH initial_value] [MINVALUE min | NOMINVALUE] [MAXVALUE max | NOMAXVALUE] [CYCLE | NOCYCLE] [CACHE cached_count | NOCACHE] [COMMENT 'comment'] ``` The options have the same meaning as in `CREATE SERIAL`. After `START WITH`, the next `NEXT_VALUE` returns the new start value: ```sql ALTER SERIAL batch_seq START WITH 500 INCREMENT BY 5; SELECT batch_seq.NEXT_VALUE; -- 500 ALTER SERIAL batch_seq CACHE 20; ALTER SERIAL batch_seq NOCACHE COMMENT 'batches'; ``` ## DROP SERIAL ```text DROP SERIAL [IF EXISTS] serial_name ``` ```sql DROP SERIAL IF EXISTS batch_seq; ``` ## See also - [AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto-increment) - [System catalog](https://www.coradb.ai/manual/sql/catalog.html): the `db_serial` view --- # CREATE, ALTER, DROP and RENAME TABLE Source: https://www.coradb.ai/manual/sql/schema/table_stmt.html This page covers the statements that create and change tables: [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#create-table), [graph (vertex and edge) tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge), [ALTER TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#alter-table), [DROP TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#drop-table) and [RENAME TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html#rename-table). Indexes, views and serials have their own pages: [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html), [CREATE VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html) and [CREATE SERIAL](https://www.coradb.ai/manual/sql/schema/serial_stmt.html). > **Try it yourself:** > The examples create small tables next to the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. In CoraDB, table definitions are part of the transaction: start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove everything again. ## CREATE TABLE ```text CREATE {TABLE | CLASS} [IF NOT EXISTS] table_name [(, ... [, , ...])] [AUTO_INCREMENT = initial_value] [ [[,] ...]] [[REPLACE] AS ] ::= column_name [DEFAULT | SHARED | AUTO_INCREMENT [(seed, increment)]] [ON UPDATE ] [ ...] [COMMENT 'comment'] ::= [{CHARACTER_SET | CHARSET} charset_name] [COLLATE collation_name] ::= [CONSTRAINT constraint_name] {NOT NULL | UNIQUE | PRIMARY KEY | FOREIGN KEY } ::= [CONSTRAINT [constraint_name]] { PRIMARY KEY (column_name [ASC | DESC], ...) | UNIQUE [KEY | INDEX] [index_name] (column_name [ASC | DESC], ...) | {KEY | INDEX} index_name (column_name [ASC | DESC], ...) | FOREIGN KEY [foreign_key_name] (column_name, ...) } [COMMENT 'comment'] ::= REFERENCES referenced_table_name [(column_name, ...)] [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET NULL}] [ON UPDATE {RESTRICT | NO ACTION | SET NULL}] ::= REUSE_OID | DONT_REUSE_OID | COMMENT [=] 'comment' | [CHARSET charset_name] [COLLATE collation_name] | ENCRYPT [=] [AES | ARIA] ``` - **IF NOT EXISTS**: do nothing, without an error, if a table with the same name already exists. - *table_name*, *column_name*: the names of the table and its columns; see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html). - *column_type*: the [data type](https://www.coradb.ai/manual/sql/datatype.html) of the column. - `TABLE` and `CLASS` are synonyms. CoraDB also supports class inheritance (`UNDER`, `INHERIT`, `CLASS ATTRIBUTE`); see [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html). The following table stores discount coupons: ```sql CREATE TABLE coupon ( code VARCHAR(16) PRIMARY KEY, description VARCHAR(100), discount_pct SMALLINT NOT NULL DEFAULT 10, valid_from DATE NOT NULL DEFAULT SYS_DATE, valid_to DATE, created_by VARCHAR(32) DEFAULT USER, INDEX idx_coupon_valid_to (valid_to) ) COMMENT = 'Discount codes'; INSERT INTO coupon (code, description) VALUES ('WELCOME10', 'First order'); SELECT code, description, discount_pct, valid_to, created_by FROM coupon; ``` | code | description | discount_pct | valid_to | created_by | |---|---|---:|---|---| | WELCOME10 | First order | 10 | NULL | DBA | `valid_from` received today's date. The table comment is stored in the catalog and shown by [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table). > **CHECK constraints are ignored:** > A `CHECK (...)` constraint in a table definition is accepted, so that scripts from other databases run unchanged, but it is not enforced. With `CHECK (discount_pct BETWEEN 1 AND 90)` in the definition above, inserting `discount_pct = 150` still succeeds. Use a [trigger](https://www.coradb.ai/manual/sql/trigger.html) to enforce such rules. ### Column definition Each column has a name and a data type, optionally followed by a default value, an `ON UPDATE` value, constraints and a comment. Column names must be unique within the table. To rename a column later, use [RENAME COLUMN](https://www.coradb.ai/manual/sql/schema/table_stmt.html#rename-column-clause). #### DEFAULT and SHARED - **DEFAULT** *value*: the value stored when an `INSERT` does not give one for the column. - **SHARED** *value*: one value shared by all rows. Inserting a row with a different value changes it for **every** row. Only one of `DEFAULT`, `SHARED` and `AUTO_INCREMENT` can be used on a column. ```sql CREATE TABLE store_setting (id INT, currency CHAR(3) SHARED 'EUR', vat_pct SMALLINT DEFAULT 19); INSERT INTO store_setting (id) VALUES (1), (2); INSERT INTO store_setting (id, currency) VALUES (3, 'RON'); INSERT INTO store_setting (id) VALUES (4); SELECT * FROM store_setting ORDER BY id; ``` | id | currency | vat_pct | |---:|---|---:| | 1 | RON | 19 | | 2 | RON | 19 | | 3 | RON | 19 | | 4 | RON | 19 | Besides constants, a default value can be one of these expressions. They are evaluated when the row is inserted: | Default value | Type | |---|---| | `SYS_DATE`, `CURRENT_DATE`, `SYSDATE` | DATE | | `SYS_TIME`, `CURRENT_TIME` | TIME | | `SYS_DATETIME`, `CURRENT_DATETIME`, `SYSDATETIME` | DATETIME | | `SYS_TIMESTAMP`, `CURRENT_TIMESTAMP` | TIMESTAMP | | `UNIX_TIMESTAMP()` | INTEGER | | `USER`, `USER()` | VARCHAR | | `TO_CHAR(date_time [, format])`, `TO_CHAR(number [, format])` | VARCHAR | ```sql CREATE TABLE invoice_no ( id INT, invoice_code VARCHAR(20) DEFAULT TO_CHAR(12345, 'S999999'), issued_on VARCHAR(10) DEFAULT TO_CHAR(SYS_DATE, 'YYYY-MM-DD') ); INSERT INTO invoice_no (id) VALUES (1); ``` The row gets `invoice_code = ' +12345'` and today's date in `issued_on`. #### AUTO_INCREMENT `AUTO_INCREMENT` numbers the rows automatically. It can be defined on `SMALLINT`, `INTEGER`, `BIGINT` and `NUMERIC(p, 0)` columns. ```text column_name INT AUTO_INCREMENT [(seed, increment)] CREATE TABLE ... (column_name INT AUTO_INCREMENT, ...) AUTO_INCREMENT = seed ``` - *seed*: the first value (default 1). Any integer is allowed. - *increment*: the step (default 1). Only positive integers are allowed. A value is generated when the column is left out of the `INSERT` or set to `NULL`: ```sql CREATE TABLE gift_card (id INT AUTO_INCREMENT(1000, 10), holder VARCHAR(40)); INSERT INTO gift_card (holder) VALUES ('Ana'), ('Mihai'); INSERT INTO gift_card VALUES (NULL, 'Ioana'); SELECT * FROM gift_card ORDER BY id; ``` | id | holder | |---:|---| | 1000 | Ana | | 1010 | Mihai | | 1020 | Ioana | The table option `AUTO_INCREMENT = seed` sets the first value for a table with exactly one `AUTO_INCREMENT` column that has no `(seed, increment)` of its own: ```sql CREATE TABLE return_request (id INT AUTO_INCREMENT PRIMARY KEY, order_id INT) AUTO_INCREMENT = 500; INSERT INTO return_request (order_id) VALUES (455); -- id = 500 ``` Otherwise the statement is rejected: ```sql CREATE TABLE t (id INT AUTO_INCREMENT, id2 INT AUTO_INCREMENT) AUTO_INCREMENT = 5; ``` ```text ERROR: To avoid ambiguity, the AUTO_INCREMENT table option requires the table to have exactly one AUTO_INCREMENT column and no seed/increment specification. ``` > **Note:** > - `AUTO_INCREMENT` does not make a column unique. Add a `PRIMARY KEY` or `UNIQUE` constraint if you need that. > - A value you insert yourself does not change the counter, so it can collide with a later generated value. > - The counter does not wrap around. When it passes the maximum of the column's type (32767 for `SMALLINT`), inserts fail; choose a type large enough from the start. > - The value generated for the last row inserted in your session is returned by [LAST_INSERT_ID](https://www.coradb.ai/manual/sql/function/information_fn.html#last_insert_id). To change the next value later, use [ALTER TABLE ... AUTO_INCREMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#auto_increment-clause). ### ON UPDATE `ON UPDATE` *value* sets a column automatically whenever another column of the row is updated, typically to record the time of the last change. The value can be `SYS_DATE`, `CURRENT_DATE`, `SYS_DATETIME`, `CURRENT_DATETIME`, `SYS_TIMESTAMP`, `CURRENT_TIMESTAMP` or `UNIX_TIMESTAMP()`. If the `UPDATE` sets the column itself, the value given in the statement is used. ```sql CREATE TABLE stock_level ( product_id INT PRIMARY KEY, units INT, changed_at DATETIME ON UPDATE SYS_DATETIME ); INSERT INTO stock_level VALUES (1795, 31, NULL); UPDATE stock_level SET units = units - 1 WHERE product_id = 1795; -- changed_at is set now ``` To remove the behavior, redefine the column without `ON UPDATE` using [MODIFY](https://www.coradb.ai/manual/sql/schema/table_stmt.html#changemodify-clauses). ### Constraints Constraints can be written after a column (column constraints) or as separate items in the column list (table constraints). Constraints on several columns must be table constraints. If you do not name a constraint, CoraDB names it `pk_
_`, `fk_
_` or `u_
_`. #### NOT NULL constraint The column must always have a value: ```sql CREATE TABLE wishlist (customer_id INT NOT NULL, product_id INT NOT NULL, note VARCHAR(100)); INSERT INTO wishlist VALUES (NULL, 1795, 'gift'); ``` ```text ERROR: SQL statement violated NOT NULL constraint. ``` #### UNIQUE constraint No two rows can have the same value in the column, or the same combination of values in the columns. `NULL` values do not count as duplicates, so several rows can have `NULL`. ```sql CREATE TABLE review ( customer_id INT, product_id INT, stars SMALLINT, CONSTRAINT uq_review UNIQUE (customer_id, product_id) ); INSERT INTO review VALUES (5, 1795, 4), (5, 123, 5), (15, 1795, 3); INSERT INTO review VALUES (5, 1795, 1); ``` ```text ERROR: Operation would have caused one or more unique constraint violations. INDEX uq_review ... key: {5, 1795} ``` #### PRIMARY KEY constraint The primary key identifies each row: its columns must be unique and not `NULL`. A table has at most one primary key, on one or more columns. Its index is ascending unless you write `DESC` after a column, as in `PRIMARY KEY (a, b DESC)`. The e-commerce table `order_items`, for example, has the primary key `(order_id, product_id)`. #### FOREIGN KEY constraint A foreign key makes the values of one or more columns refer to the primary key of another table (or of the same table). CoraDB rejects values that do not exist in the referenced table and decides what happens to the referencing rows when the referenced row is deleted or its key is updated. ```text [CONSTRAINT constraint_name] FOREIGN KEY [foreign_key_name] (column_name, ...) REFERENCES referenced_table_name [(column_name, ...)] [ON DELETE {CASCADE | RESTRICT | NO ACTION | SET NULL}] [ON UPDATE {RESTRICT | NO ACTION | SET NULL}] ``` - If you omit the referenced columns, the primary key of the referenced table is used. The number and types of the columns must match. - *foreign_key_name*, when given, takes precedence over *constraint_name*. - **ON DELETE** (default `RESTRICT`): - `RESTRICT` and `NO ACTION`: the referenced row cannot be deleted while rows refer to it. - `CASCADE`: the referencing rows are deleted too. - `SET NULL`: the foreign key columns of the referencing rows are set to `NULL`. - **ON UPDATE** (default `RESTRICT`): `RESTRICT`, `NO ACTION` or `SET NULL`, as above, when the referenced key value changes. - Changes made by `CASCADE` and `SET NULL` do not fire triggers. A shopping cart and its items. Deleting a cart deletes its items; changing a cart's id is not allowed while it has items. The second foreign key refers to the `product` vertex table: ```sql CREATE TABLE cart ( id INT PRIMARY KEY, customer_id INT NOT NULL, CONSTRAINT fk_cart_customer FOREIGN KEY (customer_id) REFERENCES customer (id) ); CREATE TABLE cart_item ( cart_id INT NOT NULL, product_id INT NOT NULL, quantity SMALLINT NOT NULL DEFAULT 1, PRIMARY KEY (cart_id, product_id), CONSTRAINT fk_cart_item_cart FOREIGN KEY (cart_id) REFERENCES cart (id) ON DELETE CASCADE ON UPDATE RESTRICT, FOREIGN KEY (product_id) REFERENCES product (id) ); INSERT INTO cart VALUES (1, 5), (2, 15); INSERT INTO cart_item (cart_id, product_id) VALUES (1, 1795), (1, 123), (2, 335); DELETE FROM cart WHERE id = 1; SELECT cart_id, product_id, quantity FROM cart_item; ``` | cart_id | product_id | quantity | |---:|---:|---:| | 2 | 335 | 1 | The two items of cart 1 were deleted with it. Other operations on these tables fail: ```sql UPDATE cart SET id = 10 WHERE id = 2; -- ON UPDATE RESTRICT INSERT INTO cart VALUES (3, 99999); -- no customer 99999 ``` ```text ERROR: Update/Delete operations are restricted by the foreign key 'fk_cart_item_cart'. ERROR: The constraint of the foreign key 'fk_cart_customer' is invalid, due to value '99999'. ``` With `ON DELETE SET NULL`, the reference is cleared instead: ```sql CREATE TABLE coupon_use ( coupon VARCHAR(16), order_id INT, FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE SET NULL ); INSERT INTO coupon_use VALUES ('WELCOME10', 455); DELETE FROM order_items WHERE order_id = 455; DELETE FROM orders WHERE id = 455; SELECT * FROM coupon_use; -- WELCOME10, NULL ``` #### KEY or INDEX `KEY` and `INDEX` are synonyms. In a table definition they create a regular (non-unique) index; a name is required. Each column can be followed by `ASC` or `DESC` to set the order of the index: ```sql CREATE TABLE order_note ( order_id INT, note VARCHAR(200), INDEX idx_order_note (order_id DESC) ); ``` For all index options, see [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html). ### Table options #### REUSE_OID Every row of a CoraDB table has an object identifier (OID), its physical address. With **REUSE_OID**, the OID of a deleted row can be reused by a new row, which keeps the table compact under heavy `DELETE`/`INSERT` traffic. Such a table cannot be referenced by OID: it cannot be the type of a column, and the OIDs of its rows cannot be read. Updatable views over it are not possible either. `REUSE_OID` is the default for ordinary tables (the [create_table_reuseoid](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes`): ```sql CREATE TABLE ref_test (c countries); ``` ```text ERROR: The class 'countries' is marked as REUSE_OID and is non-referable. Non-referable classes can't be the domain of an attribute and their instances' OIDs cannot be returned. ``` #### DONT_REUSE_OID **DONT_REUSE_OID** creates a referable table, whose rows keep their OIDs. [Vertex and edge tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge) are always created this way. #### Charset and collation `CHARSET` and `COLLATE` set the default character set and collation for the character columns of the table. See [Charset and collation](https://www.coradb.ai/manual/sql/i18n_collation.html#charset-and-collation-of-string-literals). #### Table's COMMENT `COMMENT [=] 'text'` stores a description of the table. Read it with [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table) or from the `comment` column of the `db_class` catalog view, and change it with [ALTER TABLE ... COMMENT](https://www.coradb.ai/manual/sql/schema/table_stmt.html#columns-comment). The options can be combined, separated by commas or spaces: ```sql CREATE TABLE order_note (order_id INT, note VARCHAR(200)) DONT_REUSE_OID, COMMENT = 'Notes on orders', COLLATE utf8_en_ci; ``` #### Table encryption (TDE) `ENCRYPT` stores the table's data encrypted on disk. Choose `AES` or `ARIA`; without an algorithm, the [tde_default_algorithm](https://www.coradb.ai/manual/admin/config.html) parameter decides (default `AES`). Encryption is not inherited by subclasses. See [TDE (transparent data encryption)](https://www.coradb.ai/manual/security.html#tde-transparent-data-encryption). ```sql CREATE TABLE card_vault (customer_id INT, token VARCHAR(64)) ENCRYPT = AES; ``` ### CREATE TABLE LIKE ```text CREATE {TABLE | CLASS} new_table_name LIKE source_table_name ``` Creates an empty table with the same columns, constraints, indexes and encryption setting as an existing table. Generated constraint names follow the new table name (`pk_order_archive_id`); index names you chose yourself are copied as they are, so index hints that name them keep working on the copy. Partitioned tables, tables with an `AUTO_INCREMENT` column, and tables that use inheritance or methods cannot be copied this way. ```sql CREATE TABLE order_archive LIKE orders; ``` ### CREATE TABLE AS SELECT ```text CREATE {TABLE | CLASS} table_name [(, ... [, , ...])] [REPLACE] AS ``` Creates a table and fills it with the rows of a query. - Without a column list, the columns take the names and types of the query's select list. Name computed columns with an alias. Constraints and `AUTO_INCREMENT` are not copied from the source tables. - With a column list, columns with the same name as a select-list column receive its values (converted to the declared type if needed); other declared columns get their default value or `NULL`; select-list columns that are not declared are added to the table. - **REPLACE**: when the new table has a `UNIQUE` column and the query returns duplicates for it, keep the last row instead of failing. ```sql CREATE TABLE top_customer AS SELECT customer_id, COUNT(*) AS orders_count FROM orders GROUP BY customer_id HAVING COUNT(*) >= 39; SELECT * FROM top_customer ORDER BY customer_id; ``` | customer_id | orders_count | |---:|---:| | 440 | 40 | | 444 | 39 | | 812 | 40 | With a column list, a primary key and an extra column with a default: ```sql CREATE TABLE vip_list (customer_id INT PRIMARY KEY, segment VARCHAR(10) DEFAULT 'gold') AS SELECT customer_id, COUNT(*) AS orders_count FROM orders GROUP BY customer_id HAVING COUNT(*) >= 39; SELECT * FROM vip_list ORDER BY customer_id; ``` | segment | customer_id | orders_count | |---|---:|---:| | gold | 440 | 40 | | gold | 444 | 39 | | gold | 812 | 40 | The declared columns come first, followed by the columns that exist only in the query. With `REPLACE`, one row per customer is kept, the last one returned by the query; ordered by date, that is the latest order: ```sql CREATE TABLE last_order (customer_id INT UNIQUE) REPLACE AS SELECT customer_id, order_date FROM orders WHERE customer_id IN (440, 444) ORDER BY order_date; SELECT * FROM last_order ORDER BY customer_id; ``` | customer_id | order_date | |---:|---| | 440 | 2025-12-27 | | 444 | 2025-09-06 | You can also use a [common table expression](https://www.coradb.ai/manual/sql/query/cte.html#ctes-in-other-statements) in the query. ## Graph tables (vertex and edge) Graph data is stored in **vertex tables** (the nodes) and **edge tables** (the connections between them). They are created and changed with the same statements as ordinary tables, with `VERTEX` or `EDGE` before `TABLE`: ```text CREATE [GRAPH] {VERTEX | EDGE} {TABLE | LABEL} [IF NOT EXISTS] table_name [(, ...)] [ ...] ALTER [GRAPH] {VERTEX | EDGE} [TABLE | LABEL] table_name [, ...] DROP [GRAPH] {VERTEX | EDGE} [TABLE | LABEL] [IF EXISTS] table_name [, ...] ``` - `GRAPH` is optional, and `LABEL` is a synonym of `TABLE` (a vertex or edge table is the *label* of its rows in graph terms). - A vertex table can have any columns, keys and indexes, like an ordinary table. - An edge table holds the edge's own properties. The two vertices it connects are stored by CoraDB and are given when the edge is inserted with [INSERT EDGE](https://www.coradb.ai/manual/sql/query/insert.html#insert-edge). An edge table can also have no columns at all. - Vertex and edge tables are always `DONT_REUSE_OID`. [SHOW FULL TABLES](https://www.coradb.ai/manual/sql/query/show.html#show-tables) lists them as `VERTEX TABLE` and `EDGE TABLE`. A warehouse vertex table and an edge table that records how many units of a product each warehouse holds: ```sql CREATE VERTEX TABLE warehouse (id INT PRIMARY KEY, name VARCHAR(64) NOT NULL); CREATE EDGE TABLE stocks (quantity INT NOT NULL, updated_at DATETIME DEFAULT SYSDATETIME); INSERT VERTEX INTO warehouse VALUES (1, 'Bucharest DC'); INSERT EDGE FROM (SELECT warehouse FROM warehouse WHERE id = 1) TO (SELECT product FROM product WHERE id = 1795) INTO stocks (quantity) VALUES (40); SELECT w.name, p.name, s.quantity FROM MATCH (w:warehouse)-[s:stocks]->(p:product); ``` | w.name | p.name | s.quantity | |---|---|---:| | Bucharest DC | Balboa Persistence Tee | 40 | Change and remove graph tables with the usual clauses: ```sql ALTER VERTEX TABLE warehouse ADD COLUMN city VARCHAR(32); ALTER EDGE TABLE stocks ADD COLUMN bin VARCHAR(8); DROP EDGE TABLE IF EXISTS stocks; DROP VERTEX TABLE IF EXISTS warehouse; ``` Rows of graph tables are read with [MATCH](https://www.coradb.ai/manual/graph/match.html) and changed with `INSERT VERTEX`/`INSERT EDGE`, [UPDATE](https://www.coradb.ai/manual/sql/query/update.html#updating-vertices-and-edges) and [DELETE](https://www.coradb.ai/manual/sql/query/delete.html#deleting-vertices-and-edges). For a step-by-step introduction, see the [Graph tutorial](https://www.coradb.ai/manual/graph/graph_getting_started.html). ## ALTER TABLE `ALTER TABLE` changes the definition of an existing table: its columns, constraints, indexes, comments, `AUTO_INCREMENT` counter and owner. Several clauses can be combined in one statement, separated by commas. `TABLE` and `CLASS`, and `COLUMN` and `ATTRIBUTE`, are synonyms. ```text ALTER [/*+ SKIP_UPDATE_NULL */] [TABLE | CLASS] table_name [, ...] ::= ADD [COLUMN] [FIRST | AFTER column_name] | ADD [COLUMN] (, ...) | ADD [CONSTRAINT [constraint_name]] | ADD {KEY | INDEX} index_name (column_name [(length)] [ASC | DESC], ...) [COMMENT 'comment'] | ALTER [COLUMN] column_name SET DEFAULT | CHANGE [COLUMN] old_column_name new_column_name [FIRST | AFTER column_name] | MODIFY [COLUMN] column_name [FIRST | AFTER column_name] | RENAME [COLUMN] old_column_name AS new_column_name | DROP [COLUMN] column_name [, column_name ...] | DROP CONSTRAINT constraint_name | DROP {KEY | INDEX} index_name | DROP PRIMARY KEY | DROP FOREIGN KEY constraint_name | AUTO_INCREMENT = initial_value | COMMENT [=] 'comment' | COMMENT ON COLUMN column_name [=] 'comment' [, column_name [=] 'comment' ...] | OWNER TO user_name ``` Only the owner of the table, `DBA` and members of the `DBA` group can change a table, unless the owner grants the `ALTER` permission to others (see [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant)). The clauses for class inheritance and views (`ADD SUPERCLASS`, `INHERIT`, `ADD QUERY` and so on) are described in [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html) and [ALTER VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html). The examples below change this table of supplier contacts: ```sql CREATE TABLE supplier_contact ( id INT AUTO_INCREMENT PRIMARY KEY, supplier_id INT, email VARCHAR(64) ); INSERT INTO supplier_contact (supplier_id, email) VALUES (1, 'ana@acme.example'), (2, NULL); ``` ### ADD COLUMN clause Adds one or more columns, at the end of the table or at the position given by `FIRST` or `AFTER`: ```sql ALTER TABLE supplier_contact ADD COLUMN phone VARCHAR(32) AFTER supplier_id, ADD COLUMN active SMALLINT DEFAULT 1; ALTER TABLE supplier_contact ADD COLUMN priority INT FIRST; SHOW COLUMNS FROM supplier_contact; ``` | Field | Type | Null | Key | Default | Extra | |---|---|---|---|---|---| | priority | INTEGER | YES | | NULL | | | id | INTEGER | NO | PRI | NULL | auto_increment | | supplier_id | INTEGER | YES | | NULL | | | phone | VARCHAR(32) | YES | | NULL | | | email | VARCHAR(64) | YES | | NULL | | | active | SHORT | YES | | 1 | | What the existing rows receive in the new column: - The `DEFAULT` value, if the column has one (above, `active` is 1 in both rows); - Otherwise `NULL`. A `NOT NULL` column without a default is therefore rejected on a table that has rows, unless the [add_column_update_hard_default](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) parameter is `yes` (default `no`); then the rows receive the type's [hard default value](https://www.coradb.ai/manual/sql/schema/table_stmt.html#hard-default-values). ```sql ALTER TABLE supplier_contact ADD COLUMN region VARCHAR(10) NOT NULL; ``` ```text ERROR: Cannot add NOT NULL constraint for attribute "region": there are existing NULL values for this attribute. ``` The same rules decide whether a `UNIQUE` or `PRIMARY KEY` constraint on a new column can be satisfied: a new `PRIMARY KEY` column can only be added to an empty table, and a new `UNIQUE` column with a default value fails on a table with more than one row. ### ADD CONSTRAINT clause Adds a `PRIMARY KEY`, `UNIQUE` or `FOREIGN KEY` constraint. The existing rows must satisfy it. If you omit the name, one is generated. ```sql ALTER TABLE supplier_contact ADD CONSTRAINT uq_supplier_contact_email UNIQUE (email); ALTER TABLE supplier_contact ADD CONSTRAINT fk_supplier_contact_supplier FOREIGN KEY (supplier_id) REFERENCES supplier (id); ``` ### ADD INDEX clause Adds a regular index; `KEY` and `INDEX` are synonyms. The same can be done with [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html). ```sql ALTER TABLE supplier_contact ADD INDEX idx_supplier_contact_phone (phone) COMMENT 'lookup by phone'; ``` ### ALTER COLUMN ... SET DEFAULT clause Sets or changes the default value of a column without touching its other attributes: ```sql ALTER TABLE supplier_contact ALTER COLUMN active SET DEFAULT 0; ``` ### AUTO_INCREMENT clause Sets the next value of the table's `AUTO_INCREMENT` column (the table must have exactly one): ```sql ALTER TABLE supplier_contact AUTO_INCREMENT = 100; INSERT INTO supplier_contact (supplier_id, email) VALUES (3, 'ion@acme.example'); SELECT id, supplier_id, active FROM supplier_contact ORDER BY id; ``` | id | supplier_id | active | |---:|---:|---:| | 1 | 1 | 1 | | 2 | 2 | 1 | | 100 | 3 | 0 | Make sure the new values cannot collide with existing ones in a primary key or unique column. Changing the column's type (for example from `INT` to `BIGINT`) also changes the counter's maximum. ### CHANGE/MODIFY clauses - **CHANGE** *old_name new_name* \<*column_definition*\> renames a column and redefines it. Repeat the old name to keep the name. - **MODIFY** *column_name* \<*column_definition*\> redefines a column without renaming it. Both can move the column with `FIRST` or `AFTER`. ```sql ALTER TABLE supplier_contact CHANGE email contact_email VARCHAR(100); ALTER TABLE supplier_contact MODIFY phone VARCHAR(64); ``` The new definition **replaces** the old one: a `DEFAULT`, `NOT NULL`, `AUTO_INCREMENT` or `ON UPDATE` attribute that you do not repeat is removed. Primary key, unique and regular indexes on the column are kept, and rebuilt if the type changes. Columns used in a foreign key (referencing or referenced) and partitioning columns cannot be changed. Whether existing values may be converted is controlled by two parameters: - [alter_table_change_type_strict](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) (default `yes`): values that cannot be converted to the new type, or would overflow, make the statement fail. With `no`, such values are replaced by the type's minimum or maximum, or by its [hard default value](https://www.coradb.ai/manual/sql/schema/table_stmt.html#hard-default-values), and a warning is logged. - [allow_truncated_string](https://www.coradb.ai/manual/admin/config_sql.html#statementtype-related-parameters) (default `no`): strings that would not fit in a shorter type make the statement fail. With the defaults, shortening a column below the length of its data fails: ```sql CREATE TABLE promo (code VARCHAR(20)); INSERT INTO promo VALUES ('WELCOME-2026-SPRING'); ALTER TABLE promo MODIFY code VARCHAR(8); ``` ```text ERROR: ALTER TABLE .. CHANGE : changing to new domain : cast failed, current configuration doesn't allow truncation or overflow. ``` Adding `NOT NULL` to a column that contains `NULL` values fails as well: ```text ERROR: Cannot add NOT NULL constraint for attribute "phone": there are existing NULL values for this attribute. ``` The **SKIP_UPDATE_NULL** hint adds the `NOT NULL` constraint without checking or changing the existing rows. This is fast on large tables, but existing `NULL` values then remain in a column declared `NOT NULL`: ```sql ALTER /*+ SKIP_UPDATE_NULL */ TABLE supplier_contact MODIFY phone VARCHAR(64) NOT NULL; ``` Triggers and views that use the column are not updated automatically; recreate them after changing a column's type or collation. #### Hard default values The hard default is the value CoraDB uses for existing rows when it needs a value of a type and none is given (see above): | Type | Hard default | |---|---| | INTEGER, SMALLINT, BIGINT, NUMERIC, FLOAT, DOUBLE | `0` | | DATE | `DATE'01/01/0001'` | | TIME | `TIME'00:00'` | | DATETIME | `DATETIME'01/01/0001 00:00'` | | TIMESTAMP | `TIMESTAMP'00:00:01 AM 01/01/1970'` (GMT) | | CHAR, VARCHAR | `''` (empty string) | | SET, MULTISET, LIST | `{}` | | BIT, VARBIT, BLOB, CLOB, object types | none | ### RENAME COLUMN clause ```sql ALTER TABLE supplier_contact RENAME COLUMN priority AS rank_no; ``` ### Comments Change the table's comment, or the comments of one or more columns: ```sql ALTER TABLE supplier_contact COMMENT = 'Contacts at our suppliers'; ALTER TABLE supplier_contact COMMENT ON COLUMN phone = 'Direct line'; ``` Column comments are shown by [SHOW FULL COLUMNS](https://www.coradb.ai/manual/sql/query/show.html#show-columns) and stored in the `comment` column of the `db_attribute` catalog view. A comment can also be given in a column definition, in `CREATE TABLE`, `ADD COLUMN`, `CHANGE` or `MODIFY`. ### DROP COLUMN clause Removes one or more columns and their data: ```sql ALTER TABLE supplier_contact DROP COLUMN rank_no, active; ``` ### DROP CONSTRAINT, DROP INDEX, DROP PRIMARY KEY and DROP FOREIGN KEY clauses ```sql ALTER TABLE supplier_contact DROP INDEX idx_supplier_contact_phone; ALTER TABLE supplier_contact DROP CONSTRAINT uq_supplier_contact_email; ALTER TABLE supplier_contact DROP FOREIGN KEY fk_supplier_contact_supplier; ALTER TABLE supplier_contact DROP PRIMARY KEY; ``` - `DROP CONSTRAINT` removes a primary key, unique or foreign key constraint by name. - `DROP INDEX` removes a regular index. A unique index can be removed with `DROP CONSTRAINT` or [DROP INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html). - `DROP PRIMARY KEY` needs no name, because a table has only one primary key. It fails while a foreign key refers to it. - Find constraint and index names with [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) or [SHOW CREATE TABLE](https://www.coradb.ai/manual/sql/query/show.html#show-create-table). ### OWNER TO clause Gives the table to another user. Only `DBA` and members of the `DBA` group can do this. ```sql CREATE USER catalog_admin; ALTER TABLE supplier_contact OWNER TO catalog_admin; ``` Views, triggers and stored procedures change owner in the same way; see [ALTER ... OWNER](https://www.coradb.ai/manual/sql/authorization.html#alter--owner). ## DROP TABLE ```text DROP [TABLE | CLASS] [IF EXISTS] [, ...] [CASCADE CONSTRAINTS] ::= [ONLY] table_name | ALL table_name [(EXCEPT table_name, ...)] ``` Removes tables with all their rows, indexes and constraints. Several tables can be dropped at once. - **IF EXISTS**: skip tables that do not exist instead of failing. - **CASCADE CONSTRAINTS**: also remove the foreign keys of other tables that refer to the dropped table. The rows of those tables are kept. Without it, a table whose primary key is referenced cannot be dropped. - `ONLY`, `ALL` and `EXCEPT` select subclasses in a class hierarchy; see [Class inheritance](https://www.coradb.ai/manual/sql/oodb.html). ```sql CREATE TABLE parent_t (id INT PRIMARY KEY); CREATE TABLE child_t (id INT, p INT, FOREIGN KEY (p) REFERENCES parent_t (id)); DROP TABLE parent_t; ``` ```text ERROR: The primary key 'pk_parent_t_id' referred by a foreign key 'fk_child_t_p' is not supposed to be dropped. ``` ```sql DROP TABLE IF EXISTS parent_t CASCADE CONSTRAINTS; -- child_t loses its foreign key, keeps its rows DROP TABLE IF EXISTS no_such_table, child_t; ``` To drop vertex and edge tables, see [Graph tables](https://www.coradb.ai/manual/sql/schema/table_stmt.html#graph-tables-vertex-and-edge). ## RENAME TABLE ```text RENAME [TABLE | CLASS] old_table_name {AS | TO} new_table_name [, old_table_name {AS | TO} new_table_name ...] ``` Renames one or more tables. Only the owner, `DBA` and members of the `DBA` group can rename a table, unless the owner grants the permission to others. ```sql RENAME TABLE supplier_contact TO supplier_person; ``` ## See also - [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html) - [CREATE VIEW](https://www.coradb.ai/manual/sql/schema/view_stmt.html) - [CREATE SERIAL](https://www.coradb.ai/manual/sql/schema/serial_stmt.html) - [Data types](https://www.coradb.ai/manual/sql/datatype.html) - [Partitioning](https://www.coradb.ai/manual/sql/partition.html) --- # CREATE, ALTER, DROP and RENAME VIEW Source: https://www.coradb.ai/manual/sql/schema/view_stmt.html A view is a named query. It stores no data of its own: every time you select from it, CoraDB runs its query. Views give a stable name to a frequently used query, hide columns, and let users read data without access to the underlying tables. `VIEW` and `VCLASS` are synonyms. > **Try it yourself:** > The examples run on the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the real results. Start corasql with `corasql --no-auto-commit -u dba e-commerce` and finish with `ROLLBACK;` to remove the views again. ## CREATE VIEW ```text CREATE [OR REPLACE] {VIEW | VCLASS} view_name [(view_column_name [COMMENT 'comment'], ...)] AS [WITH CHECK OPTION] [COMMENT [=] 'comment'] ``` - **OR REPLACE**: replace an existing view of the same name instead of returning an error. - *view_name*: a name that is unique among the tables and views of the database; see [Identifiers](https://www.coradb.ai/manual/sql/identifier.html). - *view_column_name*: names for the view's columns, one per column of the query. Without them, the columns take the names of the query's select list. - *select_statement*: any valid [SELECT](https://www.coradb.ai/manual/sql/query/select.html), including joins, grouping and [MATCH](https://www.coradb.ai/manual/graph/match.html) patterns. - **WITH CHECK OPTION**: reject `INSERT` and `UPDATE` statements through the view that would produce rows the view's `WHERE` condition excludes. - **COMMENT**: comments for the view and its columns. A view with one row per order, its number of items and its value: ```sql CREATE VIEW order_summary (order_id COMMENT 'Order number', customer_id, order_date, items, total) AS SELECT o.id, o.customer_id, o.order_date, COUNT(*), SUM(oi.quantity * p.unit_price * (100 - oi.discount_pct) / 100) FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN product p ON p.id = oi.product_id GROUP BY o.id, o.customer_id, o.order_date COMMENT = 'One row per order with its value'; SELECT * FROM order_summary WHERE order_id = 455; ``` | order_id | customer_id | order_date | items | total | |---:|---:|---|---:|---:| | 455 | 458 | 2025-12-30 | 3 | 221.75 | Replace a view's definition, keeping its name and the permissions granted on it: ```sql CREATE OR REPLACE VIEW order_summary AS SELECT id AS order_id, customer_id, order_date FROM orders COMMENT 'Orders without their value'; ``` [SHOW CREATE VIEW](https://www.coradb.ai/manual/sql/query/show.html#show-create-view) returns a view's query, and the `comment` columns of the `db_class` and `db_attribute` catalog views return its comments. ### Updatable views `INSERT`, `UPDATE` and `DELETE` statements can target a view when CoraDB can map each row of the view to exactly one row of a table. The view's query must: - Read from a single table or updatable view (no joins); - Not use `DISTINCT`, `GROUP BY`, `HAVING` or aggregate functions; - Combine several queries only with `UNION ALL`, each reading a different table. A column that is an expression, such as `unit_price * 1.19`, cannot be updated through the view. The user also needs the corresponding permission on the underlying table. ```sql CREATE VIEW low_stock AS SELECT id, name, units_in_stock FROM product WHERE units_in_stock < 5; UPDATE low_stock SET units_in_stock = 5 WHERE id = 5; -- updates the product table ``` > **Warning:** > In this release, updates through views work for views over vertex tables, such as `product` and `customer` in the e-commerce database. A view over an ordinary table is reported as `Vclass is not updatable`; change such tables directly. ### WITH CHECK OPTION With `WITH CHECK OPTION`, a change made through the view must keep the row visible in the view: ```sql CREATE VIEW cheap_product AS SELECT id, name, unit_price FROM product WHERE unit_price < 20 WITH CHECK OPTION; UPDATE cheap_product SET unit_price = 18.50 WHERE id = 31; -- allowed UPDATE cheap_product SET unit_price = 25 WHERE id = 31; -- the row would leave the view ``` ```text ERROR: Check option exception on view cheap_product. ``` ## ALTER VIEW ```text ALTER [VIEW | VCLASS] view_name AS | ADD QUERY | CHANGE QUERY [query_number] | DROP QUERY query_number [, query_number ...] | COMMENT [=] 'comment' | COMMENT ON COLUMN column_name [=] 'comment' [, column_name [=] 'comment' ...] ``` A view's definition is a list of queries whose results are combined with `UNION ALL`. The query given in `CREATE VIEW` is query 1; queries added later get the next numbers. - **AS** *select_statement*: replace the whole definition, like `CREATE OR REPLACE VIEW`. - **ADD QUERY**: add a query to the list. - **CHANGE QUERY** *n*: replace query *n* (default 1). - **DROP QUERY** *n*, ...: remove queries from the list. - **COMMENT**, **COMMENT ON COLUMN**: change the view's comment or its columns' comments. ```sql CREATE VIEW featured_product AS SELECT id, name, unit_price FROM product WHERE id = 1795; ALTER VIEW featured_product ADD QUERY SELECT id, name, unit_price FROM product WHERE id = 123; ALTER VIEW featured_product ADD QUERY SELECT id, name, unit_price FROM product WHERE id = 335; SELECT * FROM featured_product ORDER BY id; ``` | id | name | unit_price | |---:|---|---:| | 123 | Erika Running Short | 45.00 | | 335 | Arcadio Gym Short | 20.00 | | 1795 | Balboa Persistence Tee | 29.00 | ```sql ALTER VIEW featured_product CHANGE QUERY 3 SELECT id, name, unit_price FROM product WHERE id = 38; ALTER VIEW featured_product DROP QUERY 2; SELECT * FROM featured_product ORDER BY id; ``` | id | name | unit_price | |---:|---|---:| | 38 | Côte de Blaye | 263.50 | | 1795 | Balboa Persistence Tee | 29.00 | Replace the definition and add comments: ```sql ALTER VIEW featured_product AS SELECT id, name, unit_price FROM product WHERE unit_price > 120; ALTER VIEW featured_product COMMENT = 'Products on the home page'; ALTER VIEW featured_product COMMENT ON COLUMN unit_price = 'Current price'; ``` > **Note:** > A view is not updated when the tables it reads from change. After changing the type or collation of a column a view uses, recreate the view. ## DROP VIEW ```text DROP {VIEW | VCLASS} [IF EXISTS] view_name [, view_name ...] ``` Removes views. The underlying tables and their data are not affected. With `IF EXISTS`, views that do not exist are skipped. ```sql DROP VIEW IF EXISTS featured_product, order_summary; ``` ## RENAME VIEW ```text RENAME {VIEW | VCLASS} old_view_name {AS | TO} new_view_name [, old_view_name {AS | TO} new_view_name ...] ``` ```sql RENAME VIEW low_stock AS reorder_list; ``` ## See also - [SELECT](https://www.coradb.ai/manual/sql/query/select.html) - [CREATE TABLE](https://www.coradb.ai/manual/sql/schema/table_stmt.html) - [GRANT](https://www.coradb.ai/manual/sql/authorization.html#grant): give users access to a view --- # Writing rules Source: https://www.coradb.ai/manual/sql/syntax.html These pages cover the building blocks that every CoraDB SQL statement is made of. | Topic | What it covers | |---|---| | [Identifiers](https://www.coradb.ai/manual/sql/identifier.html) | How to name tables, columns and other objects; quoting; maximum lengths. | | [Reserved words](https://www.coradb.ai/manual/sql/keyword.html) | Words that cannot be used as unquoted names. | | [Comments](https://www.coradb.ai/manual/sql/comment.html) | `--`, `//` and `/* */` comments, and `/*+ */` hints. | | [Literals](https://www.coradb.ai/manual/sql/literal.html) | Numbers, dates and times, bit strings, character strings, collections and `NULL`. | A few general rules apply to all statements: - Keywords and identifiers are not case-sensitive. This manual writes keywords in uppercase and names in lowercase. - A statement ends with a semicolon (`;`). In [corasql](https://www.coradb.ai/manual/corasql.html) the semicolon tells the interpreter to run the statement; drivers usually run one statement per call without it. - Spaces, tabs and line breaks between words are interchangeable, so long statements can be spread over several lines. --- # Transactions: COMMIT, ROLLBACK and savepoints Source: https://www.coradb.ai/manual/sql/transaction.html A transaction is a group of SQL statements that CoraDB treats as one unit: either all of its changes become permanent (**COMMIT**) or none of them do (**ROLLBACK**). Transactions give each user a consistent view of the data while many users read and write at the same time, and they let the database recover to a consistent state after a failure. | Topic | Page | |---|---| | COMMIT, ROLLBACK, savepoints, cursor holdability, recovery | This page | | How concurrent transactions see data: MVCC, snapshots, VACUUM | [Concurrency and MVCC](https://www.coradb.ai/manual/sql/transaction_mvcc.html) | | Locks, lock modes, deadlocks and lock timeouts | [Locking](https://www.coradb.ai/manual/sql/transaction_locking.html) | | READ COMMITTED, REPEATABLE READ and SERIALIZABLE | [Isolation levels](https://www.coradb.ai/manual/sql/transaction_isolation.html) | In short: CoraDB uses multiversion concurrency control (MVCC). A transaction's changes are invisible to others until it commits, readers never wait for writers, and two transactions that modify the same row are serialized by an exclusive row lock. The default isolation level is **READ COMMITTED**. ## Autocommit By default every statement runs in **autocommit** mode: it is committed automatically when it succeeds and rolled back when it fails. To group several statements in one transaction, turn autocommit off in your client and end the transaction yourself with **COMMIT** or **ROLLBACK**. | Client | How to control autocommit | |---|---| | corasql | The session command `;autocommit off` / `;autocommit on`; see [Session commands](https://www.coradb.ai/manual/corasql.html#session-commands) | | JDBC | `Connection.setAutoCommit(false)` | | CCI and the drivers built on it | The broker parameter [CCI_DEFAULT_AUTOCOMMIT](https://www.coradb.ai/manual/admin/config_broker.html#cci_default_autocommit) (default `ON`) sets the initial mode; `cci_set_autocommit()` changes it per connection | The examples on these pages assume autocommit is off. ## Transaction commit ```sql COMMIT [WORK]; ``` **COMMIT** makes all changes of the current transaction permanent (written to the log on disk) and visible to other transactions, and releases all locks the transaction holds. Until then, only the transaction itself sees its changes. The keyword **WORK** is optional. ```sql -- autocommit off SELECT id, units_in_stock FROM product WHERE id IN (1618, 1619); -- 22, 76 UPDATE product SET units_in_stock = units_in_stock + 10 WHERE id IN (1618, 1619); SELECT id, units_in_stock FROM product WHERE id IN (1618, 1619); -- 32, 86, seen only by this transaction COMMIT; -- now permanent and visible to everyone ``` ## Transaction rollback ```sql ROLLBACK [WORK]; ``` **ROLLBACK** cancels every change made since the transaction started and releases its locks. Use it to undo mistakes before they become permanent. DDL statements are transactional too, so a schema change can be rolled back together with data changes. In the following transaction a column is dropped by mistake: ```sql CREATE TABLE gift_card (code VARCHAR(16), owner VARCHAR(64), balance NUMERIC(10,2)); COMMIT; ALTER TABLE gift_card DROP COLUMN owner; INSERT INTO gift_card (code, owner, balance) VALUES ('GC-1001', 'Alvarado LLC', 50); -- ERROR: Attribute "owner" was not found. ROLLBACK; -- the column is back; the failed INSERT can be run again ``` ## Savepoint and partial rollback A savepoint marks a point inside a transaction. **ROLLBACK TO SAVEPOINT** undoes only the changes made after that point; the transaction stays open and can continue, commit or roll back completely. A savepoint does not commit anything. ```sql SAVEPOINT mark; ROLLBACK [WORK] TO [SAVEPOINT] mark; ``` - *mark* is an identifier or a host variable (`:name`). - A transaction can have several savepoints. If a name is reused, the newest savepoint with that name is used; the older one becomes visible again after the newer one has been rolled back to. - Rolling back to a savepoint removes the savepoints set after it. **COMMIT** and a full **ROLLBACK** remove all savepoints. - You can roll back to the same savepoint several times. - **ROLLBACK** without **TO** rolls back the whole transaction. ```sql -- autocommit off; product 1618 has 22 units, 1619 has 76 UPDATE product SET units_in_stock = units_in_stock - 2 WHERE id = 1618; -- 20 SAVEPOINT sp1; UPDATE product SET units_in_stock = units_in_stock - 5 WHERE id = 1619; -- 71 SAVEPOINT sp2; UPDATE product SET units_in_stock = 0 WHERE id IN (1618, 1619); -- 0, 0 (mistake) ROLLBACK TO SAVEPOINT sp2; -- 20, 71: only the last UPDATE is undone ROLLBACK TO sp1; -- 20, 76: the second UPDATE is undone as well COMMIT; -- keeps the first UPDATE only ``` Savepoints are useful in long transactions, for example a batch job that can retry one step without repeating everything before it. ## Cursor holdability *Cursor holdability* means that a result set stays open after the transaction that produced it commits, so the application can keep fetching rows. In CoraDB cursors are holdable by default (**HOLD_CURSORS_OVER_COMMIT**). In JDBC you can set holdability per connection or per statement: ```java // connection level conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); // statement level, overrides the connection setting PreparedStatement ps = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, ResultSet.HOLD_CURSORS_OVER_COMMIT); ``` Use `ResultSet.CLOSE_CURSORS_AT_COMMIT` to close result sets at commit instead. `HOLD_CURSORS_OVER_COMMIT` is not supported on `java.sql.XAConnection`. CCI applications and the drivers built on CCI hold cursors by default. If holding is turned off for a connection, the `CCI_PREPARE_HOLDABLE` flag of `cci_prepare()` makes one statement holdable. See the prepare function of each driver for its options. **When held result sets are closed** - A **ROLLBACK** closes all result sets, including those held over earlier commits. This includes the automatic rollback after a failed statement in autocommit mode. ```java rs1 = stmt.executeQuery(sql1); conn.commit(); // rs1 stays open rs2 = stmt.executeQuery(sql2); conn.rollback(); // rs1 and rs2 are closed ``` - The application closes the result set (`rs.close()`) or the statement (`stmt.close()`), or disconnects. - The connection between the application and its CAS (the broker's application server) is closed. With the broker parameter [KEEP_CONNECTION](https://www.coradb.ai/manual/admin/config_broker.html#keep_connection) set to `AUTO`, a CAS is not restarted while it has an open holdable result set; with `ON`, holdability is not affected. Open result sets use memory on the server, so close them as soon as you are done. ## Transaction termination and recovery CoraDB guarantees that a transaction is *atomic*: after any failure, either all of its changes are in the database or none are. Recovery is automatic and based on undo/redo logging; applications do not need to repair the database after a crash. - Every change is written to the log twice: a *before image* (undo) used for **ROLLBACK** and for removing uncommitted changes after a failure, and an *after image* (redo) used to re-apply committed changes that had not yet reached the data volumes. - The current log is the *active log*. When it is full, it is copied to an *archive log*. - If a failure happens while **COMMIT** is running and the commit was not completed, the transaction is rolled back. ### Restarting the database **After a normal shutdown or a system failure,** start the server as usual (`coradb server start `). On restart CoraDB re-applies committed changes that are missing from the data volumes and removes uncommitted ones. No archive logs or backups are needed. **After a media (disk) failure,** restore the last good backup and the logs written after it with [restoredb](https://www.coradb.ai/manual/admin/admin_backup.html#restoredb), then start the server. Take regular backups with [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb) so that as few changes as possible depend on log files. ### Dirty records in the client A client keeps changed objects (*dirty records*) in its buffers and flushes them to the server when needed, for example when the transaction commits, when many objects are loaded, when the schema of their table changes, when their table is queried, or when a server-side function is called. This is automatic and does not change transaction semantics. --- # Transaction isolation levels: READ COMMITTED, REPEATABLE READ, SERIALIZABLE Source: https://www.coradb.ai/manual/sql/transaction_isolation.html The *isolation level* of a transaction determines how much it is affected by other transactions running at the same time. A higher level gives each transaction a more stable view of the data; a lower level allows more concurrency. CoraDB supports three levels: | Level | Number | Snapshot | Non-repeatable / phantom reads | Concurrent update of the same row | |---|---|---|---|---| | [READ COMMITTED](https://www.coradb.ai/manual/sql/transaction_isolation.html#read-committed-isolation-level) (default) | 4 | New for each statement | Possible | Waits, then re-evaluates the row and continues | | [REPEATABLE READ](https://www.coradb.ai/manual/sql/transaction_isolation.html#repeatable-read-isolation-level) | 5 | One for the whole transaction | no | Waits, then fails if the other transaction committed | | [SERIALIZABLE](https://www.coradb.ai/manual/sql/transaction_isolation.html#serializable-isolation-level) | 6 | Same as **REPEATABLE READ** | no | Same as **REPEATABLE READ** | At every level, dirty reads are impossible, readers never block writers, and the schema of a table that a running transaction has read cannot be changed until that transaction ends. Levels 1 to 3 of older versions are no longer supported. Background: [Concurrency and MVCC](https://www.coradb.ai/manual/sql/transaction_mvcc.html). ## SET TRANSACTION ISOLATION LEVEL ```sql SET TRANSACTION ISOLATION LEVEL isolation_level [, LOCK TIMEOUT timeout_spec]; isolation_level: READ COMMITTED | CURSOR STABILITY | 4 | REPEATABLE READ | 5 | SERIALIZABLE | 6 ``` ```sql SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; SET TRANSACTION ISOLATION LEVEL 4; SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, LOCK TIMEOUT 10; ``` Other values are rejected, for example `SET TRANSACTION ISOLATION LEVEL 3` fails with `Isolation level value in MVCC must be 'read committed', 'repeatable read' or 'serializable'.` For **LOCK TIMEOUT** see [Transaction lock timeout](https://www.coradb.ai/manual/sql/transaction_locking.html#transaction-lock-timeout). The default for new sessions is set with the system parameter [isolation_level](https://www.coradb.ai/manual/admin/config_logging.html#isolation_level): ```text # coradb.conf isolation_level = 4 # or isolation_level = "TRAN_READ_COMMITTED" ``` A new level applies from the next statement on, also inside a running transaction. Set it at the start of a transaction (after **COMMIT** or **ROLLBACK**) so that the whole transaction runs at one level. ## GET TRANSACTION ISOLATION LEVEL ```sql GET TRANSACTION ISOLATION LEVEL [ { INTO | TO } :variable ]; ``` Returns the isolation level of the current session, for example `READ COMMITTED`, or stores it in a host variable. ## Examples The examples use two sessions with autocommit off (`;autocommit off` in corasql), each set to the level being shown. Steps run in order. They change rows of the e-commerce `product` table; the last step of each example restores the data. ## READ COMMITTED isolation level **READ COMMITTED** (4) is the default. Each statement sees the data as committed when the statement started: - Rows inserted by another transaction are invisible until it commits. - A row being updated by another transaction can be read; you see its last committed version. - A row being updated by another transaction cannot be updated at the same time. The second transaction waits, then [re-evaluates](https://www.coradb.ai/manual/sql/transaction_isolation.html#read-committed-update-re-evaluation) the committed row. - Rows you are reading can be updated by others, and new rows can be inserted into the table. - The schema of a table you have read cannot be changed by others until your transaction ends. - Because every statement takes a new snapshot, the same query can return different results within one transaction (non-repeatable and phantom reads). Only exclusive row locks are used for writing. No shared row locks are taken; the intent lock on each table read is kept until the end of the transaction, which keeps the schema stable. **Example: non-repeatable read and stable schema** | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | | `SELECT COUNT(*) FROM product WHERE units_in_stock < 5;` | 217 | | 2 | `UPDATE product SET units_in_stock = 3, unit_price = 34.00 WHERE id = 1618;` then `COMMIT;` | | | | 3 | | `SELECT COUNT(*) FROM product WHERE units_in_stock < 5;` | 218: the committed change is visible in the same transaction. | | 4 | | `SELECT unit_price FROM product WHERE id = 1618;` | 34.00 (was 29.00) | | 5 | `CREATE INDEX i_product_stock ON product (units_in_stock);` | | Waits: Session 2 has read `product` and its transaction is still open. | | 6 | | `SELECT COUNT(*) FROM product WHERE units_in_stock < 5;` | 218: Session 2 keeps working on the same schema. | | 7 | | `COMMIT;` | Session 1's **CREATE INDEX** continues. | | 8 | `ROLLBACK;` then `UPDATE product SET units_in_stock = 22, unit_price = 29.00 WHERE id = 1618;` and `COMMIT;` | | Index removed, data restored. | ### Update re-evaluation When a **READ COMMITTED** statement wants to change a row that another transaction has changed but not committed, it waits. When the other transaction commits, the statement does not fail (as it would under **REPEATABLE READ**). It reads the newly committed version and checks its search condition again: - If the new version still matches, the statement changes the new version. - If it no longer matches, the row is skipped, as if it had never matched. Products 1607, 1620 and 1628 have 0, 4 and 4 units in stock. Session 2 discounts low-stock products by 5.00 while Session 1 restocks two of them: | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `UPDATE product SET units_in_stock = units_in_stock + 2 WHERE id = 1607;` `UPDATE product SET units_in_stock = units_in_stock + 10 WHERE id = 1620;` | | 1607 → 2, 1620 → 14 (not committed). Session 1 locks both rows. | | 2 | | `UPDATE product SET unit_price = unit_price - 5 WHERE units_in_stock < 5 AND id IN (1607, 1620, 1628);` | Session 2's snapshot sees all three rows matching. It updates 1628 and waits for the lock on the next row. | | 3 | `COMMIT;` | | | | 4 | | | Session 2 continues. 1607 now has 2 units: still matches, discounted. 1620 now has 14 units: no longer matches, skipped. | | 5 | | `SELECT id, unit_price, units_in_stock FROM product WHERE id IN (1607, 1620, 1628);` | 1607: 40.00, 2 · 1620: 49.00, 14 · 1628: 19.00, 4 | To restore the data: `ROLLBACK;` in Session 2, then in Session 1 `UPDATE product SET units_in_stock = units_in_stock - 2 WHERE id = 1607; UPDATE product SET units_in_stock = units_in_stock - 10 WHERE id = 1620; COMMIT;`. ## REPEATABLE READ isolation level **REPEATABLE READ** (5) gives each transaction one snapshot, taken by its first statement and kept until it ends: - Rows inserted by another transaction are invisible, even after it commits. - A row being updated by another transaction can be read; you see the version committed before your snapshot. - A row that another transaction has changed and committed after your snapshot cannot be changed by you: the statement fails with `Serializable conflict due to concurrent updates`. - Rows you are reading can be updated by others, and new rows can be inserted into the table; you just do not see the changes. - The schema of a table you have read cannot be changed by others until your transaction ends. - The same query returns the same result throughout the transaction: no non-repeatable or phantom reads. **Example: a stable snapshot** | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | | `SELECT COUNT(*) FROM product WHERE units_in_stock < 5;` | 217 | | 2 | `UPDATE product SET units_in_stock = 3, unit_price = 34.00 WHERE id = 1618;` then `COMMIT;` | | Session 1 can change rows Session 2 has read. | | 3 | | `SELECT COUNT(*) FROM product WHERE units_in_stock < 5;` | Still 217. | | 4 | | `SELECT unit_price FROM product WHERE id = 1618;` | Still 29.00. | | 5 | | `UPDATE product SET units_in_stock = units_in_stock + 1 WHERE id = 1618;` | Fails: `Serializable conflict due to concurrent updates`, because the row changed after Session 2's snapshot. | | 6 | | `ROLLBACK;` then the same **SELECT**s | 218 and 34.00: a new transaction sees the committed data. | | 7 | `UPDATE product SET units_in_stock = 22, unit_price = 29.00 WHERE id = 1618;` then `COMMIT;` | | Data restored. | **Write skew.** Snapshot isolation does not make concurrent transactions serializable. Suppose the shop requires that products 1620 and 1628 (4 units each) together never run out of stock, and each session checks the rule before removing one product from sale: | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `SELECT SUM(units_in_stock) FROM product WHERE id IN (1620, 1628);` | `SELECT SUM(units_in_stock) FROM product WHERE id IN (1620, 1628);` | 8 in both sessions: the rule allows one product to go to 0. | | 2 | `UPDATE product SET units_in_stock = 0 WHERE id = 1620;` then `COMMIT;` | `UPDATE product SET units_in_stock = 0 WHERE id = 1628;` then `COMMIT;` | Both succeed: they changed different rows. | | 3 | `SELECT SUM(units_in_stock) FROM product WHERE id IN (1620, 1628);` | | 0: the rule is broken, although each transaction respected it. | Run serially, the second transaction would have seen 4 and kept its product. To prevent write skew, make the transactions conflict on a common row, for example by updating a shared row that both read, or enforce the rule in a single statement. Restore the data with `UPDATE product SET units_in_stock = 4 WHERE id IN (1620, 1628); COMMIT;`. ## SERIALIZABLE isolation level **SERIALIZABLE** (6) is accepted for compatibility but currently behaves exactly like **REPEATABLE READ**: it prevents non-repeatable and phantom reads through snapshot isolation, but not write skew. Applications that need full serializability must avoid write skew themselves, as described above. --- # Locking: lock modes, deadlocks and lock timeout Source: https://www.coradb.ai/manual/sql/transaction_locking.html ## Lock protocol CoraDB combines [MVCC](https://www.coradb.ai/manual/sql/transaction_mvcc.html) with locking: - **Reading rows takes no row locks.** A query reads the version of each row that its snapshot can see. It only takes an *intent shared* lock on the table, which prevents the table's schema from changing while it is read. - **Changing a row takes an exclusive row lock**, held until the transaction ends. A second transaction that wants to change the same row waits until the first one commits or rolls back. - **DDL takes schema locks** on the table. When a requested lock conflicts with a lock held by another transaction, the requester waits. It continues when the holder releases the lock, which happens at **COMMIT** or **ROLLBACK**, or gives up when its [lock timeout](https://www.coradb.ai/manual/sql/transaction_locking.html#transaction-lock-timeout) expires. Locks are taken and released automatically; you cannot request them explicitly. To see the locks held and awaited in a running database, use [coradb lockdb](https://www.coradb.ai/manual/admin/admin_transactions.html#lockdb). ## Granularity locking Lockable objects form a hierarchy: rows belong to tables, and tables to the database. A lock on a row is announced on its table with an *intent* lock: an exclusive row lock puts an intent exclusive (IX) lock on the table. This way a transaction that wants to lock a whole table, for example to change its schema, sees immediately that rows of the table are in use. **Lock escalation.** To limit the number of locks, a transaction that holds more row locks on a table than the system parameter [lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#lock_escalation) (default 100,000) starts locking the table as a whole instead. Escalation happens only if no other transaction holds a lock on the table that would conflict, to avoid deadlocks caused by lock conversion. With [rollback_on_lock_escalation](https://www.coradb.ai/manual/admin/config_logging.html#rollback_on_lock_escalation) = `yes`, the transaction is rolled back instead of escalating. ## Lock mode types and compatibility | Lock | Name | Set on | Taken when | |---|---|---|---| | **S** | Shared | Row | Rarely with MVCC; used internally to protect rows or keys from being changed. | | **X** | Exclusive | Row | Before a row is inserted, updated or deleted. Held until the transaction ends. | | **IS** | Intent shared | Table | When rows of the table are read. Blocks schema changes and whole-table updates. | | **IX** | Intent exclusive | Table | When rows of the table are changed. Blocks schema changes and whole-table reads or updates; other transactions can still change other rows. | | **SIX** | Shared with intent exclusive | Table | When the whole table is protected against changes by others while some of its rows are changed, for example while an index is being loaded. Others can still read rows. | | **SCH-S** | Schema stability | Table | While a query is compiled: the schema it uses cannot change. | | **SCH-M** | Schema modification | Table | While DDL (**CREATE**, **ALTER**, **DROP**) changes the table. Blocks all other access to it. | | **BU** | Bulk update | Table | While [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb) loads rows. Several loaddb processes can load the same table; other **SELECT**, DML and DDL statements on it wait. The holder takes no row locks. | **Lock compatibility.** ✓ means the requester gets the lock while the holder keeps its lock; ✗ means the requester waits. NULL means no lock. | Requested \ held | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M | |---|---|---|---|---|---|---|---|---|---| | **NULL** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | **SCH-S** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | | **IS** | ✓ | ✓ | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✗ | | **S** | ✓ | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | | **IX** | ✓ | ✓ | ✓ | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | | **BU** | ✓ | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ | ✗ | ✗ | | **SIX** | ✓ | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **X** | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | | **SCH-M** | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | **Lock conversion.** When a transaction that already holds a lock requests another on the same object, it ends up holding the combination shown here: | Requested \ held | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M | |---|---|---|---|---|---|---|---|---|---| | **NULL** | NULL | SCH-S | IS | S | IX | BU | SIX | X | SCH-M | | **SCH-S** | SCH-S | SCH-S | IS | S | IX | BU | SIX | X | SCH-M | | **IS** | IS | IS | IS | S | IX | X | SIX | X | SCH-M | | **S** | S | S | S | S | SIX | X | SIX | X | SCH-M | | **IX** | IX | IX | IX | SIX | IX | X | SIX | X | SCH-M | | **BU** | BU | BU | BU | X | BU | BU | BU | X | SCH-M | | **SIX** | SIX | SIX | SIX | SIX | SIX | X | SIX | X | SCH-M | | **X** | X | X | X | X | X | X | X | X | SCH-M | | **SCH-M** | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | SCH-M | ### Schema locks during DDL Some DDL statements do not take **SCH-M** at once, which lets other transactions keep working while the statement is compiled and executed. **CREATE INDEX** with a filter, for example, holds **SCH-S** while it checks the filter expression, upgrades to **SIX** while it loads the index (others can read but not change rows), and takes **SCH-M** only to change the schema at the end. The downside is that two such statements on the same table can deadlock: | Step | Transaction 1 | Transaction 2 | |---|---|---| | 1 | `CREATE INDEX i_product_price ON product (unit_price) WHERE unit_price > 0;` takes **SCH-S** to check `unit_price > 0` | | | 2 | | `CREATE INDEX i_product_stock ON product (units_in_stock) WHERE units_in_stock > 0;` takes **SCH-S** to check `units_in_stock > 0` | | 3 | Takes **SIX** and loads the index | | | 4 | | Requests **SIX**, waits for transaction 1 | | 5 | Requests **SCH-M**, waits for transaction 2's **SCH-S**: deadlock | | CoraDB resolves the deadlock by rolling back one of the transactions (see [Transaction deadlock](https://www.coradb.ai/manual/sql/transaction_locking.html#transaction-deadlock)). ### Examples using locks The following examples use two sessions in **REPEATABLE READ** with autocommit off (see [Snapshot examples](https://www.coradb.ai/manual/sql/transaction_mvcc.html#snapshot-examples) for the setup). While a session waits, `coradb lockdb ` shows the locks. **Readers and writers do not block each other, but writers block writers** | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `UPDATE product SET units_in_stock = 20 WHERE id = 1618;` | | Session 1 holds **IX** on `product` and **X** on the row (and on its new version). | | 2 | | `SELECT units_in_stock FROM product WHERE id = 1618;` | 22, immediately: the reader takes only **IS** on the table and reads the committed version. | | 3 | | `UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618;` | Session 2 upgrades to **IX** and waits for the **X** lock on the row. | | 4 | `COMMIT;` | | Session 1's locks are released. | | 5 | | | Session 2 continues, but the row was changed after its snapshot: `ERROR: Serializable conflict due to concurrent updates`. | Had Session 1 rolled back in step 4, Session 2's update would have succeeded. Under **READ COMMITTED**, Session 2 would instead re-read the committed row and apply its update to it; see [READ COMMITTED](https://www.coradb.ai/manual/sql/transaction_isolation.html#read-committed-isolation-level). ## Locking to protect unique constraints With MVCC, a unique index can contain several versions of a key at the same time, each visible to different transactions, until VACUUM removes the old ones. To keep the constraint, every transaction that inserts or changes a key must lock the key's latest version. | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Socks', 'Merino socks', 9.90, 120);` | | Session 1 locks the new row, which protects key 9001. | | 2 | | `INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Gaiters', 'Ankle gaiters', 14.90, 40);` | Session 2 inserts its row, finds key 9001 in the primary key and waits for Session 1's lock on it. | | 3 | `COMMIT;` | | | | 4 | | | Session 2 continues, finds the key committed and fails with a unique constraint violation. | ```text ERROR: Operation would have caused one or more unique constraint violations. INDEX pk_product_id(B+tree: …) ON CLASS product(CLASS_OID: …). key: 9001(OID: …). ``` If Session 1 had rolled back, Session 2's insert would have succeeded. (Remove product 9001 afterwards: `DELETE FROM product WHERE id = 9001; COMMIT;`.) ## Transaction deadlock A deadlock happens when two or more transactions each wait for a lock that another of them holds. CoraDB checks for deadlocks periodically (every [deadlock_detection_interval_in_secs](https://www.coradb.ai/manual/admin/config_logging.html#deadlock_detection_interval_in_secs), default 1 second) and resolves each one by rolling back one of the transactions. The rolled-back transaction receives an error and can be retried. Because reads take no row locks and indexes are not key-locked, deadlocks are rare under MVCC. They still happen when transactions change the same rows in a different order: | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618;` | | Session 1 locks row 1618. | | 2 | | `UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1619;` | Session 2 locks row 1619. | | 3 | `UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1619;` | | Session 1 waits for Session 2. | | 4 | | `UPDATE product SET units_in_stock = units_in_stock - 1 WHERE id = 1618;` | Session 2 waits for Session 1: deadlock. | | 5 | `ERROR: Your transaction (index 1, dba@host\|4760) has been unilaterally aborted by the system.` | | CoraDB rolls back one of the transactions, here Session 1; Session 2 continues. | To avoid deadlocks, change rows in a consistent order (for example by primary key), keep transactions short, and retry a transaction that was rolled back. With [error_log_level](https://www.coradb.ai/manual/admin/config_logging.html#error_log_level) set to `NOTIFICATION`, the server error log records the locks involved in each deadlock. ## Transaction lock timeout The *lock timeout* is how long a transaction waits for a lock. When the time runs out, the statement fails with an error and the transaction is rolled back. If a deadlock occurs among waiting transactions, CoraDB rolls back the one whose wait is closest to its timeout. The default comes from the system parameter [lock_timeout](https://www.coradb.ai/manual/admin/config_logging.html#lock_timeout) (default `-1`, wait indefinitely). A session changes it with **SET TRANSACTION**: ```sql SET TRANSACTION LOCK TIMEOUT timeout_spec; timeout_spec: INFINITE -- wait indefinitely, like lock_timeout = -1 | OFF -- do not wait: fail at once, like lock_timeout = 0 | seconds -- wait at most this many seconds | :host_variable ``` ```sql SET TRANSACTION LOCK TIMEOUT 10; SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, LOCK TIMEOUT 10; -- both in one statement ``` ```text # coradb.conf lock_timeout = 10s ``` **GET TRANSACTION LOCK TIMEOUT** returns the current value in seconds, or stores it in a host variable: ```sql GET TRANSACTION LOCK TIMEOUT [ { INTO | TO } :variable ]; ``` ### Lock timeout errors A transaction that times out receives a message like this: ```text Your transaction (index 2, user1@host1|9808) timed out waiting on IX_LOCK lock on class product. You are waiting for user(s) user1@host1|corasql(9807), user1@host1|corasql(9805) to finish. ``` | Part | Meaning | |---|---| | `index 2` | The transaction index, a number assigned when the client connected. [lockdb](https://www.coradb.ai/manual/admin/admin_transactions.html#lockdb) shows it too. | | `user1@host1\|9808` | The database user, the client host and the process ID of the client. | | `IX_LOCK lock on class product` | The lock that was requested, and on which object. | | `user1@host1\|corasql(9807), …` | The transactions holding the conflicting locks. | To investigate: 1. Run `coradb lockdb ` to see which transactions hold which locks. 2. Look up the statements of those transactions in the SQL log of their broker; see [Broker logs](https://www.coradb.ai/manual/admin/control_broker.html#broker-logs). 3. If a transaction is stuck, end it with [coradb killtran](https://www.coradb.ai/manual/admin/admin_transactions.html#killtran) or the [KILL](https://www.coradb.ai/manual/sql/query/kill.html) statement. --- # Concurrency control: MVCC, snapshots and VACUUM Source: https://www.coradb.ai/manual/sql/transaction_mvcc.html ## Database concurrency When many users read and change the same data at the same time, the database must keep each transaction's view of the data consistent and prevent changes from being applied in the wrong order. How strictly transactions are separated from each other is the *isolation level*: a higher level means less interference, a lower level more concurrency. The SQL standard defines isolation in terms of three read anomalies: | Anomaly | What happens | |---|---| | **Dirty read** | Transaction *T2* reads a change that *T1* has not committed yet. | | **Non-repeatable read** | *T1* reads a row twice and gets different values, because *T2* updated or deleted it and committed in between. | | **Phantom read** | *T1* runs the same query twice and gets additional rows, because *T2* inserted them and committed in between. | CoraDB supports three isolation levels. The number in parentheses can be used instead of the name: | CoraDB isolation level | Dirty read | Non-repeatable read | Phantom read | Schema change of a table being read | |---|---|---|---|---| | [READ COMMITTED](https://www.coradb.ai/manual/sql/transaction_isolation.html#read-committed-isolation-level) (4), default | no | Possible | Possible | no | | [REPEATABLE READ](https://www.coradb.ai/manual/sql/transaction_isolation.html#repeatable-read-isolation-level) (5) | no | no | no | no | | [SERIALIZABLE](https://www.coradb.ai/manual/sql/transaction_isolation.html#serializable-isolation-level) (6) | no | no | no | no | Thanks to snapshot isolation, **REPEATABLE READ** also prevents phantom reads, but it allows *write skew*, so it is not fully serializable; **SERIALIZABLE** currently behaves like **REPEATABLE READ**. Set the level with [SET TRANSACTION ISOLATION LEVEL](https://www.coradb.ai/manual/sql/transaction_isolation.html#set-transaction-isolation-level) or the system parameter [isolation_level](https://www.coradb.ai/manual/admin/config_logging.html#isolation_level). ## Multiversion concurrency control CoraDB uses *multiversion concurrency control* (MVCC). Instead of overwriting a row in place, an update creates a new *version* of the row and keeps the old one for as long as some transaction may still need it. As a result: - Readers never wait for writers, and writers never wait for readers. A query reads the version that is valid for it, without locking rows. - Writers still take an exclusive lock on each row they change, so two transactions cannot modify the same row at the same time. See [Locking](https://www.coradb.ai/manual/sql/transaction_locking.html). - Each transaction (or, under **READ COMMITTED**, each statement) works on a consistent *snapshot* of the database. This is *snapshot isolation*. Old versions that no transaction can see any more are removed later by [VACUUM](https://www.coradb.ai/manual/sql/transaction_mvcc.html#vacuum). ## Versioning, visibility and snapshot **Row versions.** Every transaction that writes gets a unique, increasing identifier, its *MVCCID*. Each row version records the MVCCID of the transaction that inserted it and, once deleted, of the transaction that deleted it: - **Insert.** *T1* inserts a row; the version carries *insert MVCCID = T1*. Until *T1* commits, other transactions see that the inserter is still active and ignore the row. - **Delete.** *T2* deletes the row: it locks it exclusively and adds *delete MVCCID = T2*, but leaves the version in place so that others can still read it. - **Update.** *T2* updates the row: the heap now holds the new version (*insert MVCCID = T2*) with a link to the previous version, which is kept in the log. Older versions form a chain through the log. **Visibility.** Whether a transaction can see a version depends only on the state of its inserter and deleter *when the snapshot was taken*. Changes committed after that moment, and versions created after it, are ignored. All visible versions together form the transaction's snapshot, which therefore does not change while it is in use. A snapshot is defined by the lowest MVCCID still active and the highest committed MVCCID, plus the list of MVCCIDs that were active in between. Anything below the lower bound is committed and visible; anything above the upper bound started later and is invisible. To read a row, CoraDB checks the newest version first and walks back through older versions in the log until it finds one that is visible: | Insert MVCCID | Delete MVCCID | Result | |---|---|---| | Not visible to the snapshot | — | Version too new. Check the previous version, or ignore the row if there is none. | | Visible (committed before the snapshot) | None, or not visible | This version is read. | | Visible | Visible | The row was deleted before the snapshot; it is ignored. | ### Snapshot examples The examples use two or three sessions in **REPEATABLE READ**, which keeps one snapshot for the whole transaction (under **READ COMMITTED** each statement takes a new snapshot). In every session run first: ```sql -- corasql: ;autocommit off SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; ``` Steps are executed in order, top to bottom. Product 1618 (*Gobi HeatTec Tee*) costs 29.00. **Example 1: inserting a row** | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `INSERT INTO product (id, name, description, unit_price, units_in_stock) VALUES (9001, 'Trail Socks', 'Merino socks', 9.90, 120);` | | | | 2 | `SELECT name FROM product WHERE id = 9001;` | | Trail Socks: a transaction sees its own changes. | | 3 | | `SELECT name FROM product WHERE id = 9001;` | No rows: the insert is not committed. | | 4 | `COMMIT;` | | | | 5 | | `SELECT name FROM product WHERE id = 9001;` | Still no rows: Session 2's snapshot is older than the commit. | | 6 | | `COMMIT;` then `SELECT name FROM product WHERE id = 9001;` | Trail Socks: the new transaction has a new snapshot. | **Example 2: Deleting a row** (continues Example 1) | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `DELETE FROM product WHERE id = 9001;` | | | | 2 | `SELECT name FROM product WHERE id = 9001;` | | No rows. | | 3 | | `SELECT name FROM product WHERE id = 9001;` | Trail Socks: the delete is not committed. | | 4 | `COMMIT;` | | | | 5 | | `SELECT name FROM product WHERE id = 9001;` | Still Trail Socks: the old snapshot still sees the row. | | 6 | | `COMMIT;` then `SELECT name FROM product WHERE id = 9001;` | No rows. | **Example 3: updating a row** | Step | Session 1 | Session 2 | Result | |---|---|---|---| | 1 | `UPDATE product SET unit_price = 34.00 WHERE id = 1618;` | | | | 2 | `SELECT unit_price FROM product WHERE id = 1618;` | | 34.00: the new version. | | 3 | | `SELECT unit_price FROM product WHERE id = 1618;` | 29.00: the last committed version. | | 4 | `COMMIT;` | | | | 5 | | `SELECT unit_price FROM product WHERE id = 1618;` | Still 29.00. | | 6 | | `COMMIT;` then `SELECT unit_price FROM product WHERE id = 1618;` | 34.00. | **Example 4: different transactions see different versions** Three sessions; product 1618 costs 29.00 again at the start. | Step | Session 1 | Session 2 | Session 3 | Result | |---|---|---|---|---| | 1 | | `SELECT unit_price FROM product WHERE id = 1618;` | | 29.00; Session 2's snapshot is taken. | | 2 | `UPDATE product SET unit_price = 34.00 WHERE id = 1618;` then `COMMIT;` | | | | | 3 | | | `SELECT unit_price FROM product WHERE id = 1618;` | 34.00; Session 3's snapshot is taken after the commit. | | 4 | `UPDATE product SET unit_price = 39.00 WHERE id = 1618;` | | | Session 1 sees 39.00 (uncommitted). | | 5 | | `SELECT unit_price FROM product WHERE id = 1618;` | | 29.00 | | 6 | | | `SELECT unit_price FROM product WHERE id = 1618;` | 34.00 | Three versions of the same row are visible at the same time, one to each transaction. To restore the sample data afterwards, roll back Session 1 and set the price back: `UPDATE product SET unit_price = 29.00 WHERE id = 1618; COMMIT;`. ## VACUUM Because updates and deletes keep old versions, the database would grow without limit if nothing removed them. Each version goes through these stages: 1. Inserted, not committed: visible only to its inserter. 2. Committed: invisible to transactions that started before, visible to later ones. 3. Deleted, not committed: still visible to other transactions, invisible to the deleter. 4. Delete committed: still visible to transactions that started before, invisible to later ones. 5. Invisible to all active transactions. 6. Removed from the database. **VACUUM** moves versions from stage 5 to stage 6 and makes their space reusable. It runs automatically in the background of the database server. It is designed to be: - **Correct and complete:** it never removes a version that some transaction can still see, and it misses no obsolete version. - **Discreet:** it interferes as little as possible with running transactions. It does not use locks. - **Fast:** it must keep up with the workload, otherwise the database grows and performance degrades. ### How VACUUM works VACUUM does not scan the database. It reads the recovery log, which already records the address of every heap and index change together with its MVCCID. Each transaction knows the oldest MVCCID it still considers active; the smallest of these over all transactions is the *vacuum horizon*. Everything logged by MVCCIDs below the horizon is invisible to everyone and can be cleaned. - **Parallel execution.** The log is divided into fixed-size blocks. When all operations in a block are below the horizon, the *vacuum master* creates a job for it, and *vacuum workers* execute the jobs in parallel. - **Vacuum data.** Information about pending log blocks is kept in the persistent *vacuum data* file, so no work is lost if the server stops. After a crash a job may run twice, which is harmless; a job is never skipped. - **Jobs.** A worker prefetches the log pages of its block, cleans index entries immediately, collects the heap rows (OIDs) to clean, then cleans them and marks the job complete. - **Dropped tables and indexes.** Because VACUUM uses no locks, a dropped file is destroyed only after the dropping transaction commits and VACUUM has been notified. Log entries that belong to a dropped file are skipped from then on. Long-running transactions hold back the vacuum horizon: versions they might still see cannot be removed. Commit or roll back transactions promptly, especially in applications that keep connections open. ### VACUUM statement and vacuumdb You normally do not need to run VACUUM yourself. A manual vacuum is only available in stand-alone mode, that is with the database server stopped: ```bash coradb server stop mydb coradb vacuumdb -S mydb ``` In stand-alone corasql (`corasql -S`), the statement `VACUUM;` does the same (see [vacuumdb](https://www.coradb.ai/manual/admin/admin_space.html#vacuumdb)). In client-server mode both are rejected: ```sql VACUUM; ``` ```text ERROR: Manual vacuum is disabled for client-server mode. ``` The background vacuum is tuned with the system parameters described in [Other parameters](https://www.coradb.ai/manual/admin/config_other.html#vacuum_prefetch_log_mode). The size of the log buffer also matters, because MVCC and VACUUM read old versions from the log; see [log_buffer_size](https://www.coradb.ai/manual/admin/config_logging.html#log_buffer_size). --- # Triggers: CREATE, ALTER, DROP and RENAME TRIGGER Source: https://www.coradb.ai/manual/sql/trigger.html A *trigger* is a database object that performs an action automatically when a given event happens: a row of a table is inserted, updated or deleted, or a transaction commits or rolls back. Triggers can enforce rules, reject invalid changes and keep audit logs. Triggers can be defined on ordinary tables. Vertex and edge tables of a graph do not support triggers (`Graph class error. TRIGGER is not allowed with graph class.`); in the e-commerce sample database the examples therefore use the relational tables `orders` and `order_items`. ## CREATE TRIGGER ```sql CREATE TRIGGER trigger_name [ STATUS { ACTIVE | INACTIVE } ] [ PRIORITY key ] event_time event_type [ event_target ] [ IF condition ] EXECUTE [ AFTER | DEFERRED ] action [ COMMENT 'comment' ]; event_time ::= BEFORE | AFTER | DEFERRED event_type ::= INSERT | UPDATE | DELETE | STATEMENT INSERT | STATEMENT UPDATE | STATEMENT DELETE | COMMIT | ROLLBACK event_target ::= ON table_name [ ( column_name ) ] action ::= REJECT | INVALIDATE TRANSACTION | PRINT 'message' | INSERT statement | UPDATE statement | DELETE statement ``` | Part | Meaning | |---|---| | **STATUS** | `ACTIVE` (default) or `INACTIVE`; an inactive trigger does not run. | | **PRIORITY** | A non-negative number, default 0; when several triggers fire for the same event, those with higher priority run first. Give triggers on the same event distinct priorities so that their order is defined. | | *event_time* | When the condition and action run; see [Event time](https://www.coradb.ai/manual/sql/trigger.html#event-time). | | *event_type*, *event_target* | Which event fires the trigger; see [Trigger event type](https://www.coradb.ai/manual/sql/trigger.html#trigger-event-type). | | **IF** *condition* | The action runs only if the condition is true; see [Trigger condition](https://www.coradb.ai/manual/sql/trigger.html#trigger-condition). | | **EXECUTE** … *action* | What to do; see [Trigger action](https://www.coradb.ai/manual/sql/trigger.html#trigger-action). | | **COMMENT** | A description of the trigger. | The following trigger rejects order lines with a quantity of zero or less: ```sql CREATE TRIGGER trg_qty_check BEFORE UPDATE ON order_items IF new.quantity <= 0 EXECUTE REJECT; UPDATE order_items SET quantity = 0 WHERE order_id = 2; ``` ```text ERROR: The operation has been rejected by trigger "trg_qty_check". ``` ### Guidelines for trigger definition Triggers are powerful but run implicitly, so design them carefully: - **Side effects.** Conditions and actions should do only what is expected; avoid calling methods with side effects in conditions. - **Changing the target table.** An action that changes the table the trigger is defined on can fire the same trigger again and loop. Make sure the recursion ends, and limit it with [SET TRIGGER MAXIMUM DEPTH](https://www.coradb.ai/manual/sql/trigger.html#limiting-nested-trigger). - **Recursion between triggers.** If trigger A fires trigger B, which fires A again, the transaction can loop until the depth limit stops it. - **Overhead.** If the logic can be expressed more efficiently in the application or in a constraint, do so. - **Uniqueness.** Do not define two triggers for the same event that contradict each other, and set **PRIORITY** where the order matters. ### Event time | Event time | Condition and action run | |---|---| | **BEFORE** | Before the event is processed | | **AFTER** | After the event is processed | | **DEFERRED** | At the end of the transaction (cannot be used with **COMMIT** or **ROLLBACK** events) | The action can also be delayed separately: `EXECUTE AFTER action` or `EXECUTE DEFERRED action` evaluates the condition at the event time but runs the action later. ### Trigger type - A **table trigger** has a table as its event target and fires on instance or statement events. It is visible to all users who have **SELECT** permission on the table. - A **user trigger** has no target and fires on **COMMIT** or **ROLLBACK**. It belongs to the user who created it and fires only for that user's transactions. ### Trigger event type - **Instance events** fire once for every row affected: **INSERT**, **UPDATE**, **DELETE**. - **Statement events** fire once per statement, however many rows it affects: **STATEMENT INSERT**, **STATEMENT UPDATE**, **STATEMENT DELETE**. - **COMMIT** and **ROLLBACK** fire when the transaction ends; they have no target. Instance and statement events need an event target; **COMMIT** and **ROLLBACK** cannot have one. ### Trigger event target The target is a table, optionally with one column. With a column, an **UPDATE** trigger fires only when that column is updated. The following trigger keeps a log of quantity changes, one row for each changed order line: ```sql CREATE TABLE qty_log (order_id INT, product_id INT, old_qty SHORT, new_qty SHORT, changed_at DATETIME); CREATE TRIGGER trg_order_items_qty_log AFTER UPDATE ON order_items(quantity) EXECUTE INSERT INTO qty_log VALUES (obj.order_id, obj.product_id, old.quantity, obj.quantity, SYS_DATETIME) COMMENT 'audit quantity changes'; UPDATE order_items SET quantity = quantity + 1 WHERE order_id = 1; SELECT order_id, product_id, old_qty, new_qty FROM qty_log; ``` | order_id | product_id | old_qty | new_qty | |---|---|---|---| | 1 | 1137 | 2 | 3 | A statement trigger fires once, before the first row is changed: ```sql CREATE TRIGGER trg_orders_stmt BEFORE STATEMENT UPDATE ON orders(shipped_date) EXECUTE PRINT 'orders are being shipped'; ``` ### Combination of event type and target | Event type | Target | Fires when | |---|---|---| | **INSERT**, **STATEMENT INSERT** | Table | Rows are inserted into the table | | **UPDATE**, **STATEMENT UPDATE** | Table or column | Rows (or the column) of the table are updated | | **DELETE**, **STATEMENT DELETE** | Table | Rows are deleted from the table | | **COMMIT** | none | The transaction commits | | **ROLLBACK** | none | The transaction rolls back | ### Trigger condition The condition is an expression that is true or false, using the operators allowed in a **WHERE** clause. It can refer to the affected row through [correlation names](https://www.coradb.ai/manual/sql/trigger.html#correlation-name) and can contain subqueries. Without a condition, the action always runs. ```sql -- reject unusually large order lines CREATE TRIGGER trg_big_order BEFORE INSERT ON order_items IF new.quantity > 50 EXECUTE REJECT; -- check a rule across the whole table when the transaction commits CREATE TRIGGER trg_commit_check BEFORE COMMIT IF 0 < (SELECT COUNT(*) FROM orders WHERE shipped_date < order_date) EXECUTE REJECT; ``` ### Correlation name In instance triggers on **INSERT**, **UPDATE** and **DELETE**, the condition and action can refer to the affected row through *correlation names*: | Name | Refers to | |---|---| | **obj** | The row as it is now: before an update or delete, or after an insert or update | | **new** | The values proposed by an insert or update, before they are applied | | **old** | The values before an update, while the trigger runs | Which names are available depends on the event and the event time: | Event | BEFORE | AFTER or DEFERRED | |---|---|---| | **INSERT** | new | obj | | **UPDATE** | obj, new | obj, and old (AFTER only) | | **DELETE** | obj | — | Using a name that is not available is an error, for example **old** in a **DEFERRED UPDATE** trigger: ```sql CREATE TRIGGER foo_trigger DEFERRED UPDATE ON order_items IF old.quantity = 100 EXECUTE PRINT 'foo_trigger'; ``` ```text ERROR: Error compiling condition for "foo_trigger": Attribute "old" was not found. ``` ### Trigger action | Action | Effect | |---|---| | **REJECT** | Cancels the operation that fired the trigger. Only with **BEFORE**, because afterwards the change has been made. | | **INVALIDATE TRANSACTION** | Lets the operation complete but prevents the transaction from committing; it must be rolled back. Used with **DEFERRED** triggers to check a transaction as a whole. | | **PRINT** '*message*' | Prints a message to the client console (for development and testing); the operation is not affected. | | **INSERT**, **UPDATE**, **DELETE** | Runs the statement, which can use the correlation names. | ```sql -- the transaction cannot commit if it set an implausible shipping cost CREATE TRIGGER trg_shipping_check DEFERRED UPDATE ON orders IF obj.shipping_cost > 1000 EXECUTE INVALIDATE TRANSACTION; ``` > **Warning:** > - An **INSERT** action in a trigger on an **INSERT** event of the same table fires the trigger again and can loop. > - **UPDATE** triggers on partitioned tables must not change the partitioning key in a way that breaks the partitioning; CoraDB raises an error for such updates. ### Trigger's COMMENT A comment is given with **COMMENT** in **CREATE TRIGGER** or **ALTER TRIGGER**. Comments are shown in the catalog views [db_trigger](https://www.coradb.ai/manual/sql/catalog_classes.html#db_trigger) and [db_trig](https://www.coradb.ai/manual/sql/catalog_views.html#db_trig): ```sql SELECT trigger_name, target_class_name, target_attr_name, target_attr_type, comment FROM db_trig WHERE trigger_name LIKE 'trg_order%'; ``` | trigger_name | target_class_name | target_attr_name | target_attr_type | comment | |---|---|---|---|---| | trg_order_items_qty_log | order_items | quantity | INSTANCE | Audit quantity changes | In corasql, `;schema order_items` also lists the triggers of the table. ## ALTER TRIGGER **ALTER TRIGGER** changes the status, priority or comment of a trigger. To change its event, condition or action, drop and re-create it. ```sql ALTER TRIGGER trigger_name { STATUS { ACTIVE | INACTIVE } | PRIORITY key } [ COMMENT 'comment' ]; ALTER TRIGGER trigger_name COMMENT 'comment'; ``` ```sql ALTER TRIGGER trg_qty_check STATUS INACTIVE; ALTER TRIGGER trg_qty_check PRIORITY 0.7; ALTER TRIGGER trg_order_items_qty_log COMMENT 'audit order line quantity changes'; ``` - Only one of **STATUS** and **PRIORITY** can be changed per statement. - A table trigger can be changed by its owner or by a user with **ALTER** permission on the table; a user trigger only by its owner. ## DROP TRIGGER ```sql DROP TRIGGER trigger_name; ``` One trigger is dropped per statement. A table trigger can be dropped by a user with **ALTER** permission on the table; a user trigger (**COMMIT** or **ROLLBACK**) is visible to and can be dropped by its owner only. ## RENAME TRIGGER ```sql RENAME TRIGGER old_name AS new_name; ``` ```sql RENAME TRIGGER trg_qty_check AS trg_order_items_qty_check; ``` Trigger names must be unique among triggers; a trigger can have the same name as a table. The rules for renaming are the same as for **ALTER TRIGGER**. ## Deferred condition and action A trigger with **DEFERRED** as event time, or with `EXECUTE DEFERRED`, runs at the end of the transaction. Pending deferred triggers can be run earlier or cancelled: ```sql EXECUTE DEFERRED TRIGGER { trigger_name | ALL TRIGGERS }; -- run now DROP DEFERRED TRIGGER { trigger_name | ALL TRIGGERS }; -- cancel ``` ### Granting trigger authorization Permissions on triggers are not granted directly. A table trigger is available to every user who has permission on its table. Defining a table trigger requires **ALTER** permission on the table; a user trigger can be defined by any user. ## Trigger on REPLACE and INSERT ... ON DUPLICATE KEY UPDATE **REPLACE** and **INSERT … ON DUPLICATE KEY UPDATE** perform inserts, updates and deletes internally, and fire the corresponding triggers: | Statement and situation | Triggers fired, in order | |---|---| | **INSERT … ON DUPLICATE KEY UPDATE**, key exists | BEFORE UPDATE, AFTER UPDATE | | **REPLACE**, key exists (row is deleted and inserted again) | BEFORE DELETE, AFTER DELETE, BEFORE INSERT, AFTER INSERT | | Either statement, key does not exist | BEFORE INSERT, AFTER INSERT | With a trigger for each of these six events on a table `coupon (code VARCHAR(16) UNIQUE, uses INT)` that contains `'SPRING'`, each trigger writing its name to a log table: ```sql INSERT INTO coupon VALUES ('SPRING', 0) ON DUPLICATE KEY UPDATE uses = uses + 1; -- before update, after update REPLACE INTO coupon VALUES ('SPRING', 5); -- before delete, after delete, before insert, after insert REPLACE INTO coupon VALUES ('SUMMER', 0); -- before insert, after insert ``` ## Trigger debugging Check that a new trigger works as intended. A trigger that makes statements much slower may be doing too much work or looping. The following trigger is deliberately recursive: it counts `n` down by updating its own row: ```sql CREATE TABLE countdown (id INT PRIMARY KEY, n INT); INSERT INTO countdown VALUES (1, 0); CREATE TRIGGER loop_tgr BEFORE UPDATE ON countdown(n) IF new.n > 0 EXECUTE UPDATE countdown SET n = new.n - 1 WHERE id = obj.id; ``` ### Viewing trigger execution log **SET TRIGGER TRACE** prints a line on the client console each time a trigger condition is evaluated or an action runs, until it is turned off or the session ends: ```sql SET TRIGGER TRACE { ON | OFF }; ``` ### Limiting nested trigger **SET TRIGGER MAXIMUM DEPTH** limits how deeply triggers can fire other triggers (or themselves). When the limit is reached, the statement fails and the transaction must be rolled back. ```sql SET TRIGGER [ MAXIMUM ] DEPTH count; ``` The default and highest allowed depth is 32 (`SET TRIGGER DEPTH 33` fails with `Maximum trigger depth cannot exceed 32.`). Both settings apply to the current session. **GET TRIGGER** reads the current settings, optionally into a session variable: ```sql GET TRIGGER TRACE [ INTO :variable ]; -- 1 if trace is on, 0 if off GET TRIGGER [ MAXIMUM ] DEPTH [ INTO :variable ]; -- current depth limit ``` Setting `n` to 15 would fire `loop_tgr` 16 times, more than a depth of 10 allows: ```sql SET TRIGGER MAXIMUM DEPTH 10; UPDATE countdown SET n = 15 WHERE id = 1; ``` ```text ERROR: Error evaluating action for "loop_tgr", Maximum trigger depth 10 exceeded at trigger "loop_tgr". ``` --- # Query optimization: statistics Source: https://www.coradb.ai/manual/sql/tuning.html The CoraDB query optimizer chooses how to run a query (which indexes to use, the join order and join methods) from estimates of how many rows each step produces. These estimates come from the *statistics* of tables and indexes: number of rows and pages, and the number of distinct keys of each index. | Topic | Page | |---|---| | Keeping statistics up to date, checking them | This page | | Reading query plans, profiling execution with SET TRACE | [Query plans and profiling](https://www.coradb.ai/manual/sql/tuning_plan.html) | | Steering the optimizer with SQL hints and index hints | [SQL and index hints](https://www.coradb.ai/manual/sql/tuning_hints.html) | | Filtered, function-based and shared indexes | [Special indexes](https://www.coradb.ai/manual/sql/tuning_special_index.html) | | Covering indexes, ORDER BY / GROUP BY without sorting, key ranges, skip and loose scans | [Index optimizations](https://www.coradb.ai/manual/sql/tuning_index_opt.html) | ## Updating statistics Statistics are updated automatically by DDL such as **CREATE TABLE**, **CREATE INDEX** and **DROP INDEX**, but not by **INSERT**, **UPDATE** or **DELETE**. After loading or deleting a large share of a table's rows, update its statistics so that the optimizer works with realistic numbers: ```sql UPDATE STATISTICS ON table_name [, table_name ...] [WITH FULLSCAN]; UPDATE STATISTICS ON ALL CLASSES [WITH FULLSCAN]; UPDATE STATISTICS ON CATALOG CLASSES [WITH FULLSCAN]; ``` - Without **WITH FULLSCAN**, the statistics are estimated from a sample of the data, which is enough in most cases. **WITH FULLSCAN** reads all data and costs correspondingly more; use it sparingly on large tables. - **ALL CLASSES** updates every table of the database; **CATALOG CLASSES** updates the system catalog tables. ```sql UPDATE STATISTICS ON product, orders; UPDATE STATISTICS ON product WITH FULLSCAN; UPDATE STATISTICS ON ALL CLASSES; ``` Each update writes a pair of `NOTIFICATION` messages to the server error log, which shows when it started and finished: ```text ... NOTIFICATION ... CODE = -1114 ... Started to update statistics (class "product", oid : 0|204|64). ... NOTIFICATION ... CODE = -1115 ... Finished to update statistics (class "product", oid : 0|204|64, error code : 0). ``` ## Checking statistics information ### GET STATISTICS **GET STATISTICS** returns one statistics value of a table: ```sql GET STATISTICS 'item' OF table_name [ { INTO | TO } :variable ]; ``` | Item | Value | |---|---| | `'#objects'` | Number of rows | | `'#pages'` | Number of heap pages | | `'#attributes'` | Number of columns | | `'#keys(column:n)'` | Number of distinct keys of the *n*-th index on *column* (estimated unless the statistics were updated **WITH FULLSCAN**) | ```sql GET STATISTICS '#objects' OF product; -- 2115 GET STATISTICS '#attributes' OF product; -- 5 GET STATISTICS '#keys(id:1)' OF product; -- about 2,000 (sampled) ``` The values reflect the last statistics update, not necessarily the current contents of the table. ### SHOW INDEX [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) lists the indexes of a table with their estimated cardinality (number of distinct keys): ```sql SHOW INDEX FROM product; ``` | Table | Non_unique | Key_name | Column_name | Cardinality | |---|---|---|---|---| | product | 1 | idx_product_name | name | 262 | | product | 0 | pk_product_id | id | 2115 | (Selected columns.) Product names repeat in the sample data, so the name index has far fewer distinct keys than the table has rows. ### ;info stats in corasql The corasql session command `;info stats` prints all statistics of a table: rows, pages, and for each column its type, minimum and maximum and its B+tree statistics. ```text corasql> ;info stats product CLASS STATISTICS **************** Class name: product Timestamp: ... Total pages in class heap: 13 Total objects: 2115 Number of attributes: 5 Attribute: id id: 0 Type: DB_TYPE_INTEGER ... B+tree statistics: BTID: { ... } Cardinality: ... , Total pages: ... , Leaf pages: ... , Height: ... ... ``` ### Checking graph statistics For graph queries, the optimizer also uses statistics on vertex and edge tables and on how they are connected. The corasql session command `;info graph_stats` shows them. Vertex and edge table names are case-sensitive. ```text ;info graph_stats [arguments] ``` | Subcommand | Shows | |---|---| | `vertex_label_elements ` | Number of vertices with this label | | `edge_label_elements ` | Number of edges with this label | | `relationships_between_specified_label ` | Edges of all types from *vertex1* to *vertex2* | | `relationships_between_specified_label ` | Edges of one type from *vertex1* to *vertex2* | | `relationships_from_specified_label ` | Outgoing edges of one type from a vertex label | | `relationships_to_specified_label ` | Incoming edges of one type to a vertex label | Examples on the e-commerce graph: ```text ;info graph_stats vertex_label_elements product ;info graph_stats edge_label_elements likes ;info graph_stats relationships_between_specified_label customer product ;info graph_stats relationships_between_specified_label customer likes product ;info graph_stats relationships_from_specified_label customer follows ;info graph_stats relationships_to_specified_label manufactures product ``` Use them to see the size and shape of the graph: which labels are the largest, how many edges a typical vertex has, and therefore which direction of a traversal is cheaper. Graph statistics reflect the current state of the database and may be cached and refreshed periodically, depending on the configuration. --- # SQL hints, index hints and query cache Source: https://www.coradb.ai/manual/sql/tuning_hints.html ## Using SQL hint The optimizer normally finds a good plan on its own. When it does not, for example because the [statistics](https://www.coradb.ai/manual/sql/tuning.html) cannot capture a correlation in your data, *hints* tell it which join order, join method or index to prefer. Check the effect of a hint with the [query plan](https://www.coradb.ai/manual/sql/tuning_plan.html). A hint is a comment that starts with a plus sign, placed directly after the first keyword of a **SELECT**, **UPDATE**, **DELETE** or **MERGE** statement. All three [comment styles](https://www.coradb.ai/manual/sql/comment.html) work: `/*+ hint */`, `--+ hint` and `//+ hint`. Several hints are separated by spaces. ```sql { SELECT | UPDATE | DELETE } /*+ hint [ hint ... ] */ ... MERGE /*+ merge_hint [ merge_hint ... ] */ INTO ... hint ::= ORDERED | USE_NL [ ( table [, table ...] ) ] | USE_IDX [ ( table [, table ...] ) ] | USE_MERGE [ ( table [, table ...] ) ] | USE_DESC_IDX | NO_DESC_IDX | INDEX_SS [ ( table [, table ...] ) ] | NO_INDEX_SS | INDEX_LS | NO_INDEX_LS | NO_COVERING_IDX | NO_MULTI_RANGE_OPT | NO_SORT_LIMIT | NO_HASH_AGGREGATE | NO_HASH_LIST_SCAN | NO_LOGGING | RECOMPILE | QUERY_CACHE | QUERY_NO_CACHE merge_hint ::= USE_UPDATE_IDX ( index [, index ...] ) | USE_INSERT_IDX ( index [, index ...] ) | RECOMPILE ``` Unknown hints are ignored without error, so check the plan when a hint seems to have no effect: the *Query stmt* part shows the hints that were recognized. **Join hints** | Hint | Effect | |---|---| | **ORDERED** | Join the tables in the order of the **FROM** clause; the first is the outer table. | | **USE_NL** | Use nested-loop joins. | | **USE_IDX** | Use index joins (nested loops that look up the inner table in an index). | | **USE_MERGE** | Use sort-merge joins. Merge joins are considered only with this hint or with [optimizer_enable_merge_join](https://www.coradb.ai/manual/admin/config_other.html#optimizer_enable_merge_join) = `yes`. | With a table list, **USE_NL**, **USE_IDX** and **USE_MERGE** apply only to joins with those tables: in `SELECT /*+ ORDERED USE_NL(b) USE_MERGE(d) */ … FROM a JOIN b … JOIN c … JOIN d …`, *b* is joined by nested loop and *d* by merge join. **USE_NL** and **USE_MERGE** together without a table list are ignored. A hint cannot always be followed: a **RIGHT OUTER JOIN**, for example, is converted to a left outer join internally, which can change the join order. **Index hints** | Hint | Effect | |---|---| | **USE_DESC_IDX** | Scan indexes in descending order where it helps; see [Index scan in descending order](https://www.coradb.ai/manual/sql/tuning_index_opt.html#index-scan-in-descending-order). | | **NO_DESC_IDX** | Do not scan indexes in descending order. | | **INDEX_SS** / **NO_INDEX_SS** | Consider / do not consider an [index skip scan](https://www.coradb.ai/manual/sql/tuning_index_opt.html#index-skip-scan). | | **INDEX_LS** / **NO_INDEX_LS** | Consider / do not consider a [loose index scan](https://www.coradb.ai/manual/sql/tuning_index_opt.html#loose-index-scan). | | **NO_COVERING_IDX** | Do not use [covering indexes](https://www.coradb.ai/manual/sql/tuning_index_opt.html#covering-index). | | **NO_MULTI_RANGE_OPT** | Do not use the [multiple key ranges optimization](https://www.coradb.ai/manual/sql/tuning_index_opt.html#multiple-key-ranges-optimization). | | **NO_SORT_LIMIT** | Do not use the [SORT-LIMIT optimization](https://www.coradb.ai/manual/sql/tuning_index_opt.html#sort-limit-optimization). | **Other hints** - **NO_HASH_AGGREGATE**: aggregate by sorting instead of with an in-memory hash table. Hash aggregation reduces or avoids sorting; its memory is limited by [max_agg_hash_size](https://www.coradb.ai/manual/admin/config_resources.html#max_agg_hash_size). Use the hint when you know that hashing will not pay off for a query. Hash aggregation is never used for aggregates on **DISTINCT** values (such as `AVG(DISTINCT x)`), **GROUP_CONCAT** and **MEDIAN**, which need sorted input. - **NO_HASH_LIST_SCAN**: scan the result of a subquery as a list instead of building and probing a hash table. Hash list scans speed up equality lookups in subquery results; their memory is limited by [max_hash_list_scan_size](https://www.coradb.ai/manual/admin/config_resources.html#max_hash_list_scan_size). They are used only for `=` conditions and not for OID values. Use the hint when the outer query produces very few rows. - **NO_LOGGING**: do not write redo log records for the heap changes of an **INSERT**, **UPDATE** or **DELETE**. Index changes are still logged, so after a crash the table and its indexes can disagree, and committed changes may not be recoverable. Use it only for data you can reload. - **RECOMPILE**: ignore the cached plan of the statement and compile a new one. Use it when you examine plans, and for statements whose best plan depends strongly on parameter values. - **QUERY_CACHE** (also **SQL_CACHE**): cache the result of a **SELECT**; see [Query cache](https://www.coradb.ai/manual/sql/tuning_hints.html#query-cache). **QUERY_NO_CACHE** (**SQL_NO_CACHE**) turns caching off for the statement. **MERGE hints** - **USE_UPDATE_IDX** (*indexes*): indexes to use for the join and update conditions of the **UPDATE** part of a [MERGE](https://www.coradb.ai/manual/sql/query/merge.html). - **USE_INSERT_IDX** (*indexes*): indexes to use for the join condition of the **INSERT** part. - **RECOMPILE**: as above. ### Example: join order and method To list the orders of one customer, the natural plan reads the customer first and looks up its orders in the foreign key index. **ORDERED** and **USE_NL** make that choice explicit: ```sql SELECT /*+ RECOMPILE USE_NL ORDERED */ c.company_name, o.order_date FROM customer c, orders o WHERE c.company_name = 'Jones LLC' AND c.id = o.customer_id; ``` ```text Query plan: idx-join (inner join) outer: sscan class: c node[0] sargs: term[1] cost: 14 card 1 inner: iscan class: o node[1] index: fk_orders_customer_id term[0] cost: 3 card 2914 cost: 27 card 3 ``` A nested-loop join whose inner table is read through an index is shown as **idx-join**. Join hints can be limited to some tables: `/*+ USE_NL(c, o) */`. ## Index hint Index hints restrict or prioritize the indexes the optimizer may use for a table. There are two equivalent forms: a **USING INDEX** clause at the end of the statement, and **USE**, **FORCE** or **IGNORE INDEX** after a table in the **FROM** clause. The second form is rewritten into the first. ### USING INDEX ```sql SELECT ... WHERE ... [ USING INDEX index_list ] UPDATE ... WHERE ... [ USING INDEX index_list ] DELETE ... WHERE ... [ USING INDEX index_list ] index_list ::= NONE | [ ALL EXCEPT ] index_spec [, index_spec ...] index_spec ::= [table.]index_name [ (+) | (-) ] | table.NONE ``` | Form | Effect | |---|---| | `USING INDEX idx1, idx2` | Only the listed indexes are considered; a sequential scan remains possible if it is cheaper. | | `USING INDEX idx(+)` | *idx* is preferred whenever it can be used. | | `USING INDEX idx(-)` | *idx* is not used. | | `USING INDEX ALL EXCEPT idx` | All indexes except *idx* are considered. | | `USING INDEX NONE` | No index is used: sequential scans on all tables. | | `USING INDEX t.NONE` | No index is used on table *t*. | Tables for which no index is named keep all their indexes. With `USING INDEX tab1.idx1`, the optimizer chooses between *idx1* and a sequential scan for *tab1*, and among all indexes and a sequential scan for every other table. An index scan returns rows in index order, so **USING INDEX** can also be used to obtain an order without **ORDER BY**. Prefer an explicit **ORDER BY**, which the optimizer can still satisfy from the index without sorting (see [Optimizing ORDER BY clause](https://www.coradb.ai/manual/sql/tuning_index_opt.html#optimizing-order-by-clause)). ### USE, FORCE, IGNORE INDEX ```sql FROM table [ { USE | FORCE | IGNORE } INDEX ( index_spec [, index_spec ...] ) ] ... index_spec ::= [table.]index_name ``` | Hint | Same as | Effect | |---|---|---| | **USE INDEX** (*idx*) | `USING INDEX idx` | Consider only *idx* (or a sequential scan) | | **FORCE INDEX** (*idx*) | `USING INDEX idx(+)` | Prefer *idx* | | **IGNORE INDEX** (*idx*) | `USING INDEX idx(-)` | Do not use *idx* | ### Examples of index hint The `orders` table has indexes on `customer_id` (`fk_orders_customer_id`), `order_date` (`idx_orders_order_date`) and others. For the orders of customer 17 since 2024, the optimizer picks the more selective customer index: ```sql SELECT /*+ RECOMPILE */ id, order_date FROM orders WHERE customer_id = 17 AND order_date >= DATE'2024-01-01'; ``` ```text iscan class: orders node[0] index: fk_orders_customer_id term[1] sargs: term[0] cost: 3 card 1 ``` Each of the following makes it use the date index instead, with the customer condition as a data filter: ```sql SELECT /*+ RECOMPILE */ id, order_date FROM orders USE INDEX (idx_orders_order_date) WHERE customer_id = 17 AND order_date >= DATE'2024-01-01'; SELECT /*+ RECOMPILE */ id, order_date FROM orders FORCE INDEX (idx_orders_order_date) WHERE customer_id = 17 AND order_date >= DATE'2024-01-01'; SELECT /*+ RECOMPILE */ id, order_date FROM orders IGNORE INDEX (fk_orders_customer_id) WHERE customer_id = 17 AND order_date >= DATE'2024-01-01'; SELECT /*+ RECOMPILE */ id, order_date FROM orders WHERE customer_id = 17 AND order_date >= DATE'2024-01-01' USING INDEX ALL EXCEPT fk_orders_customer_id; ``` ```text iscan class: orders node[0] index: idx_orders_order_date term[0] sargs: term[1] cost: 5 card 1 ``` The *Query stmt* part of the plan shows the rewriting: `USE INDEX` becomes `using index orders.idx_orders_order_date`, `FORCE INDEX` becomes `… (+)` and `IGNORE INDEX` becomes `… (-)`. `USING INDEX NONE` forces a sequential scan: ```sql SELECT /*+ RECOMPILE */ id, order_date FROM orders WHERE customer_id = 17 AND order_date >= DATE'2024-01-01' USING INDEX NONE; ``` ```text sscan class: orders node[0] sargs: term[0] AND term[1] cost: 30 card 1 ``` In a join, indexes can be chosen per table, for example `USING INDEX o.idx_orders_order_date, c.NONE`. ### KEYLIMIT An index named in **USING INDEX** can carry a **KEYLIMIT** clause, which limits the number of index keys the scan reads: ```sql USING INDEX index_name KEYLIMIT count USING INDEX index_name KEYLIMIT skip, count ``` With *skip*, the scan first skips that many keys. Because the keys are read in index order, this returns the first rows by the index key without a sort, much like **LIMIT** over an **ORDER BY** on the key. **KEYLIMIT** cannot be combined with **USING INDEX NONE** or with an index excluded by `(-)`. The orders from 30 December 2025 onward in `idx_orders_order_date` order: the first three, then three after skipping two: ```sql SELECT id, order_date FROM orders WHERE order_date >= DATE'2025-12-30' USING INDEX idx_orders_order_date KEYLIMIT 3; ``` | id | order_date | |---|---| | 455 | 2025-12-30 | | 933 | 2025-12-30 | | 1325 | 2025-12-30 | ```sql SELECT id, order_date FROM orders WHERE order_date >= DATE'2025-12-30' USING INDEX idx_orders_order_date KEYLIMIT 2, 3; ``` | id | order_date | |---|---| | 1325 | 2025-12-30 | | 1603 | 2025-12-30 | | 2232 | 2025-12-30 | Rows with equal keys are returned in the order of the index entries; add the primary key to the index or use **ORDER BY** … **LIMIT** when that order matters. ## Query cache The **QUERY_CACHE** hint caches a **SELECT** together with its result. When the same query text is executed again with the same bind values in the same database, the result is returned from the cache instead of running the query. This helps queries that are repeated often and are expensive, such as dashboard counts: ```sql SELECT /*+ QUERY_CACHE */ YEAR(order_date) AS y, COUNT(*) FROM orders GROUP BY YEAR(order_date); ``` The first execution runs the query and stores the result; later executions read the stored result and are much faster. The hint has no effect when the query contains: - Current date or time values, such as **SYSDATE** or `ADDDATE(SYSDATE, -1)`; - Serials, column paths, methods, stored procedures or stored functions; - System tables such as `db_root` or `_db_attribute`; - System functions such as **SYS_GUID()**. In corasql, `;info qcache` shows the cache: `n_entries` (cached queries), `n_pages` (pages of cached results), lookup, hit and miss counters, and for each entry its `query_string`, creation and last-use time: ```text corasql> ;info qcache LIST_CACHE { n_hts 1010 n_entries 1 n_pages 1 lookup_counter 2 hit_counter 1 miss_counter 1 full_counter 0 } ... query_string = select /*+ QUERY_CACHE */ ... time_created = ... time_last_used = ... ref_count = 1 ... ``` The number of cached queries is limited by [max_query_cache_entries](https://www.coradb.ai/manual/admin/config_sql.html#max_query_cache_entries) and the size of cached results by [query_cache_size_in_pages](https://www.coradb.ai/manual/admin/config_sql.html#query_cache_size_in_pages). When either limit is reached, about 20% of the entries are removed. --- # Index optimizations: covering index, ORDER BY, GROUP BY and more Source: https://www.coradb.ai/manual/sql/tuning_index_opt.html An index does more than find rows quickly. Because index entries are sorted and contain the key values, the optimizer can also use an index to avoid reading the table, to avoid sorting, and to stop early in **LIMIT** queries. This page describes these optimizations. Plans and traces are shown as described in [Query plans and profiling](https://www.coradb.ai/manual/sql/tuning_plan.html); the examples use the e-commerce indexes `idx_orders_order_date` on `orders(order_date)`, `fk_orders_customer_id` on `orders(customer_id)` and the primary key of `order_items(order_id, product_id)`, plus a few indexes created for the purpose. ## Covering index An index *covers* a query when it contains every column the query uses from that table: in the **SELECT** list and in the **WHERE**, **GROUP BY**, **HAVING** and **ORDER BY** clauses. The query is then answered from the index alone, without reading the table, which saves I/O. ```sql SELECT /*+ RECOMPILE */ order_id, product_id FROM order_items WHERE order_id < 5; ``` ```text iscan class: order_items node[0] index: pk_order_items_order_id_product_id term[0] (covers) cost: 9 card 1123 ``` `(covers)` in the plan, or `covered: true` in a [trace](https://www.coradb.ai/manual/sql/tuning_plan.html#query-profiling), shows that the optimization was used. - The optimizer prefers a covering index when one is available. In a join, an index that covers the columns of its table is used for that table. - A covering index is only used where an index can be used at all. - Adding columns to an index to make it cover more queries makes the index larger and **INSERT**, **UPDATE** and **DELETE** slower; weigh this for each table. - The hint **NO_COVERING_IDX** turns the optimization off for a query. ## Optimizing ORDER BY clause Index scans return rows in index order. When that is the order requested by **ORDER BY**, no sort is needed: the plan shows `sort:` on the index scan and the comment `/* ---> skip ORDER BY */` (in a trace, `skip order by: true`). ```sql SELECT /*+ RECOMPILE */ id, order_date FROM orders WHERE order_date >= DATE'2025-12-01' ORDER BY order_date; ``` ```text iscan class: orders node[0] index: idx_orders_order_date term[0] sort: 2 asc cost: 5 card 291 /* ---> skip ORDER BY */ ``` An index can be used for **ORDER BY** *col1*, *col2* when: - The **ORDER BY** columns are the leading columns of the index, in index order: an index on (*col1*, *col2*) or (*col1*, *col2*, *col3*) works, an index on (*col1*) alone does not; - Index columns before or between them are fixed to a constant by the **WHERE** clause: with `WHERE col2 = 5`, an index on (*col1*, *col2*, *col3*) can be used for `ORDER BY col1, col3`; - Without any condition on the index, the first index column is **NOT NULL** (otherwise rows with **NULL** keys would be missing from the index scan). If an index can be used both as a covering index and to skip the sort, both optimizations apply. If the covering index is not in the requested order, the rows are read from the index and then sorted (the plan shows `temp(order by)` above the index scan). ## Index scan in descending order An index can be scanned backwards. For **ORDER BY** … **DESC** the optimizer does this on its own, without a separate descending index: ```sql SELECT /*+ RECOMPILE */ id, order_date FROM orders WHERE order_date >= DATE'2025-12-01' ORDER BY order_date DESC LIMIT 5; ``` ```text iscan class: orders node[0] index: idx_orders_order_date term[0] (desc_index) sort: 2 desc cost: 3 card 291 /* ---> skip ORDER BY */ ``` There is therefore no need to create both an ascending and a descending index on the same column, which would also make deadlocks more likely. Without **ORDER BY**, the hint **USE_DESC_IDX** asks for a descending scan, for example to get the most recent rows with **LIMIT**. The plan shows `(desc_index forced)`: ```sql SELECT /*+ RECOMPILE */ order_date FROM orders WHERE order_date > DATE'2025-01-01' LIMIT 3; -- 2025-01-02, 2025-01-03, 2025-01-04 SELECT /*+ RECOMPILE USE_DESC_IDX */ order_date FROM orders WHERE order_date > DATE'2025-01-01' LIMIT 3; -- 2025-12-31 three times ``` **NO_DESC_IDX** prevents descending scans. **USE_DESC_IDX** has no effect on joins. Relying on scan order without **ORDER BY** is fragile; prefer **ORDER BY** … **DESC**. ## Optimizing GROUP BY clause Grouping normally requires sorted (or hashed) input. When an index delivers the rows in the order of the **GROUP BY** columns, no sort is needed and the plan shows `/* ---> skip GROUP BY */`: ```sql SELECT /*+ RECOMPILE */ order_date, COUNT(*) FROM orders WHERE order_date >= DATE'2025-12-01' GROUP BY order_date; ``` ```text iscan class: orders node[0] index: idx_orders_order_date term[0] (covers) sort: 1 asc cost: 5 card 291 /* ---> skip GROUP BY */ ``` The rules are the same as for **ORDER BY**: the **GROUP BY** columns must be the leading columns of the index, possibly with constant-fixed columns in between, and without a **WHERE** condition on the index the first index column must be **NOT NULL**. Aggregate functions do not prevent the optimization: with an index on (*a*, *b*, *c*), `SELECT a, MIN(b), c, MAX(b) FROM t WHERE a > 18 GROUP BY a, b` is grouped from the index. ## Multiple key ranges optimization Many queries ask for the top *N* rows of several key ranges, for example the latest orders of a few customers. Instead of reading all matching rows and sorting them, the *multiple key ranges optimization* (MRO) scans each range of an index in **ORDER BY** order and keeps only the best *N* rows (top-N sort), stopping each range early. With an index on `orders(customer_id, order_date)`: ```sql CREATE INDEX idx_orders_cust_date ON orders (customer_id, order_date); SELECT /*+ RECOMPILE */ customer_id, id, order_date FROM orders WHERE customer_id IN (440, 812, 444) ORDER BY order_date DESC LIMIT 3; ``` | customer_id | id | order_date | |---|---|---| | 440 | 1651 | 2025-12-27 | | 440 | 462 | 2025-12-15 | | 812 | 428 | 2025-12-10 | The trace shows `mro: true` and `topnsort: true`. Only 2 index keys are read: ```text INDEX SCAN (orders.idx_orders_cust_date) (key range: ((orders.customer_id= ?:0 ) or (orders.customer_id= ?:1 ) or (orders.customer_id= ?:2 )), desc_index: true) ... SCAN (index: orders.idx_orders_cust_date), (btree time: 0, fetch: 9, ioread: 0, readkeys: 2, filteredkeys: 0, rows: 3, mro: true) (lookup time: 0, rows: 3) ORDERBY (time: 0, topnsort: true) ``` With the hint **NO_MULTI_RANGE_OPT** the same query scans `idx_orders_order_date` backwards and reads 1,387 keys to find the 3 rows. **Conditions on a single table.** MRO is considered for queries of this form: ```sql SELECT ... FROM table WHERE col_1 = ? AND ... AND col_(j-1) = ? AND col_j IN (?, ?, ...) AND col_(j+1) = ? AND ... AND col_(p-1) = ? AND key_filter_conditions ORDER BY col_p [ASC|DESC], ..., col_(p+k-1) [ASC|DESC] LIMIT n; ``` - *n* is at most the system parameter [multi_range_optimization_limit](https://www.coradb.ai/manual/admin/config_other.html#multi_range_optimization_limit) (default 100). - One index contains all columns used by the **WHERE** and **ORDER BY** clauses (no data filter), in this order: the equality columns, the single range (**IN**) column, further equality columns, then the **ORDER BY** columns. - Columns used in key filters are not **ORDER BY** columns. - Columns compared with a correlated subquery appear in the **WHERE** clause without a range condition. **Joins.** MRO also works in joins if all **ORDER BY** columns belong to one table (the *sort table*), that table meets the single-table conditions, and every column of the sort table used in a join condition is in the index and compared without a range condition. MRO is usually the fastest plan when it applies; **NO_MULTI_RANGE_OPT** turns it off. ## Index skip scan An index can normally be used only if the query has a condition on its first column. *Index skip scan* (ISS) lifts this restriction when the first column has few distinct values: it searches the index once for each value of the first column, using the condition on the following columns. `order_items.discount_pct` has only six values (0, 5, 10, 15, 20 and 25). With an index on (`discount_pct`, `product_id`, `quantity`), the hint **INDEX_SS** lets a search by product use it: ```sql CREATE INDEX idx_oi_disc_prod ON order_items (discount_pct, product_id, quantity); SELECT /*+ RECOMPILE INDEX_SS */ order_id, quantity FROM order_items WHERE product_id = 1618; ``` ```text INDEX SCAN (order_items.idx_oi_disc_prod) (key range: order_items.product_id= ?:0 ) ... SCAN (index: order_items.idx_oi_disc_prod), (btree time: 0, fetch: 30, ioread: 0, readkeys: 10, filteredkeys: 0, rows: 4) (lookup time: 0, rows: 4) ``` ISS is considered only with the hint **INDEX_SS**, and only when: 1. The query's conditions start at the second column of a composite index (`WHERE c2 = x AND c3 = y …`, or range conditions such as `c2 < x`); 2. The index is not a filtered index; 3. The first index column is not used in a range condition or key filter; 4. The query is not hierarchical and contains no aggregate function. `/*+ INDEX_SS */` applies to all tables, `/*+ INDEX_SS(t1, t2) */` to the listed tables; `/*+ INDEX_SS() */` is ignored. **NO_INDEX_SS** prevents ISS. The optimizer still decides by cost; ISS pays off only when the first column has very few distinct values. ## Loose index scan For **DISTINCT** or **GROUP BY** on the leading columns of an index (a *subkey*), a *loose index scan* jumps from one distinct subkey value to the next instead of reading every index entry. It is worthwhile when the grouped columns have few distinct values compared with the size of the index. ```sql CREATE INDEX idx_oi_disc_prod ON order_items (discount_pct, product_id, quantity); SELECT /*+ RECOMPILE INDEX_LS */ DISTINCT discount_pct FROM order_items WHERE discount_pct >= 0; ``` ```text SORT (distinct) INDEX SCAN (order_items.idx_oi_disc_prod) (key range: (order_items.discount_pct>= ?:0 ), covered: true, loose: true) ... SCAN (index: order_items.idx_oi_disc_prod), (btree time: 0, fetch: 14, ioread: 0, readkeys: 6, filteredkeys: 0, rows: 6, covered: true, loose: true) ``` Six keys are read instead of 11,230. A loose index scan is considered only with the hint **INDEX_LS** (**NO_INDEX_LS** prevents it), and only when: 1. The index covers the query; 2. The query is **SELECT DISTINCT**, **SELECT** … **GROUP BY**, or returns a single row; 3. All aggregate functions except **MIN** and **MAX** take **DISTINCT** arguments, and **COUNT(\*)** is not used; 4. The subkey has at most 1/100 of the cardinality of the whole index; 5. The index has a condition that it can use: either on the grouped column (`WHERE discount_pct >= 0 GROUP BY discount_pct`) or on a following column (`WHERE product_id > 10 GROUP BY discount_pct`). Without any condition (`SELECT … GROUP BY discount_pct`), the subkey cannot be used. A subkey is a prefix of a composite index: for an index on (a, b, c, d), (a), (a, b) and (a, b, c) are subkeys. ## In memory sort For a query with **ORDER BY** and **LIMIT**, CoraDB normally sorts the whole result and then keeps the first rows. With the *in-memory sort* optimization it keeps only the rows that can still be in the result, in an in-memory heap, and never builds the full sorted result. Traces show it as `topnsort: true` on the **ORDERBY** step. The optimization is applied automatically when: - The query has **ORDER BY** and **LIMIT**, and no **DISTINCT**; - The rows to keep fit in the sort buffer ([sort_buffer_size](https://www.coradb.ai/manual/admin/config_resources.html#memory-related-parameters)). The limit is a size, not a row count: with a 2 MB sort buffer, about 500,000 rows of one **INTEGER** column fit, but only about 2,000 rows of a **CHAR(1024)** column. ## SORT-LIMIT optimization In a join with **ORDER BY** and **LIMIT**, the *SORT-LIMIT* optimization applies the **LIMIT** to one table before the join, so that only a few rows are joined. The following query lists the five earliest orders since June 2025 with their customers: ```sql SELECT /*+ RECOMPILE */ o.id, o.order_date, c.company_name FROM orders o, customer c WHERE o.customer_id = c.id AND o.order_date >= DATE'2025-06-01' ORDER BY o.order_date LIMIT 5; ``` ```text idx-join (inner join) outer: temp(sort limit) subplan: iscan class: o node[0] index: idx_orders_order_date term[1] cost: 3 card 100 cost: 3 card 100 inner: iscan class: c node[1] index: pk_customer_id term[0] cost: 3 card 1000 sort: 2 asc cost: 6 card 291 ``` `temp(sort limit)` shows that the five first orders are selected before the customers are looked up. A SORT-LIMIT plan is possible when: - All tables in the **ORDER BY** clause are part of the SORT-LIMIT plan, and each of them is the foreign key side of a foreign key → primary key join (as `orders` here), the left side of a **LEFT JOIN** or the right side of a **RIGHT JOIN**; - The **LIMIT** is below the system parameter [sort_limit_max_count](https://www.coradb.ai/manual/admin/config_other.html#sort_limit_max_count) (default 1000; 0 disables the optimization); - The query joins at least two tables, without cross joins, **GROUP BY** or **DISTINCT**; - The **ORDER BY** expressions can be evaluated while scanning: `SELECT SUM(o.shipping_cost) … ORDER BY 1 LIMIT 5` cannot use it. The hint **NO_SORT_LIMIT** turns the optimization off. --- # Query plans and query profiling Source: https://www.coradb.ai/manual/sql/tuning_plan.html ## Viewing query plan The *query plan* shows how CoraDB will execute a query: the order in which tables are read, how they are read (index or full scan) and how they are joined. There are two ways to see it: - In corasql, the session commands `;plan simple` and `;plan detail` print the plan of each query you run. See [Session commands](https://www.coradb.ai/manual/corasql.html#session-commands). - In any client, **SET OPTIMIZATION LEVEL** controls whether plans are printed (to the client's output, for example in corasql) and whether queries are executed at all. ```sql SET OPTIMIZATION LEVEL level; GET OPTIMIZATION LEVEL [ { INTO | TO } :variable ]; ``` | Level | Optimizes | Prints plan | Executes | |---|---|---|---| | 0 | No (simplest plan; for debugging only) | no | yes | | **1** (default) | yes | no | yes | | 2 | yes | no | **no** | | 257 (256 + 1) | yes | Simple plan | yes | | 258 (256 + 2) | yes | Simple plan | **no** | | 513 (512 + 1) | yes | Detailed plan | yes | | 514 (512 + 2) | yes | Detailed plan | **no** | > **Warning:** > At levels 2, 258 and 514 *no* statement is executed: not only **SELECT**, but also **INSERT**, **UPDATE**, **DELETE**, **REPLACE**, triggers and serials. Use them to examine plans, and set level 1 again afterwards. Add the hint `/*+ RECOMPILE */` when you look at plans, so that a cached plan is not reused. ### Reading a plan The following query lists the customers of the 100 most recent orders (order IDs above 2800). `;plan detail`, or level 513, prints: ```sql SET OPTIMIZATION LEVEL 513; SELECT /*+ RECOMPILE */ DISTINCT c.company_name, o.order_date FROM orders o INNER JOIN customer c ON o.customer_id = c.id AND o.id > 2800; ``` ```text Join graph segments (f indicates final): seg[0]: [0] seg[1]: order_date[0] (f) seg[2]: customer_id[0] seg[3]: id[0] seg[4]: [1] seg[5]: company_name[1] (f) seg[6]: id[1] Join graph nodes: node[0]: orders o(2914/23) (sargs 1) location (idx:0, group:-1) node[1]: customer c(1000/11) location (idx:1, group:-1) Join graph equivalence classes: eqclass[0]: customer_id[0] id[1] Join graph edges: term[0]: o.customer_id=c.id (sel 0.001) (join term) (mergeable) (inner-join) (indexable customer_id[0] id[1]) location (idx:0, group:-1) Join graph terms: term[1]: o.id range (2800 gt_inf max) (sel 0.1) (rank 2) (sarg term) (not-join eligible) (indexable id[0]) location (idx:0, group:-1) Query plan: temp(distinct) subplan: idx-join (inner join) outer: iscan class: o node[0] index: pk_orders_id term[1] cost: 5 card 291 inner: iscan class: c node[1] index: pk_customer_id term[0] cost: 3 card 1000 cost: 10 card 291 cost: 16 card 291 Query stmt: select distinct c.company_name, o.order_date from orders o, customer c where o.customer_id=c.id and (o.id> ?:0 ) ``` The plan is read from the inside out: 1. **outer: iscan** reads `orders` (node[0]) with the index `pk_orders_id`, limited by term[1], `o.id > 2800`. 2. For each order, **inner: iscan** looks up the customer (node[1]) in `pk_customer_id` using the join condition term[0], `o.customer_id = c.id`. Together these two steps are an **idx-join**. 3. **temp(distinct)** collects the result in a temporary list and removes duplicates. The sections above "Query plan" explain the numbers in it: - **Join graph nodes** list the tables with their statistics: `orders o(2914/23)` means about 2,914 rows in 23 pages. `(sargs 1)` means one filter condition applies to the table. - **Join graph edges** are join conditions, **Join graph terms** other conditions. `sel` is the estimated selectivity (share of rows that pass), `indexable` names the columns an index can be used on. - **cost** is the estimated cost of a step including the steps below it (CPU and I/O), **card** the estimated number of rows it returns. Both are estimates based on [statistics](https://www.coradb.ai/manual/sql/tuning.html). - **Query stmt** is the query after rewriting by the optimizer; constants are shown as `?:n`. The *simple* plan (`;plan simple`, level 257) shows the same plan as one line per step, with the names in the last column of the following table. **Query plan terms** | Detailed plan | Simple plan | Meaning | |---|---|---| | `sscan` | Sequential scan | Full table scan, without an index. | | `iscan` | Index scan | Scan of an index range; `(covers)` after the index name means a [covering index](https://www.coradb.ai/manual/sql/tuning_index_opt.html#covering-index): the index alone answers the query. | | `nl-join` | Nested-loop join | For each row of the outer table, scan the inner table. | | `idx-join` | Correlated-index join | Nested-loop join that looks up each outer row in an index of the inner table. | | `m-join` | Merge join | Sort both inputs on the join columns and merge them. | | `temp` | Sort | Store rows in a temporary list, for sorting (`order:`), **DISTINCT**, **GROUP BY** and similar. | | `outer` / `inner` | | In a nested-loop join, the table read first (outer) and the table read for each of its rows (inner). | | `sargs` | | Conditions applied as data filters (not through an index). | | `(inner join)`, `(left outer join)`, `(cross join)` | | Join type. A **RIGHT OUTER JOIN** may be shown as a left outer join with the tables swapped. | ### Join methods **Merge join.** The optimizer considers sort-merge joins only with the hint **USE_MERGE** or when the system parameter [optimizer_enable_merge_join](https://www.coradb.ai/manual/admin/config_other.html#optimizer_enable_merge_join) is `yes`. Merge joins are rarely faster than index joins: ```sql SELECT /*+ RECOMPILE USE_MERGE */ c.company_name, o.order_date FROM customer c LEFT OUTER JOIN orders o ON c.id = o.customer_id AND o.shipping_cost > 45; ``` ```text Query plan: temp order: UNORDERED subplan: m-join (left outer join) edge: term[0] outer: temp order: id[0] subplan: sscan class: c node[0] cost: 14 card 1000 cost: 47 card 1000 inner: temp order: customer_id[1] subplan: sscan class: o node[1] sargs: term[1] cost: 30 card 291 cost: 43 card 291 cost: 272 card 1000 cost: 281 card 1000 ``` Both tables are scanned, sorted on the join columns (`order: id[0]`, `order: customer_id[1]`) and merged; the cost (281) is much higher than an index join would be. **Join order.** If you know that one table yields far fewer rows than the other, the hint **ORDERED** makes the tables be joined in the order of the **FROM** clause, the first being the outer table: ```sql SELECT /*+ RECOMPILE ORDERED */ p.name, oi.quantity FROM order_items oi, product p WHERE p.id = oi.product_id AND oi.quantity > 4; ``` ```text Query plan: idx-join (inner join) outer: sscan class: oi node[0] sargs: term[1] cost: 50 card 1123 inner: iscan class: p node[1] index: pk_product_id term[0] cost: 3 card 2115 cost: 77 card 1123 ``` More hints are described in [SQL and index hints](https://www.coradb.ai/manual/sql/tuning_hints.html). ## Query profiling A plan shows what the optimizer *expects*. To see what actually happened when a query ran (time, pages fetched, rows read at each step), turn on SQL tracing: ```sql SET TRACE { ON | OFF } [ OUTPUT { TEXT | JSON } ]; SHOW TRACE; ``` - **SET TRACE ON** traces the following queries of the session; **OUTPUT TEXT** is the default. - **SHOW TRACE** returns the trace of the last query as a string. If that query had the hint `/*+ RECOMPILE */`, the trace also contains its plan. - In corasql, `;trace on` shows the trace automatically after each query; see [Set SQL trace](https://www.coradb.ai/manual/corasql.html#set-autotrace). - Tracing is not available in stand-alone corasql (`-S`), and batched or array executions are not traced. The following query finds the customers with the most orders whose shipping cost was above 40: ```sql SET TRACE ON; SELECT /*+ RECOMPILE */ c.company_name, COUNT(*) AS orders, SUM(o.shipping_cost) AS shipping FROM customer c, orders o WHERE c.id = o.customer_id AND o.shipping_cost > 40 GROUP BY c.company_name ORDER BY 2 DESC, 1 LIMIT 3; SHOW TRACE; ``` ```text Query Plan: SORT (order by) SORT (group by) NESTED LOOPS (inner join) TABLE SCAN (c) INDEX SCAN (o.fk_orders_customer_id) (key range: c.id=o.customer_id) rewritten query: select c.company_name, count(*), sum(o.shipping_cost) from customer c, orders o where c.id=o.customer_id and (o.shipping_cost> ?:0 ) group by c.company_name order by 2 desc , 1 for orderby_num()<= ?:1 Trace Statistics: SELECT (time: 3, fetch: 5924, ioread: 0) SCAN (table: customer), (heap time: 0, fetch: 1011, ioread: 0, readrows: 1000, rows: 1000) SCAN (index: orders.fk_orders_customer_id), (btree time: 2, fetch: 4912, ioread: 0, readkeys: 650, filteredkeys: 0, rows: 2910) (lookup time: 1, rows: 86) GROUPBY (time: 0, hash: true, sort: false, rows: 80) ORDERBY (time: 0, sort: true, page: 0, ioread: 0) ``` How to read it: - **SELECT**: the whole query took 3 ms and 5,924 page fetches, without disk reads (all pages were in the buffer). Running the query again usually shows fewer reads. - **SCAN (table: customer)**: all 1,000 customers were read from the heap. - **SCAN (index: orders.fk_orders_customer_id)**: for each customer, the foreign key index on `orders.customer_id` was searched: 650 distinct keys, 2,910 index entries. Fetching the rows and applying `o.shipping_cost > 40` (*lookup*) left 86 rows. - **GROUPBY**: 86 rows were aggregated by hashing into 80 groups, without sorting. **ORDERBY** sorted them for the **LIMIT**. Times are in milliseconds and rounded; a time below 1 ms is shown as 0. `fetch` counts page accesses, not distinct pages. ### Trace items **SELECT** | Item | Meaning | |---|---| | time | Total time of the query (ms) | | fetch | Total page fetches | | ioread | Total pages read from disk | **SCAN** | Item | Meaning | |---|---| | heap: time, fetch, ioread | Time and pages of a table scan without index | | btree: time, fetch, ioread | Time and pages of an index scan | | readrows | Rows read by this step | | readkeys | Index keys read | | filteredkeys | Keys that a key filter was applied to | | rows | Rows returned by this step (after key filters for btree, after data filters for lookup) | | lookup: time, rows | Fetching the rows found in the index and applying the data filter | | temp: buildtime, time, hash | Scan of a temporary list; `hash` tells whether a hash list scan was used (see the [NO_HASH_LIST_SCAN](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-list-scan) hint) | | covered | The index covered the query (JSON output) | | loose | A loose index scan was used | **GROUPBY** and **ORDERBY** | Item | Meaning | |---|---| | time | Time of the step (ms) | | sort | Whether rows were sorted | | hash | Whether hash aggregation was used (see the [NO_HASH_AGGREGATE](https://www.coradb.ai/manual/sql/tuning_hints.html#no-hash-aggregate) hint) | | page | Temporary pages used for sorting, beyond the sort buffer | | rows | Result rows | In the plan part, **INDEX SCAN** shows the `key range` that limits the scan, and `covered` or `loose` when those optimizations apply. Subqueries appear as **SUBQUERY (correlated)** or **SUBQUERY (uncorrelated)** with their own statistics. ### JSON output With **OUTPUT JSON** the same statistics are returned as a JSON document, which is easier to process in tools: ```sql SET TRACE ON OUTPUT JSON; SELECT p.name, COUNT(*) FROM product p, order_items oi WHERE p.id = oi.product_id AND p.id BETWEEN 1600 AND 1605 GROUP BY p.name; SHOW TRACE; ``` ```json { "Trace Statistics": { "SELECT": { "time": 0, "fetch": 22, "ioread": 0, "SCAN": { "access": "index (product.pk_product_id)", "btree": { "time": 0, "fetch": 8, "ioread": 0, "readkeys": 6, "filteredkeys": 0, "rows": 6 }, "lookup": { "time": 0, "rows": 6 }, "SCAN": { "access": "index (order_items.fk_order_items_product_id)", "btree": { "time": 0, "fetch": 12, "ioread": 0, "readkeys": 6, "filteredkeys": 0, "rows": 18 }, "covered": true } }, "GROUPBY": { "time": 0, "hash": true, "sort": false, "rows": 6 } } } } ``` The index on `order_items.product_id` covers the query (`"covered": true`): only the number of order lines per product is needed, so no `order_items` rows are read. ### Query profiling with graph match queries For **MATCH** queries the trace contains a **SCAN (graph_match …)** step with graph-specific counters. The following query counts the customers who liked product 123 since 2025: ```sql SET TRACE ON; SELECT /*+ RECOMPILE */ COUNT(*) FROM MATCH (cu:customer)-[l:likes]->(p:product) WHERE p.id = 123 AND l.since >= DATETIME'2025-01-01 00:00:00'; SHOW TRACE; ``` ```text Query Plan: NESTED LOOPS (cross join) INDEX SCAN (p_product.pk_product_id) (key range: p.id= ?:1 ) rewritten query: select count(*) from match (cu:customer), match (p:product)-[l:likes{1, 1}]->(cu:customer) where (l.since>= ?:0 ) and p.id= ?:1 Trace Statistics: SELECT (time: 0, fetch: 6, ioread: 0) SCAN (index: product.pk_product_id), (btree time: 0, fetch: 3, ioread: 0, readkeys: 1, filteredkeys: 0, rows: 1) (lookup time: 0, rows: 1) SCAN (graph_match time: 0, fetch: 0, ioread: 0, edge_fetches: 103, vertex_fetches: 1, qualified_edges: 15, qualified_vertices:0, readrows: 15, rows: 15) ``` The optimizer starts from the product, found through its primary key, and follows its 103 `likes` edges; 15 of them satisfy the date condition. | Item | Meaning | |---|---| | time, fetch, ioread | Time (ms), page fetches and disk reads of the graph match | | edge_fetches | Edges examined while following the pattern | | vertex_fetches | Vertices examined | | qualified_edges | Edges that satisfied the conditions on edges | | qualified_vertices | Vertices that satisfied the conditions on vertices | | readrows | Rows read by the graph match | | rows | Rows it returned | Many more fetched than qualified edges or vertices mean that the traversal examines elements that do not contribute to the result: add a more selective condition, or start the pattern from the more selective end. --- # Filtered, function-based and shared indexes Source: https://www.coradb.ai/manual/sql/tuning_special_index.html Besides ordinary indexes on columns, CoraDB supports three special kinds of index: *filtered* indexes that contain only some rows, *function-based* indexes on an expression, and *shared* indexes that cover a whole inheritance hierarchy. The general syntax of **CREATE INDEX** is described in [CREATE INDEX](https://www.coradb.ai/manual/sql/schema/index_stmt.html#create-index). ## Filtered index A *filtered* (partial) index contains only the rows that satisfy a condition. It is smaller than a full index and suits queries that always look at the same small part of a table, such as open orders or unprocessed jobs. ```sql CREATE INDEX index_name ON table_name (column [, column ...]) WHERE filter_condition; ALTER INDEX index_name [ ON table_name (column [, column ...]) [ WHERE filter_condition ] ] REBUILD; filter_condition ::= condition [ AND condition ... ] ``` In the e-commerce sample database, only 9 of the 2,910 orders have no `shipped_date` yet. An index on the unshipped orders contains just those 9 rows: ```sql CREATE INDEX idx_orders_unshipped ON orders (order_date, customer_id) WHERE shipped_date IS NULL; ``` **Using a filtered index.** The optimizer uses a filtered index only when you name it in an [index hint](https://www.coradb.ai/manual/sql/tuning_hints.html#index-hint), and only for queries that contain the index's filter condition: ```sql SELECT id, order_date FROM orders USE INDEX (idx_orders_unshipped) WHERE order_date >= DATE'2025-01-01' AND shipped_date IS NULL ORDER BY order_date; ``` With the hint, [SHOW TRACE](https://www.coradb.ai/manual/sql/tuning_plan.html#query-profiling) shows that 9 index keys are read: ```text INDEX SCAN (orders.idx_orders_unshipped) (key range: (orders.order_date>= ?:0 )) skip order by: true ... SCAN (index: orders.idx_orders_unshipped), (btree time: 0, fetch: 11, ioread: 0, readkeys: 9, filteredkeys: 0, rows: 9) (lookup time: 0, rows: 9) ``` Without it, the optimizer uses the ordinary index on `order_date`, reads the 786 orders of 2025 and discards all but 9: ```text INDEX SCAN (orders.idx_orders_order_date) (key range: (orders.order_date>= ?:0 )) ... SCAN (index: orders.idx_orders_order_date), (btree time: 0, fetch: 789, ioread: 0, readkeys: 320, filteredkeys: 0, rows: 786) (lookup time: 0, rows: 9) ``` - With **USE INDEX** or `USING INDEX idx`, the filtered index is used only if the **WHERE** clause has a condition on its first column that can limit the index scan, as above. - With **FORCE INDEX** or `USING INDEX idx(+)`, it is also used when another index column appears in the **WHERE** clause; the condition is then applied as a key filter. For example `FORCE INDEX (idx_orders_unshipped) WHERE customer_id > 0 AND shipped_date IS NULL` scans the 9 index entries. - If no column of the index appears in the **WHERE** clause, the filtered index is not used. > **Warning:** > The optimizer does not check that the query's conditions imply the index's filter. If you force a filtered index on a query without the filter condition, the query sees only the rows in the index, and its result can be wrong. Always repeat the filter condition in the query. ### Restrictions on filtered indexes - Only ordinary indexes can be filtered; `CREATE UNIQUE INDEX … WHERE …` is a syntax error. - At least one column of the index must be **NOT NULL**. `CREATE INDEX … ON orders (shipped_date) WHERE …` fails with `Invalid filter expression (…) for index`, because `shipped_date` is nullable. - Conditions can be combined only with **AND**: `' or ' is not allowed in a filter expression for index`. - The condition cannot use functions whose result changes for the same input, such as **SYS_DATE**, **SYS_DATETIME** or **RAND** (`'sys_date ' is not allowed in a filter expression for index`); functions that change data, such as **INCR** and **DECR**; serial functions or pseudo-columns; aggregate functions such as **MIN**, **MAX** and **STDDEV**; operators and functions on **SET** values; or LOB functions such as **CHAR_TO_CLOB** and **BIT_TO_BLOB**. - **IS NULL** can be used only on a plain column, and not for every column of the index: `WHERE a IS NULL` is rejected for an index on `(a, b)`, and `WHERE (a + 1) IS NULL` is rejected. - The filter condition can be at most 128 characters long (`The maximum length of filter predicate string must be 128.`). - A filtered index cannot be used for an [index skip scan](https://www.coradb.ai/manual/sql/tuning_index_opt.html#index-skip-scan), and it cannot be function-based. - A filtered index on exactly the same columns as an existing index is rejected (`Index "…" already defined`); add a column, as in the example above. ## Function-based index A *function-based* index stores the result of a function of a column instead of the column value. It lets the optimizer use an index for conditions on that expression, for example case-insensitive searches or searches by year. ```sql CREATE INDEX index_name ON table_name ( function_name ( arguments ) [, column ...] ); ALTER INDEX index_name [ ON table_name ( function_name ( arguments ) ) ] REBUILD; ``` ```sql CREATE INDEX idx_customer_lower_name ON customer (LOWER(company_name)); SELECT id, company_name FROM customer WHERE LOWER(company_name) = LOWER('JONES LLC'); ``` ```text INDEX SCAN (customer.idx_customer_lower_name) (key range: lower(customer.company_name)= lower('JONES LLC')) ``` The query returns customers 102 and 401, both named *Jones LLC*. Similarly, `CREATE INDEX idx_orders_year ON orders (YEAR(order_date))` is used by `WHERE YEAR(order_date) = 2023`. [SHOW INDEX](https://www.coradb.ai/manual/sql/query/show.html#show-index) shows the expression of a function-based index in its `Func` column. The query must use the function exactly as in the index. The index above is not used for `WHERE LOWER(CONCAT('Mr. ', company_name)) = 'mr. jones llc'`, which scans the whole table. Use [USING INDEX](https://www.coradb.ai/manual/sql/tuning_hints.html#using-index) to force an index when the optimizer does not choose it. **Restrictions** - An index can contain only one function, and functions cannot be nested: `(TRIM(LEFT(company_name, 3)))` and `(LOWER(company_name), UPPER(contact_name))` fail with `Multiple or nested functions are not allowed in a function index definition`. A function can be combined with plain columns, as in `(LOWER(company_name), id)`. - The arguments of the function can only be columns and constants, but implicit type conversion is applied: `LEFT(int_col, str_col)` is accepted. - A function-based index cannot be filtered (`Invalid index specification.`). **Functions allowed in function-based indexes** | | | | | | |---|---|---|---|---| | ABS | ACOS | ADD_MONTHS | ADDDATE | ASIN | | ATAN | ATAN2 | BIT_COUNT | BIT_LENGTH | CEIL | | CHAR_LENGTH | CHR | COS | COT | DATE | | DATE_ADD | DATE_FORMAT | DATE_SUB | DATEDIFF | DAY | | DAYOFMONTH | DAYOFWEEK | DAYOFYEAR | DEGREES | EXP | | FLOOR | FORMAT | FROM_DAYS | FROM_UNIXTIME | GREATEST | | HOUR | IFNULL | INET_ATON | INET_NTOA | INSTR | | LAST_DAY | LEAST | LEFT | LN | LOCATE | | LOG | LOG10 | LOG2 | LOWER | LPAD | | LTRIM | MAKEDATE | MAKETIME | MD5 | MID | | MINUTE | MOD | MONTH | MONTHS_BETWEEN | NULLIF | | NVL | NVL2 | OCTET_LENGTH | POSITION | POWER | | QUARTER | RADIANS | REPEAT | REPLACE | REVERSE | | RIGHT | ROUND | RPAD | RTRIM | SECOND | | SECTOTIME | SIN | SQRT | STR_TO_DATE | STRCMP | | SUBDATE | SUBSTR | SUBSTRING | SUBSTRING_INDEX | TAN | | TIME | TIME_FORMAT | TIMEDIFF | TIMESTAMP | TIMETOSEC | | TO_CHAR | TO_DATE | TO_DATETIME | TO_DAYS | TO_NUMBER | | TO_TIME | TO_TIMESTAMP | TRANSLATE | TRIM | TRUNC | | UNIX_TIMESTAMP | UPPER | WEEK | WEEKDAY | YEAR | ## Shared index A *shared* index is created on a table and applies to that table and all tables that inherit from it ([UNDER](https://www.coradb.ai/manual/sql/oodb.html)), now and in the future. Like a unique index, and unlike an ordinary index, it uses one index structure for the whole hierarchy, so a query over the table and its subclasses (**FROM ALL** *table*) can use a single index. ```sql CREATE SHARED INDEX index_name ON table_name (column [, column ...]); ``` ```sql CREATE TABLE party (party_id INT, name STRING, email STRING); CREATE TABLE retail_customer UNDER party; CREATE TABLE wholesale_customer UNDER party; CREATE SHARED INDEX idx_party_email ON party (email); INSERT INTO party VALUES (3, 'Head Office', 'office@example.com'); INSERT INTO retail_customer VALUES (1, 'Ana', 'ana@example.com'); ``` - The index appears on every table of the hierarchy: [SHOW INDEXES](https://www.coradb.ai/manual/sql/query/show.html#show-index) `FROM retail_customer` lists `idx_party_email` with `Shared` = 1. Subclasses created later get it as well. - It works across several levels of inheritance. - It is used by queries on the table itself and on the whole hierarchy: ```sql SELECT party_id, name FROM party WHERE email = 'office@example.com'; -- 3, Head Office SELECT party_id, name FROM ALL party WHERE email = 'ana@example.com'; -- 1, Ana SELECT party_id, name FROM ALL party (EXCEPT wholesale_customer) WHERE email = 'ana@example.com'; ``` - It can be dropped only on the table where it was created; dropping it there removes it from all subclasses. `DROP INDEX idx_party_email ON retail_customer` fails with `Illegal operation on "idx_party_email", inherited from class "party".` Dropping the table also removes the index from its subclasses. --- # Getting started with CoraDB Source: https://www.coradb.ai/manual/start.html These pages take you from an installed CoraDB to your first queries: | Page | What you learn | |---|---| | [Quick start](https://www.coradb.ai/manual/quick_start.html) | Start the CoraDB service, create or open a database, run your first relational, graph and hybrid queries | | [Sample database](https://www.coradb.ai/manual/sample-database.html) | The e-commerce database used by the examples in this manual | | [Demo databases](https://www.coradb.ai/manual/demo-databases.html) | The other datasets you can load to explore CoraDB | | [Query tools](https://www.coradb.ai/manual/qrytool.html) | Run SQL from the command line with [corasql](https://www.coradb.ai/manual/corasql.html), and the [drivers](https://www.coradb.ai/manual/api.html) for applications | | [corasql interpreter](https://www.coradb.ai/manual/corasql.html) | All corasql options and session commands | | [Tutorial: tables and graphs](https://www.coradb.ai/manual/graph/graph_getting_started.html) | Relational tables and a graph in one database, queried together step by step | If CoraDB is not installed yet, start with [Installing and upgrading](https://www.coradb.ai/manual/install_upgrade.html). --- # About this manual Source: https://www.coradb.ai/manual/toc.html ## Manual contents | Part | Contents | |---|---| | [What is CoraDB?](https://www.coradb.ai/manual/intro.html) | [System architecture](https://www.coradb.ai/manual/intro.html#system-architecture), [Process structure](https://www.coradb.ai/manual/intro.html#process-structure), [Database volumes](https://www.coradb.ai/manual/intro.html#database-volume-structure), [Database server](https://www.coradb.ai/manual/intro.html#database-server), [Broker](https://www.coradb.ai/manual/intro.html#broker), [Drivers](https://www.coradb.ai/manual/intro.html#interface-module), [Main features](https://www.coradb.ai/manual/intro.html#coradb-characteristics) | | [Getting started](https://www.coradb.ai/manual/start.html) | [Quick start](https://www.coradb.ai/manual/quick_start.html), [Sample database](https://www.coradb.ai/manual/sample-database.html), [Demo databases](https://www.coradb.ai/manual/demo-databases.html), [Query tools](https://www.coradb.ai/manual/qrytool.html), [Tutorial: tables and graphs](https://www.coradb.ai/manual/graph/graph_getting_started.html) | | [Installing and upgrading](https://www.coradb.ai/manual/install_upgrade.html) | [Installation](https://www.coradb.ai/manual/install.html), [Environment variables and ports](https://www.coradb.ai/manual/env.html), [Upgrade](https://www.coradb.ai/manual/upgrade.html), [Removal](https://www.coradb.ai/manual/uninstall.html) | | [corasql interpreter](https://www.coradb.ai/manual/corasql.html) | The command-line SQL client | | [SQL reference](https://www.coradb.ai/manual/sql.html) | [Data types](https://www.coradb.ai/manual/sql/datatype.html), [Data definition (DDL)](https://www.coradb.ai/manual/sql/schema.html), [Data manipulation (DML)](https://www.coradb.ai/manual/sql/query.html), [Operators and functions](https://www.coradb.ai/manual/sql/function.html), [Graph queries (MATCH)](https://www.coradb.ai/manual/graph/match.html), [Relational and graph in one query](https://www.coradb.ai/manual/sql/hybrid.html), [Query optimization](https://www.coradb.ai/manual/sql/tuning.html), [Transactions](https://www.coradb.ai/manual/sql/transaction.html), [All SQL topics](https://www.coradb.ai/manual/sql.html) | | [Administration](https://www.coradb.ai/manual/admin.html) | [Controlling processes](https://www.coradb.ai/manual/admin/control.html), [Database management](https://www.coradb.ai/manual/admin/db_manage.html), [coradb utilities](https://www.coradb.ai/manual/admin/admin_utils.html), [Backup and restore](https://www.coradb.ai/manual/admin/admin_backup.html), [System parameters](https://www.coradb.ai/manual/admin/config.html), [Troubleshooting](https://www.coradb.ai/manual/admin/troubleshoot.html) | | [Security](https://www.coradb.ai/manual/security.html) | [Packet encryption](https://www.coradb.ai/manual/security.html#packet-encryption), [Access control lists](https://www.coradb.ai/manual/security.html#acl-access-control-list), [Users and privileges](https://www.coradb.ai/manual/sql/authorization.html), [Table encryption (TDE)](https://www.coradb.ai/manual/security.html#tde-transparent-data-encryption) | | [Drivers and APIs](https://www.coradb.ai/manual/api.html) | [JDBC](https://www.coradb.ai/manual/api/jdbc.html), [Node.js](https://www.coradb.ai/manual/api/node_js.html), [PHP](https://www.coradb.ai/manual/api/php.html), [ADO.NET](https://www.coradb.ai/manual/api/adodotnet.html), [Python](https://www.coradb.ai/manual/api/python.html), [CCI](https://www.coradb.ai/manual/api/cci.html) | Every page is also available as Markdown for AI tools: use the **View as Markdown** link under the page title, or replace `.html` with `.md` in the page address under `/manual/markdown/`. The whole manual can be downloaded as [llms.txt](https://www.coradb.ai/manual/llms.txt) (index of all pages), [llms-full.txt](https://www.coradb.ai/manual/llms-full.txt) (the whole manual in one file) or [coradb-manual-md.zip](https://www.coradb.ai/manual/coradb-manual-md.zip) (one Markdown file per page). ## Sample database Unless stated otherwise, the examples use the [e-commerce sample database](https://www.coradb.ai/manual/sample-database.html) and show the results it returns. Examples that change data or the schema are meant to be tried on your own copy. ## Glossary CoraDB is an object-relational and graph database. Besides relational terms, the manual uses object-oriented terms where inheritance matters, and graph terms for vertex and edge tables: | Relational term | Object-oriented term | Graph term | |---|---|---| | Table | Class | Vertex table, Edge table | | Column | Attribute | Property | | Row, Record | Instance, Object | Vertex, Edge | | Data type | Domain | | | View | Virtual class | | ## Conventions | Convention | Meaning | Example | |---|---|---| | **Bold** | SQL keywords and statement names in text | **SELECT**, **CREATE TABLE** | | *Italics* | Placeholders to replace with your own names or values | *table_name*, *db_name* | | `Code` | Names, values, commands and file names | `orders`, `coradb.conf` | | `[ ]` in syntax | Optional part | `[ ONLY ]` | | `{ a \| B }` in syntax | Choose exactly one | `{ TABLE \| CLASS }` | | `a \| b` in syntax | Alternatives | `ASC \| DESC` | | `...` in syntax | The previous element can be repeated | `column [, column ...]` | | `'{'`, `'}'` | Literal braces, as in collection values | `'{' value [, value ...] '}'` | SQL keywords are not case-sensitive; the manual writes them in uppercase. ## Version numbering A CoraDB version is written *Major*.*minor*.*patch*, for example 1.0.1. The full version string adds a build number and the hash of the source revision, for example `1.0.0.0248-b53ae4a`. --- # Uninstalling CoraDB Source: https://www.coradb.ai/manual/uninstall.html ## Linux: .sh or tar.gz installation 1. Stop CoraDB and delete the databases you no longer need, for example `testdb1` and `testdb2`: ```bash coradb service stop coradb deletedb testdb1 coradb deletedb testdb2 ``` [deletedb](https://www.coradb.ai/manual/admin/admin_utils.html#deletedb) removes the volumes and logs of a database and its entry in `databases.txt`. Back up databases you want to keep first. 2. Remove the installation directory `$CORADB`: ```bash echo $CORADB rm -rf /home/coradb/CoraDB ``` 3. Remove the startup script `/etc/init.d/coradb` if you installed it, and the lines that load `~/.coradb.sh` from your shell profile. ## Linux: RPM installation 1. Stop CoraDB and delete the databases as above. 2. Remove the package: ```bash rpm -q coradb rpm -e coradb ``` Configuration files you changed are kept with the extension `.rpmsave`, for example `/opt/coradb/conf/coradb.conf.rpmsave`. 3. Remove `/etc/init.d/coradb` if it is still there. The `coradb` Linux user and group are not removed by `rpm -e`; remove them with `userdel` and `groupdel` if needed. ## Windows Stop CoraDB with the Service Tray, then uninstall *CoraDB* in *Control Panel > Programs and Features*. The uninstaller asks whether to delete the existing databases and configuration files. For a zip installation, remove the service with `ctrlService.exe -u`, delete the installation directory and remove the `CORADB` and `CORADB_DATABASES` environment variables. --- # Upgrading CoraDB Source: https://www.coradb.ai/manual/upgrade.html Upgrading CoraDB has two parts: installing the new software and, when the database format changed, migrating the databases. ## Before you upgrade - **Back up every database** with [backupdb](https://www.coradb.ai/manual/admin/admin_backup.html#backupdb). - **Save the configuration**: the files in `$CORADB/conf` (`coradb.conf`, `coradb_broker.conf` and the others you changed) and `$CORADB_DATABASES/databases.txt`. - **Check reserved words**: identifiers that became [reserved words](https://www.coradb.ai/manual/sql/keyword.html) in the new version must be renamed or quoted. - **Locales**: if your databases use locales other than en_US, list them in `$CORADB/conf/coradb_locales.txt` of the new installation and compile them with `make_locale` before creating or migrating databases; see [Locale setting](https://www.coradb.ai/manual/sql/i18n_locale.html). - **Drivers**: plan to update the drivers of your applications to the new version; the broker and the database server must have the same version. ## Migrating a database When the database format changed, or to move a database to another machine, migrate it with [unloaddb](https://www.coradb.ai/manual/admin/admin_unload.html#unloaddb) and [loaddb](https://www.coradb.ai/manual/admin/admin_unload.html#loaddb). The example migrates `testdb`. | Step | Linux | Windows | |---|---|---| | 1. Stop CoraDB | `coradb service stop` | Stop CoraDB with the Service Tray, or `coradb service stop` | | 2. Unload the database with the **old** version, into a separate directory | `coradb unloaddb -S testdb` | same | | 3. Keep the unload files (`testdb_schema`, `testdb_objects`, `testdb_indexes`, `testdb_trigger`), `databases.txt` and the configuration files in a safe place | | | | 4. Delete the old database | `coradb deletedb testdb` | same | | 5. Install the new version | See [Installing CoraDB](https://www.coradb.ai/manual/install.html) | same | | 6. Create the database with the same locale as before | `coradb createdb testdb en_US.utf8` | same | | 7. Load the unloaded files | `coradb loaddb -u dba -s testdb_schema -d testdb_objects -i testdb_indexes --trigger-file=testdb_trigger testdb` | same | | 8. Back up the new database | `coradb backupdb -S testdb` | same | | 9. Restore your settings in the new configuration files and start CoraDB | `coradb service start`, `coradb server start testdb` | Service Tray > *Service Start*, or the same commands | - Create the database with the same language and charset as the old one; the charset decides how strings are stored and cannot be changed later. See [Charsets, collations & locales](https://www.coradb.ai/manual/sql/i18n.html). - Copy parameter values from the old configuration files instead of replacing the new files with the old ones, so that new parameters keep their defaults. See [System parameters](https://www.coradb.ai/manual/admin/config.html) and [Broker configuration](https://www.coradb.ai/manual/admin/config_broker.html). - Triggers are unloaded to a separate file, `testdb_trigger`, which loaddb loads after the data with `--trigger-file`, so that the triggers do not fire while the rows are loaded. ## After the upgrade - **Java stored procedures**: load the Java classes into the new installation again with [loadjava](https://www.coradb.ai/manual/sql/jsp.html#loadjava-utility) and start the Java SP server; see [Enabling the Java SP server](https://www.coradb.ai/manual/sql/jsp.html#enabling-the-java-sp-server). - **Statistics**: update the optimizer statistics of large tables with [UPDATE STATISTICS](https://www.coradb.ai/manual/sql/tuning.html#updating-statistics) so that plans are based on the new data. - **Applications**: test the applications with the new drivers; query results can change when the behavior of statements or functions changes between versions.