How to return 0 instead of null in postgresql?

Member

by dedrick , in category: MySQL , a month ago

How to return 0 instead of null in postgresql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , a month 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.