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

7.0 SQL Notes - Querying Databases

2

Uploaded by

Edwin Odhiambo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

7.0 SQL Notes - Querying Databases

2

Uploaded by

Edwin Odhiambo
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 51

Introduction to SQL

What is SQL
 SQL stands for Structured Query Language
 SQL allows you to access a database
 SQL is an ANSI standard computer language
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert new records in a database
 SQL can delete records from a database
 SQL can update records in a database
 SQL is easy to learn

SQL is a standard computer language for accessing and manipulating databases.

Types of databases

1. SQL
2. Access

3. Oracle

4. Sybase,

5. SQL Server

6. DB2

7. Access

SQL Database Tables

A database most often contains one or more tables. Each table is identified by a name
(e.g. "Customers" or "Orders"). Tables contain records (rows) with data.

Below is an example of a table called "Persons":

LastName FirstName Address City


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

The table above contains three records (one for each person) and four columns
(LastName, FirstName, Address, and City).

1
SQL Queries

With SQL, we can query a database and have a result set returned.

A query like this:

SELECT LastName FROM Persons

Gives a result set like this:

LastName
Hansen
Svendson
Pettersen

SQL Data Manipulation Language (DML)

SQL (Structured Query Language) is a syntax for executing queries. But the SQL
language also includes a syntax to update, insert, and delete records.

These query and update commands together form the Data Manipulation Language
(DML) part of SQL:

 SELECT - extracts data from a database table


 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database table

SQL Data Definition Language (DDL)

The Data Definition Language (DDL) part of SQL permits database tables to be created
or deleted. We can also define indexes (keys), specify links between tables, and impose
constraints between database tables.

The most important DDL statements in SQL are:

 CREATE TABLE - creates a new database table


 ALTER TABLE - alters (changes) a database table
 DROP TABLE - deletes a database table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

2
Data types

Data Type Description


integer(size) Hold integers only. The maximum number of digits are specified in
int(size) parenthesis.
smallint(size)
tinyint(size)

decimal(size,d) Hold numbers with fractions. The maximum number of digits are
numeric(size,d) specified in "size". The maximum number of digits to the right of the
decimal is specified in "d".

char(size) Holds a fixed length string (can contain letters, numbers, and special
characters). The fixed size is specified in parenthesis.

varchar(size) Holds a variable length string (can contain letters, numbers, and
special characters). The maximum size is specified in parenthesis.

date(yyyymmdd) Holds a date

Create a Database

To create a database:

CREATE DATABASE database_name

Create database GIT;


Create a Table

To create a table in a database:

CREATE TABLE tablename


(
columnname1 datatype,
3
columnname2 datatype,
.......
);

Example

This example demonstrates how you can create a table named Person, with four columns.
The column names will be LastName, FirstName, Address, and Age:

CREATE TABLE Person


(
LastName varchar,
FirstName varchar,
Address varchar,
Age int
);

This example demonstrates how you can specify a maximum length for
some columns:

CREATE TABLE Person


(
LastName varchar(30),
FirstName varchar,
Address varchar,
Age int(3)
);

The data type specifies what type of data the column can hold. The table below contains
the most common data types in SQL:

The INSERT INTO Statement

The INSERT INTO statement is used to insert new data into a table.

Syntax

INSERT INTO tablename


VALUES (value1, value2,…….);

You can also specify the columns for which you want to insert data:
4
INSERT INTO tablename (column1, column2...)
VALUES (value1, value2 ...)

Insert a New Row

This Persons table:

LastName FirstName Address City


Petersen Kari Storgt 20 Stavanger

And this SQL statement:

INSERT INTO Persons


VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes')

Will give this result:

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes

Insert Data in Specified Columns

This Persons table:

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes

And This SQL statement:

INSERT INTO Persons (LastName, Address)


VALUES ('Rasmussen', 'Storgt 67')

Will give this result:

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Hetland Camilla Hagabakka 24 Sandnes
5
Rasmussen Storgt 67

The SQL SELECT Statement

The SELECT statement is used to select data from a table. The tabular result is stored in a
result table (called the result-set).

Syntax

SELECT columnname(s)
FROM tablename;

SQL SELECT Example

To select the content of columns named "LastName" and "FirstName",


from the database table called "Persons", use a SELECT statement like
this:

SELECT LastName, FirstName FROM Persons;

The database table Persons:

