Skip to Content
MySQL 8 Cookbook
book

MySQL 8 Cookbook

by Karthik Appigatla
January 2018
Intermediate to advanced
446 pages
12h 57m
English
Packt Publishing
Content preview from MySQL 8 Cookbook

Non-recursive CTE

A Common table expression (CTE) is just like a derived table, but its declaration is put before the query block instead of in FROM clause.

Derived Table

SELECT... FROM (subquery) AS derived, t1 ...

CTE

SELECT... WITH derived AS (subquery) SELECT ... FROM derived, t1 ...

A CTE may precede SELECT/UPDATE/DELETE, including subqueries WITH derived AS (subquery), for example:

DELETE FROM t1 WHERE t1.a IN (SELECT b FROM derived);

Suppose you want to find out the percentage increase in the salary of each year with respect to the previous year. Without CTE, you need to write two subqueries, and they are essentially the same. MySQL is not smart enough to detect that and the subqueries are executed twice:

mysql> SELECT ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Cookbook

MySQL Cookbook

Paul DuBois
Advanced MySQL 8

Advanced MySQL 8

Eric Vanier, Birju Shah, Tejaswi Malepati

Publisher Resources

ISBN: 9781788395809Other