Combining two different result set into a single query - sql

Two different queries, produce two different result set.
Query 1:
Select a.customer_name, b.salary, c.manager_name
from
table123 a
left join table456 b on a.id=b.id
left join table789 c on a.id=c.id
Query2:
Select d.prty_id, e.party_val, f.prty_nme
from
table111 d
Left join table222 e on d.id=e.id
Left join table333 f on d.id=f.id
Now I have to write one single query, which will merge this above two query's result set and display one single result set.
Can anyone please help me on this.
Output value I need to insert in a new table whose column will be like below:
customer_name salary manager_name prty_id party_val prty_nme

According to your expected result, you can use UNION or UNION ALL.
The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT statements. It removes duplicate rows between the various SELECT statements.
The Oracle UNION ALL operator is used to combine the result sets of 2 or more SELECT statements. It returns all rows from the query and it does not remove duplicate rows between the various SELECT statements.
Select con1,... , coln
from tab1
where...
union
Select con1,... , coln
from tab2
where...
Just make sure your data types match up.

Related

Coalesce gives repeat columns that prevents doing a union

I have two tables (Table 1 and Table 2) that I join to then do a coalesce. So...
SELECT t1.*,
coalesce(t1.A, t2.A_T) as A
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.key = t2.key
Doing what I said above, I will get a repeated A column given I want to replace missing values in A from Table 1 with Table 2's A column. I want to do a union but a repeated A column is an issue (as seen in Table 3). You cannot do a union with different numbers of columns.
How can I fix this issue?
What I want:
Note: the actual tables I am working with have over 40 columns each. But this example is to get to the point of my issue.
Snowflake supports exclude so you could do
select coalesce(t1.A, t2.A_T) as A, t1.* exclude(t1.A)
from ...
Note that your problem stems from the fact that you are using * to select columns instead of being explicit about which columns to select.

getting output of union all without using union all

I have been given a situation to find the common record between 2 tables without using union. I could do it. But I am not able to do 'union all'. I mean I have to find out output of 2 table including duplicate without using union all. is there anyway to do it?
table A has x column and values 1,2,3
and
table B has x column and values 3,4,5
select x from A union select x from B;
o/p 1,2,3,4,5
select x from A union all select x from B;
o/p should be 1,2,3,3,4,5,6(not necessarily in order)
Union output I can achieve through below query
select nvl(a.x,b.x) output from A full outer join B on A.x=b.X order by output;
but I am not able to do union all without using oracle inbuilt union all.
You are too close to your answer.
For union, you used following query where you have a join on column x:
select nvl(a.x,b.x) output from A full outer join B on A.x=b.X order by output;
For union all, you can use join condition which can never be satisfied. It will generate same output as union all.
So you must use following query:
select nvl(a.x,b.x) output from A full outer join B on 1=2 order by output;
Cheers!!
You may get plus points in the interview if you mention some edge cases, here it could be:
Primary Key
If the column in one of the tables is not a primary key (or at leadt unique) the proposed solution for UNION
select nvl(a.x,b.x) output from A full outer join B on A.x=b.X
fails and you have to use DISTINCT
select distinct nvl(a.x,b.x) output from A full outer join B on A.x=b.X
Nullable Column
If the column in one of the tables is nullable the proposed solution for UNION ALL
select nvl(a.x, b.x) x from a full join b on a.x is null or b.x is null
fails. The other solution with on 1=2 works fine.
I have to find out output of 2 table including duplicate without using
union all
select nvl(a.x, b.x) x from a full join b on a.x is null or b.x is null
dbfiddle

How to retrieve only those rows of a table (db1) which are not in another table (db2)

I have a table t1 in db1, and another table t2 in db2. I have the same columns in both tables.
How do I retrieve only those rows which are not in the other table?
select id_num
from [db1].[dbo].[Tbl1]
except
select id_num
from [db2].[dbo].[Tb01]
You can use LEFT JOIN or WHERE NOT IN functions.
Using WHERE NOT IN:
select
dbase1.id_num from [db1].[dbo].[Tbl1] as dbase1
where dbase1.id_num not in
(select dbase2.id_num from [db2].[dbo].[Tb01] as dbase2)
Using LEFT JOIN (recommended as this is much faster)
SELECT dbase1.id_num
FROM [db1].[dbo].[Tbl1] as dbase1
LEFT JOIN [db2].[dbo].[Tb01] as dbase2 ON dbase2.id_num COLLATE Latin1_General_CI_A = dbase1.id_num COLLATE Latin1_General_CI_A
WHERE dbase2.id_num IS NULL
Compare tables with DB2 other databases may have a select a - b statement or similar. Because at the time my database also didn't have a-b I use the following. Wrap the statement in a create table statement to dig into the results. No rows and the tables are identical. I've added in a column BEFORE|AFTER which makes the results easy to read.
SELECT 'AFTER', A.* FROM
(SELECT * FROM &AFTER
EXCEPT
SELECT * FROM &BEFORE) AS A
UNION
SELECT 'BEFORE', B.* FROM
(SELECT * FROM &BEFORE
EXCEPT
SELECT * FROM &AFTER) AS B

