I have a SQL query which I want to optimize as its used as inner query of a SP.
SELECT TOP 1 @CurrentStartDate = Strt_Dt FROM (
SELECT 1 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'INPR'
UNION
SELECT TOP 1 2 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'CMPL'
ORDER BY enddate DESC
UNION
SELECT TOP 1 3 AS seq, Stat, Strt_Dt, Est_Hrs_Comp, EndDate, Tckt_Id, Envr
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID AND stat = 'PLND'
ORDER BY strt_dt
UNION
SELECT 4 AS seq, 'UNP', NULL, NULL, NULL, tckt_id, 'Unplanned'
FROM pipeline_rest_envr_info e
WHERE e.tckt_id = @TicketID
) aa
ORDER BY aa.seq
Is there any better way to use this query. I need this as I have lot logic having same type.
You are doing a union on 4 results from the same table for the same criteria, can you not just use a CASE statement? e.g.
You will still need case statements for all the fields which have logic, but it will include all data and will be a lot easier to read. Should also be a lot better for performance.