Weird behavior with a T-SQL query

Status
Not open for further replies.

StanGable

Ars Legatus Legionis
18,817
I have a big old view I'm working on that has a WHERE clause limiting the results to one type of document:

Code:
SELECT *
FROM Table1
WHERE Doc = 'Foo'

I need it to also return 'Bar' documents, so I simply added that...

Code:
SELECT *
FROM Table1
WHERE Doc = 'Foo'
     OR Doc = 'Bar'

Doing that, I get identical results, looking, to me, like there are no 'Bar' documents.

However, when I run it as...

Code:
SELECT *
FROM Table1
WHERE Doc = 'Bar'

I get a bunch of 'Bar' documents, and to get them, I have to specifically name them and them alone. If I look for 'Bar' with anything else, or even if I remove the WHERE clause completely, I still only get 'Foo'.

Has anyone ever heard of such a thing? I've worked in SQL Server for a long time, but I'm admittedly rusty and was never an expert in the first place.

Thanks for any thoughts.
 

StanGable

Ars Legatus Legionis
18,817
RB: Sorry- I was just putting in what I thought was the relevant stuff. Of course "CREATE VIEW [dbo].[vew_FooBar] AS" would precede the query and so on.

Moniker: MS SQL Server 2008.

AW: I don't think I can post the entire thing, at least not without scrubbing the sht out of it. It's not that I think there's anything really sensitive in there, but that I'm not sure what the rules are.

There *are* multiple CTEs of both tables and views and embedded queries and such, but the point, at least as I see it, is that all that remains unchanged and only this WHERE clause is modified (it's the only WHERE clause in this view definition).

If doing nothing more than setting it to "WHERE Doc = 'Foo'" or "WHERE Doc = 'Bar'" gets me the 'Foo' or 'Bar' docs (not using a variable or anything that could have an affect somewhere else), how is it possible that using "WHERE Doc IN ('Foo', 'Bar')" does not, even if there are a load of CTEs and such in the rest of the definition?
 

StanGable

Ars Legatus Legionis
18,817
Here's the entire definition (I hope I didn't mess anything up finding/replacing anything sensitive):
Code:
SELECT 	PCD.*,
	--2010-10-08:
	ISNULL(SUBSTRING(CONVERT(VARCHAR(11), POP.Last_Mod_POP_End_Date, 13), 1, 2) + '-' + 
		SUBSTRING(CONVERT(VARCHAR(11), POP.Last_Mod_POP_End_Date, 13), 4, 3) + '-' + 
		SUBSTRING(CONVERT(VARCHAR(11), POP.Last_Mod_POP_End_Date, 13), 8, 4), PCD.PerfEndDate_PrimeBar) AS POPEndDate_with_Mods,
	SOV.OrgFundingAmt + SOV.ModFundingAmt AS FundedAmount, 
	SOV.ModFundingAmt AS FundedAmountMod,
	SOV.PrmCostPriceAmt +  SOV.PrmBaseFeeAmt + SOV.PrmIncentiveFeeAmt AS PrimeContractValue, 
	SOV.OrgCostPriceAmt +  SOV.OrgBaseFeeAmt + SOV.OrgIncentiveFeeAmt + 
	SOV.ModCostPriceAmt +  SOV.ModBaseFeeAmt + SOV.ModIncentiveFeeAmt AS AwardedContractValue
