File reader functions
Use these functions to read Parquet, CSV, JSON, and Avro files in Amazon S3 as rows, or to read each file whole as one text or binary value.
You can also detect the format and column types of a CSV file before you read it. To list the files that a glob pattern matches, use the glob table function.
For a description of the sample tables and files that the examples on this page use, see Table functions in DuckDB.
read_avro function
Reads one or more Avro object container files and returns one row for each record, with one column for each field of the record schema. The function reads each Avro type as the matching type. For example, it reads int as INTEGER, long as BIGINT, string as VARCHAR, a nested record as a STRUCT, and an array as a list. A field whose type is a union with null can hold NULL.
Pass an Amazon S3 path, a path with wildcards, or a list of paths. When you read several files, the result has the columns of the first file. Directories in the form in the paths add a column for each key. To read the header of an Avro file instead of its records, use the avro_metadata function.key=value
Syntax
read_avro(path [, parameter := value [, ...] ])
Arguments
The read_avro function takes the following arguments:
path-
The Amazon S3 location of the Avro files: a
VARCHARpath that can contain wildcards, such as*, or a list of such paths (VARCHAR[]). filename-
An option that adds a column with the path of the file that each row came from. It takes a
BOOLEANorVARCHARvalue. Withtrue, the function adds aVARCHARcolumn namedfilename. AVARCHARvalue adds the same column with that name. This argument is optional. union_by_name-
Not supported by
read_avro. A call that sets it totruefails. hive_partitioning-
An option that controls whether the function adds a column for each
directory in the paths, as akey=valueBOOLEANvalue. Withtrue, it adds these columns, and withfalse, it does not. By default, the function adds these columns when the paths contain such directories. This argument is optional. hive_types-
The types of the partition columns, as a
STRUCTthat maps partition column names to type names, such as{'year': 'INTEGER'}. This argument is optional. hive_types_autocast-
An option that controls whether the function detects the types of partition values, as a
BOOLEANvalue. Withtrue(the default), partition values that look like numbers or dates are read as numbers or dates. Withfalse, they are read asVARCHAR. This argument is optional. schema-
The columns to return and their types, as a
MAP. Each key is either a field ID (INTEGER), to match the columns of the files by field ID, or a column name (VARCHAR), to match them by name. Each value is aSTRUCTwith the fieldsname,type, anddefault_value. This argument is optional. column_statistics-
The column statistics that the engine cannot read from the files, as a
MAPfrom column name to aMAPof statistic names to values. The statistic names aremin,max,count,null_count, anddistinct_count. This argument is optional. allow_empty-
An option that controls what happens when no file matches
path, as aBOOLEANvalue. Withtrue, the function returns no rows instead of an error. The default isfalse. This argument is optional. file_row_number-
Not supported by
read_avro. A call that sets it fails.
Return type
A table with one column for each field of the Avro record schema, read as the matching types, such as BIGINT for long and STRUCT for a nested record. After these columns come the file name and partition columns that you ask for or that the paths provide.
Examples
The following SQL query reads an Avro file, the current manifest list of the Iceberg table orders_iceberg. Each record describes one manifest file of the table: the sequence number at which it was added, its length in bytes, and the number of rows that it added.
SELECT sequence_number, manifest_length, added_rows_count FROM read_avro( 's3://amzn-s3-demo-bucket/tables/orders_iceberg/metadata/snap-2323752575342560560-64614ed3-6f3b-4f64-b8f0-f49b1fdef438.avro' ) ORDER BY sequence_number
The query returns the following results.
| sequence_number | manifest_length | added_rows_count |
|---|---|---|
|
|
|
|
|
|
The following SQL query reads both manifest lists of the table with a wildcard. It sets filename := true to add a column with the path of each record's file, and then counts the distinct files and the records.
SELECT count(DISTINCT filename) AS files, count(*) AS records FROM read_avro( 's3://amzn-s3-demo-bucket/tables/orders_iceberg/metadata/snap-*.avro', filename := true )
The query returns the following result.
| files | records |
|---|---|
|
|
Considerations
The columns come from the first file, so a column that only some of the files have can be left out of the result. The read_avro function does not support union_by_name := true, and a call that sets it fails.
read_blob function
Reads one or more files and returns one row for each file. The content column holds the whole file as one BLOB value, size holds its size in bytes, filename holds its path, and last_modified holds the time it was last changed.
Pass an Amazon S3 path, a path with a wildcard such as *, or a list of paths. Unlike read_text, read_blob does not require the files to hold UTF-8 text, so you can read any file, such as a Parquet file.
Syntax
read_blob(path)
Arguments
The read_blob function takes the following argument:
path-
The file to read, as a
VARCHARAmazon S3 path that can contain wildcards, or a list of such paths (VARCHAR[]).
Return type
A table with the columns filename (VARCHAR), content (BLOB), size (BIGINT), and last_modified (TIMESTAMP WITH TIME ZONE).
Examples
The following SQL query reads the data files of a Parquet table and returns their first four bytes. Every Parquet file starts with the same four bytes, PAR1.
SELECT DISTINCT left(CAST(content AS VARCHAR), 4) AS magic FROM read_blob( 's3://amzn-s3-demo-bucket/tables/sales_parquet/*' )
The query returns the following result.
| magic |
|---|
|
The following SQL query reads the files in one partition directory of the sales_csv table and checks that the size column equals the number of bytes in content.
SELECT count(*) > 0 AS has_files, bool_and( size = octet_length(content) ) AS size_is_byte_count FROM read_blob( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' )
The query returns the following result.
| has_files | size_is_byte_count |
|---|---|
|
|
The following SQL query returns the data type of each column that read_blob returns.
SELECT typeof(filename) AS filename_type, typeof(content) AS content_type, typeof(size) AS size_type, typeof(last_modified) AS last_modified_type FROM read_blob( 's3://amzn-s3-demo-bucket/tables/sales_parquet/*' ) LIMIT 1
The query returns the following result.
| filename_type | content_type | size_type | last_modified_type |
|---|---|---|---|
|
|
|
|
Considerations
To convert the content of a text file to VARCHAR, pass it to decode, or read the file with read_text instead.
read_csv function
Reads one or more delimited text files, such as CSV files, and returns one row for each data line. Unless you set them yourself, read_csv detects the delimiter, the quote and escape characters, and the line ending from a sample of the data. In the same way, it detects a type for each column and whether the first line is a header.
Pass one Amazon S3 path, a glob pattern such as 's3://amzn-s3-demo-bucket/orders/*.csv', or a list of paths and patterns. The files are read as one table. In a glob pattern, * matches any characters within one directory level, and ** matches any number of directory levels. When the paths contain Hive-style directories, the function adds a column for each key, with the value from the directory name.key=value
Use named parameters, written as , to set options, including options that detection would otherwise choose. parameter := valueread_csv_auto takes the same arguments and returns the same result. To see what detection finds for a file without reading all of it, use the sniff_csv function.
Syntax
read_csv(path [, parameter := value [, ...] ])
Arguments
The read_csv function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values, such as['s3://amzn-s3-demo-bucket/a/*.csv', 's3://amzn-s3-demo-bucket/b/*.csv']. header-
An option that controls whether the first line of each file holds column names, as a
BOOLEANvalue. Withtrue, the function reads the first line as column names, and withfalse, it reads the line as data. By default, the function detects this. This argument is optional. delim-
The field delimiter, as a
VARCHARvalue, such as',','|', or';'. By default, it is detected. Other names for this parameter aresep,delimiter, andseparator. This argument is optional. quote-
The quote character, as a
VARCHARvalue, such as'"'. By default, it is detected. This argument is optional. escape-
The character that escapes a quote character inside a quoted field, as a
VARCHARvalue. By default, it is detected. This argument is optional. new_line-
The line ending, as a
VARCHARvalue, such as'\n'or'\r\n'. By default, it is detected. This argument is optional. comment-
The comment character, a
VARCHARvalue with one character, such as'#'. A line that starts with this character is skipped. On other lines, the character and the rest of the line are ignored, unless the character is inside a quoted field. By default, it is detected. This argument is optional. skip-
The number of lines to skip at the start of each file, as a
BIGINTvalue. This argument is optional. columns-
The names and types of the columns, as a
STRUCTthat maps each column name to a type name, such as{'order_id': 'INTEGER', 'amount': 'DECIMAL(10,2)'}. The fields of each line are read into these columns in order, and column detection is turned off. This argument is optional. names-
The column names to use, as a
VARCHAR[]list. The function uses them in order instead of the names from the header line or the generated names. If the list is shorter than the number of columns, the other columns keep their names. Another name for this parameter iscolumn_names. This argument is optional. types-
The types of some or all columns, with detection choosing the rest. Pass a
STRUCTthat maps column names to type names, such as{'amount': 'DECIMAL(10,2)'}, or aVARCHAR[]list of type names in column order. Other names for this parameter aredtypesandcolumn_types. This argument is optional. all_varchar-
An option that controls the types of the columns, as a
BOOLEANvalue. Withtrue, the function reads every column asVARCHAR. This argument is optional. auto_detect-
An option that turns detection on or off, as a
BOOLEANvalue. The default istrue. Withfalse, you must give the columns incolumns, and options that you do not set keep their defaults instead of being detected. This argument is optional. auto_type_candidates-
The type names that detection can choose from, as a
VARCHAR[]list, such as['BIGINT', 'DOUBLE', 'VARCHAR']. This argument is optional. sample_size-
The number of rows that detection reads, as a
BIGINTvalue. A value of-1reads every row. This argument is optional. nullstr-
The strings to read as
NULL, as aVARCHARvalue or aVARCHAR[]list of values, such as'NA'or['NA', '']. By default, an empty field is read asNULL. Another name for this parameter isnull. This argument is optional. dateformat-
The format of
DATEvalues, as aVARCHARformat string, such as'%m/%d/%Y'. Another name for this parameter isdate_format. This argument is optional. timestampformat-
The format of
TIMESTAMPvalues, as aVARCHARformat string, such as'%Y-%m-%d %H:%M:%S'. Another name for this parameter istimestamp_format. This argument is optional. decimal_separator-
The character between the whole and fractional parts of a number, as a
VARCHARvalue, such as','. The default is'.'. This argument is optional. thousands-
The thousands separator in numbers, as a
VARCHARvalue, such as'.'together withdecimal_separator := ','. This argument is optional. normalize_names-
An option that controls whether the function changes the column names from the header line into lowercase identifiers. It takes a
BOOLEANvalue. Withtrue, spaces at the start and end are removed, and each run of spaces inside the name becomes one underscore. Other characters that are not letters, digits, or underscores are removed. A name that starts with a digit, or that is one of many SQL keywords, gets an underscore in front. These keywords includename,value,year, andorder. For example, a headerNamebecomes the column_name. This argument is optional. null_padding-
An option that controls how the function reads a line that has fewer fields than the other lines, as a
BOOLEANvalue. Withtrue, it reads such a line withNULLfor the missing fields. This argument is optional. ignore_errors-
An option that controls how the function handles errors in the data, as a
BOOLEANvalue. Withtrue, it skips lines whose fields cannot be read or converted to the column types, instead of failing the query. This argument is optional. max_line_size-
The longest line, in bytes, that the function reads, as a
BIGINTvalue. A longer line fails the query. Another name for this parameter ismaximum_line_size. This argument is optional. compression-
The compression of the files, as a
VARCHARvalue:'auto'(the default),'none','gzip', or'zstd'. With'auto', the function detects the compression from the file name extension, such as.gz. This argument is optional. encoding-
The character encoding of the files, as a
VARCHARvalue, such as'utf-8'(the default),'latin-1', or'utf-16'. This argument is optional. filename-
An option that adds a column with the path of the file that each row came from. It takes a
BOOLEANorVARCHARvalue. Withtrue, the function adds aVARCHARcolumn namedfilename. AVARCHARvalue adds the same column with that name. This argument is optional. hive_partitioning-
An option that controls whether the function adds a column for each
directory in the paths, as akey=valueBOOLEANvalue. Withtrue, it adds these columns, and withfalse, it does not. By default, the function adds these columns when the paths contain such directories. This argument is optional. hive_types-
The types of the partition columns, as a
STRUCTthat maps partition column names to type names, such as{'year': 'INTEGER'}. This argument is optional. hive_types_autocast-
An option that controls whether the function detects the types of partition values, as a
BOOLEANvalue. Withtrue(the default), partition values that can be read as a date, a timestamp, or a whole number are read asDATE,TIMESTAMP, orBIGINT. Other values are read asVARCHAR. Withfalse, they are read asVARCHAR. This argument is optional. union_by_name-
An option that controls how the function matches the columns of different files, as a
BOOLEANvalue. Withtrue, it matches them by name instead of by position, and fills a column that a file does not have withNULL. This argument is optional. allow_quoted_nulls-
An option that controls whether a quoted value can be read as
NULL, as aBOOLEANvalue. Withtrue(the default), a quoted value that matchesnullstr, such as""for an empty string, is read asNULL. Withfalse, quoted values are never read asNULL. This argument is optional.
Return type
A table with one column for each field in the files, followed by the file name and partition columns that you ask for or that the paths provide. Detection gives each column a type such as BIGINT, DOUBLE, DATE, TIMESTAMP, or VARCHAR. Without a header line, the columns are named column0, column1, and so on.
Examples
The following SQL query reads the CSV files in one partition directory. The files have no header line, so read_csv names the columns column0, column1, and column2, and the query renames them with AS. The region column comes from the region=east directory name.
SELECT column0 AS order_id, column1 AS customer, column2 AS amount, region FROM read_csv( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' ) ORDER BY column0
The query returns the following results.
| order_id | customer | amount | region |
|---|---|---|---|
|
|
|
|
|
|
|
|
The following SQL query names the columns and sets their types with columns, so amount is read as DECIMAL(10,2) instead of the detected DOUBLE.
SELECT order_id, customer, amount, typeof(amount) AS amount_type FROM read_csv('s3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*', header := false, columns := { 'order_id': 'INTEGER', 'customer': 'VARCHAR', 'amount': 'DECIMAL(10,2)' }) ORDER BY order_id
The query returns the following results.
| order_id | customer | amount | amount_type |
|---|---|---|---|
|
|
|
|
|
|
|
|
The following SQL query reads every partition directory with one glob pattern and names the columns with names. It returns the number of orders and the total amount for each value of the region partition column.
SELECT region, count(*) AS orders, sum(amount) AS total FROM read_csv('s3://amzn-s3-demo-bucket/tables/sales_csv/*/*', header := false, names := ['order_id', 'customer', 'amount']) GROUP BY region ORDER BY region
The query returns the following results.
| region | orders | total |
|---|---|---|
|
|
|
|
|
|
|
|
|
Considerations
read_csv detects whether the first line is a header line. If detection gets this wrong, set header. A file without a header line gets the column names column0, column1, and so on. To choose the column names, set names or columns.
When you set nullstr, an empty field is no longer read as NULL. To keep that, list the empty string as well, for example nullstr := ['NA', ''].
If no file matches path, the query fails.
These reads do not go through the AWS Glue Data Catalog, so AWS Glue and Lake Formation permissions do not apply to them. Your IAM permissions for Amazon S3 do. For more information about these permissions, see Reading files by Amazon S3 path.
A view cannot call read_csv. For more information about what a view can read, see What a view can read.
read_json function
Reads one or more JSON files and returns one row for each top-level JSON object, with one column for each key. The read_json function detects the layout of the files, the keys, and a type for each key, including STRUCT types for nested objects and list types for arrays.
The files can hold newline-delimited JSON, with one object on each line, as in the files of a Hive JSON table. They can also hold a top-level JSON array whose elements become the rows, or JSON values in any layout, such as one object written over many lines. Pass one Amazon S3 path, a glob pattern, or a list of paths and patterns. The files are read as one table, and Hive-style directories in the paths add a column for each key, as with key=valueread_csv.
read_json_auto takes the same arguments and returns the same result. read_ndjson reads newline-delimited JSON only. To get each object as one JSON value instead of as columns, use the read_json_objects function.
Syntax
read_json(path [, parameter := value [, ...] ])
Arguments
The read_json function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values. columns-
The keys to read and their types, as a
STRUCTthat maps each key to a type name, such as{'order_id': 'INTEGER', 'amount': 'DECIMAL(10,2)'}. The function returns only these columns, with these types, and does not detect others. This argument is optional. format-
The layout of the files, as a
VARCHARvalue. The default,'auto', detects the layout. With'newline_delimited'(or'nd'), the files hold one JSON value on each line. With'array', they hold a top-level JSON array whose elements are the rows. With'unstructured', they hold JSON values in any layout. This argument is optional. records-
An option that controls whether each object is split into columns:
'auto'(the default),true, orfalse. Withtrue, each object becomes a row with a column for each key. Withfalse, each value is returned whole in one column namedjson. This argument is optional. auto_detect-
An option that turns detection on or off, as a
BOOLEANvalue. The default istrue. Withfalse, you must give the columns incolumns. This argument is optional. sample_size-
The number of JSON values that detection reads, as a
BIGINTvalue. A value of-1reads every value. This argument is optional. maximum_depth-
The number of nesting levels that detection gives types to, as a
BIGINTvalue. Values nested deeper are returned asJSON. For example,maximum_depth := 1returns every column asJSON. This argument is optional. dateformat-
The format of
DATEvalues in strings, as aVARCHARformat string, such as'%m/%d/%Y'. Another name for this parameter isdate_format. This argument is optional. timestampformat-
The format of
TIMESTAMPvalues in strings, as aVARCHARformat string, such as'%Y-%m-%d %H:%M:%S'. Another name for this parameter istimestamp_format. This argument is optional. ignore_errors-
An option that controls how the function handles errors in the data, as a
BOOLEANvalue. Withtrue, a line of newline-delimited JSON that is not valid JSON becomes a row ofNULLvalues instead of failing the query. Withtrue, a value that cannot be converted to its column type also becomesNULL. In the other layouts, JSON that is not valid still fails the query. This argument is optional. case_insensitive_keys-
An option that controls how the function reads keys that differ only in case, as a
BOOLEANvalue. Withtrue, such keys, for exampleIDandid, are read into one column. This argument is optional. convert_strings_to_integers-
An option that controls the type that detection gives to strings that hold whole numbers, as a
BOOLEANvalue. Withtrue, string values that hold whole numbers, such as"12", are detected asBIGINTinstead ofVARCHAR. This argument is optional. compression-
The compression of the files, as a
VARCHARvalue:'auto'(the default),'none','gzip', or'zstd'. With'auto', the function detects the compression from the file name extension, such as.gz. This argument is optional. maximum_object_size-
The largest size, in bytes, of one JSON value, as a
UINTEGERvalue. The default is16777216(16 MB). A JSON value that is larger fails the query. You can raise this limit, but a value smaller than the default has no effect. This argument is optional. filename-
An option that adds a column with the path of the file that each row came from. It takes a
BOOLEANorVARCHARvalue. Withtrue, the function adds aVARCHARcolumn namedfilename. AVARCHARvalue adds the same column with that name. This argument is optional. hive_partitioning-
An option that controls whether the function adds a column for each
directory in the paths, as akey=valueBOOLEANvalue. Withtrue, it adds these columns, and withfalse, it does not. By default, the function adds these columns when the paths contain such directories. This argument is optional. hive_types-
The types of the partition columns, as a
STRUCTthat maps partition column names to type names, such as{'year': 'INTEGER'}. This argument is optional. hive_types_autocast-
An option that controls whether the function detects the types of partition values, as a
BOOLEANvalue. Withtrue(the default), partition values that can be read as a date, a timestamp, or a whole number are read asDATE,TIMESTAMP, orBIGINT. Other values are read asVARCHAR. Withfalse, they are read asVARCHAR. This argument is optional. union_by_name-
An option that controls how the function combines files that have different keys, as a
BOOLEANvalue. Withtrue, it combines their keys, and fills a column that a file does not have withNULL. This argument is optional.
Return type
A table with one column for each key of the JSON objects, followed by the file name and partition columns that you ask for or that the paths provide. Detection gives each column a type such as BIGINT, DOUBLE, VARCHAR, BOOLEAN, DATE, TIMESTAMP, a STRUCT, or a list type such as VARCHAR[]. A key whose values have different types, such as a number in one object and a string in another, gets the type JSON.
Examples
The following SQL query reads the newline-delimited JSON files of a Hive JSON table. Each key becomes a column.
SELECT order_id, customer, amount FROM read_json( 's3://amzn-s3-demo-bucket/tables/sales_json/*' ) ORDER BY order_id
The query returns the following results.
| order_id | customer | amount |
|---|---|---|
|
|
|
|
|
|
The following SQL query sets the columns and their types with columns, so amount is read as DECIMAL(10,2) instead of the detected DOUBLE.
SELECT order_id, amount, typeof(amount) AS amount_type FROM read_json('s3://amzn-s3-demo-bucket/tables/sales_json/*', columns := { 'order_id': 'INTEGER', 'customer': 'VARCHAR', 'amount': 'DECIMAL(10,2)' }) ORDER BY order_id
The query returns the following results.
| order_id | amount | amount_type |
|---|---|---|
|
|
|
|
|
|
The following SQL query reads the metadata file of the Iceberg table orders_iceberg and returns two of its fields. The metadata file is a JSON document that holds one object. To select a key that contains a hyphen, such as format-version, put the key in double quotes. The result shows that the table uses format version 2 and has two snapshots.
SELECT "format-version" AS format_version, len(snapshots) AS snapshot_count FROM read_json( 's3://amzn-s3-demo-bucket/tables/orders_iceberg/metadata/00003-7f27ce45-a215-4b96-aa29-cfc276a81182.metadata.json' )
The query returns the following result.
| format_version | snapshot_count |
|---|---|
|
|
Considerations
Detection reads a sample of the JSON values. If a key first appears after the sample, a query that reads every column, such as SELECT *, fails. A query that reads only some of the columns ignores the key. To read it, list the key in columns, or raise sample_size.
Keys are case-sensitive by default, so ID and id become two columns, and the second one gets a suffix, such as id_1. To read them into one column, set case_insensitive_keys := true.
These reads do not go through the AWS Glue Data Catalog, so AWS Glue and Lake Formation permissions do not apply to them. Your IAM permissions for Amazon S3 do. For more information about these permissions, see Reading files by Amazon S3 path.
A view cannot call read_json. For more information about what a view can read, see What a view can read.
read_json_objects function
Returns one row for each top-level JSON value in the files, in a single column named json of type JSON. Unlike read_json, it does not split objects into columns or detect types, so objects with different keys can share the files. To read fields, use the JSON functions and operators on the json column, such as ->> and json_extract.
It detects the layout of the files: newline-delimited JSON, a top-level JSON array whose elements become the rows, or JSON values in any layout. The read_json_objects_auto function takes the same arguments and returns the same result, and read_ndjson_objects reads newline-delimited JSON only.
Syntax
read_json_objects(path [, parameter := value [, ...] ])
Arguments
The read_json_objects function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values. format-
The layout of the files, as a
VARCHARvalue:'auto'(the default),'newline_delimited'(or'nd'),'array', or'unstructured', as forread_json. This argument is optional. ignore_errors-
An option that controls how the function handles errors in the data, as a
BOOLEANvalue. Withtrue, a line that is not valid JSON returnsNULLinstead of failing the query. This argument is optional. compression-
The compression of the files, as a
VARCHARvalue:'auto'(the default),'none','gzip', or'zstd'. With'auto', the function detects the compression from the file name extension. This argument is optional. maximum_object_size-
The largest size, in bytes, of one JSON value, as a
UINTEGERvalue. The default is16777216(16 MB). A JSON value that is larger fails the query. You can raise this limit, but a value smaller than the default has no effect. This argument is optional. filename-
An option that adds a column with the path of the file that each row came from. It takes a
BOOLEANorVARCHARvalue. Withtrue, the function adds aVARCHARcolumn namedfilename. AVARCHARvalue adds the same column with that name. This argument is optional. hive_partitioning-
An option that controls whether the function adds a column for each
directory in the paths, as akey=valueBOOLEANvalue. Withtrue, it adds these columns, and withfalse, it does not. By default, the function adds these columns when the paths contain such directories. This argument is optional.
Return type
A table with a column named json of type JSON, followed by the file name and partition columns that you ask for or that the paths provide.
Examples
The following SQL query reads each JSON object whole and extracts two fields with the ->> operator.
SELECT CAST(json ->> 'order_id' AS INTEGER) AS order_id, json ->> 'customer' AS customer FROM read_json_objects( 's3://amzn-s3-demo-bucket/tables/sales_json/*' ) ORDER BY order_id
The query returns the following results.
| order_id | customer |
|---|---|
|
|
|
|
The following SQL query counts all objects and the objects that have a discount key. No object has that key, so ->> returns NULL for every row and the second count is 0.
SELECT count(*) AS orders, count(json ->> 'discount') AS orders_with_discount FROM read_json_objects( 's3://amzn-s3-demo-bucket/tables/sales_json/*' )
The query returns the following result.
| orders | orders_with_discount |
|---|---|
|
|
Considerations
A key that an object does not have returns NULL from ->>, so you can read files whose objects have different keys without errors.
read_ndjson function
Reads files that hold one JSON value on each line, such as the files of a Hive JSON table. It returns one row for each line, with a column for each key. It works like read_json with format := 'newline_delimited', and it takes the same path argument and named parameters as read_json.
read_ndjson_auto takes the same arguments and returns the same result. For more information about the named parameters, see read_json function.
Syntax
read_ndjson(path [, parameter := value [, ...] ])
Arguments
The read_ndjson function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values. parameter-
A named parameter, written as
. It can be any named parameter ofparameter:=valueread_json, such ascolumns,ignore_errors, orsample_size. This argument is optional.
Return type
A table with one column for each key of the JSON objects, as for read_json. Detection gives each column a type such as BIGINT, DOUBLE, VARCHAR, or a STRUCT.
Examples
The following SQL query reads the newline-delimited JSON files of a Hive JSON table.
SELECT order_id, customer, amount FROM read_ndjson( 's3://amzn-s3-demo-bucket/tables/sales_json/*' ) ORDER BY order_id
The query returns the following results.
| order_id | customer | amount |
|---|---|---|
|
|
|
|
|
|
The following SQL query counts the lines, one for each JSON object.
SELECT count(*) AS orders FROM read_ndjson( 's3://amzn-s3-demo-bucket/tables/sales_json/*' )
The query returns the following result.
| orders |
|---|
|
Considerations
read_ndjson does not look for a top-level JSON array. A file that holds one array on one line, even an array of objects, is read as one value. The result is one row with a single column named json that holds the whole array as a list. An array written over several lines fails the query, because each line must be a complete JSON value. To read the elements as rows, use the read_json function.
read_ndjson_objects function
Returns one row for each line of the files, with the JSON value on that line in a single column named json of type JSON. It works like read_json_objects with format := 'newline_delimited', and it takes the same arguments as read_json_objects.
For more information about the arguments, see read_json_objects function.
Syntax
read_ndjson_objects(path [, parameter := value
[, ...] ])
Arguments
The read_ndjson_objects function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values. parameter-
A named parameter, written as
. It can be any named parameter ofparameter:=valueread_json_objects, such asignore_errorsorcompression. This argument is optional.
Return type
A table with a column named json of type JSON, as for read_json_objects.
Examples
The following SQL query reads each line as a JSON value and extracts the amount field as a DOUBLE.
SELECT json ->> 'customer' AS customer, CAST(json -> 'amount' AS DOUBLE) AS amount FROM read_ndjson_objects( 's3://amzn-s3-demo-bucket/tables/sales_json/*' ) ORDER BY customer
The query returns the following results.
| customer | amount |
|---|---|
|
|
|
|
Considerations
A file that holds one top-level JSON array on one line returns one row, with the whole array as one JSON value. An array written over several lines fails the query, because each line must be a complete JSON value. To get the elements as rows, use the read_json_objects function.
read_parquet function
Reads one or more Apache Parquet files and returns their rows, with the column names and types that are stored in the files. Nothing is detected from the data, because a Parquet file records its own schema.
Pass one Amazon S3 path, a glob pattern such as 's3://amzn-s3-demo-bucket/orders/*.parquet', or a list of paths and patterns. The files are read as one table. By default, the columns come from the first file, and every other file must have those columns. To combine files whose columns differ, set union_by_name := true. Hive-style directories in the paths add a column for each key, as with key=valueread_csv.
parquet_scan is an alias of read_parquet.
Syntax
read_parquet(path [, parameter := value [, ...] ])
Arguments
The read_parquet function takes the following arguments:
path-
The files to read, as a
VARCHARAmazon S3 path of a file or a glob pattern, or aVARCHAR[]list of such values. binary_as_string-
An option that controls how the function reads Parquet binary columns that have no string annotation, as a
BOOLEANvalue. Withtrue, it reads them asVARCHARinstead ofBLOB. This argument is optional. filename-
An option that adds a column with the path of the file that each row came from. It takes a
BOOLEANorVARCHARvalue. Withtrue, the function adds aVARCHARcolumn namedfilename. AVARCHARvalue adds the same column with that name. This argument is optional. file_row_number-
An option that adds a column with the position of each row in its file, as a
BOOLEANvalue. Withtrue, the function adds aBIGINTcolumn namedfile_row_number. The positions start at0. This argument is optional. hive_partitioning-
An option that controls whether the function adds a column for each
directory in the paths, as akey=valueBOOLEANvalue. Withtrue, it adds these columns, and withfalse, it does not. By default, the function adds these columns when the paths contain such directories. This argument is optional. hive_types-
The types of the partition columns, as a
STRUCTthat maps partition column names to type names, such as{'year': 'INTEGER'}. This argument is optional. hive_types_autocast-
An option that controls whether the function detects the types of partition values, as a
BOOLEANvalue. Withtrue(the default), partition values that can be read as a date, a timestamp, or a whole number are read asDATE,TIMESTAMP, orBIGINT. Other values are read asVARCHAR. Withfalse, they are read asVARCHAR. This argument is optional. union_by_name-
An option that controls how the function combines files whose columns differ, as a
BOOLEANvalue. Withtrue, it returns every column of every file, and fills a column that a file does not have withNULL. This argument is optional.
Return type
A table with the columns stored in the Parquet files, with types such as INTEGER, BIGINT, DECIMAL, DOUBLE, VARCHAR, DATE, TIMESTAMP, and BLOB. After these columns come the file name, row number, and partition columns that you ask for or that the paths provide.
Examples
The following SQL query reads the Parquet files of a Hive table and returns the orders for one region. One order has no amount, so its amount is NULL.
SELECT order_id, customer, amount FROM read_parquet( 's3://amzn-s3-demo-bucket/tables/sales_parquet/*' ) WHERE region = 'east' ORDER BY order_id
The query returns the following results.
| order_id | customer | amount |
|---|---|---|
|
|
|
|
|
|
|
|
|
The following SQL query counts the orders and adds up the amounts for each region. sum skips the NULL amount.
SELECT region, count(*) AS orders, sum(amount) AS total FROM read_parquet( 's3://amzn-s3-demo-bucket/tables/sales_parquet/*' ) GROUP BY region ORDER BY region
The query returns the following results.
| region | orders | total |
|---|---|---|
|
|
|
|
|
|
|
|
|
Considerations
By default, the result has the columns of the first file, and the columns of each other file are matched to them by name. If another file does not have one of those columns, the query fails. A column that only other files have is left out of the result without an error. To read every column of every file, set union_by_name := true.
You can also read a Parquet file by putting its quoted Amazon S3 path in place of a table name, as in FROM 's3://amzn-s3-demo-bucket/data/orders.parquet'. To set options, such as filename or union_by_name, call read_parquet instead. For more information about the sources that a FROM clause can read, see FROM clause.
These reads do not go through the AWS Glue Data Catalog, so AWS Glue and Lake Formation permissions do not apply to them. Your IAM permissions for Amazon S3 do. For more information about these permissions, see Reading files by Amazon S3 path.
A view cannot call read_parquet. For more information about what a view can read, see What a view can read.
read_text function
Reads one or more files as text and returns one row for each file. The content column holds the whole file as one VARCHAR value, size holds its size in bytes, filename holds its path, and last_modified holds the time it was last changed.
Pass an Amazon S3 path, a path with a wildcard such as *, or a list of paths. To split the content into lines or fields, combine read_text with string functions such as string_split. For more information about string functions, see String functions and operators in DuckDB.
Syntax
read_text(path)
Arguments
The read_text function takes the following argument:
path-
The file to read, as a
VARCHARAmazon S3 path that can contain wildcards, or a list of such paths (VARCHAR[]).
Return type
A table with the columns filename (VARCHAR), content (VARCHAR), size (BIGINT), and last_modified (TIMESTAMP WITH TIME ZONE).
Examples
The following SQL query reads the files in one partition directory of the sales_csv table and returns one row for each line of their content. The expression chr(10) returns the newline character. The rtrim function removes the newline at the end of each file, and string_split splits the rest of the content at each newline.
SELECT line FROM ( SELECT unnest( string_split( rtrim(content, chr(10)), chr(10) ) ) AS line FROM read_text( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' ) ) ORDER BY line
The query returns the following results.
| line |
|---|
|
|
The following SQL query returns the data type of each column that read_text returns.
SELECT typeof(filename) AS filename_type, typeof(content) AS content_type, typeof(size) AS size_type, typeof(last_modified) AS last_modified_type FROM read_text( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' ) LIMIT 1
The query returns the following result.
| filename_type | content_type | size_type | last_modified_type |
|---|---|---|---|
|
|
|
|
Considerations
Each file must contain valid UTF-8 text. If a file does not, the query fails. To read binary files, use the read_blob function.
sniff_csv function
Reads the start of one delimited text file and returns one row that describes it. The row gives the delimiter, the quote and escape characters, the line ending, the comment character, and the number of lines skipped. It also shows whether the file has a header line, and gives the columns, their types, and the date and timestamp formats. These are the options that read_csv detects for the same file.
Pass any CSV parameter of read_csv to set that option yourself. sniff_csv then detects only the rest, and the UserArguments column lists what you set. If you set columns and its types differ from the detected types, or the file has a header line whose names differ from the names in columns, the query fails. To get a row anyway, set force_match := false. The Prompt column holds a read_csv call with every option written out, which you can reuse to read the file without detection.
Syntax
sniff_csv(path [, parameter := value [, ...] ])
Arguments
The sniff_csv function takes the following arguments:
path-
The file to read, as a
VARCHARAmazon S3 path of one file or a glob pattern that matches one file. parameter-
A CSV parameter of
read_csv, such asdelim,header,names, orsample_size, written as. For more information about these parameters, see read_csv function. This argument is optional.parameter:=value
Return type
A table with one row and these columns, in this order: Delimiter, Quote, Escape, NewLineDelimiter, Comment, SkipRows, HasHeader, Columns, DateFormat, TimestampFormat, UserArguments, and Prompt. SkipRows is a UINTEGER, HasHeader is a BOOLEAN, and Columns is a list of STRUCT(name VARCHAR, type VARCHAR) values, one for each column in the file. The other columns are VARCHAR.
Examples
The following SQL query detects the delimiter, whether there is a header line, and the number of columns of a CSV file.
SELECT Delimiter AS delimiter, HasHeader AS has_header, len(Columns) AS column_count FROM sniff_csv( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' )
The query returns the following result.
| delimiter | has_header | column_count |
|---|---|---|
|
|
|
The following SQL query returns one row for each detected column, with its name and type.
SELECT c.name AS column_name, c.type AS column_type FROM (SELECT unnest(Columns) AS c FROM sniff_csv( 's3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*' )) ORDER BY column_name
The query returns the following results.
| column_name | column_type |
|---|---|
|
|
|
|
|
|
The following SQL query sets the column names with names. The detected columns take those names, so the first column is order_id instead of the generated name column0.
SELECT HasHeader AS has_header, Columns[1].name AS first_column FROM sniff_csv('s3://amzn-s3-demo-bucket/tables/sales_csv/region=east/*', names := ['order_id', 'customer', 'amount'])
The query returns the following result.
| has_header | first_column |
|---|---|
|
|
Considerations
A glob pattern that matches more than one file fails the query. Point sniff_csv at one file.
An option that the file does not use, such as a quote character in a file without quotes, is shown as the string (empty).
The Prompt text starts with FROM read_csv( and ends with a semicolon.