Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active July 2, 2021 14:37
Show Gist options
  • Save rpivo/f341c843270bc449f05ae999df019d46 to your computer and use it in GitHub Desktop.
Save rpivo/f341c843270bc449f05ae999df019d46 to your computer and use it in GitHub Desktop.
Conditional Statements in MySQL

Conditional Statements in MySQL

The following SQL schema will produce the table below.

Create table If Not Exists Employees (employee_id int, name varchar(30), salary int);
Truncate table Employees;
insert into Employees (employee_id, name, salary) values ('2', 'Meir', '3000');
insert into Employees (employee_id, name, salary) values ('3', 'Michael', '3800');
insert into Employees (employee_id, name, salary) values ('7', 'Addilyn', '7400');
insert into Employees (employee_id, name, salary) values ('8', 'Juan', '6100');
insert into Employees (employee_id, name, salary) values ('9', 'Kannon', '7700');
employee_id name salary
2 Meir 3000
3 Michael 3800
7 Addilyn 7400
8 Juan 6100
9 Kannon 7700

Let's say we want to create a new table that shows us which employees need a raise. To do this, we will have two columns: employee_id and needs_raise. If the employees salary is less than 5000, they should have a "yes" value for needs_raise. Otherwise, they should have "no".

We can achieve this with the following query that uses a conditional statement.

SELECT employee_id,
CASE
    WHEN salary < 5000 THEN "yes"
    ELSE "no"
END AS needs_raise
FROM Employees;
employee_id needs_raise
2 yes
3 yes
7 no
8 no
9 no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment