0

Is there a way to popullate a column based on another column.

For example

SELECT name, age, (select count(*) FROM ORDERS WHERE name = **value in column [name]**) FROM PEOPLE

Any help is greatly appreciated.

1
  • Yes but not with that syntax. Do you have some sample data? I would suggest joining the tables or using a subquery to get the solution Commented Jul 12, 2019 at 12:33

1 Answer 1

3

You can but you have to use proper aliases for the tables:

SELECT 
  p.name, 
  p.age, 
  (select count(*) FROM ORDERS o WHERE o.name = p.name)  counter
FROM PEOPLE p

so the 2 columns from different tables both having the same name name can be distinguished.

As suggested by Larnu, try this alternative which does the same by joining the tables and aggregating:

SELECT 
  p.name, 
  p.age, 
  count(o.name) counter
FROM PEOPLE p LEFT JOIN ORDERS o
ON o.name = p.name
GROUP BY p.name
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't this be better served with a JOIN and aggregation? The subquery will likely result in multiple scans of ORDERS.
I'm not sure about it. There are cases where such embedded queries are more efficient. Anyway this answer is based on the OP's code. The explanation about the aliases I think is more useful than a point to another direction
Thanks guys! You've been a massive help

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.