Skip to main content

Insert Data Using SQL

SQL Examples

Here are some brief examples for INSERT statement. You can execute these statements manually by TDengine CLI or TDengine Cloud Explorer or programmatically by TDengine client libraries.

Insert Single Row

The below SQL statement is used to insert one row into table "d101".

INSERT INTO test.d101 VALUES (1538548685000, 10.3, 219, 0.31);

Insert Multiple Rows

Multiple rows can be inserted in a single SQL statement. The example below inserts 2 rows into table "d101".

INSERT INTO test.d101 VALUES (1538548684000, 10.2, 220, 0.23) (1538548696650, 10.3, 218, 0.25);

Insert into Multiple Tables

Data can be inserted into multiple tables in the same SQL statement. The example below inserts 2 rows into table "d101" and 1 row into table "d102".

INSERT INTO test.d101 VALUES (1538548685000, 10.3, 219, 0.31) (1538548695000, 12.6, 218, 0.33) test.d102 VALUES (1538548696800, 12.3, 221, 0.31);

For more details about INSERT please refer to INSERT.

Client Library Examples

Here's an smart meters example to show how to use connectors in different languages, to create a super table called meters in a power database, with columns for timestamp, current, voltage, phase, and tags for group ID and location.

IMPORTANT

Before executing the sample code in this section, please create a database named power on theTDengine Cloud - Explorer page.

How to establish connection to TDegnine Cloud service, please refer to Connect to TDengine Cloud Service.

In this example, we use execute method to execute SQL and get affected rows. The variable conn is an instance of class taosrest.TaosRestConnection we just created at Connect Tutorial.

# create super table
conn.execute("CREATE STABLE IF NOT EXISTS power.meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)")
# insert multiple rows into multiple tables at once. subtables will be created automatically.
affected_row = conn.execute("""
INSERT INTO
power.d1001 USING power.meters TAGS('California.SanFrancisco',1) VALUES
('2018-10-03 14:38:10.000', 10.30000, 219, 0.31000)
('2018-10-03 14:38:20.000', 12.60000, 218, 0.33000)
('2018-10-03 14:38:30.800', 12.30000, 221, 0.31000)
power.d1002 USING power.meters TAGS('California.SanDiego',2) VALUES
('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000)
""")
print("affected_row", affected_row) # 4

view source code

IMPORTANT

Use statement is not applicable for cloud service since REST API is stateless.