Databases 5 min read

Using WITH Expressions in MySQL 8.0: Benefits, Examples, and Performance Comparison

This article explains how MySQL 8.0 introduced WITH expressions, demonstrates their ease of use and efficiency with practical examples compared to traditional views, shows performance gains through query plan analysis, and illustrates functional use cases such as replacing temporary tables.

Aikesheng Open Source Community
Aikesheng Open Source Community
Aikesheng Open Source Community
Using WITH Expressions in MySQL 8.0: Benefits, Examples, and Performance Comparison

Common table expressions (CTEs) have long been supported in commercial databases like Oracle and SQL Server, but MySQL only added the WITH feature in version 8.0. Two main advantages are highlighted: usability and efficiency.

Example 1 – Usability

A table t1 is created with several columns and indexes. After inserting 1,000 test rows, a traditional view is defined to retrieve aggregated data. The view requires repeated materialization, which can be costly.

Using a WITH expression, the same query is rewritten to compute the count and rank in a single statement, avoiding repeated view materialization. The query plan for the WITH version shows one less materialization step, resulting in faster execution.

Example 2 – Functional Use

MySQL historically could not reopen a temporary table multiple times, leading to errors such as ERROR 1137 (HY000): Can't reopen table: 'ytt_tmp1' . By defining a CTE that selects from the temporary table, the same logic can be expressed without reopening the table, eliminating the error.

Both examples demonstrate that WITH expressions simplify query writing, reduce resource consumption, and improve performance, especially when the same subquery is referenced multiple times.

Readers are encouraged to explore the MySQL manual for deeper details on CTE usage.

performanceSQLMySQLtemporary tablesWITH expression
Aikesheng Open Source Community
Written by

Aikesheng Open Source Community

The Aikesheng Open Source Community provides stable, enterprise‑grade MySQL open‑source tools and services, releases a premium open‑source component each year (1024), and continuously operates and maintains them.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.