LastName FirstName Address City


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

The result

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

6
Select All Columns

To select all columns from the "Persons" table, use a * symbol instead of column names,
like this:

SELECT * FROM Persons;

Result

LastName FirstName Address City


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

The Result Set

The result from a SQL query is stored in a result-set. Most database software systems
allow navigation of the result set with programming functions, like: Move-To-First-
Record, Get-Record-Content, Move-To-Next-Record, etc.

Semicolon after SQL Statements

Semicolon is the standard way to separate each SQL statement in database systems that
allow more than one SQL statement to be executed in the same call to the server.

Some SQL tutorials end each SQL statement with a semicolon. Is this necessary? We are
using MS Access and SQL Server 2000 and we do not have to put a semicolon after each
SQL statement, but some database programs force you to use it.

The SELECT DISTINCT Statement

The DISTINCT keyword is used to return only distinct (different) values.

The SELECT statement returns information from table columns. But what if we only
want to select distinct elements?

With SQL, all we need to do is to add a DISTINCT keyword to the SELECT statement:

7
Syntax

SELECT DISTINCT columnname(s)


FROM tablename;

Using the DISTINCT keyword

To select ALL values from the column named Company we use a SELECT
statement like this:

SELECT Company FROM Orders

Orders table

Company OrderNumber
Yu 3412
Safaricom 2312
Orange 4678
Safaricom 6798

Result

Company
Yu
Safaricom
Orange
Safaricom

To select only DIFFERENT values from the column named Company we use a
SELECT DISTINCT statement like this:

SELECT DISTINCT Company FROM Orders;

Result

Company
8
Yu
Safaricom
Orange

SQL WHERE Clause

The WHERE clause is used to specify a selection criterion.

The WHERE Clause

To conditionally select data from a table, a WHERE clause can be added to the SELECT
statement.

Syntax

SELECT column FROM table


WHERE column operator value;

With the WHERE clause, the following operators can be used:

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE
Search for a pattern
IN If you know the exact value you want to
return for at least one of the columns

Using the WHERE Clause

To select only the persons living in the city Sandnes, we add a WHERE clause to
the SELECT statement:

SELECT * FROM Persons


WHERE City='Sandnes';

Persons table
9
LastName FirstName Address City Year
Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980
Pettersen Kari Storgt 20 Stavanger 1960

Result

LastName FirstName Address City Year


Hansen Ola Timoteivn 10 Sandnes 1951
Svendson Tove Borgvn 23 Sandnes 1978
Svendson Stale Kaivn 18 Sandnes 1980

Using Quotes

Note that we have used single quotes around the conditional values in the examples.

SQL uses single quotes around text values (most database systems will also accept
double quotes). Numeric values should not be enclosed in quotes.

For text values:

This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove;

For numeric values:

This is correct:
SELECT * FROM Persons WHERE Year>1965;

This is wrong:
SELECT * FROM Persons WHERE Year>'1965';

The LIKE Condition

The LIKE condition is used to specify a search for a pattern in a column.

Syntax

SELECT column FROM table


WHERE column LIKE pattern;

10
A "%" sign can be used to define wildcards (missing letters in the pattern) both before
and after the pattern.

Using LIKE

The following SQL statement will return persons with first names that
start with an 'O':

SELECT * FROM Persons


WHERE FirstName LIKE 'O%';

The following SQL statement will return persons with first names that
end with an 'a':

SELECT * FROM Persons


WHERE FirstName LIKE '%a'

The following SQL statement will return persons with first names that
contain the pattern 'la':

SELECT * FROM Persons


WHERE FirstName LIKE '%la%';

SQL AND & OR

AND & OR

AND & OR join two or more conditions in a WHERE clause.

The AND operator displays a row if ALL conditions listed are true. The OR operator
displays a row if ANY of the conditions listed are true.

Original Table
LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes

Example

Use AND to display each person with the first name equal to Tove, and
the last name equal to Svendson:

SELECT * FROM Persons


WHERE FirstName='Tove'
11
AND LastName='Svendson';

Result:

LastName FirstName Address City


Svendson Tove Borgvn 23 Sandnes

Example

Use OR to display each person with the first name equal to Tove, or
the last name equal to Svendson:

SELECT * FROM Persons


WHERE firstname='Tove'
OR lastname='Svendson';

Result:

LastName FirstName Address City


Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes

Example

