Home > database >  Seed new table with SQL SCRIPT
Seed new table with SQL SCRIPT

Time:01-28

I need to seed my new table. I need to get all my profiles(table: profiles), and seed privacies table with all profiles with default values.

  # TABLE PRIVACIES
  profile_id, null: false

  #
  # fields
  integer       :pictures, default: 2, null: false
  integer       :friends, default: 1, null: false
  integer       :following, default: 1, null: false
  integer       :feed, default: 1, null: false
  integer       :places, default: 1, null: false

CodePudding user response:

According to the docs, the default expression will be used in any insert operation that does not specify a value for the column. So you can just do an insert of profile_ids to your PRIVACIES table, and the other columns will be filled in with default values.

Create tables:

CREATE TABLE profiles(
  profile_id integer);
INSERT INTO profiles (profile_id)
     VALUES (1),
            (5),
            (32),
            (41),
            (52);

CREATE TABLE privacies(
  profile_id integer NOT NULL,
  friends integer NOT NULL DEFAULT 2,
  following integer NOT NULL DEFAULT 1,
  feed integer NOT NULL DEFAULT 1,
  places integer NOT NULL DEFAULT 1);

I changed the table names to lowercase. PostgreSQL is case sensitive and it's easier to use lower case for all table names and field names.

Insert data from profile table into privacies table:

INSERT INTO privacies SELECT profile_id FROM profiles;

Check data in privacies table:

profile_id friends following feed places
1 2 1 1 1
5 2 1 1 1
32 2 1 1 1
41 2 1 1 1
52 2 1 1 1
  •  Tags:  
  • Related