UPDATE
I have tried most of the offered solutions and they work only when I pass a specific 'material_id'.
When I run the function on a bigger dataset it runs forever...
I work in Azure Synapse on a serverless SQL pool, so I am not sure if I can create indexes, as this was mentioned few times.
Could the problem really be in the indexing and not in the query itself?
It might be a silly question, but I am not as experienced as most of you so you will have to forgive me!!
I have a SQL function which works just fine when I am running it on a smaller table.
However, when I run the function in bigger queries the performance is so bad that I wouldn't even call it a working function...
From what I have read in some posts here, the fact that I have CASE WHEN statements as a nested query in a WHERE clause is the first problem.
The second, I imagine, is the fact that the query in the function is being execute for each row in the dataset (not sure, it is my understanding).
I am hoping that someone can help me re-write the query so that it works on bigger datasets.
The purpose of the function is to find the most recent material price at the time a material order is created.
CREATE FUNCTION my_db_name.get_price_at_mo_order
(@Material_Id VARCHAR(20),
@MO_Date DATE)
RETURNS table AS
RETURN
(SELECT
mp.price, m.product_code
FROM
my_db_name.price mp
LEFT JOIN
my_db_name.material m ON mp.material_id = m.material_id
WHERE
mp.material_id = @Material_Id
AND mp.start_date = (SELECT DISTINCT
CASE
WHEN (SELECT COUNT(*)
FROM my_db_name.price
WHERE material_id = @Material_Id
AND start_date <= @MO_Date) >= 1
THEN (SELECT MAX(CAST(start_date AS DATE))
FROM my_db_name.price
WHERE material_id = @Material_Id
AND start_date <= @MO_Date)
WHEN @MO_Date < (SELECT MIN(CAST(start_date AS DATE))
FROM my_db_name.price
WHERE material_id = @Material_Id)
THEN (SELECT MIN(CAST(start_date AS DATE))
FROM my_db_name.price
WHERE material_id = @Material_Id)
ELSE
(SELECT MAX(CAST(start_date AS DATE))
FROM my_db_name.price
WHERE material_id = @Material_Id)
END AS 'test'
FROM
my_db_name.price))