SQL is a standard computer language for accessing and manipulating
databases.
A Database Management System (DBMS) is a computer program that can access data in a database.The
DBMS program enables you to extract, modify, or store information in a database.A Relational
Database Management System (RDBMS) is a Database Management System (DBMS) where the
database is organized and accessed according to the relationships between data.
SQL Data Manipulation Language (DML)
• SELECT - extracts data from a database table
• UPDATE - updates data in a database table
• DELETE - deletes data from a database table
• INSERT INTO - inserts new data into a database table
SQL Data Definition Language (DDL)
• CREATE TABLE - creates a new database table
• ALTER TABLE - alters (changes) a database table
• DROP TABLE - deletes a database table
• CREATE INDEX - creates an index (search key)
• DROP INDEX - deletes an index
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.
The SELECT DISTINCT keyword is used to return only distinct (different) values.
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 versions of SQL the <> operator may be written as !=
1
SQL uses single quotes around text values (most database systems will also accept
double quotes). Numeric values should not be enclosed in quotes.
A "%" sign can be used to define wildcards (missing letters in the pattern) both
before and after the pattern.
The following SQL statement will return persons with first names that contain the pattern 'la':
SELECT * FROM Persons
WHERE FirstName LIKE '%la%'
SELECT column_name(s)
FROM table_name
SELECT column FROM table
WHERE column operator value
INSERT INTO table_name
VALUES (value1, value2,....)
You can also specify the columns for which you want to insert data:
INSERT INTO table_name (column1, column2,...)
VALUES (value1, value2,....)
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value
DELETE FROM table_name
WHERE column_name = some_value
Delete All Rows
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name
or
DELETE * FROM table_name
2
SELECT CompanyName, ContactName FROM customers WHERE CompanyName > 'a'
When using SQL on text data, "alfred" is greater than "a" (like in a dictionary).
The ORDER BY clause is used to sort the rows.
To display the company names in reverse alphabetical order AND the OrderNumber in numerical
order:
SELECT Company, OrderNumber FROM Orders
ORDER BY Company DESC, OrderNumber ASC
Result:
Company OrderNumber
W3Schools 2312
W3Schools 6798
Sega 3412
ABC Shop 5678
The IN operator may be used if you know the exact value you want to return for at least one of
the columns.
SELECT column_name FROM table_name
WHERE column_name IN (value1,value2,..)
The BETWEEN ... AND operator selects a range of data between two values. These values can
be numbers, text, or dates.
SELECT column_name FROM table_name
WHERE column_name
BETWEEN value1 AND value2
To display the persons alphabetically between (and including) "Hansen" and exclusive
"Pettersen", use the following SQL:
SELECT * FROM Persons WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
IMPORTANT! The BETWEEN...AND operator is treated differently in different
databases. With some databases a person with the LastName of "Hansen" or
3
"Pettersen" will not be listed (BETWEEN..AND only selects fields that are between
and excluding the test values). With some databases a person with the last name of
"Hansen" or "Pettersen" will be listed (BETWEEN..AND selects fields that are
between and including the test values). With other databases a person with the last
name of "Hansen" will be listed, but "Pettersen" will not be listed (BETWEEN..AND
selects fields between the test values, including the first test value and excluding
the last test value). Therefore: Check how your database treats the BETWEEN....AND
operator!
To display the persons outside the range used in the previous example, use the NOT operator:
SELECT * FROM Persons WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
Result:
LastName FirstName Address City
Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes
With SQL, aliases can be used for column names and table names.
Column Name Alias
The syntax is:
SELECT column AS column_alias FROM table
Table Name Alias
The syntax is:
SELECT column FROM table AS table_alias
Employees:
Employee_ID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
4
04 Pettersen, Kari
Orders:
Prod_ID Product Employee_ID
234 Printer 01
657 Table 03
865 Chair 03
5
Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
Example
Who ordered a printer?
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.Employee_ID=Orders.Employee_ID
AND Orders.Product='Printer'
Result
Name
Hansen, Ola
OR we can select data from two tables with the JOIN keyword, like this:
Example INNER JOIN
Syntax
SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
6
Who has ordered a product, and what did they order?
SELECT Employees.Name, Orders.Product
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
The INNER JOIN returns all rows from both tables where there is a match. If there are rows in
Employees that do not have matches in Orders, those rows will not be listed.
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
LEFT JOIN
Syntax
SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
The LEFT JOIN returns all the rows from the first table (Employees), even if there are
no matches in the second table (Orders). If there are rows in Employees that do not
have matches in Orders, those rows also will be listed.
SELECT Employees.Name, Orders.Product
FROM Employees
LEFT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
Result
Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari
7
RIGHT JOIN
The RIGHT JOIN returns all the rows from the second table (Orders), even if there are
no matches in the first table (Employees). If there had been any rows in Orders that
did not have matches in Employees, those rows also would have been listed.
SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table
ON first_table.keyfield = second_table.foreign_keyfield
List all orders, and who has ordered - if any.
SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
Result
Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair
Who ordered a printer?
SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
WHERE Orders.Product = 'Printer'
Result
Name
Hansen, Ola
UNION
The UNION command is used to select related information from two tables, much like the JOIN
command. However, when using the UNION command all selected columns need to be of the
same data type.
8
Note: With UNION, only distinct values are selected.
SQL Statement 1
UNION
SQL Statement 2
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects
all values.
Create a Database
To create a database:
CREATE DATABASE database_name
Create a Table
To create a table in a database:
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
.......
)
The data type specifies what type of data the column can hold. The table below contains the most
common data types in SQL:
Data Type Description
integer(size) Hold integers only. The maximum number of digits are specified in
int(size) parenthesis.
smallint(size)
tinyint(size)
decimal(size,d) Hold numbers with fractions. The maximum number of digits are
numeric(size,d) specified in "size". The maximum number of digits to the right of
the decimal is specified in "d".
char(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis.
varchar(size) Holds a variable length string (can contain letters, numbers, and
9
special characters). The maximum size is specified in parenthesis.
date(yyyymmdd) Holds a date
Create Index
Indices are created in an existing table to locate rows more quickly and efficiently. It is possible
to create an index on one or more columns of a table, and each index is given a name. The users
cannot see the indexes, they are just used to speed up queries.
Note: Updating a table containing indexes takes more time than updating a table without, this is
because the indexes also need an update. So, it is a good idea to create indexes only on columns
that are often used for a search.
A Unique Index
Creates a unique index on a table. A unique index means that two rows cannot have the same
index value.
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
The "column_name" specifies the column you want indexed.
Example
This example creates a simple index, named "PersonIndex", on the LastName field of the Person
table:
CREATE INDEX PersonIndex
ON Person (LastName)
If you want to index the values in a column in descending order, you can add the reserved word
DESC after the column name:
CREATE INDEX PersonIndex
ON Person (LastName DESC)
If you want to index more than one column you can list the column names within the
parentheses, separated by commas:
CREATE INDEX PersonIndex
ON Person (LastName, FirstName)
10
You can delete an existing index in a table with the DROP INDEX statement.
Syntax for MySQL:
ALTER TABLE table_name DROP INDEX index_name
To delete a table (the table structure, attributes, and indexes will also be
deleted):
DROP TABLE table_name
To delete a database:
DROP DATABASE database_name
if we only want to get rid of the data inside a table, and not the table
itself? Use the TRUNCATE TABLE command (deletes only the data inside the
table):
TRUNCATE TABLE table_name
The ALTER TABLE statement is used to add or drop columns in an existing
table.
ALTER TABLE table_name *
*ADD column_name datatype
ALTER TABLE table_name *
*DROP COLUMN column_name
Aggregate functions operate against a collection of values, but return a
single value.
Aggregate functions in SQL Server
Function Description
AVG(column) Returns the average value of a column
BINARY_CHECKSUM
CHECKSUM
CHECKSUM_AGG
COUNT(column) Returns the number of rows (without a NULL value) of a
column
COUNT(*) Returns the number of selected rows
11
COUNT(DISTINCT column) Returns the number of distinct results
FIRST(column) Returns the value of the first record in a specified field
(not supported in SQLServer2K)
LAST(column) Returns the value of the last record in a specified field
(not supported in SQLServer2K)
MAX(column) Returns the highest value of a column
MIN(column) Returns the lowest value of a column
STDEV(column)
STDEVP(column)
SUM(column) Returns the total sum of a column
VAR(column)
VARP(column)
SELECT FIRST(Age) AS lowest_age
FROM Persons
ORDER BY Age
SELECT LAST(Age) AS highest_age
FROM Persons
ORDER BY Age
Aggregate functions (like SUM) often need an added GROUP BY
functionality.
GROUP BY...
GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of
all column values every time they are called, and without the GROUP BY function it was
impossible to find the sum for each individual group of column values.
The syntax for the GROUP BY function is:
12
SELECT column,SUM(column) FROM table GROUP BY column
GROUP BY Example
This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
And This SQL:
SELECT Company, SUM(Amount) FROM Sales
Returns this result:
Company SUM(Amount)
W3Schools 17100
IBM 17100
W3Schools 17100
The above code is invalid because the column returned is not part of an aggregate. A GROUP BY
clause will solve this problem:
SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company
Returns this result:
Company SUM(Amount)
W3Schools 12600
IBM 4500
HAVING...
HAVING... was added to SQL because the WHERE keyword could not be used against
aggregate functions (like SUM), and without HAVING... it would be impossible to test for result
conditions.
13
The syntax for the HAVING function is:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value
This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
This SQL:
SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company
HAVING SUM(Amount)>10000
Returns this result
Company SUM(Amount)
W3Schools 12600
The SELECT INTO Statement
The SELECT INTO statement is most often used to create backup copies of tables or for
archiving records.
Syntax
SELECT column_name(s) INTO newtable [IN externaldatabase]
FROM source
Make a Backup Copy
The following example makes a backup copy of the "Persons" table:
SELECT * INTO Persons_backup
FROM Persons
14
The IN clause can be used to copy tables into another database:
SELECT Persons.* INTO Persons IN 'Backup.mdb'
FROM Persons
If you only want to copy a few fields, you can do so by listing them after the SELECT statement:
SELECT LastName,FirstName INTO Persons_backup
FROM Persons
You can also add a WHERE clause. The following example creates a "Persons_backup" table
with two columns (FirstName and LastName) by extracting the persons who lives in "Sandnes"
from the "Persons" table:
SELECT LastName,Firstname INTO Persons_backup
FROM Persons
WHERE City='Sandnes'
Selecting data from more than one table is also possible. The following example creates a new
table "Empl_Ord_backup" that contains data from the two tables Employees and Orders:
SELECT Employees.Name,Orders.Product
INTO Empl_Ord_backup
FROM Employees
INNER JOIN Orders
ON Employees.Employee_ID=Orders.Employee_ID
SQL CREATE VIEW Statement
A view is a virtual table based on the result-set of a SELECT statement.
What is a View?
In SQL, a VIEW is a virtual table based on the result-set of a SELECT statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one
or more real tables in the database. You can add SQL functions, WHERE, and JOIN statements
to a view and present the data as if the data were coming from a single table.
Note: The database design and structure will NOT be affected by the functions, where, or join
statements in a view.
15
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: The database does not store the view data! The database engine recreates the data, using
the view's SELECT statement, every time a user queries a view.
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName,UnitPrice
FROM Products
WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego
Example 1:
MySQL/Oracle:
SELECT CONCAT(region_name,store_name) FROM Geography
WHERE store_name = 'Boston';
Result:
'EastBoston'
Example 2:
Oracle:
SELECT region_name || ' ' || store_name FROM Geography
WHERE store_name = 'Boston';
Result:
'East Boston'
16
The '%' is a so called wildcard character and represents any string in our pattern.
Note that different databases use different characters as wildcard characters, for example '%' is a wildcard
character for MS SQL Server representing any string, and '*' is the corresponding wildcard character used
in MS Access.
Another wildcard character is '_' representing any single character.
The '[]' specifies a range of characters. Have a look at the following SQL statement:
SELECT *
FROM Customers
WHERE Phone LIKE '[4-6]_6%'
This SQL expression will return all customers satisfying the following conditions:
• The Phone column starts with a digit between 4 and 6 ([4-6])
• Second character in the Phone column can be anything (_)
• The third character in the Phone column is 6 (6)
• The remainder of the Phone column can be any character string (%)
create user ECI2_BARCAP_STAG_US identified by BARCAP
grant create session , create table, create view, create sequence to ECI2_BARCAP_STAG_US
alter user ECI2_BARCAP_STAG_US quota unlimited on system
GRANT CREATE PROCEDURE TO ECI2_BARCAP_STAG_US
17