Skip to content

bug: using .Order in a scope is not compatible with DB.Count() #816

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

socksy
Copy link

@socksy socksy commented Jul 14, 2025

Explain your user case and expected results

When you add an Order() statement to a Count() query, then the code runs fine in postgres. However, when you have the Order() statement in a scope, and add it to a Count() query, then it fails

GORM_DIALECT=postgres go test                                                 
2025/07/14 16:52:37 testing postgres...

2025/07/14 16:52:37 /Users/ben/code/gorm-playground/main_test.go:20
[1.413ms] [rows:1] INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age","birthday","company_id","manager_id","active") VALUES ('2025-07-14 16:52:37.439','2025-07-14 16:52:37.439',NULL,'jinzhu',0,NULL,NULL,NULL,false) RETURNING "id"

2025/07/14 16:52:37 /Users/ben/code/gorm-playground/main_test.go:25
[0.543ms] [rows:1] SELECT count(*) FROM "users" WHERE "users"."deleted_at" IS NULL

2025/07/14 16:52:37 /Users/ben/code/gorm-playground/main_test.go:32 ERROR: column "users.name" must appear in the GROUP BY clause or be used in an aggregate function (SQLSTATE 42803)
[0.402ms] [rows:0] SELECT count(*) FROM "users" WHERE "users"."deleted_at" IS NULL ORDER BY name desc
--- FAIL: TestGORM (0.00s)
    --- FAIL: TestGORM/ORDER_BY_in_scope_+_Count()_fails (0.00s)
        main_test.go:33: Failed with .Order() in a scope, got error: ERROR: column "users.name" must appear in the GROUP BY clause or be used in an aggregate function (SQLSTATE 42803)
        main_test.go:35: Count: 0
FAIL
exit status 1
FAIL	gorm.io/playground	0.050s

(seems to work fine for me in mysql and mssql)

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

Successfully merging this pull request may close these issues.

1 participant