You can also combine AND and OR (use parentheses to form complex
expressions):

SELECT * FROM Persons WHERE


(FirstName='Tove' OR FirstName='Stephen')
AND LastName='Svendson';

Result

LastName FirstName Address City


Svendson Tove Borgvn 23 Sandnes
Svendson Stephen Kaivn 18 Sandnes

SQL IN

IN

The IN operator may be used if you know the exact value you want to
return for at least one of the columns.

12
SELECT columnname FROM tablename
WHERE columnname IN (value1,value2,..);

Original Table (used in the examples)


LastName FirstName Address City
Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes
Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes

Example 1

To display the persons with LastName equal to Hansen or Pettersen,


use the following SQL:

SELECT * FROM Persons


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

Result

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Pettersen Kari Storgt 20 Stavanger

SQL BETWEEN

BETWEEN ... AND

The BETWEEN ... AND operator selects a range of data between two
values. These values can be numbers, text, or dates.

SELECT columnname FROM tablename


WHERE columnname
BETWEEN value1 AND value2;

Original Table (used in the examples)


LastName FirstName Address City
13
Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes
Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes

Example 1

To display the persons alphabetically between (and including) Hansen


and exclusive Pettersen, use the following SQL:

SELECT * FROM Persons WHERE LastName


BETWEEN 'Hansen' AND 'Pettersen';

Result

LastName FirstName Address City


Hansen Ola Timoteivn 10 Sandnes
Nordmann Anna Neset 18 Sandnes

Example 2

To display the persons outside the range used in the previous


example, use the NOT operator:

SELECT * FROM Persons WHERE LastName


NOT BETWEEN 'Hansen' AND 'Pettersen';

Result:

LastName FirstName Address City


Pettersen Kari Storgt 20 Stavanger
Svendson Tove Borgvn 23 Sandnes

The Update Statement

The UPDATE statement is used to modify the data in a table.

14
Syntax

UPDATE tablename
SET columnname = newvalue
WHERE columnname = somevalue;

Person:

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Storgt 67

Update one Column in a Row

We want to add a first name to the person with a last name of


"Rasmussen":

UPDATE Person SET FirstName = 'Nina'


WHERE LastName = 'Rasmussen';

Result:

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Storgt 67

Update several Columns in a Row

We want to change the address and add the name of the city:

UPDATE Person
SET Address = 'Stien 12', City = 'Stavanger'
WHERE LastName = 'Rasmussen';

Result

LastName FirstName Address City


15
Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

SQL ALTER TABLE

ALTER TABLE

The ALTER TABLE statement is used to add or drop columns in an


existing table.

ALTER TABLE tablename


ADD columnname datatype;

ALTER TABLE tablename


DROP COLUMN columnname;

Some database systems don't allow the dropping of a column in a database table (DROP
COLUMN columnname).

Person:

LastName FirstName Address


Pettersen Kari Storgt 20

Example

To add a column named City in the Person table:

ALTER TABLE Person ADD City varchar(30);

Result:

LastName FirstName Address City


Pettersen Kari Storgt 20

Example
16
To drop the Address column in the Person table:

ALTER TABLE Person DROP COLUMN Address

Result:

LastName FirstName City


Pettersen Kari

The DELETE Statement

The DELETE statement is used to delete rows in a table.

Syntax

DELETE FROM tablename


WHERE columnname = somevalue;

Person

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger
Rasmussen Nina Stien 12 Stavanger

Delete a Row

Nina Rasmussen is going to be deleted:

DELETE FROM Person WHERE LastName = 'Rasmussen'

Result

LastName FirstName Address City


Nilsen Fred Kirkegt 56 Stavanger

Delete All Rows

It is possible to delete all rows in a table without deleting the table.


This means that the table structure, attributes, and indexes will be
intact:

DELETE FROM tablename;


or
DELETE * FROM tablename;

17
SQL sorting

The ORDER BY keyword is used to sort the result.

Sort the Rows

The ORDER BY clause is used to sort the rows.

Orders

Company OrderNumber
Orange 3412
Airtel 5678
Zain 6798
Safaricom 2312

Example

To display the company names in alphabetical order:

SELECT Company, OrderNumber FROM Orders


ORDER BY Company;

Result

Company OrderNumber
Orange 5678
Airtel 3412
Zain 6798
Safaricom 2312

Example

To display the company names in alphabetical order AND the


