I have an application where several devices send data every second to my server. On the database I have a table with the devices and another table with the data sent every second.
The first time a device sends the data the server script should register (INSERT
) that device id in the device table and add the data to the data table.
My question is, what would be faster?
To do a
SELECT EXISTS
query to determine whether anINSERT
is required on the device table. IfSELECT EXISTS
returns false then execute anINSERT
, otherwise do nothing.To execute always an
INSERT
statement. Considering the device id is primary key on the table, if the device already exists it would return an error, otherwise it would insert it.
Only the first time a device sends data would require an actual INSERT
, after that no INSERT
would ever be required.
The PostgreSQL version is 9.4.
The table of devices is defined as follows:
CREATE TABLE common.tag
(
customer integer,
hostname character varying(150),
description text,
model integer,
configprofile integer,
id character varying(150) NOT NULL,
host integer,
CONSTRAINT tag_pk PRIMARY KEY (id),
CONSTRAINT tag_fk_client FOREIGN KEY (customer)
REFERENCES common.customer (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT tag_fk_configprofile FOREIGN KEY (configprofile)
REFERENCES common.configprofile (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT tag_fk_tagmodel FOREIGN KEY (model)
REFERENCES common.tagmodel (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)