PostgreSQL: INSERT INTO syntax error - sql

I'm following an older tutorial learning Postgres, so it's possible maybe something has changed since it was published. In the tutorial (using psql) I create a table then do some insert statements. Here is the tutorial and corresponding psql commands that cause error:
http://www.postgresqlforbeginners.com/2010/11/create-table-and-constraints.html
create table people(
id int PRIMARY KEY,
name varchar NOT NULL
);
insert into people(0,'Steve Jobs');
insert into people(1,'Mike Markkula');
insert into people(2,'Mike Scott');
insert into people(3,'John Sculley');
insert into people(4,'Michael Spindler');
insert into people(5,'Gil Amelio');
insert into people(6,'Mike Scott');
I get this error for each insert statement:
ERROR: syntax error at or near "0"
LINE 1: insert into people(0,'Steve Jobs');
^
I've tried copy pasting, capitalizing the sql commands (ie INSERT), running the command from shell outside of psql, adding spaces, using " instead of ' quotes... All result in the same errors. Has something changed or am I possibly doing something wrong?

The problem is the missing values (as noted in a comment).
I want to make some suggestions. First, whenever you use insert, you should always list the columns. This is especially important if you are learning the language -- you should be learning good habits.
Second, you don't need multiple inserts. A shorter way to insert multiple rows is:
insert into people (id, name)
values (0,'Steve Jobs'),
(1,'Mike Markkula'),
(2,'Mike Scott'),
(3,'John Sculley'),
(4,'Michael Spindler'),
(5,'Gil Amelio'),
(6,'Mike Scott');
And you should learn about serial. A more common way to write this code would be:
create table people (
id serial PRIMARY KEY,
name varchar NOT NULL
);
insert into people (name)
values ('Steve Jobs'),
('Mike Markkula'),
('Mike Scott'),
('John Sculley'),
('Michael Spindler'),
('Gil Amelio'),
('Mike Scott');
The id is assigned automatically by the database (starting at 1 rather than 0).
I should add: I am personally uncomfortable with having varchar without a length. This is perfectly fine in Postgres, but some databases would interpret it as varchar(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

Inserting to one table, insert the ID to second table

Is it possible to populate a second table when I insert into the first table?
Insert post to table1 -> table 2 column recieves table1 post's unique id.
What I got so far, am I on the right track?
CONSTRAINT [FK_dbo.Statistics_dbo.News_News_NewsID] FOREIGN KEY ([News_NewsID]) REFERENCES [dbo].[News] ([NewsID])
Lots of ways:
an insert trigger
read SCOPE_IDENTITY() after the first insert, and use it to do a second
use the output clause to do an insert
Examples:
1:
create trigger Foo_Insert on Foo after insert
as
begin
set nocount on
insert Bar(fooid)
select id from inserted
end
go
insert Foo (Name)
values ('abc');
2:
insert Foo (Name)
values ('abc');
declare #id int = SCOPE_IDENTITY();
insert Bar(fooid)
select #id
3:
insert Bar(fooid)
select id from (
insert Foo (Name)
output inserted.id
values ('abc')) x
The only thing I can think of is that you can use a trigger to accomplish this. There is nothing "built in" to SQL Server that would do it. Why not just do it from your .NET code?
Yes it is, it sounds like you want a SQL Trigger, this would allow you to trigger logic based on actions on one table, to perform other actions in the DB. Here's another article on creating Simple SQL Triggers
SQL Server 2008 - Help writing simple INSERT Trigger
A Word of caution, this will do all the logic of updating the new table, outside of any C# code you write, it might sound nice to not have to manage it upfront, but you also lose control over when and if it happens.
So if you need to do something different later, now you have to update your regular code, as well as the trigger code. This type of logic can definitely grow, in large systems, and become a nightmare to maintain. Consider this, the alternative would be to build a method that adds the id to the new table after it inserts into the first table.
While i don't know what you're using to do your inserts assuming it's a SQL Command you can get back the ID on an identity column from the insert using Scope_Identity, found here
How to insert a record and return the newly created ID using a single SqlCommand?
if it's EF or some other ORM tool, they should either automatically update the entity, or have other mechanisms to deliver this data.

Getting INSERT errors when I do UPDATE?

At work we have a SQL Server database. I don't know the db that well. I have created a new column in the table for some new functionality....straight away I have started seeing errors
My statement was this:
ALTER TABLE users
ADD locked varchar(50) NULL
GO
The error is:
Insert Error: Column name or number of supplied values does not match table definition
I have read that the error message appears when during an INSERT operation either the number of supplied column names or the number of supplied values does not match the table definition.
But I have checked so many times and i have changed the PHP code to include this columns data yet I still receive the error.
I have run the SQL query directly on the db and still get the error.
Funny enough the query which gets the error is an Update.
UPDATE "users"
SET "users"."date_last_login" = GETDATE()
WHERE id = 1
Have you considered it could be a trigger causing it? 
This is the error message you would get.
If its an Update action causing it check trigger actions that Updates on that table run.
Do it with:
#sp_helptrigger Users, 'UPDATE';
This will show triggers occuring with ‘update’ actions.
If there is a trigger, grab the triggers name and run the below (but replace TriggerNameHere with real trigger):
#sp_helptext TriggerNameHere;
This will give you any SQL that the trigger runs and could be the INSERT the error message is referring to.
Hope this helps
Aside from TRIGGERS,
the reason for that is because you are using implicit type of INSERT statement. Let's say your previous number of columns on the table is 3. You have this syntax of INSERT statement,
INSERT INTO tableName VALUES ('val1','val2','val3')
which executes normally fine. But then you have altered the table to add another column. All of your INSERT queries are inserting only three values on the table which doesn't matches to the total number of columns.
In order to fix the problem, you have to update all INSERT statements to insert 4 values on the table,
INSERT INTO tableName VALUES ('val1','val2','val3', 'val4')
and it will normally work fine.
I'll advise you to use the EXPLICIT type of INSERT wherein you have to specify the columns you want to insert values with. Eg,
INSERT INTO tableName (col1, col2, col3) VALUES ('val1','val2','val3')
in this ways, even if you have altered your tables by adding additional columns, your INSERT statement won't be affected unless the column doesn't have a default value and which is non-nullable.

SQL insert into with Hsqldb Script

I am trying to initialise my hsqldb with some default data but seem to be having a problem with identity and timestamp columns.
I just realised that I probably wasn't clear what I meant when I said "script". I am meaning the command line argument that you pass to hsqldb to generate your database at startup. I can successfully run the query inside DbVisualiser or some other database management tool.
I have a table with the following definition:
create table TableBob (
ID int NOT NULL identity ,
FieldA varchar(10) NULL,
FieldB varchar(50) NOT NULL,
INITIAL_DT timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL);
I can successfully create this table using the script but trying to insert a record doesn't work. Below is what I would consider valid sql for the insert since the ID and INITIAL_DT fields are Identity and Default columns). Strangely it inserts null into every column even though they are defined as NOT NULL....
e.g.
INSERT INTO TableBob (FieldA, FieldB) VALUES ('testFieldA', 'testFieldB');
Thanks for your help
Please try with HSQLDB's DatabaseManagerSwing (you can double click on the hsqldb.jar to start the database manager). First execute the CREATE TABLE statement, then the INSERT statement, finally the SELECT statement.
It should show the correct results.
If you want to use a script to insert data, use the SqlTool.jar which is available in the HSQLDB distribution zip package. See the guide: http://hsqldb.org/doc/2.0/util-guide/

Atomic INSERT/SELECT in HSQLDB

I have the following hsqldb table, in which I map UUIDs to auto incremented IDs:
SHORT_ID (BIG INT, PK, auto incremented) | UUID (VARCHAR, unique)
Create command:
CREATE TABLE mytable (SHORT_ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, UUID VARCHAR(36) UNIQUE)
In order to add new pairs concurrently, I want to use the atomic MERGE INTO statement. So my (prepared) statement looks like this:
MERGE INTO mytable USING (VALUES(CAST(? AS VARCHAR(36)))) AS v(x) ON mytable.UUID = v.x WHEN NOT MATCHED THEN INSERT VALUES v.x
When I execute the statement (setting the placeholder correctly), I always get a
Caused by: org.hsqldb.HsqlException: row column count mismatch
Could you please give me a hint, what is going wrong here?
Thanks in advance.
Epilogue
I reported this behavior as a bug, and it is today (2010-05-25) fixed in the hsqldb SVN repository, per hsqldb-Bugs-2989597. (Thanks, hsqldb!)
Updated Answer
Neat one! Here's what I got to work under HSQLDB 2.0.0rc9, which supports the syntax and the error message you posted:
MERGE INTO mytable
USING (SELECT 'a uuid' FROM dual) AS v(x) -- my own "DUAL" table
ON (mytable.UUID = v.x)
WHEN NOT MATCHED THEN INSERT
VALUES (NULL, x) -- explicit NULL for "SHORT_ID" :(
Note, I could not convince 2.0.0rc9 to accept ... THEN INSERT (UUID) VALUES (x), which is IIUC a perfectly acceptable and clearer specification than the above. (My SQL knowledge is hardly compendious, but this looks like a bug to me.)
Original Answer
You appear to be INSERTing a single value (a 1-tuple) into a table with more than one column. Perhaps you can modify the end of your statement to read:
... WHEN NOT MATCHED INSERT ("UUID") VALUES (v.x)
I got same problems but solve in few minutes.
Its occur when datavalues and table structure are not same.Add explicit (NULL) in your empty column value.
Like i created table
TestCase table:
ID TESTCASEID DESCRIPTION
but your insertion statement you donot want to add any description for any testcase description then you have to explicite in insertion statement you have to set null value for description