+ All Categories
Home > Documents > SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL...

SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL...

Date post: 15-Dec-2015
Category:
Upload: rylan-winget
View: 244 times
Download: 7 times
Share this document with a friend
100
SQL From: http://www.w3schools.com/ sql
Transcript
Page 1: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL

From: http://www.w3schools.com/sql

Page 2: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL

• It is a standard language for accessing and manipulating databases– MySQL, SQL Server, Access, Oracle, Sybase, DB2, and

others• SQL stands for Structured Query Language• SQL is an ANSI (American National Standards

Institute) standard– There are many variations and different systems have

their own extensions– But the major commands are same

Page 3: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL• SQL include

– Data Manipulation Language (DML)– Data Definition Language (DDL)

• The query and update commands for DML– SELECT: extracts data from a database– UPDATE: updates data in a database– DELETE: deletes data from a database– INSERT INTO: insert new data into a database

• DDL: permits database tables to be created or deleted, define indexes (keys), impose constraints between tables. Some important statements:– CREATE DATABASE: creates a new database– ALTER DATABASE: modifies a database– CREATE TABLE: creates a new table– ALTER TABLE: modifies a table– DROP TABLE: deletes a table– CREATE INDEX: creates an index– DROP INDEX: deletes an index

Page 4: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Create Persons Table

P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger

Persons Table

CREATE DATABASE test;CREATE TABLE persons (

P_Id INT,LastName VARCHAR(25),FirstName VARCHAR(25),Address VARCHAR(25),City VARCHAR(15),PRIMARY KEY (P_Id)

);

INSERT INTO persons VALUES (1, 'Hansen', 'Ola', 'Timoteivn10', 'Sandnes'); INSERT INTO persons VALUES (2, 'Svendson', 'Tove', 'Borgvn23','Sandnes'); INSERT INTO persons VALUES (3, 'Pettersen', 'Kari', 'Storgt20', 'Stavanger');

Page 5: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Aqua Data Studio• You can use either “go” or “/” to replace the “;” so that it

can process multiple SQLs at the same time.• More info:

http://www.aquafold.com/support_faq.html#commands

select * from t1 select * from t2 select * from t3

select * from t1 / select * from t2 / select * from t3 /

select * from t1 goselect * from t2 goselect * from t3go

Page 6: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL BASIC

Page 7: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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;

Page 8: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SELECT

P_Id LastName FirstName Address City1 Hansen Ola Timoteivn 10 Sandnes2 Svendson Tove Borgvn 23 Sandnes3 Pettersen Kari Storgt 20 Stavanger

Persons Table

SELECT LastName, FirstName FROM Persons;

SELECT *FROM Persons;

Page 9: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SELECT DISTINCTSELECT DISTINCT column_name(s)FROM table_name;

SELECT DISTINCT city FROM persons;

Page 10: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

WHERE clauseSELECT column_name(s)FROM table_nameWHERE column_name operator value;

SELECT * FROM personsWHERE city=‘Sandnes’;

Page 11: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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 personsWHERE city=‘Sandnes’;

Or SELECT * FROM personsWHERE city=“Sandnes”;

OrSELECT * FROM personsWHERE P_Id=1;

Page 12: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

WHERE Clause

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

INIf you know the exact value you want to return for at least one of the columns

Page 13: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Page 14: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

AND or ORSELECT * FROM personsWHERE firstname=‘Tove’ AND lastname=‘Svendson’;

SELECT * FROM personsWHERE firstname=‘Tove’ OR firstname=‘Ola’;

SELECT * FROM personsWHERE lastname=‘Svendson’ AND (firstname=‘Tove’ OR firstname=‘Ola’);

Page 15: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

ORDER BY• The ORDER BY keyword is used to sort the result-set by a specified column• It sorts the records in ascending order by default• Use DESC for a descending order

SELECT column_name(s)FROM table_nameORDER BY column_name(s) ASC|DESC;

Page 16: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

ORDER BYINSERT INTO persons VALUES (4, ‘Nilsen’, ‘Tom’, ‘Vingvn23', 'Stavanger');

SELECT * FROM PersonsORDER BY lastname;

SELECT * FROM PersonsORDER BY lastname DESC;

Page 17: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

INSERT INTO• Use to insert new records in a table

INSERT INTO table_nameVALUES (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’);

Page 18: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

UPDATE

• Update records in a tableUPDATE table_nameSET column=value, column2=value2,…WHERE some_column=some_value;

UPDATE PersonsSET 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’.

Page 19: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

DELETE statement

• Used to delete records in a tableDELETE FROM table_nameWHERE some_column=some_value;

DELETE FROM personsWHERE lastname=‘Tjessem’ AND firstname=‘Jakob’;

DELETE FROM table_name;OrDELETE * FROM table_name;

Page 20: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

TestCompanyName ContactName Address CityAlfreds Futterkiste Maria Anders Obere Str. 57 Berlin Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå Centro comercial Moctezuma Francisco Chang Sierras de Granada 9993 México D.F. Ernst Handel Roland Mendel Kirchgasse 6 Graz FISSA Fabrica Inter. Salchichas S.A. Diego Roel C/ Moralzarzal, 86 Madrid Galería del gastrónomo Eduardo Saavedra Rambla de Cataluña, 23 Barcelona Island Trading Helen Bennett Garden House Crowther Way Cowes Königlich Essen Philip Cramer Maubelstr. 90 Brandenburg Laughing Bacchus Wine Cellars Yoshi Tannamuri 1900 Oak St. Vancouver Magazzini Alimentari Riuniti Giovanni Rovelli Via Ludovico il Moro 22 Bergamo North/South Simon Crowther South House 300 Queensbridge London Paris spécialités Marie Bertrand 265, boulevard Charonne Paris Rattlesnake Canyon Grocery Paula Wilson 2817 Milton Dr. Albuquerque Simons bistro Jytte Petersen Vinbæltet 34 København The Big Cheese Liz Nixon 89 Jefferson Way Suite 2 Portland Vaffeljernet Palle Ibsen Smagsløget 45 Århus Wolski Zajazd Zbyszek

Piestrzeniewicz ul. Filtrowa 68 Warszawa

Create this Customers table and do the following SQL queries

Page 21: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

TESTCREATE TABLE customers (

CompanyName VARCHAR(100),ContactName VARCHAR(100),Address VARCHAR(100),City VARCHAR(50)

);

INSERT INTO customers VALUES ('Alfreds Futterkiste', 'Maria Anders', 'Obere Str. 57', 'Berlin'); INSERT INTO customers VALUES ('Berglunds snabbköp', 'Christina Berglund', 'Berguvsvägen 8','Luleå'); INSERT INTO customers VALUES ('Centro comercial Moctezuma', 'Francisco Chang', 'Sierras de Granada 9993', 'México D.F.');INSERT INTO customers VALUES ('Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz'); INSERT INTO customers VALUES ('FISSA Fabrica Inter. Salchichas S.A.', 'Diego Roel', 'C/Moralzarzal, 86 ', 'Madrid'); INSERT INTO customers VALUES ('Galería del gastrónomo', 'Eduardo Saavedra', 'Rambla de Cataluña, 23', 'Barcelona'); INSERT INTO customers VALUES ('Island Trading', 'Helen Bennett', 'Garden House Crowther Way', 'Cowes'); INSERT INTO customers VALUES ('Königlich Essen', 'Philip Cramer', 'Maubelstr. 90', 'Brandenburg'); INSERT INTO customers VALUES ('Laughing Bacchus Wine Cellars', 'Yoshi Tannamuri', '1900 Oak St.', 'Vancouver'); INSERT INTO customers VALUES ('Magazzini Alimentari Riuniti', 'Giovanni Rovelli', 'Via Ludovico il Moro 22', 'Bergamo'); INSERT INTO customers VALUES ('North/South', 'Simon Crowther', 'South House 300 Queensbridge', 'London'); INSERT INTO customers VALUES ('Paris spécialités', 'Marie Bertrand', '265, boulevard Charonne', 'Paris'); INSERT INTO customers VALUES ('Rattlesnake Canyon Grocery', 'Paula Wilson', '2817 Milton Dr.', 'Albuquerque'); INSERT INTO customers VALUES ('Simons bistro', 'Jytte Petersen', 'Vinbæltet 34', 'København'); INSERT INTO customers VALUES ('The Big Cheese', 'Liz Nixon', '89 Jefferson Way Suite 2', 'Portland'); INSERT INTO customers VALUES ('Vaffeljernet', 'Palle Ibsen', 'Smagsløget 45', 'Århus'); INSERT INTO customers VALUES ('Wolski Zajazd', 'Zbyszek Piestrzeniewicz', 'ul. Filtrowa 68', 'Warszawa');

Page 22: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

TESTSELEC * FROM customers;

SELECT CompanyName, ContactName FROM customers;

SELECT * FROM customers WHERE companyname LIKE ‘a%’;

SELECT * FROM customers WHERE companyname LIKE ‘A%’;

SELECT companyname, contactnameFROM customersWHERE companyname > ‘A’;

SELECT companyname, contactnameFROM customersWHERE companyname > ‘G’AND contactname > ‘G’;

Page 23: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL ADVANCED

Page 24: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

LIMIT clause

• Used to specify the number of records to return

SELECT column_name(s)FROM table_nameLIMIT number;

SELECT * FROM persons LIMIT 2;

Oracle, SQL Server: Top number|percent (e.g., Top 2, or Top 50 PERCENT

Oracle: ROWNUM<=number (e.g., ROWNUM<=5)

Page 25: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

LIKE operator• Used in a WHERE clause to search for a specified pattern in a column

SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern;

SELECT * FROM persons WHERE city LIKE ‘S%’;

%: define wildcards (missing letters) both before and after the patternSELECT * FROM persons WHERE city LIKE ‘%s’;

Page 26: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Wildcard Description% A substitute for zero or more characters _ A substitute for exactly one character

Page 27: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL WildcardsSELECT * FROM persons WHERE city LIKE ‘Sa%’;

SELECT * FROM persons WHERE city LIKE ‘%nes%’;

SELECT * FROM persons WHERE firstname LIKE ‘_la’;

SELECT * FROM persons WHERE lastname LIKE ‘S_end_on’;

Page 28: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

IN operator

• To specify multiple values in a WHERE clauseSELECT column_name(s)FROM table_nameWHERE column_name IN (value1, value2,…)

SELECT * FROM PersonsWHERE lastname IN (‘Hansen’, ‘Pettersen’)

SELECT * FROM PersonsWHERE lastname IN (SELECT lastname from Persons where city=‘Sandnes’)

Page 29: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

BETWEEN operator• Used in a WHERE clause to select a range of data between two values

SELECT column_name(s)FROM table_nameWHERE column_name BETWEEN value1 AND value 2;

SELECT * FROM personsWHERE lastname BETWEEN ‘Hansen’ AND ‘Pettersen’;

SELECT * FROM personsWHERE lastname NOT BETWEEN ‘Hansen’ AND ‘Pettersen’;

Warning: different database systems have different ways of processing BETWEEN operator

Page 30: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Alias

• An alias name can be given to a table or a columnSELECT column_name(s)FROM table_name AS alias_name;OrSELECT column_name AS alias_nameFROM table_name;

SELECT po.O_ID, p.LastName, p.FirstNameFROM Persons AS p, Orders AS poWHERE p.LastName='Hansen' AND p.FirstName='Ola';

Without alias

SELECT Orders.OrderID, Persons.LastName, Persons.FirstNameFROM Persons, OrdersWHERE Persons.LastName=‘Hansen’ AND Persons.FirstName=‘Ola’;

Page 31: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Page 32: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

JOINO_Id OrderNo P_Id1 77895 32 44678 33 22456 14 24562 15 34764 15

CREATE DATABASE test;CREATE TABLE orders (

O_Id INT,OrderNO INT,P_Id INT,PRIMARY KEY (O_Id)

);

INSERT INTO orders VALUES (1, 77895, 3); INSERT INTO orders VALUES (2, 44678, 3); INSERT INTO orders VALUES (3, 22456, 1);INSERT INTO orders VALUES (4, 24562, 1);INSERT INTO orders VALUES (5, 34764, 15);

Same as INNER JOIN

Page 33: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

INNER JOINSELECT column_name(s)FROM table_name1 INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name;

SELECT persons.lastname, persons.firstname, orders.orderNoFrom Persons INNER JOIN OrdersON persons.P_Id=orders.P_IdORDER 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.

Page 34: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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_name2ON table_name1.column_name=table_name2.column_name;

In some databases, LEFT JOIN is called LEFT OUTER JOINSELECT persons.lastname, persons.firstname, orders.orderno

FROM persons LEFT JOIN ordersON persons.P_Id=orders.P_IdORDER BY persons.lastname;

Page 35: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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_name2ON table_name1.column_name=table_name2.column_name;

In some databases, RIGHT JOIN is called RIGHT OUTER JOINSELECT persons.lastname, persons.firstname, orders.orderno

FROM persons RIGHT JOIN ordersON persons.P_Id=orders.P_IdORDER BY persons.lastname;

Page 36: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

FULL JOIN• Return rows when there is a match in one of the tables

SELECT column_name(s)FROM table_name1 FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name;

SELECT persons.lastname, persons.firstname, orders.ordernoFROM persons FULL JOIN ordersON persons.P_Id=orders.P_IdORDER BY persons.lastname;

SELECT persons.lastname, persons.firstname, orders.ordernoFROM persons LEFT JOIN ordersON persons.P_Id=orders.P_IdUNIONSELECT persons.lastname, persons.firstname, orders.ordernoFROM persons RIGHT JOIN ordersON persons.P_Id=orders.P_Id

FULL JOIN is not supported by MySQL.

FULL JOIN = LEFT JOIN UNION RIGHT JOIN

Page 37: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

UNION operator• Combines two or more SELECT statements• Each SELECT statement must have the same columns (same name, same

data types, in the same order)• UNION selects only distinct values by default. To allow duplicate values,

use UNION ALL.

SELECT column_name(s) FROM table_name1 UNIONSELECT column_name(s) FROM table_name2;

SELECT column_name(s) FROM table_name1 UNION ALLSELECT column_name(s) FROM table_name2;

SELECT P_Id FROM personsUNIONSELECT P_Id FROM orders;

Page 38: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CREATE DATABASE• Used to create a database

CREATE DATABASE database_name;

CREATE DATABASE my_db;

Page 39: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CREATE TABLE• Used to create a table within a database

CREATE TABLE table_name(column_name1 data_type,column_name2 data_type,column_name3 data_type,….);

CREATE TABLE persons (P_Id INT,LastName VARCHAR(25),FirstName VARCHAR(25),Address VARCHAR(25),City VARCHAR(15),PRIMARY KEY (P_Id)

);

Page 40: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Page 41: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

NOT NULL

• Enforce a column to not accept NULL valuesCREATE TABLE Persons(P_Id INT NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255));

Page 42: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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.

Page 43: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

UNIQUECREATE TABLE Persons(P_Id INT NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255)UNIQUE (P_Id));