FROM
	 -- Retrieve Foo Data (One Record Per Contract)
	(
	SELECT 
		ROCD.MPSAID,
		MAX(blu12.AdminContractPOC) AS AdminContractPOC,
		MAX(ROCD.DocSubTypeName) AS DocSubTypeName,				  
		MAX(ROCD.MpsAccountVisualID) AS Company_Definition_Number, 
		MAX(ROCD.MPSAccountName) AS Program, 
		MAX(ROCD.MPSAccountTitle) AS Project_Name,
		MAX(ISNULL(PCD.DocTitle, 'No Customer')) AS Customer,
		MAX(ROCD.DocVisualID) AS Prime_Contract_Number,
		MAX(CASE ROCD.DocUDFString2 WHEN '..' THEN 'None' ELSE ROCD.DocUDFString2 END) AS Alternate_Contract_Number,
		MAX(dbo.ftn_lookupItem2(ROCD.ContractGroupingCode_groupingcodecusl, 'No Contract Type')) AS ContractType,
		MAX(ISNULL(SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_OfficialContractDate, 13), 1, 2) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_OfficialContractDate, 13), 4, 3) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_OfficialContractDate, 13), 8, 4), 'No-Award-Dt')) AS AwardDate, 
	   	MAX(ISNULL(SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_IssuedOnDate, 13), 1, 2) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_IssuedOnDate, 13), 4, 3) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_IssuedOnDate, 13), 8, 4), 'No-PrfSt-Dt')) AS PerfStartDate_PrimeBar, 
	   	MAX(ISNULL(SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_CurrentCompletionDate, 13), 1, 2) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_CurrentCompletionDate, 13), 4, 3) + '-' + SUBSTRING(CONVERT(VARCHAR(11), ROCD.ContractDates_CurrentCompletionDate, 13), 8, 4), 'No-PrfEn-Dt')) AS PerfEndDate_PrimeBar, 
	   	MAX(dbo.ftn_lookupItem2(rocd_wc.WorkClassificationCode_workclasstypecusl, 'No Baring Method')) AS BaringMethod, 
	   	MAX(ISNULL(ROCD.DocumentProcessState, 'No Contract Status')) AS ContractStatus, 
	   	MAX(ISNULL(pd.DocDescription, 'No Job Desc')) AS JobDescription , 
	   	MAX(ISNULL(pd.ProjectAddress_City + ', ', '') + ISNULL(pd.ProjectAddress_State + ', ', '') + ISNULL(pd.ProjectAddress_Country, '')) AS JobLocation, 
	   	MAX(dbo.ftn_lookupItem2(pd.ProjectStatus_projectstatuscusl, 'No Data Found')) AS PrimeSubContract, 
	   	MAX(dbo.ftn_lookupItem2(pd.ProjectSecuredStatus_projectsecuredstatuscusl, 'No Contract Category')) AS ContractCategory, 
	   	MAX(dbo.ftn_lookupItem2(pd.ContractType_contracttypecusl, 'No Contract Scope')) AS ContractScope, 
	   	MAX(isnull(blu12.paymentoffice, 'No Payment Office Entered')) AS BillingOffice, 
		MAX(isnull(blu12.paymentaddress, 'No Payment Address Entered')) AS BillingOfficeAddr, 
	   	MAX(isnull(blu12.admincontractoffice, 'No Administrative Contracting Office Entered')) AS ContractAdminOffice, 
		MAX(isnull(blu12.admincontractaddress, 'No Administrative Contracting Address Entered')) AS ContractAdminOfficeAddr, 
	   	MAX(dbo.ftn_lookupItem2(pd.MarketSector_marketsectorcusl, 'No Data Found')) AS IDIQ,
		MAX(dbo.ftn_lookupItem2(PD.OfficeUnit_officeunitcusl, 'No Data Found')) AS CSCS, 
	   	MAX(dbo.ftn_lookupItem2(pd.ClientGroup_clientgroupcusl, 'No Data Found')) AS Options, 
	   	MAX(dbo.ftn_lookupItem2(pd.CompanyEntity_companyentitycusl, 'No Data Found')) AS NonDisclosureAgreement, 
	   	MAX(ISNULL(pd.DocUDFString1, 'No Restrictions Entered')) AS BillingFreqRestrictions, 
	   	MAX(ISNULL(CAST(pd.DocNote AS VARCHAR(255)), 'No Unique Reqs Entered')) AS UniqueRequirements, 
	   	MAX(ISNULL(pd.DocUDFString2, 'No Invc Support Reqs Entered')) AS InvoiceSupportRequirements, 
	   	MAX(ISNULL(pd.ProjectAlternateNumber2, 'No DPAS Entered')) AS DPASRating, 
	   	MAX(ISNULL(pd.DocUDFString3, 'No Pmt Terms Entered')) AS PaymentTerms, 
	   	MAX(ISNULL(pd.DocUDFString4, 'No Penalties Entered')) AS LatePaymentPenalties, 
	   	MAX(ISNULL(pd.ProjectSiteFaxInfoNote, 'No Comments Entered')) AS Comments, 
		MAX(CASE ROCD.DocSubTypeName WHEN 'Foo' THEN CAST(pd.SaleDate AS VARCHAR(20)) 
	                             ELSE 'No PCN or is Bar' END) AS EffectiveDate,
	   	MAX(SUBSTRING(CONVERT(VARCHAR(25), PD.contractcompletiondate, 126), 1, 10)) AS Records_Destruction_Date, 
		MAX(CASE dbo.ftn_lookupItem2(pccd_prjrol.ProjectRole_percomprjrolecusl, '') WHEN LTRIM(ROCD.DocVisualID) + '_Project Manager' THEN pccd.displayname 
	                                                                           ELSE '' END) AS ProjectMgr, 
	   	MAX(CASE dbo.ftn_lookupItem2(pccd_prjrol.ProjectRole_percomprjrolecusl, '') WHEN LTRIM(ROCD.DocVisualID) + '_Government Contract Administrator - Project' THEN pccd.displayname 
	                                                                           ELSE '' END) AS ProjectGCA, 
	   	MAX(CASE dbo.ftn_lookupItem2(pccd_prjrol.ProjectRole_percomprjrolecusl, '') WHEN LTRIM(ROCD.DocVisualID) + '_Project Controls Cost' THEN pccd.displayname 
	                                                                           ELSE '' END) AS CostPOC,
		SUM(CAST(ROUND(RCOD.ThisChangeAmt, 4) AS MONEY)) AS AwardContractValueMod,
		-- 2009-03-11:
		MAX(ISNULL(ROCD.ContractDates_ToDateChangeInDuration,0)) AS ToDateChangeInDuration,
	   	MAX(ISNULL(SUBSTRING(CONVERT(VARCHAR(11), 
				DATEADD(D,ISNULL(ROCD.ContractDates_ToDateChangeInDuration,0),ROCD.ContractDates_CurrentCompletionDate), 13), 1, 2) + '-' + SUBSTRING(CONVERT(VARCHAR(11), DATEADD(D,ISNULL(ROCD.ContractDates_ToDateChangeInDuration,0),ROCD.ContractDates_CurrentCompletionDate), 13), 4, 3) + '-' + SUBSTRING(CONVERT(VARCHAR(11), DATEADD(D,ISNULL(ROCD.ContractDates_ToDateChangeInDuration,0),ROCD.ContractDates_CurrentCompletionDate), 13), 8, 4), 'No-ExtPrfEn-Dt')) 
				AS ExtendedPerfEndDate_PrimeBar
	FROM Division_PROD_Prj.dbo.VRXC AS ROCD 
	
	       LEFT OUTER JOIN Division_PROD_Prj.dbo.cust_BriefHeader blu12 WITH (NOLOCK) 
	         	--ON ROCD.MpsAccountVisualID = blu12.CompanyDefinition 
			ON ROCD.DocumentGuid = blu12.prlncParentDocumentGuid
	
		-- Retrieve Change Bar Information (i.e. Mods)
		LEFT OUTER JOIN Division_PROD_Prj.dbo.VRXCRCBD RCOD WITH (NOLOCK) 
	         	ON ROCD.ContractID = RCOD.OriginalContractID 
		
		LEFT OUTER JOIN Division_PROD_Prj.dbo.VRXC_WorkClassifications rocd_wc WITH (NOLOCK) 
	         	ON ROCD.ContractID = rocd_wc.OriginalContractID 
	
			-- Project Document Related data and joins...
	       	INNER JOIN Division_PROD_Prj.dbo.VR_PL_ProjectDocument AS PD WITH (NOLOCK)
			ON ROCD.MPSAID = PD.MPSAID
	
	          LEFT OUTER JOIN Division_PROD_Prj.dbo.VR_PL_PCD PCD WITH (NOLOCK) 
	            	ON PD.ClientCompany_DocumentGuid = PCD.DocumentGuid 
	               	AND PD.MPSAccountName = PCD.MPSAccountName 
	
	          LEFT OUTER JOIN Division_PROD_Prj.dbo.VR_PL_PCCD pccd WITH (NOLOCK) 
	            	ON pd.MPSAID = pccd.MPSAID 
	
	          LEFT OUTER JOIN Division_PROD_Prj.dbo.VR_PL_PRCCD_PRJ pccd_prjrol WITH (NOLOCK) 
	            	ON pccd.PersonCompanyID = pccd_prjrol.PersonCompanyID           	
	
	
	
	/*	THESE ARE THE WHERE CLAUSES ****************************************************************************************************/
	
	--WHERE ROCD.DocSubTypeName IN ('Foo') -- Retrieves Foos 
	--WHERE ROCD.DocSubTypeName IN ('Bar')          -- Retrieves Bars 
	--WHERE ROCD.DocSubTypeName IN ('Foo', 'Bar')    --Retrieves Only Foos
	
	/*	END OF WHERE CLAUSES ***********************************************************************************************************/
	
	GROUP BY ROCD.MPSAID
	) AS PCD -- Foos Data
	
	INNER JOIN 
