SQL to Match columns from 2 different tables using a Select statement - sql

I have 2 tables A & B with columns 6 columns in each table.
Table A has lesser rows than table B.
I want to write a Select Statement where if the below condition satisfies
-----A.Col1=B.Col1 and A.Col2=B.Col2 and A.Col3=B.Col3 and A.Col4=B.Col4 and A.Col5=B.Col5 and A.Col6=B.Col6-----
if all conditions are satisfied then in a new column say "Match" else "NoMatch"
How do I do that ?

I would suggest using exists. If you want a new column in A:
select a.*,
(case when exists (select 1
from b
where A.Col1 = B.Col1 and A.Col2 = B.Col2 and
A.Col3 = B.Col3 and A.Col4 = B.Col4 and
A.Col5 = B.Col5 and A.Col6 = B.Col6
)
then 'match' else 'nomatch'
end) as flag
from a;
Note: If you want the new column on B, the logic is the same but the two tables are reversed.
If any of the columns can have NULL values, then you need to take that into account.

You can use CASE statement and I am considering that you need all data from tableB and matching data from tableA as follows:
select b.*, a.*,
case when A.Col1=B.Col1 and A.Col2=B.Col2
and A.Col3=B.Col3 and A.Col4=B.Col4
and A.Col5=B.Col5 and A.Col6=B.Col6
then 'Match'
else 'No match'
end as res
from tableB b
left join TableA a
on A.Col1=B.Col1 and A.Col2=B.Col2
and A.Col3=B.Col3 and A.Col4=B.Col4
and A.Col5=B.Col5 and A.Col6=B.Col6

Related

Can I replace Union all with any kind on joins?

I have the below query for negative testing, But I want to replace the union all if possible.
select A.*
from A
join B
on A.COL1=B.COL1
where B.COL3 is null
union all
select A.*
from A
join B
on A.COL2=B.COL4
where B.COL5 is null;
Need to get data from both SQL without using union all
You could combine the two queries into a single join and collapse the where condition into it:
select A.*
from A
join B on (A.COL1 = B.COL1 and B.COL3 is null) or
(A.COL2 = B.COL4 and B.COL5 is null)
Since you're only after data from Table A you don't need the join to table B at all and can re-write this as an Exists...
SELECT A.*
FROM A
WHERE EXISTS (SELECT 1
FROM B
WHERE A.COL1=B.COL1 and B.COL3 is null)
OR EXISTS (SELECT 1
FROM B
WHERE A.COL2=B.COL4 and B.COL5 is null)
But this has likely has two issues:
I'm pretty sure if you look at the execution plan for both; you'll find the union all is more efficient because it operates at a set level instead of a row level ad the OR needed in this is slower.
This will return 1 record from A instead of 2 from that of a union all. had it been a union; this should/would return the same results and avoid the union. But simply put you want the same data from A twice (or more depending on cardinality of joins)
SELECT A.*
FROM A
JOIN B ON (A.COL1 = B.COL1 OR A.COL2 = B.COL4) AND B.COL3 IS NULL;

PostgreSQL comparing null values in case statement

when I wrote a case statement to compare values in tables, it came unstuck with variables that are null. It thinks they are different (note: col1 is a character field).
select a.id,
a.col1 as a_col1,
b.col1 as b.col1,
case when a.col1=b.col1 then 0 else 1 end as chk_col1
from tablea a,
tableb b
where a.id=b.id;
... chk_col1 is always 0 when both col1's are null. I've tried
coalesce(a.col1,'null') as coalesce(b.col1,'null')
but this didn't work either. It still returned 1 for chk_col1.
Postgres supports the null-safe comparison operator is not distinct from. So, try this:
select a.id,
a.col1 as a_col1,
b.col1 as b.col1,
(case when a.col1 is not distinct from b.col1 then 0 else 1 end) as chk_col1
from tablea a join
tableb b
on a.id = b.id;
Personally, I would leave the value as a boolean:
select a.id, a.col1 as a_col1, b.col1 as b.col1,
(a.col1 is distinct from b.col1) as chk_col1
from tablea a join
tableb b
on a.id = b.id;
Also note that I used proper, explicit, standard, readable JOIN syntax.
SOLUTION! :
The variable referenced in the colaesce function must be the calculated one, i.e.
coalesce(a_col1,'null') as coalesce(b_col1,'null')
Another thing I discovered. Let's say col2 is numeric. The above doesn't work, you'd need to use a 0. Or ... more cunningly, you can use '0', i.e.
coalesce(a_col2,'0') as coalesce(b_col2,'0')
This is handy to know if you want to generate some code to compare tables by referencing pg_tables or svv_columns. In this code I had 2 tables that I'd created by reading svv_columns metadata table, and I wanted to created a case statement for each variable, so I'd have the two variables from each table side by side plus a check variable which I'd use for summarising later:
select ' coalesce(a.'||a.column_name||',''0'') as a_'||a.column_name||', coalesce(b.'||b.column_name||',''0'') as b_'||b.column_name||', case when a_'||a.column_name||'=b_'||b.column_name||' then 0 else 1 end as chk_'||a.column_name||','
from tbl_a_vars a,
tbl_b_vars b
where a.column_name=b.column_name;

SQL how to check is a value in a col is NOT in another table

Maybe I need another coffee because this seems so simple yet I cannot get my head around it.
Let's say I have a tableA with a col1 where employee IDs are stored.... ALL employee IDs. And the 2nd table, tableB has col2 which lists all employeeID who have a negative evaluation.
I need a query which returns all ID's from col1 from table1 and a newcol which show a '1' for those ID's which do NOT exist in col2 of TableB.
I am doing this in dashDB
One option uses a LEFT JOIN between the two tables:
SELECT a.col1,
CASE WHEN b.col2 IS NULL THEN 1 ELSE 0 END AS new_col
FROM tableA a
LEFT JOIN tableB b
ON a.col1 = b.col2
Alternatively you can achieve your requirement with LEFT JOIN along with IFNULL function as below.
SELECT a.col1,
IFNULL(b.col2, 1) NewCol
FROM tableA a
LEFT JOIN tableB b
ON a.col1 = b.col2

How to choose a proper filter for an sql join

If I have table A and table B, each with one column:
A:
col1
1
2
3
1
B:
col1
1
1
4
and I want all rows from A and the matching rows from B, only when the column has non null value in both tables, which one should I use?
select * from A left join B on A.col1 = B.col1 and A.col1 is not null AND B.col1 is not null;
select * from A left join B on A.col1 = B.col1 where A.col1 is not null OR B.col1 is not null;
select * from A left join B on A.col1 = B.col1 and (A.col1 is not null OR B.col1 is not null;)
My guess is that the first and the third are the same and will provide the desired output.
If you want to skip null values and you want to link both tables only on existing values you should use an INNER JOIN, the null check is redundant:
SELECT A.*
FROM A INNER JOIN B ON A.col1 = B.col1
NULL will never match any other value (not even NULL itself), unless the join condition explicitly uses the IS NULL or IS NOT NULL predicates.
In a comment you said you are checking for more than nulls in this case I would probaly take thederived table or CTE approach. Dervied table shown below as you did not specify which database backend, so I don't know if you can use CTEs.
select
from
(select from tablea where test is not null or test <>'' or test<>'N/A') a
JOin
(select from tableb where test is not null or test <>'' or test<>'N/A')b
ON a.col1 = b.col1
You just need
select * from A left join B on A.col1 = B.col1
NULL will never match anything (when not compared with IS NULLand the like), therefore NULL in A won't match anything in B.
Since you want all the rows from A, below query should work:
select * from A left outer join B on A.col1 = B.col1 where A.col1 is not null and A.col1<>'N/A' and A.col1<>''
http://sqlfiddle.com/#!2/98501/14

Compare the data in two tables with same schema

I have been doing a bit of searching for a while now on a particular problem, but I can't quite find this particular question
I have a rather unusual task to achieve in SQL:
I have two tables, say A and B, which have exactly the same column names, of the following form:
id | column_1 | ... | column_n
Both tables have the same number of rows, with the same id's, but for a given id there is a chance that the rows from tables A and B differ in one or more of the other columns.
I already have a query which returns all rows from table A for which the corresponding row in table B is not identical, but what I need is a query which returns something of the form:
id | differing_column
----------------------
1 | column_1
3 | column_6
meaning that the row with id '1' has different 'column_1' values in tables A and B, and the row with id '3' has different 'column_6' values in tables A and B.
Is this at all achievable? I imagine it might require some sort of pivot in order to get the column names as values, but I might be wrong. Any help/suggestions much appreciated.
Yes you can do that with a query like this:
WITH Diffs (Id, Col) AS (
SELECT
a.Id,
CASE
WHEN a.Col1 <> b.Col1 THEN 'Col1'
WHEN a.Col2 <> b.Col2 THEN 'Col2'
-- ...and so on
ELSE NULL
END as Col
FROM TableOne a
JOIN TableTwo b ON a.Id=b.Id
)
SELECT Id, Col
WHERE Col IS NOT NULL
Note that the above query is not going to return all the columns with differences, but only the first one that it is going to find.
You can do this with an unpivot -- assuming that the values in the columns are of the same type.
If your data is not too big, I would just recommend using a bunch of union all statements instead:
select a.id, 'Col1' as column
from a join b on a.id = b.id
where a.col1 <> b.col1 or a.col1 is null and b.col1 is not null or a.col1 is not null and b.col1 is null
union all
select a.id, 'Col2' as column
from a join b on a.id = b.id
where a.col2 <> b.col2 or a.col2 is null and b.col2 is not null or a.col2 is not null and b.col2 is null
. . .
This prevents issues with potential type conversion problems.
If you don't mind having the results on one row, you can do:
select a.id,
(case when a.col1 <> b.col1 or a.col1 is null and b.col1 is not null or a.col1 is not null and b.col1 is null
then 'Col1;'
else ''
end) +
(case when a.col2 <> b.col2 or a.col2 is null and b.col2 is not null or a.col2 is not null and b.col2 is null
then 'Col2;'
else ''
end) +
. . .
from a join b on a.id = b.id;
If your columns are of the same type, there is a slick method:
SELECT id,col
FROM (SELECT * FROM A UNION ALL SELECT * FROM B) t1
UNPIVOT (value for col in (column_1,column_2,column_3,column_4)) t2
GROUP BY id,col
HAVING COUNT(DISTINCT value) > 1
If you need to handle NULL as a unique value, then use HAVING COUNT(DISTINCT ISNULL(value,X)) > 1 with X being a value that doesn't occur in your data