T-SQL reference › Temp tables
Temp tables vs table variables vs CTEs in SQL Server
A CTE is a name for this statement. A temp table (#name) lives for the batch and can have indexes. A table variable is easy and often a worse plan. For a morning report, CTE or #temp is enough.
A #temp you reuse
SELECT customer_id, MAX(order_date) AS last_date
INTO #last
FROM Orders
GROUP BY customer_id;
SELECT c.first_name, c.last_name, l.last_date
FROM Customers c
JOIN #last l ON l.customer_id = c.customer_id
WHERE l.last_date < DATEADD(day, -90, CAST(GETDATE() AS date));
Drop is automatic at the end of the session. In SSMS, run the whole batch, not just the second half.
Try it on Harbour & Co
James Rowe (Sales Manager) needs this now: “When did each customer last order? Names, not IDs. Most recent first.” Write the query, run it, send the results. On the paid plan.
Take the ticket →Learn it on a real ticket
Monday is free on WorkSQL. A colleague’s ticket lands, you write the T-SQL, we mark it. No videos. Five minutes.
Clock in free See Monday’s tickets