-- Retrieve Summary of Value Information.
	(
	SELECT 	V1.MPSAID, 
			CAST(SUM(V1.PrmFundingAmt) AS MONEY) AS PrmFundingAmt,
			CAST(SUM(V1.PrmCostPriceAmt) AS MONEY) AS PrmCostPriceAmt,
			CAST(SUM(V1.PrmBaseFeeAmt) AS MONEY) AS PrmBaseFeeAmt,
			CAST(SUM(V1.PrmIncentiveFeeAmt) AS MONEY) AS PrmIncentiveFeeAmt,
			CAST(SUM(V1.OrgFundingAmt) AS MONEY) AS OrgFundingAmt,
			CAST(SUM(V1.OrgCostPriceAmt) AS MONEY) AS OrgCostPriceAmt,
			CAST(SUM(V1.OrgBaseFeeAmt) AS MONEY) AS OrgBaseFeeAmt,
			CAST(SUM(V1.OrgIncentiveFeeAmt) AS MONEY) AS OrgIncentiveFeeAmt,
			CAST(SUM(V1.ModFundingAmt) AS MONEY) AS ModFundingAmt,
			CAST(SUM(V1.ModCostPriceAmt) AS MONEY) AS ModCostPriceAmt,
			CAST(SUM(V1.ModBaseFeeAmt) AS MONEY) AS ModBaseFeeAmt,
			CAST(SUM(V1.ModIncentiveFeeAmt) AS MONEY) AS ModIncentiveFeeAmt
		FROM 
			(
				SELECT ROCD.MPSAID, 
					CASE WHEN ROCD.DocSubTypeName = 'Foo' AND ROCD_SOV.ItemDescription = 'funding' THEN 
						ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS PrmFundingAmt, -- SOV2
					CASE WHEN ROCD.DocSubTypeName = 'Foo' AND ROCD_SOV.ItemDescription = 'cost/price' THEN 
						ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS PrmCostPriceAmt, -- SOV2
					CASE WHEN ROCD.DocSubTypeName = 'Foo' AND ROCD_SOV.ItemDescription = 'base fee' THEN 
						ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS PrmBaseFeeAmt, -- SOV2
					CASE WHEN ROCD.DocSubTypeName = 'Foo' AND ROCD_SOV.ItemDescription = 'incentive fee' THEN 
						ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS PrmIncentiveFeeAmt, -- SOV2
					CASE ROCD_SOV.ItemDescription WHEN 'funding' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS OrgFundingAmt, -- SOV2
					CASE ROCD_SOV.ItemDescription WHEN 'cost/price' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS OrgCostPriceAmt, -- SOV3
					CASE ROCD_SOV.ItemDescription WHEN 'base fee' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS OrgBaseFeeAmt, -- SOV4
					CASE ROCD_SOV.ItemDescription WHEN 'incentive fee' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS OrgIncentiveFeeAmt, -- SOV5 
					0 AS ModFundingAmt,
					0 AS ModCostPriceAmt,
					0 AS ModBaseFeeAmt,
					0 AS ModIncentiveFeeAmt
				FROM Division_PROD_Prj.dbo.VRXC AS ROCD WITH (NOLOCK)
					INNER JOIN Division_PROD_Prj.dbo.ScheduleOfValueItem AS ROCD_SOV WITH (NOLOCK)
						ON ROCD.DocumentID = ROCD_SOV.DocumentID 
				UNION ALL 
				SELECT ROCD.MPSAID, 
					0 AS PrmFundingAmt,
					0 AS PrmCostPriceAmt, -- SOV3
					0 AS PrmBaseFeeAmt, -- SOV4
					0 AS PrmIncentiveFeeAmt, -- SOV5 
					0 AS OgrFundingAmt, -- SOV2
					0 AS OrgCostPriceAmt, -- SOV3
					0 AS OrgBaseFeeAmt, -- SOV4
					0 AS OrgIncentiveFeeAmt, -- SOV5 
					CASE ROCD_SOV.ItemDescription WHEN 'funding' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS ModFundingAmt, -- SOV2
					CASE ROCD_SOV.ItemDescription WHEN 'cost/price' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS ModCostPriceAmt, -- SOV3
					CASE ROCD_SOV.ItemDescription WHEN 'base fee' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS ModBaseFeeAmt, -- SOV4
					CASE ROCD_SOV.ItemDescription WHEN 'incentive fee' THEN ISNULL(ROCD_SOV.ScheduledUnitPrice, 0) ELSE 0 END AS ModIncentiveFeeAmt -- SOV5 
				FROM Division_PROD_Prj.dbo.VRXC ROCD WITH (NOLOCK)
					INNER JOIN Division_PROD_Prj.dbo.VRXCRCBD RCOD WITH (NOLOCK)
						ON ROCD.ContractID = RCOD.OriginalContractID 
					INNER JOIN Division_PROD_Prj.dbo.ScheduleOfValueItem ROCD_SOV WITH (NOLOCK)
						ON RCOD.DocumentID = ROCD_SOV.DocumentID
		) AS V1 
		GROUP BY V1.MPSAID 
	) AS SOV ON PCD.MPSAID = SOV.MPSAID

	--2010-10-08:
	LEFT OUTER JOIN 
		(SELECT 
			  MPSAID
			, MAX(Last_Mod_POP_End_Date) AS Last_Mod_POP_End_Date
			FROM dbo.vew_TaskBarPOPDates
			GROUP BY MPSAID
		)  AS POP
	ON POP.MPSAID = PCD.MPSAID
 

