SQL Server Insert Example - sql

I switch between Oracle and SQL Server occasionally, and often forget how to do some of the most trivial tasks in SQL Server. I want to manually insert a row of data into a SQL Server database table using SQL. What is the easiest way to do that?
For example, if I have a USERS table, with the columns of ID (number), FIRST_NAME, and LAST_NAME, what query do I use to insert a row into that table?
Also, what syntax do I use if I want to insert multiple rows at a time?

To insert a single row of data:
INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');
To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');
To insert multiple rows of data in SQL Server 2008 or later:
INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');
To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:
INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'
Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

Here are 4 ways to insert data into a table.
Simple insertion when the table column sequence is known.
INSERT INTO Table1 VALUES (1,2,...)
Simple insertion into specified columns of the table.
INSERT INTO Table1(col2,col4) VALUES (1,2)
Bulk insertion when...
You wish to insert every column of Table2 into Table1
You know the column sequence of Table2
You are certain that the column sequence of Table2 won't change while this statement is being used (perhaps you the statement will only be used once).
INSERT INTO Table1 {Column sequence} SELECT * FROM Table2
Bulk insertion of selected data into specified columns of Table2.
.
INSERT INTO Table1 (Column1,Column2 ....)
SELECT Column1,Column2...
FROM Table2

I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

For example, "person" table has "id" IDENTITY column as shown below:
CREATE TABLE person (
id INT IDENTITY, -- Here
name NVARCHAR(50),
age INT,
PRIMARY KEY(id)
)
Then, we don't need to manually put a value to "id" IDENTITY column when inserting a row:
INSERT INTO person VALUES ('John', 27) -- The value for "id" is not needed
And, we can also insert multiple rows without the values for "id" IDENTITY column:
INSERT INTO person VALUES ('John', 27), ('Tom', 18)

Related

Inserting Values Into Table with Identity Column via Databricks

I've created a table in Databricks that is mapped to a table hosted in an Azure SQL DB. I'm trying to do a very simple insert statement on a small table, but an identity column is giving me issues. This table has the aforementioned identity column and three additional columns.
I first tried something similar to below:
%sql
INSERT INTO tableName (col2, col3, col4)
VALUES (1, 'Test Value', '2018-11-16')
That was giving me a syntax error, so I did some searching and learned that Hive SQL doesn't allow you to specify columns for an INSERT statement. So then I tried something like below as a test:
%sql
INSERT INTO tableName
VALUES (100, 1, 'Test Value', '2018-11-16')
That gives me an error message that I can't insert explicit values into an identity column, but that's what I expected to happen.
If I can't specify the columns for my INSERT statement, how do I avoid issues when I have an identity column? I just want to insert values for the non-identity columns, and I want the ID column to continue incrementing like normal. The above example is extremely watered-down. I will need to do much larger insertions based on SELECT statements eventually, so any solution involving toggling on IDENTITY_INSERT probably isn't feasible.
Below is how we can create a table with an identity column -
CREATE TABLE table_name
(column_name1 data_type GENERATED ALWAYS AS IDENTITY,
column_name2......)
Below are the two ways how we can insert the data into the table with the Identity column -
First way -
INSERT INTO T2 (CHARCOL2)
SELECT CHARCOL1 FROM T1;
Second way -
INSERT INTO T2 (CHARCOL2,IDENTCOL2) OVERRIDING USER VALUE
SELECT * FROM T1;
Links for reference-
Create table - https://docs.databricks.com/sql/language-manual/sql-ref-syntax-ddl-create-table-using.html
Insert into table - https://www.ibm.com/docs/en/db2-for-zos/11?topic=statement-rules-inserting-data-into-identity-column

need to combine 3 sql-statement into 1

