You are on page 1of 31

SQL Tutorial

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

SQL Database Tables


A database most often contains one or more tables +ac" table is identified by a name (e g 3,ustomers3 or 3(rders3) -ables contain records (rows) wit" data &elow is an example of a table called 3.ersons34

Last'ame 1ansen Svendson .ettersen

)irst'ame (la -ove 8ari

"ddress -imoteivn 56 &orgvn '7 Storgt '6

*ity Sandnes Sandnes Stavanger

-"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

SELECT LastName FROM Persons


:ives a result set li!e t"is4 Last'ame 1ansen Svendson .ettersen 'ote4 Some database systems require a semicolon at t"e end of t"e SQL statement 0e don;t use t"e semicolon in our tutorials

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

SQL Database Tables


A database most often contains one or more tables +ac" table is identified by a name (e g 3,ustomers3 or 3(rders3) -ables contain records (rows) wit" data &elow is an example of a table called 3.ersons34 Last'ame 1ansen Svendson .ettersen )irst'ame (la -ove 8ari "ddress -imoteivn 56 &orgvn '7 Storgt '6 *ity Sandnes Sandnes Stavanger

-"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

SELECT LastName FROM Persons


:ives a result set li!e t"is4 Last'ame 1ansen Svendson .ettersen 'ote4 Some database systems require a semicolon at t"e end of t"e SQL statement 0e don;t use t"e semicolon in our tutorials

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

SQL #2.0. *lause

The #2.0. clause is used to specify a selection criterion.

The #2.0. *lause


-o conditionally select data from a table$ a 01+/+ clause can be added to t"e S+L+,- statement

Synta3 SELECT column FROM table WHERE column operator value


0it" t"e 01+/+ clause$ t"e following operators can be used4 Operator = >? ? > ?= >= &+-0++N LI8+ Description +qual Not equal :reater t"an Less t"an :reater t"an or equal Less t"an or equal &etween an inclusive range Searc" for a pattern

'ote( In some versions of SQL t"e >? operator may be written as 2=

&sing the #2.0. *lause


-o select only t"e persons living in t"e city 3Sandnes3$ we add a 01+/+ clause to t"e S+L+,statement4

SELECT * FROM Persons WHERE City !San"nes!


4/ersons4 table Last'ame 1ansen Svendson Svendson .ettersen 0esult Last'ame 1ansen Svendson Svendson )irst'ame (la -ove Stale "ddress -imoteivn 56 &orgvn '7 8aivn 5C *ity Sandnes Sandnes Sandnes 5ear 5@A5 5@BC 5@C6 )irst'ame (la -ove Stale 8ari "ddress -imoteivn 56 &orgvn '7 8aivn 5C Storgt '6 *ity Sandnes Sandnes Sandnes Stavanger 5ear 5@A5 5@BC 5@C6 5@D6

&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(!)*+,!

The LI6. *ondition


-"e LI8+ condition is used to specify a searc" for a pattern in a column

Synta3 SELECT column FROM table WHERE column L-.E pattern


A 3E3 sign can be used to define wildcards (missing letters in t"e pattern) bot" before and after t"e pattern

&sing LI6.
-"e following SQL statement will return persons wit" first names t"at start wit" an ;(;4

SELECT * FROM Persons WHERE FirstName L-.E !O/!


-"e following SQL statement will return persons wit" first names t"at end wit" an ;a;4

SELECT * FROM Persons WHERE FirstName L-.E !/a!


-"e following SQL statement will return persons wit" first names t"at contain t"e pattern ;la;4

SELECT * FROM Persons WHERE FirstName L-.E !/la/!

SQL I'S.0T I'TO Statement


The I'S.0T I'TO Statement
-"e INS+/- IN-( statement is used to insert new rows into a table

Synta3 -NSERT -NTO table0name 12L3ES 4value)5 value6577778


Fou can also specify t"e columns for w"ic" you want to insert data4

-NSERT -NTO table0name 4column)5 column657778 12L3ES 4value)5 value6577778

Insert a 'ew 0ow


-"is 3.ersons3 table4 Last'ame .ettersen And t"is SQL statement4 )irst'ame 8ari "ddress Storgt '6 *ity Stavanger

-NSERT -NTO Persons 12L3ES 4!Hetlan"!5 !Camilla!5 !Ha&aba99a 6:!5 !San"nes!8


0ill give t"is result4 Last'ame .ettersen 1etland )irst'ame 8ari ,amilla "ddress Storgt '6 1agaba!!a 'G *ity Stavanger Sandnes

Insert Data in Specified *olumns


-"is 3.ersons3 table4 Last'ame .ettersen 1etland )irst'ame 8ari ,amilla "ddress Storgt '6 1agaba!!a 'G *ity Stavanger Sandnes

And -"is SQL statement4

-NSERT -NTO Persons 4LastName5 2""ress8

12L3ES 4!Rasmussen!5 !Stor&t +;!8


0ill give t"is result4 Last'ame .ettersen 1etland /asmussen )irst'ame 8ari ,amilla "ddress Storgt '6 1agaba!!a 'G Storgt DB *ity Stavanger Sandnes

SQL &/D"T. Statement


The &pdate Statement
-"e ).%A-+ statement is used to modify t"e data in a table

Synta3 3P<2TE table0name SET column0name ne%0value WHERE column0name some0value

/erson( Last'ame Nilsen /asmussen )irst'ame 9red "ddress 8ir!egt AD Storgt DB *ity Stavanger

&pdate one *olumn in a 0ow


0e want to add a first name to t"e person wit" a last name of 3/asmussen34

3P<2TE Person SET FirstName WHERE LastName !Rasmussen!


0esult( Last'ame Nilsen /asmussen )irst'ame 9red Nina

!Nina!

"ddress 8ir!egt AD Storgt DB

*ity Stavanger

&pdate several *olumns in a 0ow


0e want to c"ange t"e address and add t"e name of t"e city4

3P<2TE Person

SET 2""ress !Stien )6!5 City WHERE LastName !Rasmussen!


0esult( Last'ame Nilsen /asmussen )irst'ame 9red Nina

!Stavan&er!

"ddress 8ir!egt AD Stien 5'

*ity Stavanger Stavanger

SQL D.L.T. Statement


The D.L.T. Statement
-"e %+L+-+ statement is used to delete rows in a table

Synta3 <ELETE FROM table0name WHERE column0name some0value

/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

<ELETE FROM Person WHERE LastName


0esult Last'ame Nilsen )irst'ame 9red

!Rasmussen!

"ddress 8ir!egt AD

*ity Stavanger

Delete "ll 0ows


It is possible to delete all rows in a table wit"out deleting t"e table -"is means t"at t"e table structure$ attributes$ and indexes will be intact4

<ELETE FROM table0name or

<ELETE * FROM table0name

SQL O0D.0
The O0D.0

5 7eyword is used to sort the result.

Sort the 0ows


-"e (/%+/ &F clause is used to sort t"e rows Orders( *ompany Sega A&, S"op 07Sc"ools 07Sc"ools Order'umber 7G5' ADBC '75' DB@C

.3ample
-o display t"e companies in alp"abetical order4

SELECT Company5 Or"erNumber FROM Or"ers OR<ER =' Company


0esult( *ompany A&, S"op Sega 07Sc"ools 07Sc"ools Order'umber ADBC 7G5' DB@C '75'

.3ample
-o display t"e companies in alp"abetical order AN% t"e ordernumbers in numerical order4

SELECT Company5 Or"erNumber FROM Or"ers OR<ER =' Company5 Or"erNumber


0esult( *ompany A&, S"op Sega 07Sc"ools 07Sc"ools Order'umber ADBC 7G5' '75' DB@C

.3ample
-o display t"e companies in reverse alp"abetical order4

SELECT Company5 Or"erNumber FROM Or"ers OR<ER =' Company <ESC


0esult( *ompany 07Sc"ools 07Sc"ools Sega A&, S"op Order'umber DB@C '75' 7G5' ADBC

.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

SELECT * FROM Persons WHERE FirstName !Tove! 2N< LastName !Sven"son!


0esult( Last'ame Svendson )irst'ame -ove "ddress &orgvn '7 *ity Sandnes

.3ample
)se (/ to display eac" person wit" t"e first name equal to 3-ove3$ or t"e last name equal to 3Svendson34

SELECT * FROM Persons WHERE >irstname !Tove! OR lastname !Sven"son!


0esult( Last'ame Svendson Svendson )irst'ame -ove Step"en "ddress &orgvn '7 8aivn 5C *ity Sandnes Sandnes

.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

SELECT column0name FROM table0name WHERE column0name -N 4value),value65778

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

SELECT * FROM Persons WHERE LastName -N 4!Hansen!5!Pettersen!8


0esult( Last'ame 1ansen .ettersen )irst'ame (la 8ari "ddress -imoteivn 56 Storgt '6 *ity Sandnes Stavanger

SQL

.T#..'

.T#..' ... "'D


-"e &+-0++N AN% operator selects a range of data between two values -"ese values can be numbers$ text$ or dates

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.

*olumn 'ame "lias


-"e syntax is4

SELECT column 2S column0alias FROM table

Table 'ame "lias


-"e syntax is4

SELECT column FROM table 2S table0alias

.3ample( &sing a *olumn "lias


-"is table (.ersons)4 Last'ame 1ansen Svendson .ettersen And t"is SQL4 )irst'ame (la -ove 8ari "ddress -imoteivn 56 &orgvn '7 Storgt '6 *ity Sandnes Sandnes Stavanger

SELECT LastName 2S Family5 FirstName 2S Name FROM Persons


/eturns t"is result4 )amily 1ansen Svendson .ettersen 'ame (la -ove 8ari

.3ample( &sing a Table "lias


-"is table (.ersons)4 Last'ame )irst'ame "ddress *ity

1ansen Svendson .ettersen And t"is SQL4

(la -ove 8ari

-imoteivn 56 &orgvn '7 Storgt '6

Sandnes Sandnes Stavanger

SELECT LastName5 FirstName FROM Persons 2S Employees


/eturns t"is result4 -able +mployees4 Last'ame 1ansen Svendson .ettersen )irst'ame (la -ove 8ari

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

6G Orders( /rod;ID '7G DAB CDA /roduct .rinter -able ,"air

.ettersen$ 8ari

.mployee;ID 65 67 67

0eferring to Two Tables


0e can select data from two tables by referring to two tables$ li!e t"is4

.3ample
0"o "as ordered a product$ and w"at did t"ey orderI

SELECT Employees7Name5 Or"ers7Pro"uct FROM Employees5 Or"ers WHERE Employees7Employee0-< Or"ers7Employee0-<


0esult 'ame 1ansen$ (la Svendson$ Step"en Svendson$ Step"en /roduct .rinter -able ,"air

.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

.3ample I''.0 :OI'


Synta3

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

.3ample L.)T :OI'


Synta3

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

.3ample 0I<2T :OI'


Synta3

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

SQL &'IO' and &'IO' "LL


&'IO'

-"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

SBL Statement ) 3N-ON SBL Statement 6

.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

&sing the &'IO' *ommand


.3ample
List all different employee names in Norway and )SA4

SELECT E0Name FROM Employees0Nor%ay 3N-ON SELECT E0Name FROM Employees03S2


0esult .;'ame 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari -urner$ Sally 8ent$ ,lar! Scott$ Step"en

'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

SBL Statement ) 3N-ON 2LL SBL Statement 6

&sing the &'IO' "LL *ommand


.3ample
List all employees in Norway and )SA4

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

SQL *reate Database, Table, and Inde3


*reate a Database
-o create a database4

CRE2TE <2T2=2SE "atabase0name

*reate a Table
-o create a table in a database4

CRE2TE T2=LE table0name 4 column0name) "ata0type5 column0name6 "ata0type5 ....... 8 .3ample


-"is example demonstrates "ow you can create a table named 3.erson3$ wit" four columns -"e column names will be 3LastName3$ 39irstName3$ 3Address3$ and 3Age34

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

CRE2TE 3N-B3E -N<ED in"eE0name ON table0name 4column0name8


-"e 3columnHname3 specifies t"e column you want indexed " Simple Inde3 ,reates a simple index on a table 0"en t"e )NIQ)+ !eyword is omitted$ duplicate values are allowed

CRE2TE -N<ED in"eE0name ON table0name 4column0name8


-"e 3columnHname3 specifies t"e column you want indexed

.3ample
-"is example creates a simple index$ named 3.ersonIndex3$ on t"e LastName field of t"e .erson table4

CRE2TE -N<ED Person-n"eE ON Person 4LastName8


If you want to index t"e values in a column in descending order$ you can add t"e reserved word D.S* after t"e column name4

CRE2TE -N<ED Person-n"eE ON Person 4LastName <ESC8


If you want to index more t"an one column you can list t"e column names wit"in t"e parent"eses$ separated by commas4

CRE2TE -N<ED Person-n"eE ON Person 4LastName5 FirstName8

SQL Drop Inde3, Table and Database


Drop Inde3

Fou can delete an existing index in a table wit" t"e %/(. IN%+L statement Syntax for #icrosoft SQLJet (and #icrosoft Access)4

<ROP -N<ED in"eE0name ON table0name


Syntax for #S SQL Server4

<ROP -N<ED table0name7in"eE0name


Syntax for I&# %&' and (racle4

<ROP -N<ED in"eE0name


Syntax for #ySQL4

2LTER T2=LE table0name <ROP -N<ED in"eE0name

Delete a Table or Database


-o delete a table (t"e table structure$ attributes$ and indexes will also be deleted)4

<ROP T2=LE table0name


-o delete a database4

<ROP <2T2=2SE "atabase0name

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

TR3NC2TE T2=LE table0name

SQL "LT.0 T" L.


"LT.0 T" L.
-"e AL-+/ -A&L+ statement is used to add or drop columns in an existing table

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)

/erson( Last'ame .ettersen )irst'ame 8ari "ddress Storgt '6

.3ample
-o add a column named 3,ity3 in t"e 3.erson3 table4

2LTER T2=LE Person 2<< City varc#ar4?C8


0esult( Last'ame .ettersen )irst'ame 8ari "ddress Storgt '6 *ity

.3ample
-o drop t"e 3Address3 column in t"e 3.erson3 table4

2LTER T2=LE Person <ROP COL3MN 2""ress


0esult( Last'ame .ettersen )irst'ame 8ari *ity

SQL )unctions
SQL has a lot of built%in functions for counting and calculations.

)unction Synta3
-"e syntax for built<in SQL functions is4

SELECT >unction4column8 FROM table

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@

"ggregate functions in +S "ccess


)unction AM:(column) ,()N-(column) ,()N-(N) 9I/S-(column) LAS-(column) #AL(column) #IN(column) S-%+M(column) S-%+M.(column) S)#(column) MA/(column) MA/.(column) /eturns t"e total sum of a column Description /eturns t"e average value of a column /eturns t"e number of rows (wit"out a N)LL value) of a column /eturns t"e number of selected rows /eturns t"e value of t"e first record in a specified field /eturns t"e value of t"e last record in a specified field /eturns t"e "ig"est value of a column /eturns t"e lowest value of a column

"ggregate functions in SQL Server


)unction AM:(column) &INA/FH,1+,8S)# ,1+,8S)# ,1+,8S)#HA:: ,()N-(column) ,()N-(N) ,()N-(%IS-IN,- column) 9I/S-(column) LAS-(column) #AL(column) #IN(column) S-%+M(column) /eturns t"e number of rows (wit"out a N)LL value) of a column /eturns t"e number of selected rows /eturns t"e number of distinct results /eturns t"e value of t"e first record in a specified field (not supported in SQLServer'8) /eturns t"e value of t"e last record in a specified field (not supported in SQLServer'8) /eturns t"e "ig"est value of a column /eturns t"e lowest value of a column Description /eturns t"e average value of a column

S-%+M.(column) S)#(column) MA/(column) MA/.(column) /eturns t"e total sum of a column

Scalar functions
Scalar functions operate against a single value$ and return a single value based on t"e input value

&seful Scalar )unctions in +S "ccess


)unction ),AS+(c) L,AS+(c) #I%(c$startO$endP) L+N(c) INS-/(c$c"ar) L+9-(c$numberHofHc"ar) /I:1-(c$numberHofHc"ar) /()N%(c$decimals) #(%(x$y) N(0() 9(/#A-(c$format) %A-+%I99(d$date5$date') Description ,onverts a field to upper case ,onverts a field to lower case +xtract c"aracters from a text field /eturns t"e lengt" of a text field /eturns t"e numeric position of a named c"aracter wit"in a text field /eturn t"e left part of a text field requested /eturn t"e rig"t part of a text field requested /ounds a numeric field to t"e number of decimals specified /eturns t"e remainder of a division operation /eturns t"e current system date ,"anges t"e way a field is displayed )sed to perform date calculations

SQL <0O&/

5 and 2">I'<
5 functionality.

"ggregate functions ,li7e S&+- often need an added <0O&/

<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

SELECT column5S3M4column8 FROM table ARO3P =' column

<0O&/

5 .3ample

-"is 3Sales3 -able4 *ompany 07Sc"ools "mount AA66

I&# 07Sc"ools And -"is SQL4

GA66 B566

SELECT Company5 S3M42mount8 FROM Sales


/eturns t"is result4 *ompany 07Sc"ools I&# 07Sc"ools S&+,"mount5B566 5B566 5B566

-"e above code is invalid because t"e column returned is not part of an aggregate A :/(). &F clause will solve t"is problem4

SELECT Company5S3M42mount8 FROM Sales ARO3P =' Company


/eturns t"is result4 *ompany 07Sc"ools I&# S&+,"mount5'D66 GA66

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

SELECT Company5S3M42mount8 FROM Sales ARO3P =' Company H21-NA S3M42mount8()CCCC

/eturns t"is result *ompany 07Sc"ools S&+,"mount5'D66

SQL S.L.*T I'TO Statement


The S.L.*T I'TO Statement
-"e S+L+,- IN-( statement is most often used to create bac!up copies of tables or for arc"iving records

Synta3 SELECT column0name4s8 -NTO ne%table F-N eEternal"atabaseG FROM source

+a7e a

ac7up *opy

-"e following example ma!es a bac!up copy of t"e 3.ersons3 table4

SELECT * -NTO Persons0bac9up FROM Persons


-"e IN clause can be used to copy tables into anot"er database4

SELECT Persons7* -NTO Persons -N !=ac9up7m"b! FROM Persons


If you only want to copy a few fields$ you can do so by listing t"em after t"e S+L+,- statement4

SELECT LastName5FirstName -NTO Persons0bac9up FROM Persons


Fou can also add a 01+/+ clause -"e following example creates a 3.ersonsHbac!up3 table wit" two columns (9irstName and LastName) by extracting t"e persons w"o lives in 3Sandnes3 from t"e 3.ersons3 table4

SELECT LastName5Firstname -NTO Persons0bac9up FROM Persons WHERE City !San"nes!


Selecting data from more t"an one table is also possible -"e following example creates a new table 3+mplH(rdHbac!up3 t"at contains data from t"e two tables +mployees and (rders4

SELECT Employees7Name5Or"ers7Pro"uct -NTO Empl0Or"0bac9up FROM Employees

-NNER @O-N Or"ers ON Employees7Employee0-< Or"ers7Employee0-<

SQL *0."T. >I.# Statement


" view is a virtual table based on the result%set of a S.L.*T statement.

#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

SELECT * FROM FCurrent Pro"uct ListG

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

SELECT * FROM FPro"ucts 2bove 2vera&e PriceG


Anot"er example view from t"e Nort"wind database calculates t"e total sale for eac" category in 5@@B Note t"at t"is view select its data from anot"er view called 3.roduct Sales for 5@@B34

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

SELECT * FROM FCate&ory Sales For )**;G


0e can also add a condition to t"e query Now we want to see t"e total sale only for t"e category 3&everages34

SELECT * FROM FCate&ory Sales For )**;G WHERE Cate&oryName !=evera&es!

SQL Servers % 0D +S
+odern SQL Servers are built on 0D +S.

D +S % Database +anagement System


A %atabase #anagement System (%&#S) is a computer program t"at can access data in a database -"e %&#S program enables you to extract$ modify$ or store information in a database %ifferent %&#S programs provides different functions for querying data$ reporting data$ and modifying data

0D +S % 0elational Database +anagement System


A /elational %atabase #anagement System (/%&#S) is a %atabase #anagement System (%&#S) w"ere t"e database is organiKed and accessed according to t"e relations"ips between data

/%&#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

You might also like