Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for String in PostgreSQL

I'm trying to make an table, with few properties in it. My model is Account has description property, which, by default is supposed to be "No description available for this account"

CREATE TABLE accounts
(
...
description VARCHAR DEFAULT 'No description available for this account',
...
);

In an controller description is only set if it's not empty and not equals to "\n" like that

if(!description.isEmpty() && !description.equals("\n"))
{
  account.setDescription(description);
}

After the app runs I get a table of accounts, but the property description still equals null, with no default value. Any ideas?

like image 272
John Johnson Avatar asked Feb 16 '26 07:02

John Johnson


1 Answers

Postgres sets default value only when no value is provided + NULL value is not allowed for the column.

  1. Handling at DB level:

In table creation script

description VARCHAR DEFAULT 'No description available for this account' NOT NULL

This will make update all the existing records as well

  1. Handling in code Initialize the description property with the default value(Ideally sourced from a Constants file).

private String description = "No description available for this account";

Also put a NULL check on the setter method.

like image 192
siddhant vispute Avatar answered Feb 18 '26 20:02

siddhant vispute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!