MySQL + SQL · Lesson 77

CTE and WITH Clause in MySQL

What is a CTE?

A CTE (Common Table Expression) is a temporary named result defined with WITH, used to make complex queries readable. MySQL 8+.

Example

WITH high_scorers AS (
  SELECT name, marks FROM students WHERE marks >= 90
)
SELECT * FROM high_scorers ORDER BY marks DESC;
The CTE "high_scorers" is defined once and used like a table in the main query.

Why Use CTEs?

  • Break a big query into readable named steps.
  • Reuse the same subquery result multiple times.

Summary

  • A CTE is a named temporary result defined with WITH.
  • Makes complex queries cleaner and more readable.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp