9951 explained code solutions for 126 technologies


postgresqlHow can I ensure a field in PostgreSQL is not null?


To ensure a field in PostgreSQL is not null, you can add a NOT NULL constraint when creating the table. For example:

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(50) NOT NULL
);

This will create a table named users with two columns, id and username, where the username column is not allowed to be null.

The parts of the code are as follows:

  • CREATE TABLE users - Creates a table named users
  • id SERIAL PRIMARY KEY - Creates an auto-incrementing id column as the primary key
  • username VARCHAR(50) NOT NULL - Creates a username column of type VARCHAR with a maximum length of 50 characters, and adds a NOT NULL constraint, which ensures the column cannot be null.

Helpful links

Edit this code on GitHub