create or replace function compare_lessons(d_week date, teacher varchar) returns varchar as $$ declare lesson1 varchar(100); lesson2 varchar(100); lesson3 varchar(100); lesson4 varchar(100); lesson5 varchar(100); lesson6 varchar(100); begin select c.name into lesson1 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '1'; select c.name into lesson2 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '2'; select c.name into lesson3 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '3'; select c.name into lesson1 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '4'; select c.name into lesson5 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '5'; select c.name into lesson1 from coprs c, audiences a, sheldule h, teachers t where c.id = a.corp_id and a.id = h.audience_id and t.id = h.teacher_id and t.name = teacher and h.day_week = d_week and h.lesson_id = '6'; if(lesson1 != lesson2)or(lesson2 != lesson3)or(lesson3 != lesson4)or(lesson4 != lesson5)or(lesson5 != lesson6) then return teacher; ELSE return 'none'; end if; end; $$ LANGUAGE plpgsql; SELECT distinct compare_lessons(h.day_date, t.name) FROM sheldule h, teachers t, audiences a, corps c WHERE t.id = h.teacher_id and c.id = a.corp_id and a.id = h.audience_id AND h.day_date BETWEEN TO_DATE('2022-01-07','YYYY-MM-DD') AND TO_DATE('2022-07-01','YYYY-MM-DD') and compare_lessons(h.day_date, t.name) != 'none';