CREATE TABLE Persons(P_Id INT NOT NULL UNIQUE,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255));

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

MySQL/SQL Server/Oracle/MS Access

Page 44: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

UNIQUE

ALTER TABLE PersonsADD UNIQUE (P_Id)

ALTER TABLE PersonsADD CONSTRAINT un_PersonID UNIQUE (P_Id, LastName)

When Persons table has already been created, use Alter to add new constraints.

To drop a UNIQUE constraint

ALTER TABLE PersonsDROP INDEX un_PersonID

ALTER TABLE PersonsDROP CONSTRAINT un_PersonID

MySQL

SQL Server/Oracle/MS Access

Page 45: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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(P_Id INT NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255)PRIMARY KEY (P_Id)); MySQL

CREATE TABLE Persons(P_Id INT NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255)); 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 pk_PersonID PRIMARY KEY (P_Id, LastName) );

MySQL/SQL Server/Oracle/MS Access

Page 46: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

PRIMARY KEY

ALTER TABLE PersonsADD PRIMARY KEY (P_Id)

ALTER TABLE PersonsADD CONSTRAINT un_PersonID PRIMARY KEY (P_Id, LastName)

When Persons table has already been created, use Alter to add new constraints.

To drop a constraint

ALTER TABLE PersonsDROP PRIMARY KEY

ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID

MySQL

SQL Server/Oracle/MS Access

Page 47: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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.CREATE TABLE Orders(O_Id INT NOT NULL,OrderNo INT NOT NULL,P_Id INT,PRIMARY KEY (O_Id),FOREIGN KEY (P_Id) REFERENCES Persons (P_Id)); MySQL

CREATE TABLE Orders(O_Id INT NOT NULL PRIMARY KEY,OrderNo INT NOT NULL,P_Id INT FOREIGN KEY REFERENCES Persons(P_Id)); 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));

MySQL/SQL Server/Oracle/MS Access

Page 48: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

FOREIGN KEY

ALTER TABLE OrdersADD FOREIGN KEY (P_Id)REFERENCES Persons (P_Id)

ALTER TABLE OrdersADD CONSTRAINT fk_PerOrdersFOREIGN KEY (P_Id)REFERENCES Persons(P_Id)

When Orders table has already been created, use Alter to add new constraints.

To drop a constraint

ALTER TABLE OrdersDROP FOREIGN KEY fk_PerOrders

ALTER TABLE OrdersDROP CONSTRAINT fk_PerOrders

MySQL

SQL Server/Oracle/MS Access

Page 49: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CHECK Constraint• Used to limit the value range of a column

CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CHECK (P_Id>0)) MySQL

