Adding an additional “order by” column gives me a much worse planHelp optimizing MySQL slow queryOptimizing ORDER BY for simple MySQL queryDatabase Implementations of ORDER BY in a Subqueryquery performance gains by removing operator hash match inner joinWhy are these two queries having such different executions?How can I update statistics adding the data of the last day only?left outer join - sort operations in the query plan - any ways of tuning this simple query?Why does changing the declared join column order introduce a sort?When can SARGable predicates be pushed into a CTE or derived table?Why does the location of a join change performance?

Do I really need to have a scientific explanation for my premise?

Could a cubesat propel itself to Mars?

How do I deal with a powergamer in a game full of beginners in a school club?

Is "history" a male-biased word ("his+story")?

2×2×2 rubik's cube corner is twisted!

How are such low op-amp input currents possible?

Why is there a voltage between the mains ground and my radiator?

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

show this identity with trigometric

Is Gradient Descent central to every optimizer?

Algorithm to convert a fixed-length string to the smallest possible collision-free representation?

Why does Captain Marvel assume the planet where she lands would recognize her credentials?

Making a sword in the stone, in a medieval world without magic

How could our ancestors have domesticated a solitary predator?

Who deserves to be first and second author? PhD student who collected data, research associate who wrote the paper or supervisor?

The bar has been raised

Peter's Strange Word

PTIJ: How can I halachically kill a vampire?

Subset counting for even numbers

If the Captain's screens are out, does he switch seats with the co-pilot?

Make a transparent 448*448 image

Append a note to one of three files based on user choice

How does airport security verify that you can carry a battery bank over 100 Wh?

Does "variables should live in the smallest scope as possible" include the case "variables should not exist if possible"?



Adding an additional “order by” column gives me a much worse plan


Help optimizing MySQL slow queryOptimizing ORDER BY for simple MySQL queryDatabase Implementations of ORDER BY in a Subqueryquery performance gains by removing operator hash match inner joinWhy are these two queries having such different executions?How can I update statistics adding the data of the last day only?left outer join - sort operations in the query plan - any ways of tuning this simple query?Why does changing the declared join column order introduce a sort?When can SARGable predicates be pushed into a CTE or derived table?Why does the location of a join change performance?













2















in other words, how can I get rid of the sort operator on the picture below?



enter image description here



the picture above shows the execution plan of the following 2 selects together:



 SELECT TOP 1 so.OrgType, 
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC, ch.DateAdded DESC

SELECT TOP 1 so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC--, ch.DateAdded DESC


the only difference is that on the second query, there is only one column in the order by.



would it make a difference, as I am using top 1?



I believe all the needed info are on the indexes and table definitions that can be seen on the query plan.



if anything else would help to get rid of that sort just let me know, tomorrow I will post all the possible info.










share|improve this question
























  • Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

    – Aaron Bertrand
    12 hours ago











  • @AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

    – Martin Smith
    11 hours ago







  • 1





    @MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

    – Aaron Bertrand
    9 hours ago















2















in other words, how can I get rid of the sort operator on the picture below?



enter image description here



the picture above shows the execution plan of the following 2 selects together:



 SELECT TOP 1 so.OrgType, 
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC, ch.DateAdded DESC

SELECT TOP 1 so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC--, ch.DateAdded DESC


the only difference is that on the second query, there is only one column in the order by.



would it make a difference, as I am using top 1?



I believe all the needed info are on the indexes and table definitions that can be seen on the query plan.



if anything else would help to get rid of that sort just let me know, tomorrow I will post all the possible info.










share|improve this question
























  • Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

    – Aaron Bertrand
    12 hours ago











  • @AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

    – Martin Smith
    11 hours ago







  • 1





    @MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

    – Aaron Bertrand
    9 hours ago













2












2








2


1






in other words, how can I get rid of the sort operator on the picture below?



enter image description here



the picture above shows the execution plan of the following 2 selects together:



 SELECT TOP 1 so.OrgType, 
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC, ch.DateAdded DESC

SELECT TOP 1 so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC--, ch.DateAdded DESC


the only difference is that on the second query, there is only one column in the order by.



would it make a difference, as I am using top 1?



I believe all the needed info are on the indexes and table definitions that can be seen on the query plan.



if anything else would help to get rid of that sort just let me know, tomorrow I will post all the possible info.










share|improve this question
















in other words, how can I get rid of the sort operator on the picture below?



enter image description here



the picture above shows the execution plan of the following 2 selects together:



 SELECT TOP 1 so.OrgType, 
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC, ch.DateAdded DESC

SELECT TOP 1 so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId
FROM tbl_application_crb_initialData cid

INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId

LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference

LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId

ORDER BY cid.DateAdded DESC--, ch.DateAdded DESC


the only difference is that on the second query, there is only one column in the order by.



would it make a difference, as I am using top 1?



I believe all the needed info are on the indexes and table definitions that can be seen on the query plan.



if anything else would help to get rid of that sort just let me know, tomorrow I will post all the possible info.







sql-server query-performance sql-server-2016 optimization order-by






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 8 hours ago









Martin Smith

63.6k10171255




63.6k10171255










asked 12 hours ago









marcello miorellimarcello miorelli

5,8971962138




5,8971962138












  • Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

    – Aaron Bertrand
    12 hours ago











  • @AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

    – Martin Smith
    11 hours ago







  • 1





    @MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

    – Aaron Bertrand
    9 hours ago

















  • Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

    – Aaron Bertrand
    12 hours ago











  • @AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

    – Martin Smith
    11 hours ago







  • 1





    @MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

    – Aaron Bertrand
    9 hours ago
















Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

– Aaron Bertrand
12 hours ago





Those cost % are just estimates and can actually end up being WAY, WAY off. Is the top query actually noticeably slower?

– Aaron Bertrand
12 hours ago













@AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

– Martin Smith
11 hours ago






@AaronBertrand - CPU time 756, Elapsed Time 222, Reads 2357 vs CPU time 0, Elapsed Time 0, Reads 10 from the stats in the plan - most of the tables are pretty small though. Table cardinalities 11, 19, 67,591, 232,528

– Martin Smith
11 hours ago





1




1





@MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

– Aaron Bertrand
9 hours ago





@MartinSmith Thanks, I didn’t look at the plan (mobile), just try my best to make sure drive-by readers don’t put too much weight into those percentages. Sometimes they’re useful, sometimes they’re extremely misleading.

– Aaron Bertrand
9 hours ago










1 Answer
1






active

oldest

votes


















3














Your question is missing a lot of detail but I can reproduce something similar.



Setup



CREATE TABLE T1(X INT PRIMARY KEY, Y INT INDEX IX)

CREATE TABLE T2(X INT, Y INT , PRIMARY KEY(X, Y))

INSERT INTO T2
OUTPUT INSERTED.* INTO T1
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), ROW_NUMBER() OVER (ORDER BY @@SPID)
FROM sys.all_objects o1, sys.all_objects o2;


Query 1



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y;


enter image description here



Query 2



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y, T2.Y


enter image description here



Query 3



WITH T AS
(
SELECT TOP 1 WITH TIES T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y
)
SELECT TOP 1 *
FROM T
ORDER BY T2Y


enter image description here



Query 1 just picks off the TOP 1 from the index in the desired sort order and does the needed joins on the other table for that row. If the join is successful it stops there otherwise it tries the next one in index order until it finds a row that matches or runs out of rows.



Query 2 When adding the new sort column this plan is no longer valid as there could be multiple matches tied with the TOP 1 value and SQL Server decides to join the whole lot and then get the TOP 1 from that.



Query 3 This encourages SQL Server to stick with the first strategy and then just does a TOP 1 Sort on any rows tied with the same value for the first sort key.



For my example data Query 3 works out better than Query 2 but if you have many duplicates tied for the value of the first sort key your milage may differ.



You can try this rewrite and see how it fares



WITH T
AS (SELECT TOP 1 WITH TIES so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId,
ch.DateAdded AS chDateAdded
FROM tbl_application_crb_initialData cid
INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId
LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference
LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId
ORDER BY cid.DateAdded DESC)
SELECT TOP 1 OrgType,
Status,
DBSstatusDescription,
ApplicationId
FROM T
ORDER BY chDateAdded DESC





share|improve this answer




















  • 1





    A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

    – Erik Darling
    4 hours ago











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f231950%2fadding-an-additional-order-by-column-gives-me-a-much-worse-plan%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














Your question is missing a lot of detail but I can reproduce something similar.



Setup



