Advanced SQL
Advanced SQL
SYMBOLS
These symbols are located at the left margin of the module. These illustrate the actions that should be
taken or resource to be used at a particular stage in the module.
LO Learning
Outcome
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Self-Check
Answer Key
Resources
Reading Assessment
Activity
Remember/Tips
Use Computer
1. Introduction to SQL
1.1. Overview of SQL
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
The Structured Query Language is a relational database language. By itself, SQL does not
make a DBMS. It is just a medium which is used to as a means of communicating to the DBMS
what you want it to do. SQL commands consist of English like statements which are used to
query, insert, update and delete data. What we mean by `English like’ is that SQL commands
resemble English language sentences in their construction and use. This does not mean that you
can type in something like "Pull up the figures for last quarter's sales" and expect SQL to
understand your request. What it does mean is that SQL is a lot easier to learn and understand
than most of the other computer languages
History:
1970 -- Dr. E.F. "Ted" of IBM is known as the father of relational databases. He
described a relational model for databases.
1974 -- Structured Query Language appeared.
1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
1986 -- IBM developed the first prototype of relational database and standardized by
ANSI. The first relational database was released by Relational Software.
What is SQL?
SQL is structured Query Language which is a computer language for storing, manipulating and
retrieving data stored in relational database.
SQL is an ANSI (American National Standards Institute) standard but there are many different
versions of the SQL language.
SQL is the standard language for Relation Database System. All relational database management
systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server uses SQL
as standard database language.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Function of SQL
Almost all relational database management systems use SQL (Structured Query Language) for
data manipulation and retrieval. SQL is the standard language for relational database systems.
SQL is a non-procedural language, where you need to concentrate on what you want, not on how
you get it. Put it in other way, you need not be concerned with procedural details.
SQL Commands are divided into four categories, depending upon what they do.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Non-Procedural DML: user specifies what data is required but not how it is to be
retrieved
DCL commands are used to control access to data. For example, GRANT.
Allows a DBA to define access control and privileges for users.
It is a mechanism for implementing security at a database object level.
Uses the Grant and Revoke SQL Statements
Query is used to retrieve data using SELECT.
The Relational Model defines two root languages for accessing a relational database -- Relational
Algebra and Relational Calculus.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
2. Advanced SQL
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
MySQL Syntax
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SELECT column_name(s)
FROM table_name
LIMIT number
Example
SELECT *
FROM Persons
LIMIT 5
Oracle Syntax
SELECT column_name(s)
FROM table_name
Example
SELECT *
FROM Persons
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Now we want to select only the two first records in the table above.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
The "%" sign can be used to define wildcards (missing letters in the pattern)
both before and after the pattern.
The result-set will look like this:
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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 does NOT contain the pattern "tav"
from the "Persons" table, by using the NOT keyword.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SQL Wildcards
SQL Wildcards
SQL wildcards can substitute for one or more characters when searching for data in a database.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist]
Any single character not in charlist
or
[!
charlist]
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Now we want to select the persons with a first name that starts with any character, followed by
"la" from the "Persons" table.
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.
Now we want to select the persons with a last name that starts with "b" or "s" or "p" from the
"Persons" table.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
SQL IN Syntax
SELECT column_name(s)
FROM table_name
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
IN Operator Example
SQL IN Operator
SQL IN Syntax
SELECT column_name(s)
FROM table_name
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
IN Operator Example
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the
table above.
The BETWEEN operator is used in a WHERE clause to select a range of data between two
values.
The BETWEEN operator selects a range of data between two values. The values can be
numbers, text, or dates.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
In some databases, persons with the LastName of "Hansen" or "Pettersen" will not be listed,
because the BETWEEN operator only selects fields that are between and excluding the test
values.
In other databases, persons with the LastName of "Hansen" or "Pettersen" will be listed, because
the BETWEEN operator selects fields that are between and including the test values.
And in other databases, persons with the LastName of "Hansen" will be listed, but "Pettersen"
will not be listed (like the example above), because the BETWEEN operator selects fields
between the test values, including the first test value and excluding the last test value.
Example 2
To display the persons outside the range in the previous example, use NOT BETWEEN:
WHERE LastName
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SELECT column_name(s)
FROM table_name
AS alias_name
FROM table_name
Alias 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.
Now we want to list all the orders that "Ola Hansen" is responsible for.
FROM Persons AS p,
Product_Orders AS po
FROM Persons,
Product_Orders
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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.
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.
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.
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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.
SELECT column_name(s)
FROM table_name1
ON table_name1.column_name=table_name2.column_name
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
FROM Persons
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
ON table_name1.column_name=table_name2.column_name
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Now we want to list all the persons and their orders - if any, from the tables above.
FROM Persons
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
The RIGHT JOIN keyword returns all the 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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SELECT column_name(s)
FROM table_name1
ON table_name1.column_name=table_name2.column_name
Now we want to list all the persons and their orders, and all the orders with their persons.
FROM Persons
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL.
UNION ALL
PS: The column names in the result-set of a UNION are always equal to the column names in the
first SELECT statement in the UNION.
"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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Now we want to list all the different employees in Norway and USA.
UNION
E_Name
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
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)
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
INTO Persons_Backup
FROM Persons
WHERE City='Sandnes'
The following example creates a "Persons_Order_Backup" table contains data from the two
tables "Persons" and "Orders":
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
ON Persons.P_Id=Orders.P_Id
3. SQL Functions
SQL aggregate functions return a single value, calculated from values in a column.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SQL scalar functions return a single value, based on the input value.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher than the average
OrderPrice value.
Customer
Hansen
Nilsen
Jensen
The COUNT() function returns the number of rows that matches a specified criteria.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
WHERE Customer='Nilsen'
The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders
in total:
CustomerNilsen
2
NumberOfOrders
6
Which is the total number of rows in the table?
Now we want to count the number of unique customers in the "Orders" table.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
NumberOfCustomers
3
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
FirstOrderPrice
1000
The LAST() function returns the last value of the selected column.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
LastOrderPrice
100
The MAX() function returns the largest value of the selected column.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
LargestOrderPrice
2000
The MIN() function returns the smallest value of the selected column.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
SmallestOrderPrice
100
OrderTotal
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
5700
The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
FROM table_name
GROUP BY column_name
Now we want to find the total sum (total order) of each customer.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
GROUP BY Customer
Customer total_Order
Hansen 2000
Nilsen 1700
Jensen 2000
Customer SUM(OrderPrice)
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700
The result-set above is not what we wanted.
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
LastName FirstName
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
HANSEN Ola
SVENDSON Tove
PETTERSEN Kari
LastName FirstName
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
hansen Ola
svendson Tove
pettersen Kari
Parameter Description
column_name Required. The field to extract characters from
start Required. Specifies the starting position (starts at 1)
length Optional. The number of characters to return. If omitted, the MID()
function returns the rest of the text
SQL MID() Example
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
LengthOfAddress
12
9
9
The ROUND() function is used to round a numeric field to the number of decimals specified.
Parameter Description
column_name Required. The field to round.
decimals Required. Specifies the number of decimals to be returned.
Now we want to display the product name and the price rounded to the nearest integer.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
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.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Parameter Description
column_name Required. The field to be formatted.
Format Required. Specifies the format.
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").
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
FROM Products
Mathematical operators are provided for many PostgreSQL types. For types without common
mathematical conventions for all possible permutations (e.g., date/time types) we describe the
actual behavior in subsequent sections.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Example Result
B'10001' & B'01101' 00001
B'10001' | B'01101' 11101
B'10001' # B'01101' 11110
~ B'10001' 01110
B'10001' << 3 01000
B'10001' >> 2 00100
Table 6-4 shows the available mathematical functions. In the table, dp indicates double precision.
Many of these functions are provided in multiple forms with different argument types. Except
where noted, any given form of a function returns the same datatype as its argument. The
functions working with double precision data are mostly implemented on top of the host system's
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
C library; accuracy and behavior in boundary cases may therefore vary depending on the host
system.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Finally, the above table shows the available trigonometric functions. All trigonometric functions
take arguments and return values of type double precision.
Function Description
acos(x) inverse cosine
asin(x) inverse sine
atan(x) inverse tangent
atan2(x, y) inverse tangent of x/y
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
cos(x) cosine
cot(x) cotangent
sin(x) sine
tan(x) tangent
Table .Trigonometric Functions
This section describes functions and operators for examining and manipulating string values.
Strings in this context include values of all the types CHARACTER, CHARACTER VARYING,
and TEXT. Unless otherwise noted, all of the functions listed below work on all of these types,
but be wary of potential effects of the automatic padding when using the CHARACTER type.
Generally, the functions described here also work on data of non-string types by converting that
data to a string representation first. Some functions also exist natively for bit-string types.
SQL defines some string functions with a special syntax where certain key words rather than
commas are used to separate the arguments. Details are in Table 6-6. These functions are also
implemented using the regular syntax for function invocation..
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
characters (a space
by default) from
the
beginning/end/bot
h ends of the string
upper(string) text Convert string to upper('tom') TOM
upper case
Table SQL String Functions and Operators
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are
trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected.
However, if a time portion is involved, it gets complicated.
Before talking about the complications of querying for dates, we will look at the most important
built-in functions for working with dates.
The following table lists the most important built-in date functions in MySQL:
Function Description
NOW() Returns the current date and time
CURDATE() Returns the current date
CURTIME() Returns the current time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD() Adds a specified time interval to a date
DATE_SUB() Subtracts a specified time interval from a date
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
The following table lists the most important built-in date functions in SQL Server:
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds or subtracts a specified time interval from a date
DATEDIFF() Returns the time between two dates
CONVERT() Displays date/time data in different formats
MySQL comes with the following data types for storing a date or a date/time value in the
database:
SQL Server comes with the following data types for storing a date or a date/time value in the
database:
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Note: The date types are chosen for a column when you create a new table in your database!
For an overview of all data types available, go to our complete Data Types reference.
You can compare two dates easily if there is no time component involved!
Now we want to select the records with an OrderDate of "2008-11-11" from the table above.
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
We will get no result! This is because the query is looking only for dates with no time portion.
Tip: If you want to keep your queries simple and easy to maintain, do not allow time components
in your dates!
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Self-Check 1
Answer the questions on the following questionnaire; provide the answer sheet to your
trainer.
Check your answers by looking at the feedback sheets; ask for the assistance of the
trainer whenever necessary.
Satisfactory
Questions
Response
The trainee should answer the following questions YES NO
Choose the best answer
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
Feedback to Trainee:
Answer Key
1. A
2. B
3. B
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET MODULE Using Advanced Structured Query Language
4. B
5. A
Performance Criteria
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45
INFORMATI UNIT Database Administration Level IV
ON SHEET
MODULE Using Advanced Structured Query Language
Satisfactory
Assessment Criteria
Response
The trainee will be assessed through the following criteria: YES NO
Answered all the interview questions clearly
Performed all activities accordingly
Followed all instructions in the activities
Feedback to Trainee:
Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45