Purpose
This statement is used to query data from one or more tables.
This section describes the general syntax of the SELECT statement. For other SELECT statements, see:
Privilege requirements
To execute the SELECT statement, the current user must have the SELECT privilege. For more information about OceanBase Database privileges, see Privilege types in MySQL-compatible mode.
Syntax
select_stmt:
SELECT [hint_options]
[{DISTINCT | UNIQUE} | ALL]
[SQL_CALC_FOUND_ROWS]
[STRAIGHT_JOIN]
select_expr_list
[FROM from_list]
[WHERE where_condition]
[GROUP BY group_by_condition_list [WITH ROLLUP]
| GROUP BY [group_by_condition_list] group_by_summary_option (expression_list)]
[HAVING having_condition]
[window_clause]
[ORDER BY order_by_condition_list]
[LIMIT limit_clause]
[lock_option];
select_expr_list:
select_expr [, select_expr ...]
select_expr:
*
| table_name.{* | column_name}
| table_alias_name.{* | column_name}
| expr [[AS] column_alias_name]
from_list:
DUAL
| table_references
| { location_url | table_function }
location_url:
'file_path'
(
{FORMAT = (
TYPE = 'CSV',
LINE_DELIMITER = '<string>' | <expr>,
FIELD_DELIMITER = '<string>' | <expr>,
ESCAPE = '<character>' | <expr>,
FIELD_OPTIONALLY_ENCLOSED_BY = '<character>' | <expr>,
ENCODING = 'charset',
NULL_IF = ('<string>' | <expr>, '<string>' | <expr> ...),
SKIP_HEADER = <int>,
SKIP_BLANK_LINES = { TRUE | FALSE },
PARSE_HEADER = { TRUE | FALSE },
TRIM_SPACE = { TRUE | FALSE },
EMPTY_FIELD_AS_NULL = { TRUE | FALSE }
BYTEORDERMARK = {check | nocheck}
)
| FORMAT = ( TYPE = 'PARQUET' | 'ORC' )
}
[PATTERN = '<regex_pattern>']
)
table_function:
{
FILES (
LOCATION = {'file_path' | @location_name['/path']},
{
FORMAT = (
TYPE = 'CSV',
LINE_DELIMITER = '<string>' | <expr>,
FIELD_DELIMITER = '<string>' | <expr>,
ESCAPE = '<character>' | <expr>,
FIELD_OPTIONALLY_ENCLOSED_BY = '<character>' | <expr>,
ENCODING = 'charset',
NULL_IF = ('<string>' | <expr>, '<string>' | <expr> ...),
SKIP_HEADER = <int>,
SKIP_BLANK_LINES = { TRUE | FALSE },
PARSE_HEADER = { TRUE | FALSE },
TRIM_SPACE = { TRUE | FALSE },
EMPTY_FIELD_AS_NULL = { TRUE | FALSE }
BYTEORDERMARK = {check | nocheck}
)
| FORMAT = ( TYPE = 'PARQUET' | 'ORC' )
},
[PATTERN = '<regex_pattern>']
)
| SOURCE (
TYPE = 'ODPS',
ACCESSID = '<string>',
ACCESSKEY = '<string>',
ENDPOINT = '<string>',
TUNNEL_ENDPOINT = '<string>',
PROJECT_NAME = '<string>',
SCHEMA_NAME = '<string>',
TABLE_NAME = '<string>',
QUOTA_NAME = '<string>',
COMPRESSION_CODE = '<string>'
)
}
where_condition:
expression
group_by_condition_list:
group_by_condition [, group_by_condition ...]
group_by_condition:
expression [ASC | DESC]
group_by_summary_option:
GROUPING SETS
| ROLLUP
| CUBE
expression_list:
expression [, expression ...]
having_condition:
expression
order_by_condition_list:
order_by_condition [, order_by_condition ...]
order_by_condition:
expression [ASC | DESC]
| vector_distance_function(vector_column, query_vector) [ASC | DESC] APPROXIMATE
limit_clause:
[offset,] row_count
| row_count OFFSET offset
lock_option:
locking_clause [locking_clause ...]
locking_clause:
{FOR UPDATE | FOR SHARE} [OF locking_table_list] [opt_for_update_wait]
| LOCK IN SHARE MODE
locking_table_list:
locking_table [, locking_table ...]
locking_table:
table_name
| table_alias_name
| db_name.table_name
opt_for_update_wait:
WAIT {decimal | intnum}
| NOWAIT
| NO_WAIT
| SKIP LOCKED
Parameters
Parameter |
Description |
||
|---|---|---|---|
| select_stmt | The part of the SQL statement that specifies which data to retrieve from the database. | ||
| hint_options | Optional. Specifies thehintOptions. For more information about hints, see Optimizer Hint. |
||
| {DISTINCT \ | UNIQUE} \ | ALL | Optional. Specifies whether duplicate rows are included in the returned result set.
|
| SQL_CACHE \ | SQL_NO_CACHE | Optional. Controls whether the query results are cached.
|
|
| SQL_CALC_FOUND_ROWS | Optional. Used to specify the number of threads in a thread pool.LIMITIn queries with the clause, the total number of rows returned is recorded and can be used in subsequent executions.FOUND_ROWS()The function retrieves the total number of rows. |
||
| STRAIGHT_JOIN | Optional. Forces the optimizer to follow theFROMThe clauses list the tables in order for a sequential join. This tuning command does not affect the execution result.
NoteOceanBase Database is not fully compatible with the |
||
| select_expr_list | Specify the list of columns or expressions to display in the query results. For more information about columns and expressions, see select_expr. | ||
| column_name | Column name. | ||
| FROM from_list | Optional. Specifies the data source for the query, which can be a table, view, or subquery. For more information about data sources, see from_list. | ||
| { table_function \ | location_url } | Optional. The current URL external table supports two syntax forms. For details, see the following section:
|
|
| WHERE where_condition | Optional. Specifies the filter conditions for the query. For more information, see where_condition. | ||
| GROUP BY group_by_condition_list | Optional. Specifies the column or columns on which to group the results. Aggregation functions are often used with this clause. For more information, see group_by_condition. | ||
| WITH ROLLUP | Optional. Summarize each group to represent a higher-level aggregation (also known as super-aggregation), and generate additional rows. | ||
| GROUP BY [group_by_condition_list] group_by_summary_option (expression_list) | Optional. Specifies the group by clause for advanced grouping and summarization operations.
|
||
| HAVING having_condition | Optional. Specifies conditions for filtering the results after grouping.HAVINGstatement andWHEREThe syntax is similar, butHAVINGThe statement can use aggregate functions (such asSUM,AVG(etc.). For more information, see having_condition. |
||
| window_clause | Optional. Specifies the window definition for the analytic function (also called a window function in some databases).window_clauseFor more information about the syntax, see WINDOW clause. |
||
| ORDER BY order_by_condition_list | Optional. Specifies the columns to use for sorting the result set. For more information, see order_by_condition. | ||
| LIMIT limit_clause | Optional. Specifies the number of rows to return in the result set. For more information, see limit_clause. | ||
| lock_option | Optional. Specifies the lock options for the query result. For more information, see lock_option. | ||
| vector_distance_function | Vector distance functions, supportingl2_distance(L2 distance) andcosine_distance(cosine distance). |
||
| vector_column | The name of the vector column, which must be of the VECTOR type. | ||
| query_vector | Query vector, in the format of'[value1, value2, ...]'The dimensionality must match that of the vector column. |
||
| APPROXIMATE | This is a required keyword for enabling approximate search on vector indexes and improving query performance. | ||
| inner_product | The dot product function represents a type of multiplication between two vectors. |
select_expr
select_expr: Indicates the columns or expressions included in the query result. Multiple expressions or column names are separated by commas (,). Valid values:
*: Selects all columns.Example:
Create tables
tbl1andtbl2.CREATE TABLE tbl1(col1 INT PRIMARY KEY, col2 VARCHAR(20), col3 INT) PARTITION BY HASH(col1) PARTITIONS 5;CREATE TABLE tbl2(col1 INT PRIMARY KEY, col2 VARCHAR(20), col3 INT);Insert test data into table
tbl1.INSERT INTO tbl1 VALUES(1, 'A1', 1),(2, 'A2', 2),(3, 'A3', 3);INSERT INTO tbl2 VALUES(1, 'A1', 1),(2, 'A2', 22),(3, 'A3', 33);View the data in table
tbl1.SELECT * FROM tbl1;The return result is as follows:
+------+------+------+ | col1 | col2 | col3 | +------+------+------+ | 1 | A1 | 1 | | 2 | A2 | 2 | | 3 | A3 | 3 | +------+------+------+ 3 rows in set
table_name.{* | column_name}: Select all columns or specified columns from the specified table.table_name.*: Selects all columns from the specified table.table_name.column_name: specifies a column in the table to select.Example:
Read the
col1data from tabletbl1.SELECT tbl1.col1 FROM tbl1;The return result is as follows:
+------+ | col1 | +------+ | 1 | | 2 | | 3 | +------+ 3 rows in set
table_alias_name.{* | column_name}: Similar to the previous format, but uses the table alias when selecting columns.expr [[AS] column_alias_name]: Indicates that you want to select an expression and can assign an alias to it as the column name.expr: a column name, function, or calculation expression.expr AS column_alias_name/expr column_alias_name: selects the expression and names itcolumn_alias_name.
Example:
Reads the data in column
col1from tabletbl1and calculates a new columncol1_add, whose value iscol1 + 1. Additionally, it calculatescol3 * 2to obtain a new columncol3_mul.SELECT col1, col1+1 AS col1_add, col3*2 col3_mul FROM tbl1;The return result is as follows:
+------+----------+----------+ | col1 | col1_add | col3_mul | +------+----------+----------+ | 1 | 2 | 2 | | 2 | 3 | 4 | | 3 | 4 | 6 | +------+----------+----------+ 3 rows in set
from_list
DUAL: Indicates a virtual table name. It is typically used to perform calculations or use functions when no actual table is available.Example:
SELECT 1+1, SYSDATE() FROM DUAL;The return result is as follows:
+------+---------------------+ | 1+1 | SYSDATE() | +------+---------------------+ | 2 | 2024-08-28 15:20:59 | +------+---------------------+ 1 row in settable_references: A list of table references, which can include multiple table references separated by commas (,). This specifies the list of data source tables for the query, which can be a combination of one or more tables. For detailed syntax information abouttable_references, see JOIN clause.
where_condition
expression: A conditional expression that filters the rows to be updated.
Example:
Select all row data from the tbl1 table that satisfy the conditions col1 > 1 and col2 = 'A3'.
SELECT * FROM tbl1
WHERE col1 > 1
AND col2 = 'A3';
The return result is as follows:
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 3 | A3 | 3 |
+------+------+------+
1 row in set
table_function
The LOCATION clause specifies the path for storing external table files. Typically, the data files of an external table are placed in a single directory, which can contain subdirectories. When creating a table, the external table automatically collects all files in this directory. Valid values:
file_path: the path of the external table file. The details are as follows:The local
LOCATIONformat is:LOCATION = '[file:// | sfile://] local_file_path'.file://: This protocol header indicates that when encountering files with the same logical path across multiple OBServer nodes, they are treated as different files and processed separately. Each node independently reads the file from its local path.sfile://: This protocol header indicates that when files with the same logical path are found on multiple OBServer nodes, the system will deduplicate them based on the logical path to ensure only one copy of the data is read (supports multi-server load balancing).Notice
- When using
sfile://, the system performs a consistency check on file sizes. If files under the same logical path have inconsistent sizes across different OBServer nodes, the system reports an errorOB_INVALID_EXTERNAL_FILEto prevent incorrect results caused by data inconsistency. - For version V4.4.2, starting from V4.4.2 BP2, the
sfile://protocol header is supported in the local Location format of theSELECT ... FILES(LOCATION = ...);syntax.
- When using
local_file_path: Can be a relative or absolute path. If a relative path is provided, the current directory must be the installation directory of OceanBase Database.secure_file_privspecifies the file paths that OBServer nodes are authorized to access.local_file_pathmust be a subpath of thesecure_file_privpath.The format of the remote
LOCATIONis as follows:LOCATION = '{oss\|s3}://$ACCESS_ID:$ACCESS_KEY@$HOST:s3_region/remote_file_path', where$ACCESS_ID,$ACCESS_KEY, and$HOSTare the access information required to configure access to Alibaba Cloud OSS, AWS S3, and object storage compatible with the S3 protocol.s3_regionis the region information selected when using S3. This sensitive access information is stored in the database's system tables in an encrypted manner.LOCATION = hdfs://localhost:port/PATH, wherelocalhostis the HDFS address,portis the HDFS port number, andPATHis the directory path in HDFS.With Kerberos authentication:
LOCATION = 'hdfs://localhost:port/user?principal=xxx&keytab=xxx&krb5conf=xxx&configs=xxx'. Here,principal: the user for login authentication.keytab: the path to the keytab file for user authentication.krb5conf: the path to the Kerberos environment description file for the specified user.configs: Specifies additional HDFS configuration parameters. The default is empty, but in a Kerberos environment, this parameter typically has values that need to be configured. For example:dfs.data.transfer.protection=authentication,privacy, which specifies the data transfer protection level asauthenticationandprivacy.
@location_name['/path']: Indicates creating an external table by referencing a Location object.['/path']is optional and specifies a subdirectory. For more information about creating a Location object, see CREATE LOCATION.Note
For OceanBase Database V4.4.x, the
@location_name['/path']parameter is supported starting from V4.4.1.
The FORMAT clause is used to specify attributes related to the file format. It supports three file formats: CSV, PARQUET, and ORC.
When TYPE = 'CSV', the following fields are included:
LINE_DELIMITER: the line delimiter for the CSV file. The default value isLINE_DELIMITER='\n'.FIELD_DELIMITER: Optional. Specifies the column delimiter for the CSV file. The default value isFIELD_DELIMITER='\t'.ESCAPE: Specifies the escape character for the CSV file. It must be 1 byte and defaults toESCAPE ='\'.FIELD_OPTIONALLY_ENCLOSED_BY: Optional. Specifies the character that encloses field values in a CSV file. The default is an empty string. Use this option to indicate that enclosing characters are added only for certain types of fields (such as CHAR, VARCHAR, TEXT, and JSON).ENCODING: Specifies the character set encoding format of the file. If not specified, the default value isUTF8MB4.NULL_IF: The string that will be treated asNULL. The default value is empty.SKIP_HEADER: skips the file header and specifies the number of lines to skip.SKIP_BLANK_LINES: Specifies whether to skip blank lines. The default value isFALSE, which means blank lines are not skipped.TRIM_SPACE: Specifies whether to delete leading and trailing spaces from fields in the file. The default value isFALSE, which means no spaces are deleted.EMPTY_FIELD_AS_NULL: Specifies whether to treat empty strings asNULL. The default value isFALSE, which means empty strings are not treated asNULL.PARSE_HEADER: If this parameter is specified, the first row of the CSV file is directly retrieved and used as column names for each column.Notice
The
PARSE_HEADERandSKIP_HEADERparameters cannot be used together because they conflict in meaning.BYTEORDERMARK: Optional. Specifies whether to detect and skip the BOM character. If this attribute is not specified, BOM character detection is not performed. Valid values:check: detects and skips BOM characters (recommended for files in UTF-8 with BOM format).nocheck: no BOM character detection is performed (applicable to UTF-8 files without BOM characters).
Note
For V4.4.2,
BYTEORDERMARKis supported starting from V4.4.2 BP3.
When TYPE = 'PARQUET/ORC', no additional fields are required.
The
PATTERNclause specifies a regular expression pattern string for filtering files in theLOCATIONdirectory. For each file path in theLOCATIONdirectory, if it matches this pattern string, the external table accesses the file; otherwise, it skips the file. If this parameter is not specified, all files in theLOCATIONdirectory are accessible by default.
For the ODPS format, since data is not retrieved through files and there is no meaningful URL path, only the source form of table_function is supported.
- TYPE = 'ODPS' contains the following fields:
ACCESSID: The ID of the ODPS user.ACCESSKEY: the password of the ODPS user.ENDPOINT: the connection address of the ODPS service.TUNNEL_ENDPOINT: The endpoint of the tunnel data transmission service.PROJECT_NAME: The project containing the table to be queried.SCHEMA_NAME: Optional. Specifies the SCHEMA of the table to be queried.TABLE_NAME: the name of the table to be queried.QUOTA_NAME: Optional. Specifies whether to use the specified quota.COMPRESSION_CODE: Optional. Specifies the compression format for the data source. Valid values are ZLIB, ZSTD, LZ4, and ODPS_LZ4. If not specified, compression is disabled.
Example:
Reads data in ODPS format.
SELECT * FROM
source (
type = 'ODPS',
accessid = '$ODPS_ACCESSID',
accesskey = '$ODPS_ACCESSKEY',
endpoint= '$ODPS_ENDPOINT',
project_name = 'example_project',
schema_name = '',
table_name = 'example_table',
quota_name = '',
compression_code = ''
);
location_url
- The FORMAT clause is used to specify the format-related attributes for reading files. It supports three file formats: CSV, PARQUET, and ORC.
- CSV format: Configure parse_header=true/false to specify whether to parse the first row of the file as column headers (default is false). Additionally, you must use TYPE=CSV to declare the file format (required during export).
- PARQUET/ORC format: The file structure is automatically detected, eliminating the need for an additional header row.
Example:
SELECT * FROM
FILES( location = '/data/',
format (TYPE = 'csv', field_delimiter = ',', parse_header = true),
pattern = 'datafiles$';
group_by_condition
expression [ASC | DESC]: the conditional expression for grouping. Adding ascending order (ASC) or descending order (DESC) specifies whether the order of each group in the resulting set after grouping is ascending or descending.
Example:
Query col1 and col2 from table tbl1, group by col2, sum col3, and output the result.
SELECT col1, col2, SUM(col3)
FROM tbl1
GROUP BY col2 DESC;
The return result is as follows:
+------+------+-----------+
| col1 | col2 | SUM(col3) |
+------+------+-----------+
| 3 | A3 | 3 |
| 2 | A2 | 2 |
| 1 | A1 | 1 |
+------+------+-----------+
3 rows in set
group_by_summary_option
GROUPING SETS: Indicates a custom grouping method, allowing you to specify multiple grouping combinations. It has the following characteristics:- Users can flexibly define the desired grouping combinations.
- The generated result set includes only the grouping combinations specified by the user.
Note
GROUP BY GROUPING SETS ((col1), (col2), (col3))is equivalent toGROUP BY GROUPING SETS (col1, col2, col3).Example:
SELECT col1, col2, col3, COUNT(*) FROM tbl1 GROUP BY GROUPING SETS ((col1), (col2), (col3));The return result is as follows:
+------+------+------+----------+ | col1 | col2 | col3 | COUNT(*) | +------+------+------+----------+ | 1 | NULL | NULL | 1 | | 2 | NULL | NULL | 1 | | 3 | NULL | NULL | 1 | | NULL | A1 | NULL | 1 | | NULL | A2 | NULL | 1 | | NULL | A3 | NULL | 1 | | NULL | NULL | 1 | 1 | | NULL | NULL | 2 | 1 | | NULL | NULL | 3 | 1 | +------+------+------+----------+ 9 rows in setROLLUP: Indicates a hierarchical aggregation method, which reduces the number of grouping columns layer by layer in the order of the grouping columns to generate multi-level summary results. It has the following characteristics:The grouping columns are reduced in order, according to the column sequence in
expression_list, until only a total row remains.The generated result set includes:
- The detailed data for each group.
- Sub-aggregated data for each group.
- Total rows.
ROLLUPcan be considered a special case ofGROUPING SETS. For example:GROUP BY ROLLUP(col1, col2, col3) Equivalent to GROUP BY GROUPING SETS ((col1, col2, col3), (col1, col2), (col1), ())The
ROLLUPclause can also be used together withGROUPING SETS. For example:GROUP BY GROUPING SETS((col2), (col3), ROLLUP(col1, col2, col3)) is equivalent to GROUP BY GROUPING SETS((col2), (col3), (col1, col2, col3), (col1, col2), (col1), ())Example:
SELECT col1, col2, col3, COUNT(*) FROM tbl1 GROUP BY ROLLUP (col1, col2, col3);The return result is as follows:
+------+------+------+----------+ | col1 | col2 | col3 | COUNT(*) | +------+------+------+----------+ | 1 | A1 | 1 | 1 | | 1 | A1 | NULL | 1 | | 1 | NULL | NULL | 1 | | 2 | A2 | 2 | 1 | | 2 | A2 | NULL | 1 | | 2 | NULL | NULL | 1 | | 3 | A3 | 3 | 1 | | 3 | A3 | NULL | 1 | | 3 | NULL | NULL | 1 | | NULL | NULL | NULL | 3 | +------+------+------+----------+ 10 rows in setCUBE: Indicates a multi-dimensional aggregation method used to generate all possible grouping combinations. It has the following characteristics:- The detailed data of each group.
- Summary data for all possible group combinations.
- Total rows.
CUBEcan be regarded as a special case ofGROUPING SETS. For example:GROUP BY CUBE(col1, col2, col3) is equivalent to GROUP BY GROUPING SETS ((col1, col2, col3), (col1, col2), (col1, col3), (col2, col3), (col1), (col2), (col3), ())The
CUBEclause can also be used together with theGROUPING SETSclause. For example:GROUP BY col1, CUBE(col2, col3), GROUPING SETS((col4), (col5)) is equivalent to GROUP BY GROUPING SETS( (col1, col2, col3, col4), (col1, col2, col3, col5), (col1, col2, col4), (col1, col2, col5), (col1, col3, col4), (col1, col3, col5), (col1, col4), (col1, col5))Example:
SELECT col1, col2, col3, COUNT(*) FROM tbl1 GROUP BY CUBE (col1, col2, col3);The return result is as follows:
+------+------+------+----------+ | col1 | col2 | col3 | COUNT(*) | +------+------+------+----------+ | NULL | NULL | NULL | 3 | | NULL | NULL | 1 | 1 | | NULL | NULL | 2 | 1 | | NULL | NULL | 3 | 1 | | NULL | A1 | NULL | 1 | | NULL | A2 | NULL | 1 | | NULL | A3 | NULL | 1 | | NULL | A1 | 1 | 1 | | NULL | A2 | 2 | 1 | | NULL | A3 | 3 | 1 | | 1 | NULL | NULL | 1 | | 2 | NULL | NULL | 1 | | 3 | NULL | NULL | 1 | | 1 | NULL | 1 | 1 | | 2 | NULL | 2 | 1 | | 3 | NULL | 3 | 1 | | 1 | A1 | NULL | 1 | | 2 | A2 | NULL | 1 | | 3 | A3 | NULL | 1 | | 1 | A1 | 1 | 1 | | 2 | A2 | 2 | 1 | | 3 | A3 | 3 | 1 | +------+------+------+----------+ 22 rows in set
having_condition
expression: A conditional expression that filters the results after grouping.
Example:
Query columns col1 and col2 from table tbl1, group by col2, sum col3, find rows where the sum of col3 is less than 3, and output those rows.
SELECT col1, col2, SUM(col3)
FROM tbl1
GROUP BY col2
HAVING SUM(col3) < 3;
The return result is as follows:
+------+------+-----------+
| col1 | col2 | SUM(col3) |
+------+------+-----------+
| 1 | A1 | 1 |
| 2 | A2 | 2 |
+------+------+-----------+
2 rows in set
order_by_condition
expression [ASC | DESC]: the conditional expression used to sort the result set.
ASC | DESC: Optional. Specifies the sorting order. ASC indicates ascending order (default), and DESC indicates descending order.
Example:
Query the data in table tbl1 and output the query results in descending order (DESC) by col3.
SELECT * FROM tbl1
ORDER BY col3 DESC;
The return result is as follows:
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 3 | A3 | 3 |
| 2 | A2 | 2 |
| 1 | A1 | 1 |
+------+------+------+
3 rows in set
limit_clause
[offset,] row_count: The value of this parameter must be an integer constant. The following table describes the possible values.offset: Optional. The number of rows to skip from the start of the result set. The default offset is 0, which means the first record is returned.row_count: the number of rows to return. If only therow_countparameter is used, the firstrow_countrows of the result set are returned.
row_count OFFSET offset: Skips the firstoffsetrows of the result set and returns the nextrow_countrows.
Example:
Query the data in table tbl1. Use LIMIT to force the query to start from the second row and return two rows of results from table tbl1.
SELECT * FROM tbl1
LIMIT 1, 2;
The return result is as follows:
+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
| 2 | A2 | 2 |
| 3 | A3 | 3 |
+------+------+------+
2 rows in set
lock_option
lock_option consists of one or more locking clauses. Multiple locking clauses can be written in the same query block, with each clause independently specifying the tables to lock and the waiting strategy.
{FOR UPDATE | FOR SHARE} [OF locking_table_list] [opt_for_update_wait]: adds an exclusive lock to all rows of the query result set to prevent concurrent modification by other transactions, or to prevent concurrent reads at certain transaction isolation levels. For more information about exclusive locks, see SELECT FOR UPDATE.FOR SHARE: Optional. Supported starting from V4.4.2 BP4 to be compatible with MySQL syntax. Its locking behavior is the same asFOR UPDATE, both acquiring an exclusive row lock on the query results.OF locking_table_list: Optional. Specifies the tables to be locked. Table names, table aliases, and table names qualified by database names are supported. If specified, only the result rows that meet the conditions in the specified base tables are locked; tables not listed are not locked. If omitted, all base tables in the current query block are locked.opt_for_update_wait: Optional. Specifies the behavior for acquiring locks. Valid values:WAIT {decimal | intnum}: the amount of time to wait for other transactions to release resources. If the resources are not released within this period, a return error is returned. The unit is seconds.NOWAIT/NO_WAIT: Indicates not to wait for other transactions to release resources; return immediately if resources cannot be obtained.SKIP LOCKED: Indicates that the query will not wait for row locks and will be executed immediately, removing the locked rows from the result set.
Example:
You can use
SELECT ... FOR UPDATEto acquire a row-level lock on a table. If theLIMIT 1clause is used, the query optimizer will push down the operator to the table scan step, locking only the rows returned by theLIMIT.SELECT * FROM tbl1 LIMIT 1 FOR UPDATE;If you use the
ORDER BYclause to sort the query results, the results are sorted first, and thenLIMIT 1is executed. In this case, locks are acquired for all selected rows.SELECT * FROM tbl1 ORDER BY col1 LIMIT 1 FOR UPDATE;Using
OFallows you to lock only specified tables. Multiple locking clauses can be combined within the same query block. For example, the following statement usesFOR SHAREto locktbl1andFOR UPDATEto locktbl2.SELECT * FROM tbl1, tbl2 WHERE tbl1.col1 = tbl2.col1 FOR SHARE OF tbl1 FOR UPDATE OF tbl2;When using
OF, you can also specify the wait strategy. For example, the following statement returns an error immediately if the target row is already locked by another transaction, without waiting.SELECT * FROM tbl1 FOR SHARE OF tbl1 NOWAIT;
Notice
OFonly supports base tables. An error is returned if the specified object is a view, derived table, outer reference of a CTE, virtual table, or DBLink table. An error is also returned if the specified table is not in theFROMclause of the current query block, or if the same table appears multiple times in different locking clauses.LOCK IN SHARE MODE: Acquires a shared lock while querying data, preventing other transactions from writing to the data but allowing other transactions to read from it. For more information about shared locks, see Locking query results with LOCK IN SHARE MODE.
Examples
Simple table query example
Create the table
test_tbl1.CREATE TABLE test_tbl1(col1 INT PRIMARY KEY, col2 VARCHAR(20), col3 INT);Insert test data into the
test_tbl1table.INSERT INTO test_tbl1 VALUES (1, 'A1', 10),(2, 'A2', 15),(3, 'A1', 8);View the data in column
col2of tabletest_tbl1and perform deduplication.SELECT DISTINCT col2 FROM test_tbl1;The return result is as follows:
+------+ | col2 | +------+ | A1 | | A2 | +------+ 2 rows in set
Example of querying data using dblink
Read from the
number_ttable in the remotetestdatabaseSELECT * FROM number_t@ob_dblink;The return result is as follows:
+--------+-------------+---------+---------------------+--------------------------------+ | c_int | c_bigint | c_float | c_double | c_decimal | +--------+-------------+---------+---------------------+--------------------------------+ | 214748 | 92233720368 | 3.40282 | 1.7976931348623157 | 123456789123456789.1234567890 | +--------+-------------+---------+---------------------+--------------------------------+ 1 row in setRead from the
number_ttable in the remotetestdatabase and perform a JOIN operation with the localnumber_ttable.SELECT a.c_decimal, b.c_double FROM number_t a, number_t@ob_dblink b WHERE a.c_int = b.c_int;The return result is as follows:
+--------------------------------+---------------------+ | c_decimal | c_double | +---------------------+--------------------------------+ | 123456789123456789.1234567890 | 1.7976931348623157 | +---------------------+--------------------------------+ 1 row in setRead the
datetime_ttable from the remotemysqldatabase.SELECT * FROM mysql.datetime_t@ob_dblink;The return result is as follows:
+-------------+------------+---------+----------------------+----------------------+ | c_date | c_time | c_year | c_datetime | c_timestamp | +-------------+------------+---------+-----------------------+---------------------+ | 2023-04-13 | 12:12:12 | 2078 | 2100-11-01 12:12:13 | 2100-12-01 21:14:15 | +-------------+------------+---------+----------------------+----------------------+ 1 row in set
Vector distance query example
Create a table.
CREATE TABLE vector_table ( id INT PRIMARY KEY, name VARCHAR(50), vector_col VECTOR(3) );Insert vector data into the table.
INSERT INTO vector_table VALUES (1, 'A', '[1, 2, 3]'); INSERT INTO vector_table VALUES (2, 'B', '[2, 3, 4]'); INSERT INTO vector_table VALUES (3, 'C', '[3, 4, 5]'); INSERT INTO vector_table VALUES (4, 'D', '[10, 20, 30]'); INSERT INTO vector_table VALUES (5, 'E', '[100, 200, 300]');Create a vector index.
CREATE VECTOR INDEX idx_vector ON vector_table(vector_col) WITH (distance=l2, type=hnsw);Perform vector similarity queries using the L2 distance.
SELECT id, name, vector_col FROM vector_table ORDER BY l2_distance(vector_col, '[2, 3, 4]') APPROXIMATE LIMIT 3;The return result is as follows:
+----+------+-------------+ | id | name | vector_col | +----+------+-------------+ | 2 | B | [2,3,4] | | 3 | C | [3,4,5] | | 1 | A | [1,2,3] | +----+------+-------------+ 3 rows in setPerform vector similarity queries using cosine distance.
SELECT id, name, vector_col FROM vector_table ORDER BY cosine_distance(vector_col, '[2, 3, 4]') APPROXIMATE LIMIT 3;The return result is as follows:
+----+------+-------------+ | id | name | vector_col | +----+------+-------------+ | 2 | B | [2,3,4] | | 3 | C | [3,4,5] | | 1 | A | [1,2,3] | +----+------+-------------+ 3 rows in setPerform vector queries using the WHERE condition.
SELECT id, name, vector_col FROM vector_table WHERE id > 2 ORDER BY l2_distance(vector_col, '[2, 3, 4]') APPROXIMATE LIMIT 2;The return result is as follows:
+----+------+-------------+ | id | name | vector_col | +----+------+-------------+ | 3 | C | [3,4,5] | | 4 | D | [10,20,30] | +----+------+-------------+ 2 rows in set
Notice
The following conditions must be met for a vector distance query:
- You must use the
APPROXIMATEkeyword to enable approximate search for the vector index. - The dimensionality of the query vector
query_vectormust match that of the vector column. - We recommend that you create a vector index on the vector column to improve query performance.
- The supported vector distance functions include
l2_distance(L2 distance),negative_inner_product(negative inner product), andcosine_distance(cosine distance).