Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
107 views

Advanced SQL

This document provides an overview of SQL (Structured Query Language) including: - A brief history of SQL and relational databases. - An explanation of what SQL is and its main functions such as accessing and manipulating data. - The different types of SQL statements including DDL, DML, DCL, and queries. - An introduction to advanced SQL topics like the TOP clause used to limit the number of records returned from a table. - Examples of using TOP to return a specified number or percentage of records.

Uploaded by

Aliyan Aman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views

Advanced SQL

This document provides an overview of SQL (Structured Query Language) including: - A brief history of SQL and relational databases. - An explanation of what SQL is and its main functions such as accessing and manipulating data. - The different types of SQL statements including DDL, DML, DCL, and queries. - An introduction to advanced SQL topics like the TOP clause used to limit the number of records returned from a table. - Examples of using TOP to return a specified number or percentage of records.

Uploaded by

Aliyan Aman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 67

LEARNING GUIDE # 05

Module Title: - Using Advanced SQL

MODULE CODE: ICT DBA4 05 0118

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

Practice Task Safety

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

 Allow users to access data in relational database management systems.


 Allow users to describe the data.
 Allow users to define the data in database and manipulate that data.
 Allow to embed within other languages using SQL modules, libraries & pre-compilers.
 Allow users to create and drop databases and tables.
 Allow users to create view, stored procedure, functions in a database.
 Allow users to set permissions on tables, procedures, and views
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Types of SQL Statements

Structured Query Language (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.

a) DDL (Data Definition 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

b) DML (Data Manipulation Language)


c) DCL (Data Control Language)
d) Query (Retrieving data)
DDL commands are used to define the data. For example, CREATE TABLE.
 Allows DBA or user to describe and name entitles, attributes and relationships required
for the application.
 Specification notation for defining the database schema
DML commands such as, INSERT and DELETE are used to manipulate data.
 Provides basic data manipulation operations on data held in the database.
 Language for accessing and manipulating the data organized by the appropriate data
model
 DML also known as query language
Procedural DML: user specifies what data is required and how to get the data.

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.

3. Introduction to SQL Statements/commands

The Relational Model defines two root languages for accessing a relational database -- Relational
Algebra and Relational Calculus.

There are 3 basic categories of SQL Statements:

 SQL-Data Statements -- query and modify tables and columns


o SELECT Statement-- query tables and views 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

o INSERT Statement -- add rows to tables


o UPDATE Statement -- modify columns in table rows
o DELETE Statement-- remove rows from tables
 SQL-Transaction Statements-- control transactions
o COMMIT Statement-- commit the current transaction
o ROLLBACK Statement -- roll back the current transaction
 SQL-Schema Statements -- maintain schema (catalog)
o CREATE TABLE Statement -- create tables
o CREATE VIEW Statement-- create views
o DROP TABLE Statement -- drop tables
o DROP VIEW Statement -- drop views
o GRANT Statement -- grant privileges on tables and views to other users
o REVOKE Statement-- revoke privileges on tables and views from other users

2. Advanced SQL

SQL TOP Clause

The TOP clause is used to specify the number of records to return.

The 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 TOP clause.

SQL Server Syntax

SELECT TOP number|percent column_name(s)

FROM table_name

SQL SELECT TOP Equivalent in MySQL and Oracle

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

WHERE ROWNUM <= number

Example

SELECT *

FROM Persons

WHERE ROWNUM <=5

SQL TOP Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger

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.

We use the following SELECT statement:

SELECT TOP 2 * FROM Persons

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

SQL TOP PERCENT Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
Now we want to select only 50% of the records in the table above.

We use the following SELECT statement:

SELECT TOP 50 PERCENT * FROM Persons

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

SQL LIKE Operator

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.

The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name LIKE pattern

LIKE Operator Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the persons living in a city that starts with "s" from the table above.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City LIKE 's%'

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:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Next, we want to select the persons living in a city that ends with an "s" 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

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City LIKE '%s'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Next, we want to select the persons living in a city that contains the pattern "tav" from the
"Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City LIKE '%tav%'

The result-set will look like this:

P_Id LastName FirstName Address City


3 Pettersen Kari Storgt 20 Stavanger

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.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City NOT LIKE '%tav%'

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

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

SQL Wildcards

SQL wildcards can be used when searching for data in a database.

SQL Wildcards

SQL wildcards can substitute for one or more characters when searching for data in a database.

SQL wildcards must be used with the SQL LIKE operator.

With SQL, the following wildcards can be used:

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]

SQL Wildcard Examples

We have the following "Persons" table:

P_Id LastName FirstName Address City

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

1 Hansen Ola Timoteivn 10 Sandnes


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Using the % Wildcard

Now we want to select the persons living in a city that starts with "sa" from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City LIKE 'sa%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
Next, we want to select the persons living in a city that contains the pattern "nes" from the
"Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE City LIKE '%nes%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Using the _ Wildcard

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.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE FirstName LIKE '_la'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

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.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName LIKE 'S_end_on'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes

Using the [charlist] Wildcard

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

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName LIKE '[bsp]%'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

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.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName LIKE '[!bsp]%'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

SQL 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

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 column_name IN (value1,value2,...)

IN Operator Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the
table above.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName IN ('Hansen','Pettersen')

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL 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,...)

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

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name equal to "Hansen" or "Pettersen" from the
table above.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName IN ('Hansen','Pettersen')

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL BETWEEN Operator

The BETWEEN operator is used in a WHERE clause to select a range of data between two
values.

The BETWEEN Operator

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

SQL BETWEEN Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name

BETWEEN value1 AND value2

BETWEEN Operator Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the persons with a last name alphabetically between "Hansen" and
"Pettersen" from the table above.

We use the following SELECT statement:

SELECT * FROM Persons

WHERE LastName

BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes

Note: The BETWEEN operator is treated differently in different databases!

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.

Therefore: Check how your database treats the BETWEEN operator.

Example 2

To display the persons outside the range in the previous example, use NOT BETWEEN:

SELECT * FROM Persons

WHERE LastName

NOT BETWEEN 'Hansen' AND 'Pettersen'

The result-set will look like this:

P_Id LastName FirstName Address City


2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL Alias

With SQL, an alias name can be given to a table or to a column.

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

An alias name could be anything, but usually it is short.

SQL Alias Syntax for Tables

SELECT column_name(s)

FROM table_name

AS alias_name

SQL Alias Syntax for Columns

SELECT column_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.

We use the following SELECT statement:

SELECT po.OrderID, p.LastName, p.FirstName

FROM Persons AS p,

Product_Orders AS po

WHERE p.LastName='Hansen' AND p.FirstName='Ola'

The same SELECT statement without aliases:

SELECT Product_Orders.OrderID, Persons.LastName, Persons.FirstName

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

WHERE Persons.LastName='Hansen' AND 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.

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.

Tables in a database are often related to each other with keys.

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.

Look at the "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

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.

Next, we have the "Orders" table:

O_Id OrderNo P_Id


1 77895 3

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.

Different SQL JOINs

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

SQL INNER JOIN Keyword

The INNER JOIN keyword return rows when there is at least one match in both tables.

SQL INNER JOIN Syntax

SELECT column_name(s)

FROM table_name1

INNER JOIN table_name2

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

PS: INNER JOIN is the same as JOIN.

SQL INNER JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn10 Sandnes
2 Svendson Tove Borgvn23 Sandnes
3 Pettersen Kari Storgt20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

Now we want to list all the persons with any orders.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo

FROM Persons

INNER JOIN Orders

ON Persons.P_Id=Orders.P_Id

ORDER BY Persons.LastName

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

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678

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.

SQL LEFT JOIN Keyword

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).

SQL LEFT JOIN Syntax

SELECT column_name(s)

FROM table_name1

LEFT JOIN table_name2

ON table_name1.column_name=table_name2.column_name

PS: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

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 "Orders" table:

O_Id OrderNo P_Id


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.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo

FROM Persons

LEFT JOIN Orders

ON Persons.P_Id=Orders.P_Id

ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
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).

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 RIGHT JOIN Keyword

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).

SQL RIGHT JOIN Syntax

SELECT column_name(s)

FROM table_name1

RIGHT JOIN table_name2

ON table_name1.column_name=table_name2.column_name

PS: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

SQL RIGHT JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15

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.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo

FROM Persons

RIGHT JOIN Orders

ON Persons.P_Id=Orders.P_Id

ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
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).

SQL FULL JOIN Keyword

The FULL JOIN keyword return rows when there is a match in one of the tables.

SQL FULL JOIN 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_name1

FULL JOIN table_name2

ON table_name1.column_name=table_name2.column_name

SQL FULL JOIN Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


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.

We use the following SELECT statement:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo

FROM Persons

FULL JOIN 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

ON Persons.P_Id=Orders.P_Id

ORDER BY Persons.LastName

The result-set will look like this:

LastName FirstName OrderNo


Hansen Ola 22456
Hansen Ola 24562
Pettersen Kari 77895
Pettersen Kari 44678
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.

SQL UNION Operator

The SQL UNION operator combines two or more SELECT statements.

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.

SQL UNION Syntax

SELECT column_name(s) FROM table_name1

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

SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL.

SQL UNION ALL Syntax

SELECT column_name(s) FROM table_name1

UNION ALL

SELECT column_name(s) FROM table_name2

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.

SQL UNION Example

Look at the following tables:

"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.

We use the following SELECT statement:

SELECT E_Name FROM Employees_Norway

UNION

SELECT E_Name FROM Employees_USA

The result-set will look like this:

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.

SQL UNION ALL Example

Now we want to list all employees in Norway and USA:

SELECT E_Name FROM Employees_Norway

UNION ALL

SELECT E_Name FROM Employees_USA

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

SQL SELECT INTO Statement

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.

SQL SELECT INTO Syntax

We can select all columns into the new table:

SELECT *

INTO new_table_name [IN externaldatabase]

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

INTO new_table_name [IN externaldatabase]

FROM old_tablename

SQL SELECT INTO Example

Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.

We use the following SQL statement:

SELECT *

INTO Persons_Backup

FROM Persons

We can also use the IN clause to copy the table into another database:

SELECT *

INTO Persons_Backup IN 'Backup.mdb'

FROM Persons

We can also copy only a few fields into the new table:

SELECT LastName,FirstName

INTO Persons_Backup

FROM Persons

SQL SELECT INTO - With a WHERE Clause

We can also add a WHERE clause.

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'

SQL SELECT INTO - Joined Tables

Selecting data from more than one table is also possible.

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

INNER JOIN Orders

ON Persons.P_Id=Orders.P_Id

3. SQL Functions

SQL has many built-in functions for performing calculations on data.

SQL Aggregate Functions

SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

 AVG() - Returns the average value


 COUNT() - Returns the number of rows
 FIRST() - Returns the first value
 LAST() - Returns the last value
 MAX() - Returns the largest 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

 MIN() - Returns the smallest value


 SUM() - Returns the sum

SQL Scalar functions

SQL scalar functions return a single value, based on the input value.

Useful scalar functions:

 UCASE() - Converts a field to upper case


 LCASE() - Converts a field to lower case
 MID() - Extract characters from a text field
 LEN() - Returns the length of a text field
 ROUND() - Rounds a numeric field to the number of decimals specified
 NOW() - Returns the current system date and time
 FORMAT() - Formats how a field is to be displayed

SQL AVG() Function

The AVG() Function

The AVG() function returns the average value of a numeric column.

SQL AVG() Syntax

SELECT AVG(column_name) FROM table_name

SQL AVG() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen

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 2008/10/23 1600 Nilsen


3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
Now we want to find the average value of the "OrderPrice" fields.

We use the following SQL statement:

SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

The result-set will look like this:

OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher than the average
OrderPrice value.

We use the following SQL statement:

SELECT Customer FROM Orders

WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

The result-set will look like this:

Customer
Hansen
Nilsen
Jensen

SQL COUNT() Function

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

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:

SELECT COUNT(column_name) FROM table_name

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:

SELECT COUNT(*) FROM table_name

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name

Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.

SQL COUNT(column_name) Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

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 count the number of orders from "Customer Nilsen".

We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerNilsen FROM Orders

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

SQL COUNT(*) Example

If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders

The result-set will look like this:

NumberOfOrders
6
Which is the total number of rows in the table?

SQL COUNT(DISTINCT column_name) Example

Now we want to count the number of unique customers in the "Orders" table.

We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders

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

NumberOfCustomers
3
Which is the number of unique customers (Hansen, Nilsen, and Jensen) in the “Orders” table?

SQL FIRST() Function

The FIRST() Function

The FIRST() function returns the first value of the selected column.

SQL FIRST() Syntax

SELECT FIRST(column_name) FROM table_name

SQL FIRST() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the first value of the "OrderPrice" column.

We use the following SQL statement:

SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders

Tip: Workaround if FIRST() function is not supported:

SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1

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 result-set will look like this:

FirstOrderPrice
1000

SQL LAST() Function

The LAST() Function

The LAST() function returns the last value of the selected column.

SQL LAST() Syntax

SELECT LAST(column_name) FROM table_name

SQL LAST() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the last value of the "OrderPrice" column.

We use the following SQL statement:

SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders

Tip: Workaround if LAST() function is not supported:

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 OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1

The result-set will look like this:

LastOrderPrice
100

SQL MAX() Function

The MAX() Function

The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax

SELECT MAX(column_name) FROM table_name

SQL MAX() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the largest value of the "OrderPrice" column.

We use the following SQL statement:

SELECT MAX(OrderPrice) AS LargestOrderPrice FROM 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 result-set will look like this:

LargestOrderPrice
2000

SQL MIN() Function

The MIN() Function

The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax

SELECT MIN(column_name) FROM table_name

SQL MIN() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the smallest value of the "OrderPrice" column.

We use the following SQL statement:

SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders

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

SmallestOrderPrice
100

SQL SUM() Function

The SUM() Function

The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax

SELECT SUM(column_name) FROM table_name

SQL SUM() Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find the sum of all "OrderPrice" fields".

We use the following SQL statement:

SELECT SUM(OrderPrice) AS OrderTotal FROM Orders

The result-set will look like this:

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

SQL GROUP BY Statement

Aggregate functions often need an added GROUP BY statement.

The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.

SQL GROUP BY Syntax

SELECT column_name, aggregate_function(column_name)

FROM table_name

WHERE column_name operator value

GROUP BY column_name

SQL GROUP BY Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

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

We will have to use the GROUP BY statement to group the customers.

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) as total_Order FROM Orders

GROUP BY Customer

The result-set will look like this:

Customer total_Order
Hansen 2000
Nilsen 1700
Jensen 2000

Nice! Isn't it? :)

Let's see what happens if we omit the GROUP BY statement:

SELECT Customer,SUM(OrderPrice) FROM Orders

The result-set will look like this:

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.

GROUP BY More Than One Column

We can also use the GROUP BY statement on more than one column, like this:

SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders

GROUP BY Customer,OrderDate

SQL HAVING Clause

The HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword could not be used with
aggregate functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)

FROM table_name

WHERE column_name operator value

GROUP BY column_name

HAVING aggregate_function(column_name) operator value

SQL HAVING Example

We have the following "Orders" table:

O_Id OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen

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