OrderNumber in numerical order:

SELECT Company, OrderNumber FROM Orders


ORDER BY Company, OrderNumber;

18
Result

Company OrderNumber
Orange 5678
Airtel 3412
Zain 2312
Safaricom 6798

Example

To display the company names in reverse alphabetical order:

SELECT Company, OrderNumber FROM Orders


ORDER BY Company DESC

Result:

Company OrderNumber
Zain 6798
Zain 2312
Sega 3412
ABC Shop 5678

Example

To display the company names in reverse alphabetical order AND the


OrderNumber in numerical order:

SELECT Company, OrderNumber FROM Orders


ORDER BY Company DESC, OrderNumber ASC

Result:

Company OrderNumber
Zain 2312
Zain 6798
Sega 3412
ABC Shop 5678

Notice that there are two equal company names in the result above. The only time you
will see the second column in ASC order would be when there are duplicated values in
the first sort column, or a handful of nulls.

19
SQL Alias

With SQL, aliases can be used for column names and table names.

Column Name Alias

The syntax is:

SELECT column AS columnalias FROM table;

Table Name Alias

The syntax is:

SELECT column FROM table AS tablealias;

Example: Using a Column Alias

This table (Persons):

LastName FirstName Address City


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

And this SQL:

SELECT LastName AS Family, FirstName AS Name


FROM Persons;

Returns this result:

20
Family Name
Hansen Ola
Svendson Tove
Pettersen Kari

Example: Using a Table Alias

This table (Persons):

LastName FirstName Address City


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

And this SQL:

SELECT LastName, FirstName


FROM Persons AS Employees;

Returns this result:

Table Employees:

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SQL JOIN

Joins and Keys

Sometimes we have to select data from two or more tables to make our result complete.
We have to perform a join.

Tables in a database can be related to each other with keys. A primary key is a column
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.
21
In the Employees table below, the EmployeeID column is the primary key, meaning that
no two rows can have the same EmployeeID. The EmployeeID distinguishes two persons
even if they have the same name.

When you look at the example tables below, notice that:

 The EmployeeID column is the primary key of the Employees table


 The ProdID column is the primary key of the Orders table
 The EmployeeID column in the Orders table is used to refer to the persons in the
Employees table without using their names

Employees

EmployeeID Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari

Orders

ProdID Product EmployeeID


234 Printer 01
657 Table 03
865 Chair 03

Referring to Two Tables

We can select data from two tables by referring to two tables

Example

Who has ordered a product, and what did they order?

SELECT Employees.Name, Orders.Product


FROM Employees, Orders
WHERE Employees.EmployeeID=Orders.EmployeeID;

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example
22
SELECT Employees.Name
FROM Employees, Orders
WHERE Employees.EmployeeID=Orders.EmployeeID
AND Orders.Product='Printer';

Result

Name
Hansen, Ola

Using Joins

INNER JOIN

The INNER JOIN returns all rows from both tables where there is a match. If there are
rows in Employees that do not have matches in Orders, those rows will not be listed.

Syntax

SELECT field1, field2, field3


FROM firsttable
INNER JOIN secondtable
ON firsttable.keyfield = secondtable.foreignkeyfield;

Example

SELECT Employees.Name, Orders.Product


FROM Employees
INNER JOIN Orders
ON Employees.EmployeeID=Orders.EmployeeID;

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

23
LEFT JOIN

The LEFT JOIN returns all the rows from the first table (Employees), even if there are no
matches in the second table (Orders). If there are rows in Employees that do not have
matches in Orders, those rows also will be listed.

Syntax

SELECT field1, field2, field3


FROM firsttable
LEFT JOIN secondtable
ON firsttable.keyfield = secondtable.foreignkeyfield;

Example

SELECT Employees.Name, Orders.Product


FROM Employees
LEFT JOIN Orders
ON Employees.EmployeeID=Orders.EmployeeID;

Result

Name Product
Hansen, Ola Printer
Svendson, Tove
Svendson, Stephen Table
Svendson, Stephen Chair
Pettersen, Kari

RIGHT JOIN

The RIGHT JOIN returns all the rows from the second table (Orders), even if there are no
matches in the first table (Employees). If there had been any rows in Orders that did not
have matches in Employees, those rows also would have been listed.

Syntax

SELECT field1, field2, field3


24
FROM firsttable
RIGHT JOIN secondtable
ON firsttable.keyfield = secondtable.foreignkeyfield;

