1

I have to insert some data in my table of existing client_id column , so i am using select with insert

INSERT into 'my_table' (column1, client_id, column3) VALUES (val1,select distinct client_id from 'my_table', val3)

I need client_id from the same table my_table and i need client_ids in insert statement.

SELECT DISTINCT client_id FROM my_table gives me 113 client_id so i want to insert some row for each 113 client using the above approach.

I did this query

INSERT INTO client_notification_preferences (client_id, object_type , frequency,created_at,updated_at) SELECT DISTINCT client_id, 'ClientShipment',1, CURRENT_TIMESTAMP , CURRENT_TIMESTAMP FROM client_notification_preferences;

but this gives me this error enter image description here

 create_table "client_notification_preferences", id: :uuid, default: "uuid_generate_v4()", force: :cascade do |t|
t.uuid     "client_id"
t.string   "object_type"
t.integer  "frequency"
t.datetime "created_at",  null: false
t.datetime "updated_at",  null: false

end

3
  • Show us the table definition for client_notification_preferences. Commented Oct 31, 2018 at 6:40
  • when I insert any row, id is automatically inserted so how can it violate primary key constraint Commented Oct 31, 2018 at 6:43
  • Well, you have some unique constraint which is being violated. Commented Oct 31, 2018 at 6:46

1 Answer 1

6

if val1 and val3 are variables and client_id is a field from my_table you can use from below code.

 INSERT into 'my_table' (column1, client_id, column3) select distinct val1, 
    client_id,val3 from 'my_table'

for example

INSERT into 'my_table' (column1, client_id, column3) select distinct 1, client_id,2 from 'my_table'
Sign up to request clarification or add additional context in comments.

5 Comments

i only need client_id from select statement, and select distinct client_id from 'my_table' will give me 113 client_ids together , but i need one client at a time for inserting data
do you need last client_Id?
i need all client_id
What is val1 ?
'val1' is a value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.