Professional Documents
Culture Documents
SQL Tutorial
SQL is a standard computer language for accessing and manipulating databases. In this tutorial you will learn how to use SQL to access and manipulate data in Oracle, Sybase, SQL Server, D !, "ccess, and other database systems.
Introduction to SQL
SQL is a standard computer language for accessing and manipulating databases.
#hat is SQL$
SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn
SQL is a Standard %
&T....
SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems SQL statements are used to retrieve and update data in a database SQL wor!s wit" database programs li!e #S Access$ %&'$ Informix$ #S SQL Server$ (racle$ Sybase$ etc )nfortunately$ t"ere are many different versions of t"e SQL language$ but to be in compliance wit" t"e ANSI standard$ t"ey must support t"e same ma*or !eywords in a similar manner (suc" as S+L+,-$ ).%A-+$ %+L+-+$ INS+/-$ 01+/+$ and ot"ers) 'ote( #ost of t"e SQL database programs also "ave t"eir own proprietary extensions in addition to t"e SQL standard2
-"e table above contains t"ree records (one for eac" person) and four columns (LastName$ 9irstName$ Address$ and ,ity)
SQL Queries
0it" SQL$ we can query a database and "ave a result set returned A query li!e t"is4
SQL Data +anipulation Language ,D+LSQL (Structured Query Language) is a syntax for executing queries &ut t"e SQL language also includes a syntax to update$ insert$ and delete records -"ese query and update commands toget"er form t"e %ata #anipulation Language (%#L) part of SQL4
S.L.*T < extracts data from a database table &/D"T. < updates data in a database table D.L.T. < deletes data from a database table I'S.0T I'TO < inserts new data into a database table
SQL Data Definition Language ,DDL-"e %ata %efinition Language (%%L) part of SQL permits database tables to be created or deleted 0e can also define indexes (!eys)$ specify lin!s between tables$ and impose constraints between database tables -"e most important %%L statements in SQL are4
*0."T. T" L. < creates a new database table "LT.0 T" L. < alters (c"anges) a database table
D0O/ T" L. < deletes a database table *0."T. I'D.1 < creates an index (searc" !ey) D0O/ I'D.1 < deletes an index
Introduction to SQL
SQL is a standard computer language for accessing and manipulating databases.
#hat is SQL$
SQL stands for Structured Query Language SQL allows you to access a database SQL is an ANSI standard computer language SQL can execute queries against a database SQL can retrieve data from a database SQL can insert new records in a database SQL can delete records from a database SQL can update records in a database SQL is easy to learn
SQL is a Standard %
&T....
SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems SQL statements are used to retrieve and update data in a database SQL wor!s wit" database programs li!e #S Access$ %&'$ Informix$ #S SQL Server$ (racle$ Sybase$ etc )nfortunately$ t"ere are many different versions of t"e SQL language$ but to be in compliance wit" t"e ANSI standard$ t"ey must support t"e same ma*or !eywords in a similar manner (suc" as S+L+,-$ ).%A-+$ %+L+-+$ INS+/-$ 01+/+$ and ot"ers) 'ote( #ost of t"e SQL database programs also "ave t"eir own proprietary extensions in addition to t"e SQL standard2
-"e table above contains t"ree records (one for eac" person) and four columns (LastName$ 9irstName$ Address$ and ,ity)
SQL Queries
0it" SQL$ we can query a database and "ave a result set returned A query li!e t"is4
SQL Data +anipulation Language ,D+LSQL (Structured Query Language) is a syntax for executing queries &ut t"e SQL language also includes a syntax to update$ insert$ and delete records -"ese query and update commands toget"er form t"e %ata #anipulation Language (%#L) part of SQL4
S.L.*T < extracts data from a database table &/D"T. < updates data in a database table D.L.T. < deletes data from a database table I'S.0T I'TO < inserts new data into a database table
SQL Data Definition Language ,DDL-"e %ata %efinition Language (%%L) part of SQL permits database tables to be created or deleted 0e can also define indexes (!eys)$ specify lin!s between tables$ and impose constraints between database tables -"e most important %%L statements in SQL are4
*0."T. T" L. < creates a new database table "LT.0 T" L. < alters (c"anges) a database table D0O/ T" L. < deletes a database table *0."T. I'D.1 < creates an index (searc" !ey) D0O/ I'D.1 < deletes an index
&sing Quotes
Note t"at we "ave used single quotes around t"e conditional values in t"e examples SQL uses single quotes around text values (most database systems will also accept double quotes) Numeric values s"ould not be enclosed in quotes 9or text values4
T#is is correct$ SELECT * FROM Persons WHERE FirstName !Tove! T#is is %ron&$ SELECT * FROM Persons WHERE FirstName Tove
9or numeric values4
T#is is correct$ SELECT * FROM Persons WHERE 'ear()*+, T#is is %ron&$ SELECT * FROM Persons WHERE 'ear(!)*+,!
&sing LI6.
-"e following SQL statement will return persons wit" first names t"at start wit" an ;(;4
/erson( Last'ame Nilsen /asmussen )irst'ame 9red "ddress 8ir!egt AD Storgt DB *ity Stavanger
!Nina!
*ity Stavanger
3P<2TE Person
!Stavan&er!
/erson( Last'ame Nilsen /asmussen )irst'ame 9red Nina "ddress 8ir!egt AD Stien 5' *ity Stavanger Stavanger
Delete a 0ow
3Nina /asmussen3 is going to be deleted4
!Rasmussen!
"ddress 8ir!egt AD
*ity Stavanger
SQL O0D.0
The O0D.0
.3ample
-o display t"e companies in alp"abetical order4
.3ample
-o display t"e companies in alp"abetical order AN% t"e ordernumbers in numerical order4
.3ample
-o display t"e companies in reverse alp"abetical order4
.3ample
-o display t"e companies in reverse alp"abetical order AN% t"e ordernumbers in numerical order4
SELECT Company5 Or"erNumber FROM Or"ers OR<ER =' Company <ESC5 Or"erNumber 2SC
0esult( *ompany 07Sc"ools 07Sc"ools Sega A&, S"op Order'umber '75' DB@C 7G5' ADBC
SQL "'D 8 O0
"'D 8 O0
AN% and (/ *oin two or more conditions in a 01+/+ clause -"e AN% operator displays a row if ALL conditions listed are true -"e (/ operator displays a row if ANF of t"e conditions listed are true
Original Table ,used in the e3amplesLast'ame 1ansen Svendson )irst'ame (la -ove "ddress -imoteivn 56 &orgvn '7 *ity Sandnes Sandnes
Svendson
Step"en
8aivn 5C
Sandnes
.3ample
)se AN% to display eac" person wit" t"e first name equal to 3-ove3$ and t"e last name equal to 3Svendson34
.3ample
)se (/ to display eac" person wit" t"e first name equal to 3-ove3$ or t"e last name equal to 3Svendson34
.3ample
Fou can also combine AN% and (/ (use parent"eses to form complex expressions)4
SELECT * FROM Persons WHERE 4FirstName !Tove! OR FirstName !Step#en!8 2N< LastName !Sven"son!
0esult( Last'ame Svendson Svendson )irst'ame -ove Step"en "ddress &orgvn '7 8aivn 5C *ity Sandnes Sandnes
SQL I'
I'
-"e IN operator may be used if you !now t"e exact value you want to return for at least one of t"e columns
Original Table ,used in the e3amplesLast'ame 1ansen Nordmann .ettersen Svendson )irst'ame (la Anna 8ari -ove "ddress -imoteivn 56 Neset 5C Storgt '6 &orgvn '7 *ity Sandnes Sandnes Stavanger Sandnes
.3ample 9
-o display t"e persons wit" LastName equal to 31ansen3 or 3.ettersen3$ use t"e following SQL4
SQL
.T#..'
SELECT column0name FROM table0name WHERE column0name =ETWEEN value) 2N< value6
Original Table ,used in the e3amplesLast'ame 1ansen Nordmann .ettersen Svendson )irst'ame (la Anna 8ari -ove "ddress -imoteivn 56 Neset 5C Storgt '6 &orgvn '7 *ity Sandnes Sandnes Stavanger Sandnes
SQL "lias
#ith SQL, aliases can be used for column names and table names.
SQL :OI'
:oins and 6eys
Sometimes we "ave to select data from two or more tables to ma!e our result complete 0e "ave to perform a *oin -ables in a database can be related to eac" ot"er wit" !eys A primary !ey is a column wit" a unique value for eac" row +ac" primary !ey value must be unique wit"in t"e table -"e purpose is to bind data toget"er$ across tables$ wit"out repeating all of t"e data in every table In t"e 3+mployees3 table below$ t"e 3+mployeeHI%3 column is t"e primary !ey$ meaning t"at no two rows can "ave t"e same +mployeeHI% -"e +mployeeHI% distinguis"es two persons even if t"ey "ave t"e same name 0"en you loo! at t"e example tables below$ notice t"at4
-"e 3+mployeeHI%3 column is t"e primary !ey of t"e 3+mployees3 table -"e 3.rodHI%3 column is t"e primary !ey of t"e 3(rders3 table -"e 3+mployeeHI%3 column in t"e 3(rders3 table is used to refer to t"e persons in t"e 3+mployees3 table wit"out using t"eir names
.mployees4 .mployee;ID 65 6' 67 'ame 1ansen$ (la Svendson$ -ove Svendson$ Step"en
.ettersen$ 8ari
.mployee;ID 65 67 67
.3ample
0"o "as ordered a product$ and w"at did t"ey orderI
.3ample
0"o ordered a printerI
SELECT Employees7Name FROM Employees5 Or"ers WHERE Employees7Employee0-< Or"ers7Employee0-< 2N< Or"ers7Pro"uct !Printer!
0esult 'ame 1ansen$ (la
&sing :oins
(/ we can select data from two tables wit" t"e J(IN !eyword$ li!e t"is4
SELECT >iel")5 >iel"65 >iel"? FROM >irst0table -NNER @O-N secon"0table ON >irst0table79ey>iel" secon"0table7>orei&n09ey>iel"
0"o "as ordered a product$ and w"at did t"ey orderI
SELECT Employees7Name5 Or"ers7Pro"uct FROM Employees -NNER @O-N Or"ers ON Employees7Employee0-< Or"ers7Employee0-<
-"e INN+/ J(IN returns all rows from bot" tables w"ere t"ere is a matc" If t"ere are rows in +mployees t"at do not "ave matc"es in (rders$ t"ose rows will not be listed 0esult 'ame 1ansen$ (la Svendson$ Step"en Svendson$ Step"en /roduct .rinter -able ,"air
SELECT >iel")5 >iel"65 >iel"? FROM >irst0table LEFT @O-N secon"0table ON >irst0table79ey>iel" secon"0table7>orei&n09ey>iel"
List all employees$ and t"eir orders < if any
SELECT Employees7Name5 Or"ers7Pro"uct FROM Employees LEFT @O-N Or"ers ON Employees7Employee0-< Or"ers7Employee0-<
-"e L+9- J(IN returns all t"e rows from t"e first table (+mployees)$ even if t"ere are no matc"es in t"e second table ((rders) If t"ere are rows in +mployees t"at do not "ave matc"es in (rders$ t"ose rows also will be listed 0esult 'ame 1ansen$ (la Svendson$ -ove Svendson$ Step"en Svendson$ Step"en .ettersen$ 8ari -able ,"air /roduct .rinter
SELECT >iel")5 >iel"65 >iel"? FROM >irst0table R-AHT @O-N secon"0table ON >irst0table79ey>iel" secon"0table7>orei&n09ey>iel"
List all orders$ and w"o "as ordered < if any
SELECT Employees7Name5 Or"ers7Pro"uct FROM Employees R-AHT @O-N Or"ers ON Employees7Employee0-< Or"ers7Employee0-<
-"e /I:1- J(IN returns all t"e rows from t"e second table ((rders)$ even if t"ere are no matc"es in t"e first table (+mployees) If t"ere "ad been any rows in (rders t"at did not "ave matc"es in +mployees$ t"ose rows also would "ave been listed 0esult 'ame 1ansen$ (la Svendson$ Step"en Svendson$ Step"en /roduct .rinter -able ,"air
.3ample
0"o ordered a printerI
SELECT Employees7Name FROM Employees -NNER @O-N Or"ers ON Employees7Employee0-< Or"ers7Employee0-< WHERE Or"ers7Pro"uct !Printer!
0esult 'ame 1ansen$ (la
-"e )NI(N command is used to select related information from two tables$ muc" li!e t"e J(IN command 1owever$ w"en using t"e )NI(N command all selected columns need to be of t"e same data type 'ote( 0it" )NI(N$ only distinct values are selected
.mployees;'orway4 .;ID 65 6' 67 6G .mployees;&S"4 .;ID 65 6' 67 6G .;'ame -urner$ Sally 8ent$ ,lar! Svendson$ Step"en Scott$ Step"en .;'ame 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari
'ote( -"is command cannot be used to list all employees in Norway and )SA In t"e example above we "ave two employees wit" equal names$ and only one of t"em is listed -"e )NI(N command only selects distinct values
&'IO' "LL
-"e )NI(N ALL command is equal to t"e )NI(N command$ except t"at )NI(N ALL selects all values
SELECT E0Name FROM Employees0Nor%ay 3N-ON 2LL SELECT E0Name FROM Employees03S2
0esult .;'ame 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari -urner$ Sally 8ent$ ,lar! Svendson$ Step"en Scott$ Step"en
*reate a Table
-o create a table in a database4
CRE2TE T2=LE Person 4 LastName varc#ar5 FirstName varc#ar5 2""ress varc#ar5 2&e int 8
-"is example demonstrates "ow you can specify a maximum lengt" for some columns4
CRE2TE T2=LE Person 4 LastName varc#ar4?C85 FirstName varc#ar5 2""ress varc#ar5 2&e int4?8 8
-"e data type specifies w"at type of data t"e column can "old -"e table below contains t"e most common data types in SQL4 Data Type integer(siKe) int(siKe) smallint(siKe) tinyint(siKe) decimal(siKe$d) numeric(siKe$d) c"ar(siKe) varc"ar(siKe) date(yyyymmdd) Description 1old integers only -"e maximum number of digits are specified in parent"esis
1old numbers wit" fractions -"e maximum number of digits are specified in 3siKe3 -"e maximum number of digits to t"e rig"t of t"e decimal is specified in 3d3 1olds a fixed lengt" string (can contain letters$ numbers$ and special c"aracters) -"e fixed siKe is specified in parent"esis 1olds a variable lengt" string (can contain letters$ numbers$ and special c"aracters) -"e maximum siKe is specified in parent"esis 1olds a date
*reate Inde3
Indices are created in an existing table to locate rows more quic!ly and efficiently It is possible to create an index on one or more columns of a table$ and eac" index is given a name -"e users cannot see t"e indexes$ t"ey are *ust used to speed up queries
'ote( )pdating a table containing indexes ta!es more time t"an updating a table wit"out$ t"is is because t"e indexes also need an update So$ it is a good idea to create indexes only on columns t"at are often used for a searc" " &ni=ue Inde3 ,reates a unique index on a table A unique index means t"at two rows cannot "ave t"e same index value
.3ample
-"is example creates a simple index$ named 3.ersonIndex3$ on t"e LastName field of t"e .erson table4
Fou can delete an existing index in a table wit" t"e %/(. IN%+L statement Syntax for #icrosoft SQLJet (and #icrosoft Access)4
Truncate a Table
0"at if we only want to get rid of t"e data inside a table$ and not t"e table itselfI )se t"e -/)N,A-+ -A&L+ command (deletes only t"e data inside t"e table)4
2LTER T2=LE table0name 2<< column0name "atatype 2LTER T2=LE table0name <ROP COL3MN column0name
'ote( Some database systems don;t allow t"e dropping of a column in a database table (%/(. ,(L)#N columnHname)
.3ample
-o add a column named 3,ity3 in t"e 3.erson3 table4
.3ample
-o drop t"e 3Address3 column in t"e 3.erson3 table4
SQL )unctions
SQL has a lot of built%in functions for counting and calculations.
)unction Synta3
-"e syntax for built<in SQL functions is4
Types of )unctions
-"ere are several basic types and categories of functions in SQL -"e basic types of functions are4
Aggregate 9unctions
Scalar functions
"ggregate functions
Aggregate functions operate against a collection of values$ but return a single value 'ote( If used among many ot"er expressions in t"e item list of a S+L+,- statement$ t"e S+L+,must "ave a :/(). &F clause22
4/ersons4 table ,used in most e3amples'ame 1ansen$ (la Svendson$ -ove .ettersen$ 8ari "ge 7G GA 5@
Scalar functions
Scalar functions operate against a single value$ and return a single value based on t"e input value
SQL <0O&/
5 and 2">I'<
5 functionality.
<0O&/
5...
:/(). &F was added to SQL because aggregate functions (li!e S)#) return t"e aggregate of all column values every time t"ey are called$ and wit"out t"e :/(). &F function it was impossible to find t"e sum for eac" individual group of column values -"e syntax for t"e :/(). &F function is4
<0O&/
5 .3ample
GA66 B566
-"e above code is invalid because t"e column returned is not part of an aggregate A :/(). &F clause will solve t"is problem4
2">I'<...
1AMIN: was added to SQL because t"e 01+/+ !eyword could not be used against aggregate functions (li!e S)#)$ and wit"out 1AMIN: it would be impossible to test for result conditions -"e syntax for t"e 1AMIN: function is4
SELECT column5S3M4column8 FROM table ARO3P =' column H21-NA S3M4column8 con"ition value
-"is 3Sales3 -able4 *ompany 07Sc"ools I&# 07Sc"ools -"is SQL4 "mount AA66 GA66 B566
+a7e a
ac7up *opy
#hat is a >iew$
In SQL$ a MI+0 is a virtual table based on t"e result<set of a S+L+,- statement A view contains rows and columns$ *ust li!e a real table -"e fields in a view are fields from one or more real tables in t"e database Fou can add SQL functions$ 01+/+$ and J(IN statements to a view and present t"e data as if t"e data were coming from a single table 'ote( -"e database design and structure will N(- be affected by t"e functions$ w"ere$ or *oin statements in a view
Synta3 CRE2TE 1-EW vie%0name 2S SELECT column0name4s8 FROM table0name WHERE con"ition
'ote( -"e database does not store t"e view data2 -"e database engine recreates t"e data$ using t"e view;s S+L+,- statement$ every time a user queries a view
&sing >iews
A view could be used from inside a query$ a stored procedure$ or from inside anot"er view &y adding functions$ *oins$ etc $ to a view$ it allows you to present exactly t"e data you want to t"e user -"e sample database Nort"wind "as some views installed by default -"e view 3,urrent .roduct List3 lists all active products (products t"at are not discontinued) from t"e .roducts table -"e view is created wit" t"e following SQL4
CRE2TE 1-EW FCurrent Pro"uct ListG 2S SELECT Pro"uct-<5Pro"uctName FROM Pro"ucts WHERE <iscontinue" No
0e can query t"e view above as follows4
Anot"er view from t"e Nort"wind sample database selects every product in t"e .roducts table t"at "as a unit price t"at is "ig"er t"an t"e average unit price4
CRE2TE 1-EW FPro"ucts 2bove 2vera&e PriceG 2S SELECT Pro"uctName53nitPrice FROM Pro"ucts WHERE 3nitPrice(4SELECT 21A43nitPrice8 FROM Pro"ucts8
0e can query t"e view above as follows4
CRE2TE 1-EW FCate&ory Sales For )**;G 2S SELECT <-ST-NCT Cate&oryName5Sum4Pro"uctSales8 2S Cate&orySales FROM FPro"uct Sales >or )**;G ARO3P =' Cate&oryName
0e can query t"e view above as follows4
SQL Servers % 0D +S
+odern SQL Servers are built on 0D +S.
/%&#S was invented by I&# in t"e early 5@B6;s /%&#S is t"e basis for SQL$ and for all modern database systems li!e (racle$ SQL Server$ I&# %&'$ Sybase$ #ySQL$ and #icrosoft Access