SQL
SQL
From:
http://www.w3schools.com/sql
SQL
It is a standard language for accessing and
manipulating databases
MySQL, SQL Server, Access, Oracle, Sybase,
DB2, and others
SQL
SQL include
Data Manipulation Language (DML)
Data Definition Language (DDL)
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn
10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
Pettersen
Kari
Storgt 20
Stavanger
select * from t2
/
select * from t3
/
select * from t1
go
select * from t2
go
select * from t3
go
SQL BASIC
SELECT
SELECT is used to select data from a database
The result is stored in a result table, called the
result-set
SQL is not case sensitive
SELECT syntax
SELECT column_name(s)
FROM table_name;
SELECT * FROM table_name;
SELECT
Persons Table
P_Id
LastName
FirstName
Address
City
Hansen
Ola
Timoteivn
10
Sandnes
Svendson
Tove
Borgvn 23
Sandnes
3
Pettersen
Kari
Storgt 20
SELECT LastName, FirstName FROM
Persons;
Stavanger
SELECT DISTINCT
SELECT DISTINCT column_name(s)
FROM table_name;
WHERE clause
SELECT column_name(s)
FROM table_name
WHERE column_name operator value;
SELECT * FROM persons
WHERE city=Sandnes;
WHERE Clause
Text values should be quoted by single
quotes or double quotes
Numeric values do not need to be
enclosed in quotes
SELECT * FROM
persons
WHERE
city=Sandnes;
Or
SELECT * FROM
persons
WHERE
city=Sandnes;
Or
SELECT * FROM
WHERE Clause
Operator
Description
Equal
<>
Not equal
>
Greater than
<
Less than
>=
<=
BETWEEN
LIKE
IN
AND or OR
AND, OR operators are used to filter records
based on more than one condition
AND=both the first and the second conditions is
true
OR=either the first or the second condition is true
AND or OR
SELECT * FROM persons
WHERE firstname=Tove AND
lastname=Svendson;
ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC;
ORDER BY
INSERT INTO persons VALUES (4, Nilsen, Tom, Vingvn23',
'Stavanger');
INSERT INTO
Use to insert new records in a table
INSERT INTO table_name
VALUES (value1, value2,
value3,);
INSERT INTO table_name (column1, column2, column3,
VALUES (value1, value2, value3,);
INSERT INTO persons VALUES (4, Nilsen, Tom, Vingvn23',
'Stavanger');
INSERT INTO persons (P_Id, lastname, firstname)
VALUES (5, Tjessem, Jakob);
UPDATE
Update records in a table
UPDATE table_name
SET column=value, column2=value2,
WHERE some_column=some_value;
UPDATE Persons
SET Address=Nissestien 67, city=Sandnes
WHERE lastname=Tjessem AND firstname=Jakob;
Warning: if you forget to add WHERE clause, all the address and
city will be set to Nissestien 67 and Sandnes.
DELETE statement
Used to delete records in a table
DELETE FROM table_name
WHERE some_column=some_value;
DELETE FROM persons
WHERE lastname=Tjessem AND firstname=Jakob;
CompanyName
Alfreds Futterkiste
Berglunds snabbkp
Centro comercial
Moctezuma
Ernst Handel
FISSA Fabrica Inter.
Salchichas S.A.
Galera del gastrnomo
Test
ContactName
Maria Anders
Christina
Berglund
Francisco
Chang
Roland
Mendel
Diego Roel
Address
Obere Str. 57
Berguvsvgen 8
City
Berlin
Lule
Sierras de Granada
9993
Kirchgasse 6
Mxico D.F.
C/ Moralzarzal, 86
Madrid
Graz
Eduardo
Rambla de Catalua, 23 Barcelona
Saavedra
Island Trading
Helen
Garden House Crowther Cowes
Bennett
Way
Kniglich Essen
Philip Cramer Maubelstr. 90
Brandenburg
Laughing Bacchus Wine
Yoshi
1900 Oak St.
Vancouver
Cellars
Tannamuri
Magazzini Alimentari
Giovanni
Via Ludovico il Moro 22 Bergamo
Riuniti
Rovelli
North/South
Simon
South House 300
London
Crowther
Queensbridge
Paris spcialits
Marie
265, boulevard
Paris
Bertrand
Charonne
Rattlesnake Create
Canyon this Customers
Paula Wilson
2817
Milton
Dr.following
Albuquerque
table
and
do the
Grocery
SQL queries
TEST
TEST
SELEC * FROM customers;
SELECT CompanyName, ContactName FROM
customers;
SELECT * FROM customers WHERE companyname
LIKE a%;
SELECT * FROM customers WHERE companyname
LIKE A%;
SELECT companyname, contactname
FROM customers
WHERE companyname > A;
SELECT companyname, contactname
FROM customers
WHERE companyname > G
AND contactname > G;
SQL ADVANCED
LIMIT clause
Used to specify the number of records to return
SELECT column_name(s)
FROM table_name
LIMIT number;
SELECT * FROM persons LIMIT 2;
LIKE operator
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
SELECT * FROM persons WHERE city LIKE
S%;
%: define
wildcards
(missing letters)
both before and
after the pattern
SQL Wildcards
Description
SQL Wildcards
SELECT * FROM persons WHERE city
LIKE Sa%;
IN operator
To specify multiple values in a
SELECT
column_name(s)
WHERE
clause
FROM table_name
WHERE column_name IN (value1, value2,)
SELECT * FROM Persons
WHERE lastname IN (Hansen, Pettersen)
SELECT * FROM Persons
WHERE lastname IN (SELECT lastname from Persons
where city=Sandnes)
BETWEEN operator
Warning:
different
database
systems have
different ways of
processing
BETWEEN
operator
Alias
An alias name can be given to a table or a column
SELECT column_name(s)
FROM table_name AS alias_name;
Or
SELECT column_name AS alias_name
FROM table_name;
SELECT po.O_ID, p.LastName, p.FirstName
FROM Persons AS p, Orders AS po
WHERE p.LastName='Hansen' AND p.FirstName='Ola';
Without alias
SELECT Orders.OrderID, Persons.LastName,
Persons.FirstName
FROM Persons, Orders
WHERE Persons.LastName=Hansen AND
Persons.FirstName=Ola;
JOIN
Used to query data from two or more tables
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 where there is a match in one of
the tables
JOIN
O_Id
OrderNo
P_Id
77895
44678
22456
24562
34764
15
INTO
INTO
INTO
INTO
INTO
orders
orders
orders
orders
orders
VALUES
VALUES
VALUES
VALUES
VALUES
(1,
(2,
(3,
(4,
(5,
77895,
44678,
22456,
24562,
34764,
3);
3);
1);
1);
15);
INNER JOIN
SELECT column_name(s)
FROM table_name1 INNER JOIN table_name2
ON
table_name1.column_name=table_name2.column_n
ame;
SELECT persons.lastname, persons.firstname,
orders.orderNo
From Persons INNER JOIN Orders
ON persons.P_Id=orders.P_Id
ORDER BY persons.Lastname;
The INNER JOIN keyword returns
rows where there is at least one
match in both tables. If there are
rows in Persons that do not have
matches in Orders, those rows
will NOT be listed.
LEFT JOIN
Returns all rows from the left table, even if there are no matches in the right table
SELECT column_name(s)
FROM table_name1 LEFT JOIN table_name2
ON
table_name1.column_name=table_name2.column_n
ame;
SELECT persons.lastname, persons.firstname,
orders.orderno
FROM persons LEFT JOIN orders
ON persons.P_Id=orders.P_Id
ORDER BY persons.lastname;
In some
databases,
LEFT JOIN
is called
LEFT
OUTER
JOIN
RIGHT JOIN
Returns all rows from the right table (table 2), even if there are no matches in the left table (table 1)
SELECT column_name(s)
FROM table_name1 RIGHT JOIN table_name2
ON
table_name1.column_name=table_name2.column_n
ame;
SELECT persons.lastname, persons.firstname,
orders.orderno
FROM persons RIGHT JOIN orders
ON persons.P_Id=orders.P_Id
ORDER BY persons.lastname;
In some
databases,
RIGHT JOIN
is called
RIGHT
OUTER
JOIN
FULL JOIN
UNION operator
CREATE DATABASE
CREATE TABLE
Constraints
Used to limit the type of data that can go into a table
Can be specified when a table is created (with the
CREATE TABLE statement) or after the table is created
(with the ALTER TABLE statement)
Type of constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NOT NULL
Enforce a column to not accept NULL
values
CREATE
TABLE Persons
(
P_Id
INT NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address
varchar(255),
City
varchar(255)
);
UNIQUE
Uniquely identifies each record in a
database table
UNIQUE and PRIMARY KEY both
provide a guarantee for uniqueness
for a column or set of columns
A PRIMARY KEY constraint
automatically has a UNIQUE
constraint defined on it.
UNIQUE
CREATE TABLE Persons
CREATE TABLE Persons
(
(
P_Id
INT NOT NULL,
P_Id
INT NOT NULL UNIQUE,
LastName varchar(255) NOT
LastName varchar(255) NOT
NULL,
NULL,
FirstName varchar(255),
FirstName varchar(255),
Addressvarchar(255),MySQ
Addressvarchar(255),
Cityvarchar(255)
Cityvarchar(255)
L
UNIQUE (P_Id)
); SQL Server/Oracle/MS
Access
);
CREATE TABLE Persons
(
MySQL/SQL Server/Oracle/MS
P_Id
INT NOT NULL,
Access
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Addressvarchar(255),
Cityvarchar(255)
CONSTRAINT uc_PersonID UNIQUE (P_Id,
LastName)
);
UNIQUE
When Persons table has already been
created, use Alter to add new
constraints.
ALTER TABLE
ALTER TABLE Persons
Persons
ADD CONSTRAINT un_PersonID UNIQUE (P_Id,
ADD UNIQUE (P_Id)
LastName)
To drop a UNIQUE constraint
ALTER TABLE Persons
DROP INDEX un_PersonID MySQL
ALTER TABLE Persons
DROP CONSTRAINT
un_PersonID
PRIMARY KEY
Each table should have one and only one primary key
Primary key should be unique and does not contain NULL values
CREATE TABLE Persons
CREATE TABLE Persons
(
(
P_Id
INT NOT NULL,
P_Id
INT NOT NULL PRIMARY
LastName varchar(255) NOT
KEY,
NULL,
LastName varchar(255) NOT
FirstName varchar(255),
NULL,
Addressvarchar(255),
FirstName varchar(255),
Cityvarchar(255)
Addressvarchar(255),
SQL Server/Oracle/MS
MySQL
PRIMARY KEY (P_Id)
Cityvarchar(255)
Access
);
);
CREATE TABLE Persons
( P_Id INT NOT NULL,
LastName varchar(255) NOT NULL,MySQL/SQL
Server/Oracle/MS Access
FirstName varchar(255),
Addressvarchar(255),
Cityvarchar(255)
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,
PRIMARY KEY
When Persons table has already been
created, use Alter to add new
constraints.
ALTER TABLE Persons ALTER TABLE Persons
ADD PRIMARY KEY
ADD CONSTRAINT un_PersonID PRIMARY KEY (P_Id,
(P_Id)
LastName)
To drop a constraint
ALTER TABLE Persons
DROP PRIMARY KEY
ALTER TABLE Persons
DROP CONSTRAINT
pk_PersonID
MySQL
FOREIGN KEY
A foreign key in one table points to a primary key in another table
The foreign key constraint prevents invalid data from being inserted into the foreign
key column because it has to be one of the values contained in the table it points to.
FOREIGN KEY
When Orders table has already been
created, use Alter to add new
constraints.
ALTER TABLE Orders
ALTER TABLE Orders
ADD CONSTRAINT
ADD FOREIGN KEY (P_Id)
fk_PerOrders
REFERENCES Persons
FOREIGN KEY (P_Id)
(P_Id)
REFERENCES Persons(P_Id)
To drop a constraint
MySQL
ALTER TABLE Orders
DROP FOREIGN KEY
fk_PerOrders
ALTER TABLE Orders
DROP CONSTRAINT
fk_PerOrders
CHECK Constraint
CHECK Constraint
When a table has already been created,
use Alter to add new constraints.
ALTER TABLE Persons
ADD CHECK (P_Id>0)
To drop a constraint
ALTER TABLE Persons
DROP CONSTRAINT
chk_Person
DEFAULT Constraint
DEFAULT Constrain
When a table has already been created,
use Alter to add new constraints.
ALTER TABLE Persons
ALTER COLUMN City SET
DEFAULT Sandnes
To drop a constraint
MySQL
ALTER TABLE Persons
ALTER City DROP DEFAULT
ALTER TABLE Persons
ALTER COLUMN City DROP
DEFAULT
MySQL
SQL Views
A view is a virtual table based on the result-set of an SQL statement
A view just looks like a real table with fields and records from one or
more real tables in the database
CREATE VIEW
SandnesLastName AS
SELECT LastName
FROM Sandnes
SELECT * FROM
SandnesLastName
SQL Views
A view can be updated or dropped
CREATE OR REPLACE OR ALTER VIEW
view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
ALTER VIEW Sandnes AS
SELECT LastName, FirstName,
Address
FROM Persons
WHERE city=Sandnes
SQL FUNCTIONS
SQL Functions
SQL Aggregate functions: return a single
value calculated from values in a column
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
SQL Functions
SQL Scalar functions: returns a single value
based on the input value
UCASE() Converts a field to upper case
LCASE() Converts a field to lower case
MID() Extracts 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
ProductNa
me
UnitPrice
UnitsInStoc UnitsOnOrd
k
er
Jarlsberg
10.45
16
15
Mascarpon
e
32.56
23
20
3
Gorgonzola
15.67
CREATE
TABLE products
(
P_Id
INT,
ProductName VARCHAR(25),
UnitPrice
decimal,
UnitsInStock
INT,
UnitsOnOrder
INT,
PRIMARY KEY (P_Id)
);
OrderDate
OrderPrice
Customer
2008/11/12
1000
Hansen
2008/10/23
1600
Nilsen
2008/09/02
700
Hansen
2008/09/03
300
Hansen
2008/08/30
2000
Jensen
2008/10/04
100
Nilsen
2011-08-06,
2011-08-07,
2011-08-08,
2011-08-09,
2011-08-10,
2011-08-11,
1000, Hansen);
1600, Nilsen);
700, Hansen);
300, Hansen);
2000, Jensen);
100, Nilsen);
start
length
Optional. The number of characters to return. If
omitted,
MID() function
SELECT MID(City,
1, 4) the
as SmallCity
From returns the rest of the
MySQL
text
Persons
SELECT substr(City, 1, 4) as SmallCity
From Persons
PostgreS
QL
PostgreSQL: http://www.postgresql.org/docs/9.1/static/functions-
Description
column_na
me
decimals
Required. Specifies the number of decimals to be
returned.
UPDATE Products
SET
UnitPrice=10.49
WHERE P_Id=1
SELECT ROUND(UnitPrice, 0) as Price
From Products
Function
Description
NOW()
CURDATE()
CURTIME()
DATE()
EXTRACT()
DATE_ADD()
DATE_SUB()
DATEDIFF()
PostgreSQL: http://www.postgresql.org/docs/8.2/static/functionsdatetime.html
MySQL
SELECT
NOW()
PostgreS
QL
DATE(date)
SELECT ProductName, DATE(OrderDate) as
OrderDate
FROM Orders
WHERE OrderId=1
MySQL DATE_ADD()
Function
MySQL DATE_FORMAT()
Function
DATE_FORMAT(date, format)
SELECT DATE_FORMAT(NOW(), %m-%d-%y)
Function
Description
GETDATE()
DATEPART()
DATEADD()
DATEDIFF()
CONVERT()
SQL DATATYPES
SQL Datatype
Access
Data type
Text
Memo
Byte
Integer
Long
Single
Double
Currency
AutoNumber
Date/Time
Yes/No
OLE Object
Hyperlink
Description
Storage
Use for text or combinations of text and numbers. 255
characters maximum
Memo is used for larger amounts of text. Stores up to 65,536
characters. Note: You cannot sort a memo field. However,
they are searchable
Allows whole numbers from 0 to 255
1 byte
Allows whole numbers between -32,768 and 32,767
2 bytes
Allows whole numbers between -2,147,483,648 and
4 bytes
2,147,483,647
Single precision floating-point. Will handle most decimals
4 bytes
Double precision floating-point. Will handle most decimals
8 bytes
Use for currency. Holds up to 15 digits of whole dollars, plus 4 8 bytes
decimal places. Tip: You can choose which country's currency
to use
AutoNumber fields automatically give each record its own
4 bytes
number, usually starting at 1
Use for dates and times
8 bytes
A logical field can be displayed as Yes/No, True/False, or
1 bit
On/Off. In code, use the constants True and False (equivalent
to -1 and 0). Note: Null values are not allowed in Yes/No
fields
Can store pictures, audio, video, or other BLOBs (Binary Large up to
OBjects)
1GB
Contain links to other files, including web pages
SQL Datatype
Data type
CHAR(size)
MySQL:
Text
Description
Holds a fixed length string (can contain letters, numbers, and
special characters). The fixed size is specified in parenthesis. Can
store up to 255 characters
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and
special characters). The maximum size is specified in
parenthesis. Can store up to 255 characters. Note: If you put a
greater value than 255 it will be converted to a TEXT type
TINYTEXT
Holds a string with a maximum length of 255 characters
TEXT
Holds a string with a maximum length of 65,535 characters
BLOB
For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of
data
MEDIUMTEXT
Holds a string with a maximum length of 16,777,215 characters
MEDIUMBLOB
For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes
of data
LONGTEXT
Holds a string with a maximum length of 4,294,967,295
characters
LONGBLOB
For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295
bytes of data
ENUM(x,y,z,etc. Let you enter a list of possible values. You can list up to 65535
)
values in an ENUM list. If a value is inserted that is not in the list,
a blank value will be inserted.Note: The values are sorted in the
order you enter them.
SQL Datatype
Data type
TINYINT(size)
MySQL:
Number
Description
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of
digits may be specified in parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum
number of digits may be specified in parenthesis
MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The
maximum number of digits may be specified in parenthesis
INT(size)
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*.
The maximum number of digits may be specified in parenthesis
BIGINT(size)
-9223372036854775808 to 9223372036854775807 normal. 0 to
18446744073709551615 UNSIGNED*. The maximum number of digits
may be specified in parenthesis
FLOAT(size,d)
A small number with a floating decimal point. The maximum number
of digits may be specified in the size parameter. The maximum
number of digits to the right of the decimal point is specified in the d
parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of
digits may be specified in the size parameter. The maximum number
of digits to the right of the decimal point is specified in the d
parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The
maximum number of digits may be specified in the size parameter.
The maximum number of digits to the right of the decimal point is
specified in the
d parameter
Unsigned:
integer
cannot be
SQL Datatype
MySQL:
Date
Data type
Description
DATE()
DATETIME()
TIMESTAMP(
)
TIME()
YEAR()
Homework 5
Create one database containing
several tables using PostgreSQL
SELECT * FROM Persons
10 SQL queries WHERE lastname IN (SELECT
lastname from Persons
querieswhere city=Sandnes)
Embedded
GroupBy queries
Join queries SELECT Customer, SUM(OrderPrice)
FROM CumOrders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000
SQL Quiz
http://www.w3schools.com/sql/sql_qu
iz.asp