CREATE TABLE T1(X INT PRIMARY KEY, Y INT INDEX IX)

CREATE TABLE T2(X INT, Y INT , PRIMARY KEY(X, Y))

INSERT INTO T2
OUTPUT INSERTED.* INTO T1
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), ROW_NUMBER() OVER (ORDER BY @@SPID)
FROM sys.all_objects o1, sys.all_objects o2;


Query 1



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y;


enter image description here



Query 2



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y, T2.Y


enter image description here



Query 3



WITH T AS
(
SELECT TOP 1 WITH TIES T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y
)
SELECT TOP 1 *
FROM T
ORDER BY T2Y


enter image description here



Query 1 just picks off the TOP 1 from the index in the desired sort order and does the needed joins on the other table for that row. If the join is successful it stops there otherwise it tries the next one in index order until it finds a row that matches or runs out of rows.



Query 2 When adding the new sort column this plan is no longer valid as there could be multiple matches tied with the TOP 1 value and SQL Server decides to join the whole lot and then get the TOP 1 from that.



Query 3 This encourages SQL Server to stick with the first strategy and then just does a TOP 1 Sort on any rows tied with the same value for the first sort key.



For my example data Query 3 works out better than Query 2 but if you have many duplicates tied for the value of the first sort key your milage may differ.



You can try this rewrite and see how it fares



WITH T
AS (SELECT TOP 1 WITH TIES so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId,
ch.DateAdded AS chDateAdded
FROM tbl_application_crb_initialData cid
INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId
LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference
LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId
ORDER BY cid.DateAdded DESC)
SELECT TOP 1 OrgType,
Status,
DBSstatusDescription,
ApplicationId
FROM T
ORDER BY chDateAdded DESC





share|improve this answer




















  • 1





    A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

    – Erik Darling
    4 hours ago
















3














Your question is missing a lot of detail but I can reproduce something similar.



Setup



CREATE TABLE T1(X INT PRIMARY KEY, Y INT INDEX IX)

CREATE TABLE T2(X INT, Y INT , PRIMARY KEY(X, Y))

INSERT INTO T2
OUTPUT INSERTED.* INTO T1
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), ROW_NUMBER() OVER (ORDER BY @@SPID)
FROM sys.all_objects o1, sys.all_objects o2;


Query 1



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y;


enter image description here



Query 2



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y, T2.Y


enter image description here



Query 3



WITH T AS
(
SELECT TOP 1 WITH TIES T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y
)
SELECT TOP 1 *
FROM T
ORDER BY T2Y


enter image description here



Query 1 just picks off the TOP 1 from the index in the desired sort order and does the needed joins on the other table for that row. If the join is successful it stops there otherwise it tries the next one in index order until it finds a row that matches or runs out of rows.



Query 2 When adding the new sort column this plan is no longer valid as there could be multiple matches tied with the TOP 1 value and SQL Server decides to join the whole lot and then get the TOP 1 from that.



Query 3 This encourages SQL Server to stick with the first strategy and then just does a TOP 1 Sort on any rows tied with the same value for the first sort key.



For my example data Query 3 works out better than Query 2 but if you have many duplicates tied for the value of the first sort key your milage may differ.



You can try this rewrite and see how it fares



WITH T
AS (SELECT TOP 1 WITH TIES so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId,
ch.DateAdded AS chDateAdded
FROM tbl_application_crb_initialData cid
INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId
LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference
LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId
ORDER BY cid.DateAdded DESC)
SELECT TOP 1 OrgType,
Status,
DBSstatusDescription,
ApplicationId
FROM T
ORDER BY chDateAdded DESC





share|improve this answer




















  • 1





    A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

    – Erik Darling
    4 hours ago














3












3








3







Your question is missing a lot of detail but I can reproduce something similar.



Setup



CREATE TABLE T1(X INT PRIMARY KEY, Y INT INDEX IX)

CREATE TABLE T2(X INT, Y INT , PRIMARY KEY(X, Y))

INSERT INTO T2
OUTPUT INSERTED.* INTO T1
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), ROW_NUMBER() OVER (ORDER BY @@SPID)
FROM sys.all_objects o1, sys.all_objects o2;


Query 1



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y;


enter image description here



Query 2



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y, T2.Y


enter image description here



Query 3



