Vous êtes sur la page 1sur 75

SQL Tutorial

SQL is a standard language for accessing databases. Our SQL tutorial will teach you how to use SQL to access and manipulate data in: MySQL, SQL Server, Access, Oracle, Sybase, systems.
SQL Synta#
SELECT Company, Country FROM Customers WHERE Country <> 'USA'

!", and other database

SQL $esult
Company %sland &rading )aler*a del gastr+nomo Laughing !acchus ,ine -ellars .aris sp/cialit/s Simons bistro ,ols1i 2a3a4d Country '( Spain -anada 0rance enmar1 .oland

Introduction to SQL

SQL is a standard language for accessing and manipulating databases.

,hat is SQL5

SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an A6S% 7American 6ational Standards %nstitute8 standard

,hat -an SQL do5



SQL can e#ecute 9ueries 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 SQL can create stored procedures in a database

SQL can create views in a database SQL can set permissions on tables, procedures, and views

SQL is a Standard : !'&....


Although SQL is an A6S% 7American 6ational Standards %nstitute8 standard, there are many different versions of the SQL language. ;owever, to be compliant with the A6S% standard, they all support at least the ma3or commands 7such as S<L<-&, '. A&<, <L<&<, %6S<$&, ,;<$<8 in a similar manner. Note: Most of the SQL database programs also have their own proprietary e#tensions in addition to the SQL standard=

'sing SQL in >our ,eb Site


&o build a web site that shows some data from a database, you will need the following:

An $ !MS database program 7i.e. MS Access, SQL Server, MySQL8 A server:side scripting language, li1e .;. or AS. SQL ;&ML ? -SS

$ !MS
$ !MS stands for $elational atabase Management System. !", Oracle, MySQL, and Microsoft

$ !MS is the basis for SQL, and for all modern database systems li1e MS SQL Server, %!M Access. &he data in $ !MS is stored in database ob3ects called tables. A table is a collections of related data entries and it consists of columns and rows.

SQL Syntax

atabase &ables
A database most often contains one or more tables. <ach table is identified by a name 7e.g. @-ustomers@ or @Orders@8. &ables contain records 7rows8 with data. !elow is an e#ample of a table called @.ersons@: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

.ettersen

(ari

Storgt "B

Stavanger

&he table above contains three records 7one for each person8 and five columns 7.D%d, Last6ame, 0irst6ame, Address, and -ity8.

SQL Statements
Most of the actions you need to perform on a database are done with SQL statements. &he following SQL statement will select all the records in the @.ersons@ table:

SELECT * FROM Persons


%n this tutorial we will teach you all about the different SQL statements.

(eep in Mind &hat...

SQL is not case sensitive

Semicolon after SQL Statements5


Some database systems re9uire a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be e#ecuted in the same call to the server. ,e are using MS Access and SQL Server "BBB and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.

SQL

ML and

L
ata Manipulation Language 7 ML8 and the ML part of SQL: ata efinition Language 7 L8.

SQL can be divided into two parts: &he

&he 9uery and update commands form the

SELECT : e#tracts data from a database UPDATE : updates data in a database DELETE : deletes data from a database INSERT INTO : inserts new data into a database

&he L part of SQL permits database tables to be created or deleted. %t also define inde#es 71eys8, specify lin1s between tables, and impose constraints between tables. &he most important L statements in SQL are:

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 INDE DROP INDE : creates an inde# 7search 1ey8

: deletes an inde#

SQL SELECT Statement

&his chapter will e#plain the S<L<-& and the S<L<-& E statements.

&he SQL S<L<-& Statement


&he S<L<-& statement is used to select data from a database. &he result is stored in a result table, called the result:set.

SQL S<L<-& Synta#


SELECT o!umn"name#s$ FROM ta%!e"name
and

SELECT * FROM ta%!e"name

Note: SQL is not case sensitive. S<L<-& is the same as select.

An SQL S<L<-& <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the content of the columns named @Last6ame@ and @0irst6ame@ from the table above. ,e use the following S<L<-& statement:

SELECT Last&ame,F'rst&ame FROM Persons


&he result:set will loo1 li1e this: LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari

S<L<-& E <#ample
6ow we want to select all the columns from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons


Tip: &he asteris1 7E8 is a 9uic1 way of selecting all columns= &he result:set will loo1 li1e this: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6avigation in a $esult:set
Most database software systems allow navigation in the result:set with programming functions, li1e: Move:&o:0irst:$ecord, )et: $ecord:-ontent, Move:&o:6e#t:$ecord, etc. .rogramming functions li1e these are not a part of this tutorial. &o learn about accessing data with function calls, please visit our A O tutorial or our .;. tutorial.

F .revious

6e#t -hapter G

SQL SELECT Statement


F .revious
&his chapter will e#plain the S<L<-& and the S<L<-& E statements.

6e#t -hapter G

&he SQL S<L<-& Statement


&he S<L<-& statement is used to select data from a database. &he result is stored in a result table, called the result:set.

SQL S<L<-& Synta#


SELECT o!umn"name#s$ FROM ta%!e"name
and

SELECT * FROM ta%!e"name

Note: SQL is not case sensitive. S<L<-& is the same as select.

An SQL S<L<-& <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the content of the columns named @Last6ame@ and @0irst6ame@ from the table above. ,e use the following S<L<-& statement:

SELECT Last&ame,F'rst&ame FROM Persons


&he result:set will loo1 li1e this: LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari

S<L<-& E <#ample
6ow we want to select all the columns from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons


Tip: &he asteris1 7E8 is a 9uic1 way of selecting all columns= &he result:set will loo1 li1e this: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6avigation in a $esult:set
Most database software systems allow navigation in the result:set with programming functions, li1e: Move:&o:0irst:$ecord, )et: $ecord:-ontent, Move:&o:6e#t:$ecord, etc. .rogramming functions li1e these are not a part of this tutorial. &o learn about accessing data with function calls, please visit our A O tutorial or our .;. tutorial.

F .revious

6e#t -hapter G

SQL SELECT DISTINCT Statement


F .revious
&his chapter will e#plain the S<L<-& %S&%6-& statement.

6e#t -hapter G

&he SQL S<L<-&

%S&%6-& Statement

%n a table, some of the columns may contain duplicate values. &his is not a problem, however, sometimes you will want to list only the different 7distinct8 values in a table. &he %S&%6-& 1eyword can be used to return only distinct 7different8 values.

SQL S<L<-&

%S&%6-& Synta#
o!umn"name#s$

SELECT ()ST)&CT FROM ta%!e"name

S<L<-&

%S&%6-& <#ample

&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select only the distinct values from the column named @-ity@ from the table above. ,e use the following S<L<-& statement:

SELECT ()ST)&CT C'ty FROM Persons


&he result:set will loo1 li1e this:

City Sandnes Stavanger

F .revious

6e#t -hapter G

SQL !"ERE -lause


F .revious
&he ,;<$< clause is used to filter records.

6e#t -hapter G

&he ,;<$< -lause


&he ,;<$< clause is used to e#tract only those records that fulfill a specified criterion.

SQL ,;<$< Synta#


SELECT o!umn"name#s$ FROM ta%!e"name WHERE o!umn"name operator *a!ue

,;<$< -lause <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select only the persons living in the city @Sandnes@ from the table above. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty+'San,nes'


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

Quotes Around &e#t 0ields


SQL uses single 9uotes around te#t values 7most database systems will also accept double 9uotes8. Although, numeric values should not be enclosed in 9uotes. 0or te#t values:

T-'s 's

orre t.

SELECT * FROM Persons WHERE F'rst&ame+'To*e' T-'s 's /ron0. SELECT * FROM Persons WHERE F'rst&ame+To*e
0or numeric values:

T-'s 's

orre t.

SELECT * FROM Persons WHERE 1ear+2345 T-'s 's /ron0. SELECT * FROM Persons WHERE 1ear+'2345'

Operators Allowed in the ,;<$< -lause


