patternsqlMinor
How come an INNER JOIN returns zero rows when I use coalesce?
Viewed 0 times
rowscomecoalescejoinreturnshowinnerwhenzerouse
Problem
I have the following query:
The column named
How can I set this value to
SELECT CPC.importe
FROM fac_factura FAC
INNER JOIN fac_concepto_periodo_control CPC ON CPC.id_factura = FAC.id
INNER JOIN fac_factura_deuda_pendiente FDP ON FDP.id_factura = FAC.id
INNER JOIN fac_item_facturacion FIF ON CPC.id_item_facturacion = FIF.id
WHERE FIF.codigo = 427
AND FDP.estado ILIKE 'CANCELADA'
AND CPC.estado ILIKE 'FACTURADO'The column named
importe is numeric but the JOIN conditions are not being fulfilled so it returns a blank value instead of a NULL mark.How can I set this value to
0 instead of a blank value, I tried with COALESCE but it's not working.Solution
The column named importe is numeric but the JOIN conditions are not being fulfilled so it returns a blank value instead of a NULL mark.
How can I set this value to 0 instead of a blank value, I tried with COALESCE but it's not working.
If the join conditions are not being fulfilled you have 0-rows. An INNER JOIN on false returns 0-rows: not one row with a null value, not one row with a zero.
Returns nothing. What you want is an outer join.
Now that you have a row, you can use
How can I set this value to 0 instead of a blank value, I tried with COALESCE but it's not working.
If the join conditions are not being fulfilled you have 0-rows. An INNER JOIN on false returns 0-rows: not one row with a null value, not one row with a zero.
SELECT x,y
FROM ( VALUES (1) ) AS t(x)
JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
(0 rows)Returns nothing. What you want is an outer join.
SELECT x,y
FROM ( VALUES (1) ) AS t(x)
LEFT OUTER JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
1 |
(1 row)Now that you have a row, you can use
COALESCESELECT x, coalesce(y,0) AS y
FROM ( VALUES (1) ) AS t(x)
LEFT OUTER JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
1 | 0
(1 row)Code Snippets
SELECT x,y
FROM ( VALUES (1) ) AS t(x)
JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
(0 rows)SELECT x,y
FROM ( VALUES (1) ) AS t(x)
LEFT OUTER JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
1 |
(1 row)SELECT x, coalesce(y,0) AS y
FROM ( VALUES (1) ) AS t(x)
LEFT OUTER JOIN ( VALUES (2) ) AS g(y)
ON false;
x | y
---+---
1 | 0
(1 row)Context
StackExchange Database Administrators Q#176822, answer score: 2
Revisions (0)
No revisions yet.