Insert Into Statement
Insert Into Statement
SQL (Structured Query Language) is a computer language aimed to store, manipulate, and query data
stored in relational databases. The first incarnation of SQL appeared in 1974, when a group in IBM
developed the first prototype of a relational database. The first commercial relational database was
released by Relational Software (later becoming Oracle).
Standards for SQL exist. However, the SQL that can be used on each one of the major RDBMS today is
in different flavors. This is due to two reasons: 1) the SQL command standard is fairly complex, and it is
not practical to implement the entire standard, and 2) each database vendor needs a way to differentiate its
product from others. In this tutorial, such differences are noted where appropriate.
This SQL programming help site lists commonly-used SQL statements, and is divided into the following
sections:
SQL Commands: Basic SQL statements for storing, retrieving, and manipulating data in a relational
database.
The INSERT INTO statement is used to add new records into a database table.
In SQL, there are basically two ways to INSERT data into a table: One is to insert it one row at a time,
the other is to insert multiple rows at a time. In this section, we'll take a look at the first case.
Syntax
The syntax for inserting data into a table one row at a time is as follows:
Examples
Table Store_Information
1
We want to insert one additional row into the table representing the sales data for Los Angeles on January
10, 1999. On that day, this store had $900 in sales, and the Manager_ID for this store is 10. We will use
the following SQL script:
Table Store_Information
Please note that we can specify the column names in any order -- the order does not have to be the same
as that of the table. For example, the following SQL statement is equivalent to the SQL statement above:
If we leave off the column names in the INSERT INTO statement, we will need to make sure that data is
inserted in the same column order as that in the table. For example,
will result in Store_Name being set to 900, Manager_ID being set to 'Los Angeles', and Sales being set to
10. Clearly this is not what we intend to accomplish.
In the first two examples, we insert a value for every column in the table. Sometimes, we may decide to
insert value into some of the columns and leave the rest of the columns blank. For those cases, we simply
specify the column names that we want to insert values into in our SQL statement. Below is an example:
2
Table Store_Information
In this case, the value for the Manager_ID column in the second row is NULL. NULL means that data
does not exist, and we discuss the concept of NULL later in this tutorial.
Update Statement
Syntax
UPDATE can be used to modify one column at a time or multiple columns at a time. The syntax for
updating a single column is as follows:
UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";
UPDATE "table_name"
SET column_1 = [value1], column_2 = [value2], ...
WHERE "condition";
Examples
Table Store_Information
We notice that the sales for Los Angeles on Jan-08-1999 is actually $500 instead of $300, and that
particular entry needs to be updated. To do so, we use the following SQL query:
3
UPDATE Store_Information
SET Sales = 500
WHERE Store_Name = 'Los Angeles'
AND Txn_Date = 'Jan-08-1999';
Table Store_Information
In this case, there is only one row that satisfies the condition in the WHERE clause. If there are multiple
rows that satisfy the condition, all of them will be modified. If no WHERE clause is specified, all rows
will be modified.
We notice that the 'San Diego' entry has the wrong Sales and TXN_Date information. To fix it, we run the
following SQL statement:
UPDATE Store_Information
SET Sales = 600, Txn_Date = 'Jan-15-1999'
WHERE Store_Name = 'San Diego';
Table Store_Information
IMPORTANT: When using the UPDATE statement, pay special attention to make sure that some type
of filtering criteria is specified. Otherwise, the value of all rows can be changed.
Exercises
4
1. Using the same Store_Information table right above, what data is in the table after the following SQL
statement is executed?
UPDATE Store_Information
SET Sales = 800
WHERE Store_Name = 'Boston';
2. Continuing to use the same table. What is the content of the table after the following SQL statement is
executed?
UPDATE Store_Information
SET Sales = 2000
WHERE Store_Name = 'Los Angeles' AND Txn_Date = 'Jan-10-1999';
3. Again using the same table. What is the content of the table after the following SQL statement is
executed?
UPDATE Store_Information
SET Sales = 1000;
The DELETE FROM statement in SQL is used to remove records from a table.
Please note that the DELETE FROM command cannot delete any rows of data that would
violate FOREIGN KEY or other constraints.
Syntax
The WHERE clause is important here. Without specifying a condition, all records from the table will be
deleted.
"Condition" can be simple (such as "Sales > 500") or complex (such as from the result of a subquery).
Examples
Two examples of how to use the DELETE FROM statement are shown below.
Table Store_Information
5
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999
We decide not to keep any information on Los Angeles in this table. To accomplish this, we type the
following SQL:
Table Store_Information
In Example 1, the criteria we use to determine which rows to delete is quite simple. We can also use a
more complex condition. Below is an example where we use a subquery as the condition. Assume we
have the following two tables:
Table Store_Information
Table Geography
Region_Name Store_Name
East Boston
East New York
West Los Angeles
6
West San Diego
We want to remove data for all stores in the East region from Store_Information (assuming that a store is
either in the East region or the West region—it cannot be in more than one region). We use the following
SQL statement to accomplish this:
If we leave out the WHERE clause in a DELETE FROM command, we will delete all rows from the
table. Most times, this is not what we intend to do. To prevent this, it is a best practice in database
management to always run the corresponding SELECT statement first to make sure the rows selected are
the ones we intend to remove from the table. This can be done by replacing "DELETE" with "SELECT
*".
Exercises
For the questions below, we use the following table as the starting point:
Table Clients
1. Which of the following SQL statements is valid? (There may be more than one answer)
a) DELETE * FROM Clients WHERE State = 'CO';
b) DELETE FROM Clients WHERE State = 'CO';
7
c) DELETE FROM Clients HAVING State = 'CO';
d) DELETE FROM Clients WHERE Customer_ID < 10;
2. How many rows are deleted after the following SQL statement is executed?
DELETE FROM Clients WHERE State = 'CO';
Select
The SELECT statement in SQL is used to retrieve data from a relational database.
Syntax
"table_name" is the name of the table where data is stored, and "column_name" is the name of the column
containing the data to be retrieved.
To select more than one column, add a comma to the name of the previous column, and then add the
column name. If you are selecting three columns, the syntax will be,
Examples
We will provide examples for each of the following three use cases:
Table Store_Information
8
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999
To select a single column, we specify the column name between SELECT and FROM as follows:
Result:
Store_Name
Los Angeles
San Diego
Los Angeles
Boston
We can use the SELECT statement to retrieve more than one column. To select Store_Name and Sales
columns from Store_Information, we use the following SQL:
Result:
Store_Name Sales
Los Angeles 1500
San Diego 250
Los Angeles 300
Boston 700
There are two ways to select all columns from a table. The first is to list the column name of each column.
The second, and the easier, way is to use the symbol *. For example, to select all columns
from Store_Information, we issue the following SQL:
Result:
9
Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999
Exercises
For these exercises, assume we have a table called Users with the following columns:
Table Users
Column Name
First_Name
Last_Name
Birth_Date
Gender
Date_Joined
1. Which of the following SQL statement is incorrect? (There can be more than one answer)
a) SELECT * FROM Users;
b) SELECT First_Name, Gender, Last_Name FROM Users;
c) SELECT First_Name, Last_Name Users;
d) SELECT All FROM Users;
2. (True Or False) In SQL, the order of the columns in a SELECT statement must be the same as the
order of the columns in the underlying table. For example, in the table Users, you must select First_Name
before Last_Name.
WHERE Clause
The WHERE clause is used to filter the result set based on the condition specified following the
word WHERE.
The WHERE clause can be used with the following types of SQL statements:
SELECT
UPDATE
DELETE
10
Syntax
SELECT "column_name"
FROM "table_name"
WHERE "condition";
UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";
"Condition" can include a single comparison clause (called simple condition) or multiple comparison
clauses combined together using AND or OR operators (compound condition).
Examples
We provide examples here to show how to use WHERE in the SELECT statement.
Table Store_Information
we key in,
SELECT Store_Name
FROM Store_Information
WHERE Sales > 1000;
Result:
11
Store_Name
Los Angeles
To view all data with sales greater than $1,000 or with transaction date of 'Jan-08-1999', we use the
following SQL,
SELECT *
FROM Store_Information
WHERE Sales > 1000 OR Txn_Date = 'Jan-08-1999';
Result:
As mentioned above, the WHERE clause can be used with UPDATE and DELETE statements in
addition to the SELECTstatement. Examples of how to use the WHERE clause with these two
commands can be seen in the UPDATE and DELETEsections.
Exercises
For these exercises, assume we have a table called Users with the following data:
Table Users
1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT * FROM Users WHERE Gender = 'M';
b) SELECT * WHERE Gender = 'M' FROM Users;
c) SELECT Gender= 'M' FROM Users;
d) SELECT Gender FROM Users WHERE Last_Name = 'Wilkes';
12
2. What's the result of the following query?
SELECT * FROM Users WHERE Join_Date = 'Apr-09-2015';
3. (True or False) The condition used in the WHERE clause must include a column that is part of the
SELECT clause.
Distinct
In SQL, the DISTINCT keyword is used in the SELECT statement to retrieve unique values from a
database table. Any value that has a duplicate will only show up once.
Syntax
"table_name" is the name of the table where data is stored, and "column_name" is the name of the column
containing the data to be retrieved.
Examples
Table Store_Information
Result:
Store_Name
Los Angeles
San Diego
Boston
Result:
Store_Name Txn_Date
Los Angeles Jan-05-1999
San Diego Jan-07-1999
Los Angeles Jan-08-1999
Boston Jan-08-1999
Exercises
For these exercises, assume we have a table called Users with the following data:
Table Users
And Or
The keywords AND and OR are Boolean operators used to specify compound conditions in
the WHERE clause.
Syntax
14
The syntax for using AND and OR in a compound condition is as follows:
SELECT "column_name"
FROM "table_name"
WHERE "simple condition"
{ [AND|OR] "simple condition"}+;
The { }+ means that the expression inside the bracket will occur one or more times. [AND|OR] means
that either AND or ORcan be used. In addition, we can use the parenthesis sign ( ) to indicate the order of
the condition.
Example
Table Store_Information
If we want to select all stores with sales greater than $1,000 or all stores with sales less than $500 but
greater than $275 in Table Store_Information, we key in,
SELECT Store_Name
FROM Store_Information
WHERE Sales > 1000
OR (Sales < 500 AND Sales > 275);
Result:
Store_Name
Los Angeles
San Francisco
Exercises
For these exercises, assume we have a table called Users with the following data:
Table Users
15
Sophie Lee Jan-05-1960 F Apr-05-2015
Richard Brown Jan-07-1975 M Apr-05-2015
Jamal Santo Oct-08-1983 M Apr-09-2015
Casey Healy Sep-20-1969 M Apr-09-2015
Jill Wilkes Nov-20-1979 F Apr-15-2015
1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT First_Name AND Last_Name FROM Users;
b) SELECT First_Name, Last_Name FROM Users WHERE Join_Date > 'Apr-01-2015' AND Birth_Date
< 'Jan-01-1980';
c) SELECT First_Name OR User_Name FROM Users;
d) SELECT * FROM Users WHERE Last_Name = 'Brown' AND Gender = 'F';
In
The IN operator in SQL filters the result set based on a list of discrete values. The list of discrete values
can be simply be listed out or is provided by a separate SELECT statement (this is called a subquery).
Syntax
Below is the syntax for the IN operator when the possible values are listed out directly.
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ('value1', 'value2', ...);
The number of values in the parenthesis can be one or more, with each values separated by comma.
Values can be numerical or string characters. If there is only one value inside the parenthesis, this
commend is equivalent to,
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IN ( [SELECT STATEMENT] );
16
Please note that the IN operator cannot be used if the filtering criteria is a continuous range. For example,
if we are looking for any value that is between 0 and 1, we cannot use the IN operator because it is not
possible to list every possible value between 0 and 1.
Example
Table Store_Information
To select all records for the Los Angeles and the San Diego stores in Table Store_Information, we key
in,
SELECT *
FROM Store_Information
WHERE Store_Name IN ('Los Angeles', 'San Diego');
Result:
For an example of the IN operator used in conjunction with a separate SELECT statement, please see
the Subquery section.
Exercises
For these exercises, assume we have a table called Users with the following data:
Table Users
1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT Gender FROM Users IN ('M');
b) SELECT * FROM Users HAVING Gender IN ('M','F');
c) SELECT First_Name, Last_Name FROM Users WHERE Gender IN ('M','F');
d) SELECT DISTINCT First_Name, Last_Name WHERE Gender IN ('M','F');
Between
The BETWEEN operator is used when the filtering criteria is a continuous range with a maximum value
and a minimum value. It is always used in the WHERE clause.
Syntax
SELECT "column_name"
FROM "table_name"
WHERE "column_name" BETWEEN 'value1' AND 'value2';
This will select all rows whose column has a value between 'value1' and 'value2.'
Examples
Table Store_Information
Example 1
To select view all sales information between January 6, 1999, and January 10, 1999, we key in,
18
SELECT *
FROM Store_Information
WHERE Txn_Date BETWEEN 'Jan-06-1999' AND 'Jan-10-1999';
Note that date may be stored in different formats in different databases. This tutorial simply choose one of
the formats.
Result:
BETWEEN is an inclusive operator, meaning that 'value1' and 'value2' are included in the result. If we
wish to exclude 'value1' and 'value2' but include everything in between, we need to change the query to
the following:
SELECT "column_name"
FROM "table_name"
WHERE ("column_name" > 'value1')
AND ("column_name" < 'value2');
Example 2
We can also use the BETWEEN operator to exclude a range of values by adding NOT in front
of BETWEEN. In the above example, if we want to show all rows where the Sales column is not
between 280 and 1000, we will use the following SQL:
SELECT *
FROM Store_Information
WHERE Sales NOT BETWEEN 280 and 1000;
Result:
Exercises
For these exercises, assume we have a table called User_Sales with the following data:
Table User_Sales
19
Sophie Lee Jan-05-1960 F Apr-05-2015 500
Richard Brown Jan-07-1975 M Apr-05-2015 200
Jamal Santo Oct-08-1983 M Apr-09-2015 350
Casey Healy Sep-20-1969 M Apr-09-2015 80
Jill Wilkes Nov-20-1979 F Apr-15-2015 210
1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT * FROM User_Sales WHERE Total_Sales BETWEEN 200 OR 300;
b) SELECT * FROM User_Sales WHERE Total_Sales IS BETWEEN 200 OR 300;
c) SELECT * FROM User_Sales WHERE Total_Sales IS BETWEEN 200 AND 300;
d) SELECT * FROM User_Sales WHERE Total_Sales BETWEEN 200 AND 300;
Like
The LIKE operator is used to filter the result set based on a string pattern. It is always used in
the WHERE clause.
Syntax
SELECT "column_name"
FROM "table_name"
WHERE "column_name" LIKE {PATTERN};
{PATTERN} often consists of wildcards. We saw several examples of wildcard matching in the previous
section.
Example
Table Store_Information
20
SAN FRANCISCO 300 Jan-08-1999
BOSTON 700 Jan-08-1999
We want to find all stores whose name contains 'AN'. To do so, we key in,
SELECT *
FROM Store_Information
WHERE Store_Name LIKE '%AN%';
Result:
The "%" sign before 'AN' means that there may be 0, 1, or more characters before the pattern 'AN.' The
"%" sign after 'AN' means that there may be 0, 1, or more characters after the pattern 'AN.' Out of the four
store names, 'LOS ANGELES,' 'SAN DIEGO,' and 'SAN FRANCISCO' all contain this pattern.
Exercises
For these exercises, assume we have a table called User_Sales with the following data:
Table User_Sales
1) 1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT First_Name, Last_Name FROM User_Sales WHERE First_Name LIKE 'A%' Last_Name
LIKE 'W%';
b) SELECT First_Name, Last_Name FROM User_Sales WHERE First_Name LIKE 'J%' AND
Last_Name LIKE 'W%';
c) SELECT First_Name, Last_Name FROM User_Sales First_Name LIKE 'J%' AND Last_Name LIKE
'W%';
d) SELECT First_Name, Last_Name FROM User_Sales WHERE First_Name LIKE 'J%', Last_Name
LIKE 'W%';
21
2. How many records will be returned by the following query? (Assuming the database is configured to
be case-insensitive)
SELECT * FROM User_Sales WHERE Last_Name LIKE '%l_e%';
3. How many records will be returned by the following query? (Assuming the database is configured to
be case-insensitive)
SELECT * FROM User_Sales WHERE First_Name LIKE '%a%' OR Last_Name LIKE '%e%';
Order By
The ORDER BY command in SQL sorts the result set in either ascending or descending order. ORDER
BY usually appears last in a SQL statement because it is performed after the result set has been retrieved.
Syntax
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
ORDER BY "column_name" [ASC, DESC];
The [ ] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes
before the ORDER BYclause. ASC means that the results will be shown in ascending order,
and DESC means that the results will be shown in descending order. If neither is specified, the default
is ASC.
It is possible to order by more than one column. In this case, the ORDER BY clause above becomes
Assuming that we choose ascending order for both columns, the output will be ordered in ascending order
according to column 1. If there is a tie for the value of column 1, we then sort in ascending order by
column 2.
Examples
Table Store_Information
22
Boston 700 Jan-08-1999
To list the contents of Table Store_Information by Sales in descending order, we key in,
Result:
In addition to column name, we may also use column position (based on the SQL query) to indicate
which column we want to apply the ORDER BY clause. The first column is 1, second column is 2, and
so on. In the above example, we will achieve the same results by the following command:
Example 3: ORDER BY a single column using a column not in the SELECT statement
The column(s) we use to sort the result do not need to be in the SELECT clause. For example, the
following SQL,
SELECT Store_Name
FROM Store_Information
ORDER BY Sales DESC;
Store_Name
Los Angeles
Boston
San Francisco
San Diego
Table Product_Sales
we can use the SQL statement below to order the results by Revenue (defined as Price * Units):
Result:
Product_ID Revenue
1 90
3 75
2 60
Exercises
For these exercises, assume we have a table called User_Sales with the following data:
Table User_Sales
1. Which of the following SQL statement is valid? (There can be more than one answer)
a) SELECT * FROM User_Sales ORDER BY Sales;
b) SELECT * FROM User_Sales ORDER BY Last_Name DESC;
c) SELECT * FROM User_Sales ORDER BY First_Name WHERE Sales > 100;
d) SELECT * FROM User_Sales ORDER BY Last_Name, First_Name;
24
2. What is the result of the following query?
SELECT * FROM User_Sales WHERE Join_Date IN ('Apr-05-2015','Apr-15-2015') ORDER BY Sales;
Group By
The GROUP BY clause is used to tell SQL what level of granularity the aggregate function should be
calculated in. The level of granularity is represented by the columns in the SELECT statement that are
not aggregate functions.
Syntax
More than one column can be specified in the GROUP BY clause, and more than one function can be
included.
GROUP BY is the command that can trip up many beginners, as it is often possible to have a SQL
statement with the correct GROUP BY syntax, yet get the wrong results. A good rule of thumb when
using GROUP BY is to include all the non-aggregate function columns in the SELECT statement in
the GROUP BY clause.
Examples
Table Store_Information
We want to find total sales for each store. To do so, we would key in,
25
SELECT Store_Name, SUM(Sales)
FROM Store_Information
GROUP BY Store_Name;
Result:
Store_Name SUM(Sales)
Los Angeles 2300
San Diego 250
Boston 700
In Example 1, there is only one column associated with GROUP BY. It is possible to have two or more
columns associated with GROUP BY.
We want to find total sales for each product at each store. To do so, we would key in,
Result:
We want to find total sales and the average sales for each product at each store. To do so, we would key
in,
Result:
26
Example 4: Group by month / date / week
A common use of the GROUP BY function is on a time period, which can be month, week, day, or even
hour. This type of query is often combined with the ORDER BY keyword to provide a query result that
shows a time series.
For example, to find total daily sales from Store_Information, we use the following SQL:
Result:
Txn_Date SUM(Sales)
Jan-05-1999 2000
Jan-07-1999 250
Jan-08-1999 1000
Exercises
For these exercises, assume we have a table called Region_Sales with the following data:
Table Region_Sales
2. Write a SQL statement that calculates the total dollar sales amount for each region. What is the result?
27
3. Write a SQL statement that calculates the average annual dollar sales amount for just the East region
and the West region. What is the result?
Having
The HAVING clause is used to filter the result set based on the result of an aggregate function. It is
typically located near or at the end of the SQL statement.
HAVING is often coupled with the presence of the GROUP BY clause, although it is possible to have
a HAVING clause without the GROUP BY clause.
Syntax
The brackets around "column_name1" and GROUP BY "column_name1" means that they are optional.
Note: We may select zero, one, or more columns in addition to the aggregate function. If we do select any
column outside of the aggregate function, there is no need for the GROUP BY clause.
Example
Table Store_Information
To see only the stores with sales over $1,500, we would type,
Result:
28
Store_Name SUM(Sales)
Los Angeles 1800
Total sales for both San Diego and Boston are below $1,500, so the "HAVING SUM(Sales) > 1500"
clause filters out these two stores.
Exercises
For these exercises, assume we have a table called Region_Sales with the following data:
Table Region_Sales
29