MySQL Tutorial

The INSERT statement

The insert statement is used to insert records into a table. The keywords used in an insert statement are summarised in the following table.

Keyword Description
INSERT Inserts data into a table
INTO Specifies the name of the table to insert the data
VALUES The data for the fields in the table

The following example inserts two records into the search table.

insert.sql

INSERT INTO search (Category,
        Page,
        Directory,
        LinkName,
        Keywords,
        Description)
    VALUES ('ASP',
        'cookies.html',
        'http://www.juicystudio.com/tutorial/asp/',
        'Reading Cookies',
        'request,cookies,key,subkey,domain',
        'Using the Request object to read cookies in ASP');

INSERT INTO search (Category,
        Page,
        Directory,
        LinkName,
        Keywords,
        Description)
    VALUES ('PHP',
        'cookies.html',
        'http://www.juicystudio.com/tutorial/php/',
        'Using Cookies',
        'cookies,setting,retrieving,reading,setcookie,isset',
        'Using cookies in PHP');

The file may then be used with MySQL as follows:

mysql> \. insert.sql

If a field in your table allows NULL values, you may omit the field from the INSERT statement.

Characters that require Escaping

The following characters have a special meaning to MySQL, and will need to be escaped by putting a backslash before them in order that they are interpreted correctly.

Characters Name
' Single quote
" Double quote
\ Blackslash
% Percent
_ Underscore

The following example shows how you would escape an underscore in the string, "last_modified".

'last\_modified'

You can escape single quotes by placing two single quotes together, as in the following example.

'Don''t care!'

You might also like...

Comments

About the author

Gez Lemon United Kingdom

I'm available for contract work. Please visit Juicify for details.

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous