DML Commands in SQL SERVER : INSERT (Part 1)

DML: Data Manipulation Language

INSERT Command is used to store data in a table.

In this session we will see how data can be stored in SQL SERVER.

Syntax for the INSERT Command is :

INSERT INTO <Table Name>
(
    column 1,
    column 2,
    |
    |
    |
    column N
)
VALUES
(
    Value 1,
    Value 2,
    |
    |
    |
    Value N
)

Create  a table with the name MOBILE using the following commands:

CREATE TABLE MOBILE
(
    BRAND     VARCHAR(10),
    MODEL     VARCHAR(100),
    PRICE       INT
)

Insert the data into above table using the INSERT command syntax given above:

Data can be inserted into MOBILE table using 2 options:

Option 1:

Mentioning the columns names in the INSERT statement and the order in which data needs to be inserted into table.

This is the best practice one should cultivate from the begining of their career.
Inserting data into a table with out column names ( Option 2) is not only a bad practice, but also i will cause errors when new columns are added to table.

INSERT INTO MOBILE
(
    BRAND  , 
    MODEL   ,
    PRICE  
)
VALUES
(
    'NOKIA',
    'NOKIA 800 C',
    9500
)

Data in the MODEL Table after executing the above query:
















Option 2:

Command given in Option 1 can also be written as follows:

INSERT INTO MOBILE
VALUES
(
    'NOKIA',
    'NOKIA 800 C',
    9500
)

Data in the MODEL Table after executing the above query:


















But while writing the command using option 2 atmost care should be taken to make sure that values are in the same order as that of the columns in the table :

Following command wrongly inserts BRAND NAME as 'NOKIA 800 C' and MODEL as 'NOKIA'

INSERT INTO MOBILE
VALUES
(
    'NOKIA 800C',
    'NOKIA',
    9500
)




















So, Care should be taken in such a way that values should be in the same order as that of column names.

Summary:

This article provides information about using simple INSERT Query.

This entry was posted in . Bookmark the permalink.

Leave a reply