I have teams:
create table team (
id integer primary key,
type text
);
Also, I have players:
create table player
(
id integer primary key,
age integer,
team_id integer references team(id)
);
The type of a team can either be 'YOUTH' or 'ADULT'. In a youth team, only players starting from age 16 are allowed in official games. In an adult team, only players starting from age 18 are allowed in official games.
Given a team identifier, I want to find all allowed players for the upcoming game. I have the following query:
select player.*
from player
join team
on player.team_id = team.id
where team.id = 1 and
(
(team.type = 'YOUTH' and player.age >= 16) or
(team.type = 'ADULT' and player.age >= 18)
);
This works. However, in this query, for every player I am repetitively checking the type of the team. This value will stay the same during the whole query.
Is there a way to improve this query? Should I replace it with a pgplsql function where I first store the team into a local variable, and then discriminate with following flow?
IF team.type = 'YOUTH' THEN <youth query> ELSE <adult query> END IF
For me, that feels like killing a fly with a bazooka, but I don't see an alternative right now.
I created a SQL fiddle: http://rextester.com/TPFA20157