1

My code works fine in a SQL database but when trying to execute on postgresql, it starts throwing an error. I've tried adding "symbol" after GROUP BY and even "symbol.symbol"

SELECT symbol,name,price,total, SUM(shares) 
FROM symbol 
WHERE user_id=? 
GROUP BY name

column "symbol.symbol" must appear in the GROUP BY clause or be used in an aggregate function

3
  • 2
    SQL is a query language used by all relational databases. So Postgres is a "SQL database" as well. Your group by usage is invalid standard SQL and should be rejected by any self-respecting database. Commented Jan 7, 2022 at 21:41
  • I suspect the original query was for SQLite, it accepts lots of queries. What do you expect a symbol to be, if there may be multiple different symbols inside a single group of names? Commented Jan 7, 2022 at 21:44
  • @yeputons Yes I didn't know there was a difference but yes I was in fact using SQLite. I have a database where users bought stock, and so I am searching the stock based on the persons ID, and symbol is just the STOCK acryonym, for example AAPL and name is Apple. As far as what I want to get is a table with the symbol, names, price and total that the specific user bought. Commented Jan 7, 2022 at 21:48

2 Answers 2

2

Every field that is not part of a domain (or aggregate) function in the select list needs to be in the group-by clause. In your case, that's symbol, name, price, and total.

Furthermore, name and total are terrible field names, as they are reserved words. In SQL Server, you would enclose those in square brackets. In PostgreSQL you would put them in double-quotes.

But really, you should not use those names.

Sign up to request clarification or add additional context in comments.

2 Comments

Noted, I will rethink the names and I will go ahead and try your code.
name is a only a non-reserved key word in Postgres and does not require quoting - but I do agree that it's a questionable name for a column. total is not a keyword at all in Postgres (or SQL in general)
1

The GROUP BY clause should include symbol, name, price, total and sum(shares). Your select clause should also include name.

SELECT name,symbol,name,price,total, SUM(shares) 
FROM symbol 
WHERE user_id=? 
GROUP BY name,symbol,name,price,total

This should at the very least be a valid statement.

Comments

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.