Skip to content

Use nested SQL queries to handle complex inserts #41

@oliverjam

Description

@oliverjam

const SELLER_ID = `SELECT id FROM devpop_users WHERE devpop_users.name = ($1)`;
return db.query(SELLER_ID, [name]).then((result) => {
// result is a postgres object returned from the db query, from which we take the user id
// console.log(result);
const INSERT_ITEM = `INSERT INTO products(name, title, product_type, description, price, seller_id) VALUES ($1, $2, $3, $4, $5, $6) RETURNING name,title, product_type, description, price`;

It is generally simpler to handle an insert like this with a nested SQL sub-query (i.e. when you need to query something in order to insert another thing). You could avoid having to make a separate SELECT before you run the INSERT:

INSERT INTO products(name, title, product_type, description, price, seller_id) VALUES (
  'abc', 
  'def', 
  'trousers', 
  'jkadfjkdf', 
  '10', 
  (SELECT id FROM devpop_users WHERE name = 'oli')
) RETURNING id, name, seller_id;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions