0

How to get all data from 1st table and corresponding data from 2nd table?

Hello, I have two tables. I need all data from 1st table and one column from 2nd table but putt null if there is no data in 2nd table. What I do SELECT O.*, E.EXPLANATION FROM OBIS_CODE O INNER JOIN EXPLANATION E ON O.OBIS_CODE = E.OBIS_CODE This return me the data if there is data in 2nd table but I need null if there is no data. Please help.

20th Nov 2017, 7:56 AM
Salman Mushtaq
Salman Mushtaq - avatar
11 Respuestas
+ 3
Try this: SELECT O.*, E.EXPLANATION FROM OBIS_CODE O LEFT OUTER JOIN EXPLANATION E ON E.OBIS_CODE = O.OBIS_CODE;
20th Nov 2017, 8:03 AM
Ipang
+ 3
@Salman You are correct that ISNULL will work in this example. However, it's not advised for all occasions. Checkout the link in my previous response and go to the section titled "Comparing COALESCE and ISNULL" for potential issues that might eventually cause problems for other uses in the future.
20th Nov 2017, 9:20 AM
David Carroll
David Carroll - avatar
+ 3
Here is an excellent article with a breakdown of scenerios where ISNULL can be problematic with unexpected behavior: - http://www.itprotoday.com/software-development/coalesce-vs-isnull
20th Nov 2017, 9:28 AM
David Carroll
David Carroll - avatar
+ 2
Thanks Ipang. It works fine. Just one thing can I change the text Null to Not Available?
20th Nov 2017, 8:15 AM
Salman Mushtaq
Salman Mushtaq - avatar
+ 2
What is the DBMS please..?
20th Nov 2017, 8:17 AM
Ipang
+ 2
MS SQL SERVER
20th Nov 2017, 8:25 AM
Salman Mushtaq
Salman Mushtaq - avatar
+ 2
Its work with below query SELECT O.*, ISNULL (E.EXPLANATION, 'Not Available') FROM OBIS_CODE O LEFT OUTER JOIN EXPLANATION E ON E.OBIS_CODE = O.OBIS_CODE; Thanks all
20th Nov 2017, 8:52 AM
Salman Mushtaq
Salman Mushtaq - avatar
+ 2
@David, thanks for the hand, interesting point that is :) @Salman Mushtaq, sorry for the delay, something just came up, yes the ISNULL function is designed for the purpose, yet @David's suggestion is also a viable solution so you might give it a try. Cheers! @All
20th Nov 2017, 9:41 AM
Ipang
+ 2
@David thanks man for such a valuable information. @Ipang thanks dear. Best of all ! happy coding :)
20th Nov 2017, 10:57 AM
Salman Mushtaq
Salman Mushtaq - avatar
+ 1
@Salman You will want to use the COALESCE SQL function in MS SQL Server. - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/coalesce-transact-sql Applying this to Ipang's example: SELECT O.*, COALESCE (E.EXPLANATION, 'Not Available') AS EXPLANATION FROM OBIS_CODE O LEFT OUTER JOIN EXPLANATION E ON E.OBIS_CODE = O.OBIS_CODE;
20th Nov 2017, 8:36 AM
David Carroll
David Carroll - avatar