Using Advanced Structured Query Language
Using Advanced Structured Query Language
Based on
Ethiopian Occupational Standard (EOS)
MODULE DESCRIPTION: This unit covers the skills, knowledge and attitudes required to
use advanced structured query language (SQL) to define, create and manipulate
database structures and associated data in a relational database.
LEARNING OUTCOMES:
The TOP clause can be very useful on large tables with thousands of records.
Returning a large number of records can impact on performance.
FROM table_name
Now we want to select only the two first records in the table above.
Timoteivn
1 Hansen Ola Sandnes
10
Now we want to select only 50% of the records in the table above.
The LIKE operator is used in a WHERE clause to search for a specified pattern in
a column.
SELECT column_name(s)
FROM table_name
Now we want to select the persons living in a city that starts with "s" from the
table above.
The "%" sign can be used to define wildcards (missing letters in the pattern) both
before and after the pattern.
Using Advanced Structured Query Language
The result-set will look like this:
Next, we want to select the persons living in a city that ends with an "s" from the
"Persons" table.
Timoteivn
1 Hansen Ola Sandnes
10
Next, we want to select the persons living in a city that contains the pattern "tav"
from the "Persons" table.
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.
Timoteivn
1 Hansen Ola Sandnes
10
SQL Wildcards
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data
in a database.
Description
Wildcard
or
[!charlist]
Now we want to select the persons living in a city that starts with "sa" from the
"Persons" table.
Next, we want to select the persons living in a city that contains the pattern "nes"
from the "Persons" table.
Now we want to select the persons with a first name that starts with any
character, followed by "la" from the "Persons" table.
Now we want to select the persons with a last name that starts with "b" or "s" or
"p" from the "Persons" table.
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.
SQL IN Operator
The IN Operator
SQL IN Syntax
SELECT column_name(s)
FROM table_name
IN Operator Example
The BETWEEN operator selects a range of data between two values. The values
can be numbers, text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name
Now we want to select the persons with a last name alphabetically between
"Hansen" and "Pettersen" from the table above.
WHERE LastName
Timoteivn
1 Hansen Ola Sandnes
10
Example 2
To display the persons outside the range in the previous example, use NOT
BETWEEN:
WHERE LastName
SQL Alias
SQL Alias
You can give a table or a column another name by using an alias. This can be a
good thing to do if you have very long or complex table names or column names.
SELECT column_name(s)
FROM table_name
AS alias_name
FROM table_name
Alias Example
Now we want to list all the orders that "Ola Hansen" is responsible for.
FROM Persons AS p,
Product_Orders AS po
WHERE p.LastName='Hansen'
WHERE p.FirstName='Ola'
FROM Persons,
Product_Orders
WHERE Persons.LastName='Hansen'
WHERE Persons.FirstName='Ola'
As you'll see from the two SELECT statements above; aliases can make queries
easier to both write and to read.
SQL Joins
SQL joins are used to query data from two or more tables, based on a
relationship between certain columns in these tables.
SQL JOIN
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.
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.
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.
Before we continue with examples, we will list the types of JOIN you can use,
and the differences between them.
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no
matches in the right table
RIGHT 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
The INNER JOIN keyword return rows when there is at least one match in both
tables.
Using Advanced Structured Query Language
SQL INNER JOIN Syntax
SELECT column_name(s)
FROM table_name1
ON table_name1.column_name=table_name2.column_name
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
FROM Persons
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
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.
The LEFT JOIN keyword returns all rows from the left table (table_name1), even
if there are no matches in the right table (table_name2).
SELECT column_name(s)
FROM table_name1
Timoteivn
1 Hansen Ola Sandnes
10
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders - if any, from the tables
above.
FROM Persons
ORDER BY Persons.LastName
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).
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).
SELECT column_name(s)
FROM table_name1
ON table_name1.column_name=table_name2.column_name
"Orders" table:
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the orders with containing persons - if any, from the
tables above.
FROM Persons
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
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).
The FULL JOIN keyword return rows when there is a match in one of the tables.
SELECT column_name(s)
FROM table_name1
ON table_name1.column_name=table_name2.column_name
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders, and all the orders with their
persons.
FROM Persons
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
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.
The UNION operator is used to combine the result-set of two or more SELECT
statements.
Notice that each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types. Also, the
columns in each SELECT statement must be in the same order.
UNION
Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
UNION ALL
"Employees_Norway":
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
"Employees_USA":
E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen
Now we want to list all the different employees in Norway and USA.
UNION
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and USA. In
the example above we have two employees with equal names, and only one of
them will be listed. The UNION command selects only distinct values.
UNION ALL
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
The SQL SELECT INTO statement can be used to create backup copies of
tables.
The SELECT INTO statement selects data from one table and inserts it into a
different table.
The SELECT INTO statement is most often used to create backup copies of
tables.
SELECT *
FROM old_tablename
Or we can select only the columns we want into the new table:
SELECT column_name(s)
FROM old_tablename
Make a Backup Copy - Now we want to make an exact copy of the data in our
"Persons" table.
SELECT *
INTO Persons_Backup
FROM Persons
We can also use the IN clause to copy the table into another database:
SELECT *
FROM Persons
We can also copy only a few fields into the new table:
SELECT LastName,FirstName
INTO Persons_Backup
FROM Persons
The following SQL statement creates a "Persons_Backup" table with only the
persons who lives in the city "Sandnes":
SELECT LastName,Firstname
FROM Persons
WHERE City='Sandnes'
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
ON Persons.P_Id=Orders.P_Id
SQL Functions
SQL scalar functions return a single value, based on the input value.
Tip: The aggregate functions and the scalar functions will be explained in details
in the next chapters.
OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher then
the average OrderPrice value.
Customer
Nilsen
Jensen
The COUNT() function returns the number of rows that matches a specified
criteria.
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but
not with Microsoft Access.
WHERE Customer='Nilsen'
The result of the SQL statement above will be 2, because the customer Nilsen has
made 2 orders in total:
CustomerNilsen
NumberOfOrders
Now we want to count the number of unique customers in the "Orders" table.
NumberOfCustomers
which is the number of unique customers (Hansen, Nilsen, and Jensen) in the
"Orders" table.
The FIRST() function returns the first value of the selected column.
FirstOrderPrice
1000
The LAST() function returns the last value of the selected column.
LastOrderPrice
100
The MAX() function returns the largest value of the selected column.
LargestOrderPrice
2000
The MIN() function returns the smallest value of the selected column.
SmallestOrderPrice
100
OrderTotal
5700
GROUP BY column_name
Now we want to find the total sum (total order) of each customer.
GROUP BY Customer
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
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.
We can also use the GROUP BY statement on more than one column, like this:
GROUP BY Customer,OrderDate
Using Advanced Structured Query Language
SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.
FROM table_name
GROUP BY column_name
Now we want to find if any of the customers have a total order of less than 2000.
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of
more than 1500.
GROUP BY Customer
HAVING SUM(OrderPrice)>1500
Customer SUM(OrderPrice)
Jensen 2000
Now we want to select the content of the "LastName" and "FirstName" columns
above, and convert the "LastName" column to uppercase.
LastName FirstName
HANSEN Ola
PETTERSEN Kari
Now we want to select the content of the "LastName" and "FirstName" columns
above, and convert the "LastName" column to lowercase.
hansen Ola
svendson Tove
pettersen Kari
Parameter Description
Now we want to extract the first four characters of the "City" column above.
SmallCity
Sand
Sand
Stav
The LEN() function returns the length of the value in a text field.
Now we want to select the length of the values in the "Address" column above.
LengthOfAddress
12
Parameter Description
Now we want to display the product name and the price rounded to the nearest
integer.
ProductName UnitPrice
Jarlsberg 10
Mascarpone 33
Gorgonzola 16
The NOW() function returns the current system date and time.
Now we want to display the products and prices per today's date.
Parameter Description
Now we want to display the products and prices per today's date (with today's
date displayed in the following format "YYYY-MM-DD").
FROM Products
SQL Syntax
Statement
or
or
SELECT column_name
FROM table_name AS table_alias
or
or
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
or
SELECT * SELECT *
FROM table_name
SELECT SELECT *
INTO INTO new_table_name [IN externaldatabase]
FROM old_table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
4. www.Microsoft .com