I have 3 SQL-Statements that I would like to combine into just one so I dont have to make multiple requests to my database from my programm (java).
My DB is PostgreSQL 9.4
First one creates a new user in umgmt_users
INSERT INTO umgmt_users ("user") VALUES ('test1')
Second one gets the id of that user (db is postgres and id data type is serial, so it get assigned automatically with me/the programm not knowing what id the user will get
SELECT umgmt_users.id
FROM umgmt_users
WHERE umgmt_users.user = 'test1'
Thrird is to add the just created user with his id (which I need the second statement for) and some other values into a different table
INSERT INTO
umgmt_user_oe_fac_role ("user_id", "oe_id", "fac_id", "role_id")
VALUES ('ID OF USER test1 created in first statement', '1', '2', '1');
Is there a way to get all three Statements into one?
create user
look up the ID he got assigned
insert his ID + other values into a different table
I'm not that good at SQL, I tried to put brackets around the select and put it into the insert & also looked at UNION and WITH but can not get it to work...
EDIT: Ended up using this solution from a_horse_with_no_name
with new_user as (
INSERT INTO umgmt_users ("user") VALUES ('test1')
returning id
)
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
SELECT id, 1, 2, 1
FROM new_user;
All you need is two inserts:
INSERT INTO umgmt_users ("user") VALUES ('test1');
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
VALUES (lastval(), 1, 2, 1);
In order for lastval() to work correctly there must be no other statement between the two inserts and the have to be run in a single transaction (so autocommit needs to be turned off)
Alternatively you can use a data modifying CTE which is then executed as a single statement:
with new_user as (
INSERT INTO umgmt_users ("user") VALUES ('test1')
returning id
)
INSERT INTO umgmt_user_oe_fac_role (user_id, oe_id, fac_id, role_id)
SELECT id, 1, 2, 1
FROM new_user;
Please don't put numbers in single quotes.
The answer to this is : It's impossible to combine these into a single plain vanilla ANSI SQL statement.
The first and third ones talk about two different tables altogether.
The second one is a Select Statement which is a different type of statement from the other two.

SQLite : insert multiple value (select from) with insert specified value

i'm trying to make sqlite query that can insert multiple values , here's my query that i try :
insert into table1(idy_table1,idx_table1)
values ('1', //specified value insert to idy_table1
(select id_table2 from table2)) //insert value from select id_table2
i'm having some trouble, it just only insert one value,
and my question is how to make a proper query? so i can make it work.
The VALUES clause always adds one row.
(Except when you're using multiple tuples, but this does not work with queries.)
The easiest way to add multiple rows from a query is to use the SELECT form of the INSERT statement:
INSERT INTO Table1(idy_table1, idx_table1)
SELECT '1', id_table2 FROM table2;

Insert multiple rows into single column

I'm new to SQL, (using SQL 2008 R2) and I am having trouble inserting multiple rows into a single column.
I have a table named Data and this is what I am trying
INSERT INTO Data ( Col1 ) VALUES
('Hello', 'World')
That code was taken from this question, but it, like many other examples I have found on the web uses 2 columns, I just want to use 1. What am I doing wrong?
Thanks
To insert into only one column, use only one piece of data:
INSERT INTO Data ( Col1 ) VALUES
('Hello World');
Alternatively, to insert multiple records, separate the inserts:
INSERT INTO Data ( Col1 ) VALUES
('Hello'),
('World');
to insert values for a particular column with other columns remain same:-
INSERT INTO `table_name`(col1,col2,col3)
VALUES (1,'val1',0),(1,'val2',0),(1,'val3',0)
I believe this should work for inserting multiple rows:
INSERT INTO Data ( Col1 ) VALUES
('Hello'), ('World'),...
Another way to do this is with union:
INSERT INTO Data ( Col1 )
select 'hello'
union
select 'world'
If your DBMS supports the notation, you need a separate set of parentheses for each row:
INSERT INTO Data(Col1) VALUES ('Hello'), ('World');
The cross-referenced question shows examples for inserting into two columns.
Alternatively, every SQL DBMS supports the notation using separate statements, one for each row to be inserted:
INSERT INTO Data (Col1) VALUES ('Hello');
INSERT INTO Data (Col1) VALUES ('World');
INSERT INTO Data ( Col1 ) VALUES ('Hello'), ('World')
In that code you are inserting two column value.
You can try this
INSERT INTO Data ( Col1 ) VALUES ('Hello'),
INSERT INTO Data ( Col1 ) VALUES ('World')
Kindly ensure, the other columns are not constrained to accept Not null values, hence while creating columns in table just ignore "Not Null" syntax. eg
Create Table Table_Name(
col1 DataType,
col2 DataType);
You can then insert multiple row values in any of the columns you want to.
For instance:
Insert Into TableName(columnname)
values
(x),
(y),
(z);
and so on…
Hope this helps.
INSERT INTO hr.employees (location_id) VALUE (1000) WHERE first_name LIKE '%D%';
let me know if there is any problem in this statement.

INSERT INTO a Table

I'm trying to simply adding some data in a table but I receive an error:
Msg 110, Level 15, State 1, Line 1
There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
Here what I'm using
INSERT INTO dbo.ReModalities
(ModalityId, Name, Description)
VALUES
(
1,'A','A.',
2,'B','B.'
);
This should give you an idea of the Table Column
INSERT INTO [XXX].[dbo].[ReModalities]
([ModalityId]
,[Name]
,[Description])
VALUES
(<ModalityId, int,>
,<Name, nvarchar(64),>
,<Description, nvarchar(256),>)
GO
Also I would like to know if there is way I can avoid typing the IDs (the table has PK so they should be created automatically) many thanks!
Each row of the values statement should be enclosed in parenthesis. Try:
VALUES
(1,'A','A.'),
(2,'B','B.');
If the ID has a default value or is an identity, you can omit it:
insert dbo.ReModalities
(Name, Description)
values ('A','A.'),
('B','B.');