CASE expression with Derived Table: Alternative combo for multiple row UPDATE.

In this blog post, we will leverage the CASE expression and a Derived Table for updating multiple rows within the same UPDATE statement.

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.


A Handy Find

This blog post stems from a fantastic PDF I happened upon on the web (Can’t quite remember where I ran into it). MySQL Notes for Professionals is a jam-packed PDF of useful knowledge, tips, and pointers. The section on bulk updates with the CASE expression grabbed my attention. Salivating at the opportunity to learn something new and grow, I found a use inline with my own interest and needs, so here we are. Be sure and check it out through the link provided.


Present Data Set

We are working with this table and data. It represents a mock pipe/manufacturer/pipe grade system complete with pipe name, manufacturer, and a grade type for each:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mysql> SELECT pipe_name, manufacturer, pipe_grade
    -> FROM asset_staging;
+-------------+--------------+------------+
| pipe_name   | manufacturer | pipe_grade |
+-------------+--------------+------------+
| Joint-278   | Company 2    | X75        |
| Joint-8819  | PipeCo       | X75        |
| Joint-9844  | PipeCo       | X75        |
| Joint-2528  | PipeCo       | X75        |
| Joint-889   | Company 2    | X75        |
| Joint-98434 | PipeCo       | X75        |
| Joint-78344 | Company 1    | X75        |
| Joint-171C  | PipeCo       | X75        |
| Joint-68444 | Company 3    | X75        |
| Joint-4841R | PipeCo       | X75        |
| Joint-1224C | PipeCo       | X75        |
| Joint-2138  | PipeCo       | X75        |
| Joint-122B  | Company 2    | X75        |
+-------------+--------------+------------+
13 rows in set (0.00 sec)

Goal And How-To

We need to change the pipe_grade column value on a per manufacturer basis as follows:

Company 1 = X75A
Company 2 = X75B
Company 3 = X75C
PipeCo = C75X

Of course, these 4 individual UPDATE statements can take care of this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
UPDATE asset_staging
SET pipe_grade = 'X75A'
WHERE manufacturer = 'Company 1';

UPDATE asset_staging
SET pipe_grade = 'X75B'
WHERE manufacturer = 'Company 2';

UPDATE asset_staging
SET pipe_grade = 'X75C'
WHERE manufacturer = 'Company 3';

UPDATE asset_staging
SET pipe_grade = 'C75X'
WHERE manufacturer = 'PipeCo';
chris-ried-521588-unsplash

Photo by Chris Ried on Unsplash

Yet, a CASE expression inside the UPDATE command is also an option.
Here is how that looks:

1
2
3
4
5
6
7
8
9
10
11
12
mysql> UPDATE asset_staging
SET pipe_grade =
(CASE manufacturer
    WHEN 'Company 1' THEN 'X75A'
    WHEN 'Company 2' THEN 'X75B'
    WHEN 'Company 3' THEN 'X75C'
    WHEN 'PipeCo' THEN 'C75X'
    END
)
WHERE manufacturer IN (SELECT DISTINCT manufacturer FROM asset_staging);

mysql> ERROR 1093 (HY000): You can't specify target table 'asset_staging' for update in FROM clause

Wait a minute.
Shouldn’t that work?
I thought:

WHERE manufacturer IN (SELECT DISTINCT manufacturer FROM asset_staging);

was the same as:

WHERE manufacturer IN ('Company 1', 'Company 2','Company 3','PipeCo');

?

I’ll dig in to the issue by first running that SELECT query,

mysql> SELECT DISTINCT manufacturer FROM asset_staging;
+--------------+
| manufacturer |
+--------------+
| Company 2    |
| PipeCo       |
| Company 1    |
| Company 3    |
+--------------+
4 rows in set (0.00 sec)

The query does return the same number of rows, with the same names. The ordering of names is different though.
But that’s fine too. The IN() predicate column or expression only has to be in the list of supplied values. Turns out, MySQL is ‘slapping our hand’ for referencing the asset_staging table in the subquery during an UPDATE of it (the asset_staging table).

