Using select distinct with IF condition How can I ignore the is_enrolled field from distinct? This is the query:

select DISTINCT
`courses`.*, IF(course_enrollments.user_id=12, TRUE, FALSE) as is_enrolled 
from `courses` 
inner join `course_time_periods` on `course_time_periods`.`course_id` = `courses`.`id` 
inner join `org_time_periods` on `time_period_id` = `org_time_periods`.`id` 
left join `course_groups` on `course_time_periods`.`id` = `course_groups`.`course_period_id` 
left join `course_enrollments` on `course_groups`.`id` = `course_enrollments`.`group_id`
where `org_time_periods`.`started_at` &lt;= "2017-08-12 12:39:05" 
    and `org_time_periods`.`finished_at` &gt;= "2017-08-12 12:39:05" 
    and `courses`.`is_active` = true 
    and `courses`.`organization_id` = 2 
    and `course_enrollments`.`deleted_at` is null 


This duplicating one course because it's enrolled, so it returns the first row with is_enrolled as trueand next one as false.
It looks like you are trying to generate a list of all courses, plus a note as to which of those courses a specific user is enrolled in.

If that's the case, try changing the query as follows:

    select DISTINCT
    `courses`.*, IF(`course_enrollments`.`group_id` IS NOT NULL, TRUE, FALSE) as is_enrolled 
    from `courses` 
    inner join `course_time_periods` on `course_time_periods`.`course_id` = `courses`.`id` 
    inner join `org_time_periods` on `time_period_id` = `org_time_periods`.`id` 
    left join `course_groups` on `course_time_periods`.`id` = `course_groups`.`course_period_id` 
    left join `course_enrollments` on (    `course_groups`.`id` = `course_enrollments`.`group_id`
                                       AND `course_enrollments.user_id` = 12
                                      )
    where `org_time_periods`.`started_at` &lt;= "2017-08-12 12:39:05" 
        and `org_time_periods`.`finished_at` &gt;= "2017-08-12 12:39:05" 
        and `courses`.`is_active` = true 
        and `courses`.`organization_id` = 2 
        and `course_enrollments`.`deleted_at` is null 


As far as I can tell, your left joins only exist to check to see if the user_id in question showed up in a course_enrollments row. So, I modified the join to course_enrollments so that only rows with the indicated user_id would be returned by the join.

Then, instead of checking for user_id = 12, we simple test for whether a row was returned from course_enrollments. If a row was returned, then the user you're interested in is enrolled; otherwise, they are not enrolled.

Note: the code is untested.