You are on page 1of 78

SQL - Structured Query Language

Table of Contents
Introduction.................................................................................................................................................... 4
What is SQL? ............................................................................................................................................ 4
What Can SQL do? ................................................................................................................................... 4
SQL is a Standard - BUT.... ...................................................................................................................... 4
Using SQL in Your Web Site ..................................................................................................................... 4
RDBMS ..................................................................................................................................................... 4
SQL Syntax ................................................................................................................................................... 5
SQL Statements ........................................................................................................................................ 5
Semicolon after SQL Statements? ............................................................................................................ 5
SQL DML and DDL ................................................................................................................................... 5
SQL Commands ............................................................................................................................................ 6
Select ........................................................................................................................................................ 6
DISTINCT .................................................................................................................................................. 7
WHERE ..................................................................................................................................................... 8
Quotes around Text Fields .................................................................................................................... 8
Operators Allowed in the WHERE Clause ............................................................................................ 8
SQL AND & OR Operators........................................................................................................................ 9
SQL IN Clause ........................................................................................................................................ 10
SQL BETWEEN Operator ....................................................................................................................... 11
SQL Wildcards ........................................................................................................................................ 13
Using the % Wildcard .......................................................................................................................... 13
Using the _ Wildcard ........................................................................................................................... 14
Using the [charlist] Wildcard ................................................................................................................ 14
SQL LIKE Operator ................................................................................................................................. 15
SQL ORDER BY ..................................................................................................................................... 16
SQL Aggregate Functions: ...................................................................................................................... 18
Average Function avg(): ...................................................................................................................... 18
Count Function count(): ....................................................................................................................... 20
SQL MAX() Function ........................................................................................................................... 21
SQL MIN() Function ............................................................................................................................ 21
SQL SUM() Function ........................................................................................................................... 22
SQL GROUP BY Statement.................................................................................................................... 23
GROUP BY More Than One Column ................................................................................................. 24
The HAVING Clause ............................................................................................................................... 25
SQL Alias ................................................................................................................................................ 26
SQL Joins ................................................................................................................................................ 28
SQL INNER JOIN ................................................................................................................................ 29
SQL LEFT JOIN .................................................................................................................................. 30
SQL RIGHT JOIN ................................................................................................................................ 31
SQL FULL JOIN .................................................................................................................................. 32
String Concatenate ................................................................................................................................. 33
SQL Substring ......................................................................................................................................... 34
SQL TRIM ............................................................................................................................................... 35
SQL Length ............................................................................................................................................. 36
SQL REPLACE ....................................................................................................................................... 37
SQL DATE............................................................................................................................................... 38
Table Manipulation ...................................................................................................................................... 39
SQL CREATE TABLE ............................................................................................................................. 39
SQL CONSTRAINTS .............................................................................................................................. 40
NOT NULL Constraint ......................................................................................................................... 40
DEFAULT Constraint .......................................................................................................................... 40
UNIQUE Constraint: ............................................................................................................................ 41
CHECK Constraint: ............................................................................................................................. 41
PRIMARY KEY Constraint .................................................................................................................. 42
FOREIGN KEY Constraint .................................................................................................................. 43
SQL VIEW ............................................................................................................................................... 44
CREATE VIEW.................................................................................................................................... 44
SQL INDEXES ........................................................................................................................................ 46
CREATE INDEX .................................................................................................................................. 47
ALTER Table ........................................................................................................................................... 48
ALTER Table ADD Column................................................................................................................. 49
ALTER TABLE MODIFY Column ........................................................................................................ 50
ALTER Table RENAME Column ......................................................................................................... 51
Alter Table Drop Column..................................................................................................................... 52
Alter Table Add Index .......................................................................................................................... 52
Alter Table Drop Index ........................................................................................................................ 53
Alter Table Add Constraint .................................................................................................................. 53
Alter Table Drop Constraint ................................................................................................................. 53
DROP Table ............................................................................................................................................ 54
Truncate Table ........................................................................................................................................ 54
SQL USE: ................................................................................................................................................ 55
SQL Insert Into ........................................................................................................................................ 56
SQL Update: ........................................................................................................................................... 57
SQL DELETE FROM .............................................................................................................................. 59
Advanced SQL ............................................................................................................................................ 60
SQL UNION............................................................................................................................................. 60
SQL UNION ALL ..................................................................................................................................... 61
SQL INTERSECT .................................................................................................................................... 62
SQL MINUS............................................................................................................................................. 63
SQL LIMIT ............................................................................................................................................... 64
SQL TOP ................................................................................................................................................. 65
SQL SUB QUERIES ............................................................................................................................... 66
Correlated Query: ................................................................................................................................ 66
SQL EXISTS ........................................................................................................................................... 67
SQL CASE .............................................................................................................................................. 68
SQL NULL ............................................................................................................................................... 69
SQL ISNULL ........................................................................................................................................... 70
SQL IFNULL ............................................................................................................................................ 71
SQL NVL ................................................................................................................................................. 71
SQL COALESCE: ................................................................................................................................... 72
SQL NULLIF ............................................................................................................................................ 73
SQL Rank ................................................................................................................................................ 74
SQL Median ............................................................................................................................................ 75
SQL Running Totals ................................................................................................................................ 76
SQL Percent to Total ............................................................................................................................... 77
SQL Cumulative Percent to Total ........................................................................................................... 78
Introduction
In this tutorial you will get to know about the basic and intermediate SQL commands focusing
more from a testing perspective.
At the end of this training session you will be able to write basic to intermediate complex queries to help
data testing for your application or project.

What is SQL?
SQL stands for Structured Query Language.
SQL is a standard language for accessing and manipulating databases.
SQL is an ANSI (American National Standards Institute) standard.

What Can SQL do?


SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....


Although SQL is ANSI standard, 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.

Using SQL in Your Web Site


To build a web site that shows some data from a database, you will need the following:
An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
A server-side scripting language, like PHP or ASP
SQL
HTML / CSS

RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and
for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables. A table is a collection of related
data entries and it consists of columns and rows. The database table columns (called also table fields)
have their own unique names and have a pre-defined data types. Table columns can have various
attributes defining the column functionality (the column is a primary key, there is an index defined on the
column, the column has certain default value, etc.).
While table columns describe the data types, the table rows contain the actual data for the columns.
SQL Syntax
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.
SQL is not case sensitive

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement. Semicolon is the
standard way to separate each SQL statement in database systems that allow more than one SQL
statement to be executed in the same call to the server.
We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after
each SQL statement, but some database programs force you to use it.

SQL DML and DDL


SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition
Language (DDL).

The query and update commands form the DML part of SQL:
 SELECT - extracts data from a database
 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys),
specify links between tables, and impose constraints between tables.

The most important DDL statements in SQL are:


 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
SQL Commands
In this section, we discuss the following SQL commands, which are frequently used in SQL
queries. By the end of this section, you will learn the basics of retrieving data from the database using
SQL.

Select
The SQL SELECT statement is used to select data from a SQL database table. This is usually
the very first SQL command every SQL newbie learns and this is because the SELECT SQL statement is
one of the most used SQL commands.

Syntax:
SELECT Column1, Column2, Column3 FROM Table1

The list of column names after the SQL SELECT command determines which columns you want
to be returned in your result set. If you want to select all columns from a database table, you can use the
following SQL statement: SELECT * FROM Table1
When the list of columns following the SELECT SQL command is replaced with asterix (*) all
table columns are returned. Word of caution here, it‟s always better to explicitly specify the columns in the
SELECT list, as this will improve your query performance significantly.
The table name following the SQL FROM keyword (in our case Table1) tells the SQL interpreter which
table to use to retrieve the data.

Example:
Table Structure and Data: Store_Information
Store_id Store_name Sales Date
St_01 Best Buy $300,000 Jan-05-2010
St_02 WalMart $780,890 Jan-05-2010
St_02 Sams Club $240,675 Jan-05-2010

Query 1:
SELECT Store_name FROM Store_Information

Result:
Store_name
Best Buy
WalMart
Sams Club
Query 2:
SELECT * FROM Store_Information

Result:
Store_id Store_name Sales Date
St_01 Best Buy $300,000 Jan-05-2010
St_02 WalMart $780,890 Jan-05-2010
St_02 Sams Club $240,675 Jan-05-2010
DISTINCT
The SELECT keyword allows us to grab all information from a column (or columns) on a table.
This, of course, necessarily means that there will be redundancies. What if we only want to select each
DISTINCT element? This is easy to accomplish in SQL. All we need to do is to add DISTINCT after
SELECT.

Syntax:
SELECT DISTINCT "column_name" FROM "table_name"

Example:
Table Structure and Data: Store_Information
Store_id Store_name Sales Date
St_01 Best Buy $300,000.00 Jan-05-2010
St_02 WalMart $780,890.00 Jan-05-2010
St_03 Sams Club $240,675.00 Jan-05-2010
St_01 Best Buy $350.00 Jan-05-2010
St_01 Best Buy $4567.00 Jan-05-2010
St_03 Sams Club $240,675.00 Jan-05-2010

Query 1:
SELECT DISTINCT store_name FROM Store_Information

