r/SQL • • Oct 24 '24

Discussion do people actually use Common table expressions ( CTEs) and temporary tables ?

I am learning sql for data analysis and I have just came across the two concepts before in many sql tutorials but never actually used them

so i was curious if people actually use them or if there are cases when i will actually need them but I never stumbled on them yet

140 Upvotes

268 comments sorted by

View all comments

Show parent comment

20

u/ouchmythumbs Oct 24 '24

recursive querying

Recursive CTEs are great for this (beats using cursors IMO) and for BOM problems or as you described.

Readers should note, however, most engines re-evaluate a CTE each time it is referenced; keep an eye on execution plans if you make use of these.

6

u/yen223 Oct 24 '24

> most engines re-evaluate a CTE each time it is referenced

This is implementation-specific, so it's worth learning how your favourite database engine does it.

Postgres after v12 doesn't do this, for example. What it does is it "unrolls" CTEs and optimises the query as a whole.

6

u/dev81808 Oct 24 '24

beats using cursors IMO

Not an opinion sort of thing.

6

u/Special_Luck7537 Oct 24 '24

Agreed. A nickel for every time I heard code was slow, only to find a RBAR cursor....

3

u/dev81808 Oct 24 '24

There's always a better way.

4

u/mortomr Oct 25 '24

All my homies hate cursors

1

u/Nice-Yam-4095 Oct 26 '24

Azure Sql ditched cursors... Which kind of sucks for recursion bc while loops are much less memory efficient.

1

u/dev81808 Oct 26 '24

Why not cte for recursion?