postgresqlHow can I use PostgreSQL ENUM data types in my software development project?
PostgreSQL ENUM data types provide a way to define a set of possible values for a column. This can be used to ensure data integrity and avoid errors when inserting data.
Example code
CREATE TYPE status_type AS ENUM ('active', 'inactive', 'deleted');
CREATE TABLE users (
id serial PRIMARY KEY,
name varchar(50) NOT NULL,
status status_type NOT NULL DEFAULT 'active'
);
This code creates a status_type
ENUM type and a users
table with a status
column of the status_type
type. The status
column will only accept values of active
, inactive
and deleted
.
When inserting data into the users
table, you can only insert values that are part of the status_type
ENUM. For example:
INSERT INTO users (name, status) VALUES ('John Doe', 'active');
This will insert a row with the name John Doe
and a status of active
. Attempting to insert a value that is not part of the status_type
ENUM will result in an error.
Code explanation
CREATE TYPE status_type AS ENUM ('active', 'inactive', 'deleted')
: This creates astatus_type
ENUM type with three possible values:active
,inactive
, anddeleted
.CREATE TABLE users (id serial PRIMARY KEY, name varchar(50) NOT NULL, status status_type NOT NULL DEFAULT 'active')
: This creates ausers
table with anid
column,name
column, andstatus
column of thestatus_type
type. Thestatus
column has a default value ofactive
.INSERT INTO users (name, status) VALUES ('John Doe', 'active')
: This inserts a row with the nameJohn Doe
and a status ofactive
.
Helpful links
More of Postgresql
- How can I set a PostgreSQL interval to zero?
- How can I troubleshoot zero damaged pages in PostgreSQL?
- How can I use PostgreSQL and ZFS snapshots together?
- How can Zalando use PostgreSQL to improve its software development?
- How can I use PostgreSQL's "zero if null" feature?
- How do I use PostgreSQL and ZFS together?
- How do I use PostgreSQL ZonedDateTime to store date and time information?
- How can I use PostgreSQL with YAML?
- How do I use PostgreSQL's XMLTABLE to parse XML data?
- How do I store binary data in a Postgresql database using the bytea data type?
See more codes...