Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Error: insert or update on table "routines" violates foreign key constraint "routines_creatorId_fkey"

This is what my tables look like:

async function createTables() {
  try {
    console.log("Starting to build tables...")
  
    await client.query(`
    CREATE TABLE users (
      id SERIAL PRIMARY KEY,
      username VARCHAR(255) UNIQUE NOT NULL,
      password VARCHAR(255) NOT NULL
    );`)
    await client.query(`
    CREATE TABLE activities ( 
      id SERIAL PRIMARY KEY,
      name VARCHAR(255) UNIQUE NOT NULL,
      description TEXT NOT NULL
    ); 
    `)
    await client.query(`
    CREATE TABLE routines(
        id SERIAL PRIMARY KEY,
        "creatorId" INTEGER REFERENCES users(id),
        "isPublic" BOOLEAN DEFAULT false,
        name VARCHAR(255) UNIQUE NOT NULL,
        goal TEXT NOT NULL
      );
      `)

    await client.query(`
    CREATE TABLE routine_activities (
      id SERIAL PRIMARY KEY, 
      "routineId" INTEGER REFERENCES routines(id),
      "activityId" INTEGER REFERENCES activities(id),
      duration INTEGER,
      count INTEGER,
      UNIQUE ("routineId", "activityId")
    );
  `);
  } catch (error) {
    console.error(error)
    throw error
  }
}

and this is the function I am writing to manipulate my routines table:

async function createRoutine({ creatorId, isPublic, name, goal }) {

  try {
    const { rows: [routine] } = await client.query(`
      INSERT INTO routines("creatorId", "isPublic", "name", "goal")
      VALUES ($1, $2, $3, $4)
      RETURNING *;
    `, [creatorId, isPublic, name, goal]);
    return routine;
  } catch (error) {
    console.error(error)
  }
}

Am I creating my foreign keys correctly within the tables, or is there a better way to reference keys from a different table? Could the issue be something other than my table creation?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!