I have two tables one is users and other is students. I wish to execute a single SQL statement that inserts into both these tables different values. The id is PK for users and I have referenced the same id in the student table with (id INTEGER NOT NULL PRIMARY KEY REFERENCES users(id)
)
I tried this:
INSERT INTO users (id, password, firstName, lastName, emailAddress, enrollDate, lastAccess, enabled, type) VALUES (100222222, 'password', 'Robert', 'McReady', '[email protected]', '2016-03-07', '2015-09-03', true, 's')
AND
INSERT INTO students (id, programCode, programDescription, year) VALUES (100222222, 'a', 'b', 3)
This statement throws syntax error (syntax error at or near "AND"
), and I don’t understand why. I am connecting this SQL prepared statement through Java so my code is like this:
String sqlInsert = "INSERT INTO users (id, password, firstName, lastName, emailAddress, enrollDate, lastAccess" + ", enabled, type) VALUES (100222222, 'password', 'Robert', 'McReady', '[email protected]', " + "'2016-03-07', '2015-09-03', 's', true)";
Is there a way so I can code this sqlInsert statement to insert into two different tables with different values in a single sql statement in Java?
2
Answers
It is not possible to combine two insert statements with an AND. They need to be seperated.
In your code, depending on the language/framework, you can make one transaction for both statements, so they will be comitted at the same time to your DB.
If the goal is to avoid repeating the value for the ID column, this could be done using a data modifying CTE:
Postgres also allows to run two statements with a single
Statement.executeUpdate()
call as long as they are delimited with a;
(not with an "AND")However the above is not the correct approach. You should not put the actual values directly into your SQL strings.
It’s better (safer and more efficient) to use a
PreparedStatement
. As the ID will be stored in a Java variable, there is no need to repeat it.This has the additional advantage that you can pass the values for the
DATE
columns as properLocalDate
instances rather than strings. If you insert both in a single transaction you make sure that either both rows or nothing is inserted.Something like the following (without proper error handling and cleanup!)