Chapter-6 Add From Handout
Chapter-6 Add From Handout
2
SQL Database Tables
A database is a collection of related data.
It can also be viewed as a collection of related tables.
A table is a set of columns and rows.
Each column is referred to as a field. Each value in a field represents a
single type of data.
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":
The table above contains three records (one for each person) and four
3
columns (LastName, FirstName, Address, and City).
SQL Data Definition Language (DDL)
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
4
Create a Database
To create a database:
CREATE DATABASE database_name;
Create a Table
To create a table in a database:
CREATE TABLE table_name
(
column_name1 data_type, column_name2 data_type,.......
);
Example 1
This example demonstrates how you can create a
table named "Person", with four columns.
The column names will be "LastName", "FirstName",
"Address", and "Age":
5
…CON’T
SQL Query for Example 1 previous
CREATE TABLE Person
(
LastName varchar(30),
FirstName varchar(20),
Address varchar(40),
Age int(3)
);
6
DATA TYPES
The data type specifies what type of data the column can hold.
The table below contains the most common data types in SQL:
9
…CON’T
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);
10
Drop Index
You can delete an existing index in a table with
the DROP statement.
DROP INDEX table_name.index_name;
Delete a Table or Database
To delete a table (the table structure, attributes,
and indexes will also be deleted):
DROP TABLE table_name;
To delete a database:
DROP DATABASE database_name;
11
ALTER TABLE
The ALTER TABLE statement is used to add or drop columns
in an existing table.
ALTER TABLE table_name
ADD column_name datatype;
12
…CON’T
Example 1
To add a column named "City" in the "Person"
table:
ALTER TABLE Person ADD City varchar(30);
Person:
Result:
13
…CON’T
Example 2
To drop the "Address" column in the "Person"
table:
ALTER TABLE Person DROP COLUMN Address;
Person:
Result:
Types of Functions
There are several basic types and categories of functions in
SQL.
The basic types of functions are:
Aggregate Functions
Aggregate functions
Aggregate functions operate against a collection of values, but
return a single value.
Note: If used among many other expressions in the item list of
a SELECT statement, the SELECT must have a GROUP BY
15
clause!!
…CON’T
"Persons" table (used in most examples)
Name Age
Hansen, Ola 34
Svendson, Tove 45
Pettersen, Kari 19
16
AGGREGATE FUNCTIONS IN MS ACCESS
Function Description
AVG(column) Returns the average value of a column
18
GROUP BY and HAVING
Aggregate functions (like SUM) often need an added GROUP
BY functionality.
GROUP BY...
GROUP BY... was added to SQL because aggregate functions
(like SUM) return the aggregate of all column values every
time they are called, and without the GROUP BY function it
was impossible to find the sum for each individual group of
column values.
The syntax for the GROUP BY function is:
SELECT column,SUM(column) FROM table GROUP BY
column;
19
…CON’T
Example 1
GROUP BY Example This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
Company SUM_Amount
W3Schools 17100
IBM 17100
20
W3Schools 17100
…CON’T
The above code is invalid because the column
returned is not part of an aggregate.
A GROUP BY clause will solve this problem:
SELECT Company,SUM(Amount) FROM Sales
GROUP BY Company;
Returns this result:
Company SUM(Amount)
W3Schools 12600
IBM 4500.
21
HAVING
HAVING... was added to SQL because the WHERE
keyword could not be used against aggregate
functions (like SUM), and without HAVING... it
would be impossible to test for result conditions.
The syntax for the HAVING function is:
SELECT column,SUM(column) FROM table
GROUP BY column
HAVING SUM(column) condition value;
This "Sales" Table:
Company Amount
W3Schools 5500
IBM 4500
W3Schools 7100
22
…CON’T
This SQL:
SELECT Sum(Company) as SUM_Amount FROM Sales
GROUP BY Company
HAVING SUM(Amount)>10000;
Company SUM(Amount)
W3Schools 12600
23
…CON’T
AVG Aggregate Function calculates the average
of the values in column
The argument of the function AVG must be
numeric.
All Null values are eliminated before the function
AVG is applied
Syntax
GROUP BY project_no
…CON’T
To get the number of each job in all projects:
26
STATISTICAL AGGREGATE FUNCTIONS
The following AF are belongs to the group of
statistical AF
VAR-computes the variance of all the values
listed in a column or expression.
VARP computes the variance for the population
of all the values listed in a column or expression.
STDEV- Computes the standard deviation of all
the values listed in a column or expression
Is computed as the square root of the corresponding
variance
STDEVP- Computes the standard deviation for the
population of all the values in the column expression
27
THE CREATE VIEW STATEMENT
In SQL, a VIEW is a virtual table based on the
result-set of a SELECT statement.
A view contains rows and columns, just like a real
table.
The fields in a view are fields from one or more real
tables in the database.
You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the
data were coming from a single table.
Note: The database design and structure will NOT
be affected by the functions, where, or join
statements in a view.
28
…CON’T
Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;
29
Using Views
A view could be used from inside a query, a stored
procedure, or from inside another view.
By adding functions, joins, etc., to a view, it allows you to
present exactly the data you want to the user.
The sample database Northwind has some views
installed by default.
The view "Current Product List" lists all active products
(products that are not discontinued) from the Products
table.
The view is created with the following SQL:
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
30
WHERE Discontinued=No;
SQL QUICK REFERENCE
Statement Syntax
32
…CON’T
Below is an example of a table called "Persons":
33
8.1 SQL QUERIES
With SQL, we can query a database and have a
result set returned.
A query like this:
Example 1
Select Some Columns
To select the columns named "LastName" and "FirstName", use
a SELECT statement like this:
35
…CON’T
Example 2
Select All Columns
To select all columns from the "Persons" table, use a * symbol
instead of column names, like this:
36
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:
Example 1
Using the DISTINCT keyword
To select ALL values from the column named "Company" we
use a SELECT statement like this: 37
…CON’T
38
…CON’T
Example 2
To select only DIFFERENT values from the
column named "Company" we use a SELECT
DISTINCT statement like this:
39
The WHERE Clause
To conditionally select data from a table, a WHERE
clause can be added to the SELECT statement.
41
…CON’T
Example 2
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:
42
The LIKE Condition
The LIKE condition is used to specify a search for a
pattern in a column.
43
…CON’T
The following SQL statement will return persons
with first names that end with an 'a':
44
The INSERT INTO Statement
The INSERT INTO statement is used to insert new rows into a
table.
You can also specify the columns for which you want to insert
data:
Example 1
Insert a New Row, This "Persons" table:
45
…CON’T
Example 2
Insert Data in Specified Columns
This "Persons" table:
46
THE UPDATE STATEMENT
The UPDATE statement is used to modify the data in a
table.
Example 1
Update one Column in a Row
This "Persons" table:
47
…CON’T
Example 2
Update several Columns in a Row
This "Persons" table:
48
THE DELETE STATEMENT
The DELETE statement is used to delete rows in a
table.
Example 1
Delete a Row
This "Persons" table:
49
…CON’T
Example 2
Delete All Rows
50
Sort the Rows
The ORDER BY clause is used to sort the rows.
Orders:
Example 1
To display the companies in alphabetical order:
Result:
51
…CON’T
Example 2
To display the companies in alphabetical order AND the order
numbers in numerical order:
Example 3
To display the companies in reverse alphabetical order:
52
…CON’T
Example 4
To display the companies in reverse alphabetical order
AND the
Order numbers in numerical order:
53
AND & OR
AND 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.
Example 1
Use AND to display each person with the first name equal to "Tove",
and the last name equal to "Svendson":
54
…CON’T
Example 2
Use OR to display each person with the first name equal to "Tove",
or the last name equal to "Svendson":
Example 3
You can also combine AND and OR (use parentheses to form
complex expressions):
55
IN OPERATOR
The IN operator may be used if you know the exact value you
want to return for at least one of the columns.
Example 1
To display the persons with LastName equal to "Hansen" or
"Pettersen", use the following SQL:
56
BETWEEN ... AND
The BETWEEN ... AND operator selects a range of data between
two values.
These values can be numbers, text, or dates.
Example 1
To display the persons alphabetically between (and including)
"Hansen" and exclusive "Pettersen", use the following SQL:
57
…CON’T
Example 2
To display the persons outside the range used in the
previous example, use the NOT operator:
58
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.
The purpose is to bind data together, across tables, without repeating all
of the data in every table.
In the "Employees" table below, the "Employee_ID" column is the primary
key, meaning that no two rows can have the same Employee_ID.
The Employee_ID distinguishes two persons even if they have the same
name.
When you look at the example tables below, notice that:
The "Employee_ID" column is the primary key of the "Employees" Table
The "Prod_ID" column is the primary key of the "Orders" table
The "Employee_ID" column in the "Orders" table is used to refer to the persons
in the "Employees" table without using their names
59
THE PRIMARY KEY CLAUSE
The primary key of a table is a column or group of
columns whose values are different in every row.
Example1 shows the specification of the primary key for
the Employee table
USE DML;
CREATE TABLE Employees (
Employee_ID INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(30) NOT NULL
)
60
THE FOREIGN KEY CLAUSE
A foreign key is a column or group of columns in one table that
contains values that match the primary key values in the same
or another table.
Each foreign key is defined using the FOREIGN KEY clause
combined with the REFERENCES clause.
Example shows the specification of the foreign key in the Orders
table of the DML database.
Example 5.10
USE DML;
CREATE TABLE Orders (
Prod_ID VARCHAR(20) NOT NULL primary key,
Product CHAR(10) NOT NULL,
Employee_ID INTEGER NOT NULL Foreign key
REFERENCES Employees) 61
…CON’T
Employees:
62
REFERRING TO TWO TABLES
We can select data from two tables by referring to two tables, like
this:
Example 1
Who has ordered a product, and what did they order?
63
Using Joins
OR we can select data from two tables with the JOIN keyword, like this:
The INNER JOIN returns all rows from both tables where there is a
match.
Syntax
If there are rows in Employees that do not have matches in Orders, those
rows will not be listed.
64
…CON’T
Example LEFT JOIN
Syntax
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.
65
…CON’T
Example RIGHT JOIN
Syntax
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.
66
…CON’T
Example 1
Who ordered a printer?
67
UNION
The UNION command is used to select related information from two
tables, much like the JOIN command.
when using the UNION command all selected columns need to be of
the same data type.
Note: With UNION, only distinct values are selected.
68
Using the UNION Command
Example
List all different employee names in Norway and USA:
70
- END -