1

I want to filter a query based on a conditional condition, for example if ProjectId equals 1 then filter based on some condition otherwise, another diffrerent condition:

something that- if possible in SQL- would look like this:

SELECT * FROM [dbo].[Commits] 
WHERE CASE WHEN ProjectId=1 THEN (CommitsCount > 2) ELSE (Name LIKE 'R%') END

Example:

ProjectId   Name      CommitsCount
----------- --------- -----------
1           Ahmed     2
1           Ahmed     6
2           Kamel     10
3           Rami      NULL

The result I need from the query is:

ProjectId   Name      CommitsCount
----------- --------- -----------
1           Ahmed     6
3           Rami      NULL

2 Answers 2

2

Use case conditions in where clauses is not recommended. One reason is that they impede optimization of the query. Another is simply that they are not needed, so it make the conditions more complicated than necessary.

So I would recommend:

select c.*
from dbo.commits c
where (c.ProjectId = 1 and c.CommitsCount > 2) or
      (c.ProjectId <> 1 and c.Name = 'R&');
Sign up to request clarification or add additional context in comments.

Comments

1

You could use:

SELECT * 
FROM [dbo].[Commits] 
WHERE (CASE WHEN ProjectId  = 1 AND CommitsCount > 2 THEN 1
            WHEN ProjectId != 1 AND Name LIKE 'R%'   THEN 1
      END) = 1

db<>fiddle demo

(Name ='R&') => Name LIKE 'R%'

2 Comments

I've added an example, illustrating how should the result be
Oh thanks I have a mistake in my query (used & instead of %), great answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.