3 2008/09/02 700 Hansen


4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen

Now we want to find if any of the customers have a total order of less than 2000.

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders

GROUP BY Customer

HAVING SUM(OrderPrice)<2000

The result-set will look like this:

Customer SUM(OrderPrice)
Nilsen 1700

Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than
1500.

We add an ordinary WHERE clause to the SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Orders

WHERE Customer='Hansen' OR Customer='Jensen'

GROUP BY Customer

HAVING SUM(OrderPrice)>1500

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

Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000

SQL UCASE() Function

The UCASE() Function

The UCASE() function converts the value of a field to uppercase.

SQL UCASE() Syntax

SELECT UCASE(column_name) FROM table_name

Syntax for SQL Server

SELECT UPPER(column_name) FROM table_name

SQL UCASE() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the content of the "LastName" and "FirstName" columns above, and
convert the "LastName" column to uppercase.

We use the following SELECT statement:

SELECT UCASE(LastName) as LastName,FirstName FROM Persons

The result-set will look like this:

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

SQL LCASE() Function

The LCASE() Function

The LCASE() function converts the value of a field to lowercase.

SQL LCASE() Syntax

SELECT LCASE(column_name) FROM table_name

Syntax for SQL Server

SELECT LOWER(column_name) FROM table_name

SQL LCASE() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to select the content of the "LastName" and "FirstName" columns above, and
convert the "LastName" column to lowercase.

We use the following SELECT statement:

SELECT LCASE(LastName) as LastName,FirstName FROM Persons

The result-set will look like this:

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

SQL MID() Function

The MID() Function

The MID() function is used to extract characters from a text field.

SQL MID() Syntax

SELECT MID(column_name,start[,length]) FROM table_name

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

We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to extract the first four characters of the "City" column above.

We use the following SELECT statement:

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 MID(City,1,4) as SmallCity FROM Persons

The result-set will look like this:

SmallCity
Sand
Sand
Stav

SQL LEN() Function

The LEN() Function

The LEN() function returns the length of the value in a text field.

SQL LEN() Syntax

SELECT LEN(column_name) FROM table_name

SQL LEN() Example

We have the following "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the length of the values in the "Address" column above.

We use the following SELECT statement:

SELECT LEN(Address) as LengthOfAddress FROM Persons

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

LengthOfAddress
12
9
9

SQL ROUND() Function

The ROUND() Function

The ROUND() function is used to round a numeric field to the number of decimals specified.

SQL ROUND() Syntax

SELECT ROUND(column_name,decimals) FROM table_name

Parameter Description
column_name Required. The field to round.
decimals Required. Specifies the number of decimals to be returned.

SQL ROUND() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice


1 Jarlsberg 1000 g 10.45
2 Mascarpone 1000 g 32.56
3 Gorgonzola 1000 g 15.67

Now we want to display the product name and the price rounded to the nearest integer.

We use the following SELECT statement:

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 ProductName, ROUND(UnitPrice,0) as UnitPrice FROM Products

The result-set will look like this:

ProductName UnitPrice
Jarlsberg 10
Mascarpone 33
Gorgonzola 16

SQL NOW() Function

The NOW() Function

The NOW() function returns the current system date and time.

SQL NOW() Syntax

SELECT NOW() FROM table_name

SQL NOW() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice


1 Jarlsberg 1000 g 10.45
2 Mascarpone 1000 g 32.56
3 Gorgonzola 1000 g 15.67

Now we want to display the products and prices per today's date.

We use the following SELECT statement:

SELECT ProductName, UnitPrice, Now() as PerDate FROM Products

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

ProductName UnitPrice PerDate


Jarlsberg 10.45 10/7/2008 11:25:02 AM
Mascarpone 32.56 10/7/2008 11:25:02 AM
Gorgonzola 15.67 10/7/2008 11:25:02 AM

SQL FORMAT() Function

The FORMAT() Function

