Session ID 235 3/9/10 1:15 2:45 - Capistrano Unified...
Transcript of Session ID 235 3/9/10 1:15 2:45 - Capistrano Unified...
EXPERIENCE LEVEL BEGINNER/GENERAL
PRESENTATION LEVEL TECHNICAL
SESSION TYPE NEW
In this session we will describe the basics of a relational
database and cover basic SQL commands that may be of use
in the future transition of QSS software to a relational
database and SQL environment.
Description of Session
Definition of Relational Database
app_user_id screen access_codeprintx di_no site_no yr_no system user_id_name user_audit_id
AAMBRIZ USER-AAMBRIZ Y 3 13 72 2010FINANCE ANA AMBRIZ AAMB
ABETTENC USER-ABETTENC Y 3 6 0 2010PAYROLL ANNAMARIE BETTENCOURT ABET
ABETTIS USER-ABETTIS Y 3 13 84 2010FINANCE ANGELA BETTIS ABET
ABROWN USER-ABROWN Y 3 24 300 2010FINANCIAL ANNETTE BROWN ABRO
ABSENCE USER-ABSENCE Y 3 24 0 2010FIN/PAY ABSENCE TRAINING ABSE
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems like MS SQL
Server, PostgreSQL , IBM DB2, Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables.
A table is a collections of related data entries and it consists of columns and rows.
One-to-one relationships
One-to-one relationships are single-valued in both directions. A manager
manages one department; a department has only one manager.
M_id Name Address D_id
1 John Smith 1234 Oak 2
2 Sam Jones 5241 Clark 1
3 Lisa Haines 12 Meadow 3
D_id Department
1 HR
2 Business Services
3 Information Tech
One-to-many relationships
An employee can work in only one department. One department can have
many employees
D_id Department
1 HR
2 Business Services
3 Information Tech
E_id Name Address D_id
1 Ellen Smith 154 oak 3
2 Sam Jones 358 drake 2
3 Edward Blyth 658 lancer 3
4 Jamie Garcia 985 california 1
5 Taylor Johnson 669 tami 1
Many-to-many relationship
An employee can work on more than one project, and a project can have
more than one employee.
E_id Name
1 Tammi
2 John
3 Sally
4 Sara
5 Jim
6 Eddie
P_Id Projectname
1 Migration
2 Training
3 Advertising
E_id P_id
1 1
1 2
3 2
6 1
6 3
5 1
What is SQL?
•SQL stands for Structured Query Language
•SQL lets you access and manipulate databases
•SQL is an ANSI (American National Standards Institute) standard
What Can SQL do?
•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
Execute Commands
•Command Line Tools
•GUI Tools
•Applications
Interface With Database
•Local Connection
•ODBC
•Applications
SQL DML (Data Manipulation Language) and DDL (Data Definition Language)
SQL can be divided into multiple parts: The Data Manipulation Language (DML) and the
Data Definition Language (DDL) are two examples.
The query and update commands form the DML part of SQL:
•SELECT - extracts data from a database
•UPDATE - updates data in a database
•DELETE - deletes data from a database
•INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted.
•CREATE DATABASE - creates a new database
•CREATE TABLE - creates a new table
•ALTER TABLE - modifies a table
•DROP TABLE - deletes a table
Data Control Language (DCL) statements. Some
examples:
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the
GRANT command
Transaction Control (TCL) statements are used to
manage the changes made by DML statements. It
allows statements to be grouped together into logical
transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which
you can later roll back
ROLLBACK - restore database to original since the last
COMMIT
SET TRANSACTION - Change transaction options like
isolation level and what rollback segment to use
bigintInteger value (-9,223,372,036,854,775,808 -9,223,372,036,854,775,807)
intsmaller Integer value (-2,147,483,648) -(2,147,483,647)
smallint smaller Integer value (-32,768) - (32,767)
tinyint smaller Integer values 0 - 255
bit Integer data value (either 1 or 0 value)
decimal Decimal values from -10^38 - 10^38
numeric Decimal values from -10^38 - 10^38
moneyMoney values (-922,337,203,685,477.5808) -(922,337,203,685,477.5807)
smallmoneySmaller Money Values (-214,748.3648) -(214,748.3647)
datetimeDate value (January 1, 1753) - (December 31, 9999)
smalldatetimeSmaller Date Value (January 1, 1900) - (June 6, 2079)
timestampUnique Number Value (updates when row is updated)
charCharacter String Value (max 8,000 characters)
varcharCharacter String Value maximum of 8,000 characters, unless otherwise noted)
ncharCharacter String Value (max 4,000 characters)
nvarcharCharacter String Value (max 4,000 characters)
textCharacter String Value (max 2,147,483,647 characters)
ntextCharacter String Value (max 1,073,741,823 characters)
binary Binary Value (max 8,000 bytes)
varbinary Binary Value (max 8,000 bytes)
image Binary Value (max 2,147,483,647 bytes)
uniqueidentifier Global Unique ID (GUID)
SQL Server Data Types
The SQL SELECT Statement
The SELECT statement is used to select data from a database.
The result is stored in a result table, called the result-set.
SELECT column_name(s) FROM table_name
SELECT * FROM Persons
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
SELECT LastName,FirstName FROM Persons
LastName FirstNameHansen OlaSvendson TovePettersen Kari
The SQL SELECT DISTINCT Statement
In a table, some of the columns may contain duplicate values. This is not a problem, however,
sometimes you will want to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only distinct (different) values.
SELECT DISTINCT column_name(s) FROM table_name
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT DISTINCT City FROM Persons
CitySandnesStavanger
SQL WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified
criteria.
SELECT column_name(s) FROM table_name WHERE column_name operator value
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons WHERE City='Sandnes'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
Quotes Around Text FieldsSQL uses single quotes around text values (most
database systems will also accept double quotes).
Although, numeric values should not be enclosed in
quotes
This is correct:
SELECT * FROM Persons WHERE FirstName='Tove'
This is wrong:
SELECT * FROM Persons WHERE FirstName=Tove
For text values:
For numeric values:
This is correct:
SELECT * FROM Persons WHERE Year=1965
This is wrong:
SELECT * FROM Persons WHERE Year='1965'
Operators Allowed in the WHERE Clause
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 equalBETWEEN Between an inclusive rangeLIKE Search for a patternIN If you know the exact value you want to
return for at least one of the columns
Note: In some versions of SQL the <> operator may be written as !=
SQL AND & OR Operators
The AND & OR operators are used to filter records based on more than one condition.
The AND & OR Operators
The AND operator displays a record if both the first condition and the second
condition is true.
The OR operator displays a record if either the first condition or the second
condition is true.
AND Operator Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
Now we want to select only the persons with the first name equal to "Tove" AND the last
name equal to "Svendson":
SELECT * FROM Persons WHERE FirstName='Tove„ AND
LastName='Svendson'
P_Id LastName FirstName Address City2 Svendson Tove Borgvn 23 Sandnes
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove" OR the first name
equal to "Ola":
SELECT * FROM Persons WHERE FirstName='Tove„ OR FirstName='Ola'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons WHERE FirstName='Tove„ OR 'Ola'
SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set.
The ORDER BY keyword is used to sort the result-set
by a specified column.
The ORDER BY keyword sort the records in ascending
order by default.
If you want to sort the records in a descending order,
you can use the DESC keyword.
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
ORDER BY Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Tom Vingvn 23 Stavanger
Now we want to select all the persons from the table above, however, we want to
sort the persons by their last name.
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes4 Nilsen Tom Vingvn 23 Stavanger3 Pettersen Kari Storgt 20 Stavanger2 Svendson Tove Borgvn 23 Sandnes
SELECT * FROM Persons ORDER BY LastName
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Tom Vingvn 23 Stavanger
ORDER BY DESC Example
Now we want to select all the persons from the table above, however, we
want to sort the persons descending by their last name.
SELECT * FROM Persons ORDER BY LastName
DESC
P_Id LastName FirstName Address City2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Tom Vingvn 23 Stavanger1 Hansen Ola Timoteivn 10 Sandnes
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted,
only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2,
column3,...)
VALUES (value1, value2, value3,...)
SQL INSERT INTO Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger
Insert Data Only in Specified Columns
It is also possible to only add data in specific columns.
The following SQL statement will add a new row, but
only add data in the "P_Id", "LastName" and the
"FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger5 Tjessem Jakob
The UPDATE Statement
The UPDATE statement is used to update existing
records in a table.
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
SQL UPDATE Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger5 Tjessem Jakob
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger5 Tjessem Jakob Nissestien 67 Sandnes
SQL UPDATE Warning
Caution:
The WHERE clause (in the previous slide) specifies which record or records that should be updated. If you
omit the WHERE clause, all records will be updated!
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
P_Id LastName FirstName Address City1 Hansen Ola Nissestien 67 Sandnes2 Svendson Tove Nissestien 67 Sandnes3 Pettersen Kari Nissestien 67 Sandnes4 Nilsen Johan Nissestien 67 Sandnes5 Tjessem Jakob Nissestien 67 Sandnes
The DELETE Statement
The DELETE statement is used to delete rows in a
table.
DELETE FROM table_name
WHERE some_column=some_value
Caution:
Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or
records that should be deleted. If you omit the WHERE clause, all records will be deleted!
SQL DELETE ExampleP_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger5 Tjessem Jakob Nissestien 67 Sandnes
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Johan Bakken 2 Stavanger
DELETE FROM table_name
or
DELETE * FROM table_name
or
TRUNCATE TABLE table name
Note: Be very careful when deleting records. You cannot undo this statement!
Delete All Rows
The TOP Clause
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.
SELECT TOP number|percent column_name(s)
FROM table_name
SQL SELECT TOP Equivalent in PostgreSQL and Oracle
SELECT column_name(s)
FROM table_name
LIMIT number
SELECT *
FROM Persons
LIMIT 5
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number
SELECT *
FROM Persons
WHERE ROWNUM <=5
SQL TOP And TOP PERCENT Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger4 Nilsen Tom Vingvn 23 Stavanger
SELECT TOP 2 * FROM Persons
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
SELECT TOP 50 PERCENT * FROM Persons
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
The LIKE Operator
The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
LIKE Operator Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE City LIKE 's%'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE City LIKE '%s'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
LIKE Operator Example Cont…
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE City LIKE '%tav%'
P_Id LastName FirstName Address City3 Pettersen Kari Storgt 20 Stavanger
It is also possible to select the persons living in a city that NOT contains the
pattern "tav" from the "Persons" table, by using the NOT keyword.
SELECT * FROM Persons
WHERE City NOT LIKE '%tav%'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
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.
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] or [!charlist] Any single character not in charlist
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 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.
SELECT * FROM Persons
WHERE City LIKE 'sa%'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes
Using the _ Wildcard
Now we want to select the persons with a first name that starts with any character, followed
by "la" from the "Persons" table.
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
SELECT * FROM Persons
WHERE FirstName LIKE '_la'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
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.
SELECT * FROM Persons
WHERE LastName LIKE '[bsp]%'
P_Id LastName FirstName Address City2 Svendson Tove Borgvn 23 Sandnes3 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.
SELECT * FROM Persons
WHERE LastName LIKE '[!bsp]%'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 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.
SELECT * FROM Persons
WHERE LastName IN ('Hansen','Pettersen')
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes3 Pettersen Kari Storgt 20 Stavanger
NOT can be used exclude values listed
The BETWEEN Operator
The BETWEEN operator selects a range of data between two values. The values can be numbers,
text, or dates.
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
BETWEEN Operator Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 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.
SELECT * FROM Persons
WHERE LastName
BETWEEN 'Hansen' AND 'Pettersen'
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes
To display the persons outside the range in the example, use NOT BETWEEN
Note: The BETWEEN operator is treated differently in different databases.
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.
Between Note:
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
•MIN() - Returns the smallest value
•SUM() - Returns the sum
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.
SELECT column_name,
aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
SQL GROUP BY Example
O_Id OrderDate OrderPrice Customer1 2008/11/12 1000 Hansen2 2008/10/23 1600 Nilsen3 2008/09/02 700 Hansen4 2008/09/03 300 Hansen5 2008/08/30 2000 Jensen6 2008/10/04 100 Nilsen
Now we want to find the total sum (total order) of each customer.
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
Customer SUM(OrderPrice)Hansen 2000Nilsen 1700Jensen 2000
The HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.
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
O_Id OrderDate OrderPrice Customer1 2008/11/12 1000 Hansen2 2008/10/23 1600 Nilsen3 2008/09/02 700 Hansen4 2008/09/03 300 Hansen5 2008/08/30 2000 Jensen6 2008/10/04 100 Nilsen
Now we want to find if any of the customers have a total order of less than 2000.
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
Customer SUM(OrderPrice)Nilsen 1700
SQL HAVING Example 2
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.
SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500
Customer SUM(OrderPrice)Hansen 2000Jensen 2000
SQL JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables, based on a
relationship between certain columns in these tables.
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.
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 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.
O_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 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
•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.
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON
table_name1.column_name=table_name2.column_name
Note: INNER JOIN is the same as JOIN.
SQL INNER JOIN ExampleP_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 34764 15
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
LastName FirstName OrderNoHansen Ola 22456Hansen Ola 24562Pettersen Kari 77895Pettersen Kari 44678
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).
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 34764 15
Now we want to list all the persons and their orders - if any, from the tables above.
SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
SQL LEFT JOIN Example Cont…
LastName FirstName OrderNoHansen Ola 22456Hansen Ola 24562Pettersen Kari 77895Pettersen Kari 44678Svendson 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).
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if
there are no matches in the left table (table_name1).
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 34764 15
Now we want to list all the orders with containing persons - if any, from the tables above.
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
SQL RIGHT JOIN Example Cont…
LastName FirstName OrderNoHansen Ola 22456Hansen Ola 24562Pettersen Kari 77895Pettersen 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.
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL FULL JOIN ExampleP_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 34764 15
Now we want to list all the persons and their orders, and all the orders with their persons.
SELECT Persons.LastName, Persons.FirstName,
Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
SQL FULL JOIN Example Cont…
LastName FirstName OrderNoHansen Ola 22456Hansen Ola 24562Pettersen Kari 77895Pettersen Kari 44678Svendson Tove
34764
The FULL JOIN keyword returns all the rows from the left table (Persons), and all the rows from the
right table (Orders). If there are rows in "Persons" that do not have matches in "Orders", or if there are
rows in "Orders" that do not have matches in "Persons", those rows will be listed as well.
The SQL UNION Operator
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.
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION
ALL.
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
Note: 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
"Employees_Norway":
E_ID E_Name01 Hansen, Ola02 Svendson, Tove03 Svendson, Stephen04 Pettersen, Kari
"Employees_USA":
E_ID E_Name01 Turner, Sally02 Kent, Clark03 Svendson, Stephen04 Scott, Stephen
Now we want to list all the different employees in Norway and USA.
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
E_NameHansen, OlaSvendson, ToveSvendson, StephenPettersen, KariTurner, SallyKent, ClarkScott, 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.
The SQL SELECT INTO Statement
The SELECT INTO statement selects data from one table and inserts it into a different table.
The SELECT INTO statement is most often used to create backup copies of tables.
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename
We can select all columns into the new table:
Or we can select only the columns we want into the new table:
SELECT column_name(s)
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.
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
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
The CREATE DATABASE Statement
CREATE DATABASE database_name
CREATE DATABASE Example
Now we want to create a database called "my_db".
We use the following CREATE DATABASE statement:
CREATE DATABASE my_db
Database tables can be added with the CREATE TABLE statement.
The CREATE TABLE Statement
The CREATE TABLE statement is used to create a table in a database.
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
....
)
The data type specifies what type of data the column can hold. For a complete reference of all the
data types available in MS Access, MySQL, and SQL Server, Reference the documentation for the
SQL server you will be using
CREATE TABLE Example
Now we want to create a table called "Persons" that contains five columns:
P_Id, LastName, FirstName, Address, and City.
CREATE TABLE Persons
(
P_Id int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The P_Id column is of type int and will hold a number. The LastName,
FirstName, Address, and City columns are of type varchar with a maximum
length of 255 characters.
P_Id LastName FirstName Address City
The ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table.
ALTER TABLE table_name
ADD column_name datatype
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
The DROP TABLE Statement
DROP TABLE table_name
The DROP DATABASE Statement
DROP DATABASE database_name
The TRUNCATE TABLE Statement
TRUNCATE TABLE table_name
SQL NULL Values
If a column in a table is optional, we can insert a new record or update an existing
record without adding a value to this column. This means that the field will be
saved with a NULL value.
NULL values are treated differently from other values.
NULL is used as a placeholder for unknown values.
Note: It is not possible to compare NULL and 0; they are not equivalent.
SQL Working with NULL Values
P_Id LastName FirstName Address City1 Hansen Ola Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Stavanger
How can we test for NULL values?
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators instead.
SQL IS NULL
How do we select only the records with NULL values in the "Address" column?
We will have to use the IS NULL operator:
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL
LastName FirstName AddressHansen OlaPettersen Kari
SQL IS NOT NULL
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL
LastName FirstName AddressSvendson Tove Borgvn 23
Auto Increment A Field
Very often we would like the value of the primary key field to be created
automatically every time a new record is inserted.
Syntax for SQL Server
CREATE TABLE Persons
(
P_Id int PRIMARY KEY IDENTITY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The MS SQL Server uses the IDENTITY keyword to
perform an auto-increment feature.
By default, the starting value for IDENTITY is 1, and it
will increment by 1 for each new record.
To specify that the "P_Id" column should start at value
10 and increment by 5, change the identity to
IDENTITY(10,5).
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
Syntax for Postgres
CREATE TABLE Persons
(
P_Id int PRIMARY KEY serial,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
The Postgres Server uses the “serial” keyword to
perform an auto-increment feature.
The starting value for “serial” is 1, and it will increment
by 1 for each new record.
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column
(a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')
Syntax for Oracle
In Oracle the code is a little bit more tricky.
You will have to create an auto-increment field with the
sequence object (this object generates a number
sequence).
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called
seq_person, that starts with 1 and will increment by 1. It
will also cache up to 10 values for performance. The
cache option specifies how many sequence values will
be stored in memory for faster access.
To insert a new record into the "Persons" table, we will
have to use the nextval function (this function retrieves
the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
SQL Constraints
Constraints are used to limit the type of
data that can go into a table.
Constraints can be specified when a table
is created (with the CREATE TABLE
statement) or after the table is created
(with the ALTER TABLE statement).
We will focus on the following constraints:
•NOT NULL
•UNIQUE
•PRIMARY KEY
•FOREIGN KEY
•DEFAULT
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT
accept NULL values.
The NOT NULL constraint enforces a field to always
contain a value. This means that you cannot insert a
new record, or update a record without adding a value
to this field.
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL UNIQUE Constraint on CREATE TABLE
The following SQL creates a UNIQUE constraint on the "P_Id" 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),
UNIQUE (P_Id)
)
SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT
NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use
the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE 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 UNIQUE (P_Id)
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ADD CONSTRAINT uc_PersonID UNIQUE
(P_Id,LastName)
To DROP a UNIQUE Constraint
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID
ALTER TABLE Persons
DROP INDEX uc_PersonID
MySQL:
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
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)
)
MySQL: 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, use the following SQL syntax:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY
(P_Id,LastName)
)
MySQL / SQL Server / Oracle / MS Access:
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 (P_Id)
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 pk_PersonID PRIMARY KEY
(P_Id,LastName)
To DROP a PRIMARY KEY Constraint
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger
O_Id OrderNo P_Id1 77895 32 44678 33 22456 24 24562 1
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy link between
tables.
The FOREIGN KEY constraint also prevents that invalid data is 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
SQL Server / Oracle / MS Access:
CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
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 Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is
already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
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 Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To DROP a FOREIGN KEY Constraint
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders
SQL Server / Oracle / MS Access:
ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a
default value into a column.
The default value will be added to all new
records, if no other value is specified.
SQL DEFAULT Constraint on CREATE TABLE
My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
SQL DEFAULT Constraint on ALTER TABLE
ALTER TABLE Persons
ALTER City SET DEFAULT 'SANDNES'
MySQL:
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
To DROP a DEFAULT Constraint
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT
SQL Server / Oracle / MS Access:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL 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 one single table.
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Note: A view always shows up-to-date data! The database engine recreates the data, using the view's
SQL statement, every time a user queries a view.