Search code examples
sqlpostgresqlpgadmin

Can I add a default constraint to a column in a view in POSTGRES?


I have a simple view. It consists of a few columns from a table and a few new columns which are based on the values of the ones from the tables. It looks like this:

| flightid | capacity | bookedseats | availablseats |

available seats is simply (capacity - bookedseats). However, sometimes bookedseats is NULL, when no seats are booked. Which then makes availableseats NULL also. I would ideally like availableseats to be 0. Is this possible?

I thought I could add a default constraint, to set it to 0 when nothing is booked but I can't work out how to apply a DEFAULT constraint to a column in a view.

Any ideas?

Thanks


Solution

  • you can use DEFAULT only on insert with VALUES, to coalesce NULL, use COALESCE in query, eg: select coalesce(availablseats,0) availablseats it will give 0 if availablseats is null