Only thing cooler than CTEs are Recursive CTEs, but I struggle to find use cases where I can sneak one in.
I believe recursive CTEs are pretty cool for tree traversal. Anytime you've got a table with a foreign key on its own primary key they might come in handy.
Yes, CTEs are awesome. Especially when you don't force materialization and the optimizer can work its magic.
I've had a lot of fun with window functions as well.
CTEs are so helpful for me. They make complex queries much easier to construct and lets me ‘unit test’ the parts I’m working on.
Same here, CTEs were a game changer for me when I learned about them
I was skeptical of CTEs for a long time. I just used subqueries when I could in T SQL, and then I got a new job and my new company used Postgres. In the adaptation process I took a new look at CTEs and became a convert - it's just nicer and easier to read the intermediate step than as a subquery
You can create a functional enum view by just assigning enums as the column names and storing a single row of the int (or whatever enum) representation.
Then use that view in a cross join. You can (almost) eliminate magic numbers entirely and makes the code much more human legible.
Example
CREATE VIEW AS enum.OrderType
SELECT
CAST (1 as 'New'),
CAST (2 as 'Pending'),
CAST (3 as 'Shipped')
GO
-- Assuming a table with OrderId and OrderTypeId
SELECT o.OrderId
FROM dbo.Orders AS o
CROSS JOIN enum.OrderType AS ot
WHERE o.OrderTypeId = ot.[Pending]
-- Only returns orders where TypeId = 2, no need to know what Id that is or for anyone else to in the future either.
This trick works even on large datasets with a lot of complex joins. Getting the status name itself to return is a bit more of a chore though.
Hey, that's pretty neat. Perhaps you could wrap a the OrderType view in a CTE and join on that to get the values back?
CTEs can be useful, particularly in PostgreSQL, where there are writable CTEs, but a lot of the time, I prefer using temp tables over CTEs, as they often perform better for larger datasets. I think one of my favorite constructs is window functions. I've found many uses for them, over the years.
Subqueries in Subqueries in Subqueries
Those work, but require a lot of careful structuring to get right, and can be a pain to debug. With a CTE, you can just call on the intermediate steps to trace down problems.
Programming
All things programming and coding related. Subcommunity of Technology.
This community's icon was made by Aaron Schneider, under the CC-BY-NC-SA 4.0 license.