Result:
Store_name
Best Buy
WalMart
Sams Club
WHERE
The SQL WHERE clause is used to select data conditionally, by adding it to already existing SQL
SELECT query. In other words, the WHERE clause is used to extract only those records that fulfill a
specified criterion.

Syntax:
SELECT column_name(s) FROM table_name WHERE column_name operator value

Example:
Table Structure and Data: Customers
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
Steven Goldfish goldfish@fishhere.net 4/4/1974 323-455-4545
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623

Query 1:
SELECT * FROM Customers WHERE Last Name=‟Smith‟

Result:
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623

Quotes around Text Fields


SQL uses single quotes around text values (most database systems will also accept double quotes).
Numeric values should not be enclosed in quotes.

For text values:


This is correct: SELECT * FROM Customers WHERE Last Name='Smith'
This is wrong: SELECT * FROM Customers WHERE Last Name=Smith
For numeric values:
This is correct: SELECT * FROM Persons WHERE Year=1965
This is wrong: SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause


Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one of the columns
Note: In some SQL version the operator „<>‟ (Not equal) may be written as „!=‟.
SQL AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition. The AND
operator displays a record if both the first condition and the second condition is true. The OR operator
displays a record if either the first condition or the second condition is true.
The AND & OR operators can be used alone as well as together in any combinations. Also you
can have nested combination by putting them along with values in parenthesis ().

Syntax:
SELECT "column_name" / * FROM "table_name" WHERE "simple condition" ({[AND|OR] "simple
condition"}+)
where {}+ means The {}+ means that the expression inside the bracket will occur one or more times

Example:
Table Structure and data: Customers
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
Steven Goldfish goldfish@fishhere.net 4/4/1974 323-455-4545
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623

Query 1:
SELECT * FROM Customers WHERE First Name = 'John' AND Last Name = 'Smith'

Result:
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222

Query 2:
SELECT * FROM Customers WHERE First Name = 'John' OR First Name = 'Paula'

Result:
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295

Query 3:
SELECT * FROM Customers WHERE (First Name = 'James' OR First Name = 'Paula') AND Last Name =
'Brown'

Result:
First Name Last Name Email DOB Phone
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295
SQL IN Clause
The SQL IN clause allows you to specify discrete values in your SQL WHERE search criteria.

Syntax:
SELECT Column1, Column2, Column3, … FROM Table1 WHERE Column1 IN (Valu1, Value2, …)

Example:
Table Structure and Data: EmployeeHours
Employee Date Hours
John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 9
John Smith 5/7/2004 8
Allan Babel 5/7/2004 9
Tina Crown 5/7/2004 8
John Smith 5/8/2004 10
Allan Babel 5/8/2004 8
Tina Crown 5/8/2004 8
Query 1:
SELECT * FROM EmployeeHours WHERE Date IN ('5/6/2004', '5/7/2004')

Result:
Employee Date Hours
John Smith 5/6/2004 8
Allan Babel 5/6/2004 8
Tina Crown 5/6/2004 9
John Smith 5/7/2004 8
Allan Babel 5/7/2004 9
Tina Crown 5/7/2004 8
Query 2:
SELECT * FROM EmployeeHours WHERE Hours IN (9, 10)

Result:
Employee Date Hours
Tina Crown 5/6/2004 9
Allan Babel 5/7/2004 9
John Smith 5/8/2004 10
SQL BETWEEN Operator
The BETWEEN operator is used in a WHERE clause to select a range of data between two
values.The values can be numbers, text, or dates.

Syntax:
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

Example:
Table Structure and Data: Customers
First Name Last Name Email DOB Phone
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
Steven Goldfish goldfish@fishhere.net 4/4/1974 323-455-4545
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623

Query 1:
SELECT * FROM Customers WHERE DOB BETWEEN '1/1/1975' AND „1/1/2004'

Result:
First Name Last Name Email DOB Phone
Paula Brown pb@heroowndomain.org 5/24/1978 416-323-3295
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623

Query 2:
Select * FROM Customers WHERE Last Name BETWEEN „Goldfish‟ and „Smith‟

The result for this query may vary between different database providers

Result 1:
First Name Last Name Email DOB Phone
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
In this result, the values that exist between the range values are displayed, excluding the range
values.

Result 2:
First Name Last Name Email DOB Phone
Steven Goldfish goldfish@fishhere.net 4/4/1974 323-455-4545
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
Amanda Smith Amandas@hotmail.com 5/14/1987 236-587-4623
John Smith John.Smith@yahoo.com 2/4/1968 626-222-2222
In this result, the values that exist between the range values and including the range values are
displayed.
Result 3:
First Name Last Name Email DOB Phone
Steven Goldfish goldfish@fishhere.net 4/4/1974 323-455-4545
James Nixon Jnixon@verizon.net 6/13/1981 839-435-8642
In this result, the values that exist between the range values and including the starting range
value and excluding the ending range values are displayed.
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
SQL wildcards must be used with the SQL LIKE operator.

With SQL, the following wildcards can be used:


Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] or
Any single character not in charlist
[!charlist]

We can consider the following table for the examples of wildcards.

Table Structure and data: Persons


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Using the % Wildcard


Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.

Query:
SELECT * FROM Persons WHERE City LIKE 'sa%'

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Next, we want to select the persons living in a city that contains the pattern "nes" from the "Persons"
table.

Query:
SELECT * FROM Persons WHERE City LIKE '%nes%'

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Using the _ Wildcard
Now we want to select the persons with a first name that starts with any character, followed by
"la" from the "Persons" table.

Query:
SELECT * FROM Persons WHERE FirstName LIKE '_la'

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
Next, we want to select the persons with a last name that starts with "S", followed by any character,
followed by "end", followed by any character, followed by "on" from the "Persons" table.

Query:
SELECT * FROM Persons WHERE LastName LIKE 'S_end_on'

Result:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard


Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the
"Persons" table.

Query:
SELECT * FROM Persons WHERE LastName LIKE '[bsp]%'

Result:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Next, we want to select the persons with a last name that do not start with "b" or "s" or "p" from the
"Persons" table.

Query:
SELECT * FROM Persons WHERE LastName LIKE '[!bsp]%'

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

Syntax:
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern

Table Structure and Data: Persons


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons living in a city that starts with "s" from the table above.

Query:
SELECT * FROM Persons WHERE City LIKE 's%'

The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the
pattern.

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Next, we want to select the persons living in a city that ends with an "s" from the "Persons" table.

Query:
SELECT * FROM Persons WHERE City LIKE '%s'

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
It is also possible to select the persons living in a city that NOT contains the pattern "tav" from the
"Persons" table, by using the NOT keyword.

Query:
SELECT * FROM Persons WHERE City NOT LIKE '%tav%'

Result:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
SQL ORDER BY
So far, we have seen how to get data out of a table using SELECT and WHERE commands.
Often, however, we need to list the output in a particular order. This could be in ascending order, in
descending order, or could be based on either numerical value or text value. In such cases, we can use
the ORDER BY keyword to achieve our goal.

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 BY clause. 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.

Table Structure and Data: Persons


P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
Now we want to select all the persons from the table above, however, we want to sort the persons by
their last name.

Query:
SELECT * FROM Persons ORDER BY LastName

Result:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
4 Nilsen Tom Vingvn 23 Stavanger
3 Pettersen Kari Storgt 20 Stavanger
2 Svendson Tove Borgvn 23 Sandnes
Since we haven‟t given name order by value it is sorted in ascending order by default.
Now we want to select all the persons from the table above, however, we want to sort the persons
descending by their last name.

Query:
SELECT * FROM Persons ORDER BY LastName DESC

Result:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
1 Hansen Ola Timoteivn 10 Sandnes
SQL Aggregate Functions:
Since we have started dealing with numbers, the next natural question to ask is if it is possible to
do math on those numbers, such as summing them up or taking their average. The answer is yes! SQL
has several arithmetic functions, and they are:
 AVG: Average of the column.
 COUNT: Number of records.
 MAX: Maximum of the column.
 MIN: Minimum of the column.
 SUM: Sum of the column.

Syntax:
SELECT "function type" ("column_name") FROM "table_name"
In addition to using functions, it is also possible to use SQL to perform simple tasks such as addition (+)
and subtraction (-). For character-type data, there are also several string functions available, such as
concatenation, trim, and substring functions. Different RDBMS vendors have different string functions
implementations, and it is best to consult the references for your RDBMS to see how these functions are
used.
We will see each of the functions below in detail.

Average Function avg():


SQL uses the AVG() function to calculate the average of a column.

Syntax:
SELECT AVG("column_name") FROM "table_name"

Table Structure and data: Orders


O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the average value of the "OrderPrice" fields.

Query:
SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

Result:
OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher than the average OrderPrice
value.
Query:
SELECT Customer FROM Orders WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

Result:

Customer
Hansen
Nilsen
Jensen
Count Function count():
This function allows us to COUNT up the number of row in a certain table. The NULL values in
the column or table will not be counted.

Syntax:
SELECT COUNT("column_name") FROM "table_name"
SELECT COUNT(*) FROM "table_name"
SELECT COUNT(DISTINCT "Column_name") FrOM "table_Name"
Note: COUNT (DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft
Access.

Table Structure and data: Orders


O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

COUNT (column_name) Example:


Now we want to count the number of orders from "Customer Nilsen".
Query:
SELECT COUNT(Customer) AS CustomerNilsen FROM Orders WHERE Customer='Nilsen'

Result:
CustomerNilsen
2

COUNT (*) Example:


Now we want to count the total number of orders in the Orders table.
Query:
SELECT COUNT (*) AS NumberOfOrders FROM Orders
Result:
NumberOfOrders
6

COUNT (DISTINCT column_name) Example:


Now we want to count the number of unique customers in the "Orders" table.
Query:
SELECT COUNT (DISTINCT Customer) AS NumberOfCustomers FROM Orders
Result:
NumberOfCustomers
3

The above result is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.
SQL MAX() Function
The MAX() function returns the largest value of the selected column.

Syntax:
SELECT MAX(column_name) FROM table_name

Example:
Table Structure and Data: Orders
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the largest value of the "OrderPrice" column.


Query:
SELECT MAX(OrderPrice) AS LargestOrderPrice FROM Orders

Result:
LargestOrderPrice
2000

SQL MIN() Function


The MIN() function returns the smallest value of the selected column.

Syntax:
SELECT MIN(column_name) FROM table_name

We will use the table structure and data that we used for MAX() function.

Now we want to find the smallest value of the "OrderPrice" column.

Query:
SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders

Result:

SmallestOrderPrice
100
SQL SUM() Function
The SUM() function returns the total sum of a numeric column.

Syntax:
SELECT SUM(column_name) FROM table_name

We will use the table structure and data that we used for MAX() function.

Now we want to find the sum of all "OrderPrice" fields".

Query:
SELECT SUM(OrderPrice) AS OrderTotal FROM Orders

Result:

OrderTotal
5700
SQL GROUP BY Statement
Aggregate functions often need an added GROUP BY statement.The GROUP BY statement is used in
conjunction with the aggregate functions to group the result-set by one or more columns.

Syntax:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name
operator value GROUP BY column_name
Example:
Table Structure and Data: Orders
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers.

Query:
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer

Result:
Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000

Let‟s see if we can‟t use GROUP BY in the above query what would be the result:

Query:
SELECT Customer,SUM(OrderPrice) FROM Orders

Result:
Customer SUM(OrderPrice)
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700
Explanation of why the above SELECT statement cannot be used:
The SELECT statement above has two columns specified (Customer and SUM(OrderPrice). The
"SUM(OrderPrice)" returns a single value (that is the total sum of the "OrderPrice" column), while
"Customer" returns 6 values (one value for each row in the "Orders" table). This will therefore not give us
the correct result. However, you have seen that the GROUP BY statement solves this problem.

GROUP BY More Than One Column


We can also use the GROUP BY statement on more than one column, like this:
SELECT Customer, OrderDate, SUM (OrderPrice) FROM Orders GROUP BY Customer, OrderDate
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.

Syntax:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name
operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value

Example:
We will be using the same table structure and data that we used for Group BY statement.
Now we want to find if any of the customers have a total order of less than 2000.

Query:
SELECT Customer,SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING
SUM(OrderPrice)<2000

Result:
Customer SUM(OrderPrice)
Nilsen 1700
SQL Alias
There are two types of aliases that are used most frequently: column alias and table alias.

Column aliases exist to help organizing output. Using a column alias would greatly make the output much
more readable.

The second type of alias is the table alias. This is accomplished by putting an alias directly after the table
name in the FROM clause. This is convenient when you want to obtain information from two separate
tables. The advantage of using a table alias when doing joins is readily apparent when we talk about
joins.

Syntax for Tables Alias


SELECT column_name(s) FROM table_name AS alias_name

Syntax for Columns Alias


SELECT column_name AS alias_name FROM table_name

Example:
Assume we have a table called "Persons" and another table called "Product_Orders". We will give the
table aliases of "p" and "po" respectively.
Table Structure and Data: Persons
P_Id First Name Last Name Contact
P001 James David 609-345-3453
P002 John Charles 345-345-4534
P003 Dav Smith 786-123-7890
P004 Keith Jenny 978-321-4234

Table Structure and Data: Product_Orders

Order_Id Product Order_date P_Id


OD001 Samsung Printer SX493 01/08/2010 P003
Samsung BD Player
OD002 23/08/2010 P001
BD-C550
OD003 Sony Playstation 3 12/08/2010 P002
OD004 Lenovo Keyboard 14/08/2010 P003

Now we want to list all the order_ id that "Ola Hansen" is responsible for.

Query:
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons AS p, Product_Orders AS po WHERE
p.LastName='Smith' AND p.FirstName='Dav' and p.P_id = po.P_Id
OR
SELECT po.OrderID, p.LastName, p.FirstName FROM Persons p, Product_Orders po WHERE
p.LastName='Smith' AND p.FirstName='Dav' and Persons.P_id = Product_Orders.P_Id

Using „AS‟ is mostly useful for Column Alias. We can use „AS‟ both in Column Alias as well as Table
Alias. Using „AS‟ make the query more readable and easily understand that the alias is used.
The same SELECT statement without aliases:

SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName FROM Persons,


Product_Orders WHERE Persons.LastName='Smith' AND Persons.FirstName='Dav'

As you'll see from the two SELECT statements above; aliases can make queries easier to both write and
to read.
SQL Joins
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on
a relationship between certain columns in these tables.

Tables in a database are often related to each other with keys. A primary key is a column (or a
combination of columns) with a unique value for each row. Each primary key value must be unique within
the table. The purpose is to bind data together, across tables, without repeating all of the data in every
table.

Example:
Table Structure and Data: Persons
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two rows can
have the same P_Id. The P_Id distinguishes two persons even if they have the same name.

Other related table is:


Table Structure & Data: Orders
O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Note that the "O_Id" column is the primary key in the "Orders" table and that the "P_Id" column refers to
the persons in the "Persons" table without using their names.

Notice that the relationship between the two tables above is the "P_Id" column.

Different SQL Joins


 JOIN or INNER JOIN: Return rows when there is at least one match in both tables.
 LEFT JOIN or LEFT OUTER JOIN: Return all rows from the left table, even if there are
no matches in the right table.
 RIGHT JOIN or RIGHT OUTER JOIN: Return all rows from the right table, even if there
are no matches in the left table.
 FULL JOIN: Return rows when there is a match in one of the tables.
SQL INNER JOIN
The INNER JOIN will select all rows from both tables as long as there is a match between the
columns we are matching on.

If you don't put INNER or OUTER keywords in front of the SQL JOIN keyword, then INNER JOIN
is used. In short "INNER JOIN" = "JOIN"

Syntax:
SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON
table_name1.column_name=table_name2.column_name

Example:
Table Structure and data: Persons
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Table Structure and data: Orders


O_Id OrderNo P_Id
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Now we want to list all the persons with any orders.

Query:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

Result:
LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678

The INNER JOIN keyword return rows when there is at least one match in both tables. If there are rows in
"Persons" that do not have matches in "Orders", those rows will NOT be listed.
SQL LEFT JOIN
The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most
databases), selects all the rows from the first table listed after the FROM clause, no matter if they have
matches in the second table.

Syntax:
SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON
table_name1.column_name=table_name2.column_name

Example:
Let‟s consider the tables Persons and Orders that we used in Inner Join.

Now we want to list all the persons and their orders - if any.

Query:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

Result:
LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove

The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no matches in
the right table (Orders).
SQL RIGHT JOIN
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no
matches in the left table (table_name1). In other words, the RIGHT OUTER JOIN or just RIGHT JOIN
behaves exactly as SQL LEFT JOIN, except that it returns all rows from the second table (the right table
in our SQL JOIN statement).

Syntax:
SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON
table_name1.column_name=table_name2.column_name
Example:
Let‟s consider the tables Persons and Orders that we used in Inner Join.

Now we want to list all the orders with containing persons - if any, from the tables above.

Query:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

Result:
LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
34764

The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches
in the left table (Persons).
SQL FULL JOIN
The FULL JOIN keyword return rows when there is a match in one of the tables.

Syntax:
SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON
table_name1.column_name=table_name2.column_name

Example:
Let‟s consider the tables Persons and Orders that we used in Inner Join.

Now we want to list all the persons and their orders, and all the orders with their persons.

Query:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo FROM Persons FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id ORDER BY Persons.LastName

Result:
LastName FirstName OrderNo
Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
Svendson Tove
34764

The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the right
table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are rows in
"Orders" that do not have matches in "Persons", those rows will be listed as well.
String Concatenate
Sometimes it is necessary to combine together (concatenate) the results from several different
fields. Each database provides a way to do this:
 MySQL: CONCAT()
 Oracle: CONCAT(), ||
 SQL Server: +

Syntax:
MySQL:
SELECT CONCAT(str1, str2, str3, ...) FROM table_name

Oracle:
SELECT CONCAT(column_name or str1,column_name or str2) FROM table_name

SELECT column_name or str1 || column_name or str2 FROM table_name

SQL Server:
SELECT column_name or str1 + column or str2 FROM table_name

Please note the Oracle CONCAT() function only allows two arguments -- only two strings can be put
together at a time using this function. However, it is possible to concatenate more than two strings at a
time in Oracle using '||'.

Example:
Table Structure and Data: Geography
Region_name Store_name
East Boston
East New York
West Los Angeles
West San Diego

Query:

MySQL/Oracle:
SELECT CONCAT(Region_name,Store_name) FROM Geography WHERE Store_name = 'Boston'

Result:
'EastBoston'

Oracle:
SELECT Region_name || ' ' || Store_name FROM Geography WHERE Store_name = 'Boston'
Result:
'East Boston'

SQL Server:
SELECT Region_name + ' ' + Store_name FROM Geography WHERE Store_name = 'Boston'

Result:
'East Boston'
SQL Substring
The Substring function in SQL is used to grab a portion of the stored data. This function is called
differently for the different databases:

 MySQL: SUBSTR(), SUBSTRING()


 Oracle: SUBSTR()
 SQL Server: SUBSTRING()

Syntax:
SELECT SUBSTR(str,pos) FROM table_name
The above syntax is to select all characters from <str> starting with position <pos>.

SELECT SUBSTR(str,pos,len) FROM table_name


The above syntax is select characters starting with the <pos>th character in string <str> and select the
next <len> characters.

Example:
Let‟s use the same table structure and data of Geography table that is used in SQL Concatenate.

Query:
SELECT SUBSTR(store_name, 3) FROM Geography WHERE store_name = 'Los Angeles'

Result:
's Angeles'

Query:
SELECT SUBSTR(store_name,2,4) FROM Geography WHERE store_name = 'San Diego'

Result:
'an D'
SQL TRIM
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common
pattern being removed is white spaces. This function is called differently in different databases:

 MySQL: TRIM(), RTRIM(), LTRIM()


 Oracle: RTRIM(), LTRIM()
 SQL Server: RTRIM(), LTRIM()

Syntax:
SELECT TRIM([[LOCATION] [remstr] FROM ] str)

[LOCATION] can be either LEADING, TRAILING, or BOTH. This function gets rid of the [remstr] pattern
from either the beginning of the string or the end of the string, or both. If no [remstr] is specified, white
spaces are removed.

LTRIM(str): Removes all white spaces from the beginning of the string.

RTRIM(str): Removes all white spaces at the end of the string.

Example:

Query:
SELECT TRIM(' Sample ')

Result: 'Sample'

Query:
SELECT LTRIM(' Sample ');

Result:
'Sample '

Query:
SELECT RTRIM(' Sample ');

Result:
' Sample'
SQL Length
The length function in SQL is used to get the length of a string. This function is called differently for the
different databases:

 MySQL & Oracle: LENGTH()


 SQL Server: LEN()

Syntax:
SELECT Length(column_name) FROM table_name

Example:
Table Structure and Data: Geography

Region_name Store_name
East Boston
East New York
West Los Angeles
West San Diego

Query:
SELECT Store_name, Length(Store_name) FROM Geography

Result:
Store_name Length(Store_name)
Boston 6
New York 8
Los Angeles 11
San Diego 9
SQL REPLACE

The Replace function in SQL is used to update the content of a string. The function call is REPLACE() for
MySQL, Oracle, and SQL Server.

Syntax:
SELECT REPLACE(str1, str2, str3) FROM table_name
In str1, find where str2 occurs, and replace it with str3.

Example:
Let‟s use the same table structure and data of Geography table that is used in SQL Length.

Query:
SELECT REPLACE(region_name, 'ast', 'astern') FROM Geography

Result:
Region_name
Eastern
Eastern
West
West
SQL DATE
The Date function is used to retrieve the current database system time. The Date function is called
differently for the different databases.

Syntax:
SQL Server:
SELECT GETDATE()
MySQL:
SELECT SYSDATE()
Oracle:
SELECT SYSDATE() from Dual

GETDATE or SYSDATE does not require any argument.

Example:

SQL Server:
Query:
SELECT GETDATE();

Result:
'2010-11-21 00:05:02.123'

GETDATE function is most useful when we need to record the time a particular transaction happens. In
SQL Server, we simply insert the value of the GETDATE() function into the table to achieve this. We can
also set the default value of a column to be GETDATE() to achieve the same purpose.

MySQL:
Query:
SELECT SYSDATE();

Result:
'2010-11-21 00:05:02.123'

Oracle:
Query:
SELECT SYSDATE FROM DUAL;

Result:
'21-Nov-2010'
Table Manipulation
Tables are the basic structure where data is stored in the database. Tables are divided into rows
and columns. Each row represents one piece of data, and each column can be thought of as representing
a component of that piece of data. So, for example, if we have a table for recording customer information,
then the columns may include information such as First Name, Last Name, Address, City, Country, Birth
Date, and so on. As a result, when we specify a table, we include the column headers and the data types
for that particular column.
The data types are the data that comes in a variety of forms. It could be an integer (such as 1), a
real number (such as 0.55), a string (such as 'sql'), a date/time expression (such as '2000-JAN-25
03:22:22'), or even in binary format. When we specify a table, we need to specify the data type
associated with each column (i.e., we will specify that 'First Name' is of type char(50) - meaning it is a
string with 50 characters). One thing to note is that different relational databases allow for different data
types, so it is wise to consult with a database-specific reference first.
At the end of this section of the tutorial, you will be able to write queries for table manipulation.

SQL CREATE TABLE


Here we will see how to create tables.
Syntax:
CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2"
"data_type_for_column_2", ... )
Example:
If we are to create the customer table then the query would be

Query 1:
CREATE TABLE customer (First_Name char(50),Last_Name char(50),Address char(50),City
char(50),Country char(25),Birth_Date date)

Sometimes, we want to provide a default value for each column. A default value is used when you do not
specify a column's value when inserting data into the table. To specify a default value, add "Default
[value]" after the data type declaration. In the above example, if we want to default column "Address" to
"Unknown" and City to "Delhi", the query would be

Query 2:
CREATE TABLE customer (First_Name char(50),Last_Name char(50),Address char(50) default
'Unknown',City char(50) default 'Delhi',Country char(25),Birth_Date date)
SQL CONSTRAINTS
The Constraints are to limit the type of data that can go into a table. Such constraints can be
specified when the table when the table is first created via the CREATE TABLE statement, or after the
table is already created via the ALTER TABLE statement.

Common types of constraints include the following:


 NOT NULL Constraint: Ensures that a column cannot have NULL value.
 DEFAULT Constraint: Provides a default value for a column when none is specified.
 UNIQUE Constraint: Ensures that all values in a column are different.
 CHECK Constraint: Makes sure that all values in a column satisfy certain criteria.
 Primary Key Constraint: Used to uniquely identify a row in the table.
 Foreign Key Constraint: Used to ensure referential integrity of the data.

NOT NULL Constraint


By default, a column can hold NULL. If you not want to allow NULL value in a column, you will
want to place a constraint on this column specifying that NULL is now not an allowable value.

Example:
Query:
CREATE TABLE Customer (SID integer NOT NULL, Last_Name varchar (30) NOT NULL, First_Name
varchar(30))

In the above query Columns "SID" and "Last_Name" cannot include NULL, while "First_Name" can
include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer (Last_Name, First_Name) values ('Wong','Ken') will result in an error because
this will lead to column "SID" being NULL, which violates the NOT NULL constraint on that column.

DEFAULT Constraint
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does
not provide a specific value.

Example:
Query:
CREATE TABLE Student (Student_ID integer Unique, Last_Name varchar (30), First_Name varchar (30),
Score DEFAULT 80)

INSERT INTO Student (Student_ID, Last_Name, First_Name) values ('10','Johnson','Rick')

The table will look like the following:


Student_ID Last_Name First_Name Score
10 Johnson Rick 80

Even though we didn't specify a value for the "Score" column in the INSERT INTO statement, it does get
assigned the default value of 80 since we had already set 80 as the default value for this column.
UNIQUE Constraint:
The UNIQUE constraint ensures that all values in a column are distinct.

Example:
Query:
CREATE TABLE Customer (SID integer Unique, Last_Name varchar (30), First_Name varchar(30))

The column "SID" has a unique constraint, and hence cannot include duplicate values. Such constraint
does not hold for columns "Last_Name" and "First_Name".

So, if the table already contains the following rows:


SID Last_Name First_Name
1 Johnson Stella
2 James Gina
3 Aaron Ralph

Query:
INSERT INTO Customer values ('3','Lee','Grace')

The above query will result in an error because '3' already exists in the SID column, thus trying to insert
another row with that value violates the UNIQUE constraint.

Please note that a column that is specified as a primary key must also be unique. At the same time, a
column that's unique may or may not be a primary key. In addition, multiple UNIQUE constraints can be
defined on a table.

CHECK Constraint:
The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the
database will only insert a new row or update an existing row if the new value satisfies the CHECK
constraint. The CHECK constraint is used to ensure data quality.

Example:
Query:
CREATE TABLE Customer (SID integer CHECK (SID > 0), Last_Name varchar (30), First_Name
varchar(30));

Column "SID" has a constraint -- its value must only include integers greater than 0.

So, attempting to execute the following statement,


INSERT INTO Customer values ('-3','Gonzales','Lynn') will result in an error because the values for SID
must be greater than 0.
PRIMARY KEY Constraint
The primary key is used to uniquely identify each row in a table. It can either be part of the actual
record itself, or it can be an artificial field (one that has nothing to do with the actual record). A primary
key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are
called a composite key.

Primary keys can be specified either when the table is created (using CREATE TABLE) or by
changing the existing table structure (using ALTER TABLE).

Below are examples for specifying a primary key when creating a table:

MySQL:
CREATE TABLE Customer (SID integer, Last_Name varchar(30), First_Name varchar(30), PRIMARY
KEY (SID))

Oracle:
CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name
varchar(30))

SQL Server:
CREATE TABLE Customer (SID integer PRIMARY KEY, Last_Name varchar(30), First_Name
varchar(30))

Below are examples for specifying a primary key by altering a table:

MySQL:
ALTER TABLE Customer ADD PRIMARY KEY (SID)

Oracle:
ALTER TABLE Customer ADD PRIMARY KEY (SID)

SQL Server:
ALTER TABLE Customer ADD PRIMARY KEY (SID)

Note: Before using the ALTER TABLE command to add a primary key, you'll need to make sure that the
field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.
FOREIGN KEY Constraint
A foreign key is a field (or fields) that points to the primary key of another table. The purpose of
the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed
to appear in the database are permitted.

For example, say we have two tables, a CUSTOMER table that includes all customer data, and
an ORDERS table that includes all customer orders. The constraint here is that all orders must be
associated with a customer that is already in the CUSTOMER table. In this case, we will place a foreign
key on the ORDERS table and have it relate to the primary key of the CUSTOMER table. This way, we
can ensure that all orders in the ORDERS table are related to a customer in the CUSTOMER table. In
other words, the ORDERS table cannot contain information on a customer that is not in the CUSTOMER
table.

Table Structure and Data: Customer


Column_name Characteristic
SID Primary Key
Last_Name
First_Name
Table Structure and Data: Orders
Column_name Characteristic
Order_ID Primary Key
Order_Date
Customer_SID Foreign Key
Amount
In the above example, the Customer_SID column in the ORDERS table is a foreign key pointing to the
SID column in the CUSTOMER table.

Below we show examples of how to specify the foreign key when creating the ORDERS table:
MySQL:
CREATE TABLE ORDERS (Order_ID integer, Order_Date date, Customer_SID integer, Amount double,
Primary Key (Order_ID), Foreign Key (Customer_SID) references CUSTOMER(SID))

Oracle:
CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date date, Customer_SID integer
references CUSTOMER(SID), Amount double)

