0% found this document useful (0 votes)
4 views

Insert Into Statement

The document provides an overview of SQL (Structured Query Language), including its history, standards, and various commands such as INSERT, UPDATE, DELETE, and SELECT. It explains the syntax and usage of these commands with examples, highlighting the importance of the WHERE clause to filter results. Additionally, it includes exercises to reinforce understanding of SQL operations.

Uploaded by

hiti protogene
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Insert Into Statement

The document provides an overview of SQL (Structured Query Language), including its history, standards, and various commands such as INSERT, UPDATE, DELETE, and SELECT. It explains the syntax and usage of these commands with examples, highlighting the importance of the WHERE clause to filter results. Additionally, it includes exercises to reinforce understanding of SQL operations.

Uploaded by

hiti protogene
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 29

DATA DRIVEN APPLICATION

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.

Insert Into Statement

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:

INSERT INTO "table_name" ("column1", "column2", ...)


VALUES ("value1", "value2", ...);

Examples

The examples refer to a table that has the following structure,

Table Store_Information

Column Name Data Type


Store_Name char(50)
Manager_ID integer
Sales float
Txn_Date datetime

Example 1: All column names are specified

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:

INSERT INTO Store_Information (Store_Name, Manager_ID, Sales, Txn_Date)


VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

Now the table will hold the following data:

Table Store_Information

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999

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:

INSERT INTO Store_Information (Sales, Store_Name, Manager_ID, Txn_Date)


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');

Example 2: None of the column names are specified

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,

INSERT INTO Store_Information


VALUES ('Los Angeles', 10, 900, 'Jan-10-1999');

will give us the desired result, while

INSERT INTO Store_Information


VALUES (900, 'Los Angeles', 10, 'Jan-10-1999');

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.

Example 3: Some of the column names are specified

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:

INSERT INTO Store_Information (Store_Name, Sales, Txn_Date)


VALUES ('New York', 500, 'Jan-10-1999');

Now the table becomes:

2
Table Store_Information

Store_Name Manager_ID Sales Txn_Date


Los Angeles 10 900 Jan-10-1999
New York 500 Jan-10-1999

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

The UPDATE statement is used to modify data in a database table.

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";

The syntax for updating multiple columns is as follows:

UPDATE "table_name"
SET column_1 = [value1], column_2 = [value2], ...
WHERE "condition";

Examples

We use the following table for our examples.

Table Store_Information

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

Example 1: Update a single column

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';

The resulting table would look like

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 500 Jan-08-1999
Boston 700 Jan-08-1999

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.

Example 2: Update multiple columns

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';

The table now becomes,

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 600 Jan-15-1999
Los Angeles 500 Jan-08-1999
Boston 700 Jan-08-1999

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;

Delete From Statement

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 syntax for the DELETE FROM statement is as follows:

DELETE FROM "table_name"


WHERE "condition";

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.

Example 1: DELETE FROM using a simple condition

We use the following table as the starting point.

Table Store_Information

Store_Name Sales Txn_Date

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:

DELETE FROM Store_Information


WHERE Store_Name = 'Los Angeles';

Now the table becomes,

Table Store_Information

Store_Name Sales Txn_Date


San Diego 250 Jan-07-1999
Boston 700 Jan-08-1999

Example 2: DELETE FROM using the results from a subquery

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

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

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:

DELETE FROM Store_Information


WHERE Store_Name IN
(SELECT Store_Name FROM Geography
WHERE Region_Name = 'East');

Upon execution, the Store_Information table becomes,

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999

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

Customer_ID Last_Name First_Name City Stat e Join_Date


2 Larry Kerr Seattle WA Oct-15-2001
5 Aaron Wallace Denver CO Oct-18-2001
6 Jayson Fortran Raleigh NC Oct-24- 2001
12 Jill Dobbs Buffalo NY Nov-15-2001
13 Lisa Yamaguchi San Diego CA Nov-15- 2001
20 Ally Smith Seattle WA Nov-25-2001
67 Teyu Lee Cupertino CA Jan-11-2002

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';

3. What is the effect of the following SQL?


DELETE FROM Clients WHERE 1 = 1;

Select

The SELECT statement in SQL is used to retrieve data from a relational database.

Syntax

Number of Columns SQL Syntax

1 SELECT "column_name" FROM "table_name";

More Than 1 SELECT "column_name1"[, "column_name2"] FROM "table_name";

All SELECT * FROM "table_name";

"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,

SELECT "column_name1", "column_name2", "column_name3" FROM "table_name";

Note there is no comma after the last column selected.

Examples

We will provide examples for each of the following three use cases:

 Retrieve one column


 Retrieve multiple columns

 Retrieve all columns

Let's use the following table to illustrate all three cases:

Table Store_Information

Store_Name Sales Txn_Date

8
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Example 1: Select one column

To select a single column, we specify the column name between SELECT and FROM as follows:

SELECT Store_Name FROM Store_Information;

