SQL Join query to return matching and non-matching record - sql

I am working on a SQL Syntax to write a Join query.
I couldnt get the expected output, i request expert to help me.
Table: Table1
ScriptNumber Date Filled RefillsLeft
100 01/02/2014 1
200 01/03/2014 0
300 01/22/2014 3
Table : Table 2
ScriptNumber Date Filled RefillsLeft
100 02/02/2014 0
Expected output
ScriptNumber Date Filled RefillsLeft
100 02/02/2014 0
300 null null
SQL Statement
SELECT Table_2.ScriptNumber
,Table_2.DateFilled
,Table_2.RefillsLeft
FROM Table_1
LEFT JOIN Table_2
ON Table_1.ScriptNumber = Table_2.ScriptNumber

Your problem is coming from including columns in SELECT statement from table_2 that do not have values for rows that exists in table_1. You need to change SELECT Table_2.ScriptNumber to SELECT Table_1.ScriptNumber
As future reference make sure you always select all relevant columns from LEFT tables and only columns you need from RIGHT table. Otherwise you end up with less NULL rows instead of having data that is present in LEFT table.

A left join could be useful here to get the records you want in Table_1 and any relevant details that may exist in Table_2
select Table_1.ScriptNumber
, Table_2.DateFilled
, Table_2.RefillsLeft
from Table_1
left join Table_2 on Table_1.ScriptNumber = Table_2.ScriptNumber
where Table_1.RefillsLeft > 0
Such a description is helpful in your questions, too.

Related

Multiple table join query - IDs and data tables

SOLVED turns out it was my where clause which was throwing off the results, I changed this out and added the where clause to the ON statement
I need some help.
I have a table with 25 million IDs and 4 tables with IDs and data. I need to create a new table with these 25 million IDs as well as the associated table data from the 4 tables. Each data table will not contain the full 25 million IDs. So as an example;
ID Table:
ID
A
B
Table 1
ID
measure_a
measure_b
B
1
3
Table 2
ID
measure_f
measure_g
A
3
4
etc..
Expected output:
ID
measure_a
measure_b
measure_f
measure_g
A
3
4
NULL
NULL
B
NULL
NULL
1
3
The most important thing is the 25 million IDs are in the final table. I've tried multiple joins but end up with a hugely reduced number of IDs which I believe is due to the IDs which don't match on the join condition being filtered out.
Any help is greatly appreciated.
You would use left joins:
select ids.id, t1.measure_a, t1.measure_b, t2.measure_f, t2.measure_g
from ids left join
table1 t1
on ids.id = t1.id left join
table2 t2
on ids.id = t2.id;

Duplicate rows in left join

I have 2 tables. There are about 100000 of null in one column, other values are integer, total values are about 200000. Another table has only the integer value. When I use the left join on this column, it gave me a lot of duplicates rows. Is it ok to use left join here?
Table 1:
Column 1
2
3
5
null
null
Table 2:
Column 1
1
2
3
so on
Your example is really odd. Why would anyone have null values in an ID field? But anyway.
If you need fields from table 2 in the resultset as you say above then you must use an INNER JOIN not a LEFT JOIN
Something like:
SELECT DISTINCT a.id, a.name, b.someOtherField
FROM Table1 a
INNER JOIN Table2 b ON a.id = b.id
Please note: Since only the ID field of table 1 has null values there will be no records selected from table 1 with id IS NULL because they have no equivalent in table 2. Adding the DISTINCT keyword helps in case this query would still produce duplicates.

SQL 'belong to' logic

So, I have been trying to write a query in SQL but facing an issue. I am trying to write a 'belongs to' kind of condition. What I want to do is if the values being fetched belongs to a column in another table then populate one thing otherwise populate null.
for ex.
NAME table
ID NAMES
1 A
2 B
3 C
4 D
5 E
XYZ table
ID
2
4
5
I wrote the query something like this
(CASE WHEN NAME.ID IN (SELECT ID FROM XYZ) THEN NAME.NAMES ELSE NULL END ) AS 'ABC'
This query does run but it has been running for 14 hours (OBVIOUSLY FOR A VERY HUGE AMOUNT OF DATA) and still there is no result. Is there some flaw in this logic or is there some better way it could be done?
I expect a result like this:
ABC
NULL
B
NULL
D
E
You just need a plain left join here:
SELECT
CASE WHEN t2.ID IS NOT NULL THEN t1.NAMES END AS ABC
FROM NAME t1
LEFT JOIN XYZ t2
ON t1.ID = t2.ID;
Demo
Note that a CASE expressions else condition, if not explicitly specified, defaults to NULL. This behavior works here because you want to render NULL if a given record in the NAME table does not match to any record in the XYZ table.
The problem isn't your logic. It is simply how the code is optimized. The subquery is probably being run for each row in the outer query.
I would recommend switching to exists:
(case when exists (select 1 from xyz where xyz.id = name.id) then name.names
end) as abc
This maintains the semantics of your original query. In particular, there is no danger that duplicates in xyz would return multiple rows (as would happen with a left join).
For performance for this -- or for the left join -- you want an index on xyz(id).

how to fetch distinct records from 3 tables which should contain all the values from 1 table

I have query which should fetch all the matching records from 3 tables. other records which are not common in three tables, it should union the records from first table..
EX:
select a.x,a.y,a.z
from table1 a,table2 b,table3 c
where a.x=b.x
and b.x=c.x;
above query will fetch common records among all 3 tables.
I need to add the records to my result set which are not present in table2 or table3.
Records should come like below:
1 abc acd
2 xyz xzy
3 pqr prq
4 null null -- incase 4 is not present in either table2 or table3
You need to use an outer join instead:
select a.x,a.y,a.z
from table1 a
left join table2 b on a.x=b.x
left join table3 c on b.x=c.x;
A Visual Explanation of SQL Joins
You state
other records which are not common in three tables, it should union
the records from first table.
Then state
I need to add the records to my result set which are not present in
table2 or table3.
For the first case use a full outer join which will return all rows from all tables. For the second case use left joins which will leave out rows that have no match to table1.

SQL STATEMENT QUERY

I have table1Name with data populated and table2 with no data populated.
select * from [database1Name].dbo.table1Name
join [database1Name].dbo.table2Name
on [database1Name].dbo.table1Name.fieldName like value;
After running the above sql statement it joins the tables but does not show any populated data from the table 'table1Name'.
Why does this happen?
Using JOIN which is an INNER JOIN means that it will get you only data where the condition matches. So if the second table has not data, then the condition is never met, so you get no data in return.
In your case you need a LEFT JOIN. This will get all the rows from the left table (table1Name in your case) and the corresponding values from the right table when the condition is met.
SELECT *
FROM [database1Name].dbo.table1Name
LEFT JOIN [database1Name].dbo.table2Name
ON [database1Name].dbo.table1Name.fieldName like [database1Name].dbo.table2Name.fieldName;
Just to mention that using joins mean that you might get multiple times a single row from a specific table. For instance since you have a LIKE condition, if fieldName of Table 1 matches fieldName in 2 rows from Table 2 then you will get two rows containing the same row from Table 1 and the two rows from Table 2:
Example:
Table1
FieldName
1
2
Table2
FieldName OtherField
1 1
1 2
Result of LEFT JOIN
T1FieldName T2FieldName T2OtherField
1 1 1
1 1 2
2 NULL NULL