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

350
Views
Calculate the sum of a query that uses order by and limit Postgres

The following query returns a table of grades. I want the sum of it and i cant figure out how to do it.

SELECT grade
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50

I get this error:

ERROR: column "grade" must appear in the GROUP BY clause or be used in an aggregate function

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

SELECT SUM(grades)
FROM
(
SELECT grade as grades
FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50
) z
over 4 years ago · Santiago Trujillo Report

0

The problem here is the ORDER BY clause which you would know if you pasted the full error, instead of forcing us to recreate your problem from scratch because you didn't provide the DDL and data.

CREATE TABLE "GradesTable" ( status text, student_id int, grade int );
INSERT INTO "GradesTable" (status, student_id, grade) VALUES
  ('success', 1, 80),
  ('success', 1, 100);

Query

SELECT sum(grade)                                                    FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 ORDER BY grade DESC
 LIMIT 50
;
ERROR:  column "GradesTable.grade" must appear in the GROUP BY clause or be used in an aggregate function
LINE 4:  ORDER BY grade DESC

However this works,

SELECT sum(grade)
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
 LIMIT 50
;
 sum 
-----
 180
(1 row)

But you shouldn't have a LIMIT if you have only one agg that can only ever return one row.

SELECT sum(grade)
 FROM "GradesTable"
 WHERE status='success' AND student_ID=1
;

If you meant to order by sum(grade) you can do that, but you lose the ability to order by grade the second you aggregate it together. However, in this example it doesn't matter because you're only returning one row.

And as a separate note you should never quote identifiers in PostgreSQL. Make everything lowercase, never quote table names or column names.

over 4 years ago · Santiago Trujillo Report
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!