How about just SELECT from that subquery then ‘feed’ the result set to the UPDATE right?
Like this:

mysql> SELECT * FROM (SELECT DISTINCT manufacturer FROM asset_staging);
ERROR 1248 (42000): Every derived table must have its own alias

Hmmm…
Turns out we can’t do that either. The subquery in the FROM clause must be treated differently.
See below.

Derived Table

Let’s come to understand Derived Tables with a description and explanation from the Official Documentation in Section 13.2.10.8.


A derived table is a subquery in a SELECT statement FROM clause:


In this sense, Derived tables act like tables. Therefore they require an ALIAS since all tables must be named in the FROM clause.

First, let’s get this SELECT on the DISTINCT manufacturer column working.

1
2
3
4
5
6
7
8
9
10
mysql> SELECT * FROM (SELECT DISTINCT manufacturer FROM asset_staging) AS my_der_tbl;
+--------------+
| manufacturer |
+--------------+
| Company 2    |
| PipeCo       |
| Company 1    |
| Company 3    |
+--------------+
4 rows in set (0.00 sec)

By providing the AS my_der_tbl table ALIAS that worked.
We could even ALIAS the column from the Derived Table and the outer query will recognize and return it no problem:

1
2
3
4
5
6
7
8
9
10
mysql> SELECT maker FROM (SELECT DISTINCT manufacturer AS maker FROM asset_staging) as my_der_tbl;
+-----------+
| maker     |
+-----------+
| Company 2 |
| PipeCo    |
| Company 1 |
| Company 3 |
+-----------+
4 rows in set (0.00 sec)

For this immediate need, the below UPDATE accomplishes the goal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mysql> UPDATE asset_staging
SET pipe_grade =
(CASE manufacturer
    WHEN 'Company 1' THEN 'X75A'
    WHEN 'Company 2' THEN 'X75B'
    WHEN 'Company 3' THEN 'X75C'
    WHEN 'PipeCo' THEN 'C75X'
    END
)
WHERE manufacturer IN (SELECT * FROM (SELECT DISTINCT manufacturer
                                      FROM asset_staging) AS derived_tbl);

Query OK, 13 rows affected (0.06 sec)
Rows matched: 13  Changed: 13  Warnings: 0

∗Note:
Remember, per the docs, AS table_name is a mandatory clause in the Derived Table syntax.


Updated Data and Final Thoughts

Let’s verify the results by selecting those previous 3 columns:

mysql> SELECT pipe_name, manufacturer, pipe_grade
    -> FROM asset_staging;
+-------------+--------------+------------+
| pipe_name   | manufacturer | pipe_grade |
+-------------+--------------+------------+
| Joint-278   | Company 2    | X75B       |
| Joint-8819  | PipeCo       | C75X       |
| Joint-9844  | PipeCo       | C75X       |
| Joint-2528  | PipeCo       | C75X       |
| Joint-889   | Company 2    | X75B       |
| Joint-98434 | PipeCo       | C75X       |
| Joint-78344 | Company 1    | X75A       |
| Joint-171C  | PipeCo       | C75X       |
| Joint-68444 | Company 3    | X75C       |
| Joint-4841R | PipeCo       | C75X       |
| Joint-1224C | PipeCo       | C75X       |
| Joint-2138  | PipeCo       | C75X       |
| Joint-122B  | Company 2    | X75B       |
+-------------+--------------+------------+

All updates are successful.


I hope through this blog post, you now have and idea how to use MySQL Derived Tables. For this example, pairing them with the CASE expression, allowed updating multiple rows within the same table in one UPDATE statement.

I would love to hear your thoughts on Derived Tables best practices and implementations. Although new to me, I am excited to continue to explore, learn, and employ them as I discover use cases they would serve best.

I have included links to informative and interesting articles I found while searching and studying Derived Tables. Feel free to read those as well.

Visit the official MySQL 5.7 On-line Manual for more information.


A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.
Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive notifications for the latest post from “Digital Owl’s Prose” via email, please subscribe by clicking the ‘Click To Subscribe!’ button in the sidebar!
Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.


Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Advertisements

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.