Example
SELECT Employees.Name, Orders.Product
FROM Employees
RIGHT JOIN Orders
ON Employees.EmployeeID=Orders.EmployeeID;

Result

Name Product
Hansen, Ola Printer
Svendson, Stephen Table
Svendson, Stephen Chair

Example

SELECT Employees.Name
FROM Employees
INNER JOIN Orders
ON Employees.EmployeeID=Orders.EmployeeID
WHERE Orders.Product = 'Printer';

Result

Name
Hansen, Ola

SQL UNION and UNION ALL

UNION

25
The UNION command is used to select related information from two
tables, much like the JOIN command. However, when using the UNION
command all selected columns need to be of the same data type.

SQL Statement 1
UNION
SQL Statement 2;

Employees1

EmpID EmpName

1 John

2 Emilly

3 James

4 Mary

5 Johnson

Employees2

EmpID EmpName

1 Daniel

2 Donny

3 Kenny

4 Smith

5 Faith

Using the UNION Command

Example

26
SELECT EmpName FROM Employees1
UNION
SELECT EmpName FROM Employees2;

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 is listed. The
UNION command only selects distinct values.

UNION ALL

The UNION ALL command is equal to the UNION command, except


that UNION ALL selects all values.

SQL Statement 1
UNION ALL
SQL Statement 2;

Using the UNION ALL Command

Example

SELECT EmpName FROM Employees1


UNION ALL
SELECT EmpName FROM Employees2;

Create Index

Indices are created in an existing table to locate rows more quickly and efficiently. It is
possible to create an index on one or more columns of a table, and each index is given a
name. The users cannot see the indexes; they are just used to speed up queries.

Updating a table containing indexes takes more time than updating a table without, this is
because the indexes also need an update. So, it is a good idea to create indexes only on
columns that are often used for a search.

A Unique Index

Creates a unique index on a table. A unique index means that two rows cannot have the
same index value.

CREATE UNIQUE INDEX indexname


ON tablename (columnname);

27
The columnname specifies the column you want indexed.

A Simple Index

Creates a simple index on a table. When the UNIQUE keyword is


omitted, duplicate values are allowed.

CREATE INDEX indexname


ON tablename (columnname)

The columnname specifies the column you want indexed.

Example

This example creates a simple index, named PersonIndex, on the LastName field of
the Person table:

CREATE INDEX PersonIndex


ON Person (LastName);

If you want to index the values in a column in descending order, you can add the
reserved word DESC after the column name.

CREATE INDEX PersonIndex


ON Person (LastName DESC);

If you want to index more than one column you can list the column names within the
parentheses, separated by commas.

CREATE INDEX PersonIndex


ON Person (LastName, FirstName);

SQL Drop Index, Table and Database

28
Drop Index

You can delete an existing index in a table with the DROP INDEX statement.

Syntax for MySQL:

ALTER TABLE tablename DROP INDEX indexname;

Delete a Table or Database

To delete a table (the table structure attributes, and indexes will also be
deleted):

DROP TABLE tablename;

To delete a database

DROP DATABASE databasename;


Truncate a Table

What if we only want to get rid of the data inside a table, and not the
table itself? Use the TRUNCATE TABLE command (deletes only the data
inside the table):

TRUNCATE TABLE tablename;

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 in SQL

 AVG( ) - Returns the average value


 COUNT( ) - Returns the number of rows
 FIRST( ) - Returns the first value in a table column
 LAST( ) - Returns the last value in a table column
 MAX( ) - Returns the largest value in a table column
 MIN( ) - Returns the smallest value in a table column
 SUM( ) - Returns the total in a table column

29
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
 TODAY – Returns the current system date

SQL AVG () Function

The AVG () Function

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

SQL AVG ( )

Syntax

SELECT AVG(columnname) FROM tablename;

SQL AVG ( )
Example

Sales

OrderId 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

30
SELECT AVG(OrderPrice) FROM sales;

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 sales


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

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.

SQL COUNT (columnname) Syntax

The COUNT (columnname) function returns the number of values


(NULL values will not be counted) of the specified column:

SELECT COUNT(columnname) FROM tablename;

SQL COUNT (*) Syntax

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

SELECT COUNT(*) FROM tablename;

31
SQL COUNT (DISTINCT columnname) Syntax

