sqlsql-servert-sql

How to combine two queries keeping all results from one


I have a table of Accounts:

AccountID Name
1 Account A
2 Account B
3 Account C
4 Account D
5 Account E

and a table of CurrentAccounts:

AccountID
2
4

The desired result of combining these two tables is:

AccountID Name Active
1 Account A False
2 Account B True
3 Account C False
4 Account D True
5 Account E False

I have achieved the desired result with this SQL:

DECLARE @T1 AS TABLE (ID INT, Name VARCHAR(20), Active BIT);
    
INSERT INTO @t1 
    SELECT ID, Name, 0 
    FROM Accounts;

UPDATE @T1 
SET Active = 1 
WHERE ID IN (SELECT ID FROM CurrentAccounts);
    
SELECT * FROM @T1

However, there must be a more efficient way of achieving the same result.


Solution

  • A simple sub-query will give you the results you require:

    create table Account (AccountId int, Name varchar(128));
    create table CurrentAccount (AccountId int);
    
    insert into Account (AccountId, Name)
    values
    (1, 'Account A'),
    (2, 'Account B'),
    (3, 'Account C'),
    (4, 'Account D'),
    (5, 'Account E');
    
    insert into CurrentAccount (AccountId)
    values
    (2),
    (4);
    
    select
        *
        , case when exists (select 1 from CurrentAccount ca where ca.AccountId = a.AccountId) then 'True' else 'False' end Active
    from Account a;
    
    AccountId Name Active
    1 Account A False
    2 Account B True
    3 Account C False
    4 Account D True
    5 Account E False

    db<>fiddle