Query execution
You can use the ydb sql subcommand to execute an SQL query. The query can be of any type (DDL, DML, etc.) and can consist of several subqueries. The ydb sql subcommand establishes a streaming connection and retrieves data through it. With in-stream query execution, no limit is imposed on the amount of data read. Data can also be written using this command, which is more efficient when executing repeated queries with data passed through parameters.
General format of the command:
ydb [global options...] sql [options...]
global options: Global parameters.options: Subcommand parameters.
View the description of the query execution command:
ydb sql --help
Parameters of the subcommand
|
Name |
Description |
|
|
Print general usage help. |
|
|
Print complete usage help, including specific commands not shown with |
|
|
Script (query) text to execute. |
|
|
Path to a file with query text to execute. Path |
|
|
Statistics mode.
|
|
|
Execute an explain request for the query. Displays the query's logical plan. The query is not actually executed and does not affect database data. |
|
|
Same as |
|
|
Execute the query in |
|
|
Output format.
|
Working with parameterized queries
For a detailed description with examples on how to use parameterized queries, see Executing parameterized queries.
Examples
Note
The examples use the quickstart profile. To learn more, see Creating a profile to connect to a test database.
Running DDL and DML together in a single query is not supported.
# Creating a table
ydb -p quickstart sql -s '
CREATE TABLE series (
series_id Uint64,
title Utf8,
series_info Utf8,
release_date Date,
PRIMARY KEY (series_id)
);
'
# Populating with data and retrieving a sample
ydb -p quickstart sql -s '
UPSERT INTO series (series_id, title, series_info, release_date)
VALUES (1, "Title1", "Info1", Cast("2023-04-20" as Date));
SELECT * FROM series;
'
# Adding an index
ydb -p quickstart sql -s '
ALTER TABLE series
ADD INDEX title_idx GLOBAL ON (title);
'
Command output:
┌──────────────┬───────────┬─────────────┬──────────┐
| release_date | series_id | series_info | title |
├──────────────┼───────────┼─────────────┼──────────┤
| "2023-04-20" | 1 | "Info1" | "Title1" |
└──────────────┴───────────┴─────────────┴──────────┘
To run a query from a file (for example, script1.yql) with JSON output
ydb -p quickstart sql -f script1.yql --format json-unicode
Command output:
{"release_date":"2023-04-20","series_id":1,"series_info":"Info1","title":"Title1"}
Examples of passing parameters to scripts are given in the article on passing parameters to query execution commands.