The COUNT (DISTINCT columnname) function returns the number of


distinct values of the specified column:

SELECT COUNT(DISTINCT columnname) FROM tablename

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

SQL COUNT(columnname) Example

We have the following Sales table:

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

We use the following SQL statement:

SELECT COUNT(Customer) AS Customer Nilsen FROM Sales


WHERE Customer='Nilsen';

The result of the SQL statement above will be 2, because the customer
Nilsen has made 2 Sales in total:

CustomerNilsen
2

SQL COUNT(*) Example

If we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberofSales FROM Sales

32
The result-set will look like this:

NumberOfSales
6

SQL COUNT(DISTINCT columnname) Example

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

We use the following SQL statement:

SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Sales

The result-set will look like this:

NumberOfCustomers
3

This is the number of unique customers (Hansen, Nilsen, and Jensen) in the Sales table.

SQL FIRST () Function

The FIRST () Function

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

SQL FIRST () Syntax

SELECT FIRST(columnname) FROM tablename;

SQL FIRST () Example

Sales

OrderId 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

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

We use the following SQL statement:

SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Sales

Workaround if FIRST () function is not supported:

SELECT OrderPrice FROM Sales ORDER BY orderid LIMIT 1;

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(columnname) FROM tablename;

SQL LAST () Example

We have the following Sales table:

OrderId 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

34
We use the following SQL statement:

SELECT LAST(orderPrice) AS Last orderPrice FROM Sales;

Workaround if LAST () function is not supported:

SELECT OrderPrice FROM Sales ORDER BY orderid 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(columnname) FROM tablename;

SQL MAX () Example

Sales

OrderId 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 Sales

35
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(columnname) FROM tablename;

SQL MIN () Example

Sales

OrderId 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

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

We use the following SQL statement:

SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Sales

The result-set will look like this:

SmallestOrderPrice
100

The SUM ( ) Function

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


36
Syntax

SELECT SUM(columnname) FROM tablename;

SQL SUM () Example

Sales

OrderId 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 Sales

The result-set will look like this:

OrderTotal
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 columnname, aggregatefunction(columnname)


FROM tablename
37
WHERE columnname operator value
GROUP BY columnname;

SQL GROUP BY Example

Sales

OrderId 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

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

We use the following SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Sales


GROUP BY Customer

The result-set will look like this:

Customer SUM(OrderPrice)
Hansen 2000
Nilsen 1700
Jensen 2000

SELECT Customer, SUM(OrderPrice) FROM Sales

Result

Customer SUM(OrderPrice)

38
Hansen 5700
Nilsen 5700
Hansen 5700
Hansen 5700
Jensen 5700
Nilsen 5700

