I have this query with syntax error. Can you help me find the error please?
I spend couple of hour and I can't solve it. Thanks.
String sql = " INSERT INTO appointments (patient_firstname, patient_surname, fees, time, date, doctor)"
+ " SELECT (time, date, doctor)"
+ " WHERE NOT EXISTS (SELECT * FROM appointments WHERE time = ?)";
pst=conn.prepareStatement(sql);
pst.setString(1,txt_firstname.getText());
pst.setString(2,txt_surname.getText());
pst.setString(3, txt_fee.getText());
pst.setString(4, (String) cbox_time.getSelectedItem());
pst.setString(5,txt_date.getText());
pst.setString(6, (String) cbox_doctors.getSelectedItem());
pst.executeUpdate();
The issues with your INSERT statement includes :-
You appear to be attempting an INSERT SELECT where the VALUES to be inserted are obtained from the SELECT clause, but you are trying to mix this with VALUES. The two types cannot be combined.
You are trying to select using columns within parenthesises and anyway those three columns WILL NOT match the 6 columns required for the insert.
You only have 1 ? to be bound, you are trying to bind 6.
I'd suggest that you could simplify matters by defining the table with a UNIQUE constraint on the doctor, date and time columns. Then use a standard INSERT OR IGNORE with the VALUES clause.
e.g. consider the following demonstration SQL :-
DROP TABLE IF EXISTS appointments;
CREATE TABLE IF NOT EXISTS appointments (patient_firstname TEXT, patient_surname TEXT, fees REAL, time TEXT, date TEXT, doctor INTEGER, UNIQUE (doctor, date, time));
INSERT OR IGNORE INTO appointments VALUES ('Fred','Bloggs',100.50,'10:00','2019-01-01',1);
INSERT OR IGNORE INTO appointments VALUES ('Mary','Smith',100.50,'10:00','2019-01-01',2);
INSERT OR IGNORE INTO appointments VALUES ('Sue','Bell',100.50,'10:00','2019-01-01',2);
SELECT * FROM appointments;
This results in :-
i.e Sue Bell's appointment has not been added because of the UNIQUE constraint conflict, which has been ignored so there is no error.
The log being :-
DROP TABLE IF EXISTS appointments
> OK
> Time: 0.177s
CREATE TABLE IF NOT EXISTS appointments (patient_firstname TEXT, patient_surname TEXT, fees REAL, time TEXT, date TEXT, doctor INTEGER, UNIQUE (doctor, date, time))
> OK
> Time: 0.084s
INSERT OR IGNORE INTO appointments VALUES ('Fred','Bloggs',100.50,'10:00','2019-01-01',1)
> Affected rows: 1
> Time: 0.083s
INSERT OR IGNORE INTO appointments VALUES ('Mary','Smith',100.50,'10:00','2019-01-01',2)
> Affected rows: 1
> Time: 0.084s
INSERT OR IGNORE INTO appointments VALUES ('Sue','Bell',100.50,'10:00','2019-01-01',2)
> Affected rows: 0
> Time: 0s
SELECT * FROM appointments
> OK
> Time: 0.003s
Related
I'm trying to add a test user to my website that employers can look at to see my work. I want to use some of the data I have entered into my profile so that it is faster.
I have a workouts table:
CREATE TABLE workouts(
id INTEGER NOT NULL,
userID INTEGER NOT NULL,
DateAndTime smalldatetime NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (UserID) REFERENCES users(id)
);
I have taken 25 of the first results and put it into a temporary workouts2 table:
CREATE TABLE workouts2 (
userid integer,
dateandtime smalldatetime);
Now I want to take those rows from workouts2 and put them into workouts. I have tried to add them by inserting workouts2 into workouts like this:
insert into workouts (id , userID, DateandTime) values (select * from workouts2);
This gives me an Error: in prepare, near "select": syntax error (1)
I can do it one at a time like this:
insert into workouts (userid, dateandtime) values (2, "2022-01-02T06:00");
Doing it one at a time is not ideal.
What am I missing here? I know I have a syntax error but I don't know how to fix it.
I have looked at this question which inserts one at a time:
How to insert a unique ID into each SQLite row?
The problem is it only inserts one at a time.
You should use SELECT instead of VALUES and not include the column id, which is auto-incremented, in the list of columns of workouts which will receive the values (such a column does not exist in workouts2):
INSERT INTO workouts (userID, DateandTime)
SELECT *
FROM workouts2;
Hello i have an sqlite db with many records like 10540 record they are ordered by creation time , i want to shift like a record in the middle and like to do it automatically
for example :
select * from table1 where id >= 8521;
UPDATE Table1 SET id = id +1 ;
does not work i get Error: Result: UNIQUE constraint failed:
so i want to shift up all records from 8521 to the last record and get place in the 8520 place for example so i can insert my record in that place of table .
even the
id = select max(id)+1
does not work how can i increment the id from last record to the needed record so i can put a place in the records db
A simple update statement would fail, as it would try to create duplicate values in the primary key.
What you can do is this:
First update the column to the negatives of the values they should have:
update table1
set id = -(id + 1)
where id > 8520;
Now there are no duplicates and you just need to update again to the positive values:
update table1
set id = -id
where id < 0;
This will do the trick, but any kind of updating the primary key is not a recommended practice
Consider the following table definition:
CREATE TABLE names (
id INTEGER,
name TEXT NOT NULL,
PRIMARY KEY (id)
)
Does it guarantee that the id will be auto-incremented for every new insert AND that the values for deleted rows will not be reused?
I looked up in the documentation for Sqlite3, but couldn't find the answer.
id INTEGER PRIMARY KEY on it's own guarantees (requires) a unique integer value and will if no value is specifically assigned provide one until the highest value has reached the highest allowed value for a 64 bit signed integer (9223372036854775807) after which an unused value may be found and applied.
With AUTOINCREMENT there is a guarantee (if not circumvented) of always providing a higher value BUT if 9223372036854775807 is reached instead of allocating an unused number an SQLITE_FULL error will result. That is the only difference from the point of view of what number will be assigned.
Neither guarantees a monotonically increasing value.
Without AUTOINCREMENT the calculation/algorithm is equivalent to
1 + max(rowid) and if the value is greater than 9223372036854775807 an attempt is made to find an unused and therefore lower value.
I've not seen that anyone has come across the situation where a random unused value has not been assigned.
With AUTOINCREMENT the calculation/algorithim is
the greater of 1 + max(rowid) or SELECT seq FROM sqlite_sequence WHERE name = 'the_table_name_the_rowid_is_being_assigned_to' and if the value is greater than 9223372036854775807 then SQLITE_FULL ERROR.
noting that either way there is the possibility that the max rowid is for a row that eventually doesn't get inserted and therefore the potential for gaps.
The answer is perhaps best put as: it's best/recommended to use the id column solely for it's intended purpose, that of efficiently identifying a row and not as a means of handling other data requirements, and if done so, there there is no need for AUTOINCREMENT (which has overheads)
In short
Does it guarantee that the id will be auto-incremented
NO
values for deleted rows will not be reused?
NO for the given code
for :-
CREATE TABLE names (id INTEGER PRIMARY KEY AUTOINCREMENT name TEXT NOT NULL)
again NO as if 9223372036854775807 is reached then an SQLITE_FULL error will result, otherwise YES.
So really AUTOINCREMENT is only really relevant (if the id used as expected/intended) when the 9223372036854775807'th row has been inserted.
Perhaps consider the following :-
DROP TABLE IF EXISTS table1;
DROP TABLE IF EXISTS table2;
CREATE TABLE IF NOT EXISTS table1 (id INTEGER PRIMARY KEY, somecolumn TEXT);
CREATE TABLE IF NOT EXISTS table2 (id INTEGER PRIMARY KEY AUTOINCREMENT, somecolumn TEXT);
INSERT INTO table1 VALUES (9223372036854775807,'blah');
INSERT INTO table2 VALUES (9223372036854775807,'blah');
INSERT INTO table1 (somecolumn) VALUES(1),(2),(3);
SELECT * FROM table1;
INSERT INTO table2 (somecolumn) VALUES(1),(2),(3);
This creates the two similar tables, the only difference being the use of AUTOINCREMENT. Each has a row inserted with the highest allowable value for the id column.
An attempt is then made to insert 3 rows where the id will be assigned by SQLite.
3 rows are inserted into the table without AUTOINCREMENT but no rows are inserted when AUTOINCREMENT is used. as per :-
CREATE TABLE IF NOT EXISTS table1 (id INTEGER PRIMARY KEY, somecolumn TEXT)
> OK
> Time: 0.098s
CREATE TABLE IF NOT EXISTS table2 (id INTEGER PRIMARY KEY AUTOINCREMENT, somecolumn TEXT)
> OK
> Time: 0.098s
INSERT INTO table1 VALUES (9223372036854775807,'blah')
> Affected rows: 1
> Time: 0.094s
INSERT INTO table2 VALUES (9223372036854775807,'blah')
> Affected rows: 1
> Time: 0.09s
INSERT INTO table1 (somecolumn) VALUES(1),(2),(3)
> Affected rows: 3
> Time: 0.087s
SELECT * FROM table1
> OK
> Time: 0s
INSERT INTO table2 (somecolumn) VALUES(1),(2),(3)
> database or disk is full
> Time: 0s
The result of the SELECT for table1 (which may differ due to randomness) was :-
I have the 'SchoolYearTeachingDays' table with just one column, in which are dates:
CREATE TABLE SchoolYearTeachingDays (
aDate DATE PRIMARY KEY
UNIQUE
);
I filled it with many dates which are unique. These dates excludes dates for Sundays and for Saturdays.
I have another, the 'TeachingSaturdaysInSchoolYear' table:
CREATE TABLE TeachingSaturdaysInSchoolYear (
id INT PRIMARY KEY
UNIQUE,
aDate DATE,
TimetableForTheDay TEXT
);
This table holds just two dates. These two dates are for two Saturdays. On these two Saturdays we have to teach students.
When I do the following query on this table, I get these two records:
2018-04-14
2018-05-05
I want to INSERT these two dates from the 'TeachingSaturdaysInSchoolYear' table into 'SchoolYearTeachingDays' table.
I am trying with this query:
INSERT INTO SchoolYearTeachingDays
SELECT aDate FROM TeachingSaturdaysInSchoolYear
;
but I get this error:
Error: UNIQUE constraint failed: SchoolYearTeachingDays.aDate
How this query of mine works and why I get this error? How do I accomplish my goal?
Best, Pal
You are violating unique constraint by inserting duplicate values into the table SchoolYearTeachingDays.
To fix the error put a not in condition so that dates which are already inserted won't get inserted again into SchoolYearTeachingDays table.
Example,
INSERT INTO SchoolYearTeachingDays
SELECT aDate FROM TeachingSaturdaysInSchoolYear T WHERE T.aDate NOT IN (SELECT S.aDate FROM SchoolYearTeachingDays S)
I have an SQLite database for an art exhibition. In the table "exhibits" I have columns for the artwork ID, the exhibition space ID, a begin date, and an end date. The default value for "end date" is NULL.
Of course, the same artwork cannot be displayed in two different spaces at once. So I want to ensure that a new row with an artwork ID is not created unless all existing rows with that same artwork ID have a non-null end date.
Is there some kind of constraint, trigger, etc. that I can add to the table to ensure this?
I am not an expert on writing triggers for SQLite but something like this should work,
CREATE TRIGGER check_open_ended_exhibit BEFORE INSERT ON exhibits
BEGIN
SELECT RAISE(ABORT, "Open ended exhibit exists")
WHERE EXISTS(SELECT * FROM exhibits WHERE artworkID = NEW.artworkID AND enddate IS NULL);
END
According to your information “Artwork” cannot be displayed twice in the same show which means the EndTime is a unique field when constraining it together with Artwork. So by making these two together your constrain you won’t be able to insert a record if you already have “artwork and NULL”.
So yeah you can just create a unique constrain on these two columns.
CREATE TABLE testConstrain (
id INTEGER NOT NULL,
endDate DATETIME
)
CREATE UNIQUE INDEX testConstrain
ON testConstrain(id, endDate);
INSERT INTO testConstrain VALUES('1',null)
INSERT INTO testConstrain VALUES('2','01-01-2018')
INSERT INTO testConstrain VALUES('1','01-01-2018')
INSERT INTO testConstrain VALUES('1',null)
`
And you will get:
Started executing query at Line 11
(1 row affected)
(1 row affected)
(1 row affected)
Msg 2601, Level 14, State 1, Line 4
Cannot insert duplicate key row in object 'bginsburg.testConstrain' with unique index 'testConstrain'. The duplicate key value is (1, ).
The statement has been terminated.