CASE

Even though the CASE expression seems to remind us of imperative structures such as IF, SWITCH, and the like, it still does not allow for program flow control like those imperative structures, but rather allows for declarative evaluation of values based on certain conditions. Let's have a look at the following example in order to better understand this feature.

Please enter the following query in the SQL tab of the test database via the phpMyAdmin interface:

SELECT id, COUNT(*) as Total, COUNT(CASE WHEN superior IS NOT NULL THEN id END) as 'Number of superiors'FROM employeesWHERE id = 2;

This query should yield the following result set:

Result set of the query containing the CASE statement

As the result shows, the row with an id value ...

Get Mastering The Faster Web with PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.