Result:

Store_Name
Los Angeles
San Diego
Los Angeles
Boston

Example 2: Select multiple columns

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:

SELECT Store_Name, Sales FROM Store_Information;

Result:

Store_Name Sales
Los Angeles 1500
San Diego 250
Los Angeles 300
Boston 700

Example 3: Select all columns

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:

SELECT * FROM Store_Information;

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.

3. (True Or False) The following two SQL statements are equivalent:


a) Select * From Users;
b) SELECT * FROM Users;

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

The syntax for using WHERE in the SELECT statement is as follows:

SELECT "column_name"
FROM "table_name"
WHERE "condition";

The syntax for using WHERE in the UPDATE statement is as follows:

UPDATE "table_name"
SET "column_1" = [new value]
WHERE "condition";

The syntax for using WHERE in the DELETE statement is as follows:

DELETE FROM "table_name"


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.

Example 1: WHERE Clause With Simple Condition

To select all stores with sales above $1,000 in Table Store_Information,

Table Store_Information

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

we key in,

SELECT Store_Name
FROM Store_Information
WHERE Sales > 1000;

Result:

11
Store_Name
Los Angeles

Example 2: WHERE Clause With OR Operator

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:

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999

Using WHERE With UPDATE and DELETE

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

First_Name Last_Name Birth_Date Gender Join_Date


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 * 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

SELECT DISTINCT "column_name"


FROM "table_name";

"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

The examples will use the following table:

Table Store_Information

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

Example 1: Use DISTINCT on one column

To select all distinct stores in Table Store_Information, we key in,

SELECT DISTINCT Store_Name FROM Store_Information;

Result:

Store_Name
Los Angeles
San Diego
Boston

Example 2: Use DISTINCT on multiple columns


13
We can apply DISTINCT to multiple columns. If we want to get a list showing all unique combinations
of stores and transaction dates, we would type in the following,

SELECT DISTINCT Store_Name, Txn_Date FROM Store_Information;

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

First_Name Last_Name Birth_Date Gender Join_Date


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?


a) SELECT DISTINCT * FROM Users;
b) SELECT DISTINCT First_Name FROM Users;
c) SELECT DISTINCT First_Name Last_Name FROM Users;

2. What's the result of the following query?


SELECT DISTINCT Join_Date From Users;

3. What's the result of the following query?


SELECT DISTINCT Gender, Join_Date From 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

We use the following table as our example:

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999
Boston 700 Jan-08-1999

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

First_Name Last_Name Birth_Date Gender Join_Date

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';

2. How many records will be returned by the following query?


SELECT * FROM Users WHERE Gender = 'M' AND Join_Date = 'Apr-09-2015';

3. How many records will be returned by the following query?


SELECT * FROM Users WHERE Gender = 'M' OR Join_Date = 'Apr-05-2015';

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).

The IN operator is always used with the WHERE clause.

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,

WHERE "column_name" = 'value1'

The syntax for the IN operator in a subquery construct is as follows:

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

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999
Boston 700 Jan-08-1999

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:

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999

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

First_Name Last_Name Birth_Date Gender Join_Date


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
17
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 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');

2. How many records will be returned by the following query?


SELECT * FROM Users WHERE Join_Date IN ('Apr-05-2015','Apr-15-2015');

3. How many records will be returned by the following query?


SELET * FROM Users WHERE Gender IN ('M') AND Join_Date = 'Apr-15-2015');

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

The syntax for the BETWEEN operator is as follows:

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

We use the following table for our examples.

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999
Boston 700 Jan-08-1999

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:

Store_Name Sales Txn_Date


San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999
Boston 700 Jan-08-1999

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:

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999

Exercises

For these exercises, assume we have a table called User_Sales with the following data:

Table User_Sales

First_Name Last_Name Birth_Date Gender Joi n_Date Total_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;

2. How many records will be returned by the following query?


SELECT * FROM User_Sales WHERE Join_Date BETWEEN 'Apr-05-2015' AND 'Apr-10-2015';

3. How many records will be returned by the following query?


SELECT * FROM User_Sales WHERE Gender = 'F' OR Total_Sales BETWEEN 50 AND 100;

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

The syntax for the LIKE operator is as follows:

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

We use the following table for our example.

Table Store_Information

Store_Name Sales Txn_Date


LOS ANGELES 1500 Jan-05-1999
SAN DIEGO 250 Jan-07-1999

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:

Store_Name Sales Txn_Date


LOS ANGELES 1500 Jan-05-1999
SAN DIEGO 250 Jan-07-1999
SAN FRANCISCO 300 Jan-08-1999

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

First_Name Last_Name Birth_Date Gender Joi n_Date Total_Sales


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) 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

The syntax for an ORDER BY statement is as follows:

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

ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]

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

We use the following table for Examples 1-3.

Table Store_Information

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
San Francisco 300 Jan-08-1999

22
Boston 700 Jan-08-1999

Example 1: ORDER BY a single column using column name

