Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name NOT NULL constraint in CREATE TABLE query

For a test tomorrow we're told to name our constraints I know it's possible to create a constraint when you use ALTER TABLE but can you add a name to a not null constraint when you CREATE TABLE?

f.e.

CREATE TABLE test (
    test1 VARCHAR 
    CONSTRAINT nn_test1 NOT NULL (test1)
)

I get an error when trying to run this query. Am I writing it wrong?

The error I get is

ERROR:  syntax error at or near "NOT"   
LINE 3: CONSTRAINT nn_test1 NOT NULL (test1))  
                            ^
SQL state: 42601  
Character: 56
like image 800
sheetka Avatar asked Mar 08 '23 04:03

sheetka


1 Answers

You have two options to define a named not null constraint:

Inline with the column:

CREATE TABLE test 
(
   test1 VARCHAR CONSTRAINT nn_test1 NOT NULL, 
   test2 integer --<< no comma because it's the last column
);

Or at the end of columns as an out-of-line constraint. But then you need a check constraint:

CREATE TABLE test 
(
   test1 VARCHAR, 
   test2 integer, --<< comma required after the last column
   constraint nn_test1 check (test1 is not null)
);
like image 121
a_horse_with_no_name Avatar answered Mar 15 '23 13:03

a_horse_with_no_name