How to return 0 instead of null in postgresql?

Member

by dedrick , in category: MySQL , a year ago

How to return 0 instead of null in postgresql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a year ago

@dedrick 

In PostgreSQL, the COALESCE function can be used to return 0 instead of null.


For example, if you want to return 0 instead of null in a specific column of a table, you can use the following query:

1
2
SELECT COALESCE(column_name, 0) AS new_column_name
FROM table_name;


This query will return the value of the specified column, but if the value is null, it will be replaced with 0 instead.


Alternatively, you can also use the following query to set a default value of 0 for a column in a table:

1
2
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT 0;


With this query, any new rows inserted into the table will have a value of 0 in the specified column if no value is provided.


These are two ways to return 0 instead of null in PostgreSQL.

Related Threads:

How to return 0 instead of null in laravel?
How to return null results in sparql?
How to set value to null in PostgreSQL?
How to add 0 in front of number in PostgreSQL?
How to coalesce two column with default value 0 in postgresql?
How to return randomly multiple rows in postgresql?