CREATE TABLE Persons(P_Id int NOT NULL CHECK (P_Id>0),LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255)) 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 chk_Person CHECK (P_Id>0 AND City='Sandnes‘));

MySQL/SQL Server/Oracle/MS Access

Page 50: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CHECK Constraint

ALTER TABLE PersonsADD CHECK (P_Id>0)

ALTER TABLE PersonsADD CONSTRAINT chk_PersonCHECK (P_Id>0 AND City=‘Sandnes’)

When a table has already been created, use Alter to add new constraints.

To drop a constraint

ALTER TABLE PersonsDROP CONSTRAINT chk_Person

SQL Server/Oracle/MS Access

Page 51: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

DEFAULT Constraint• Used to insert a default value into a column

CREATE TABLE Persons(P_Id int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255) DEFAULT 'Sandnes')

CREATE TABLE Orders(O_Id int NOT NULL,OrderNo int NOT NULL,P_Id int,OrderDate date DEFAULT GETDATE())MySQL/SQL Server/Oracle/MS Access

MySQL/SQL Server/Oracle/MS Access

Page 52: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

DEFAULT Constrain

ALTER TABLE PersonsALTER City SET DEFAULT ‘Sandnes’

ALTER TABLE PersonsALTER COLUMN City SET DEFAULT ‘Sandnes’

When a table has already been created, use Alter to add new constraints.

To drop a constraint

ALTER TABLE PersonsALTER City DROP DEFAULT

ALTER TABLE PersonsALTER COLUMN City DROP DEFAULT

MySQL

SQL Server/Oracle/MS Access

MySQLSQL Server/Oracle/MS Access

Page 53: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CREATE INDEX statement

• An index can be created in a table to find data more quickly and efficiently.

• The users cannot see the indexes.• Indexes can speed up searches/queries• Updating a table with indexes takes more time

than updating a table without indexes. Because indexes also need to update.

• So please create indexes on columns (and tables) that will be frequently searched.

Page 54: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

CREATE INDEX statementCREATE INDEX index_nameON table_name (column_name) Duplicate values are allowed

CREATE UNIQUE INDEX index_nameON table_name (column_name)

Duplicate values are not allowed

CREATE INDEX PIndexON Persons (lastname)

CREATE INDEX PIndexON Persons (LastName, FirstName)

Page 55: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DROP INDEX, DROP TABLE, DROP DATABASE

DROP INDEX index_name ON table_name MS Access

DROP INDEX table_name.index_name MS SQL Server

DROP INDEX index_name

DROP DATABASE database_name

DB2/Oracle

ALTER TABLE table_name DROP INDEX index_name MySQL

DROP TABLE table_name

TRUNCATE TABLE table_name Delete data inside the table, not the table itself

Page 56: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL ALTER TABLE statement• Alter table statement is used to add, delete, or modify columns in an

existing table

ALTER TABLE table_nameADD column_name datatype To add a column in a table

ALTER TABLE table_nameDROP COLUMN column_name

To delete a column in a table (some database systems don’t allow deleting a column)

ALTER TABLE table_nameALTER COLUMN column_name datatype

To change the data type of a column in a table

Page 57: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL ALTER TABLE statementALTER TABLE PersonsADD DateOfBirth date

ALTER TABLE PersonsDROP COLUMN DateOfBirth

Page 58: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL AUTO INCREMENT

• Auto-increment allows a unique number to be generated when a new record is inserted into a table

CREATE TABLE Persons(P_Id int NOT NULL AUTO_INCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),PRIMARY KEY (P_Id))

ALTER TABLE Persons AUTO_INCREMENT=100

To start the auto_increment with another value

INSERT INTO Persons (FirstName, LastName) VALUES (‘Lars’, ‘Monsen’)

MySQL

Page 59: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL AUTO INCREMENT

• Auto-increment allows a unique number to be generated when a new record is inserted into a table

CREATE TABLE Persons(P_Id int PRIMARY KEY IDENTITY,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))

ALTER TABLE Persons AUTO_INCREMENT=100

To start the auto_increment with another value

INSERT INTO Persons (FirstName, LastName) VALUES (‘Lars’, ‘Monsen’)

SQL Server

To start at 10 and increment by 5 IDENTITY(10,5)

Page 60: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL AUTO INCREMENT

• Auto-increment allows a unique number to be generated when a new record is inserted into a table

CREATE TABLE Persons(P_Id PRIMARY KEY AUTOINCREMENT,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))

INSERT INTO Persons (FirstName, LastName) VALUES (‘Lars’, ‘Monsen’)

Access

To start at 10 and increment by 5 AUTOINCREMENT(10,5)

Page 61: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL AUTO INCREMENT

• Auto-increment allows a unique number to be generated when a new record is inserted into a table

