Insert query failing with a Syntax error while trying to run it - sql

Movie Table has 4 Attributes: movie_id, moive_name, desc, genre_id
movie_id (autoNumber) PK
moive_name(short Text)
desc(long Text)
genre_id(number) FK
This is the query I am trying to run
INSERT INTO Movie (moive_name,description,genre_id)
VALUES('Rise','dfdsfsa','1')
I know moive_name is miss spelled but its like that in the db aswell will fix it later.
I am still getting a systax error
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
I am sure the table is called Movie. I left out the movie_id field since I want it to auto fill with the next number as its autoNumber. Do you guys maybe know what I am doing wrong?

In your table have four values , but you are trying to insert with three values.
It won't work in oracle.Create Movie_id as a primary key without auto increment and create sequence for your movie id
CREATE SEQUENCE movie_id
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
and try this insert statement
INSERT INTO Movie (movie_id,moive_name,description,genre_id)
VALUES(movie_id.nextval,'Rise','dfdsfsa','1')

i think you are trying to insert a string in number '1' should be like 1
INSERT INTO Movie (moive_name,description,genre_id)
VALUES('Rise','dfdsfsa',1)

Hi Tristan,Provide genre_id without single codes as it is a numeric value. Not sure how you are generating movie_id, if it is a sequence number, provide the number
INSERT INTO Movie (movie_id,moive_name,description,genre_id)
VALUES (your_movie_id,'Rise','dfdsfsa',1)

Related

ORA-01722! Why can't I INSERT a NUMBER into a NUMBER data field without getting this error?

Can someone tell me what is going on here?
So I have a simple table location and it only has two columns; one is a number and the other varchar2.
I'm simply trying to insert some data into the locations table so I can get cracking with the other larger datasets but keep getting this damn error every time.
Error starting at line : 7 in command -
INSERT INTO location
VALUES (1, 'Head Office')
Error report -
ORA-01722: invalid number
NOTE: Before down-voting, YES - I have seen others posting about this but is usually for something less obvious than my situation where they are trying to enter a string into a number field or a number into a string field!
In my case however, the data in the INSERT statement is a number AND the data type is also NUMBER!
DATA STRUCTURE:
CREATE TABLE location(
locID NUMBER(4) NOT NULL,
locName VARCHAR2(100) NOT NULL
);
INSERT STATEMENT:
INSERT INTO location
VALUES (1, 'Head Office');
The error code can be seen above there where I first mentioned it.
Thanks in advance.
P.S. It may be worth mentioning that the ID field in 'location' table is being used as a FOREIGN KEY in a separate table 'employees'. I have however, checked that the data types matched!
EDIT #1: I'm using ORACLE SQL Developer
Always include the columns when doing an insert:
INSERT INTO location (locId, locname)
VALUES (1, 'Head Office');
From your description of the problem, this should not actually fix it. This is just a good habit.
The above is correct SQL for your table. If the error continues to happen it is probably coming from a trigger on the table.
Think like its stupid, you are getting number error from "head office" not from 1. Actually you are trying to insert string into number.
If you dont want to write column names to insert you should totally define all values in insert in place as located in table. I assume your table structure is
locId|locNumber
So your insert should be like below
insert into table values (1,'head office')
I hope you understand shortcut logic

ID generation in Oracle

I'm trying to create a table in Oracle as follows:
create table person (
person_id number(5) generated always as identity
minvalue 1
maxvalue 99999
increment by 1 start with 1
cycle
cache 10,
firstname varchar(10),
lastname varchar(10));
This works all fine, but when I try something like this:
insert into person
values ('firstname', 'lastname');
I'm getting an error. When I try putting in a number where the ID should be, I get a different error.
I'm confused because I originally thought that formatting the person_id in this way automatically generated unique ID values, so that I wouldn't be able to put them in.
I'm also a bit confused on how this all fits into JDBC. If I'm working with Java and I insert a tuple into such a table, how am I able to get the generated ID into my Java program? I can't search by first and last name, because there could be two people with the same name.
You need to list the columns for an insert:
insert into person(firstname, lastname)
values ('firstname', 'lastname');
The fact that the column is generated doesn't affect the syntax of the insert. So, with no columns, the insert is the same as:
insert into person(person_id, firstname, lastname)
values ('firstname', 'lastname');
And with two values and three columns, you are getting an error.

