Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use nested SQL queries to handle complex inserts #41

Open
oliverjam opened this issue Jan 28, 2022 · 0 comments
Open

Use nested SQL queries to handle complex inserts #41

oliverjam opened this issue Jan 28, 2022 · 0 comments

Comments

@oliverjam
Copy link

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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant