Skip to content

Commit 9fd4097

Browse files
authored
Fix GROUP BY ordering: sort groups lexicographically before output (#159)
1 parent c3a6ed0 commit 9fd4097

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

src/executor/operator.cpp

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,8 +646,33 @@ bool AggregateOperator::open() {
646646
}
647647

648648
groups_.clear();
649+
650+
// Sort group keys lexicographically for deterministic GROUP BY ordering
651+
std::vector<std::string> sorted_keys;
652+
sorted_keys.reserve(groups_map.size());
649653
for (auto& pair : groups_map) {
650-
auto& state = pair.second;
654+
sorted_keys.push_back(pair.first);
655+
}
656+
std::sort(sorted_keys.begin(), sorted_keys.end(),
657+
[&groups_map](const std::string& a, const std::string& b) {
658+
const auto& a_vals = groups_map[a].group_values;
659+
const auto& b_vals = groups_map[b].group_values;
660+
if (a_vals.size() != b_vals.size()) {
661+
return a_vals.size() < b_vals.size();
662+
}
663+
for (size_t i = 0; i < a_vals.size(); ++i) {
664+
if (a_vals[i] < b_vals[i]) {
665+
return true;
666+
}
667+
if (b_vals[i] < a_vals[i]) {
668+
return false;
669+
}
670+
}
671+
return false;
672+
});
673+
674+
for (auto& key : sorted_keys) {
675+
auto& state = groups_map[key];
651676
std::vector<common::Value> row = std::move(state.group_values);
652677
for (size_t i = 0; i < aggregates_.size(); ++i) {
653678
switch (aggregates_[i].type) {

0 commit comments

Comments
 (0)