Insert with 2 DEFAULT constraints in a row

Let's say I have a create table script like that:
CREATE TABLE Person (
id INT PRIMARY KEY,
age INT DEFAULT 18,
iq INT DEFAULT 100
);
So I have two DEFAULT constraints in a row. Now I make an insertion like that:
INSERT INTO Person VALUES(1,85);
How do we know if we skip the attribute age or the attribute iq?
Thank you for your help.
The answer to your question: it depends. ;-)
MySQL
Running your query on MySQL will get you the following error:
Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
For MySQL you need to tell the DBMS which columns you want to have (and which columns the DB should fill with default data). Like this:
INSERT INTO Person(id, age) VALUES(1,85);
Or you need to tell the DB, where to use default values. You can pass the keyword DEFAULT for these columns:
INSERT INTO Person VALUES(1,85, DEFAULT);
See: MySQL INSERT Syntax
SQLite
SQLite acts like MySQL, the error message here is:
SQLITE_ERROR: table Person has 3 columns but 2 values were supplied
Which means, you have to specify the columns.
PostgreSQL
Running the query on a PostgreSQL table will yield
id age iq
1 85 100
Here PostgreSQL will use the columns from the table definition in the defined order and fill all remaining columns with the default value.
MS SQL Server
See: How to insert default values in SQL table?

Custom SERIAL / autoincrement per group of values

