When you want to group subsets of rows by one column you probably dont want group by

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2024-11-23

In a booking system, I wanted to group appointment slots by date, which would be a function of the datetime start_time column. My first instinct was group by but this would lose rows since group by aggregates (at least in postgres)

Ultimately I wrote:

<?php
    $query->selectRaw("*, DATE(start_time) as date")
    /// which gives lots of rows with the same date

    // and then grouping together in PHP in a way that does not 

Lesson:

When you want to group by some shared value in SQL, but preserve all the underlying rows, you want to do select *, new_col instead of group by.