SQL For Better Study
SQL For Better Study
What is SQL?
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as 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.
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g.
"Customers" or "Orders"). Tables contain records (rows) with data. In this tutorial we will use the
well-known North wind sample database (included in MS Access and MS SQL Server).
ustom CustomerName
erID
ContactName
Address
City
PostalC Country
ode
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Germany
Ana Trujillo
Emparedados y helados
Ana Trujillo
Avda. de la
Constitucin
Mxico D.F.
05021
Mexico
2
2222
3
Antonio Moreno
Mataderos
2312
Mxico D.F.
05023
Mexico
Thomas Hardy
120 Hanover
Sq.
London
WA1
1DP
UK
Berglunds snabbkp
Christina Berglund
Berguvsvgen Lule
8
S-958
22
Sweden
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements.The following
SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
SQL is NOT case sensitive: select is the same as SELECT In this tutorial we will write all SQL
keywords in upper-case.
Example
SELECT CustomerName,City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
Example
SELECT DISTINCT City FROM Customers;
Example
SELECT * FROM Customers
WHERE Country='Mexico';
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Description
Equal
<>
Not equal. Note: In some versions of SQL this operator may be written as !=
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
IN
5
The AND operator displays a record if both the first condition AND the second condition are true.The
OR operator displays a record if either the first condition OR the second condition is true.
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND City='Berlin';
OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "Mnchen", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='Mnchen';
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='Mnchen');
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Example
SELECT * FROM Customers
ORDER BY Country,CustomerName;
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
7
The following SQL statement will insert a new row, but only insert data in the "CustomerName",
"City", and "Country" columns (and the CustomerID field will of course also be updated
automatically):
Example
INSERT INTO Customers (CustomerName, City, Country)
VALUES ('Cardinal', 'Stavanger', 'Norway');
Example
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';
8
DELETE FROM table_name;
or
DELETE * FROM table_name;
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The example above, creates a select statement by adding a variable (txtUserId) to a select string.
The variable is fetched from the user input (Request) to the page.
The rest of this chapter describes the potential dangers of using user input in SQL statements.
SQL Injection
SQL injection is a technique where malicious users can inject SQL commands into an SQL statement,
via web page input.
Injected SQL commands can alter SQL statement and compromise the security of a web application.
Server Result
SELECT * FROM Users WHERE UserId = 105 or 1=1
The SQL above is valid. It will return all rows from the table Users, since WHERE 1=1 is always
true.
Does the example above seem dangerous? What if the Users table contains names and passwords?
The SQL statement above is much the same as this:
9
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1
Password:
Server Code
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Users WHERE Name ='" + uName + "' AND Pass ='" + uPass + "'"
A smart hacker might get access to user names and passwords in a database by simply inserting " or
""=" into the user name or password text box.
The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
The result SQL is valid. It will return all rows from the table Users, since WHERE ""="" is always
true.
10
Example
SELECT *
FROM Persons
LIMIT 5;
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5;
Example
SELECT TOP 2 * FROM Customers;
Example
SELECT TOP 50 PERCENT * FROM Customers;
Example
SELECT * FROM Customers
WHERE City LIKE 's%';
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern. You
will learn more about wildcards in the next chapter.
The following SQL statement selects all customers with a City ending with the letter "s":
11
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
The following SQL statement selects all customers with a Country containing the pattern "land":
Example
SELECT * FROM Customers
WHERE Country LIKE '%land%';
Using the NOT keyword allows you to select records that does NOT match the pattern.
The following SQL statement selects all customers with a Country NOT containing the pattern "land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
Description
[charlist]
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
12
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
IN Operator Example
The following SQL statement selects all customers with a City of "Paris" or "London":
Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
Example
13
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
Example
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'C' AND 'M';
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'C' AND 'M';
SQL aliases are used to temporarily rename a table or a column heading
SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
Example
14
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
In the following SQL statement we combine four columns (Address, City, PostalCode, and Country)
and create an alias named "Address":
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address
FROM Customers;
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName="Around the Horn" AND c.CustomerID=o.CustomerID;
The same SQL statement without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the Horn" AND
Customers.CustomerID=Orders.CustomerID;
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER
JOIN return all rows from multiple tables where the join condition is met.
Let's look at a selection from the "Orders" table:
OrderID
CustomerID
OrderDate
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
CustomerName
ContactName
Country
Alfreds Futterkiste
Maria Anders
Germany
Ana Trujillo
Mexico
Antonio Moreno
Mexico
15
Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.
Then, if we run the following SQL statement (that contains an INNER JOIN):
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
it will produce something like this:
OrderID
CustomerName
OrderDate
10308
9/18/1996
10365
11/27/1996
10383
12/16/1996
10355
11/15/1996
10278
Berglunds snabbkp
8/12/1996
NNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
16
Demo Database
In this tutorial we will use the well-known Northwind sample database.Below is a selection from the
"Customers" table:
C us id
CustomerName
ContactName Address
City
PostalCode Count
Alfreds Futterkiste
Maria Anders
Obere Str.
57
Berlin
12209
Germa
Ana Trujillo
Mexico
Antonio
Moreno
Mataderos
2312
Mexico
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
17
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
Customer CustomerName
ID
ContactName
Address
City
PostalCode Cou
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Ger
Ana Trujillo
Emparedados y
helados
Ana Trujillo
Avda. de la
Constitucin
2222
Mxico
D.F.
05021
Mex
Antonio Moreno
Taquera
Antonio Moreno
Mataderos 2312
Mxico
D.F.
05023
Mex
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
18
10309
37
1996-09-19
10310
77
1996-09-20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
19
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
Photo
Notes
Davolio
Nancy
12/8/1968
EmpID1.pic
Fuller
Andrew
2/19/1952
EmpID2.pic
Leverling
Janet
8/30/1963
EmpID3.pic
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;
20
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
Demo Database
In this tutorial we will use the well-known Northwind sample database.Below is a selection from the
"Customers" table:
CustomerID CustomerName
ContactName Address
City
PostalCod
e
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin
2222
Mxico
D.F.
05021
Mataderos
2312
Mxico
D.F.
05023
Antonio
Moreno
CustomerID
EmployeeID
OrderDate
ShipperID
10308
1996-09-18
10309
37
1996-09-19
10310
77
1996-09-20
21
OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados
10308
10365
10382
10351
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all
the rows from the right table (Orders). If there are rows in "Customers" that do not have matches in
"Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will
be listed as well.
The SQL UNION operator combines the result of two or more SELECT statements.
22
Demo Database
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
CustomerID
CustomerName
ContactName Address
City
PostalCode C
Alfreds Futterkiste
Maria Anders
Obere Str. 57
Berlin
12209
Avda. de la
Constitucin 2222
Mxico
D.F.
05021
Mataderos 2312
Mxico
D.F.
05023
Antonio
Moreno
SupplierName
ContactName
Address
City
PostalCod
e
Exotic Liquid
Charlotte
Cooper
49 Gilbert St.
Londona
EC1 4SD
Shelley Burke
P.O. Box
78934
New
Orleans
70117
Grandma Kelly's
Homestead
Regina Murphy
707 Oxford
Rd.
Ann Arbor
48104
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Note: UNION cannot be used to list ALL cities from the two tables. If several customers and
suppliers share the same city, each city will only be listed once. UNION selects only distinct values.
Use UNION ALL to also select duplicate values!
23
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
With SQL, you can copy information from one table into another.
The SELECT INTO statement copies data from one table and inserts it into a new table.
24