Jump to content

Spark SQL scripting

From Open Lakehouse Wiki
Revision as of 00:52, 25 November 2026 by Open Lakehouse Wiki sync (talk | contribs) (Sync from open-lakehouse/wiki@7c9abaa)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Spark SQL scripting
Also known as SQL Scripting, procedural SQL in Spark
Field SQL query engines
Key parts Compound statement (BEGIN ... END), local variables, IF, CASE, WHILE, REPEAT, LOOP, FOR, LEAVE, ITERATE, condition handlers, cursors
Open source implementations Apache Spark
Related Spark error classes, Spark SQL ANSI mode, SQL pipe syntax
Last verified 23 November 2026 against the v4.3.0 tag of apache/spark (docs/sql-ref-scripting.md, docs/control-flow/*.md, SqlBaseParser.g4, AstBuilder.scala, SQLConf.scala, classic SparkSession.scala), SPARK-48338, SPARK-54499 and the Spark 4.1.0 and 4.2.0 release notes.

In Apache Spark, SQL scripting is the procedural extension of Spark SQL that runs a block of statements written between BEGIN and END, with local variables, loops, conditional logic and error handlers, as a single request. The Spark documentation describes the syntax as based on the SQL/PSM standard.[1] SQL scripting lets ETL and analysis logic that used to need Python or Scala driver code stay entirely in SQL; the umbrella ticket also names it as a step toward stored procedures and data warehouse migrations.[2]

Is SQL scripting enabled by default?

Yes, since Spark 4.1.0. The Spark 4.1.0 release notes state that SQL Scripting is generally available (GA) and enabled by default (SPARK-54499).[3][4] The switch is spark.sql.scripting.enabled, a configuration added in Spark 4.0.0 whose default in Spark 4.3.0 is true. Its description in the 4.3.0 source still calls the feature "under development", a wording older than the GA decision.[5]

Two parts of SQL scripting stay behind internal flags in Spark 4.3.0, both off by default. CONTINUE handlers need spark.sql.scripting.continueHandlerEnabled (added in 4.1.0), and cursors (DECLARE CURSOR, OPEN, FETCH, CLOSE) need spark.sql.scripting.cursorEnabled (added in 4.2.0). Without them the parser rejects these statements.[5][6] The release notes list CONTINUE HANDLER support under 4.1.0 (SPARK-53621) and cursor support under 4.2.0 (SPARK-54759).[3][7]

What does Spark SQL scripting support?

Every SQL script is a compound statement: BEGIN, an optional declaration section, a body of statements separated by semicolons, and END.[1] The declaration section can declare local variables (with an optional DEFAULT), named conditions, cursors and condition handlers.[8]

The body of a Spark SQL script can contain:[1]

  • control flow: IF, CASE, WHILE, REPEAT, LOOP, FOR loops over query results, and LEAVE and ITERATE to exit or continue a labelled loop;
  • DDL such as CREATE, ALTER and DROP, and DML such as INSERT;
  • queries, whose result sets are returned to the caller;
  • SET for local and session variables, and EXECUTE IMMEDIATE;
  • nested compound statements, each with its own scope for variables, cursors, conditions and handlers.

Compound statements are not atomic. The only supported mode is NOT ATOMIC: when a statement fails, earlier statements in the block are not rolled back.[8]

How does error handling work in SQL scripts?

A condition handler catches errors raised inside its compound statement. A handler can name a Spark error condition such as DIVIDE_BY_ZERO, a user-declared condition, one or more SQLSTATE values, SQLEXCEPTION (any SQLSTATE except the XX and 02 classes) or NOT FOUND (the 02 class).[1] When several handlers apply, Spark uses the one in the innermost compound statement and, among those, the most specific: a named condition beats a SQLSTATE, which beats a generic handler.[1] The error names and SQLSTATEs are the ones described in Spark error classes.

An EXIT handler runs its action and then leaves the compound statement that declared it. A CONTINUE handler runs its action and resumes with the statement after the one that failed.[1] A user-declared condition without an explicit SQLSTATE gets 45000.[8]

Example

The following script, adapted from the Spark compound statement reference, catches a division by zero with an EXIT handler. It runs with the Spark 4.3.0 defaults, because EXIT handlers do not need an extra flag.[8]

BEGIN
  DECLARE a INT DEFAULT 1;
  DECLARE b INT DEFAULT 5;
  DECLARE EXIT HANDLER FOR DIVIDE_BY_ZERO
    div0: BEGIN
      VALUES (15);
    END div0;
  SET a = 10;
  SET a = b / 0;      -- raises DIVIDE_BY_ZERO under ANSI mode
  VALUES (a);         -- not reached
END;
-- returns 15

A FOR loop iterates over the rows of a query:[9]

BEGIN
  DECLARE total INT DEFAULT 0;
  sumOdd: FOR r AS SELECT num FROM range(1, 20) AS t(num) DO
    IF r.num > 10 THEN
      LEAVE sumOdd;
    ELSEIF r.num % 2 = 0 THEN
      ITERATE sumOdd;
    END IF;
    SET total = total + r.num;
  END FOR sumOdd;
  VALUES (total);     -- 25
END;

The Spark documentation notes that such loops can often be replaced by a single relational query, which is usually more efficient; here SELECT sum(num) FROM range(1, 10) AS t(num) WHERE num % 2 = 1.[9]

How to run a SQL script from PySpark or Scala

A script is passed as one string to spark.sql(); the parser returns a compound body instead of a single query, and the returned DataFrame holds the result set of the last query the script ran.[10] Named parameter markers can be passed in, but positional parameters are rejected for SQL scripts, and a script cannot be run through EXECUTE IMMEDIATE.[11] The documentation describes two ways to pass data in and out of a script: session variables and parameter markers.[1]

df = spark.sql("""
BEGIN
  DECLARE n INT DEFAULT 0;
  SET n = :iterations;
  WHILE n > 0 DO
    SET n = n - 1;
  END WHILE;
  VALUES (n);
END
""", args={"iterations": 3})
df.show()   # one row: 0

See also

References

  1. ↑ 1.0 1.1 1.2 1.3 1.4 1.5 1.6 SQL Scripting (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  2. ↑ SPARK-48338: Sql Scripting support for Spark SQL. Apache Software Foundation JIRA.Retrieved 2026-11-23.
  3. ↑ 3.0 3.1 Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-23.
  4. ↑ SPARK-54499: Enable SQL Scripting by default for Spark 4.1 release. Apache Software Foundation JIRA.Retrieved 2026-11-23.
  5. ↑ 5.0 5.1 SQLConf.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  6. ↑ AstBuilder.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  7. ↑ Spark Release 4.2.0. Apache Software Foundation.Retrieved 2026-11-23.
  8. ↑ 8.0 8.1 8.2 8.3 Compound Statement (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  9. ↑ 9.0 9.1 FOR Statement (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  10. ↑ SqlScriptingE2eSuite.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  11. ↑ classic/SparkSession.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.