Search code examples
sqlsql-serverjoinleft-joininner-join

Optimize SQL Query Using Join


I was using 2 variables with a SELECT statement for each.

I was told that I could optimize my query by using JOIN to do the query just once.

I managed to combine the statement into one. But it did not use JOIN, and there are still 2 SELECT statements in my current query.

Current query:

BEGIN

DECLARE @EntityId int, @Country nvarchar(10), @OrganizationId int, 
@Username nvarchar(100) = 'user1'

Set @OrganizationId = (SELECT BU.OrganizationId 
FROM [Company].[Config].[BusinessUnit] BU 
WHERE BU.EntityId = (SELECT BU.EntityId
FROM [Company].[PES].[EmployeeProfile] EP
LEFT JOIN   Config.BusinessUnit bu on EP.EntityCode = BU.EntityCode
WHERE EP.Username = @Username))

IF(@OrganizationId = 3)
    SET @Country = 'MS'
ELSE
    SET @Country = 'SG'
SELECT @Country

END

Is my current query good to go, or can it be further improved? Thank you.


Previous query:

BEGIN

DECLARE @EntityId int, @Country nvarchar(10), @OrganizationId int, 
@Username nvarchar(100) = 'user1'

Set @EntityId = (SELECT BU.EntityId
FROM [Company].[PES].[EmployeeProfile] EP
LEFT JOIN   Config.BusinessUnit bu on EP.EntityCode = BU.EntityCode
WHERE EP.Username = @Username)

Set @OrganizationId = (SELECT BU.OrganizationId 
FROM [Company].[PES].[BusinessUnit] BU 
WHERE @EntityId = BU.EntityId)

IF(@OrganizationId = 3)
    SET @Country = 'MS'
ELSE
    SET @Country = 'SG'
SELECT @Country

END

Solution

  • Why not combine this into a single query?

    SELECT @Country = (CASE WHEN @OrganizationId = 3 THEN 'MS'
                            ELSE 'SG'
                       END)
    FROM [Company].[PES].[EmployeeProfile] EP JOIN
         Config.BusinessUnit cbu 
         ON EP.EntityCode = cbu.EntityCode JOIN
         [Company].[PES].[BusinessUnit] BU 
         ON cbu.EntityId = bu.EntityId
    WHERE EP.Username = @Username)