IMD SolutionComputing LibraryShop main store

Troubleshooting

Why Node-RED MQTT messages never combine into one MySQL insert

Edge computing and IIoT Published 7 min read By IMD Solution engineering team

Short answer

Node-RED delivers every MQTT publication as its own message, so a function that expects an array of topic and payload pairs never sees a complete sample and the MySQL table stays empty. Give each stream its own msg.topic, combine the messages with a Join node set to the topic count, put the parameterized INSERT in msg.topic for node-red-node-mysql, and clear the node's red configuration triangle before the first test.

On this page
  1. Why does each MQTT value reach the function on its own?
  2. Why does the function find no array of topic and payload pairs?
  3. How do you combine separate MQTT topics into one message?
  4. Should one PLC read replace the separate MQTT messages?
  5. Where does the INSERT statement go in node-red-node-mysql?
  6. Why does the MySQL node show a red triangle before any test?
  7. What table columns make each row traceable?
  8. How do you prove the insert before loading every field?
  9. Questions asked

Your Node-RED flow shows no error, the broker delivers, and still the MySQL table stays empty — or fills with rows in which most columns are blank. The cause sits upstream of the database: Node-RED hands your function one MQTT message at a time, so a function written around an array of topic and payload pairs only ever sees a fragment of a sample. Join the messages into one record before the SQL step, put the INSERT in msg.topic for node-red-node-mysql, clear the MySQL node's red configuration triangle, and give the table an id and a timestamp. The sections below follow the fault in the order you meet it.

Why does each MQTT value reach the function on its own? #

Node-RED passes one message at a time along each wire, so the PLC's topics arrive as separate msg objects and no node ever holds two of them at the same instant.

A function node runs once per arriving message and keeps no memory between runs, so it cannot wait for a second publication to complete a set. Two wires feeding one input deliver their messages at different moments — never together — which makes the empty table a property of the runtime, not a wiring mistake. This is the same trap described in why a Node-RED function never combines two values that arrive separately, and the way out is the same in both cases: an explicit combining node, or one upstream message that already carries the whole sample.

Why does the function find no array of topic and payload pairs? #

A plain MQTT-in message carries a single publication — the topic string in msg.topic and the value in msg.payload — so a function expecting an array of topic and payload pairs iterates over the wrong shape, matches no case, and every mapped variable keeps its empty-string default.

Put a Debug node on the MQTT-in output, set it to show the complete msg object, and record what actually arrives: one publication per message, for example /speed/data1/ALTPRG01 in msg.topic with the value in msg.payload. The function assumes the opposite shape — an array of objects, each carrying its own topic and payload — and that shape exists only after a Join node. While you are there, compare the incoming topic strings with the switch cases character for character: a changed path segment, a missing leading slash or different capitalization breaks the match silently, and the column simply stays empty without raising any error.

How do you combine separate MQTT topics into one message? #

Give every stream its own msg.topic and set a Join node to manual mode with the count equal to the number of topics — here 11 — and the node releases one combined message once the last distinct topic has arrived.

The documented recipe for building one message out of separate streams is exactly this: a unique topic per stream in, one grouped message out, with the Join node keying each part by its topic. Downstream of it, the function finally sees the shape it was written for.

Worked example: with each topic publishing every 500 ms, a full sample completes every 500 ms, so the joined path writes 1 ÷ 0.5 s = 2 rows each second — 2 × 3,600 = 7,200 rows in an hour. Without the Join, the MySQL node inserts on every arrival: 11 topics × 2 = 22 messages each second, which is 22 × 3,600 = 79,200 fragment rows in an hour. That Join count is the number that decides which of the two tables you get.

Should one PLC read replace the separate MQTT messages? #

Yes when the values sit in one PLC address range — read the block once and publish a single message holding the whole sample, because values captured together are consistent and no combining logic has to guess which arrivals belong to which sample.

One message per sample also removes the Join's main failure mode: nothing stalls the record by arriving late. Keep separate topics only where the sources are genuinely independent — different controllers or different scan rates — and then define the incomplete case explicitly. Gate the write so the insert fires only when every mapped field is present, and treat a sample that never completes as a fault to alarm on, not as a row to store half-filled. In a simulation the broker is the only publisher, so the Join carries the design; in the real installation, the block read published as one message is the sturdier shape.

Where does the INSERT statement go in node-red-node-mysql? #

The node takes the SQL from msg.topic and returns the result in msg.payload, so build a parameterized INSERT into msg.topic after the Join and pass the values as a parameter object in msg.payload.

node-red-node-mysql binds the object in msg.payload to named placeholders in the statement, in the style below; if the MySQL node variant installed in your palette documents a different placeholder syntax, follow its own documentation.

msg.topic = 'INSERT INTO realtimeexample (speed, printing, tensionuw)';
msg.topic += ' VALUES (:speed, :printing, :tensionuw)';
msg.payload = { speed: speed, printing: printing, tensionuw: tensionuw };
return msg;

Map every property to an explicit column name — inserts that rely on column order break the first time the table changes — and never concatenate payload values into the SQL string: a stray character becomes a broken statement, and text from outside the flow becomes an injection path. The same msg.topic pattern also works from a Template node, as shown in Save Node-RED OPC UA values to MySQL through a template insert.

Why does the MySQL node show a red triangle before any test? #

