query results sorted randomly with each execution

braxx 461 Reputation points
2021-03-26T14:20:34.333+00:00

Need your advice guys!

I am doing a migration of SQL queries from Oracle to Sql Server and observed a weird behavior of one of them. Each execution of the below query may give me results sorted different way and the wrong calculation of BAR_CURR_CODE column. While the same query run in Oracle always returns the same, stable results.

SELECT  
	PROD_ID,  
	UOM_ID,  
	FIRST_VALUE(BAR_CURR_CODE) over(partition BY prod_id order by  
						  		case   
								when UOM_ID in ('IT') then 1  
								when UOM_ID in ('MP') then 2  
								when UOM_ID in ('BP') then 3  
								when UOM_ID in ('CS') then 4  
								when UOM_ID in ('SW') then 5  
								else 99 end  
								) AS BAR_CURR_CODE  
	, BAR_CURR_CODE AS org_BAR_CURR_CODE  
FROM  
	[BSR_STG_Q].[Cdl_Prod_Uom_Fct]  
WHERE  
	curr_ind  = 'Y'  
	and BAR_CURR_CODE is not null  
	and prod_Id = '00267461'  

Here is the proof. First execution in SQL Server. BAR_CURR_CODE is different than in second execution.
81941-case1.png

Second execution in SQL Server. Made a couple of seconds after first one. Data were not updated during this time.

81934-case2.png

Here is the example of the same query from Oracle. The result is always the same with each execution

81942-case-ora1.png

I do not understand why the behaviour is different in SQL Server and Oracle and how can I fix it.
TIA

Bartek

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
0 comments No comments
{count} votes

6 answers

Sort by: Most helpful
  1. MelissaMa-msft 24,246 Reputation points Moderator
    2021-03-30T01:46:33.647+00:00

    Hi @braxx

    Thanks for your update.

    We recommend that you could post CREATE TABLE statements for your table together with INSERT statements with sample data, the creation of non-clustered index ,enough to illustrate all angles of the problem. We also need to see the expected result of the sample after executing your query.

    In SQL Server, there are clustered index and non-cluseted index and there are not Normal index or Bitmap index like in Oracle. But it has a feature called Bitmap Filters, which are different but similar. You could have a deep read on it and find out whether it is what you are looking for.

    Best regards
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.