C0rinthian

Ars Tribunus Angusticlavius
6,858
Here is your problem:
Code:
   SELECT 
      ROCD.MPSAID,
      MAX(blu12.AdminContractPOC) AS AdminContractPOC,
      MAX(ROCD.DocSubTypeName) AS DocSubTypeName,

So if you return docSubTypeName of 'Foo' and 'Bar', it's only going to return 'Foo' because you're ultimately asking for the max value of that field.

This is assuming that the same ROCD.MPSAID can have records of both 'Foo' and 'Bar' docSubTypeName.
 

StanGable

Ars Legatus Legionis
18,817
C0rinthian":384rwvjz said:
Here is your problem:
Code:
   SELECT 
      ROCD.MPSAID,
      MAX(blu12.AdminContractPOC) AS AdminContractPOC,
      MAX(ROCD.DocSubTypeName) AS DocSubTypeName,

So if you return docSubTypeName of 'Foo' and 'Bar', it's only going to return 'Foo' because you're ultimately asking for the max value of that field.

This is assuming that the same ROCD.MPSAID can have records of both 'Foo' and 'Bar' docSubTypeName.

GAH! You are beautiful. Thank you very much.
 

A.W.

Ars Tribunus Angusticlavius
6,790
Dracorat":2fkqqius said:
You should try not to have queries that long. You should consider a level of normalization (so you don't have to "chop up" fields) and using views as query objects.
It seems fine to me, though I would refactor the subselects into actual CTEs, for the sake of readability. There's nothing wrong with a gigantic query, as long as it's readable.
 

Handor

Ars Tribunus Militum
2,513
The weird behavior is the result, obviously, of the weird MAX stuff, as c0rinthian mentioned. But what do you need all those MAXes for in the first place? Are you sure they're correct for what you want to do?

I ask only because it's bitten you once, and it might bite you again if you aren't careful, because all that data might be coming from lots of different rows that aren't really compatible. There are other ways to select single rows, if that's the goal.

Edit: And, on a similar note, are you SURE you want all those NOLOCKs? If you have a reason for using them, so be it, but yikes!
 

StanGable

Ars Legatus Legionis
18,817
Full story: I'm actually updating an SSRS report that utilizes this view, and I haven't had *any* training on the systems and databases this company uses.

[whiner mode] This has made for a very frustrating couple of weeks trying to finish something that should have taken 4-5 days max IMO, and also leaves me loathe to modify anything beyond what's absolutely necessary. I feel like I'm flying blind and alternate between a) wanting to call my boss and tell him to just quit fcking assigning me tasks that require a level of knowledge I haven't been given, and b) wondering if I'm just not concentrating hard enough to grasp the obvious. [/whiner]

