I have the following database relationship and query for PostgreSQL below:
create table gender(
gender_id int primary key,
gender char(10))
create table student(
student_id int primary key,
first_name char(50) not null,
last_name char(50) not null,
gender_id int not null,
constraint gender_fk foreign key(gender_id) references gender(gender_id))
insert into gender values(1, 'Male');
insert into gender values(2, 'Female');
insert into gender values(3, 'Other');
insert into student values(101, 'John', 'Smith', 1);
insert into student values(102, 'Sara', 'Bradford', 2);
insert into student values(103, 'Joseph', 'Brown', 1);
insert into student values(104, 'David', 'Lopez', 3);
How do I create an inner join statement that checks if the student’s gender is ‘Female’?
All other genders (‘Male’ and ‘Other’) will just have null value. I want an output like the following inner-joined table:
2
Answers
We don’t even need to involve the
gender
table:SQL
CASE
defaults tonull
, when theELSE
part is missing.If you insist on a join, rather use
LEFT [OUTER] JOIN
and filter for ‘Female’ in the join condition. Then all other genders default tonull
automatically.:fiddle
This second query is for situations where the
gender_id
of ‘Female’ is not readily known already, or ‘Female’ is really a variable.Since both
first_name
andlast_name
areNOT NULL
, plain concatenation is fine. else consider null-safe concatenation withconcat_ws()
. See:Aside: you do not want to use the data type
char(n)
. See:You don’t need a JOIN for this, but if you were to use one I would suggest an OUTER join instead of INNER. See this: