MySQL for the Internet of Things

(Steven Felgate) #1
Chapter 5 ■ MySQL priMer

Now let’s say we want to see the results of our result set ordered by sensor value. We will use the same
query that selected the rows for the fern on the deck, but we order the rows by sensor value in ascending and
descending order using the ORDER BY clause. Listing 5-6 shows the results of each option.


Listing 5-6. ORDER BY Examples


mysql> SELECT plant_name, sensor_value FROM plant_monitoring.plants WHERE plant_name =
'fern on deck' ORDER BY sensor_value ASC;
+--------------+--------------+
| plant_name | sensor_value |
+--------------+--------------+
| fern on deck | 0.43 |
| fern on deck | 0.477 |
| fern on deck | 0.51 |
| fern on deck | 0.73 |
+--------------+--------------+
4 rows in set (0.00 sec)


mysql> SELECT plant_name, sensor_value FROM plant_monitoring.plants WHERE plant_name =
'fern on deck' ORDER BY sensor_value DESC;
+--------------+--------------+
| plant_name | sensor_value |
+--------------+--------------+
| fern on deck | 0.73 |
| fern on deck | 0.51 |
| fern on deck | 0.477 |
| fern on deck | 0.43 |
+--------------+--------------+
4 rows in set (0.00 sec)


As I mentioned, there is a lot more to the SELECT statement than shown here, but what we have seen
here will get you very far, especially when working with data typical of most small to medium-sized IOT
solutions.


Adding Data


Now that you have a database and tables created, you will want to load or insert data into the tables. You can
do so using the INSERT INTO statement. Here we specify the table and the data for the row. The following
shows a simple example:


INSERT INTO plant_monitoring.plants (plant_name, sensor_value) VALUES ('fern in den', 0.2319);


In this example, I am inserting data for one of my plants by specifying the name and value. What about
the other columns, you wonder? In this case, the other columns include a timestamp column, which will be
filled in by the database server. All other columns (just the one) will be set to NULL, which means no value is
available, the value is missing, the value is not zero, or the value is empty.^11


(^11) https://en.wikipedia.org/wiki/Null_%28SQL%29

Free download pdf