SQL Materijali I Nasoki
SQL Materijali I Nasoki
What is SQL?
Most of the SQL database programs also have their own proprietary
extensions in addition to the SQL standard!
To build a web site that shows data from a database, you will need:
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.
SQL Syntax
Database Tables
CustomerI ContactNam
CustomerName Address City PostalCode Country
D e
1 Alfreds Maria Obere Str. Germa
Berlin 12209
Futterkiste Anders 57 ny
Ana Trujillo Avda. de la
Ana México
2 Emparedados Constitució 05021 Mexico
Trujillo D.F.
y helados n 2222
Antonio
Antonio Mataderos México
3 Moreno 05023 Mexico
Moreno 2312 D.F.
Taquería
120
4 Around the Thomas Londo
Hanover WA1 1DP UK
Horn Hardy n
Sq.
Berglunds Christina Berguvsvä Swede
5 Luleå S-958 22
snabbköp Berglund gen 8 n
The table above contains five records (one for each customer) and
seven columns (CustomerID, CustomerName, ContactName, Address,
City, PostalCode, and Country).
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:
and
SELECT * Example
The following SQL statement selects all the columns from the
"Customers" table:
Navigation in a Result-set
The following SQL statement selects only the distinct values from the
"City" columns from the "Customers" table:
The WHERE clause is used to extract only those records that fulfill a
specified criterion.
The following SQL statement selects all the customers from the
country "Mexico", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
SQL requires single quotes around text values (most database systems
will also allow double quotes).
However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Operator Description
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN To specify multiple possible values for a column
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 are true.
The following SQL statement selects all customers from the country
"Germany" AND the city "Berlin", in the "Customers" table:
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 "München", in the "Customers" table:
Example
SELECT * FROM Customers
WHERE City='Berlin'
OR City='München';
You can also combine AND and OR (use parenthesis to form complex
expressions).
The following SQL statement selects all customers from the country
"Germany" AND the city must be equal to "Berlin" OR "München", in
the "Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Germany'
AND (City='Berlin' OR City='München');
Example
SELECT * FROM Customers
ORDER BY Country;
Example
SELECT * FROM Customers
ORDER BY Country DESC;
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
The first form does not specify the column names where the data will
be inserted, only their values:
The second form specifies both the column names and the values to be
inserted:
Example
INSERT INTO Customers (CustomerName, ContactName, Address,
City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen
21','Stavanger','4006','Norway');
Note: Did you notice that we did not insert any number into the
CustomerID field?
The CustomerID column is automatically updated with a unique
number for each record in the table.
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';
Update Warning!
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg';
SQL DELETE Statement
Example
DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria
Anders';
or
SQL Injection
Since SQL statements are text only, it is easy, with a little piece of
computer code, to dynamically change SQL statements to provide the
user with selected data:
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
The rest of this chapter describes the potential dangers of using user
input in SQL statements.
SQL Injection
Injected SQL commands can alter SQL statement and compromise the
security of a web application.
UserId:
105 or 1=1
UserId:
Server Result
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?
A smart hacker might get access to all the user names and passwords
in a database by simply inserting 105 or 1=1 into the input box.
User Name:
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.
Example
SELECT * FROM Users; DROP TABLE Suppliers
The SQL above will return all rows in the Users table, and then delete
the table called Suppliers.
Server Code
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
User id:
The code at the server would create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers
This is not a very good idea. Many of these words (like delete or drop)
and characters (like semicolons and quotation marks), are used in
common language, and should be allowed in many types of input.
The only proven way to protect a web site from SQL injection attacks,
is to use SQL parameters.
The SQL engine checks each parameter to ensure that it is correct for
its column and are treated literally, and not as part of the SQL to be
executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
Note: You have just learned to avoid SQL injection. One of the top
website vulnerabilities.
Examples
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
The SELECT TOP clause can be very useful on large tables with
thousands of records. Returning a large number of records can impact
on performance.
Note: Not all database systems support the SELECT TOP clause.
MySQL Syntax
SELECT column_name(s)
FROM table_name
LIMIT number;
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;
The following SQL statement selects the two first records from the
"Customers" table:
Example
SELECT TOP 2 * FROM Customers;
The following SQL statement selects the first 50% of the records from
the "Customers" table:
Example
SELECT TOP 50 PERCENT * FROM Customers;
The following SQL statement selects all customers with a City starting
with the letter "s":
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":
Example
SELECT * FROM Customers
WHERE City LIKE '%s';
Using the NOT keyword allows you to select records that do NOT
match the pattern.
The following SQL statement selects all customers with Country NOT
containing the pattern "land":
Example
SELECT * FROM Customers
WHERE Country NOT LIKE '%land%';
SQL Wildcards
In SQL, wildcard characters are used with the SQL LIKE operator.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for a single character
[charlist] Sets and ranges of characters to match
[^charlist]
Matches only a character NOT specified
or
within the brackets
[!charlist]
The following SQL statement selects all customers with a City starting
with "ber":
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
The following SQL statement selects all customers with a City starting
with any character, followed by "erlin":
Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';
The following SQL statement selects all customers with a City starting
with "L", followed by any character, followed by "n", followed by any
character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
The following SQL statement selects all customers with a City starting
with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting
with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
The following SQL statement selects all customers with a City NOT
starting with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
or
SQL IN Operator
The IN Operator
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...);
IN Operator Example
Example
SELECT * FROM Customers
WHERE City IN ('Paris','London');
The BETWEEN operator selects values within a range. The values can
be numbers, text, or dates.
The following SQL statement selects all products with a price BETWEEN
10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use
NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
The following SQL statement selects all products with a price BETWEEN
10 and 20, but products with a CategoryID of 1,2, or 3 should not be
displayed:
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';
Example
SELECT * FROM Orders
WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
SQL Aliases
SQL Aliases
The following SQL statement specifies two aliases, one for the
CustomerName column and one for the ContactName column. Tip: It
requires double quotation marks or square brackets if the column
name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS [Contact
Person]
FROM Customers;
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+',
'+Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the
following:
The following SQL statement selects all the orders from the customer
with CustomerID=4 (Around the Horn). We use the "Customers" and
"Orders" tables, and give them the table aliases of "c" and "o"
respectively (Here we have used aliases to make the SQL shorter):
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;
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
WHERE Customers.CustomerName="Around the Horn" AND
Customers.CustomerID=Orders.CustomerID;
SQL Joins
SQL joins are used to combine rows from two or more tables.
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 returns all rows from multiple tables where the
join condition is met.
INNER 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