postgresql
  1. postgresql-not-null-constraint

Not-Null Constraint - (PostgreSQL Constraints)

In PostgreSQL, constraints are used to enforce rules on data columns in a table. The NOT NULL constraint is used to prevent a column from containing null (undefined) values. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the NOT NULL constraint in PostgreSQL constraints.

Syntax

CREATE TABLE table_name (
  column1 datatype NOT NULL,
  column2 datatype,
  column3 datatype NOT NULL,
  ...
);

Example

Let's create a table with the NOT NULL constraint on two columns.

CREATE TABLE cars (
  id serial PRIMARY KEY,
  make varchar(50) NOT NULL,
  model varchar(50),
  year integer NOT NULL
);

In this example, the make and year columns are defined with the NOT NULL constraint, while the model column is not.

Explanation

In the above example, we created a table named cars. The NOT NULL constraint was applied to the make and year columns to ensure that they always contain a value and not null. The model column does not have the NOT NULL constraint and can be null.

If you attempt to insert NULL into the make or year columns, you will receive an error. For example:

INSERT INTO cars (make, model, year) VALUES (NULL, 'Accord', 2021);

The above statement will result in an error because we attempted to insert NULL into the make column.

Use

The NOT NULL constraint is useful for ensuring that important data is not missing from a column. It can be used on columns that are required for the proper functioning of the application or database.

Important Points

  • The NOT NULL constraint can be applied to any data type.
  • A table can have multiple columns with the NOT NULL constraint applied to them.
  • Columns defined with the primary key constraint are implicitly defined as NOT NULL.

Summary

In this tutorial, we discussed the NOT NULL constraint in PostgreSQL constraints. We covered the syntax, example, output, explanation, use, and important points of the NOT NULL. The NOT NULL constraint is a simple yet powerful tool that helps maintain data integrity by preventing the insertion of null values in a specified column. With this knowledge, you can now create tables with the NOT NULL constraint or add the constraint to an existing column in your PostgreSQL database.

Published on: