Skip to content
Advertisement

sqlite3 INSERT INTO UNION SELECT

INSERT INTO table1
    SELECT "hello" AS field1, 15 AS field2, 1262340000 AS timestamp 
    UNION 
    SELECT "byebye", 10, 1262340000 
    UNION 
    SELECT "hi", 20, 1262340000 
    UNION 
    SELECT "boo", 25, 1262340000 

Table columns:

field1  field2  timestamp   pk

pk is the auto-incrementing primary key

An error occurs when I execute this SQL

DB Error: 1 “table table1 has 4 columns but 3 values were supplied”

Advertisement

Answer

You should explicitly specify which columns in table1 your insert is targeting:

INSERT INTO table1 (field1, field2, timestamp)
SELECT 'hello', 15, 1262340000
UNION ALL
SELECT 'byebye', 10, 1262340000
UNION ALL
SELECT 'hi', 20, 1262340000
UNION ALL
SELECT 'boo', 25, 1262340000;

When you omit the select list entirely, SQLite will fall back to expecting values for all columns in the table, in the exact order specified by the table definition. In your case, as you only provided values for 3 out of the 4 total columns, you get an error. Note that you could have also used VALUES here:

INSERT INTO table1 (field1, field2, timestamp)
VALUES
    ('hello',  15, 1262340000),
    ('byebye', 10, 1262340000),
    ('hi',     20, 1262340000),
    ('boo',    25, 1262340000);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement