You are here
Home > Sql Server > SQL Query (INSERT Statement)

SQL Query (INSERT Statement)

SQL Query

      Insert Statement:

  • Insert statement is used to insert data in to a table.
  • There are two basic syntaxes of the insert statement.
  • Syntax 1:
  • insert into table_name

    values(value1, value2,….. ,valueN);

  • If you are adding values for all columns, you do not specify the column names.
  • Syntax 2:
  • insert into table_name (column1,column2,…..,columnN)
  • values(value1, value2,….. ,valueN);
  • Here,column1,column2,……,columnN are columns name.
  • To insert data we have to specify both values and column names.
  • Database Table: student
Id Name
1 Karan
2 Anil
  • Example-1:

insert into student(Id,Name)

values(3,’ Smita’);

  • One record will be inserted. Select data from student table.
  • select * from student;
  • Output:
Id Name
1 Karan
2 Anil
3 Smita

 

  • Example-2:    Database Table: student
    Id Name
    1 Karan
    2 Anil

    insert into student values(4,’ Juhi’);

  • One record will be inserted. Select data from student table.
  • select * from student;
  • Output:
Id Name
1 Karan
2 Anil
4 Juhi

 

  • Insert into Select Statement:

  • Insert into Select statement is used to add multiple records into database.
  • It requires that data types match in source and target tables.
  • Insert all columns from one table to another table.
  • Syntax:
  • insert into table_name2

    select * from table_name1

    where condition;

  • Insert some columns from one table to another table.
  • Syntax:
  • insert into table_name2(column1, column2,…., columnN)

    select (column1, column2,…., columnN) from table_name1

    where condition;

  • Database Table: student1
Id Name City
1 Karan Anand
2 Anil Anand
3 Rohit V.V.Nagar
4 Smita V.V.Nagar
5 Juhi Borsad
6 Atul Ahmedabad
  • Database Table: student2
  • Columns names of student2: Stu_id,Firstname,City
  • Example-1:
  • insert into student2(Stu_id,Firstname,City)

    select Id, Name,City from student1;

  • Six records will be inserted. Select data from student2 table.
  • select * from student2;
  • Output:
Stu_id Firstname City
1 Karan Anand
2 Anil Anand
3 Rohit V.V.Nagar
4 Smita V.V.Nagar
5 Juhi Borsad
6 Atul Ahmedabad
  • Example-2:

insert into student2(Stu_id,Firstname,City)

select Id, Name,City from student1

where City=’ Anand’;

  • Records will be inserted. Select data from student2 table.

select * from student2;

Output:

Stu_id Firstname City
1 Karan Anand
2 Anil Anand
3 Rohit V.V.Nagar
4 Smita V.V.Nagar
5 Juhi Borsad
6 Atul Ahmedabad
1 Karan Anand
2 Anil Anand

 

 

Keep visiting my site ask2tech.com for upcoming top technical article

Learn more about DBA at TechNet Consultancy

Leave a Reply

Top