SQL UNION - illogical results

I have an interesting problem with UNION in SQL.
My Statement is of this form:
with tab as (
(select FldA, FldB From Table1A inner join Table1B on Field1A=Field1B)
UNION
(select FldA, FldB From Table2A inner join Table2B on Field2A=Field2B)
)
select * from tab
where FldA="XYZ"
When I run this, I get only 1 row returned - which is not correct. I can verify it's not correct just by commenting the UNION and second Select statement:
with tab as (
(select FldA, FldB From Table1A inner join Table1B on Field1A=Field1B)
--UNION
--(select FldA, FldB From Table2A inner join Table2B on Field2A=Field2B)
)
select * from tab
where FldA="XYZ"
If I run this version, I get THREE rows returned! I assume I'm doing something stupid - but I can't imagine what.
UNION removes duplicates, to keep duplicates use UNION ALL.
In this sense, UNION works the same as DISTINCT. As with DISTINCT records are considered duplicates if the records are identical for every (selected) column.
UNION removes duplicates regardless of in which set the duplicates occur, since the DISTINCT is executed after the UNION.
If you have 2 queries/data sets A and B, if you UNION these together, you get the DISTINCT combination of both. If there are duplicates in A they are removed. If a record exists in A and in B, it is also returned uniquely (i.e., it only occurs once in your final result set).
union removes duplicates from the result. A common "gotcha" with it is that it removes any duplicates from the results, regardless of whether they're duplicate between the two result sets or within any one of the result sets.
If you need to preserve these duplicates, you could use union all instead.

In SQL, a Join is actually an Intersection? And it is also a linkage or a "Sideway Union"?

I always thought of a Join in SQL as some kind of linkage between two tables.
For example,
select e.name, d.name from employees e, departments d
where employees.deptID = departments.deptID
In this case, it is linking two tables, to show each employee with a department name instead of a department ID. And kind of like a "linkage" or "Union" sideway".
But, after learning about inner join vs outer join, it shows that a Join (Inner join) is actually an intersection.
For example, when one table has the ID 1, 2, 7, 8, while another table has the ID 7 and 8 only, the way we get the intersection is:
select * from t1, t2 where t1.ID = t2.ID
to get the two records of "7 and 8". So it is actually an intersection.
So we have the "Intersection" of 2 tables. Compare this with the "Union" operation on 2 tables. Can a Join be thought of as an "Intersection"? But what about the "linking" or "sideway union" aspect of it?
You're on the right track; the rows returned by an INNER JOIN are those that satisfy the join conditions. But this is like an intersection only because you're using equality in your join condition, applied to columns from each table.
Also be aware that INTERSECTION is already an SQL operation and it has another meaning -- and it's not the same as JOIN.
An SQL JOIN can produce a new type of row, which has all the columns from both joined tables. For example: col4, col5, and col6 don't exist in table A, but they do exist in the result of a join with table B:
SELECT a.col1, a.col2, a.col3, b.col4, b.col5, b.col6
FROM A INNER JOIN B ON a.col2=b.col5;
An SQL INTERSECTION returns rows that are common to two separate tables, which must already have the same columns.
SELECT col1, col2, col3 FROM A
INTERSECT
SELECT col1, col2, col3 FROM B;
This happens to produce the same result as the following join:
SELECT a.col1, a.col2, a.col3
FROM A INNER JOIN B ON a.col1=b.col1 AND a.col2=b.col2 AND a.col3=b.col3;
Not every brand of database supports the INTERSECTION operator.
A join 'links' or erm... joins the rows from two tables. I think that's what you mean by 'sideways union' although I personally think that is a terrible way to phrase it. But there are different types of joins that do slightly different things:
An inner join is indeed an intersection.
A full outer join is a union.
This page on Jeff Atwood's blog describes other possibilities.
An Outer Join - is not related to - Union or Union All.
For example, a 'null' would not occur as a result of Union or Union All operation, but it results from an Outer Join.
INNER JOIN treats two NULLs as two different values. So, if you join based on a nullable column, and if both tables have NULL values in that column, then INNER JOIN will ignore those rows.
Therefore, to correctly retrieve all common rows between two tables, INTERSECT should be used. INTERSECT treats two NULLs as the same value.
Example(SQLite):
Create two tables with nullable columns:
CREATE TABLE Table1 (id INT, firstName TEXT);
CREATE TABLE Table2 (id INT, firstName TEXT);
Insert NULL values:
INSERT INTO Table1 VALUES (1, NULL);
INSERT INTO Table2 VALUES (1, NULL);
Retrieve common rows using INNER JOIN (This shows no output):
SELECT * FROM Table1 INNER JOIN Table2 ON
Table1.id=Table2.id AND Table1.firstName=Table2.firstName;
Retrieve common rows using INTERSECT (This correctly shows the common row):
SELECT * FROM Table1 INTERSECT SELECT * FROM Table2;
Conclusion:
Even though, many times both INTERSECT and INNER JOIN can be used to get the same results, they are not the same and should be picked depending on the situation.