S
S
Stergy2019-07-18 17:52:57
PostgreSQL
Stergy, 2019-07-18 17:52:57

How to add only unique values ​​in a PostgreSQL query?

I am writing in ruby, there is a function that adds data to the table using a Postgres query, how can I fix the query so that the data is added if the name field with such data does not yet exist. If the table already has a row with the same name field, then do not add anything.
Here is the request itself:

INSERT INTO plans (name, holl_id, status, start_date, end_date,
       review_start_date, review_end_date, approval_date, expiration_date, created_at, updated_at)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2019-07-18
@melkij

on conflict do nothing
https://www.postgresql.org/docs/current/sql-insert.html
Well, a unique field index, of course.
If you are on 9.4 in which there is no on conflict - update. 9.4 EOL after six months.

M
Michael, 2019-07-18
@MisFis123

You need to add a Unique Constraint on the name field
https://www.postgresql.org/docs/9.4/ddl-constraint... section 5.3.3

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question