I have a table called books that I just altered to have a column called yearPUB. I'm trying to populate each row with a year but it's not working. This is the INSERT statement I'm using.
INSERT INTO books (yearPub)
VALUES (2002),
(2006),
(1999),
(2005),
(2003),
(2001),
(1998),
(1968),
(2009),
(1988),
Can someone tell me why it doesn't work?
You need to insert them one at a time, e.g.:
INSERT INTO books (yearPub) VALUES (2002);
INSERT INTO books (yearPub) VALUES (2006);
Alternatively, you could insert using a subquery with a select statement. The syntax may differ depending on what database you are using. For example, you could follow an example here and write something like:
INSERT INTO books (yearPub)
SELECT yearNumber FROM othertablename;
Related
A couple of days ago I took it upon myself to learn the fundamentals of SQL. While doing so, I came across the statement INSERT INTO which is used to insert records into a table or to specific columns. Imagine I have a table with 50 columns, let's name this table My_table. If I were to implement the INSERT INTO statement to My_table it would look something like this (please correct me if my syntax is wrong):
INSERT INTO My_table (column_1, column_2, column_3, column_4,...)
VALUES (value_1, value_2, value_3, value_4,...)
This list of columns would continue until I have specified all 50. Is there an alternative method to specifying all columns?
What I had in mind was code that looked something along the lines of:
INSERT INTO My_table (*)
You can do
INSERT INTO my_table VALUES (value_1, value_2...)
Keep in mind that the order in which you put said values is the order of the column, i.e. you had a table consisting of a CHAR(5) column called "name" and a BIGINT column called logindate in this exact order you would do
INSERT INTO my_table VALUES ("bobby", 12345678);
I have an existing table in MS SQL called myTab.
It has the following fields
empno(PK) nchar(10),
age int
Now, i want to add a myGUID column and fill it up with a GUID whenever i insert a new row as well as Updating existing rows.
So i added the statement
ALTER TABLE myTab ADD myGUID uniqueidentifier DEFAULT NewId() NOT NULL;
Updating existing rows works correctly.
But, when i try to insert values,
INSERT INTO myTab VALUES ( 1000, 22 );
It fails, and gives the following message
**Column name or number of supplied values does not match table definition.**
When i do
insert into sourav_test2 values (20055711,23,NEWID());
The above statement works.
I want a GUID to be filled without changing the insert statement. Is it possible via a Trigger or a Function?
Always list the columns you are inserting!
INSERT INTO myTab (empno, age)
VALUES ('1000', 22);
Also use correct types for the values. Unmentioned columns will be assigned their default values, or NULL if there is no explicit default.
Your table has three columns, so if you leave out the column list, then the insert expects three values. You can still set a default, if you want by using the DEFAULT keyword in the VALUES clause:
INSERT INTO myTab (empno, age, myGUID)
VALUES ('1000', 22, DEFAULT);
Sourav's question about triggers got me thinking, so I tried a little test. Why?
Imagine a scenario where an application has already been written with thousands of INSERT statements that leave off the column list. In this case, if you could write an INSTEAD OF INSERT trigger that provides the column list, you could hopefully save yourself from correcting thousands of INSERT statements due to a newly added column.
Off the top of my head, I admittedly did not know if this could work.
So I wrote this little test:
CREATE TABLE tt (ColA varchar(1));
INSERT INTO tt VALUES ('a');
ALTER TABLE tt
ADD ColB uniqueidentifier DEFAULT NEWID();
GO
CREATE TRIGGER tr_tt
ON tt
INSTEAD OF INSERT
AS
INSERT INTO tt (ColA)
SELECT ColA FROM inserted;
GO
INSERT INTO tt VALUES ('a');
SELECT * FROM tt;
DROP TABLE tt;
I also tried a variation of the TRIGGER with the following INSERT just to be thorough:
INSERT INTO tt (ColA, ColB)
SELECT ColA, NEWID() FROM inserted;
The result was the same in both cases: The same error as reported in the question. So to answer the question:
Can't we use a trigger here which can do it?
The answer is NO. Even if you put an INSTEAD OF INSERT TRIGGER on the table, the parser will still not let you write an INSERT..VALUES() statement unless the number and order of VALUES exactly matches the definition of the table. A TRIGGER cannot be used to get around it.
Sooner or later, lazy coding exacts its price.
How would I insert into multiple tables with one sql script in db2
For example, insert a row into T1 DOCK_DOOR and then insert into T2 DOCK_DOOR_LANE multiple times based on the dock_door_sysid from the first table.
My first approach was the following. I was attempting to use a with with three inserts. on the other hand, doing to inserts on the second table is not and option if this can be automated with one insert.
thanks for any feedback
sql example
WITH ins AS (
INSERT INTO DBF1.DOCK_DOOR (DOCK_DOOR_SYSID,DOOR_NUMBER,DOOR_NAME,DOCK_SYSID,DOOR_SEQ,ENCRYPTION_CODE,RFID_ENBLD_FLAG,LANES_COUNT,CMNT_TEXT,CREATE_TS,CREATE_USERID,UPDATE_TS,UPDATE_USERID,VER_NUMBER,ACTIVE_FLAG,STATUS_SYSID,DOOR_TYPE_SYSID)
VALUES (nextval for DBF1.DOCK_DOOR_SEQ,'026','DOOR025',61,25,NULL,'N','2',NULL,current timestamp,'SQL_INSERT',current timestamp,'SQL_INSERT',0,NULL,1723,1142)
RETURNING door_number,dock_door_sysid),
ins2 AS (
INSERT INTO SIT.DOCK_DOOR_lane (DOCK_DOOR_LANE_SYSID,DOOR_LANE_ID,DOCK_DOOR_SYSID,LANE_ID,CREATE_TS,CREATE_USERID,UPDATE_TS,UPDATE_USERID,VER_NUMBER)
VALUES (nextval for DBF1.DOCK_DOOR_LANE_seq,door_number||''||'A',dock_door_sysid,'A',current timestamp},'SQL_INSERT',current timestamp,'SQL_INSERT',0)
SELECT door_number,dock_door_sysid FROM DBF1.DOCK_DOOR
RETURNING door_number,dock_door_sysid)
INSERT INTO DBF1.DOCK_DOOR_lane (DOCK_DOOR_LANE_SYSID,DOOR_LANE_ID,DOCK_DOOR_SYSID,LANE_ID,CREATE_TS,CREATE_USERID,UPDATE_TS,UPDATE_USERID,VER_NUMBER)
VALUES (nextval for DBF1.DOCK_DOOR_LANE_seq,door_number||''||'B',dock_door_sysid,'B',current timestamp},'SQL_INSERT',current timestamp,'SQL_INSERT',0)
SELECT door_number,dock_door_sysid FROM DBF1.DOCK_DOOR;
Table 1 = dock_door
Table 2 = Dock_door_lane
You could do it with a trigger on the dock_door table.
However, if you're on a recent, version on IBM i. You might be able to make use of data change table reference
Your statement would look something like this
insert into dock_door_lane
select <....>
from final table (insert into dock_door <...>)
I'm not sure it will work, as this article indicates that at least at a couple of years ago DB2 for i didn't support the secondary insert required.
This old SO question also seems to confirm that at least at v7.1, the double insert isn't supported.
If I get a chance, I'll run a test on a 7.2 system Monday.
So I'm having some issues producing a query with multiple temporary tables.
First I created the temporary tables.
CREATE GLOBAL TEMPORARY TABLE DIDV (DID VARCHAR(50))
INSERT INTO DIDV VALUES ('8090630909077434001');
INSERT INTO DIDV VALUES ('7471990179373590001');
INSERT INTO DIDV VALUES ('7605256906013877001');
INSERT INTO DIDV VALUES ('1604387368720407001');
INSERT INTO DIDV VALUES ('3512739534818409001');
CREATE GLOBAL TEMPORARY TABLE KEYW (KEW VARCHAR(50))
INSERT INTO KEYW VALUES ('%Corporate Insurance Pol%');
INSERT INTO KEYW VALUES ('%Tax Return%');
INSERT INTO KEYW VALUES ('%Audit%');
INSERT INTO KEYW VALUES ('%Corporate Governance%');
INSERT INTO KEYW VALUES ('%Board%');
INSERT INTO KEYW VALUES ('%Shareholder%');
Then I write my query as follows. It seems like a simple query. However, I get the error 'ORA-00918: column ambiguously defined'. I don't know if I can do a join of the 2 temporary tables, especially they do not have any relationship. I just want to query result where the unique id's are in the DIDV table and where the title and comment columns do not contain the KEW fields.
SELECT TO_CHAR(DID) DID, TO_CHAR(DROOTPARENTID) PARENTID, DBARCODE,
DDOCTITLE, XCOMMENTS, XDIVISION, DEXTOBJECTTYPE
FROM PSA.URM_EXTITEMS_PSA, DIDV, KEYW
WHERE PSA.URM_EXTITEMS_PSA.DID = DIDV.DID
AND PSA.URM_EXTITEMS_PSA.DDOCTITLE NOT LIKE KEYW.KEW
AND PSA.URM_EXTITEMS_PSA.XCOMMENTS NOT LIKE KEYW.KEW;
Any help understanding this is appreciated.
Please let me know if any clarification is needed.
A table DIDV contains a column named DID
A table URM_EXTITEMS_PSA also contains a column named DID (I know this because a where condition contains a clause WHERE PSA.URM_EXTITEMS_PSA.DID = DIDV.DID ).
A select statement in your query contains an expression referencing the column DID:
SELECT TO_CHAR(DID) ....
Oracle doesn't really know (I don't know too) which DID do you want to get in a result - the 'DID' column which comes from DIDV table or the DID column which comes from URM_EXTITEMS_PSA table. Therefore Oracle throws an error ORA-00918: column ambiguously defined.
Just append an aliast to this DIV column in the select clause, either DIDV or URM_EXTITEMS_PSA, in this way:
SELECT TO_CHAR(DIDV.DID) ....
I know that WHERE clause contains PSA.URM_EXTITEMS_PSA.DID = DIDV.DID and actually both DIDs are equal, so Oracle should be smart enaugh to say Oh, yes, he wrote PSA.URM_EXTITEMS_PSA.DID = DIDV.DID, so I can pick DID from any table ....
Unfortunatelu Oracle is not so smart (maybe they improve this in a new version ?), and for now you must append an alias or a table name.
I am trying to insert values into 1 column of a table when a condition is satisfied.
Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.
I have this query:
INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>
I am getting an exception:
Incorrect Syntax Near WHERE Keyword
I am able to do this using UPDATE:
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
But was wondering why the INSERT query was failing. Any advise appreciated.
As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.
This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.
So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.
In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:
INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
The SQL Insert dont accept where parameters, you could check this: SQL Insert Definition...
I do not know the whole question of what you want to do, but just using the INSERT statement is not possible, however it is possible to condition the insertion of data into a table, if this data is dependent on another table or comes from another table ... check here... SQL Insert explain in wikipedia
like this:
Copying rows from other tables
INSERT INTO phone_book2
SELECT *
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
or
INSERT INTO phone_book2 ( [name], [phoneNumber] )
SELECT [name], [phoneNumber]
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
Based on your question I have the feeling that you are trying to UPDATE a column in a table rather than insert.
Something like:
UPDATE column SET value WHERE different_column_value = some_value
I know this is kinda late, for those who still want to use the where clause in an insert query, it's kinda possible with a hack.
My understanding is that, you want to insert only if a condition is true. Let's assume you have a column in your database "surname" and you want to insert only if a surname doesn't exist from the table.
You kinda want something like INSERT INTO table_name blha blha blah WHERE surname!="this_surname".
The solution is to make that cell unique from your admin panel.
Insert statement will insert a new record. You cannot apply a where clause to the record that you are inserting.
The where clause can be used to update the row that you want.
update SET = where .
But insert will not have a where clause.
Hope this answers your question
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
I take it the code you included is simply a template to show how you structured your query. See the SO questions here, here and the MSDN question here.
In SQL Server (which uses Transact-SQL aka T-SQL) you need an UPDATE query for INSERT where columns already have values - by using the answer #HaveNoDisplayName gave :)
If you are executing INSERT / UPDATE from code (or if you need it regularly) I would strongly recommend using a stored procedure with parameters.
You could extend the procedure further by adding an INSERT block to the procedure using an IF-ELSE to determine whether to execute INSERT new record or UPDATE an existing, as seen in this SO answer.
Finally, take a look at SQLFiddle for a sandbox playground to test your SQL without risk to your RDMS :-)
Private case I found useful: Conditional insert which avoids duplications:
-- create a temporary table with desired values
SELECT 'Peter' FirstName, 'Pan' LastName
INTO #tmp
-- insert only if row doesn't exist
INSERT INTO Persons (FirstName, LastName)
SELECT *
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM Persons where FirstName=t.FirstName and LastName=t.LastName)
If the data need to be added for a column for an existing row then it’s UPDATE.
INSERT is creating a new row in the table.
For conditional INSERT, you can use the MERGE command.