3

I want to insert a row to the table if only the table is empty. I went through this Execute INSERT if table is empty? but am unable to do so.i am using MariaDB as rdbms.Please help.Thanks in advance.

Here is my sql syntax:

INSERT INTO `policy` (`policy1`, `policy2`, `policy3`, `policy4`)
    SELECT ('F', 'F', 'F', 'F')
    WHERE NOT EXISTS (SELECT * FROM `policy`) 

My table structure is:

CREATE TABLE `policy` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `policy1` varchar(255) DEFAULT NULL,
  `policy2` varchar(255) DEFAULT NULL,
  `policy3` varchar(255) DEFAULT NULL,
  `policy4` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1
jarlh
  • 42,561
  • 8
  • 45
  • 63
rock11
  • 718
  • 4
  • 17
  • 34

4 Answers4

4

You can also use the dual table for this purpose:

INSERT INTO `policy` (`policy1`, `policy2`, `policy3`, `policy4`)
    SELECT 'F', 'F', 'F', 'F'  -- no parentheses!
    FROM dual
    WHERE NOT EXISTS (SELECT * FROM `policy`) ;

dual is a built-in table with one row, designed for purposes like this. The naming and idea come from the Oracle database.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • thank you for this hint! I searched for a reference why there is a difference between mysql and mariadb. I found this: *FROM DUAL could be used when you only SELECT computed values, but require a WHERE clause, perhaps to test that a script correctly handles empty resultsets* - https://mariadb.com/kb/en/library/dual/ – Sebastian Brosch Apr 23 '19 at 10:50
2

You can use the following solution:

INSERT INTO `policy` (`policy1`, `policy2`, `policy3`, `policy4`)
    SELECT * FROM (SELECT 'F' c1, 'F' c2, 'F' c3, 'F' c4)t
    WHERE NOT EXISTS (SELECT 1 FROM `policy`);

demo on dbfiddle.uk

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87
0

You can use exists like:

if not exists(select 1 from table)
begin
    -- do stuff
end
Apoorv Mishra
  • 1,489
  • 1
  • 8
  • 12
  • 1
    no you can't this is not SQL Server (MSSQL) where this syntax is allowed on plain SQL exection.. In MySQL this syntax is only allowed on stored programs like triggers, functions and procedures.. So this syntax wil give a parse error on MySQL and MariaDB. – Raymond Nijland Apr 23 '19 at 10:18
0
INSERT INTO `policy` (`policy1`, `policy2`, `policy3`, `policy4`)
    Select * from (
    SELECT ('F', 'F', 'F', 'F')
    WHERE NOT EXISTS (SELECT 'F', 'F', 'F', 'F' FROM `policy`))
Amirhossein
  • 1,148
  • 3
  • 15
  • 34