CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 2 · Lesson 9/32

    Querying files directly with Spark SQL and choosing save modes

    Execute SQL queries directly on files, including ORC Files, JSON Files, CSV Files, Text Files, and Delta Files, and understand the different save modes for outputting data in Spark SQL.

    17 min read
    5% of exam
    10 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Query ORC, JSON, CSV, text and Delta data in place with the format.path syntax, without creating a table
    • Pick read_files or a temporary view defined with USING when a file needs reader options such as header or a schema
    • Explain why delta.path reads a Delta table through its transaction log, and how time travel is tied to the delta format
    • Predict what append, overwrite, ignore and errorifexists do when the target already exists, and name the default
    • Map the save modes onto INSERT INTO and INSERT OVERWRITE, including how a PARTITION clause limits an overwrite

    Key concept

    A path used as a table name — In Spark SQL, FROM accepts a file format followed by a backquoted storage path, such as orc./mnt/archive/clicks/. The files at that location are read as one relation, and you can filter, aggregate and join it like any table, all without registering one first.

    1.Querying a file path as a table with format.path

    Raw files usually arrive before anyone has defined a table for them: a drop of JSON events, an archive of ORC files, a folder of log lines. Spark SQL can query that data where it already sits. In the FROM clause, write a file format, a dot, and the storage path in backticks, for example json./mnt/raw/events/``. Spark resolves that identifier to the files at the path and returns rows. Nothing is added to the catalog, and nothing remains once the query finishes.

    A path in backticks after the format name stands in for a table namesql
    -- Referencing a path as a table requires back ticks
    > SELECT * FROM delta.`somedir/delta_table`;
    
    > SELECT * FROM `csv`.`spreadsheets/data.csv`;

    Only a fixed set of words can go before the dot: json, csv, avro, parquet, orc, binaryFile, text and delta, matched case-insensitively. The part after the dot is the location of the table in the file system. That location is usually a directory, so json./mnt/raw/events/` reads every file in it as a single relation. With three files of 100 records each, count(*) returns 300. For self-describing formats such as JSON, ORC and Parquet, the schema comes from the file contents, so no column list is required. The caller also needs the ANY_FILE` permission to use this syntax.

    The relation behaves like any other table once it is resolved. SELECT count(*) FROM orc./mnt/archive/clicks/ WHERE event_date = '2026-01-15' filters ORC rows the same way it would filter a catalog table. The format word always goes before the path. Spark SQL has no read_orc() or ORC_TABLE() function, no LOAD ORC statement, and no FROM "path" USING orc clause. The only table-valued function for reading files is read_files, and it takes the format as an option.

    The text format is the exception among file formats because it does no parsing. Each line of the file becomes one row in a single value column of type string, so text./logs/app/`` returns one row per log line, ready for string functions to split. Use it for line-oriented data such as logs. When the data is delimited, CSV parsing into columns is the better fit.

    Checkpoint 1 of 9· Check yourself

    An application writes plain log lines into /logs/app/. What does SELECT * FROM text./logs/app/ return?

    Checkpoint 2 of 9· Exam question

    A data engineer has a directory of newline-delimited JSON files at /mnt/raw/events/ and wants to inspect the data without first creating a table or DataFrame. They run: SELECT count(*) FROM json.`/mnt/raw/events/` The directory contains 3 files, each holding 100 valid JSON records that share a consistent schema. What does this query return?

    Checkpoint 3 of 9· Exam question

    A team stores historical clickstream data as ORC files under /mnt/archive/clicks/ and wants a quick row count for a specific event_date partition column without creating a table. Which SQL statement queries the ORC files directly and filters on that column?

    Sources123

    2.When a file needs options: the limits of direct queries and read_files

    The backtick syntax is short, and the cost of that is configuration. A direct query cannot pass reader options or a schema. For CSV this causes real problems. A CSV file with a header line comes back with the header as an ordinary data row, and with no inferSchema every column is a string. Rewriting the query as csv./mnt/raw/sales.csv` fixes neither problem, because the direct path cannot carry header or inferSchema` either. The fix is to set both options on the reader.

    The DataFrame reader with header and inferSchema set, so the first line supplies column names and numeric columns are typedpython
    # Read the CSV file into a DataFrame
    df = (spark.read
      .format("csv")
      .option("header", "true")
      .option("inferSchema", "true")
      .load("/Volumes/<catalog>/<schema>/<volume>/reviews_csv"))

    In SQL, read_files covers the same need. It is a table-valued function that takes a path and then options as named parameters (format => 'csv', header => true), and it reads JSON, CSV, XML, TEXT, BINARYFILE, PARQUET, AVRO and ORC. It can detect the format and infer one unified schema across all the files. Inference has a cost, though: without a schema, read_files has to read every file unless the query has a LIMIT. For large drops, supply the schema yourself. With CSV, the schema also has to follow the file's column order, because CSV fields are matched to schema fields by position.

    read_files with an explicit schema, so no files are scanned for inferencesql
    SELECT * FROM read_files(
      '/Volumes/<catalog>/<schema>/<volume>/reviews_csv',
      format => 'csv',
      header => true,
      schema => 'review_id string, rating int, comment string'
    )
    Schema that read_files returns for each format
    FormatResulting schema
    TEXTFixed: one value column of type STRING
    BINARYFILEFixed: path, modificationTime, length, content
    JSON, CSV, XML, PARQUET, AVRO, ORCInferred from file contents, or set with the schema option

    read_files also understands Hive-style directory layouts. When files sit under folders such as /event_date=2026-01-15/, it infers event_date as a partition column, so a WHERE clause can filter on it even though the value is not stored inside the files.

    Checkpoint 4 of 9· Fill the gap

    This reader should use the CSV's first line as column names and give numeric columns a numeric type instead of string. Which option name fills the blank?

    # Read the CSV file into a DataFrame
    df = (spark.read
      .format("csv")
      .option("header", "true")
      .option(" ? ", "true")
      .load("/Volumes/<catalog>/<schema>/<volume>/reviews_csv"))

    Checkpoint 5 of 9· Exam question

    A engineer receives a CSV export where the first line holds column names and numeric columns should not be read as strings. They write: df = spark.read.csv("/mnt/raw/sales.csv") df.createOrReplaceTempView("sales") spark.sql("SELECT avg(amount) FROM sales") The query fails because amount is read as a string and the header row product,amount,region appears as a data row. Which change fixes both problems?

    Sources42

    3.A temporary view over a file path with CREATE TEMPORARY VIEW ... USING

    A temporary view is a session-scoped name for a query. Scope and lifetime are covered in Temporary views and global temporary views. For files, the useful form is CREATE TEMPORARY VIEW name USING format OPTIONS (path ..., ...). It records the path and the reader options together once. Every later query then reads the file by its short name, with the options already applied, and no permanent table is created.

    A CSV-backed view that sets header and FAILFAST parsing once, then queries the file by namesql
    CREATE TEMPORARY VIEW diamonds
    USING CSV
    OPTIONS (path "/databricks-datasets/Rdatasets/data-001/csv/ggplot2/diamonds.csv", header "true", mode "FAILFAST");
    
    SELECT * FROM diamonds;

    Any reader option can go into OPTIONS. The mode option sets how malformed records are handled: PERMISSIVE, the default, puts nulls in fields that fail to parse, DROPMALFORMED drops those lines, and FAILFAST aborts the read. JSON that spans several lines per record needs multiline=true here. Without it, the default single-line reader expects exactly one object per line. The view lasts only for the current session. For a one-off query that also needs a schema, Databricks recommends read_files over USING JSON.

    A view over multi-line JSON, where the multiline option is set once on the viewsql
    CREATE TEMPORARY VIEW multiLineJsonTable
    USING json
    OPTIONS (path="/Volumes/<catalog>/<schema>/<volume>/multi-line.json",multiline=true)

    Checkpoint 6 of 9· Match them up

    You are writing the OPTIONS clause of a file-backed temporary view. Match each setting to what it does when the view is read.

    Tap a term, then the definition that fits it.

    Sources45

    4.Querying a Delta table by path

    A Delta table is more than a directory of files. Delta Lake keeps Parquet data files, and alongside them a file-based transaction log that records which changes have been committed. SELECT * FROM delta./path/to/table`` tells Spark to resolve the directory through that log. The result is the table's current committed version, the same data a query against the registered table name would return.

    The log is also what makes time travel possible. A table reference can include a temporal specification, such as VERSION AS OF 3, TIMESTAMP AS OF an expression, or the @V3 shorthand, to read an earlier version. Only Delta keeps that history. Adding a temporal specification to a parquet.path` or orc.path reference raises an error. The same directory read with parquet` is just a set of data files with no transaction history behind it.

    Checkpoint 7 of 9· Check yourself

    A bad job overwrote rows in a Delta table stored at /lake/orders, and nobody registered it in the catalog. To see the data as it was at version 12, which query works?

    Sources61

    5.Save modes: what happens when the target already exists

    Every write has to decide what to do when the target path or table already holds data. The save mode makes that decision, set with DataFrameWriter.mode() or the mode argument of save(). When no format is given, save() writes in the format set by spark.sql.sources.default.

    The four save modes when data already exists at the target
    ModeBehaviour when data exists
    appendNew rows are added to the existing data
    overwriteExisting data is replaced
    error / errorifexists (default)An exception is thrown
    ignoreThe write is silently skipped

    The default is the cautious choice. A scheduled job that runs twice by mistake fails loudly instead of doubling the data or wiping it. Use overwrite for full refreshes, append for incremental loads, and ignore for setup steps that should run only once, such as seeding a reference dataset. ignore gives no warning. If an ignore write was skipped because old data was there, nothing reports it.

    overwrite replaces the path, then append adds a second row, so the read returns bothpython
    import tempfile
    with tempfile.TemporaryDirectory(prefix="mode") as d:
        # Overwrite the path with a new Parquet file
        spark.createDataFrame(
            [{"age": 100, "name": "Alice"}]
        ).write.mode("overwrite").format("parquet").save(d)
    
        # Append another DataFrame into the Parquet file
        spark.createDataFrame(
            [{"age": 120, "name": "Sue"}]
        ).write.mode("append").format("parquet").save(d)

    Checkpoint 8 of 9· Fill the gap

    The first write puts Alice's row at path d. The second write must keep that row and add Sue's, so a later read of d returns both rows. Which save mode fills the blank?

    import tempfile
    with tempfile.TemporaryDirectory(prefix="mode") as d:
        # Overwrite the path with a new Parquet file
        spark.createDataFrame(
            [{"age": 100, "name": "Alice"}]
        ).write.mode("overwrite").format("parquet").save(d)
    
        # Append another DataFrame into the Parquet file
        spark.createDataFrame(
            [{"age": 120, "name": "Sue"}]
        ).write.mode(" ? ").format("parquet").save(d)

    Sources78

    6.The same choices in SQL: INSERT INTO and INSERT OVERWRITE

    SQL has no mode keyword. The choice is built into the statement. INSERT INTO is append: the inserted rows are added to the rows already there. INSERT OVERWRITE is overwrite, and its scope depends on whether a PARTITION clause is present. Without one, the whole table is truncated before the first new row is written. With a partition spec, only the partitions that match it are truncated, and the rest of the table is kept.

    How SQL statements correspond to save modes
    Save modeSQL statementEffect on existing rows
    appendINSERT INTO table_name queryKept; new rows are added
    overwriteINSERT OVERWRITE table_name queryWhole table truncated first
    overwrite, partition-scopedINSERT OVERWRITE table_name PARTITION (...) queryOnly matching partitions truncated

    The partition rule is easy to get wrong. A nightly INSERT OVERWRITE sales SELECT ... WHERE day = current_date() with no PARTITION clause does not replace only today's data. It truncates the entire table and leaves just today's rows. To replace a single day, name the partition statically, for example PARTITION (day = '2026-10-21'). A dynamic partition spec in INSERT OVERWRITE requires the target to be a Delta Lake table. To write files from SQL in the first place, CREATE TABLE ... USING format AS SELECT creates a table of that format from a query result.

    Writing ORC files from SQL with CREATE TABLE ... USING ... AS SELECTsql
    -- Write wanderbricks reviews to ORC format
    CREATE TABLE reviews_orc
    USING ORC
    AS SELECT * FROM samples.wanderbricks.reviews;

    Checkpoint 9 of 9· Check yourself

    Table sales is partitioned by day and holds a year of data. To fix one day's figures, a job runs INSERT OVERWRITE sales SELECT * FROM sales_fixed WHERE day = '2026-10-20'. What does sales contain afterwards?

    Sources9

    Sources

    (10)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “file_format: One of json, csv, avro, parquet, orc, binaryFile, text, delta (case insensitive).”
      ↩︎ Querying a file path as a table with format.path
      “path_to_table: The location of the table in the file system. You must have the ANY_FILE permission to use this syntax.”
      ↩︎ Querying a file path as a table with format.path
      “temporal_spec: When used references a Delta table at the specified point in time or version.”
      ↩︎ Querying a Delta table by path
      “Databricks raises an error if you use a temporal_spec for a table that is not in Delta Lake format.”
      ↩︎ Querying a Delta table by path
      “-- Referencing a path as a table requires back ticks”
      ↩︎ Key concept
      “Databricks raises an error if you use a temporal_spec for a table that is not in Delta Lake format.”
      ↩︎ Exam trap 5
    2. 2.
      “The schema is inferred from the file contents, or provided explicitly using the schema option.”
      ↩︎ Querying a file path as a table with format.path
      “Can detect the file format automatically and infer a unified schema across all files.”
      ↩︎ When a file needs options: the limits of direct queries and read_files
      “This function requires named parameter invocation for the option keys.”
      ↩︎ When a file needs options: the limits of direct queries and read_files
      “read_files attempts to infer a unified schema across the discovered files, which requires reading all the files unless a LIMIT statement is used”
      ↩︎ When a file needs options: the limits of direct queries and read_files
      “read_files can also infer partitioning columns if files are stored under Hive-style partitioned directories, that is /column_name=column_value/.”
      ↩︎ When a file needs options: the limits of direct queries and read_files
    3. 3.
      “The text format reads each line of a text file as a row in a DataFrame with a single value column of type StringType.”
      ↩︎ Querying a file path as a table with format.path
    4. 4.
      “CSV has no column-name metadata, so Spark maps schema fields to columns by position”
      ↩︎ When a file needs options: the limits of direct queries and read_files
      “The view is visible only to the current session and is dropped when the session ends.”
      ↩︎ A temporary view over a file path with CREATE TEMPORARY VIEW ... USING
      “FAILFAST: aborts the reading if any malformed data is found”
      ↩︎ A temporary view over a file path with CREATE TEMPORARY VIEW ... USING
      “If you use SQL to read CSV data directly without using temporary views or read_files, the following limitations apply:”
      ↩︎ Exam trap 1
      “PERMISSIVE (default): nulls are inserted for fields that could not be parsed correctly”
      ↩︎ Checkpoint
    5. 5.
      “Databricks recommends using read_files instead of USING JSON because read_files allows the specification of schema and additional file processing options.”
      ↩︎ A temporary view over a file path with CREATE TEMPORARY VIEW ... USING
    6. 6.
      “Delta Lake is open source software that extends Parquet data files with a file-based transaction log for ACID transactions and scalable metadata handling.”
      ↩︎ Querying a Delta table by path
    7. 8.
      “If format is not specified, the default data source configured by spark.sql.sources.default is used.”
      ↩︎ Save modes: what happens when the target already exists
      “Accepted values are 'append', 'overwrite', 'ignore', and 'error' or 'errorifexists' (default).”
      ↩︎ Exam trap 3
      “Accepted values are 'append', 'overwrite', 'ignore', and 'error' or 'errorifexists' (default).”
      ↩︎ Prediction
    8. 9.
      “If you specify INTO all rows inserted are additive to the existing rows.”
      ↩︎ The same choices in SQL: INSERT INTO and INSERT OVERWRITE
      “Otherwise, all partitions matching the partition_spec are truncated before inserting the first row.”
      ↩︎ The same choices in SQL: INSERT INTO and INSERT OVERWRITE
      “When specifying a dynamic partition for INSERT OVERWRITE, the table_name must be a Delta Lake table.”
      ↩︎ The same choices in SQL: INSERT INTO and INSERT OVERWRITE
      “Without a partition_spec the table is truncated before inserting the first row.”
      ↩︎ Exam trap 4
      “Without a partition_spec the table is truncated before inserting the first row. Otherwise, all partitions matching the partition_spec are truncated before inserting the first row.”
      ↩︎ Checkpoint

    Also cited

    Spotted a mistake, or was something unclear? Tell us.