The FORMAT() function is used to format how a field is to be displayed.

SQL FORMAT() Syntax

SELECT FORMAT(column_name,format) FROM table_name

Parameter Description
column_name Required. The field to be formatted.
Format Required. Specifies the format.

SQL FORMAT() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice


1 Jarlsberg 1000 g 10.45
2 Mascarpone 1000 g 32.56
3 Gorgonzola 1000 g 15.67

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").

We use the following SELECT statement:

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 ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate

FROM Products

The result-set will look like this:

ProductName UnitPrice PerDate


Jarlsberg 10.45 2008-10-07
Mascarpone 32.56 2008-10-07
Gorgonzola 15.67 2008-10-07

Special SQL functions

Mathematical Functions and Operators

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.

Table below shows the available mathematical operators.

Mathematical Operators Name

Description Example Result


+ addition 2+3 5
- subtraction 2-3 -1
* multiplication 2*3 6
/ division (integer 4/2 2
division truncates
results)
% modulo (remainder) 5%4 1
^ exponentiation 2.0 ^ 3.0 8
|/ square root |/ 25.0 5

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

||/ cube root ||/ 27.0 3


! factorial 5! 120
!! factorial (prefix !! 5 120
operator)
@ absolute value @ -5.0 5
& binary AND 91 & 15 11
| binary OR 32 | 3 35
# binary XOR 17 # 5 20
~ binary NOT ~1 -2
<< binary shift left 1 << 4 16
>> binary shift right 8 >> 2 2
The "binary" operators are also available for the bit string types BIT and BIT VARYING, as
shown in Table 6-3. Bit string arguments to &, |, and # must be of equal length. When bit
shifting, the original length of the string is preserved, as shown in the table.

Bit String Binary Operators

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.

Table below shows Mathematical Functions

Function Return Type Description Example Result


abs(x) (same as x) absolute value abs(-17.4) 17.4
cbrt(dp) dp cube root cbrt(27.0) 3
ceil(dp or (same as input) smallest integer ceil(-42.8) -42
numeric) not less than
argument
degrees(dp) dp radians to degrees(0.5) 28.6478897565412
degrees
exp(dp or (same as input) exponential exp(1.0) 2.71828182845905
numeric)
floor(dp or (same as input) largest integer floor(-42.8) -43
numeric) not greater than
argument
ln(dp or (same as input) natural ln(2.0) 0.693147180559945
numeric) logarithm
log(dp or (same as input) base 10 log(100.0) 2
numeric) logarithm
log(b numeric, x numeric logarithm to log(2.0, 64.0) 6.0000000000
numeric) base b
mod(y, x) (same as remainder of y/x mod(9,4) 1
argument types)
pi() dp "Pi" constant pi() 3.14159265358979
pow(x dp, e dp) dp raise a number pow(9.0, 3.0) 729
to exponent e

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

pow(x numeric, numeric raise a number pow(9.0, 3.0) 729


e numeric) to exponent e
radians(dp) dp degrees to radians(45.0) 0.785398163397448
radians
random() dp random value random()
between 0.0 and
1.0
round(dp or (same as input) round to nearest round(42.4) 42
numeric) integer
round(v numeric round to s round(42.4382, 42.44
numeric, s decimal places 2)
integer)
sign(dp or (same as input) sign of the sign(-8.4) -1
numeric) argument (-1, 0,
+1)
sqrt(dp or (same as input) square root sqrt(2.0) 1.4142135623731
numeric)
trunc(dp or (same as input) truncate toward trunc(42.8) 42
numeric) zero
trunc(v numeric, numeric truncate to s trunc(42.4382, 42.43
s integer) decimal places 2)

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

String Functions and Operators

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..

Function Return Description Example Result


Type
string || string text String 'Post' || 'greSQL' PostgreSQL
concatenation
bit_length(string) integer Number of bits in bit_length('jose') 32
string
char_length(string) or integer Number of char_length('jose') 4
character_length(string) characters in string
convert(string using text Change encoding convert('PostgreSQL' 'PostgreSQL'
conversion_name) using specified using in Unicode
conversion name. iso_8859_1_to_utf_8) (UTF-8)

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

Conversions can encoding


be defined by
CREATE
CONVERSION.
Also there are
some pre-defined
conversion names.
See Table 6-8 for
available
conversion names.
lower(string) text Convert string to lower('TOM') tom
lower case
octet_length(string) integer Number of bytes in octet_length('jose') 4
string
overlay(string placing text Insert substring overlay('Txxxxas' Thomas
string from integer [for placing 'hom' from 2
integer]) for 4)
position(substring in integer Location of position('om' in 3
string) specified substring 'Thomas')
substring(string [from text Extract substring substring('Thomas' hom
integer] [for integer]) from 2 for 3)
substring(string from text Extract substring substring('Thomas' mas
pattern) matching POSIX from '...$')
regular expression
substring(string from text Extract substring substring('Thomas' oma
pattern for escape) matching SQL from '%#"o_a#"_' for
regular expression '#')
trim([leading | trailing | text Remove the trim(both 'x' from Tom
both] [characters] from longest string 'xTomxx')
string) containing only the

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 Date Functions

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.

MySQL Date Functions

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

DATEDIFF() Returns the number of days between two dates


DATE_FORMAT() Displays date/time data in different formats

SQL Server Date Functions

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

SQL Date Data Types

MySQL comes with the following data types for storing a date or a date/time value in the
database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MM:SS
 TIMESTAMP - format: YYYY-MM-DD HH:MM:SS
 YEAR - format YYYY or YY

SQL Server comes with the following data types for storing a date or a date/time value in the
database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MM:SS

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

 SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS


 TIMESTAMP - format: a unique number

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.

SQL Working with Dates

You can compare two dates easily if there is no time component involved!

Assume we have the following "Orders" table:

OrderId ProductName OrderDate


1 Geitost 2008-11-11
2 Camembert Pierrot 2008-11-09
3 Mozzarella di Giovanni 2008-11-11
4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId ProductName OrderDate


1 Geitost 2008-11-11
3 Mozzarella di Giovanni 2008-11-11
Now, assume that the "Orders" table looks like this (notice the time component in the
"OrderDate" 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

OrderId ProductName OrderDate


1 Geitost 2008-11-11 13:23:44
2 Camembert Pierrot 2008-11-09 15:45:21
3 Mozzarella di Giovanni 2008-11-11 11:12:01
4 Mascarpone Fabioli 2008-10-29 14:56:59

If we use the same SELECT statement as above:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

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

1. Which SQL statement is used to extract data from a database?


A. SELECT
B. OPEN
C. EXTRACT
D. GET
2. Which SQL statement is used to update data in a database?
A. MODIFY
B. UPDATE
C. SAVE AS
D. SAVE
3. Which SQL statement is used to delete data from a database?
A. COLLAPSE
B. DELETE
C. REMOVE

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. Which SQL statement is used to insert new data in a database?


A. ADD RECORD
B. INSERT INTO
C. INSERT NEW
D. ADD NEW
5. With SQL, how do you select a column named "FirstName" from a
table named "Persons"?
A. SELECT FirstName FROM Persons
B. SELECT Persons.FirstName
C. EXTRACT FirstName FROM Persons

 The trainee’s underpinning knowledge was


[ ] Satisfactory [ ] Not satisfactory

 Feedback to Trainee:

Trainee’s Signature: Date:


Instructor’s Signature: Date:

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

Trainees’ Performance is:


[ ] Satisfactory [ ] Not Satisfactory

Feedback to Trainee:

Trainee’s Signature: Date:


Instructor’s Signature: Date:

Using Advanced SQL version 1.0 Year 2012 prepared By: Aliyan A. Page 45

You might also like