I'm trying to make a blog system of sort and I ran into a slight problem.
Simply put, there's 3 columns in my article table:
id SERIAL,
category VARCHAR FK,
category_id INT
id column is obviously the PK and it is used as a global identifier for all articles.
category column is well .. category.
category_id is used as a UNIQUE ID within a category so currently there is a UNIQUE(category, category_id) constraint in place.
However, I also want for category_id to auto-increment.
I want it so that every time I execute a query like
INSERT INTO article(category) VALUES ('stackoverflow');
I want the category_id column to be automatically be filled according to the latest category_id of the 'stackoverflow' category.
Achieving this in my logic code is quite easy. I just select latest num and insert +1 of that but that involves two separate queries.
I am looking for a SQL solution that can do all this in one query.
This has been asked many times and the general idea is bound to fail in a multi-user environment - and a blog system sounds like exactly such a case.
So the best answer is: Don't. Consider a different approach.
Drop the column category_id completely from your table - it does not store any information the other two columns (id, category) wouldn't store already.
Your id is a serial column and already auto-increments in a reliable fashion.
Auto increment SQL function
If you need some kind of category_id without gaps per category, generate it on the fly with row_number():
Serial numbers per group of rows for compound key
Concept
There are at least several ways to approach this. First one that comes to my mind:
Assign a value for category_id column inside a trigger executed for each row, by overwriting the input value from INSERT statement.
Action
Here's the SQL Fiddle to see the code in action
For a simple test, I'm creating article table holding categories and their id's that should be unique for each category. I have omitted constraint creation - that's not relevant to present the point.
create table article ( id serial, category varchar, category_id int )
Inserting some values for two distinct categories using generate_series() function to have an auto-increment already in place.
insert into article(category, category_id)
select 'stackoverflow', i from generate_series(1,1) i
union all
select 'stackexchange', i from generate_series(1,3) i
Creating a trigger function, that would select MAX(category_id) and increment its value by 1 for a category we're inserting a row with and then overwrite the value right before moving on with the actual INSERT to table (BEFORE INSERT trigger takes care of that).
CREATE OR REPLACE FUNCTION category_increment()
RETURNS trigger
LANGUAGE plpgsql
AS
$$
DECLARE
v_category_inc int := 0;
BEGIN
SELECT MAX(category_id) + 1 INTO v_category_inc FROM article WHERE category = NEW.category;
IF v_category_inc is null THEN
NEW.category_id := 1;
ELSE
NEW.category_id := v_category_inc;
END IF;
RETURN NEW;
END;
$$
Using the function as a trigger.
CREATE TRIGGER trg_category_increment
BEFORE INSERT ON article
FOR EACH ROW EXECUTE PROCEDURE category_increment()
Inserting some more values (post trigger appliance) for already existing categories and non-existing ones.
INSERT INTO article(category) VALUES
('stackoverflow'),
('stackexchange'),
('nonexisting');
Query used to select data:
select category, category_id From article order by 1,2
Result for initial inserts:
category category_id
stackexchange 1
stackexchange 2
stackexchange 3
stackoverflow 1
Result after final inserts:
category category_id
nonexisting 1
stackexchange 1
stackexchange 2
stackexchange 3
stackexchange 4
stackoverflow 1
stackoverflow 2
Postgresql uses sequences to achieve this; it's a different approach from what you are used to in MySQL. Take a look at http://www.postgresql.org/docs/current/static/sql-createsequence.html for complete reference.
Basically you create a sequence (a database object) by:
CREATE SEQUENCE serials;
And then when you want to add to your table you will have:
INSERT INTO mytable (name, id) VALUES ('The Name', NEXTVAL('serials')

How to test a CONSTRAINT in oracle

I have the following constraint:
ALTER TABLE Movie
ADD CONSTRAINT NomsRANGE
CHECK (totalNoms BETWEEN 0 AND 20);
...and used the following to try and test it:
INSERT INTO Movie
(totalNoms)
VALUES
('23');
I get the following error:
cannot insert NULL into ("ALI"."MOVIE"."MOVIEID")
My scheme is:
Actor (actorID, lastName, firstName, middleName, suffix, gender, birthDate, deathDate)
Movie (movieID, title, year, company, totalNoms, awardsWon, DVDPrice, discountPrice)
Quote (quoteID, quote)
Role (roleID ,roleName ,gender ,actorID* ,movieID*)
RoleQuote (roleID*, quoteID*)
And my relationships are:
CONSTRAINT_NAME C
------------------------------ -
QUOTE_FK R
ROLE_FK R
MOVIE_ROLE_FK R
ACTOR_ROLE_FK R
ACTORID P
MOVIEID P
QUOTEID P
ROLEID P
ROLEQUOTEID P
9 rows selected.
Answer:
The answer was simple none of you spotted this it took me all day but i solved it so am posting solution so it helps others.
INSERT INTO Movie(movieID, totalNoms)
VALUES('049', '22');
I missed the first value which was the primary key as the error was saying:
cannot insert NULL into ("ALI"."MOVIE"."MOVIEID")
When i entered a new primary key it showed the constraint was violated
Thank you guys for all the help
If you omit columns in an INSERT statement, the database still needs to fill the column for that row. Which would be NULL, unless you setup a DEFAULT constraint/etc for each column.
The error is telling you that MOVIE.movieid does not accept NULL, which is good. It sounds like you need to setup the sequence to populate the value, or provide logic for however you want MOVIE.movieid populated (far less ideal). The sequence can either be referenced in the INSERT statement to fill the value, or you can look at triggers/default constraints to handle things in the background.
You'll have to figure out how you want/need to handle any other errors relating to column NULLability. Only after this is done, will you be able to see if your CHECK constraint works -- there's a little concern about if the value is provided as a string, if Oracle will implicitly convert it to an INT/NUMERIC data type.
1) The specific error is telling you that your INSERT statement needs to specify the MovieID. If you have created sequences to generate your synthetic primary key values, you'd want something like this (assuming there are no other NOT NULL columns in the Movie table)
INSERT INTO Movie
(movieID, totalNoms)
VALUES
(movieId_seq.nextval, 23);
2) Assuming that totalNoms is a NUMBER since your check constraint is treating it like a number, you would want to insert the number 23 rather than the string 23. Forcing Oracle to do implicit conversions is never a good idea-- it probably won't matter on a simple INSERT like this but if you get in the habit of using numbers when you're dealing with numeric fields and strings when you're dealing with character fields, life will be a lot easier.