I know those MAX()s could be gotten around by grouping, but I'm not sure why the original developer used them instead.

Regarding the NOLOCKs, I assume he/she just wanted to make sure the tables being queried weren't getting tied up- are there other reasons, and what are the penalties for using it? Is there a performance hit?
 
It weirds me out that the rows returned by the view depend on the conditions in the outer query. In an uncorrelated subquery, which a view essentially expands to, isn't the output of the subquery independent of the outer query, regardless of what aggregation it performs? That is, shouldn't the maxes be performed before filtering on "doc", and thus independent of the docs queried for?
 

A.W.

Ars Tribunus Angusticlavius
6,790
Solomonoff's Secret":3w19o1j0 said:
It weirds me out that the rows returned by the view depend on the conditions in the outer query. In an uncorrelated subquery, which a view essentially expands to, isn't the output of the subquery independent of the outer query, regardless of what aggregation it performs? That is, shouldn't the maxes be performed before filtering on "doc", and thus independent of the docs queried for?
It is independent of the outer query, but the aggregation was occurring *in* the subquery, so its independent result was already filtered.
 

Handor

Ars Tribunus Militum
2,513
StanGable":fmkvs515 said:
Full story: I'm actually updating an SSRS report that utilizes this view, and I haven't had *any* training on the systems and databases this company uses.

