S
S
sirinotapple2022-03-27 23:21:03
PostgreSQL
sirinotapple, 2022-03-27 23:21:03

How can I prevent an empty field from being entered into a table?

Hello, I have

CREATE TABLE myTable (id BIGSERIAL NOT NULL PRIMARY KEY, firstName VARCHAR(50), lastName VARCHAR(50));
INSERT INTO myTable (id, firstName, lastName) VALUES (1, 'field', 'anotherField');
SELECT * FROM myTable;
6240c72ae2cec224620618.jpeg
But somehow I can
INSERT INTO myTable(lastName) VALUES('upsertedLastNameOnly orger');
(even though id is NOT NULL)
and even
INSERT INTO myTable(lastName) VALUES('upsertedLastNameOnly orger') ON CONFLICT (id) DO UPDATE SET lastName = EXCLUDED.lastName;

does not update the field, but simply adds it without an id
How to make it so that you cannot enter an empty id in the request or skip it

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2022-03-27
@sirinotapple

Where did you see an empty id?
BIGSERIAL - Equivalent to a BIGINT field with a DEFAULT value from an automatically generated sequence (do \d+ myTableit in psql for fun), so if you don't specify a value for id in the INSERT, it is taken from the sequence.
For the same reason

INSERT INTO myTable(lastName) VALUES('upsertedLastNameOnly orger') ON CONFLICT (id)
does not make sense, because there can be no conflict on id here.
In general, what exactly do you want? The id field is filled in and cannot be empty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question