SQL Server:
CREATE TABLE ORDERS (Order_ID integer primary key, Order_Date datetime, Customer_SID integer
references CUSTOMER(SID), Amount double)

Below are examples for specifying a foreign key by altering a table. This assumes that the ORDERS table
has been created, and the foreign key has not yet been put in:
MySQL:
ALTER TABLE ORDERS ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID)

Oracle:
ALTER TABLE ORDERS ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid)
REFERENCES CUSTOMER(SID)

SQL Server:
ALTER TABLE ORDERS ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID)
SQL VIEW
A view is a virtual table. A view consists of rows and columns just like a table. The difference
between a view and a table is that views are definitions built on top of other tables (or views), and do not
hold data themselves. If data is changing in the underlying table, the same change is reflected in the
view. A view can be built on top of a single table or multiple tables. It can also be built on top of another
view. In the SQL Create View page, we will see how a view can be built.

Views offer the following advantages:


 Ease of use: A view hides the complexity of the database tables from end users.
Essentially we can think of views as a layer of abstraction on top of the database tables.
 Space savings: Views takes very little space to store, since they do not store actual data.
 Additional data security: Views can include only certain columns in the table so that only
the non-sensitive columns are included and exposed to the end user. In addition, some
databases allow views to have different security settings, thus hiding sensitive data from
prying eyes.