The red triangle is the editor's not-configured marker — host, port, user, password or database is missing — and nothing behind it can write until you open the node and complete its connection, because a drawn wire proves nothing about the database session.

Open the node's configuration, complete the server, credentials and database, and redeploy; the triangle clears once the configuration is whole, and the node then shows its real connection state as status under it. Only then does a test mean anything. If the configuration is complete and the deploy still fails with the server refusing the session, work through Fix ECONNREFUSED when Node-RED connects to a remote SQL database — reachability, port and account grants, in that order — and read the node's runtime error output rather than trusting the wire.

What table columns make each row traceable? #

Give the table an AUTO_INCREMENT id as primary key and a DATETIME column defaulting to the insert time, because without them no row can be told apart from the next or tied to when its sample was stored.

CREATE TABLE realtimeexample (
  id INT(11) NOT NULL AUTO_INCREMENT,
  timestamp DATETIME NOT NULL DEFAULT now(),
  speed INT(11),
  printing TEXT(100),
  tensionuw INT(11),
  PRIMARY KEY (id)
);

Both the id and the timestamp fill themselves on every insert, so the flow never has to send them, and every row can be sorted and compared on id. Match each column type to what the controller actually sends — integer columns for the numeric values, a text column for a flag such as printing — and decide before the first insert how an unavailable value is represented, because an empty string and a NULL are different facts in any later report.

How do you prove the insert before loading every field? #

Commission the path in small steps — one known test value, a minimal insert, a Debug node immediately before the MySQL node, and a read-back that compares the stored row with what you sent — then widen it.

  1. Confirm the MQTT-in side: a Debug node set to the complete msg object shows one topic and one value per message, with strings that match the switch cases exactly.
  2. Confirm the Join side: its output carries every mapped field before the function runs, and the insert is gated on that condition.
  3. Run the minimal three-column insert — speed, printing, tensionuw — with the Debug node immediately before the MySQL node showing both msg.topic and msg.payload.
  4. Read the row back with SELECT * FROM realtimeexample ORDER BY id DESC LIMIT 1; and compare values and timestamp with what you sent.
  5. Add the remaining columns, redeploy and repeat the read-back; when a value goes wrong, find the first point where it changes — MQTT input, Join output, function output, binding, stored row — and fix that point only.

Decision: when the controller can supply one block, publish one message per sample and skip the Join; when the topics arrive separately, the Join count decides and no INSERT reaches MySQL until it is met. The SQL travels in msg.topic, the red triangle is cleared before the first test, the first row is proven by read-back, and only then do the remaining columns follow.

Questions asked

What happens to the joined record when one MQTT topic stops publishing?

The Join never reaches its configured count, which is eleven in the worked flow, so it stops releasing messages and the table goes quiet instead of filling with fragments. Gate the insert so it fires only when every mapped field is present, and alarm on the stalled topic. A missing row exposes the fault; a partial row hides it.

Can the timestamp come from the PLC instead of the database?

Yes. Keep the column with its default for arrival time and add a second DATETIME column filled through a named placeholder when the controller's own sample clock matters. Arrival time and sample time answer different questions, when the row landed versus when the value was captured, and collapsing them into one column makes both ambiguous.

Why do numeric columns end up holding zeros after a run?

A partial sample reached the insert and its empty strings were bound to integer columns. With MySQL in non-strict mode an empty string converts to 0 with a warning; in strict mode the same insert fails with an incorrect-value error. Either way the cause sits upstream, so check the values arriving at the MySQL node before changing the schema.

Do you need an MQTT out node on the database path?

No. The mqtt-in node alone feeds the flow; an mqtt-out node only republishes a message to the broker and contributes nothing to the write. It earns its place only when another subscriber needs the combined sample, for example a second flow or a plant-wide topic mirroring what was stored.

Does a Template node work as well as a function for the INSERT?

For a fixed statement, yes: a Template node whose output field is set to msg.topic can carry the INSERT directly, which suits simple flows. A function builds the statement and the parameter object together, which suits the joined-sample insert, where the values travel in msg.payload alongside the SQL.

Keep reading

  • How-to

    Connect Node-RED on ctrlX CORE to a MySQL server

    Send the SQL as msg.topic to a node-red-node-mysql node: create the table once as an administrator, prove one INSERT and SELECT from Inject nodes, then route Read Datalayer values into a multi-row insert. Grant the runtime account only SELECT and INSERT on db1, match its host part to the client address the server reports, and keep a local snap's data directory on external media.

    Edge computing and IIoT

  • How-to

    Pass PLC node data into a Node-RED MSSQL insert

    The PLC read node already emits your data on msg.payload; the missing piece is mapping those properties to named parameters in the MSSQL node's INSERT. Attach a Debug node to read each property path and type, build a payload object of named values, keep floats numeric, and prove the write by querying one known row back from the table.

    Edge computing and IIoT

  • How-to

    Combine two MQTT sensor inputs in one Node-RED calculation

    Node-RED accepts many wires into one node but delivers each message separately, so combine the two MQTT streams explicitly. Use a Join node in manual mode with a message count of 2 and msg.topic as the key, or a Function node that stores the latest temperature and smoke flag in context and evaluates both on every arrival.

    Edge computing and IIoT

Saving the payload_raw value from MQTT in Node-RED to MySQL