WITH T AS
(
SELECT TOP 1 WITH TIES T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y
)
SELECT TOP 1 *
FROM T
ORDER BY T2Y


enter image description here



Query 1 just picks off the TOP 1 from the index in the desired sort order and does the needed joins on the other table for that row. If the join is successful it stops there otherwise it tries the next one in index order until it finds a row that matches or runs out of rows.



Query 2 When adding the new sort column this plan is no longer valid as there could be multiple matches tied with the TOP 1 value and SQL Server decides to join the whole lot and then get the TOP 1 from that.



Query 3 This encourages SQL Server to stick with the first strategy and then just does a TOP 1 Sort on any rows tied with the same value for the first sort key.



For my example data Query 3 works out better than Query 2 but if you have many duplicates tied for the value of the first sort key your milage may differ.



You can try this rewrite and see how it fares



WITH T
AS (SELECT TOP 1 WITH TIES so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId,
ch.DateAdded AS chDateAdded
FROM tbl_application_crb_initialData cid
INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId
LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference
LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId
ORDER BY cid.DateAdded DESC)
SELECT TOP 1 OrgType,
Status,
DBSstatusDescription,
ApplicationId
FROM T
ORDER BY chDateAdded DESC





share|improve this answer















Your question is missing a lot of detail but I can reproduce something similar.



Setup



CREATE TABLE T1(X INT PRIMARY KEY, Y INT INDEX IX)

CREATE TABLE T2(X INT, Y INT , PRIMARY KEY(X, Y))

INSERT INTO T2
OUTPUT INSERTED.* INTO T1
SELECT TOP 1000000 ROW_NUMBER() OVER (ORDER BY @@SPID), ROW_NUMBER() OVER (ORDER BY @@SPID)
FROM sys.all_objects o1, sys.all_objects o2;


Query 1



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y;


enter image description here



Query 2



SELECT TOP 1 T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y, T2.Y


enter image description here



Query 3



WITH T AS
(
SELECT TOP 1 WITH TIES T1.Y AS T1Y, T2.Y AS T2Y
FROM T1 JOIN T2 ON T1.X = T2.X
ORDER BY T1.Y
)
SELECT TOP 1 *
FROM T
ORDER BY T2Y


enter image description here



Query 1 just picks off the TOP 1 from the index in the desired sort order and does the needed joins on the other table for that row. If the join is successful it stops there otherwise it tries the next one in index order until it finds a row that matches or runs out of rows.



Query 2 When adding the new sort column this plan is no longer valid as there could be multiple matches tied with the TOP 1 value and SQL Server decides to join the whole lot and then get the TOP 1 from that.



Query 3 This encourages SQL Server to stick with the first strategy and then just does a TOP 1 Sort on any rows tied with the same value for the first sort key.



For my example data Query 3 works out better than Query 2 but if you have many duplicates tied for the value of the first sort key your milage may differ.



You can try this rewrite and see how it fares



WITH T
AS (SELECT TOP 1 WITH TIES so.OrgType,
ch.Status,
rcs.DBSstatusDescription,
cid.ApplicationId,
ch.DateAdded AS chDateAdded
FROM tbl_application_crb_initialData cid
INNER JOIN tbl_season_organisationId so
ON cid.OrganisationId = so.OrgId
LEFT JOIN tbl_crbHistory ch
ON cid.ClientReference = ch.ClientReference
LEFT JOIN ref_crbStatus rcs
ON ch.Status = rcs.statusId
ORDER BY cid.DateAdded DESC)
SELECT TOP 1 OrgType,
Status,
DBSstatusDescription,
ApplicationId
FROM T
ORDER BY chDateAdded DESC






share|improve this answer














share|improve this answer



share|improve this answer








edited 9 hours ago

























answered 11 hours ago









Martin SmithMartin Smith

63.6k10171255




63.6k10171255







  • 1





    A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

    – Erik Darling
    4 hours ago













  • 1





    A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

    – Erik Darling
    4 hours ago








1




1





A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

– Erik Darling
4 hours ago






A+ for the first time I've seen someone use TOP WITH TIES for a good reason.

– Erik Darling
4 hours ago


















draft saved

draft discarded
















































Thanks for contributing an answer to Database Administrators Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f231950%2fadding-an-additional-order-by-column-gives-me-a-much-worse-plan%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2