Explanation of why the above SELECT statement cannot be used: The SELECT
statement above has two columns specified (Customer and SUM (OrderPrice). The SUM
(OrderPrice) returns a single value (that is the total sum of the OrderPrice column), while
Customer returns 6 values (one value for each row in the Sales 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 Sales


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 columnname, aggregatefunction(columnname)


FROM tablename
WHERE columnname operator value
GROUP BY columnname
HAVING aggregatefunction(columnname) operator value

SQL HAVING Example

Sales

OrderId OrderDate OrderPrice Customer


1 2008/11/12 1000 Hansen

39
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

SELECT Customer, SUM(OrderPrice) FROM Sales


GROUP BY Customer
HAVING SUM(OrderPrice)<2000

Result

Customer SUM(OrderPrice)
Nilsen 1700

We add an ordinary WHERE clause to the SQL statement:

SELECT Customer,SUM(OrderPrice) FROM Sales


WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500

Result

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(columnname) FROM tablename;

Syntax for SQL Server

SELECT UPPER(columnname) FROM tablename;


SQL UCASE () Example
40
We have the following Persons table:

PId 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
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(columnname) FROM tablename;

Syntax for SQL Server

SELECT LOWER(columnname) FROM tablename;


SQL LCASE () Example

Persons

PId LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
41
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;

Result

LastName FirstName
Hansen Ola
Venison Tove
Petersen Kari

SQL MID () Function

The MID () Function

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

SQL MID () Syntax

SELECT MID(columnname,start[,length]) FROM tablename;

Parameter Description
columnname 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

Persons

PId LastName FirstName Address City


42
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:

SELECT MID(City,1,4) as SmallCity FROM Persons

Result

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(columnname) FROM tablename;

SQL LEN () Example

Persons

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

43
We use the following SELECT statement:

SELECT LEN(Address) as LengthOfAddress FROM Persons;

The result-set will look like this:

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(columnname,decimals) FROM tablename;

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

SQL ROUND () Example

Products

ProdID ProductName Unit UnitPrice


1 Bread 1000 g 10.45
2 Margarine 1000 g 32.56
3 Milk 1000 g 15.67

SELECT ProductName, ROUND(UnitPrice,0as UnitPrice FROM Products;

Result
44
ProductName UnitPrice
Bread 10
Margarine 33
Milk 16

SQL NOW () Function

The NOW () Function

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

SQL NOW () Syntax

SELECT NOW() FROM tablename;

SQL NOW () Example

We have the following Products table:

ProdID ProductName Unit UnitPrice


1 Bread 1000 g 10.45
2 Margarine 1000 g 32.56
3 Milk 1000 g 15.67

We use the following SELECT statement:

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

The result-set will look like this:

ProductName UnitPrice PerDate


Bread 10.45 10/7/2008 11:25:02 AM
Margarine 32.56 10/7/2008 11:25:02 AM
Milk 15.67 10/7/2008 11:25:02 AM

SQL FORMAT () Function

The FORMAT () Function


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

SQL FORMAT () Syntax

SELECT FORMAT(columnname,format) FROM tablename;

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

SQL FORMAT () Example

We have the following Products table:

ProdID ProductName Unit UnitPrice


1 Bread 1000 g 10.45
2 Margarine 1000 g 32.56
3 Milk 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:

SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate


FROM Products

The result-set will look like this:

ProductName UnitPrice PerDate


Bread 10.45 2008-10-07
Margarine 32.56 2008-10-07
Milk 15.67 2008-10-07

46
SQL PRIMARY KEY Constraint

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the PId column when the Persons table
is created:

MySQL:

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns.

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons


47
(
empno NOT NULL,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT empno PRIMARY KEY (empno)
);

SQL PRIMARY KEY Constraint on ALTER TABLE

To create a PRIMARY KEY constraint on the "P_Id" column when the table is already
created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD PRIMARY KEY (PId)

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons


ADD CONSTRAINT pkPersonID PRIMARY KEY (P_Id,LastName)

Note: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table
was first created).

To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


DROP PRIMARY KEY

SQL Server / Oracle / MS Access:

ALTER TABLE Persons

SQL FOREIGN KEY Constraint

48
SQL FOREIGN KEY Constraint

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

PId LastName FirstName Address City


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

Sales

OrderId OrderNo PId


1 77895 3
2 44678 3
3 22456 2
4 24562 1

Note that the PId column in the "Sales" table points to the "P_Id" column in the "Persons"
table.

The PId column in the Persons table is the PRIMARY KEY in the Persons table.

The PId column in the Sales table is a FOREIGN KEY in the Sales table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.

The FOREIGN KEY constraint also prevents that invalid data form being inserted into
the foreign key column, because it has to be one of the values contained in the table it
points to.

SQL FOREIGN KEY Constraint on CREATE TABLE

49
The following SQL creates a FOREIGN KEY on the PId column when the Sales table is
created:

MySQL:

CREATE TABLE Sales


(
OrderId int NOT NULL,
OrderNo int NOT NULL,
PId int,
PRIMARY KEY (OrderId),
FOREIGN KEY (PId) REFERENCES Persons(PId)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Sales


(
OorderId int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
PId int FOREIGN KEY REFERENCES Persons(PId)
)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Sales


(
OrderId int NOT NULL,
OrderNo int NOT NULL,
PId int,
PRIMARY KEY (OrderId),
CONSTRAINT fkPerSales FOREIGN KEY (PId)
REFERENCES Persons(PId)
)

SQL FOREIGN KEY Constraint on ALTER TABLE

To create a FOREIGN KEY constraint on the "P_Id" column when the "Sales" table is
already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Sales


ADD FOREIGN KEY (PId)
REFERENCES Persons(PId)
50
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Sales


ADD CONSTRAINT fkPerSales
FOREIGN KEY (PId)
REFERENCES Persons(PId)

To DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Sales


DROP FOREIGN KEY fkPerSales
SQL Server / Oracle / MS Access:
ALTER TABLE Sales
DROP CONSTRAINT fkPerSales

51

You might also like