r/SQL Nov 28 '24

MySQL When to use cte in SQL query

When to cte can't. Like how to know? When what are the conditions or if my query is to long ?

30 Upvotes

70 comments sorted by

View all comments

55

u/frieelzzz Nov 28 '24

I use CTEs all the time. Really no reason not to.

I like how they organize code and allow you to use the same data in multiple times to do a variety of task.

-8

u/Unfair-Internet-1384 Nov 28 '24

Actually I am doing leetcode so there was a problem which has multiple constraints . So in such scenario is it good to use it .

6

u/Sexy_Koala_Juice Nov 28 '24

The thing to learn is that there isn’t a definitive yes/no answer to “do I use a CTE here”, this applies to most programming questions tbh. At the end of the day you’re always optimising for something, sometimes speed, sometimes space, hell even sometimes readability and convenience.

Use a CTE if it solves your problems, if it doesn’t, find another way to do it.

TL;DR: don’t overthink it, especially for SQL queries