CREATE VIEW
Views can be considered as virtual tables. Generally speaking, a table has a set of definition, and it
physically stores the data. A view also has a set of definitions, which is build on top of table(s) or other
view(s), and it does not physically store the data.

Syntax:
CREATE VIEW "VIEW_NAME" AS SELECT * FROM table_name

Example:
Table Structure: Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date

We want to create a view called V_Customer that contains only the First_Name, Last_Name, and Country
columns from this table,
Query:
CREATE VIEW V_Customer AS SELECT First_Name, Last_Name, Country FROM Customer

Now we have a view called V_Customer with the following structure:

View V_Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Country Char(25)

We can also use a view to apply joins to two tables. In this case, users only see one view rather than two
tables, and the SQL statement users need to issue becomes much simpler. Let's say we have the
following two tables:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010

Table Structure and Data: Geography


Region_name Store_name
East Boston
East New York
West Los Angeles
West San Diego

We want to build a view that has sales by region information.

Query:
CREATE VIEW V_REGION_SALES AS SELECT A1.region_name REGION, SUM(A2.Sales) SALES
FROM Geography A1, Store_Information A2 WHERE A1.store_name = A2.store_name
GROUP BY A1.region_name

This gives us a view, V_REGION_SALES, that has been defined to store sales by region records. If we
want to find out the content of this view, we type in,

Query:
SELECT * FROM V_REGION_SALES

Result:
Region Sales
East $1250
West $4290
SQL INDEXES
Indexes help us retrieve data from tables quicker. Let's use an example to illustrate this point:
Say we are interested in reading about how to grow peppers in a gardening book. Instead of reading the
book from the beginning until we find a section on peppers, it is much quicker for us to go to the index
section at the end of the book, locate which pages contain information on peppers, and then go to these
pages directly. Going to the index first saves us time and is by far a more efficient method for locating the
information we need.
The same principle applies for retrieving data from a database table. Without an index, the
database system reads through the entire table (this process is called a 'table scan') to locate the desired
information. With the proper index in place, the database system can then first go through the index to
find out where to retrieve the data, and then go to these locations directly to get the needed data. This is
much faster.
Therefore, it is often desirable to create indexes on tables. An index can cover one or more
columns. The syntax for creating a table index is shown in the CREATE INDEX section. Below we
discuss some general strategies when building and using an index:

1. Build index on columns of integer type


Integers take less space to store, which means the query will be faster. If the column you want to build an
index for is not of type integer, consider creating a surrogate integer key (or simply a surrogate column of
type integer) which maps one-to-one to the column you want to build the index for.

2. Keep index as narrow as possible


Narrower indexes take less space, require less time to process, which in turn means the query will run
faster.

3. Column order is important


For indexes covering multiple columns, the order of the columns in the index is important. The best
practice is to use the column with the lowest cardinality first, and the column with the highest cardinality
last. Recall cardinality means the number of distinct values for that column. So, if "SELECT DISTINCT
(COLUMN1) FROM TABLE_NAME;" returns 5, that means the cardinality for COLUMN1 is 5.

4. Make sure the column you are building an index for is declared NOT NULL
This can decrease the size of the index, which in turn will speed up the query.
CREATE INDEX
A table index helps SQL statements run faster.

Syntax:
CREATE INDEX "INDEX_NAME" ON "TABLE_NAME" (COLUMN_NAME)

Let's assume that we have the following table,

TABLE Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date

We want to create an index on the column Last_Name,


Query:
CREATE INDEX IDX_CUSTOMER_LAST_NAME on CUSTOMER (Last_Name)

If we want to create an index on both City and Country,


Query:
CREATE INDEX IDX_CUSTOMER_LOCATION on CUSTOMER (City, Country)

There is no strict rule on how to name an index. The generally accepted method is to place a prefix, such
as "IDX_", before an index name to avoid confusion with other database objects. It is also a good idea to
provide information on which table and column(s) the index is used on.

Please note that the exact syntax for CREATE INDEX may be different for different databases. You
should consult with your database reference manual for the precise syntax.
ALTER Table
Once a table is created in the database, there are many occasions where one may wish to
change the structure of the table.

Syntax:
ALTER TABLE "table_name" [alter specification]

[alter specification] is dependent on the type of alteration we wish to perform.

Following is the of list a number of common changes:


 ALTER Table ADD Column
 ALTER Table MODIFY Column
 ALTER Table RENAME Column
 ALTER Table DROP Column
 ALTER Table ADD Index
 ALTER Table DROP Index
 ALTER Table ADD Constraint
 ALTER Table DROP constraint
ALTER Table ADD Column
Syntax:
ALTER TABLE "table_name" ADD "column 1" "Data Type"

Example:
Table: Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date

Our goal is to add a column called "Gender".


Query:
ALTER TABLE customer ADD Gender char(1)

Resulting Table Structure:


Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date
Gender Char(1)

Note that the new column Gender becomes the last column in the customer table.

It is also possible to add multiple columns. For example, we want to add a column called "Email" and
another column called "Telephone"

Query:
ALTER TABLE customer ADD (Email char(30), Telephone char(20))

Resulting Table Structure:


Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date
Gender Char(1)
Email Char(30)
Telephone Char(30)
ALTER TABLE MODIFY Column
Sometimes we need to change the data type of a column. To do this, we use the ALTER TABLE
Modify Column command.

Oracle and MySQL Syntax:


ALTER TABLE "table_name" MODIFY "column 1" "New Data Type"

SQL Server syntax:


ALTER TABLE "table_name" ALTER COLUMN "column 1" "New Data Type"

Example:
Table: Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date
Our goal is to alter the data type of the "Address" column to char(100).

MySQL & Oracle Query:


ALTER TABLE customer MODIFY Address char(100)

SQL Server:
ALTER TABLE customer ALTER COLUMN Address char(100)

Resulting table structure:


Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(100)
City Char(50)
Country Char(25)
Birth_Date Date
ALTER Table RENAME Column
Sometimes we need to change the data type of a column. To do this, we use the ALTER TABLE
RENAME Column command.

Syntax:
My SQL:
ALTER TABLE "table_name" Change "column 1" "column 2" ["Data Type"]

Oracle:
ALTER TABLE "table_name" RENAME COLUMN "column 1" TO "column 2"

Example:
Table Structure: Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date

Our goal is to rename "Address" to "Addr"

MySQL Query:
ALTER table Customer CHANGE Address Addr char(50)

Oracle Query:
ALTER table Customer RENAME COLUMN Address TO Addr

SQL Server:
It is not possible to rename a column using the ALTER TABLE statement in SQL Server.

Resulting table structure:


Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Addr Char(50)
City Char(50)
Country Char(25)
Birth_Date Date
Alter Table Drop Column
Sometimes we need to delete a column after a table is created. To do this, we use the ALTER
TABLE DROP Column command.

Syntax:
MySQL:
ALTER TABLE "table_name" DROP "column 1"

Oracle & SQL Server:


ALTER TABLE "table_name" DROP COLUMN "column 1"

Example:
Table Structure: Customer
Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)
Birth_Date Date
Our goal is to drop the "Birth_Date" column.

MySQL Query:
ALTER table customer drop Birth_Date

Oracle & SQL Server Query:


ALTER table customer drop column Birth_Date

Resulting table structure:


Column_name Data type
First_Name Char(50)
Last_Name Char(50)
Address Char(50)
City Char(50)
Country Char(25)

Alter Table Add Index

MySQL Syntax:
ALTER TABLE "table_name" ADD INDEX " INDEX_NAME " (COLUMN_NAME)
Example:
Let‟s consider the same Customer table for this case. Our goal is to add an index on the
"Country" column.

Query:
ALTER table customer ADD INDEX IDX_COUNTRY (Country)

Please note that using ALTER TABLE to add an index is not supported in Oracle or SQL Server.
Alter Table Drop Index

MYSQL Syntax:
ALTER TABLE "table_name" DROP INDEX " INDEX_NAME "
Example:
Our goal is to drop the index created in the ALTER TABLE ADD INDEX section which is the index
for Country column.

Query:
ALTER table customer DOP INDEX IDX_COUNTRY

Please note that using ALTER TABLE to drop an index is not supported in Oracle or SQL Server.

Alter Table Add Constraint

Syntax:
ALTER TABLE "table_name"ADD [CONSTRAINT_NAME] [CONSTRAINT_TYPE]
[CONSTRAINT_CONDITION]
The syntax is same for MySQL,Oracle and SQL Server

Example:
Our goal is to add a UNIQUE constraint to the "Address" column in the Customer Table.

Query:
ALTER TABLE customer ADD CONSTRAINT con_first UNIQUE (first_name) where con_first is the name
of the constraint.

Alter Table Drop Constraint

Syntax:
ALTER TABLE "table_name" DROP [CONSTRAINT|INDEX] "CONSTRAINT_NAME"

Example:
Our goal to drop the UNIQUE constraint on the "Address" column in the Customer Table, created
in the ALTER Table ADD Constraint section

Query:
ALTER TABLE customer DROP CONSTRAINT con_first
DROP Table
Sometimes we may decide that we need to get rid of a table in the database for some reason. In
fact, it would be problematic if we cannot do so because this could create a maintenance nightmare for
the DBA's. Fortunately, SQL allows us to do it, as we can use the DROP TABLE command.

Syntax:
DROP TABLE "table_name"

Example:
Our goal is to delete the Customer table used in the earlier sections.

Query:
DROP TABLE Customer

Truncate Table
Sometimes we wish to get rid of all the data in a table. One way of doing this is with DROP
TABLE, which we saw in the last section. But if we wish to simply get rid of the data but not the table itself
then we can use the TRUNCATE TABLE command.

Syntax:
TRUNCATE TABLE "table_name"

Example:
Our goal is to truncate Customer table

Query:
TRUNCATE TABLE customer
SQL USE:
The USE keyword is used to select a database in MySQL.

Syntax:
USE "Database Name"

Example 1:
If you want to connect to a database called "Scores", then

Query:
USE Scores;

In MySQL, you can access tables in multiple databases by specifying [Database Name].[Table Name]. If
the table you want to access is currently in the database you use, there is no need to specify the
database name.

Example 2:
if you want to access table "Course_110" from database "Scores" and table "Students" from database
"Personnel", you can type in the following:

Query:
USE Scores;

SELECT ...
FROM Course_110, Personnel.Students
WHERE ...
SQL Insert Into
In this section we will see how to insert data into a table.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.

Syntax:

Inserting one row at a time:


INSERT INTO "table_name"("column_name1","column_name2"...) VALUES ("value1","value2"...)

Inserting multiple rows at a time:


INSERT INTO "table1" ("column1", "column2", ...) SELECT "column3", "column4", ... FROM "table2"
Here use a SELECT statement to specify the data that we want to insert into the table.Note that
this is the simplest form. The entire statement can easily contain WHERE, GROUP BY, and HAVING
clauses, as well as table joins and aliases.

Example:
Table Structure: Store_Information
Column_name Data type
Store_name Char(50)
Sales Float
Sales_Date Datetime

Query:
Inserting one row at a time:
INSERT INTO Store_Information (Store_name, Sales,Sales_Date) VALUES ('Los Angeles', 900, 'Jan-10-
1999')

Inserting multiple rows at a time:


INSERT INTO Store_Information (Store_name, Sales,Sales_Date) SELECT store_name, Sales,
Sales_Date FROM Sales_Information WHERE Year(Date) = 1998
SQL Update:
We might come under some situation that there is a need to modify the data. To do so, we can
use the UPDATE command.

Syntax:
To update one column and rows satisfies the condition:
UPDATE "table_name" SET "column_1" = [new value] WHERE {condition}
The above syntax will update value of only the column specified of any rows that satisfies the
given condition.

To update one column and all rows:


UPDATE "table_name" SET "column_1" = [new value]
The above syntax will update value of only the column specified and all the rows in the table
since there is no condition specified.

To update more than one column at a time:


UPDATE "table_name" SET column_1 = [value1], column_2 = [value2] WHERE {condition}
The above syntax will update the columns that are specified of any rows that satifies the given
condition.

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
Our goal is to update the sales of Los Angeles store on date 20-Nov-2010 from $1500 to $1750.

Query 1:
UPDATE Store_Information SET Sales = 1750 WHERE Store_name = "Los Angeles" AND Date = "20-
Nov-2010"

Resulting Table Data:


Store_name Sales Date
Los Angeles $1750 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
Query 2:
UPDATE Store_Information SET Sales = 1750

Resulting Table Data:


Store_name Sales Date
Los Angeles $1750 20-Nov-2010
San Diego $1750 20-Nov-2010
Boston $1750 21-Nov-2010
Los Angeles $1750 21-Nov-2010
Query 3:
UPDATE Store_Information SET Sales = 1750, Date=‟21-Nov-2010‟ WHERE Store_name = "San Diego"

Resulting Table Data:


Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $1750 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
Query 3:
UPDATE Store_Information SET Sales = 150, Date=‟01-Nov-2010‟

Resulting Table Data:


Store_name Sales Date
Los Angeles $150 01-Nov-2010
San Diego $150 01-Nov-2010
Boston $150 01-Nov-2010
Los Angeles $150 01-Nov-2010
SQL DELETE FROM
Sometimes we may want to remove records from a table. To do so, we can use the DELETE
FROM command.

Syntax:
DELETE FROM "table_name" WHERE {condition}

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010

Our goal is to remove all the records related to Los Angeles store.

Query:
DELETE FROM Store_Information WHERE store_name = "Los Angeles"

Resulting Table Data:


Store_name Sales Date
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Advanced SQL
SQL UNION
The purpose of the SQL UNION query is to combine the results of two queries together. In this
respect, UNION is somewhat similar to JOIN in that they are both used to related information from
multiple tables. One restriction of UNION is that all corresponding columns need to be of the same data
type. Also, when using UNION, only distinct values are selected (similar to SELECT DISTINCT).

Syntax:
[SQL Statement 1] UNION [SQL Statement 2]

Example
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Table Structure and Data: Internet_Sales


Date Sales
20-Nov-2010 $2300
21-Nov-2010 $3050
22-Nov-2010 $1250
24-Nov-2010 $1800

Our goal is to find out all the dates where there is a sales transaction.

Query:
SELECT Date FROM Store_Information UNION SELECT Date FROM Internet_Sales

Result:
Date
20-Nov-2010
21-Nov-2010
22-Nov-2010
23-Nov-2010
24-Nov-2010
SQL UNION ALL

The purpose of the SQL UNION ALL command is also to combine the results of two queries
together. The difference between UNION ALL and UNION is that, while UNION only selects distinct
values, UNION ALL selects all values.

Syntax:
[SQL Statement 1] UNION ALL [SQL Statement 2]
Example
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Table Structure and Data: Internet_Sales


Date Sales
20-Nov-2010 $2300
21-Nov-2010 $3050
22-Nov-2010 $1250
24-Nov-2010 $1800

Our goal is to find out all the dates where there is a sales transaction at a store as well as all the dates
where there is a sale over the internet

Query:
SELECT Date FROM Store_Information UNION ALL SELECT Date FROM Internet_Sales

Result:
Date
20-Nov-2010
20-Nov-2010
21-Nov-2010
21-Nov-2010
23-Nov-2010
20-Nov-2010
21-Nov-2010
22-Nov-2010
24-Nov-2010
SQL INTERSECT
Similar to the UNION command, INTERSECT also operates on two SQL statements. The
difference is that, while UNION essentially acts as an OR operator (value is selected if it appears in either
the first or the second statement), the INTERSECT command acts as an AND operator (value is selected
only if it appears in both statements).

Syntax:
[SQL Statement 1] INTERSECT [SQL Statement 2]

Example
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Table Structure and Data: Internet_Sales


Date Sales
20-Nov-2010 $2300
21-Nov-2010 $3050
22-Nov-2010 $1250
24-Nov-2010 $1800

Our goal is to find out all the dates where there are both store sales and internet sales. To do so, we use
the following SQL statement:

Query:
SELECT Date FROM Store_Information INTERSECT SELECT Date FROM Internet_Sales

Result:
Date
20-Nov-2010
21-Nov-2010

Please note that the INTERSECT command will only return distinct values.
SQL MINUS
The MINUS operates on two SQL statements. It takes all the results from the first SQL statement,
and then subtract out the ones that are present in the second SQL statement to get the final answer. If
the second SQL statement includes results not present in the first SQL statement, such results are
ignored.

Syntax:
[SQL Statement 1] MINUS [SQL Statement 2]
Example
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Table Structure and Data: Internet_Sales


Date Sales
20-Nov-2010 $2300
21-Nov-2010 $3050
22-Nov-2010 $1250
24-Nov-2010 $1800

Our goal is to find out all the dates where there are store sales, but no internet sales. To do so, we use
the following SQL statement:

Query:
SELECT Date FROM Store_Information MINUS SELECT Date FROM Internet_Sales

Result:
Date
23-Nov-2010

"20-Nov-2010", "21-Nov-2010" and “23-Nov-2010” are the distinct values returned from "SELECT Date
FROM Store_Information". "20-Nov-2010", "21-Nov-2010" are also returned from the second SQL
statement, "SELECT Date FROM Internet_Sales," so they are excluded from the final result set.

Please note that the MINUS command will only return distinct values. Some databases may use EXCEPT
instead of MINUS.
SQL LIMIT
Sometimes we may not want to retrieve all the records that satsify the critera specified in WHERE
or HAVING clauses.In MySQL, this is accomplished using the LIMIT keyword.

Syntax:
[SQL Statement 1] LIMIT [N]
In the above syntax, [N] is the number of records to be returned. Please note that the ORDER BY
clause is usually included in the SQL statement. Without the ORDER BY clause, the results we get would
be dependent on what the database default is.

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Our goal is to show the two highest sales amounts in Table Store_Information

Query:
SELECT Store_name, Sales, Date FROM Store_Information ORDER BY Sales DESC LIMIT 2

Result:
Store_name Sales Date
Los Angeles $1800 21-Nov-2010
Los Angeles $1500 20-Nov-2010
SQL TOP
In the previous section, we saw how LIMIT can be used to retrieve a subset of records in MySQL.
In Microsoft SQL Server, this is accomplished using the TOP keyword.

Syntax:
SELECT TOP [TOP argument] "column_name" FROM "table_name"

In the above syntax,[TOP argument] can be one of two possible types:


[N]: The first N records are returned.
[N'] PERCENT: The number of records corresponding to N'% of all qualifying records are returned.

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Our goal is to show the two highest sales amounts in Table Store_Information

Query 1:
SELECT TOP 2 store_name, Sales, Date FROM Store_Information ORDER BY Sales DESC

Result:
Store_name Sales Date
Los Angeles $1800 21-Nov-2010
Los Angeles $1500 20-Nov-2010

Alternatively,if we want to show the top 25% of sales amounts from Table Store_Information

Query 2:
SELECT TOP 20 PERCENT store_name, Sales, Date FROM Store_Information ORDER BY Sales DESC

Result:
Store_name Sales Date
Los Angeles $1800 21-Nov-2010
SQL SUB QUERIES
It is possible to embed a SQL statement within another. When this is done on the WHERE or the
HAVING statements, we have a subquery construct.

Syntax:
SELECT "column_name1" FROM "table_name1" WHERE "column_name2" [Comparison Operator]
(SELECT "column_name3" FROM "table_name2" WHERE [Condition])

[Comparison Operator] could be equality operators such as =, >, <, >=, <=. It can also be a text operator
such as "LIKE". The portion after the [Comparison Operator] is considered as the "inner query", while the
portion before the [Comparison Operator] is considered as the "outer query".

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010
Table Structure and Data: Geography
Region_name Store_name
East Boston
West Los Angeles
West San Diego
Our goal is to use a subquery to find the sales of all stores in the West region

Query:
SELECT SUM(Sales) FROM Store_Information WHERE Store_name IN (SELECT store_name FROM
Geography WHERE region_name = 'West')

Result:
SUM(Sales)
$4290
In this example, instead of joining the two tables directly and then adding up only the sales amount for
stores in the West region, we first use the sub query to find out which stores are in the West region, and
then we sum up the sales amount for these stores.

Correlated Query:
In the example given in SQL Subquery, the inner query is first executed, and the result is then fed
into the outer query. This type of subquery is called a simple subquery. If the inner query is dependent on
the outer query, we will have a correlated subquery.

Example:
Query:
SELECT SUM(a1.Sales) FROM Store_Information a1 WHERE a1.Store_name IN (SELECT Store_name
FROM Geography a2 WHERE a2.Store_name = a1.Store_name)
Result:
SUM(Sales)
$5540

Notice the WHERE clause in the inner query, where the condition involves a table from the outer query.

SQL EXISTS
In the previous section, we used IN to link the inner query and the outer query in a subquery
statement. IN is not the only way to do so -- one can use many operators such as >, <, or =. EXISTS is a
special operator that we will discuss in this section.

EXISTS simply tests whether the inner query returns any row. If it does, then the outer query
proceeds. If not, the outer query does not execute, and the entire SQL statement returns nothing.

Syntax:
SELECT "column_name1" FROM "table_name1" WHERE EXISTS (SELECT * FROM "table_name2"
WHERE [Condition])
Please note that instead of *, you can select one or more columns in the inner query. The effect will be
identical.

Query 1:
SELECT SUM(Sales) FROM Store_Information WHERE EXISTS (SELECT * FROM Geography WHERE
region_name = 'West')

Result:
SUM(Sales)
$6340

Query 2:
SELECT SUM(Sales) FROM Store_Information WHERE EXISTS (SELECT * FROM Geography WHERE
region_name = 'South')

Result:
No records returned.

At first, this may appear confusing, because the subquery includes the [region_name =
'West'] condition, yet the query summed up stores for all regions. Upon closer inspection, we
find that since the subquery returns more than 0 row, the EXISTS condition is true, and the
condition placed inside the inner query does not influence how the outer query is run.
SQL CASE
CASE is used to provide if-then-else type of logic to SQL.

Syntax:
SELECT CASE ("column_name")
WHEN "condition1" THEN "result1"
WHEN "condition2" THEN "result2"
...
[ELSE "resultN"]
END
FROM "table_name"

In the above syntax, "condition" can be a static value or an expression. The ELSE clause is optional.

Example:
Table Structure and Data: Store_Information
Store_name Sales Date
Los Angeles $1500 20-Nov-2010
San Diego $990 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $1800 21-Nov-2010
New York $800 23-Nov-2010

Our goal is to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San Diego'
by 1.5

Query:
SELECT store_name, CASE store_name
WHEN 'Los Angeles' THEN Sales * 2
WHEN 'San Diego' THEN Sales * 1.5
ELSE Sales
END
"New Sales",
Date
FROM Store_Information

"New Sales" is the name given to the column with the CASE statement.

Result:
Store_name Sales Date
Los Angeles $3000 20-Nov-2010
San Diego $1485 20-Nov-2010
Boston $1250 21-Nov-2010
Los Angeles $3600 21-Nov-2010
New York $800 23-Nov-2010
SQL NULL
In SQL, NULL means that data does not exist. NULL does not equal to 0 or an empty string. Both
0 and empty string represent a value, while NULL has no value.
Any mathematical operations performed on NULL will result in NULL. For example, 10 + NULL =
NULL
Aggregate functions such as SUM, COUNT, AVG, MAX, and MIN exclude NULL values. This is
not likely to cause any issues for SUM, MAX, and MIN. However, this can lead to confusion with AVG and
COUNT.

Example:
Table Structure and Data: Sales_Data
Store_name Sales
Store A $300
Store B $200
Store C $100
Store D NULL

Below are the results for each aggregate function:


SUM (Sales) = 600
AVG (Sales) = 200
MAX (Sales) = 300
MIN (Sales) = 100
COUNT (Sales) = 3

Note that the AVG function counts only 3 rows (the NULL row is excluded), so the average is 600 / 3 =
200, not 600 / 4 = 150. The COUNT function also ignores the NULL rolw, which is why COUNT (Sales) =
3.
SQL ISNULL
The ISNULL function is available in both SQL Server and MySQL. However, their uses are
different:

SQL Server:
In SQL Server, the ISNULL() function is used to replace NULL value with another value.

Example:
Table Structure and Data: Sales_Data
Store_name Sales
Store A $300
Store B NULL

Query:
SELECT SUM(ISNULL(Sales,100)) FROM Sales_Data

Result:
SUM(Sales)
$400

This is because NULL has been replaced by 100 via the ISNULL function.

MySQL
In MySQL, the ISNULL() function is used to test whether an expression is NULL. If the expression is
NULL, this function returns 1. Otherwise, this function returns 0.

For example,
ISNULL(3*3) returns 0
ISNULL(3/0) returns 1
SQL IFNULL
SQL ifnull() function is used find null value in rows and returns value on our condition if null value found in
column from database table name, otherwise if column value is not null it will return column value.

Example:
Table Structure and Data: Sales_Data
Store_name Sales
Store A $300
Store B NULL

Query:
SELECT SUM(IFNULL(Sales,100)) FROM Sales_Data

Result:
SUM(Sales)
$400

SQL NVL
The NVL() function is available in Oracle, and not in MySQL or SQL Server. This function is used
to replace NULL value with another value. It is similar to the IFNULL Function in MySQL and the ISNULL
Function in SQL Server.

Example:
Table Structure and Data: Sales_Data
Store_name Sales
Store A $300
Store B NULL

Query:
SELECT SUM(NVL(Sales,100)) FROM Sales_Data

Result:
SUM(Sales)
$400
SQL COALESCE:
The COALESCE function in SQL returns the first non-NULL expression among its arguments. It is
same as CASE statement in SQL.

Syntax:
SELECT COALESCE(column_name EXPR1,column_name EXPR2,column_name EXPR3...)
coalesce_column_name FROM table_name

Example:
Table Structure and Data: Contact_Info
Name Business_Phone Cell_Phone Home_Phone
Jeff Thomas 732-784-3455 923-234-5645 762-234-3452
Robert Lu 234-345-6457 NULL 356-478-2562
James Martin NULL 478-917-2896 NULL
Young Bright NULL NULL 767-926-2345

Our goal is to find out the best way to contact each person according to the following rules:
1. If a person has a business phone, use the business phone number.
2. If a person does not have a business phone and has a cell phone, use the cell phone number.
3. If a person does not have a business phone, does not have a cell phone, and has a home phone,
use the home phone number.

We can use the COALESCE function to achieve our goal:

Query:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone
FROM Contact_Info

Result:
Name Contact_Phone
Jeff Thomas 732-784-3455
Robert Lu 234-345-6457
James Martin 478-917-2896
Young Bright 767-926-2345
SQL NULLIF
The NULLIF function takes two arguments. If the two arguments are equal, then NULL is
returned. Otherwise, the first argument is returned. It is the same as CASE statement in SQL.

Syntax:
SELECT Column_name1, NULLIF(column_name2 exp1,column_name2 exp2) FROM table_name

Example:
Table structure and Data: Sales_Data
Store_name Actual Goal
Store A 50 30
Store B 20 20
Store C 30 40
Store D 80 80

Our goal is to show NULL if actual sales is equal to sales goal, and show actual sales if the two are
different.

Query:
SELECT Store_name, NULLIF(Actual,Goal) FROM Sales_Data

Result:
Store_name NULLIF(Actual,Goal)
Store A 50
Store B NULL
Store C 30
Store D NULL
SQL Rank
Displaying the rank associated with each row is a common request, and there is no
straightforward way to do so in SQL. To display rank in SQL, the idea is to do a self-join, list out the
results in order, and do a count on the number of records that's listed ahead of (and including) the record
of interest.

Example:
Table Structure and Data: Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophie 40
Greg 50
Jeff 20
Query:
SELECT a1.Name, a1.Sales, COUNT(a2.sales) Sales_Rank FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.Sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) GROUP BY a1.Name,
a1.Sales ORDER BY a1.Sales DESC, a1.Name DESC

Result:
Name Sales Sales_Rank
Greg 50 1
Sophie 40 2
Stella 20 3
Jeff 20 3
Jennifer 15 5
John 10 6

Let's focus on the WHERE clause. The first part of the clause, (a1.Sales <= a2.Sales), makes sure we
are only counting the number of occurrences where the value in the Sales column is less than or equal to
itself. If there are no duplicate values in the Sales column, this portion of the WHERE clause by itself
would be sufficient to generate the correct ranking.

The second part of the clause, (a1.Sales=a2.Sales and a1.Name = a2.Name), ensures that when there
are duplicate values in the Sales column, each one would get the correct rank.
SQL Median
To get the median, we need to be able to accomplish the following:
 Sort the rows in order and find the rank for each row.
 Determine what is the "middle" rank. For example, if there are 9 rows, the middle rank would be
5.
 Obtain the value for the middle-ranked row.

Example:
Table Structure and Data: Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophie 40
Greg 50
Jeff 20
Query:
SELECT Sales Median FROM (SELECT a1.Name, a1.Sales, COUNT(a1.Sales) Rank FROM Total_Sales
a1, Total_Sales a2 WHERE a1.Sales < a2.Sales OR (a1.Sales=a2.Sales AND a1.Name <= a2.Name)
group by a1.Name, a1.Sales order by a1.Sales desc) a3 WHERE Rank = (SELECT (COUNT(*)+1) DIV 2
FROM Total_Sales)

Result:
Median
20

You will find that Lines 2-6 are the same as how we find the rank of each row. Line 7 finds the "middle"
rank. DIV is the way to find the quotient in MySQL, the exact way to obtain the quotient may be different
with other databases. Finally, Line 1 obtains the value for the middle-ranked row.
SQL Running Totals
Displaying running totals is a common request, and there is no straightforward way to do so in
SQL. The idea for using SQL to display running totals similar to that for displaying rank: first do a self-join,
then, list out the results in order. Where as finding the rank requires doing a count on the number of
records that's listed ahead of (and including) the record of interest, finding the running total requires
summing the values for the records that's listed ahead of (and including) the record of interest.

Example:
Table Structure and Data: Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophie 40
Greg 50
Jeff 20

Query:
SELECT a1.Name, a1.Sales, SUM(a2.Sales) Running_Total FROM Total_Sales a1, Total_Sales a2
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) GROUP BY a1.Name,
a1.Sales ORDER BY a1.Sales DESC, a1.Name DESC

Result:
Name Sales Running_Total
Greg 50 50
Sophie 40 90
Stella 20 110
Jeff 20 130
Jennifer 15 145
John 10 155

The combination of the WHERE clause and the ORDER BY clause ensure that the proper running totals
are tabulated when there are duplicate values.
SQL Percent to Total
To display percent to total in SQL, we want to leverage the ideas we used for rank/running total
plus subquery. Different from what we saw in the SQL Subquery section, here we want to use the
subquery as part of the SELECT.

Example:
Table Structure and Data: Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophie 40
Greg 50
Jeff 20

Query:
SELECT a1.Name, a1.Sales, a1.Sales/(SELECT SUM(Sales) FROM Total_Sales) Pct_To_Total FROM
Total_Sales a1, Total_Sales a2 WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name =
a2.Name) GROUP BY a1.Name, a1.Sales ORDER BY a1.Sales DESC, a1.Name DESC

Result:
Name Sales Running_Total
Greg 50 0.3226
Sophie 40 0.2581
Stella 20 0.1290
Jeff 20 0.1290
Jennifer 15 0.0968
John 10 0.0645

The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide the
individual values by this sum to obtain the percent to total for each row.
SQL Cumulative Percent to Total
To display cumulative percent to total in SQL, we use the same idea as we saw in the Percent To
Total section. The difference is that we want the cumulative percent to total, not the percentage
contribution of each individual row.
Example:
Table Structure and Data: Total_Sales
Name Sales
John 10
Jennifer 15
Stella 20
Sophie 40
Greg 50
Jeff 20

Query:
SELECT a1.Name, a1.Sales, SUM(a2.Sales)/(SELECT SUM(Sales) FROM Total_Sales) Pct_To_Total
FROM Total_Sales a1, Total_Sales a2 WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and
a1.Name = a2.Name) GROUP BY a1.Name, a1.Sales ORDER BY a1.Sales DESC, a1.Name DESC

Result:
Name Sales Running_Total
Greg 50 0.3226
Sophie 40 0.5806
Stella 20 0.7097
Jeff 20 0.8387
Jennifer 15 0.9335
John 10 1.0000

The subquery "SELECT SUM(Sales) FROM Total_Sales" calculates the sum. We can then divide the
running total, "SUM(a2.Sales)", by this sum to obtain the cumulative percent to total for each row.

You might also like