,ith the ,;<$< clause, the following operators can be used: Operator H IJ J I JH IH !<&,<<6 L%(< %6 Des#ription <9ual 6ot e9ual )reater than Less than )reater than or e9ual Less than or e9ual !etween an inclusive range Search for a pattern %f you 1now the e#act value you want to return for at least one of the columns

Note: %n some versions of SQL the IJ operator may be written as =H

F .revious

6e#t -hapter G

SQL AND $ OR Operators


F .revious
&he A6 K O$ operators are used to filter records based on more than one condition.

6e#t -hapter G

&he A6
&he A6

K O$ Operators

operator displays a record if both the first condition and the second condition is true.

&he O$ operator displays a record if either the first condition or the second condition is true.

A6

Operator <#ample

&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select only the persons with the first name e9ual to @&ove@ A6

the last name e9ual to @Svendson@:

,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE F'rst&ame+'To*e' A&( Last&ame+'S*en,son'


&he result:set will loo1 li1e this: P_Id " LastName Svendson FirstName &ove Address !orgvn "C City Sandnes

O$ Operator <#ample
6ow we want to select only the persons with the first name e9ual to @&ove@ O$ the first name e9ual to @Ola@: ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE F'rst&ame+'To*e' OR F'rst&ame+'O!a'


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

-ombining A6
>ou can also combine A6

K O$
and O$ 7use parenthesis to form comple# e#pressions8. the first name e9ual to @&ove@ O$ to @Ola@:

6ow we want to select only the persons with the last name e9ual to @Svendson@ A6 ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame+'S*en,son' A&( #F'rst&ame+'To*e' OR F'rst&ame+'O!a'$


&he result:set will loo1 li1e this: P_Id " LastName Svendson FirstName &ove Address !orgvn "C City Sandnes

F .revious

6e#t -hapter G

SQL ORDER B% (eyword


F .revious 6e#t -hapter G

&he O$ <$ !> 1eyword is used to sort the result:set.

&he O$ <$ !> (eyword


&he O$ <$ !> 1eyword is used to sort the result:set by a specified column. &he O$ <$ !> 1eyword sort the records in ascending order by default. %f you want to sort the records in a descending order, you can use the <S- 1eyword.

SQL O$ <$ !> Synta#


SELECT o!umn"name#s$ FROM ta%!e"name OR(ER 61 o!umn"name#s$ ASC7(ESC

O$ <$ !> <#ample


&he @.ersons@ table: P_Id A " C L LastName ;ansen Svendson .ettersen 6ilsen FirstName Ola &ove (ari &om Address &imoteivn AB !orgvn "C Storgt "B Mingvn "C City Sandnes Sandnes Stavanger Stavanger

6ow we want to select all the persons from the table above, however, we want to sort the persons by their last name. ,e use the following S<L<-& statement:

SELECT * FROM Persons OR(ER 61 Last&ame


&he result:set will loo1 li1e this: P_Id A L C " LastName ;ansen 6ilsen .ettersen Svendson FirstName Ola &om (ari &ove Address &imoteivn AB Mingvn "C Storgt "B !orgvn "C City Sandnes Stavanger Stavanger Sandnes

O$ <$ !>

<S- <#ample

6ow we want to select all the persons from the table above, however, we want to sort the persons descending by their last name. ,e use the following S<L<-& statement:

SELECT * FROM Persons OR(ER 61 Last&ame (ESC


&he result:set will loo1 li1e this: P_Id " C L A LastName Svendson .ettersen 6ilsen ;ansen FirstName &ove (ari &om Ola Address !orgvn "C Storgt "B Mingvn "C &imoteivn AB City Sandnes Stavanger Stavanger Sandnes

F .revious

6e#t -hapter G

SQL INSERT INTO Statement


F .revious
&he %6S<$& %6&O statement is used to insert new records in a table.

6e#t -hapter G

&he %6S<$& %6&O Statement


&he %6S<$& %6&O statement is used to insert a new row in a table.

SQL %6S<$& %6&O Synta#


%t is possible to write the %6S<$& %6&O statement in two forms. &he first form doesnNt specify the column names where the data will be inserted, only their values:

)&SERT )&TO ta%!e"name 8ALUES #*a!ue2, *a!ue9, *a!ue:,;;;$


&he second form specifies both the column names and the values to be inserted:

)&SERT )&TO ta%!e"name # o!umn2, o!umn9, 8ALUES #*a!ue2, *a!ue9, *a!ue:,;;;$

o!umn:,;;;$

SQL %6S<$& %6&O <#ample


,e have the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to insert a new row in the @.ersons@ table. ,e use the following SQL statement:

)&SERT )&TO Persons 8ALUES #<,'&'!sen', '=o-an', '6a>>en 9', 'Sta*an0er'$


&he @.ersons@ table will now loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

C L

.ettersen 6ilsen

(ari Oohan

Storgt "B !a11en "

Stavanger Stavanger

%nsert

ata Only in Specified -olumns

%t is also possible to only add data in specific columns. &he following SQL statement will add a new row, but only add data in the @.D%d@, @Last6ame@ and the @0irst6ame@ columns:

)&SERT )&TO Persons #P"),, Last&ame, F'rst&ame$ 8ALUES #5, 'T?essem', '=a>o%'$
&he @.ersons@ table will now loo1 li1e this: P_Id A " C L P LastName ;ansen Svendson .ettersen 6ilsen &3essem FirstName Ola &ove (ari Oohan Oa1ob Address &imoteivn AB !orgvn "C Storgt "B !a11en " City Sandnes Sandnes Stavanger Stavanger

F .revious

6e#t -hapter G

SQL UPDATE Statement


F .revious
&he '. A&< statement is used to update records in a table.

6e#t -hapter G

&he '. A&< Statement


&he '. A&< statement is used to update e#isting records in a table.

SQL '. A&< Synta#


UP(ATE ta%!e"name SET o!umn2+*a!ue, o!umn9+*a!ue9,;;; WHERE some" o!umn+some"*a!ue
Note: 6otice the ,;<$< clause in the '. A&< synta#. &he ,;<$< clause specifies which record or records that should be updated. %f you omit the ,;<$< clause, all records will be updated=

SQL '. A&< <#ample


&he @.ersons@ table: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

" C L P

Svendson .ettersen 6ilsen &3essem

&ove (ari Oohan Oa1ob

!orgvn "C Storgt "B !a11en "

Sandnes Stavanger Stavanger

6ow we want to update the person @&3essem, Oa1ob@ in the @.ersons@ table. ,e use the following SQL statement:

UP(ATE Persons SET A,,ress+'&'ssest'en 4@', C'ty+'San,nes' WHERE Last&ame+'T?essem' A&( F'rst&ame+'=a>o%'
&he @.ersons@ table will now loo1 li1e this: P_Id A " C L P LastName ;ansen Svendson .ettersen 6ilsen &3essem FirstName Ola &ove (ari Oohan Oa1ob Address &imoteivn AB !orgvn "C Storgt "B !a11en " 6issestien QR City Sandnes Sandnes Stavanger Stavanger Sandnes

SQL '. A&< ,arning


!e careful when updating records. %f we had omitted the ,;<$< clause in the e#ample above, li1e this:

UP(ATE Persons SET A,,ress+'&'ssest'en 4@', C'ty+'San,nes'


&he @.ersons@ table would have loo1ed li1e this: P_Id A " C L P LastName ;ansen Svendson .ettersen 6ilsen &3essem FirstName Ola &ove (ari Oohan Oa1ob Address 6issestien 6issestien 6issestien 6issestien 6issestien City Sandnes Sandnes Sandnes Sandnes Sandnes

QR QR QR QR QR

F .revious

6e#t -hapter G

SQL DELETE Statement


F .revious
&he <L<&< statement is used to delete records in a table.

6e#t -hapter G

&he
&he

<L<&< Statement

<L<&< statement is used to delete rows in a table.

SQL

<L<&< Synta#

(ELETE FROM ta%!e"name WHERE some" o!umn+some"*a!ue


Note: 6otice the ,;<$< clause in the <L<&< synta#. &he ,;<$< clause specifies which record or records that should be deleted. %f you omit the ,;<$< clause, all records will be deleted=

SQL

<L<&< <#ample

&he @.ersons@ table: P_Id A " C L P LastName ;ansen Svendson .ettersen 6ilsen &3essem FirstName Ola &ove (ari Oohan Oa1ob Address &imoteivn AB !orgvn "C Storgt "B !a11en " 6issestien QR City Sandnes Sandnes Stavanger Stavanger Sandnes

6ow we want to delete the person @&3essem, Oa1ob@ in the @.ersons@ table. ,e use the following SQL statement:

(ELETE FROM Persons WHERE Last&ame+'T?essem' A&( F'rst&ame+'=a>o%'


&he @.ersons@ table will now loo1 li1e this: P_Id A " C L LastName ;ansen Svendson .ettersen 6ilsen FirstName Ola &ove (ari Oohan Address &imoteivn AB !orgvn "C Storgt "B !a11en " City Sandnes Sandnes Stavanger Stavanger

elete All $ows


%t is possible to delete all rows in a table without deleting the table. &his means that the table structure, attributes, and inde#es will be intact:

(ELETE FROM ta%!e"name or (ELETE * FROM ta%!e"name


Note: !e very careful when deleting records. >ou cannot undo this statement=

F .revious

6e#t -hapter G

SQL TOP -lause

F .revious

6e#t -hapter G

&he &O. -lause


&he &O. clause is used to specify the number of records to return. &he &O. clause can be very useful on large tables with thousands of records. $eturning a large number of records can impact on performance. Note: 6ot all database systems support the &O. clause.

SQL Server Synta#


SELECT TOP num%er7per ent FROM ta%!e"name o!umn"name#s$

SQL S<L<-& &O. <9uivalent in MySQL and Oracle


MySQL Synta#
SELECT o!umn"name#s$ FROM ta%!e"name L)M)T num%er

<#ample
SELECT * FROM Persons L)M)T 5

Oracle Synta#
SELECT o!umn"name#s$ FROM ta%!e"name WHERE ROW&UM <+ num%er

<#ample
SELECT * FROM Persons WHERE ROW&UM <+5

SQL &O. <#ample


&he @.ersons@ table: P_Id A " C L LastName ;ansen Svendson .ettersen 6ilsen FirstName Ola &ove (ari &om Address &imoteivn AB !orgvn "C Storgt "B Mingvn "C City Sandnes Sandnes Stavanger Stavanger

6ow we want to select only the two first records in the table above. ,e use the following S<L<-& statement:

SELECT TOP 9 * FROM Persons


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

SQL &O. .<$-<6& <#ample


&he @.ersons@ table: P_Id A " C L LastName ;ansen Svendson .ettersen 6ilsen FirstName Ola &ove (ari &om Address &imoteivn AB !orgvn "C Storgt "B Mingvn "C City Sandnes Sandnes Stavanger Stavanger

6ow we want to select only PBS of the records in the table above. ,e use the following S<L<-& statement:

SELECT TOP 5A PERCE&T * FROM Persons


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

F .revious

6e#t -hapter G

SQL LI&E Operator


F .revious 6e#t -hapter G
&he L%(< operator is used in a ,;<$< clause to search for a specified pattern in a column.

&he L%(< Operator


&he L%(< operator is used to search for a specified pattern in a column.

SQL L%(< Synta#


SELECT o!umn"name#s$ FROM ta%!e"name WHERE o!umn"name L)BE pattern

L%(< Operator <#ample

&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the persons living in a city that starts with @s@ from the table above. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty L)BE 'sC'


&he @S@ sign can be used to define wildcards 7missing letters in the pattern8 both before and after the pattern. &he result:set will loo1 li1e this: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6e#t, we want to select the persons living in a city that ends with an @s@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty L)BE 'Cs'


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

6e#t, we want to select the persons living in a city that contains the pattern @tav@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty L)BE 'Cta*C'


&he result:set will loo1 li1e this: P_Id C LastName .ettersen FirstName (ari Address Storgt "B City Stavanger

%t is also possible to select the persons living in a city that 6O& contains the pattern @tav@ from the @.ersons@ table, by using the 6O& 1eyword. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty &OT L)BE 'Cta*C'


&he result:set will loo1 li1e this: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

"

Svendson

&ove

!orgvn "C

Sandnes

F .revious

6e#t -hapter G

SQL !i'd#ards
F .revious
SQL wildcards can be used when searching for data in a database.

6e#t -hapter G

SQL ,ildcards
SQL wildcards can substitute for one or more characters when searching for data in a database. SQL wildcards must be used with the SQL L%(< operator. ,ith SQL, the following wildcards can be used: !i'd#ard S D TcharlistU TVcharlistU or T=charlistU Des#ription A substitute for 4ero or more characters A substitute for e#actly one character Any single character in charlist Any single character not in charlist

SQL ,ildcard <#amples


,e have the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

'sing the S ,ildcard


6ow we want to select the persons living in a city that starts with @sa@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty L)BE 'saC'


&he result:set will loo1 li1e this:

P_Id A "

LastName ;ansen Svendson

FirstName Ola &ove

Address &imoteivn AB !orgvn "C

City Sandnes Sandnes

6e#t, we want to select the persons living in a city that contains the pattern @nes@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE C'ty L)BE 'CnesC'


&he result:set will loo1 li1e this: P_Id A " LastName ;ansen Svendson FirstName Ola &ove Address &imoteivn AB !orgvn "C City Sandnes Sandnes

'sing the D ,ildcard


6ow we want to select the persons with a first name that starts with any character, followed by @la@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE F'rst&ame L)BE '"!a'


&he result:set will loo1 li1e this: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

6e#t, we want to select the persons with a last name that starts with @S@, followed by any character, followed by @end@, followed by any character, followed by @on@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame L)BE 'S"en,"on'


&he result:set will loo1 li1e this: P_Id " LastName Svendson FirstName &ove Address !orgvn "C City Sandnes

'sing the TcharlistU ,ildcard


6ow we want to select the persons with a last name that starts with @b@ or @s@ or @p@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame L)BE 'D%spEC'


&he result:set will loo1 li1e this: P_Id " LastName Svendson FirstName &ove Address !orgvn "C City Sandnes

.ettersen

(ari

Storgt "B

Stavanger

6e#t, we want to select the persons with a last name that do not start with @b@ or @s@ or @p@ from the @.ersons@ table. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame L)BE 'DF%spEC'


&he result:set will loo1 li1e this: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

F .revious

6e#t -hapter G

SQL IN Operator
F .revious 6e#t -hapter G

&he %6 Operator
&he %6 operator allows you to specify multiple values in a ,;<$< clause.

SQL %6 Synta#
SELECT o!umn"name#s$ FROM ta%!e"name WHERE o!umn"name )& #*a!ue2,*a!ue9,;;;$

%6 Operator <#ample
&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the persons with a last name e9ual to @;ansen@ or @.ettersen@ from the table above. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame )& #'Hansen','Pettersen'$


&he result:set will loo1 li1e this: P_Id A C LastName ;ansen .ettersen FirstName Ola (ari Address &imoteivn AB Storgt "B City Sandnes Stavanger

F .revious

6e#t -hapter G

SQL BET!EEN Operator


F .revious 6e#t -hapter G
&he !<&,<<6 operator is used in a ,;<$< clause to select a range of data between two values.

&he !<&,<<6 Operator


&he !<&,<<6 operator selects a range of data between two values. &he values can be numbers, te#t, or dates.

SQL !<&,<<6 Synta#


SELECT o!umn"name#s$ FROM ta%!e"name WHERE o!umn"name 6ETWEE& *a!ue2 A&( *a!ue9

!<&,<<6 Operator <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the persons with a last name alphabetically between @;ansen@ and @.ettersen@ from the table above. ,e use the following S<L<-& statement:

SELECT * FROM Persons WHERE Last&ame 6ETWEE& 'Hansen' A&( 'Pettersen'


&he result:set will loo1 li1e this: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

Note: &he !<&,<<6 operator is treated differently in different databases. %n some databases, persons with the Last6ame of @;ansen@ or @.ettersen@ will not be listed, because the !<&,<<6 operator only selects fields that are between and e#cluding the test values8. %n other databases, persons with the Last6ame of @;ansen@ or @.ettersen@ will be listed, because the !<&,<<6 operator selects fields that are between and including the test values8.

And in other databases, persons with the Last6ame of @;ansen@ will be listed, but @.ettersen@ will not be listed 7li1e the e#ample above8, because the !<&,<<6 operator selects fields between the test values, including the first test value and e#cluding the last test value. &herefore: -hec1 how your database treats the !<&,<<6 operator.

<#ample "
&o display the persons outside the range in the previous e#ample, use 6O& !<&,<<6:

SELECT * FROM Persons WHERE Last&ame &OT 6ETWEE& 'Hansen' A&( 'Pettersen'
&he result:set will loo1 li1e this: P_Id " C LastName Svendson .ettersen FirstName &ove (ari Address !orgvn "C Storgt "B City Sandnes Stavanger

F .revious

6e#t -hapter G

SQL A'ias
F .revious
,ith SQL, an alias name can be given to a table or to a column.

6e#t -hapter G

SQL Alias
>ou can give a table or a column another name by using an alias. &his can be a good thing to do if you have very long or comple# table names or column names. An alias name could be anything, but usually it is short.

SQL Alias Synta# for &ables


SELECT o!umn"name#s$ FROM ta%!e"name AS a!'as"name

SQL Alias Synta# for -olumns


SELECT o!umn"name AS a!'as"name FROM ta%!e"name

Alias <#ample
Assume we have a table called @.ersons@ and another table called @.roductDOrders@. ,e will give the table aliases of @p@ and @po@ respectively.

6ow we want to list all the orders that @Ola ;ansen@ is responsible for. ,e use the following S<L<-& statement:

SELECT po;Or,er)(, p;Last&ame, p;F'rst&ame FROM Persons AS p, Pro,u t"Or,ers AS po WHERE p;Last&ame+'Hansen' A&( p;F'rst&ame+'O!a'
&he same S<L<-& statement without aliases:

SELECT Pro,u t"Or,ers;Or,er)(, Persons;Last&ame, Persons;F'rst&ame FROM Persons, Pro,u t"Or,ers WHERE Persons;Last&ame+'Hansen' A&( Persons;F'rst&ame+'O!a'
As youNll see from the two S<L<-& statements aboveW aliases can ma1e 9ueries easier to both write and to read.

F .revious

6e#t -hapter G

SQL (oins
F .revious 6e#t -hapter G
SQL 3oins are used to 9uery data from two or more tables, based on a relationship between certain columns in these tables.

SQL OO%6
&he OO%6 1eyword is used in an SQL statement to 9uery data from two or more tables, based on a relationship between certain columns in these tables. &ables in a database are often related to each other with 1eys. A primary 1ey is a column 7or a combination of columns8 with a uni9ue value for each row. <ach primary 1ey value must be uni9ue within the table. &he purpose is to bind data together, across tables, without repeating all of the data in every table. Loo1 at the @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ote that the @.D%d@ column is the primary 1ey in the @.ersons@ table. &his means that no two rows can have the same .D%d. &he .D%d distinguishes two persons even if they have the same name. 6e#t, we have the @Orders@ table: O_Id OrderNo P_Id

A " C L P

RRXYP LLQRX ""LPQ "LPQ" CLRQL

C C A A AP

6ote that the @OD%d@ column is the primary 1ey in the @Orders@ table and that the @.D%d@ column refers to the persons in the @.ersons@ table without using their names. 6otice that the relationship between the two tables above is the @.D%d@ column.

ifferent SQL OO%6s


!efore we continue with e#amples, we will list the types of OO%6 you can use, and the differences between them.

(OIN: $eturn rows when there is at least one match in both tables LEFT (OIN: $eturn all rows from the left table, even if there are no matches in the right table RI)"T (OIN: $eturn all rows from the right table, even if there are no matches in the left table FULL (OIN: $eturn rows when there is a match in one of the tables

F .revious

6e#t -hapter G

SQL INNER (OIN (eyword


F .revious 6e#t -hapter G

SQL %66<$ OO%6 (eyword


&he %66<$ OO%6 1eyword return rows when there is at least one match in both tables.

SQL %66<$ OO%6 Synta#


SELECT o!umn"name#s$ FROM ta%!e"name2 )&&ER =O)& ta%!e"name9 O& ta%!e"name2; o!umn"name+ta%!e"name9; o!umn"name
PS: %66<$ OO%6 is the same as OO%6.

SQL %66<$ OO%6 <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L P OrderNo RRXYP LLQRX ""LPQ "LPQ" CLRQL P_Id C C A A AP

6ow we want to list all the persons with any orders. ,e use the following S<L<-& statement:

SELECT Persons;Last&ame, Persons;F'rst&ame, Or,ers;Or,er&o FROM Persons )&&ER =O)& Or,ers O& Persons;P"),+Or,ers;P"), OR(ER 61 Persons;Last&ame
&he result:set will loo1 li1e this: LastName ;ansen ;ansen .ettersen .ettersen FirstName Ola Ola (ari (ari OrderNo ""LPQ "LPQ" RRXYP LLQRX

&he %66<$ OO%6 1eyword return rows when there is at least one match in both tables. %f there are rows in @.ersons@ that do not have matches in @Orders@, those rows will 6O& be listed.

SQL LEFT (OIN (eyword


F .revious 6e#t -hapter G

SQL L<0& OO%6 (eyword


&he L<0& OO%6 1eyword returns all rows from the left table 7tableDnameA8, even if there are no matches in the right table 7tableDname"8.

SQL L<0& OO%6 Synta#


SELECT o!umn"name#s$ FROM ta%!e"name2 LEFT =O)& ta%!e"name9 O& ta%!e"name2; o!umn"name+ta%!e"name9; o!umn"name
PS: %n some databases L<0& OO%6 is called L<0& O'&<$ OO%6.

SQL L<0& OO%6 <#ample


&he @.ersons@ table:

P_Id A " C

LastName ;ansen Svendson .ettersen

FirstName Ola &ove (ari

Address &imoteivn AB !orgvn "C Storgt "B

City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L P OrderNo RRXYP LLQRX ""LPQ "LPQ" CLRQL P_Id C C A A AP

6ow we want to list all the persons and their orders : if any, from the tables above. ,e use the following S<L<-& statement:

SELECT Persons;Last&ame, Persons;F'rst&ame, Or,ers;Or,er&o FROM Persons LEFT =O)& Or,ers O& Persons;P"),+Or,ers;P"), OR(ER 61 Persons;Last&ame
&he result:set will loo1 li1e this: LastName ;ansen ;ansen .ettersen .ettersen Svendson FirstName Ola Ola (ari (ari &ove OrderNo ""LPQ "LPQ" RRXYP LLQRX

&he L<0& OO%6 1eyword returns all the rows from the left table 7.ersons8, even if there are no matches in the right table 7Orders8.

F .revious

6e#t -hapter G

SQL RI)"T (OIN (eyword


F .revious 6e#t -hapter G

SQL $%);& OO%6 (eyword


&he $%);& OO%6 1eyword $eturn all rows from the right table 7tableDname"8, even if there are no matches in the left table 7tableDnameA8.

SQL $%);& OO%6 Synta#


SELECT o!umn"name#s$ FROM ta%!e"name2 R)GHT =O)& ta%!e"name9 O& ta%!e"name2; o!umn"name+ta%!e"name9; o!umn"name

PS: %n some databases $%);& OO%6 is called $%);& O'&<$ OO%6.

SQL $%);& OO%6 <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L P OrderNo RRXYP LLQRX ""LPQ "LPQ" CLRQL P_Id C C A A AP

6ow we want to list all the orders with containing persons : if any, from the tables above. ,e use the following S<L<-& statement:

SELECT Persons;Last&ame, Persons;F'rst&ame, Or,ers;Or,er&o FROM Persons R)GHT =O)& Or,ers O& Persons;P"),+Or,ers;P"), OR(ER 61 Persons;Last&ame
&he result:set will loo1 li1e this: LastName ;ansen ;ansen .ettersen .ettersen FirstName Ola Ola (ari (ari OrderNo ""LPQ "LPQ" RRXYP LLQRX CLRQL

&he $%);& OO%6 1eyword returns all the rows from the right table 7Orders8, even if there are no matches in the left table 7.ersons8.

F .revious

6e#t -hapter G

SQL FULL (OIN (eyword


F .revious 6e#t -hapter G

SQL 0'LL OO%6 (eyword


&he 0'LL OO%6 1eyword return rows when there is a match in one of the tables.

SQL 0'LL OO%6 Synta#


SELECT o!umn"name#s$ FROM ta%!e"name2 FULL =O)& ta%!e"name9 O& ta%!e"name2; o!umn"name+ta%!e"name9; o!umn"name

SQL 0'LL OO%6 <#ample


&he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L P OrderNo RRXYP LLQRX ""LPQ "LPQ" CLRQL P_Id C C A A AP

6ow we want to list all the persons and their orders, and all the orders with their persons. ,e use the following S<L<-& statement:

SELECT Persons;Last&ame, Persons;F'rst&ame, Or,ers;Or,er&o FROM Persons FULL =O)& Or,ers O& Persons;P"),+Or,ers;P"), OR(ER 61 Persons;Last&ame
&he result:set will loo1 li1e this: LastName ;ansen ;ansen .ettersen .ettersen Svendson FirstName Ola Ola (ari (ari &ove OrderNo ""LPQ "LPQ" RRXYP LLQRX CLRQL &he 0'LL OO%6 1eyword returns all the rows from the left table 7.ersons8, and all the rows from the right table 7Orders8. %f there are rows in @.ersons@ that do not have matches in @Orders@, or if there are rows in @Orders@ that do not have matches in @.ersons@, those rows will be listed as well.

F .revious

6e#t -hapter G

SQL UNION Operator


F .revious
&he SQL '6%O6 operator combines two or more S<L<-& statements.

6e#t -hapter G

&he SQL '6%O6 Operator


&he '6%O6 operator is used to combine the result:set of two or more S<L<-& statements. 6otice that each S<L<-& statement within the '6%O6 must have the same number of columns. &he columns must also have similar data types. Also, the columns in each S<L<-& statement must be in the same order.

SQL '6%O6 Synta#


SELECT U&)O& SELECT o!umn"name#s$ FROM ta%!e"name2 o!umn"name#s$ FROM ta%!e"name9

Note: &he '6%O6 operator selects only distinct values by default. &o allow duplicate values, use '6%O6 ALL.

SQL '6%O6 ALL Synta#


SELECT o!umn"name#s$ FROM ta%!e"name2 U&)O& ALL SELECT o!umn"name#s$ FROM ta%!e"name9
PS: &he column names in the result:set of a '6%O6 are always e9ual to the column names in the first S<L<-& statement in the '6%O6.

SQL '6%O6 <#ample


Loo1 at the following tables: *Emp'oyees_Nor+ay* : E_ID BA B" BC BL *Emp'oyees_USA* : E_ID BA B" BC BL E_Name &urner, Sally (ent, -lar1 Svendson, Stephen Scott, Stephen E_Name ;ansen, Ola Svendson, &ove Svendson, Stephen .ettersen, (ari

6ow we want to list a'' t,e di--erent employees in 6orway and 'SA. ,e use the following S<L<-& statement:

SELECT E"&ame FROM Emp!oyees"&or/ay U&)O& SELECT E"&ame FROM Emp!oyees"USA


&he result:set will loo1 li1e this:

E_Name ;ansen, Ola Svendson, &ove Svendson, Stephen .ettersen, (ari &urner, Sally (ent, -lar1 Scott, Stephen

Note: &his command cannot be used to list all employees in 6orway and 'SA. %n the e#ample above we have two employees with e9ual names, and only one of them will be listed. &he '6%O6 command selects only distinct values.

SQL '6%O6 ALL <#ample


6ow we want to list a'' employees in 6orway and 'SA:

SELECT E"&ame FROM Emp!oyees"&or/ay U&)O& ALL SELECT E"&ame FROM Emp!oyees"USA
Resu't

E_Name ;ansen, Ola Svendson, &ove Svendson, Stephen .ettersen, (ari &urner, Sally (ent, -lar1 Svendson, Stephen Scott, Stephen

F .revious

6e#t -hapter G

SQL SELECT INTO Statement

F .revious
&he SQL S<L<-& %6&O statement can be used to create bac1up copies of tables.

6e#t -hapter G

&he SQL S<L<-& %6&O Statement


&he S<L<-& %6&O statement selects data from one table and inserts it into a different table. &he S<L<-& %6&O statement is most often used to create bac1up copies of tables.

SQL S<L<-& %6&O Synta#


,e can select all columns into the new table:

SELECT * )&TO ne/"ta%!e"name D)& eHterna!,ata%aseE FROM o!,"ta%!ename


Or we can select only the columns we want into the new table:

SELECT o!umn"name#s$ )&TO ne/"ta%!e"name D)& eHterna!,ata%aseE FROM o!,"ta%!ename

SQL S<L<-& %6&O <#ample


.a/e a Ba#/up Copy : 6ow we want to ma1e an e#act copy of the data in our @.ersons@ table. ,e use the following SQL statement:

SELECT * )&TO Persons"6a >up FROM Persons


,e can also use the %6 clause to copy the table into another database:

SELECT * )&TO Persons"6a >up )& '6a >up;m,%' FROM Persons


,e can also copy only a few fields into the new table:

SELECT Last&ame,F'rst&ame )&TO Persons"6a >up FROM Persons

SQL S<L<-& %6&O : ,ith a ,;<$< -lause


,e can also add a ,;<$< clause. &he following SQL statement creates a @.ersonsD!ac1up@ table with only the persons who lives in the city @Sandnes@:

SELECT Last&ame,F'rstname )&TO Persons"6a >up FROM Persons WHERE C'ty+'San,nes'

SQL S<L<-& %6&O : Ooined &ables


Selecting data from more than one table is also possible. &he following e#ample creates a @.ersonsDOrderD!ac1up@ table contains data from the two tables @.ersons@ and @Orders@:

SELECT Persons;Last&ame,Or,ers;Or,er&o )&TO Persons"Or,er"6a >up FROM Persons )&&ER =O)& Or,ers O& Persons;P"),+Or,ers;P"),

F .revious

6e#t -hapter G

SQL CREATE DATABASE Statement


F .revious 6e#t -hapter G

&he -$<A&<
&he -$<A&<

A&A!AS< Statement

A&A!AS< statement is used to create a database.

SQL -$<A&<

A&A!AS< Synta#

CREATE (ATA6ASE ,ata%ase"name

-$<A&<

A&A!AS< <#ample

6ow we want to create a database called @myDdb@. ,e use the following -$<A&< A&A!AS< statement:

CREATE (ATA6ASE my",%


atabase tables can be added with the -$<A&< &A!L< statement.

F .revious

6e#t -hapt

SQL CREATE TABLE Statement


F .revious 6e#t -hapter G

&he -$<A&< &A!L< Statement


&he -$<A&< &A!L< statement is used to create a table in a database.

SQL -$<A&< &A!L< Synta#


CREATE TA6LE # o!umn"name2 o!umn"name9 o!umn"name: ;;;; $ ta%!e"name ,ata"type, ,ata"type, ,ata"type,

&he data type specifies what type of data the column can hold. 0or a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete ata &ypes reference.

-$<A&< &A!L< <#ample


6ow we want to create a table called @.ersons@ that contains five columns: .D%d, Last6ame, 0irst6ame, Address, and -ity. ,e use the following -$<A&< &A!L< statement:

CREATE TA6LE Persons # P"), 'nt, Last&ame *ar -ar#955$, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&he .D%d column is of type int and will hold a number. &he Last6ame, 0irst6ame, Address, and -ity columns are of type varchar with a ma#imum length of "PP characters. &he empty @.ersons@ table will now loo1 li1e this: P_Id LastName FirstName Address City

&he empty table can be filled with data with the %6S<$& %6&O statement.

F .revious

6e#t -hapter G

SQL Constraints
F .revious 6e#t -hapter G

SQL -onstraints

-onstraints are used to limit the type of data that can go into a table. -onstraints can be specified when a table is created 7with the -$<A&< &A!L< statement8 or after the table is created 7with the AL&<$ &A!L< statement8. ,e will focus on the following constraints:

6O& 6'LL '6%Q'< .$%MA$> (<> 0O$<%)6 (<> -;<-( <0A'L&

&he ne#t chapters will describe each constraint in details.

F .revious

6e#t -hapter G

SQL NOT NULL -onstraint


F .revious
!y default, a table column can hold 6'LL values.

6e#t -hapter G

SQL 6O& 6'LL -onstraint


&he 6O& 6'LL constraint enforces a column to 6O& accept 6'LL values. &he 6O& 6'LL constraint enforces a field to always contain a value. &his means that you cannot insert a new record, or update a record without adding a value to this field. &he following SQL enforces the @.D%d@ column and the @Last6ame@ column to not accept 6'LL values:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $

F .revious

6e#t -hapter G

SQL UNI0UE -onstraint


F .revious 6e#t -hapter G

SQL '6%Q'< -onstraint

&he '6%Q'< constraint uni9uely identifies each record in a database table. &he '6%Q'< and .$%MA$> (<> constraints both provide a guarantee for uni9ueness for a column or set of columns. A .$%MA$> (<> constraint automatically has a '6%Q'< constraint defined on it. 6ote that you can have many '6%Q'< constraints per table, but only one .$%MA$> (<> constraint per table.

SQL '6%Q'< -onstraint on -$<A&< &A!L<


&he following SQL creates a '6%Q'< constraint on the @.D%d@ column when the @.ersons@ table is created: .yS0L:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, U&)IUE #P"),$ $
S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL U&)IUE, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&o allow naming of a '6%Q'< constraint, and for defining a '6%Q'< constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, CO&STRA)&T u "Person)( U&)IUE #P"),,Last&ame$ $

SQL '6%Q'< -onstraint on AL&<$ &A!L<


&o create a '6%Q'< constraint on the @.D%d@ column when the table is already created, use the following SQL: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( U&)IUE #P"),$


&o allow naming of a '6%Q'< constraint, and for defining a '6%Q'< constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( CO&STRA)&T u "Person)( U&)IUE #P"),,Last&ame$

&o

$O. a '6%Q'< -onstraint

&o drop a '6%Q'< constraint, use the following SQL: .yS0L:

ALTER TA6LE Persons (ROP )&(EJ u "Person)(


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons (ROP CO&STRA)&T u "Person)(

F .revious

6e#t -hapter G

SQL PRI.AR% &E% -onstraint


F .revious 6e#t -hapter G

SQL .$%MA$> (<> -onstraint


&he .$%MA$> (<> constraint uni9uely identifies each record in a database table. .rimary 1eys must contain uni9ue values. A primary 1ey column cannot contain 6'LL values. <ach table should have a primary 1ey, and each table can have only one primary 1ey.

SQL .$%MA$> (<> -onstraint on -$<A&< &A!L<


&he following SQL creates a .$%MA$> (<> on the @.D%d@ column when the @.ersons@ table is created: .yS0L:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, PR)MAR1 BE1 #P"),$ $
S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons

# P"), 'nt &OT &ULL PR)MAR1 BE1, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&o allow naming of a .$%MA$> (<> constraint, and for defining a .$%MA$> (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, CO&STRA)&T p>"Person)( PR)MAR1 BE1 #P"),,Last&ame$ $

SQL .$%MA$> (<> -onstraint on AL&<$ &A!L<


&o create a .$%MA$> (<> constraint on the @.D%d@ column when the table is already created, use the following SQL: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( PR)MAR1 BE1 #P"),$


&o allow naming of a .$%MA$> (<> constraint, and for defining a .$%MA$> (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( CO&STRA)&T p>"Person)( PR)MAR1 BE1 #P"),,Last&ame$


Note: %f you use the AL&<$ &A!L< statement to add a primary 1ey, the primary 1ey column7s8 must already have been declared to not contain 6'LL values 7when the table was first created8.

&o

$O. a .$%MA$> (<> -onstraint

&o drop a .$%MA$> (<> constraint, use the following SQL: .yS0L:

ALTER TA6LE Persons (ROP PR)MAR1 BE1


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons (ROP CO&STRA)&T p>"Person)(

F .revious

6e#t -hapter G

SQL FOREI)N &E% -onstraint


F .revious 6e#t -hapter G

SQL 0O$<%)6 (<> -onstraint


A 0O$<%)6 (<> in one table points to a .$%MA$> (<> in another table. LetNs illustrate the foreign 1ey with an e#ample. Loo1 at the following two tables: &he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L OrderNo RRXYP LLQRX ""LPQ "LPQ" P_Id C C " A

6ote that the @.D%d@ column in the @Orders@ table points to the @.D%d@ column in the @.ersons@ table. &he @.D%d@ column in the @.ersons@ table is the .$%MA$> (<> in the @.ersons@ table. &he @.D%d@ column in the @Orders@ table is a 0O$<%)6 (<> in the @Orders@ table. &he 0O$<%)6 (<> constraint is used to prevent actions that would destroy lin1s between tables. &he 0O$<%)6 (<> constraint also prevents that invalid data form being inserted into the foreign 1ey column, because it has to be one of the values contained in the table it points to.

SQL 0O$<%)6 (<> -onstraint on -$<A&< &A!L<


&he following SQL creates a 0O$<%)6 (<> on the @.D%d@ column when the @Orders@ table is created: .yS0L:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL, Or,er&o 'nt &OT &ULL, P"), 'nt, PR)MAR1 BE1 #O"),$, FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$ $
S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL PR)MAR1 BE1, Or,er&o 'nt &OT &ULL,

P"), 'nt FORE)G& BE1 REFERE&CES Persons#P"),$ $


&o allow naming of a 0O$<%)6 (<> constraint, and for defining a 0O$<%)6 (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL, Or,er&o 'nt &OT &ULL, P"), 'nt, PR)MAR1 BE1 #O"),$, CO&STRA)&T K>"PerOr,ers FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$ $

SQL 0O$<%)6 (<> -onstraint on AL&<$ &A!L<


&o create a 0O$<%)6 (<> constraint on the @.D%d@ column when the @Orders@ table is already created, use the following SQL: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers A(( FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$


&o allow naming of a 0O$<%)6 (<> constraint, and for defining a 0O$<%)6 (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers A(( CO&STRA)&T K>"PerOr,ers FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$

&o

$O. a 0O$<%)6 (<> -onstraint

&o drop a 0O$<%)6 (<> constraint, use the following SQL: .yS0L:

ALTER TA6LE Or,ers (ROP FORE)G& BE1 K>"PerOr,ers


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers (ROP CO&STRA)&T K>"PerOr,ers

F .revious

6e#t -hapter G

SQL FOREI)N &E% -onstraint


F .revious 6e#t -hapter G

SQL 0O$<%)6 (<> -onstraint


A 0O$<%)6 (<> in one table points to a .$%MA$> (<> in another table. LetNs illustrate the foreign 1ey with an e#ample. Loo1 at the following two tables: &he @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

&he @Orders@ table: O_Id A " C L OrderNo RRXYP LLQRX ""LPQ "LPQ" P_Id C C " A

6ote that the @.D%d@ column in the @Orders@ table points to the @.D%d@ column in the @.ersons@ table. &he @.D%d@ column in the @.ersons@ table is the .$%MA$> (<> in the @.ersons@ table. &he @.D%d@ column in the @Orders@ table is a 0O$<%)6 (<> in the @Orders@ table. &he 0O$<%)6 (<> constraint is used to prevent actions that would destroy lin1s between tables. &he 0O$<%)6 (<> constraint also prevents that invalid data form being inserted into the foreign 1ey column, because it has to be one of the values contained in the table it points to.

SQL 0O$<%)6 (<> -onstraint on -$<A&< &A!L<


&he following SQL creates a 0O$<%)6 (<> on the @.D%d@ column when the @Orders@ table is created: .yS0L:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL, Or,er&o 'nt &OT &ULL, P"), 'nt, PR)MAR1 BE1 #O"),$, FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$ $
S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL PR)MAR1 BE1, Or,er&o 'nt &OT &ULL, P"), 'nt FORE)G& BE1 REFERE&CES Persons#P"),$ $

&o allow naming of a 0O$<%)6 (<> constraint, and for defining a 0O$<%)6 (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL, Or,er&o 'nt &OT &ULL, P"), 'nt, PR)MAR1 BE1 #O"),$, CO&STRA)&T K>"PerOr,ers FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$ $

SQL 0O$<%)6 (<> -onstraint on AL&<$ &A!L<


&o create a 0O$<%)6 (<> constraint on the @.D%d@ column when the @Orders@ table is already created, use the following SQL: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers A(( FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$


&o allow naming of a 0O$<%)6 (<> constraint, and for defining a 0O$<%)6 (<> constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers A(( CO&STRA)&T K>"PerOr,ers FORE)G& BE1 #P"),$ REFERE&CES Persons#P"),$

&o

$O. a 0O$<%)6 (<> -onstraint

&o drop a 0O$<%)6 (<> constraint, use the following SQL: .yS0L:

ALTER TA6LE Or,ers (ROP FORE)G& BE1 K>"PerOr,ers


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Or,ers (ROP CO&STRA)&T K>"PerOr,ers

F .revious

6e#t -hapter G

SQL C"EC& -onstraint


F .revious 6e#t -hapter G

SQL -;<-( -onstraint


&he -;<-( constraint is used to limit the value range that can be placed in a column. %f you define a -;<-( constraint on a single column it allows only certain values for this column. %f you define a -;<-( constraint on a table it can limit the values in certain columns based on values in other columns in the row.

SQL -;<-( -onstraint on -$<A&< &A!L<


&he following SQL creates a -;<-( constraint on the @.D%d@ column when the @.ersons@ table is created. &he -;<-( constraint specifies that the column @.D%d@ must only include integers greater than B. .y S0L:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, CHECB #P"),>A$ $
S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL CHECB #P"),>A$, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&o allow naming of a -;<-( constraint, and for defining a -;<-( constraint on multiple columns, use the following SQL synta#: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, CO&STRA)&T ->"Person CHECB #P"),>A A&( C'ty+'San,nes'$ $

SQL -;<-( -onstraint on AL&<$ &A!L<


&o create a -;<-( constraint on the @.D%d@ column when the table is already created, use the following SQL: .yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( CHECB #P"),>A$


&o allow naming of a -;<-( constraint, and for defining a -;<-( constraint on multiple columns, use the following SQL synta#:

.yS0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons A(( CO&STRA)&T ->"Person CHECB #P"),>A A&( C'ty+'San,nes'$

&o

$O. a -;<-( -onstraint

&o drop a -;<-( constraint, use the following SQL: S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons (ROP CO&STRA)&T ->"Person

F .revious

6e#t -hapter G

SQL DEFAULT -onstraint


F .revious 6e#t -hapter G

SQL
&he

<0A'L& -onstraint

<0A'L& constraint is used to insert a default value into a column.

&he default value will be added to all new records, if no other value is specified.

SQL

<0A'L& -onstraint on -$<A&< &A!L<


<0A'L& constraint on the @-ity@ column when the @.ersons@ table is created:

&he following SQL creates a

.y S0L 2 S0L Ser1er 2 Ora#'e 2 .S A##ess:

CREATE TA6LE Persons # P"), 'nt &OT &ULL, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ (EFAULT 'San,nes' $
&he <0A'L& constraint can also be used to insert system values, by using functions li1e )<& A&<78:

CREATE TA6LE Or,ers # O"), 'nt &OT &ULL, Or,er&o 'nt &OT &ULL, P"), 'nt, Or,er(ate ,ate (EFAULT GET(ATE#$ $

SQL

<0A'L& -onstraint on AL&<$ &A!L<


<0A'L& constraint on the @-ity@ column when the table is already created, use the following SQL:

&o create a .yS0L:

ALTER TA6LE Persons ALTER C'ty SET (EFAULT 'SA&(&ES'


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons ALTER COLUM& C'ty SET (EFAULT 'SA&(&ES'

&o

$O. a

<0A'L& -onstraint

&o drop a .yS0L:

<0A'L& constraint, use the following SQL:

ALTER TA6LE Persons ALTER C'ty (ROP (EFAULT


S0L Ser1er 2 Ora#'e 2 .S A##ess:

ALTER TA6LE Persons ALTER COLUM& C'ty (ROP (EFAULT

F .revious

6e#t -hapter G

SQL CREATE INDE


F .revious

Statement
6e#t -hapter G

&he -$<A&< %6 <Z statement is used to create inde#es in tables. %nde#es allow the database application to find data fastW without reading the whole table.

%nde#es
An inde# can be created in a table to find data more 9uic1ly and efficiently. &he users cannot see the inde#es, they are 3ust used to speed up searches?9ueries. Note: 'pdating a table with inde#es ta1es more time than updating a table without 7because the inde#es also need an update8. So you should only create inde#es on columns 7and tables8 that will be fre9uently searched against.

SQL -$<A&< %6 <Z Synta#


-reates an inde# on a table. uplicate values are allowed:

CREATE )&(EJ 'n,eH"name O& ta%!e"name # o!umn"name$

SQL -$<A&< '6%Q'< %6 <Z Synta#


-reates a uni9ue inde# on a table. uplicate values are not allowed:

CREATE U&)IUE )&(EJ 'n,eH"name

O& ta%!e"name # o!umn"name$


Note: &he synta# for creating inde#es varies amongst different databases. &herefore: -hec1 the synta# for creating inde#es in your database.

-$<A&< %6 <Z <#ample


&he SQL statement below creates an inde# named @.%nde#@ on the @Last6ame@ column in the @.ersons@ table:

CREATE )&(EJ P)n,eH O& Persons #Last&ame$


%f you want to create an inde# on a combination of columns, you can list the column names within the parentheses, separated by commas:

CREATE )&(EJ P)n,eH O& Persons #Last&ame, F'rst&ame$

F .revious

6e#t -hapter G

SQL DROP INDE 3 DROP TABLE3 and DROP DATABASE


F .revious
%nde#es, tables, and databases can easily be deleted?removed with the

6e#t -hapter G
$O. statement.

&he
&he

$O. %6 <Z Statement

$O. %6 <Z statement is used to delete an inde# in a table.

$O. %6 <Z Synta# for MS Access:


(ROP )&(EJ 'n,eH"name O& ta%!e"name

$O. %6 <Z Synta# for MS SQL Server:


(ROP )&(EJ ta%!e"name;'n,eH"name

$O. %6 <Z Synta# for


(ROP )&(EJ 'n,eH"name

!"?Oracle:

$O. %6 <Z Synta# for MySQL:


ALTER TA6LE ta%!e"name (ROP )&(EJ 'n,eH"name

&he
&he

$O. &A!L< Statement

$O. &A!L< statement is used to delete a table.

(ROP TA6LE ta%!e"name

&he
&he

$O.

A&A!AS< Statement

$O.

A&A!AS< statement is used to delete a database.

(ROP (ATA6ASE ,ata%ase"name

&he &$'6-A&< &A!L< Statement


,hat if we only want to delete the data inside the table, and not the table itself5 &hen, use the &$'6-A&< &A!L< statement:

TRU&CATE TA6LE ta%!e"name

F .revious

6e#t -hapter G

SQL ALTER TABLE Statement


F .revious 6e#t -hapter G

&he AL&<$ &A!L< Statement


&he AL&<$ &A!L< statement is used to add, delete, or modify columns in an e#isting table.

SQL AL&<$ &A!L< Synta#


&o add a column in a table, use the following synta#:

ALTER TA6LE ta%!e"name A(( o!umn"name ,atatype


&o delete a column in a table, use the following synta# 7notice that some database systems donNt allow deleting a column8:

ALTER TA6LE ta%!e"name (ROP COLUM& o!umn"name


&o change the data type of a column in a table, use the following synta#:

ALTER TA6LE ta%!e"name ALTER COLUM& o!umn"name ,atatype

SQL AL&<$ &A!L< <#ample


Loo1 at the @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to add a column named @ ateOf!irth@ in the @.ersons@ table. ,e use the following SQL statement:

ALTER TA6LE Persons A(( (ateOK6'rt- ,ate


6otice that the new column, @ ateOf!irth@, is of type date and is going to hold a date. &he data type specifies what type of data the column can hold. 0or a complete reference of all the data types available in MS Access, MySQL, and SQL Server, go to our complete ata &ypes reference. &he @.ersons@ table will now li1e this: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger DateO-Birt,

-hange

ata &ype <#ample

6ow we want to change the data type of the column named @ ateOf!irth@ in the @.ersons@ table. ,e use the following SQL statement:

ALTER TA6LE Persons ALTER COLUM& (ateOK6'rt- year


6otice that the @ ateOf!irth@ column is now of type year and is going to hold a year in a two:digit or four:digit format.

$O. -OL'M6 <#ample


6e#t, we want to delete the column named @ ateOf!irth@ in the @.ersons@ table. ,e use the following SQL statement:

ALTER TA6LE Persons (ROP COLUM& (ateOK6'rt&he @.ersons@ table will now li1e this: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

F .revious

6e#t -hapter G

SQL AUTO INCRE.ENT 0ield


F .revious 6e#t -hapter G
Auto:increment allows a uni9ue number to be generated when a new record is inserted into a table.

A'&O %6-$<M<6& a 0ield

Mery often we would li1e the value of the primary 1ey field to be created automatically every time a new record is inserted. ,e would li1e to create an auto:increment field in a table.

Synta# for MySQL


&he following SQL statement defines the @.D%d@ column to be an auto:increment primary 1ey field in the @.ersons@ table:

CREATE TA6LE Persons # P"), 'nt &OT &ULL AUTO")&CREME&T, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$, PR)MAR1 BE1 #P"),$ $
MySQL uses the A'&OD%6-$<M<6& 1eyword to perform an auto:increment feature. !y default, the starting value for A'&OD%6-$<M<6& is A, and it will increment by A for each new record. &o let the A'&OD%6-$<M<6& se9uence start with another value, use the following SQL statement:

ALTER TA6LE Persons AUTO")&CREME&T+2AA


&o insert a new record into the @.ersons@ table, we will not have to specify a value for the @.D%d@ column 7a uni9ue value will be added automatically8:

)&SERT )&TO Persons #F'rst&ame,Last&ame$ 8ALUES #'Lars','Monsen'$


&he SQL statement above would insert a new record into the @.ersons@ table. &he @.D%d@ column would be assigned a uni9ue value. &he @0irst6ame@ column would be set to @Lars@ and the @Last6ame@ column would be set to @Monsen@.

Synta# for SQL Server


&he following SQL statement defines the @.D%d@ column to be an auto:increment primary 1ey field in the @.ersons@ table:

CREATE TA6LE Persons # P"), 'nt PR)MAR1 BE1 )(E&T)T1, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&he MS SQL Server uses the % <6&%&> 1eyword to perform an auto:increment feature. !y default, the starting value for % <6&%&> is A, and it will increment by A for each new record. &o specify that the @.D%d@ column should start at value AB and increment by P, change the identity to % <6&%&>7AB,P8. &o insert a new record into the @.ersons@ table, we will not have to specify a value for the @.D%d@ column 7a uni9ue value will be added automatically8:

)&SERT )&TO Persons #F'rst&ame,Last&ame$ 8ALUES #'Lars','Monsen'$

&he SQL statement above would insert a new record into the @.ersons@ table. &he @.D%d@ column would be assigned a uni9ue value. &he @0irst6ame@ column would be set to @Lars@ and the @Last6ame@ column would be set to @Monsen@.

Synta# for Access


&he following SQL statement defines the @.D%d@ column to be an auto:increment primary 1ey field in the @.ersons@ table:

CREATE TA6LE Persons # P"), PR)MAR1 BE1 AUTO)&CREME&T, Last&ame *ar -ar#955$ &OT &ULL, F'rst&ame *ar -ar#955$, A,,ress *ar -ar#955$, C'ty *ar -ar#955$ $
&he MS Access uses the A'&O%6-$<M<6& 1eyword to perform an auto:increment feature. !y default, the starting value for A'&O%6-$<M<6& is A, and it will increment by A for each new record. &o specify that the @.D%d@ column should start at value AB and increment by P, change the autoincrement to A'&O%6-$<M<6&7AB,P8. &o insert a new record into the @.ersons@ table, we will not have to specify a value for the @.D%d@ column 7a uni9ue value will be added automatically8:

)&SERT )&TO Persons #F'rst&ame,Last&ame$ 8ALUES #'Lars','Monsen'$


&he SQL statement above would insert a new record into the @.ersons@ table. &he @.D%d@ column would be assigned a uni9ue value. &he @0irst6ame@ column would be set to @Lars@ and the @Last6ame@ column would be set to @Monsen@.

Synta# for Oracle


%n Oracle the code is a little bit more tric1y. >ou will have to create an auto:increment field with the se9uence ob3ect 7this ob3ect generates a number se9uence8. 'se the following -$<A&< S<Q'<6-< synta#:

CREATE SEIUE&CE seL"person M)&8ALUE 2 START W)TH 2 )&CREME&T 61 2 CACHE 2A


&he code above creates a se9uence ob3ect called se9Dperson, that starts with A and will increment by A. %t will also cache up to AB values for performance. &he cache option specifies how many se9uence values will be stored in memory for faster access. &o insert a new record into the @.ersons@ table, we will have to use the ne#tval function 7this function retrieves the ne#t value from se9Dperson se9uence8:

)&SERT )&TO Persons #P"),,F'rst&ame,Last&ame$ 8ALUES #seL"person;neHt*a!,'Lars','Monsen'$


&he SQL statement above would insert a new record into the @.ersons@ table. &he @.D%d@ column would be assigned the ne#t number from the se9Dperson se9uence. &he @0irst6ame@ column would be set to @Lars@ and the @Last6ame@ column would be set to @Monsen@.

F .revious

6e#t -hapter G

SQL 4ie+s
F .revious
A view is a virtual table. &his chapter shows how to create, update, and delete a view.

6e#t -hapter G

SQL -$<A&< M%<, Statement


%n SQL, a view is a virtual table based on the result:set of an SQL statement. A view contains rows and columns, 3ust li1e a real table. &he fields in a view are fields from one or more real tables in the database. >ou can add SQL functions, ,;<$<, and OO%6 statements to a view and present the data as if the data were coming from one single table.

SQL -$<A&< M%<, Synta#


CREATE 8)EW *'e/"name AS SELECT o!umn"name#s$ FROM ta%!e"name WHERE on,'t'on
Note: A view always shows up:to:date data= &he database engine recreates the data, using the viewNs SQL statement, every time a user 9ueries a view.

SQL -$<A&< M%<, <#amples


%f you have the 6orthwind database you can see that it has several views installed by default. &he view @-urrent .roduct List@ lists all active products 7products that are not discontinued8 from the @.roducts@ table. &he view is created with the following SQL:

CREATE 8)EW DCurrent Pro,u t L'stE AS SELECT Pro,u t)(,Pro,u t&ame FROM Pro,u ts WHERE ('s ont'nue,+&o
,e can 9uery the view above as follows:

SELECT * FROM DCurrent Pro,u t L'stE


Another view in the 6orthwind sample database selects every product in the @.roducts@ table with a unit price higher than the average unit price:

CREATE 8)EW DPro,u ts A%o*e A*era0e Pr' eE AS SELECT Pro,u t&ame,Un'tPr' e FROM Pro,u ts WHERE Un'tPr' e>#SELECT A8G#Un'tPr' e$ FROM Pro,u ts$

,e can 9uery the view above as follows:

SELECT * FROM DPro,u ts A%o*e A*era0e Pr' eE


Another view in the 6orthwind database calculates the total sale for each category in AYYR. 6ote that this view selects its data from another view called @.roduct Sales for AYYR@:

CREATE 8)EW DCate0ory Sa!es For 233@E AS SELECT ()ST)&CT Cate0ory&ame,Sum#Pro,u tSa!es$ AS Cate0orySa!es FROM DPro,u t Sa!es Kor 233@E GROUP 61 Cate0ory&ame
,e can 9uery the view above as follows:

SELECT * FROM DCate0ory Sa!es For 233@E


,e can also add a condition to the 9uery. 6ow we want to see the total sale only for the category @!everages@:

SELECT * FROM DCate0ory Sa!es For 233@E WHERE Cate0ory&ame+'6e*era0es'

SQL 'pdating a Miew


>ou can update a view by using the following synta#:

SQL -$<A&< O$ $<.LA-< M%<, Synta#


CREATE OR REPLACE 8)EW *'e/"name AS SELECT o!umn"name#s$ FROM ta%!e"name WHERE on,'t'on
6ow we want to add the @-ategory@ column to the @-urrent .roduct List@ view. ,e will update the view with the following SQL:

CREATE 8)EW DCurrent Pro,u t L'stE AS SELECT Pro,u t)(,Pro,u t&ame,Cate0ory FROM Pro,u ts WHERE ('s ont'nue,+&o

SQL

ropping a Miew
$O. M%<, command.

>ou can delete a view with the

SQL

$O. M%<, Synta#

(ROP 8)EW *'e/"name

F .revious

6e#t -hapter G

SQL Date 0unctions


F .revious 6e#t -hapter G

SQL

ates

&he most difficult part when wor1ing with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database. As long as your data contains only the date portion, your 9ueries will wor1 as e#pected. ;owever, if a time portion is involved, it gets complicated. !efore tal1ing about the complications of 9uerying for dates, we will loo1 at the most important built:in functions for wor1ing with dates.

MySQL

ate 0unctions

&he following table lists the most important built:in date functions in MySQL: Fun#tion 6O,78 -'$ A&<78 -'$&%M<78 A&<78 <Z&$A-&78 A&<DA 78 A&<DS'!78 A&< %0078 A&<D0O$MA&78 Des#ription $eturns the current date and time $eturns the current date $eturns the current time <#tracts the date part of a date or date?time e#pression $eturns a single part of a date?time Adds a specified time interval to a date Subtracts a specified time interval from a date $eturns the number of days between two dates isplays date?time data in different formats

SQL Server

ate 0unctions

&he following table lists the most important built:in date functions in SQL Server: Fun#tion )<& A&<78 A&<.A$&78 A&<A 78 A&< %0078 -O6M<$&78 Des#ription $eturns the current date and time $eturns a single part of a date?time Adds or subtracts a specified time interval from a date $eturns the time between two dates isplays date?time data in different formats

SQL

ate

ata &ypes

.yS0L comes with the following data types for storing a date or a date?time value in the database:

A&< : format >>>>:MM: A&<&%M< : format: >>>>:MM: &%M<S&AM. : format: >>>>:MM: ><A$ : format >>>> or >> ;;:MM:SS ;;:MM:SS

S0L Ser1er comes with the following data types for storing a date or a date?time value in the database:

A&< : format >>>>:MM: A&<&%M< : format: >>>>:MM: ;;:MM:SS ;;:MM:SS

SMALL A&<&%M< : format: >>>>:MM: &%M<S&AM. : format: a uni9ue number

Note: &he date types are chosen for a column when you create a new table in your database= 0or an overview of all data types available, go to our complete ata &ypes reference.

SQL ,or1ing with

ates

>ou can compare two dates easily if there is no time component involved= Assume we have the following @Orders@ table: OrderId A " C L Produ#tName )eitost -amembert .ierrot Mo44arella di )iovanni Mascarpone 0abioli OrderDate "BBX:AA:AA "BBX:AA:BY "BBX:AA:AA "BBX:AB:"Y

6ow we want to select the records with an Order ate of @"BBX:AA:AA@ from the table above. ,e use the following S<L<-& statement:

SELECT * FROM Or,ers WHERE Or,er(ate+'9AAMN22N22'


&he result:set will loo1 li1e this: OrderId A C Produ#tName )eitost Mo44arella di )iovanni OrderDate "BBX:AA:AA "BBX:AA:AA

6ow, assume that the @Orders@ table loo1s li1e this 7notice the time component in the @Order ate@ column8: OrderId A " C L Produ#tName )eitost -amembert .ierrot Mo44arella di )iovanni Mascarpone 0abioli OrderDate "BBX:AA:AA "BBX:AA:BY "BBX:AA:AA "BBX:AB:"Y

AC:"C:LL AP:LP:"A AA:A":BA AL:PQ:PY

%f we use the same S<L<-& statement as above:

SELECT * FROM Or,ers WHERE Or,er(ate+'9AAMN22N22'


we will get no result= &his is because the 9uery is loo1ing only for dates with no time portion. Tip: %f you want to 1eep your 9ueries simple and easy to maintain, do not allow time components in your dates=

F .revious

6e#t -hapter G

SQL NULL 4a'ues


F .revious
6'LL values represent missing un1nown data. !y default, a table column can hold 6'LL values. &his chapter will e#plain the %S 6'LL and %S 6O& 6'LL operators.

6e#t -hapter G

SQL 6'LL Malues


%f a column in a table is optional, we can insert a new record or update an e#isting record without adding a value to this column. &his means that the field will be saved with a 6'LL value. 6'LL values are treated differently from other values. 6'LL is used as a placeholder for un1nown or inapplicable values.

Note: %t is not possible to compare 6'LL and BW they are not e9uivalent.

SQL ,or1ing with 6'LL Malues


Loo1 at the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address !orgvn "C City Sandnes Sandnes Stavanger

Suppose that the @Address@ column in the @.ersons@ table is optional. &his means that if we insert a record with no value for the @Address@ column, the @Address@ column will be saved with a 6'LL value. ;ow can we test for 6'LL values5 %t is not possible to test for 6'LL values with comparison operators, such as H, I, or IJ. ,e will have to use the %S 6'LL and %S 6O& 6'LL operators instead.

SQL %S 6'LL
;ow do we select only the records with 6'LL values in the @Address@ column5 ,e will have to use the %S 6'LL operator:

SELECT Last&ame,F'rst&ame,A,,ress FROM Persons WHERE A,,ress )S &ULL


&he result:set will loo1 li1e this: LastName ;ansen .ettersen FirstName Ola (ari Address

Tip: Always use %S 6'LL to loo1 for 6'LL values.

SQL %S 6O& 6'LL


;ow do we select only the records with no 6'LL values in the @Address@ column5 ,e will have to use the %S 6O& 6'LL operator:

SELECT Last&ame,F'rst&ame,A,,ress FROM Persons WHERE A,,ress )S &OT &ULL

&he result:set will loo1 li1e this: LastName Svendson FirstName &ove Address !orgvn "C

%n the ne#t chapter we will loo1 at the %S6'LL78, 6ML78, %06'LL78 and -OAL<S-<78 functions.

F .revious

6e#t -hapter G

SQL NULL 0unctions


F .revious 6e#t -hapter G

SQL %S6'LL78, 6ML78, %06'LL78 and -OAL<S-<78 0unctions


Loo1 at the following @.roducts@ table: P_Id A " C Produ#tName Oarlsberg Mascarpone )orgon4ola UnitPri#e AB.LP C".PQ AP.QR UnitsInSto#/ AQ "C Y UnitsOnOrder AP "B

Suppose that the @'nitsOnOrder@ column is optional, and may contain 6'LL values. ,e have the following S<L<-& statement:

SELECT Pro,u t&ame,Un'tPr' e*#Un'ts)nSto >OUn'tsOnOr,er$ FROM Pro,u ts


%n the e#ample above, if any of the @'nitsOnOrder@ values are 6'LL, the result is 6'LL. MicrosoftNs %S6'LL78 function is used to specify how we want to treat 6'LL values. &he 6ML78, %06'LL78, and -OAL<S-<78 functions can also be used to achieve the same result. %n this case we want 6'LL values to be 4ero. !elow, if @'nitsOnOrder@ is 6'LL it will not harm the calculation, because %S6'LL78 returns a 4ero if the value is 6'LL: S0L Ser1er 2 .S A##ess

SELECT Pro,u t&ame,Un'tPr' e*#Un'ts)nSto >O)S&ULL#Un'tsOnOr,er,A$$ FROM Pro,u ts


Ora#'e Oracle does not have an %S6'LL78 function. ;owever, we can use the 6ML78 function to achieve the same result:

SELECT Pro,u t&ame,Un'tPr' e*#Un'ts)nSto >O&8L#Un'tsOnOr,er,A$$ FROM Pro,u ts


.yS0L MySQL does have an %S6'LL78 function. ;owever, it wor1s a little bit different from MicrosoftNs %S6'LL78 function.

%n MySQL we can use the %06'LL78 function, li1e this:

SELECT Pro,u t&ame,Un'tPr' e*#Un'ts)nSto >O)F&ULL#Un'tsOnOr,er,A$$ FROM Pro,u ts


or we can use the -OAL<S-<78 function, li1e this:

SELECT Pro,u t&ame,Un'tPr' e*#Un'ts)nSto >OCOALESCE#Un'tsOnOr,er,A$$ FROM Pro,u ts

F .revious

6e#t -hapter G

SQL Data Types


F .revious
ata types and ranges for Microsoft Access, MySQL and SQL Server.

6e#t -hapter G

Microsoft Access
Data type &e#t Memo !yte %nteger Long Single ouble -urrency Auto6umber ate?&ime >es?6o Ole Ob3ect ;yperlin1 Loo1up ,i4ard

ata &ypes
Stora5e

Des#ription 'se for te#t or combinations of te#t and numbers. "PP characters ma#imum Memo is used for larger amounts of te#t. Stores up to QP,PCQ characters. Note: >ou cannot sort a memo field. ;owever, they are searchable Allows whole numbers from B to "PP Allows whole numbers between :C",RQX and C",RQR Allows whole numbers between :",ALR,LXC,QLX and ",ALR,LXC,QLR Single precision floating:point. ,ill handle most decimals ouble precision floating:point. ,ill handle most decimals 'se for currency. ;olds up to AP digits of whole dollars, plus L decimal places. Tip: >ou can choose which countryNs currency to use Auto6umber fields automatically give each record its own number, usually starting at A 'se for dates and times A logical field can be displayed as >es?6o, &rue?0alse, or On?Off. %n code, use the constants &rue and 0alse 7e9uivalent to :A and B8.Note: 6ull values are not allowed in >es?6o fields -an store pictures, audio, video, or other !LO!s 7!inary Large O!3ects8 -ontain lin1s to other files, including web pages Let you type a list of options, which can then be chosen from a drop:down list

A " L L X X

byte bytes bytes bytes bytes bytes

L bytes X bytes A bit up to A)! L bytes

MySQL

ata &ypes
ate?&ime types.

%n MySQL there are three main types : te#t, number, and Te6t types: Data type -;A$7si4e8 MA$-;A$7si4e8

&%6>&<Z& &<Z& !LO! M< %'M&<Z& M< %'M!LO! LO6)&<Z& LO6)!LO! <6'M7#,y,4,etc.8

Des#ription ;olds a fi#ed length string 7can contain letters, numbers, and special characters8. &he fi#ed si4e is specified in parenthesis. -an store up to "PP characters ;olds a variable length string 7can contain letters, numbers, and special characters8. &he ma#imum si4e is specified in parenthesis. -an store up to "PP characters. Note: %f you put a greater value than "PP it will be converted to a &<Z& type ;olds a string with a ma#imum length of "PP characters ;olds a string with a ma#imum length of QP,PCP characters 0or !LO!s 7!inary Large O!3ects8. ;olds up to QP,PCP bytes of data ;olds a string with a ma#imum length of AQ,RRR,"AP characters 0or !LO!s 7!inary Large O!3ects8. ;olds up to AQ,RRR,"AP bytes of data ;olds a string with a ma#imum length of L,"YL,YQR,"YP characters 0or !LO!s 7!inary Large O!3ects8. ;olds up to L,"YL,YQR,"YP bytes of data Let you enter a list of possible values. >ou can list up to QPPCP values in an <6'M list. %f a value is inserted that is not in the list, a blan1 value will be inserted.

Note: &he values are sorted in the order you enter them. >ou enter the possible values in this format: <6'M7NZN,N>N,N2N8 Similar to <6'M e#cept that S<& may contain up to QL list items and can store more than one choice

S<& Num7er types: Data type &%6>%6&7si4e8 SMALL%6&7si4e8 M< %'M%6&7si4e8 %6&7si4e8 !%)%6&7si4e8 0LOA&7si4e,d8

O'!L<7si4e,d8

<-%MAL7si4e,d8

Des#ription :A"X to A"R normal. B to "PP '6S%)6< E. &he ma#imum number of digits may be specified in parenthesis :C"RQX to C"RQR normal. B to QPPCP '6S%)6< E. &he ma#imum number of digits may be specified in parenthesis :XCXXQBX to XCXXQBR normal. B to AQRRR"AP '6S%)6< E. &he ma#imum number of digits may be specified in parenthesis :"ALRLXCQLX to "ALRLXCQLR normal. B to L"YLYQR"YP '6S%)6< E. &he ma#imum number of digits may be specified in parenthesis :Y""CCR"BCQXPLRRPXBX to Y""CCR"BCQXPLRRPXBR normal. B to AXLLQRLLBRCRBYPPAQAP '6S%)6< E. &he ma#imum number of digits may be specified in parenthesis A small number with a floating decimal point. &he ma#imum number of digits may be specified in the si4e parameter. &he ma#imum number of digits to the right of the decimal point is specified in the d parameter A large number with a floating decimal point. &he ma#imum number of digits may be specified in the si4e parameter. &he ma#imum number of digits to the right of the decimal point is specified in the d parameter A O'!L< stored as a string , allowing for a fi#ed decimal point. &he ma#imum number of digits may be specified in the si4e parameter. &he ma#imum number of digits to the right of the decimal point is specified in the d parameter

E&he integer types have an e#tra option called '6S%)6< . 6ormally, the integer goes from an negative to positive value. Adding the '6S%)6< attribute will move that range up so it starts at 4ero instead of a negative number. Date types: Data type A&<78 Des#ription A date. 0ormat: >>>>:MM: Note: &he supported range is from NABBB:BA:BAN to NYYYY:A":CAN EA date and time combination. 0ormat: >>>>:MM: ;;:MM:SS Note: &he supported range is from NABBB:BA:BA BB:BB:BBN to NYYYY:A":CA "C:PY:PYN EA timestamp. &%M<S&AM. values are stored as the number of seconds since the 'ni# epoch 7NAYRB:BA: BA BB:BB:BBN '&-8. 0ormat: >>>>:MM: ;;:MM:SS Note: &he supported range is from NAYRB:BA:BA BB:BB:BAN '&- to N"BCX:BA:BY BC:AL:BRN '&A time. 0ormat: ;;:MM:SS Note: &he supported range is from N:XCX:PY:PYN to NXCX:PY:PYN A year in two:digit or four:digit format. Note: Malues allowed in four:digit format: AYBA to "APP. Malues allowed in two:digit format: RB to QY, representing years from AYRB to "BQY E<ven if A&<&%M< and &%M<S&AM. return the same format, they wor1 very differently. %n an %6S<$& or '. A&< 9uery, the &%M<S&AM. automatically set itself to the current date and time. &%M<S&AM. also accepts various formats, li1e >>>>MM ;;MMSS, >>MM ;;MMSS, >>>>MM , or >>MM .

A&<&%M<78

&%M<S&AM.78

&%M<78

><A$78

SQL Server
C,ara#ter strin5s: Data type char7n8 varchar7n8 varchar7ma#8 te#t

ata &ypes

Des#ription 0i#ed:length character string. Ma#imum X,BBB characters Mariable:length character string. Ma#imum X,BBB characters Mariable:length character string. Ma#imum A,BRC,RLA,X"L characters Mariable:length character string. Ma#imum ")! of te#t data

Stora5e n

Uni#ode strin5s: Data type nchar7n8 nvarchar7n8 nvarchar7ma#8 nte#t Binary types: Data type bit binary7n8 varbinary7n8 varbinary7ma#8 image Num7er types: Data type tinyint smallint int bigint decimal7p,s8 Des#ription Allows whole numbers from B to "PP Allows whole numbers between :C",RQX and C",RQR Allows whole numbers between :",ALR,LXC,QLX and ",ALR,LXC,QLR Allows whole numbers between :Y,""C,CR",BCQ,XPL,RRP,XBX and Y,""C,CR",BCQ,XPL,RRP,XBR 0i#ed precision and scale numbers. Allows numbers from :ABVCX [A to ABVCX \A. &he p parameter indicates the ma#imum total number of digits that can be stored 7both to the left and to the right of the decimal point8. p must be a value from A to CX. efault is AX. &he s parameter indicates the ma#imum number of digits stored to the right of the decimal point. s must be a value from B to p. efault value is B 0i#ed precision and scale numbers. P:AR bytes Allows numbers from :ABVCX [A to ABVCX \A. &he p parameter indicates the ma#imum total number of digits that can be stored 7both to the left and to the right of the decimal point8. p must be a value from A to CX. efault is AX. &he s parameter indicates the ma#imum number of digits stored to the right of the decimal point. s must be a value from B to p. efault value is B Monetary data from :"AL,RLX.CQLX to "AL,RLX.CQLR L bytes Monetary data from :Y"",CCR,"BC,QXP,LRR.PXBX to Y"",CCR,"BC,QXP,LRR.PXBR X bytes 0loating precision number data from :A.RY< [ CBX to A.RY< [ CBX. L or X bytes &he n parameter indicates whether the field should hold L or X bytes. float7"L8 holds a L: byte field and float7PC8 holds an X:byte field. efault value of n is PC. 0loating precision number data from :C.LB< [ CX to C.LB< [ CX Stora5e A byte " bytes L bytes X bytes P:AR bytes Des#ription Allows B, A, or 6'LL 0i#ed:length binary data. Ma#imum X,BBB bytes Mariable:length binary data. Ma#imum X,BBB bytes Mariable:length binary data. Ma#imum ")! Mariable:length binary data. Ma#imum ")! Stora5e Des#ription 0i#ed:length 'nicode data. Ma#imum L,BBB characters Mariable:length 'nicode data. Ma#imum L,BBB characters Mariable:length 'nicode data. Ma#imum PCQ,XRB,YA" characters Mariable:length 'nicode data. Ma#imum ")! of te#t data Stora5e

numeric7p,s8

smallmoney money float7n8

real Date types: Data type datetime datetime" smalldatetime date time datetimeoffset timestamp

L bytes

Des#ription 0rom Oanuary A, ARPC to ecember CA, YYYY with an accuracy of C.CC milliseconds 0rom Oanuary A, BBBA to ecember CA, YYYY with an accuracy of ABB nanoseconds 0rom Oanuary A, AYBB to Oune Q, "BRY with an accuracy of A minute Store a date only. 0rom Oanuary A, BBBA to ecember CA, YYYY Store a time only to an accuracy of ABB nanoseconds &he same as datetime" with the addition of a time 4one offset Stores a uni9ue number that gets updated every time a row gets created or modified. &he timestamp value is based upon an internal cloc1 and does not correspond to real time. <ach table may have only one timestamp variable

Stora5e X bytes Q:X bytes L bytes C bytes C:P bytes X:AB bytes

Ot,er data types: Data type Des#ription

s9lDvariant uni9ueidentifier #ml cursor table

Stores Stores Stores Stores Stores

up to X,BBB bytes of data of various data types, e#cept te#t, nte#t, and timestamp a globally uni9ue identifier 7)'% 8 ZML formatted data. Ma#imum ")! a reference to a cursor used for database operations a result:set for later processing

F .revious

6e#t -hapter G

SQL Fun#tions
F .revious
SQL has many built:in functions for performing calculations on data.

6e#t -hapter G

SQL Aggregate 0unctions


SQL aggregate functions return a single value, calculated from values in a column. 'seful aggregate functions:

AM)78 : $eturns the average value -O'6&78 : $eturns the number of rows 0%$S&78 : $eturns the first value LAS&78 : $eturns the last value MAZ78 : $eturns the largest value M%678 : $eturns the smallest value S'M78 : $eturns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value. 'seful scalar functions:

'-AS<78 : -onverts a field to upper case L-AS<78 : -onverts a field to lower case M% 78 : <#tract characters from a te#t field L<678 : $eturns the length of a te#t field $O'6 78 : $ounds a numeric field to the number of decimals specified 6O,78 : $eturns the current system date and time 0O$MA&78 : 0ormats how a field is to be displayed

Tip: &he aggregate functions and the scalar functions will be e#plained in details in the ne#t chapters.

F .revious

6e#t -hapter G

SQL A4)89 0unction

F .revious

6e#t -hapter G

&he AM)78 0unction


&he AM)78 function returns the average value of a numeric column.

SQL AM)78 Synta#


SELECT A8G# o!umn"name$ FROM ta%!e"name

SQL AM)78 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the average value of the @Order.rice@ fields. ,e use the following SQL statement:

SELECT A8G#Or,erPr' e$ AS Or,erA*era0e FROM Or,ers


&he result:set will loo1 li1e this:

OrderA1era5e YPB

6ow we want to find the customers that have an Order.rice value higher than the average Order.rice value. ,e use the following SQL statement:

SELECT Customer FROM Or,ers WHERE Or,erPr' e>#SELECT A8G#Or,erPr' e$ FROM Or,ers$
&he result:set will loo1 li1e this:

Customer ;ansen 6ilsen Oensen

F .revious

6e#t -hapter G

SQL COUNT89 0unction


F .revious
&he -O'6&78 function returns the number of rows that matches a specified criteria.

6e#t -hapter G

SQL -O'6&7columnDname8 Synta#


&he -O'6&7columnDname8 function returns the number of values 76'LL values will not be counted8 of the specified column:

SELECT COU&T# o!umn"name$ FROM ta%!e"name

SQL -O'6&7E8 Synta#


&he -O'6&7E8 function returns the number of records in a table:

SELECT COU&T#*$ FROM ta%!e"name

SQL -O'6&7 %S&%6-& columnDname8 Synta#


&he -O'6&7 %S&%6-& columnDname8 function returns the number of distinct values of the specified column:

SELECT COU&T#()ST)&CT

o!umn"name$ FROM ta%!e"name

Note: -O'6&7 %S&%6-&8 wor1s with O$A-L< and Microsoft SQL Server, but not with Microsoft Access.

SQL -O'6&7columnDname8 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to count the number of orders from @-ustomer 6ilsen@. ,e use the following SQL statement:

SELECT COU&T#Customer$ AS Customer&'!sen FROM Or,ers WHERE Customer+'&'!sen'


&he result of the SQL statement above will be ", because the customer 6ilsen has made " orders in total:

CustomerNi'sen "

SQL -O'6&7E8 <#ample


%f we omit the ,;<$< clause, li1e this:

SELECT COU&T#*$ AS &um%erOKOr,ers FROM Or,ers


&he result:set will loo1 li1e this:

Num7erO-Orders

which is the total number of rows in the table.

SQL -O'6&7 %S&%6-& columnDname8 <#ample


6ow we want to count the number of uni9ue customers in the @Orders@ table. ,e use the following SQL statement:

SELECT COU&T#()ST)&CT Customer$ AS &um%erOKCustomers FROM Or,ers


&he result:set will loo1 li1e this:

Num7erO-Customers C

which is the number of uni9ue customers 7;ansen, 6ilsen, and Oensen8 in the @Orders@ table.

F .revious

6e#t -hapter G

SQL FIRST89 0unction


F .revious 6e#t -hapter G

&he 0%$S&78 0unction


&he 0%$S&78 function returns the first value of the selected column.

SQL 0%$S&78 Synta#


SELECT F)RST# o!umn"name$ FROM ta%!e"name

SQL 0%$S&78 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the first value of the @Order.rice@ column. ,e use the following SQL statement:

SELECT F)RST#Or,erPr' e$ AS F'rstOr,erPr' e FROM Or,ers

Tip: ,or1around if 0%$S&78 function is not supported:

SELECT Or,erPr' e FROM Or,ers OR(ER 61 O"), L)M)T 2


&he result:set will loo1 li1e this:

FirstOrderPri#e ABBB

F .revious

6e#t -hapter G

SQL LAST89 0unction


F .revious 6e#t -hapter G

&he LAS&78 0unction


&he LAS&78 function returns the last value of the selected column.

SQL LAS&78 Synta#


SELECT LAST# o!umn"name$ FROM ta%!e"name

SQL LAS&78 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the last value of the @Order.rice@ column. ,e use the following SQL statement:

SELECT LAST#Or,erPr' e$ AS LastOr,erPr' e FROM Or,ers

Tip: ,or1around if LAS&78 function is not supported:

SELECT Or,erPr' e FROM Or,ers OR(ER 61 O"), (ESC L)M)T 2


&he result:set will loo1 li1e this:

LastOrderPri#e ABB

F .revious

6e#t -hapter G

SQL .A 89 0unction

F .revious

6e#t -hapter G

&he MAZ78 0unction


&he MAZ78 function returns the largest value of the selected column.

SQL MAZ78 Synta#


SELECT MAJ# o!umn"name$ FROM ta%!e"name

SQL MAZ78 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the largest value of the @Order.rice@ column. ,e use the following SQL statement:

SELECT MAJ#Or,erPr' e$ AS Lar0estOr,erPr' e FROM Or,ers


&he result:set will loo1 li1e this:

Lar5estOrderPri#e "BBB

F .revious

6e#t -hapter G

SQL .IN89 0unction


F .revious 6e#t -hapter G

&he M%678 0unction


&he M%678 function returns the smallest value of the selected column.

SQL M%678 Synta#


SELECT M)&# o!umn"name$ FROM ta%!e"name

SQL M%678 <#ample


,e have the following @Orders@ table: O_Id A " C L P OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB OrderPri#e ABBB AQBB RBB CBB "BBB Customer ;ansen 6ilsen ;ansen ;ansen Oensen

"BBX?AB?BL

ABB

6ilsen

6ow we want to find the smallest value of the @Order.rice@ column. ,e use the following SQL statement:

SELECT M)&#Or,erPr' e$ AS Sma!!estOr,erPr' e FROM Or,ers


&he result:set will loo1 li1e this:

Sma''estOrderPri#e ABB

F .revious

6e#t -hapter G

SQL SU.89 0unction


F .revious 6e#t -hapter G

&he S'M78 0unction


&he S'M78 function returns the total sum of a numeric column.

SQL S'M78 Synta#


SELECT SUM# o!umn"name$ FROM ta%!e"name

SQL S'M78 <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the sum of all @Order.rice@ fields@. ,e use the following SQL statement:

SELECT SUM#Or,erPr' e$ AS Or,erTota! FROM Or,ers


&he result:set will loo1 li1e this:

OrderTota' PRBB

F .revious

6e#t -hapter G

SQL )ROUP B% Statement


F .revious
Aggregate functions often need an added )$O'. !> statement.

6e#t -hapter G

&he )$O'. !> Statement


&he )$O'. !> statement is used in con3unction with the aggregate functions to group the result:set by one or more columns.

SQL )$O'. !> Synta#


SELECT o!umn"name, a00re0ate"Kun t'on# o!umn"name$ FROM ta%!e"name WHERE o!umn"name operator *a!ue GROUP 61 o!umn"name

SQL )$O'. !> <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find the total sum 7total order8 of each customer. ,e will have to use the )$O'. !> statement to group the customers. ,e use the following SQL statement:

SELECT Customer,SUM#Or,erPr' e$ FROM Or,ers GROUP 61 Customer


&he result:set will loo1 li1e this: Customer ;ansen 6ilsen Oensen 6ice= %snNt it5 :8 LetNs see what happens if we omit the )$O'. !> statement: SU.8OrderPri#e9 "BBB ARBB "BBB

SELECT Customer,SUM#Or,erPr' e$ FROM Or,ers


&he result:set will loo1 li1e this: Customer ;ansen 6ilsen ;ansen SU.8OrderPri#e9 PRBB PRBB PRBB

;ansen Oensen 6ilsen

PRBB PRBB PRBB

&he result:set above is not what we wanted. E6p'anation o- +,y t,e a7o1e SELECT statement #annot 7e used: &he S<L<-& statement above has two columns specified 7-ustomer and S'M7Order.rice8. &he @S'M7Order.rice8@ returns a single value 7that is the total sum of the @Order.rice@ column8, while @-ustomer@ returns Q values 7one value for each row in the @Orders@ table8. &his will therefore not give us the correct result. ;owever, you have seen that the )$O'. !> statement solves this problem.

)$O'. !> More &han One -olumn


,e can also use the )$O'. !> statement on more than one column, li1e this:

SELECT Customer,Or,er(ate,SUM#Or,erPr' e$ FROM Or,ers GROUP 61 Customer,Or,er(ate

F .revious

6e#t -hapter G

SQL "A4IN) -lause


F .revious 6e#t -hapter G

&he ;AM%6) -lause


&he ;AM%6) clause was added to SQL because the ,;<$< 1eyword could not be used with aggregate functions.

SQL ;AM%6) Synta#


SELECT o!umn"name, a00re0ate"Kun t'on# o!umn"name$ FROM ta%!e"name WHERE o!umn"name operator *a!ue GROUP 61 o!umn"name HA8)&G a00re0ate"Kun t'on# o!umn"name$ operator *a!ue

SQL ;AM%6) <#ample


,e have the following @Orders@ table: O_Id A " C L P Q OrderDate "BBX?AA?A" "BBX?AB?"C "BBX?BY?B" "BBX?BY?BC "BBX?BX?CB "BBX?AB?BL OrderPri#e ABBB AQBB RBB CBB "BBB ABB Customer ;ansen 6ilsen ;ansen ;ansen Oensen 6ilsen

6ow we want to find if any of the customers have a total order of less than "BBB. ,e use the following SQL statement:

SELECT Customer,SUM#Or,erPr' e$ FROM Or,ers GROUP 61 Customer HA8)&G SUM#Or,erPr' e$<9AAA

&he result:set will loo1 li1e this: Customer 6ilsen SU.8OrderPri#e9 ARBB

6ow we want to find if the customers @;ansen@ or @Oensen@ have a total order of more than APBB. ,e add an ordinary ,;<$< clause to the SQL statement:

SELECT Customer,SUM#Or,erPr' e$ FROM Or,ers WHERE Customer+'Hansen' OR Customer+'=ensen' GROUP 61 Customer HA8)&G SUM#Or,erPr' e$>25AA
&he result:set will loo1 li1e this: Customer ;ansen Oensen SU.8OrderPri#e9 "BBB "BBB

F .revious

6e#t -hapter G

SQL UCASE89 0unction


F .revious 6e#t -hapter G

&he '-AS<78 0unction


&he '-AS<78 function converts the value of a field to uppercase.

SQL '-AS<78 Synta#


SELECT UCASE# o!umn"name$ FROM ta%!e"name

Synta# for SQL Server


SELECT UPPER# o!umn"name$ FROM ta%!e"name

SQL '-AS<78 <#ample


,e have the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the content of the @Last6ame@ and @0irst6ame@ columns above, and convert the @Last6ame@ column to uppercase. ,e use the following S<L<-& statement:

SELECT UCASE#Last&ame$ as Last&ame,F'rst&ame FROM Persons


&he result:set will loo1 li1e this:

LastName ;A6S<6 SM<6 SO6 .<&&<$S<6

FirstName Ola &ove (ari

F .revious

6e#t -hapter G

SQL LCASE89 0unction


F .revious 6e#t -hapter G

&he L-AS<78 0unction


&he L-AS<78 function converts the value of a field to lowercase.

SQL L-AS<78 Synta#


SELECT LCASE# o!umn"name$ FROM ta%!e"name

Synta# for SQL Server


SELECT LOWER# o!umn"name$ FROM ta%!e"name

SQL L-AS<78 <#ample


,e have the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to select the content of the @Last6ame@ and @0irst6ame@ columns above, and convert the @Last6ame@ column to lowercase. ,e use the following S<L<-& statement:

SELECT LCASE#Last&ame$ as Last&ame,F'rst&ame FROM Persons


&he result:set will loo1 li1e this: LastName hansen svendson pettersen FirstName Ola &ove (ari

F .revious

6e#t -hapter G

SQL .ID89 0unction


F .revious 6e#t -hapter G

&he M% 78 0unction

&he M% 78 function is used to e#tract characters from a te#t field.

SQL M% 78 Synta#
SELECT M)(# o!umn"name,startD,!en0t-E$ FROM ta%!e"name
Parameter columnDname start length Des#ription $e9uired. &he field to e#tract characters from $e9uired. Specifies the starting position 7starts at A8 Optional. &he number of characters to return. %f omitted, the M% 78 function returns the rest of the te#t

SQL M% 78 <#ample
,e have the following @.ersons@ table: P_Id A " C LastName ;ansen Svendson .ettersen FirstName Ola &ove (ari Address &imoteivn AB !orgvn "C Storgt "B City Sandnes Sandnes Stavanger

6ow we want to e#tract the first four characters of the @-ity@ column above. ,e use the following S<L<-& statement:

SELECT M)(#C'ty,2,<$ as Sma!!C'ty FROM Persons


&he result:set will loo1 li1e this:

Sma''City Sand Sand Stav

F .revious

6e#t -hapter G

SQL LEN89 0unction


F .revious 6e#t -hapter G

&he L<678 0unction


&he L<678 function returns the length of the value in a te#t field.

SQL L<678 Synta#


SELECT LE&# o!umn"name$ FROM ta%!e"name

SQL L<678 <#ample


,e have the following @.ersons@ table: P_Id A LastName ;ansen FirstName Ola Address &imoteivn AB City Sandnes

" C

Svendson .ettersen

&ove (ari

!orgvn "C Storgt "B

Sandnes Stavanger

6ow we want to select the length of the values in the @Address@ column above. ,e use the following S<L<-& statement:

SELECT LE&#A,,ress$ as Len0t-OKA,,ress FROM Persons


&he result:set will loo1 li1e this:

Len5t,O-Address A" Y Y

F .revious

6e#t -hapter G

SQL ROUND89 0unction


F .revious 6e#t -hapter G

&he $O'6 78 0unction


&he $O'6 78 function is used to round a numeric field to the number of decimals specified.

SQL $O'6 78 Synta#


SELECT ROU&(# o!umn"name,,e 'ma!s$ FROM ta%!e"name
Parameter columnDname decimals Des#ription $e9uired. &he field to round. $e9uired. Specifies the number of decimals to be returned.

SQL $O'6 78 <#ample


,e have the following @.roducts@ table: Prod_Id A " C Produ#tName Oarlsberg Mascarpone )orgon4ola Unit ABBB g ABBB g ABBB g UnitPri#e AB.LP C".PQ AP.QR

6ow we want to display the product name and the price rounded to the nearest integer. ,e use the following S<L<-& statement:

SELECT Pro,u t&ame, ROU&(#Un'tPr' e,A$ as Un'tPr' e FROM Pro,u ts


&he result:set will loo1 li1e this: Produ#tName Oarlsberg Mascarpone )orgon4ola UnitPri#e AB CC AQ

F .revious

6e#t -hapter G

SQL NO!89 0unction


F .revious 6e#t -hapter G

&he 6O,78 0unction


&he 6O,78 function returns the current system date and time.

SQL 6O,78 Synta#


SELECT &OW#$ FROM ta%!e"name

SQL 6O,78 <#ample


,e have the following @.roducts@ table: Prod_Id A " C Produ#tName Oarlsberg Mascarpone )orgon4ola Unit ABBB g ABBB g ABBB g UnitPri#e AB.LP C".PQ AP.QR

6ow we want to display the products and prices per todayNs date. ,e use the following S<L<-& statement:

SELECT Pro,u t&ame, Un'tPr' e, &o/#$ as Per(ate FROM Pro,u ts


&he result:set will loo1 li1e this: Produ#tName Oarlsberg Mascarpone )orgon4ola UnitPri#e AB.LP C".PQ AP.QR PerDate AB?R?"BBX AA:"P:B" AM AB?R?"BBX AA:"P:B" AM AB?R?"BBX AA:"P:B" AM

F .revious

6e#t -hapter G

SQL FOR.AT89 0unction


F .revious 6e#t -hapter G

&he 0O$MA&78 0unction


&he 0O$MA&78 function is used to format how a field is to be displayed.

SQL 0O$MA&78 Synta#


SELECT FORMAT# o!umn"name,Kormat$ FROM ta%!e"name
Parameter Des#ription

columnDname format

$e9uired. &he field to be formatted. $e9uired. Specifies the format.

SQL 0O$MA&78 <#ample


,e have the following @.roducts@ table: Prod_Id A " C Produ#tName Oarlsberg Mascarpone )orgon4ola Unit ABBB g ABBB g ABBB g UnitPri#e AB.LP C".PQ AP.QR

6ow we want to display the products and prices per todayNs date 7with todayNs date displayed in the following format @>>>>:MM: @8. ,e use the following S<L<-& statement:

SELECT Pro,u t&ame, Un'tPr' e, FORMAT#&o/#$,'1111NMMN(('$ as Per(ate FROM Pro,u ts


&he result:set will loo1 li1e this: Produ#tName Oarlsberg Mascarpone )orgon4ola UnitPri#e AB.LP C".PQ AP.QR PerDate "BBX:AB:BR "BBX:AB:BR "BBX:AB:BR

F .revious

6e#t -hapter G

>ou ;ave Learned SQL, No+ !,at:


F .revious 6e#t -hapter G

SQL Summary
&his SQL tutorial has taught you the standard computer language for accessing and manipulating database systems. >ou have learned how to e#ecute 9ueries, retrieve data, insert new records, delete records and update records in a database with SQL. >ou have also learned how to create databases, tables, and inde#es with SQL, and how to drop them. >ou have learned the most important aggregate functions in SQL. >ou now 1now that SQL is the standard language that wor1s with all the well:1nown database systems li1e MS SQL Server, %!M !", Oracle, MySQL, and MS Access.

6ow >ou (now SQL, ,hatNs 6e#t5


Our recommendation is to learn about A O or .;. MySQL. %f you want to learn more about A O, please visit our A O tutorial. %f you want to learn more about MySQL, please visit our .;. tutorial.

F .revious

6e#t -hapter G