If i have an empty table (created but without rows in it), and i would like to get the number 0
from the below query, how i could achieve that?
select count(*) over (partition by field_name)
from my_empty_table
Right now the postgres doesn't emmit any results as the table is empty.
1 Answer 1
Your query outputs one row for each row in the table, so an empty table must result in an empty output. (COALESCE handles NULL values, but what you have is not a NULL value, but no value at all.)
You could add another query:
select count(*) over (partition by field_name)
from my_empty_table
union all
select 0
from my_empty_table
where not exists (select * from my_empty_table);
-
Let's starts by a thanks! I have update the needs behind my question in the case you may have a tip for me. This answer solves the question an shall be considered the corrrect one!.Victor– Victor2018年10月12日 12:03:13 +00:00Commented Oct 12, 2018 at 12:03
-
take a look at this snippet it also works! It is based on your idea about using "not exists"
SELECT CASE WHEN NOT EXISTS (SELECT TRUE FROM my_table) THEN 1 ELSE (select count(*) over (partition by org_id) + 1 FROM my_table) END AS next_internal_id
Victor– Victor2018年10月12日 15:28:59 +00:00Commented Oct 12, 2018 at 15:28
Explore related questions
See similar questions with these tags.
org_id
, you get multiple output rows. Is that really what you want?insert into <table> (a,b,c) values select 1,3,4,(<insert here the subquery for getting the internal id>
)... not sure if the best strategy.. i know that i could make this within the selection (instead of the insertion) usingrow_number() over partition by
... an assing an internal id "on the fly" as that internal_id has no meaning in the data model