CREATE SEQUENCE seq_personMINVALUE 1START WITH 1INCREMENT BY 1CACHE 10

INSERT INTO Persons (P_Id,FirstName,LastName)VALUES (seq_person.nextval,'Lars','Monsen')

Oracle

To start at 10 and increment by 5 AUTOINCREMENT(10,5)

Page 62: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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 databaseCREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

CREATE VIEW Sandnes ASSELECT LastName, FirstNameFROM PersonsWHERE city=‘Sandnes’

SELECT * FROM Sandnes

CREATE VIEW SandnesLastName ASSELECT LastNameFROM Sandnes

SELECT * FROM SandnesLastName

Page 63: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL Views• A view can be updated or dropped

CREATE OR REPLACE OR ALTER VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition

ALTER VIEW Sandnes ASSELECT LastName, FirstName, AddressFROM PersonsWHERE city=‘Sandnes’

SELECT * FROM Sandnes

DROP VIEW view_name

DROP VIEW Sandnes

Page 64: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL FUNCTIONS

Page 65: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Page 66: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

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

Page 67: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Create Products TablePersons Table

CREATE TABLE products (P_Id INT,ProductName VARCHAR(25),UnitPrice decimal,UnitsInStock INT,UnitsOnOrder INT,PRIMARY KEY (P_Id)

);

INSERT INTO products VALUES (1, ‘Jarlsberg', 10.45, 16, 15); INSERT INTO products VALUES (2, ‘Mascarpone', 32.56, 23,NULL); INSERT INTO products VALUES (3, ‘Gorgonzola', 15.67, 9, 20);

P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder

1 Jarlsberg 10.45 16 15

2 Mascarpone 32.56 23

3 Gorgonzola 15.67 9 20

Page 68: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL AVG() Function

• AVG() returns the average value of a numeric columnSELECT AVG(column_name) FROM table_name

SELECT AVG(UnitPrice) AS UnitAverage FROM Products

SELECT ProductName FROM productsWHERE UnitPrice>( SELECT AVG(UnitPrice) FROM Products)

Page 69: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL COUNT() Function• COUNT() returns the number of rows that matches a specified criteria

SELECT COUNT(column_name) FROM table_name

SELECT COUNT(*) FROM Products

SELECT COUNT(DISTINCT column_name) FROM table_name

SELECT COUNT(DISTINCT city) As CityName From persons

Page 70: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL MAX() Function

• MAX() returns the largest value of the selected columnSELECT MAX(column_name) FROM table_name

SELECT MAX(UnitPrice) AS LargestUnitPrice FROM Products

Page 71: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL SUM() Function

• SUM() returns the total sum of the selected columnSELECT SUM(column_name) FROM table_name

SELECT SUM(UnitPrice) AS TotalUnitPrice FROM Products

Page 72: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Create CumOrders Table

CREATE TABLE CumOrders (O_Id INT,OrderDate Date,OrderPrice INT,Customer Varchar(30),PRIMARY KEY (O_Id) );

INSERT INTO cumorders VALUES (1, ‘2011-08-06’, 1000, ‘Hansen’); INSERT INTO cumorders VALUES (2, ‘2011-08-07’, 1600, ‘Nilsen’); INSERT INTO cumorders VALUES (3, ‘2011-08-08’, 700, ‘Hansen’);INSERT INTO cumorders VALUES (4, ‘2011-08-09’, 300, ‘Hansen’);INSERT INTO cumorders VALUES (5, ‘2011-08-10’, 2000, ‘Jensen’);INSERT INTO cumorders VALUES (6, ‘2011-08-11’, 100, ‘Nilsen’);

O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen

Page 73: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL GROUP BY Statement

• Aggregate functions often need an added GROUP BY statement to group the result-set by one or more columns

SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_name

SELECT Customer, SUM(OrderPrice) FROM CumOrdersGROUP BY Customer

SELECT Customer, OrderDate, SUM(OrderPrice) FROM CumOrdersGROUP BY Customer, OrderDate

Page 74: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL HAVING Clause

• HAVING was added to SQL because the WHERE keyword could not be used wit the aggregate functions

SELECT column_name, aggregate_function(column_name)FROM table_nameWHERE column_name operator valueGROUP BY column_nameHAVING aggregate_function(column_name) operator value

SELECT Customer, SUM(OrderPrice) FROM CumOrdersGROUP BY CustomerHAVING SUM(OrderPrice)<2000

Page 75: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL HAVING Clause

SELECT Customer, SUM(OrderPrice) FROM CumOrdersWHERE Customer=‘Hansen’ OR Customer=‘Jensen’GROUP BY CustomerHAVING SUM(OrderPrice)>1500

Page 76: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL UCASE() Function

• UCASE() converts the value of a field to uppercase.SELECT UCASE(column_name) FROM table_name

SELECT UCASE(LastName) as LastName From Persons

Page 77: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL LCASE() Function

• LCASE() converts the value of a field to lowercase.SELECT LCASE(column_name) FROM table_name

SELECT LCASE(LastName) as LastName From Persons

Page 78: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL MID() Function

• MID() extracts characters from a text field

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

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

Parameter Description

column_name Required. The field to extract characters from

start Required. Specifies the starting position (starts at 1)

length Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text

SELECT substr(City, 1, 4) as SmallCity From PersonsPostgreSQL

MySQL

PostgreSQL: http://www.postgresql.org/docs/9.1/static/functions-string.html

Page 79: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL LENGTH() Function

• LENGTH() returns the length of the value in a text field.

SELECT LENGTH(column_name) FROM table_name

SELECT LENGTH(Address) as LengthOfAddress From Persons

Page 80: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL ROUND() Function• ROUND() rounds a numeric field to the number of decimals specified

SELECT ROUND(column_name, decimals) FROM table_name

SELECT ROUND(UnitPrice, 0) as Price From Products

Parameter Description

column_name Required. The field to round.

decimals Required. Specifies the number of decimals to be returned.

UPDATE ProductsSET UnitPrice=10.49WHERE P_Id=1

Page 81: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL Date Functions

• Introduces some build-in functions to deal with datesFunction Description

NOW() Returns the current date and time

CURDATE() Returns the current date

CURTIME() Returns the current time

DATE() Extracts the date part of a date or date/time expression

EXTRACT() Returns a single part of a date/time

DATE_ADD() Adds a specified time interval to a date

DATE_SUB() Subtracts a specified time interval from a date

DATEDIFF() Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats

MySQL Date Functions

PostgreSQL: http://www.postgresql.org/docs/8.2/static/functions-datetime.html

Page 82: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL NOW() Function• NOW() returns the current date and time

SELECT NOW(), CURDATE(), CURTIME()

CREATE TABLE Orders(OrderId int NOT NULL,ProductName varchar(50) NOT NULL,OrderDate datetime NOT NULL,PRIMARY KEY (OrderId))

INSERT INTO orders VALUES (1, ‘Jarlsberg Cheese’, NOW())

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

SELECT NOW()PostgreSQLMySQL

Page 83: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL CURDATE() Function• CURDATE() returns the current date

SELECT NOW(), CURDATE(), CURTIME()

CREATE TABLE Orders(OrderId int NOT NULL,ProductName varchar(50) NOT NULL,OrderDate datetime NOT NULL,PRIMARY KEY (OrderId))

INSERT INTO orders VALUES (2, ‘Jarlsberg Cheese’, CURDATE())

Page 84: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL DATE() Function• DATE() function extracts the date part of a date or date/time expression

DATE(date)

SELECT ProductName, DATE(OrderDate) as OrderDateFROM OrdersWHERE OrderId=1

Page 85: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL EXTRACT() Function• The EXTRACT() function returns a single part of a date/time, such as year, month,

day, hour, minute, etc.• Unit value can be: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER,

YEAR, or any combination of them

EXTRACT(unit FROM date)

SELECT EXTRACT(YEAR FROM OrderDate) as OrderYear,EXTRACT(Month FROM OrderDate) as OrderMonth,EXTRACT(DAY FROM OrderDate) as OrderDayFROM OrdersWHERE OrderID=1

Page 86: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL DATE_ADD() Function• The DATE_ADD() function adds a specified time interval to a date.

DATE_ADD(date, INTERVAL expr type)

SELECT OrderID, DATE_ADD(OrderDate, INTERVAL 45 DAY) AS OrderPayDate FROM Orders

Page 87: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL DATE_SUB() Function• The DATE_SUB() function subtracts a specified time interval from a date.

DATE_SUB(date, INTERVAL expr type)

SELECT OrderID, DATE_SUB(OrderDate, INTERVAL 5 DAY) AS SubtractDate FROM Orders

Page 88: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL DATEIFF() Function• The DATEDIFF() function returns the time between two dates.

DATEDIFF(date1, date2)

SELECT DATEDIFF ( ‘2010-11-30’, ‘2010-11-29’) AS DiffDate

Page 89: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

MySQL DATE_FORMAT() Function• The DATE_FORMAT() function displays the date/time in different formats.

DATE_FORMAT(date, format)

SELECT DATE_FORMAT(NOW(), ‘%m-%d-%y’)

Page 90: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL Date Functions

• Introduces some build-in functions to deal with datesSQL Server Date Functions

Function Description

GETDATE() Returns the current date and time

DATEPART() Returns a single part of a date/time

DATEADD() Adds or subtracts a specified time interval from a date

DATEDIFF() Returns the time between two dates

CONVERT() Displays date/time data in different formats

Page 91: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL Date Datatypes

• MySQL – Date: YYYY-MM-DD– Datetime: YYYY-MM-DD HH:MM:SS– Timestamp: YYYY-MM-DD HH:MM:SS– Year: YYYY or YY

SELECT * FROM Orders WHERE OrderDate=‘2011-08-06’

Page 92: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL NULL Values• NULL values represent missing unknown data.• NULL is used as a placeholder for unknown or inapplicable

values• NULL vs. 0INSERT INTO persons VALUES (5, 'Ding', 'Ying', NULL, NULL);

DELETE FROM Persons WHERE P_ID=5

SELECT * FROM PersonsWHERE Address IS NULL

SELECT * FROM PersonsWHERE Address IS NOT NULL

Page 93: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL NULL FunctionsSELECT ProdcutName, UnitPrice*(UnitsInStock+UnitsOnOrder)FROM Products

ISNULL(), NVL(), IFNULL(), COALESCE() are used to treat NULL values. Below all makes nulls to be zero

SELECT ProductName, UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))FROM Products SQL Server/Access

