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.
11 Respostas
+ 3
Try this:
SELECT O.*, E.EXPLANATION
FROM OBIS_CODE O LEFT OUTER JOIN EXPLANATION E ON E.OBIS_CODE = O.OBIS_CODE;
+ 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.
+ 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
+ 2
Thanks Ipang. It works fine. Just one thing can I change the text Null to Not Available?
+ 2
What is the DBMS please..?
+ 2
MS SQL SERVER
+ 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
+ 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
+ 2
@David thanks man for such a valuable information. @Ipang thanks dear.
Best of all ! happy coding :)
+ 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;