Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a column value input as a default for another column in the same insert statement?

Tags:

postgresql

I would like to know if it is possible to reuse a column input value as a default for another column value input if it is left blank. I've tried to simply stuff the reference after the DEFAULT code.

CREATE TABLE members (
    name varchar(50) NOT NULL,
    username varchar(50) DEFAULT name
    );

INSERT INTO members (name) VALUES ('el duderino');
SELECT * FROM members;

Desired results;

     name     |   username
--------------+--------------
 el duderino  | el duderino

The insert statement runs but doesn't find the table as it doesn't get built due to the following error...

psql:website.sql:38: ERROR: cannot use column references in default expression

Is it possible to reference the value first name in the default statement in one line? Or does this have to be done in stages?

like image 950
TekkSparrow Avatar asked Apr 03 '17 17:04

TekkSparrow


1 Answers

If you are getting a similar error when setting default values in Postgres. For example :

ERROR: cannot use column reference in DEFAULT expression LINE 6: is_used boolean DEFAULT No,

The solution is to put your default value in single quotes;

like image 110
Deolu Philip Avatar answered Oct 08 '22 10:10

Deolu Philip