SELECT ProductName, UnitPrice*(UnitsInStock+NVL(UnitsOnOrder,0))FROM Products Oracle

SELECT ProductName, UnitPrice*(UnitsInStock+IFNULL(UnitsOnOrder,0)) AS PriceFROM Products

SELECT ProductName, UnitPrice*(UnitsInStock+COALESCE(UnitsOnOrder,0))AS PriceFROM Products

MySQL

Page 94: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DATATYPES

Page 95: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DatatypeData type Description StorageText Use for text or combinations of text and numbers. 255 characters maximum Memo 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

Byte Allows whole numbers from 0 to 255 1 byteInteger Allows whole numbers between -32,768 and 32,767 2 bytesLong Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytesSingle Single precision floating-point. Will handle most decimals 4 bytesDouble Double precision floating-point. Will handle most decimals 8 bytesCurrency Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal

places. Tip: You can choose which country's currency to use8 bytes

AutoNumber AutoNumber fields automatically give each record its own number, usually starting at 1

4 bytes

Date/Time Use for dates and times 8 bytesYes/No A logical field can be displayed as Yes/No, True/False, or 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

1 bit

OLE Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) up to 1GBHyperlink Contain links to other files, including web pages Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down

list4 bytes

Access

Page 96: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DatatypeData type DescriptionCHAR(size) 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.You enter the possible values in this format: ENUM('X','Y','Z')

SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

MySQL: Text

Page 97: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DatatypeData type DescriptionTINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be

specified in parenthesisSMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may

be specified in parenthesisMEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of

digits may be specified in parenthesisINT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum

number of digits may be specified in parenthesisBIGINT(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

MySQL: Number

Unsigned: integer cannot be negative

Page 98: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL DatatypeData type DescriptionDATE() A date. Format: YYYY-MM-DDNote: The supported range is from

'1000-01-01' to '9999-12-31'DATETIME() *A date and time combination. Format: YYYY-MM-DD

HH:MM:SSNote: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SSNote: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC

TIME() A time. Format: HH:MM:SSNote: The supported range is from '-838:59:59' to '838:59:59'

YEAR() A year in two-digit or four-digit format.Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

MySQL: Date

Page 99: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

Homework 5

• Create one database containing several tables using PostgreSQL

• 10 SQL queries– Embedded queries– GroupBy queries– Join queries SELECT Customer, SUM(OrderPrice)

FROM CumOrdersGROUP BY CustomerHAVING SUM(OrderPrice)<2000

SELECT persons.lastname, persons.firstname, orders.orderNoFrom Persons INNER JOIN OrdersON persons.P_Id=orders.P_IdORDER BY persons.Lastname;

SELECT * FROM PersonsWHERE lastname IN (SELECT lastname from Persons where city=‘Sandnes’)

Page 100: SQL From: . SQL It is a standard language for accessing and manipulating databases – MySQL, SQL Server, Access, Oracle, Sybase,

SQL Quiz

• http://www.w3schools.com/sql/sql_quiz.asp


Recommended