Infinite Recursion Guards


With recursive is the only SQL construct that is not guaranteed to terminate, eventually.0 As the DBMS is typically a very crucial system, infinite loops must be prevented at all times. Therefore, the SQL standard provides a distinct feature for that: the cycle clause. A subset of recursive queries can be protected by the use of union [distinct] inside the recursion. Finally, some systems put a limit on the number of times the recursive leg is processed. Most of those systems allow manual adjustment and removal of that limit.

BigQuery 2026-02-02Db2 (LUW) 12.1.3dDuckDB 1.4.0H2 2.4.240MariaDB 12.1.2acMySQL 9.6.0cOracle DB 23.26.1bPostgreSQL 18SQL Server 2025cSQLite 3.51.0cycle(… union [distinct] …)Limited by ExceptionLimited by WarningUnlimited with Warning
  1. Use cycle … restrict • No using … sub-clause
  2. No using … sub-clause
  3. Configurable
  4. False positives possible

Configuring Limits

Some of the systems that abort execution if an execution threshold has exceeded, allow to adjust or even remove that limit.

MariaDB 12.1.2MySQL 9.6.0SQL Server 2025aOPTION (maxrecursion …)SET max_recursive_iterations = …SET cte_max_recursion_depth = …/*+ SET_VAR(cte_max_recursion_depth = …) */
  1. Use 0 for “unlimited”

The following examples show the respective, non-standard syntax to increase the limit to its maximum. The first two variants are added to the respective statement:

WITH … ()
SELECT …
OPTION (maxrecursion 0)
WITH … ()
SELECT /*+ SET_VAR(cte_max_recursion_depth = 4294967295) */

The following affects all recursive queries of the current session. These settings can be applied on a global (server) level as well.

SET SESSION max_recursive_iterations = 4294967295
SET SESSION cte_max_recursion_depth = 4294967295

You can’t catch up on 20 years of SQL evolution in one day. Subscribe the newsletter via E-Mail, Bluesky or RSS to gradually catch up and to keep modern-⁠sql.com on your radar.

About the Author

Photo of Markus Winand

Markus Winand provides insights into SQL and shows how different systems support it at modern-sql.com. Previously he made use-the-index-luke.com, which is still actively maintained. Markus can be hired as trainer, speaker and consultant via winand.at.

Buy the Book

Cover of “SQL Performance Explained”: Squirrel running on grass

The essence of SQL tuning in 200 pages

Buy now!
(paperback and/or PDF)

Paperback also available at Amazon.com.

Hire Markus

Markus offers SQL training and consulting for developers working at companies of all sizes.
Learn more »

Footnotes

  1. More formally: “the only ISO/IEC 9075-2:2023 construct”. ISO/IEC 9075-4:2023 has imperative loops, of course.

Connect with Markus Winand

Subscribe mailinglistsSubscribe the RSS feedMarkus Winand on LinkedInMarkus Winand on XINGMarkus Winand on TwitterMarkus Winand on Bluesky
Copyright 2015-2026 Markus Winand. All righs reserved.
Legal | Contact | NO WARRANTY | Trademarks | Privacy and GDPR