To list the contents of Table Store_Information by Sales in descending order, we key in,

SELECT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY Sales DESC;

Result:

Store_Name Sales Txn_Date


Los Angeles 1500 Jan-05-1999
Boston 700 Jan-08-1999
San Francisco 300 Jan-08-1999
San Diego 250 Jan-07-1999

Example 2: ORDER BY a single column using column position

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:

SELECT Store_Name, Sales, Txn_Date


FROM Store_Information
ORDER BY 2 DESC;

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;

works fine and will give the following result:

Store_Name
Los Angeles
Boston
San Francisco
San Diego

Example 4: ORDER BY an expression


23
It is also possible to sort the result by an expression. For example, in the following table,

Table Product_Sales

Product_ID Price Units


1 10 9
2 15 4
3 25 3

we can use the SQL statement below to order the results by Revenue (defined as Price * Units):

SELECT Product_ID, Price*Units Revenue


FROM Product_Sales
ORDER BY Price*Units DESC;

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

First_Name Last_Name Gender Join_Date Sales


Sophie Lee F Apr-05-2015 500
Richard Brown M Apr-05-2015 200
Jamal Santo M Apr-09-2015 350
Casey Healy M Apr-09-2015 80
Jill Wilkes 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 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;

3. What is the result of the following query?


SELECT * FROM User_Sales ORDER BY Join_Date DESC, 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

The syntax for GROUP BY is,

SELECT "column_name1", "function type" ("column_name2")


FROM "table_name"
GROUP BY "column_name1";

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

We use the following table for our examples.

Table Store_Information

Store_Name Product_ID Sales Txn_Date


Los Angeles 1 1500 Jan-05-1999
Los Angeles 2 500 Jan-05-1999
San Diego 1 250 Jan-07-1999
Los Angeles 1 300 Jan-08-1999
Boston 1 700 Jan-08-1999

Example 1: GROUP BY a single column

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

Example 2: GROUP BY multiple columns

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,

SELECT Store_Name, Product_ID, SUM(Sales)


FROM Store_Information
GROUP BY Store_Name, Product_ID;

Result:

Store_Name Product_ID SUM(Sales)


Los Angeles 1 1800
Los Angeles 2 500
San Diego 1 250
Boston 1 700

Example 3: GROUP BY multiple columns and multiple functions

We want to find total sales and the average sales for each product at each store. To do so, we would key
in,

SELECT Store_Name, Product_ID, SUM(Sales), AVG(Sales)


FROM Store_Information
GROUP BY Store_Name, Product_ID;

Result:

Store_Name Product_ID SUM(Sales) AVG(Sales)


Los Angeles 1 1800 900
Los Angeles 2 500 500
San Diego 1 250 250
Boston 1 700 700

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:

SELECT Txn_Date, SUM(Sales)


FROM Store_Information
GROUP BY Txn_Date
ORDER BY Txn_Date;

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

Region Year Orders Total_Sales


West 2013 1560 325000
West 2014 1820 380000
North 2013 790 148000
North 2014 995 185000
East 2013 1760 375000
East 2014 2220 450000
South 2013 1790 388000
South 2014 1695 360000

1. Which of the following order is correct for a SQL statement?


a) SELECT...FROM...WHERE...GROUP BY...ORDER BY
b) SELECT...FROM...ORDER BY...WHERE...GROUP BY
c) SELECT...FROM...WHERE...ORDER BY...GROUP BY
d) SELECT...WHERE...FROM...GROUP BY...ORDER BY

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 syntax for HAVING is,

SELECT ["column_name1"], "function type" ("column_name2")


FROM "table_name"
[GROUP BY "column_name1"]
HAVING (arithmetic function condition);

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

We use the following table for our example.

Table Store_Information

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

To see only the stores with sales over $1,500, we would type,

SELECT Store_Name, SUM(Sales)


FROM Store_Information
GROUP BY Store_Name
HAVING SUM(Sales) > 1500;

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

Region Year Orders Total_Sales


West 2013 1560 325000
West 2014 1820 380000
North 2013 790 148000
North 2014 995 185000
East 2013 1760 375000
East 2014 2220 450000
South 2013 1790 388000
South 2014 1695 360000

1. Which of the following order is correct for a SQL statement?


a) SELECT...FROM...ORDER BY...WHERE...HAVING
b) SELECT...FROM...WHERE...ORDER BY...HAVING
c) SELECT...WHERE...FROM...HAVING...ORDER BY
d) SELECT...FROM...WHERE...HAVING...ORDER BY

2. What is the result of the following SQL statement?


SELECT Region, SUM(Orders) FROM Region_Sales GROUP BY Region HAVING SUM(Orders) >
2500;

3. What is the result of the following SQL statement?


SELECT Region, SUM(Orders) FROM Region_Sales WHERE Total_Sales < 385000 GROUP BY
Region HAVING SUM(Orders) > 2500;

29

You might also like