[whiner mode] This has made for a very frustrating couple of weeks trying to finish something that should have taken 4-5 days max IMO, and also leaves me loathe to modify anything beyond what's absolutely necessary. I feel like I'm flying blind and alternate between a) wanting to call my boss and tell him to just quit fcking assigning me tasks that require a level of knowledge I haven't been given, and b) wondering if I'm just not concentrating hard enough to grasp the obvious. [/whiner]

I know those MAX()s could be gotten around by grouping, but I'm not sure why the original developer used them instead.

Regarding the NOLOCKs, I assume he/she just wanted to make sure the tables being queried weren't getting tied up- are there other reasons, and what are the penalties for using it? Is there a performance hit?

Ouch, you have my sympathies. Sounds pretty unpleasant.

I'll leave the MAX statements alone, because they don't really seem to be your responsibility at the moment. The problem I see is just that most of the users I deal with would tend to assume that all the values in the single row returned from that portion of the query came from the same source record, unless it were made very clear that that wasn't the case (which it's not here, of course). I'd just file that in the back of my head in case questions arise later, or if you find a good opportunity to broach the topic with someone who might know.

As far as the NOLOCKs go, the only reason you might use it is to avoid problems due to locking-- either this query takes a really long time to run and bogs down others in the system, or other operations take a long time and bog down this one. But databases lock for a reason. You could get completely inconsistent results, because you're liable to be reading data that's in the middle of a transaction.

So let's say you want to query the balance of a number of accounts associated with an organization. If your NOLOCK query hits that data while a transfer of $100k is under way, that $100k being transferred might show up in the source account, the destination account, both, or neither, depending on just when in the process you ask. Alternatively, suppose a transaction goes haywire and generates spurious data that will get caught down the line before the transaction commits, generating a rollback. You might end up reading data that never would actually have made it to a committed state, so who knows what it might show?

In other words, I personally would basically never use a NOLOCK, not unless I really, really didn't care about the consistency of the data being returned. If the user only cares about a very impressionistic understanding of the data, then I guess that might be a justifiable reason to keep it on the table. Even then, though, I probably wouldn't use it. I'd find other solutions, like better indexing, data replication so the work could be done on a different copy of the data, or some other, less volatile way of solving the problem.
 

Handor

Ars Tribunus Militum
2,513
Solomonoff's Secret":3e94uwtq said:
It weirds me out that the rows returned by the view depend on the conditions in the outer query. In an uncorrelated subquery, which a view essentially expands to, isn't the output of the subquery independent of the outer query, regardless of what aggregation it performs? That is, shouldn't the maxes be performed before filtering on "doc", and thus independent of the docs queried for?

No, the MAXes are happening in the SELECT statement whose WHERE includes the criteria filtering on the doc. Unless you're seeing something I'm not?
 
Status
Not open for further replies.