Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSql column unique and not null

My Problem is to make the Column email NOT NULL AND UNIQUE

ALTER TABLE benutzer ADD email VARCHAR(75) UNIQUE;

works fine but

ALTER TABLE benutzer ADD email VARCHAR(75) UNIQUE NOT NULL;

or

ALTER TABLE benutzer ADD email VARCHAR(75) UNIQUE ,NOT NULL;

work not fine :-(

the error is:

FEHLER: Syntaxerror by „NULL“

I don't understand the Problem from Postgresql >.<

EDIT:

I have solve the Problem. The Solution for my Problem is to delete the records in my Table.

like image 293
user3763754 Avatar asked Jul 03 '26 07:07

user3763754


1 Answers

It is not possible to add a new column that is both UNIQUE and NOT NULL at the same time, when it contains existing records.

The reason for this is due to the fact that adding a column gives it null values to start with, and simultaneously saying there are not allowed to nulls is a contradiction.

  1. The solution is to remove your data, add the column then add the data back

OR

  1. create unique default data for the new column

OR

  1. create the column first, generate unique data for it, then add NOT NULL afterwards

for reference another answer with more info: Create unique constraint with null columns

like image 54
Zaffer Avatar answered Jul 05 '26 22:07

Zaffer