You are on page 1of 29

SQL is a standard computer language for accessing and manipulating databases.

What 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 - BUT....


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) Note: #ost of t"e SQL database programs also "ave t"eir own proprietary extensions in addition to t"e SQL standard2

SQL

atabase 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 LastName 1ansen Svendson .ettersen !irstName (la -ove 8ari "ddress -imoteivn 56 &orgvn '7 Storgt '6 #it$ 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 LastName 1ansen Svendson .ettersen Note4 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

ata %anipulation Language & %L'

SQL (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

SQL

S(L(#T < extracts data from a database table U) "T( < updates data in a database table (L(T( < deletes data from a database table *NS(+T *NT, < inserts new data into a database table

ata

efinition Language &

L'

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

#+("T( T"BL( < creates a new database table "LT(+ T"BL( < alters (c"anges) a database table +,) T"BL( < deletes a database table #+("T( *N (- < creates an index (searc" !ey) +,) *N (- < deletes an index

SQL S(L(#T (.ample


-o select t"e content of columns named 3LastName3 and 39irstName3$ from t"e database table called 3.ersons3$ use a S+L+,- statement li!e t"is4

SELECT LastName,FirstName FROM Persons


The database table /)ersons/:

LastName 1ansen Svendson .ettersen The result LastName 1ansen Svendson .ettersen

!irstName (la -ove 8ari

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

#it$ Sandnes Sandnes Stavanger

!irstName (la -ove 8ari

Select "ll #olumns


-o select all columns from t"e 3.ersons3 table$ use a = symbol instead of column names$ li!e t"is4

SELECT * FROM Persons


+esult LastName 1ansen Svendson .ettersen !irstName (la -ove 8ari "ddress -imoteivn 56 &orgvn '7 Storgt '6 #it$ Sandnes Sandnes Stavanger

The +esult Set


-"e result from a SQL query is stored in a result<set #ost database software systems allow navigation of t"e result set wit" programming functions$ li!e4 #ove<-o<9irst</ecord$ :et</ecord< ,ontent$ #ove<-o<Next</ecord$ etc .rogramming functions li!e t"ese are not a part of t"is tutorial -o learn about accessing data wit" function calls$ please visit our A%( tutorial

Semicolon after SQL Statements?


Semicolon is t"e standard way to separate eac" SQL statement in database systems t"at allow more t"an one SQL statement to be executed in t"e same call to t"e server Some SQL tutorials end eac" SQL statement wit" a semicolon Is t"is necessary> 0e are using #S Access and SQL Server '666 and we do not "ave to put a semicolon after eac" SQL statement$ but some database programs force you to use it

The S(L(#T

*ST*N#T Statement

-"e %IS-IN,- !eyword is used to return only distinct (different) values

-"e S+L+,- statement returns information from table columns &ut w"at if we only want to select distinct elements> 0it" SQL$ all we need to do is to add a %IS-IN,- !eyword to t"e S+L+,- statement4

S$nta. SELECT DISTINCT column_name(s) FROM ta le_name

Using the

*ST*N#T 0e$1ord

-o select ALL values from t"e column named 3,ompany3 we use a S+L+,- statement li!e t"is4

SELECT Com!an" FROM Or#ers


/,rders/ table #ompan$ Sega 07Sc"ools -rio 07Sc"ools +esult #ompan$ Sega 07Sc"ools -rio 07Sc"ools Note t"at 307Sc"ools3 is listed twice in t"e result<set -o select only %I99+/+N- values from t"e column named 3,ompany3 we use a S+L+,- %IS-IN,statement li!e t"is4 ,rderNumber 7?5' '75' ?@AB @ACB

SELECT DISTINCT Com!an" FROM Or#ers


+esult: #ompan$ Sega 07Sc"ools -rio

The W2(+( clause is used to specif$ a selection criterion.

The W2(+( #lause


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

S$nta. SELECT column FROM ta le $%ERE column o!erator &alue


0it" t"e 01+/+ clause$ t"e following operators can be used4 ,perator D EF F E FD ED LI8+ Searc" for a pattern IN If you !now t"e exact value you want to return for at least one of t"e columns escription +qual Not equal :reater t"an Less t"an :reater t"an or equal Less t"an or equal

&+-0++N &etween an inclusive range

Note: In some versions of SQL t"e EF operator may be written as 2D

Using the W2(+( #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 $%ERE Cit"'(San#nes(


/)ersons/ table LastName 1ansen Svendson Svendson .ettersen +esult LastName 1ansen Svendson !irstName (la -ove "ddress -imoteivn 56 &orgvn '7 #it$ Sandnes Sandnes 3ear 5CG5 5CAB !irstName (la -ove Stale 8ari "ddress -imoteivn 56 &orgvn '7 8aivn 5B Storgt '6 #it$ Sandnes Sandnes Sandnes Stavanger 3ear 5CG5 5CAB 5CB6 5C@6

Svendson

Stale

8aivn 5B

Sandnes

5CB6

Using 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 $%ERE FirstName'(To&e( T)is is +ron,* SELECT * FROM Persons $%ERE FirstName'To&e
9or numeric values4

T)is is correct* SELECT * FROM Persons $%ERE -ear./012 T)is is +ron,* SELECT * FROM Persons $%ERE -ear.(/012(

The L*4( #ondition


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

S$nta. SELECT column FROM ta le $%ERE column LI3E !attern


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

Using L*4(
-"e following SQL statement will return persons wit" first names t"at start wit" an ;(;4

SELECT * FROM Persons $%ERE FirstName LI3E (O4(


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

SELECT * FROM Persons $%ERE FirstName LI3E (4a(


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

SELECT * FROM Persons $%ERE FirstName LI3E (4la4(

The *NS(+T *NT, Statement


-"e INS+/- IN-( statement is used to insert new rows into a table

S$nta. INSERT INTO ta le_name 56L7ES (&alue/, &alue8,9999)


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

INSERT INTO ta le_name (column/, column8,999) 56L7ES (&alue/, &alue8,9999)

*nsert a Ne1 +o1


-"is 3.ersons3 table4 LastName .ettersen And t"is SQL statement4 !irstName 8ari "ddress Storgt '6 #it$ Stavanger

INSERT INTO Persons 56L7ES ((%etlan#(, (Camilla(, (%a,a a::a 8;(, (San#nes()
0ill give t"is result4 LastName .ettersen 1etland !irstName 8ari ,amilla "ddress Storgt '6 1agaba!!a '? #it$ Stavanger Sandnes

*nsert

ata in Specified #olumns

-"is 3.ersons3 table4 LastName .ettersen 1etland !irstName 8ari ,amilla "ddress Storgt '6 1agaba!!a '? #it$ Stavanger Sandnes

And -"is SQL statement4

INSERT INTO Persons (LastName, 6##ress) 56L7ES ((Rasmussen(, (Stor,t 1<()

0ill give t"is result4 LastName .ettersen 1etland /asmussen !irstName 8ari ,amilla "ddress Storgt '6 1agaba!!a '? Storgt @A #it$ Stavanger Sandnes

The Update Statement


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

S$nta. 7PD6TE ta le_name SET column_name ' ne+_&alue $%ERE column_name ' some_&alue

)erson: LastName Nilsen /asmussen !irstName 9red "ddress 8ir!egt G@ Storgt @A #it$ Stavanger

Update one #olumn in a +o1


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

7PD6TE Person SET FirstName ' (Nina( $%ERE LastName ' (Rasmussen(
+esult: LastName Nilsen /asmussen !irstName 9red Nina "ddress 8ir!egt G@ Storgt @A #it$ Stavanger

Update se5eral #olumns in a +o1


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

7PD6TE Person SET 6##ress ' (Stien /8(, Cit" ' (Sta&an,er( $%ERE LastName ' (Rasmussen(
+esult: LastName !irstName "ddress #it$

Nilsen /asmussen

9red Nina

8ir!egt G@ Stien 5'

Stavanger Stavanger

The

(L(T( Statement

-"e %+L+-+ statement is used to delete rows in a table

S$nta. DELETE FROM ta le_name $%ERE column_name ' some_&alue

)erson: LastName Nilsen /asmussen !irstName 9red Nina "ddress 8ir!egt G@ Stien 5' #it$ Stavanger Stavanger

elete a +o1
3Nina /asmussen3 is going to be deleted4

DELETE FROM Person $%ERE LastName ' (Rasmussen(


+esult LastName Nilsen !irstName 9red "ddress 8ir!egt G@ #it$ Stavanger

elete "ll +o1s


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

DELETE FROM ta le_name or DELETE * FROM ta le_name

Sort the +o1s


-"e (/%+/ &I clause is used to sort t"e rows ,rders: #ompan$ Sega A&, S"op ,rderNumber 7?5' G@AB

07Sc"ools 07Sc"ools

'75' @ACB

(.ample
-o display t"e company names in alp"abetical order4

SELECT Com!an", Or#erNum er FROM Or#ers ORDER =- Com!an"


+esult: #ompan$ A&, S"op Sega 07Sc"ools 07Sc"ools ,rderNumber G@AB 7?5' @ACB '75'

(.ample
-o display t"e company names in alp"abetical order AN% t"e (rderNumber in numerical order4

SELECT Com!an", Or#erNum er FROM Or#ers ORDER =- Com!an", Or#erNum er


+esult: #ompan$ A&, S"op Sega 07Sc"ools 07Sc"ools ,rderNumber G@AB 7?5' '75' @ACB

(.ample
-o display t"e company names in reverse alp"abetical order4

SELECT Com!an", Or#erNum er FROM Or#ers ORDER =- Com!an" DESC


+esult: #ompan$ 07Sc"ools 07Sc"ools Sega A&, S"op ,rderNumber @ACB '75' 7?5' G@AB

(.ample

-o display t"e company names in reverse alp"abetical order AN% t"e (rderNumber in numerical order4

SELECT Com!an", Or#erNum er FROM Or#ers ORDER =- Com!an" DESC, Or#erNum er 6SC
+esult: #ompan$ 07Sc"ools 07Sc"ools Sega A&, S"op ,rderNumber '75' @ACB 7?5' G@AB

Notice t"at t"ere are two equal company names (07Sc"ools) in t"e result above -"e only time you will see t"e second column in AS, order would be w"en t"ere are duplicated values in t"e first sort column$ or a "andful of nulls

"N

6 ,+

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 ANI of t"e conditions listed are true

,riginal Table &used in the e.amples'


LastName 1ansen Svendson Svendson !irstName (la -ove Step"en "ddress -imoteivn 56 &orgvn '7 8aivn 5B #it$ Sandnes Sandnes Sandnes

(.ample
)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 $%ERE FirstName'(To&e( 6ND LastName'(S&en#son(


+esult: LastName Svendson !irstName -ove "ddress &orgvn '7 #it$ Sandnes

(.ample
)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 $%ERE >irstname'(To&e( OR lastname'(S&en#son(


+esult: LastName Svendson Svendson !irstName -ove Step"en "ddress &orgvn '7 8aivn 5B #it$ Sandnes Sandnes

(.ample
Iou can also combine AN% and (/ (use parent"eses to form complex expressions)4

SELECT * FROM Persons $%ERE (FirstName'(To&e( OR FirstName'(Ste!)en() 6ND LastName'(S&en#son(


+esult: LastName Svendson Svendson !irstName -ove Step"en "ddress &orgvn '7 8aivn 5B #it$ Sandnes Sandnes

*N
-"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 column_name FROM ta le_name $%ERE column_name IN (&alue/,&alue8,99)

,riginal Table &used in the e.amples'


LastName 1ansen Nordmann .ettersen Svendson !irstName (la Anna 8ari -ove "ddress -imoteivn 56 Neset 5B Storgt '6 &orgvn '7 #it$ Sandnes Sandnes Stavanger Sandnes

(.ample 7
-o display t"e persons wit" LastName equal to 31ansen3 or 3.ettersen3$ use t"e following SQL4

SELECT * FROM Persons $%ERE LastName IN ((%ansen(,(Pettersen()


+esult:

LastName 1ansen .ettersen

!irstName (la 8ari

"ddress -imoteivn 56 Storgt '6

#it$ Sandnes Stavanger

B(TW((N ... "N


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

SELECT column_name FROM ta le_name $%ERE column_name =ET$EEN &alue/ 6ND &alue8

,riginal Table &used in the e.amples'


LastName 1ansen Nordmann .ettersen Svendson !irstName (la Anna 8ari -ove "ddress -imoteivn 56 Neset 5B Storgt '6 &orgvn '7 #it$ Sandnes Sandnes Stavanger Sandnes

(.ample 7
-o display t"e persons alp"abetically between (and including) 31ansen3 and exclusive 3.ettersen3$ use t"e following SQL4

SELECT * FROM Persons $%ERE LastName =ET$EEN (%ansen( 6ND (Pettersen(


+esult: LastName 1ansen Nordmann !irstName (la Anna "ddress -imoteivn 56 Neset 5B #it$ Sandnes Sandnes

*%),+T"NT8 -"e &+-0++N AN% operator is treated differently in different databases 0it" some databases a person wit" t"e LastName of 31ansen3 or 3.ettersen3 will not be listed (&+-0++N AN% only selects fields t"at are between and excluding t"e test values) 0it" some databases a person wit" t"e last name of 31ansen3 or 3.ettersen3 will be listed (&+-0++N AN% selects fields t"at are between and including t"e test values) 0it" ot"er databases a person wit" t"e last name of 31ansen3 will be listed$ but 3.ettersen3 will not be listed (&+-0++N AN% selects fields between t"e test values$ including t"e first test value and excluding t"e last test value) -"erefore4 ,"ec! "ow your database treats t"e &+-0++N AN% operator2

(.ample 9
-o display t"e persons outside t"e range used in t"e previous example$ use t"e N(- operator4

SELECT * FROM Persons $%ERE LastName

NOT =ET$EEN (%ansen( 6ND (Pettersen(


+esult: LastName .ettersen Svendson !irstName 8ari -ove "ddress Storgt '6 &orgvn '7 #it$ Stavanger Sandnes

#olumn Name "lias


-"e syntax is4

SELECT column 6S column_alias FROM ta le

Table Name "lias


-"e syntax is4

SELECT column FROM ta le 6S ta le_alias

(.ample: Using a #olumn "lias


-"is table (.ersons)4 LastName 1ansen Svendson .ettersen And t"is SQL4 !irstName (la -ove 8ari "ddress -imoteivn 56 &orgvn '7 Storgt '6 #it$ Sandnes Sandnes Stavanger

SELECT LastName 6S Famil", FirstName 6S Name FROM Persons


/eturns t"is result4 !amil$ 1ansen Svendson .ettersen Name (la -ove 8ari

(.ample: Using a Table "lias


-"is table (.ersons)4 LastName !irstName "ddress #it$

1ansen Svendson .ettersen And t"is SQL4

(la -ove 8ari

-imoteivn 56 &orgvn '7 Storgt '6

Sandnes Sandnes Stavanger

SELECT LastName, FirstName FROM Persons 6S Em!lo"ees


/eturns t"is result4 -able +mployees4 LastName 1ansen Svendson .ettersen !irstName (la -ove 8ari

:oins and 4e$s


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+mployeeJI%3 column is t"e primary !ey$ meaning t"at no two rows can "ave t"e same +mployeeJI% -"e +mployeeJI% 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+mployeeJI%3 column is t"e primary !ey of t"e 3+mployees3 table -"e 3.rodJI%3 column is t"e primary !ey of t"e 3(rders3 table -"e 3+mployeeJI%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

(mplo$ees4 (mplo$ee;* 65 6' 67 6? ,rders: )rod;* )roduct (mplo$ee;* Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari

'7? @GA B@G

.rinter -able ,"air

65 67 67

+eferring to T1o Tables


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

(.ample
0"o "as ordered a product$ and w"at did t"ey order>

SELECT Em!lo"ees9Name, Or#ers9Pro#uct FROM Em!lo"ees, Or#ers $%ERE Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID


+esult Name 1ansen$ (la Svendson$ Step"en Svendson$ Step"en )roduct .rinter -able ,"air

(.ample
0"o ordered a printer>

SELECT Em!lo"ees9Name FROM Em!lo"ees, Or#ers $%ERE Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID 6ND Or#ers9Pro#uct'(Printer(


+esult Name 1ansen$ (la

Using :oins
(/ we can select data from two tables wit" t"e K(IN !eyword$ li!e t"is4

(.ample *NN(+ :,*N


S$nta.

SELECT >iel#/, >iel#8, >iel#? FROM >irst_ta le INNER @OIN secon#_ta le

ON >irst_ta le9:e">iel# ' secon#_ta le9>orei,n_:e">iel#


0"o "as ordered a product$ and w"at did t"ey order>

SELECT Em!lo"ees9Name, Or#ers9Pro#uct FROM Em!lo"ees INNER @OIN Or#ers ON Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID


-"e INN+/ K(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 +esult Name 1ansen$ (la Svendson$ Step"en Svendson$ Step"en )roduct .rinter -able ,"air

(.ample L(!T :,*N


S$nta.

SELECT >iel#/, >iel#8, >iel#? FROM >irst_ta le LEFT @OIN secon#_ta le ON >irst_ta le9:e">iel# ' secon#_ta le9>orei,n_:e">iel#
List all employees$ and t"eir orders < if any

SELECT Em!lo"ees9Name, Or#ers9Pro#uct FROM Em!lo"ees LEFT @OIN Or#ers ON Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID


-"e L+9- K(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 +esult Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en Svendson$ Step"en .ettersen$ 8ari -able ,"air )roduct .rinter

(.ample +*<2T :,*N

S$nta.

SELECT >iel#/, >iel#8, >iel#? FROM >irst_ta le RIA%T @OIN secon#_ta le ON >irst_ta le9:e">iel# ' secon#_ta le9>orei,n_:e">iel#
List all orders$ and w"o "as ordered < if any

SELECT Em!lo"ees9Name, Or#ers9Pro#uct FROM Em!lo"ees RIA%T @OIN Or#ers ON Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID


-"e /I:1- K(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 +esult Name 1ansen$ (la Svendson$ Step"en Svendson$ Step"en )roduct .rinter -able ,"air

(.ample
0"o ordered a printer>

SELECT Em!lo"ees9Name FROM Em!lo"ees INNER @OIN Or#ers ON Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID $%ERE Or#ers9Pro#uct ' (Printer(
+esult Name 1ansen$ (la

UN*,N
-"e )NI(N command is used to select related information from two tables$ muc" li!e t"e K(IN command 1owever$ w"en using t"e )NI(N command all selected columns need to be of t"e same data type Note: 0it" )NI(N$ only distinct values are selected

SBL Statement / 7NION SBL Statement 8

(mplo$ees;Nor1a$4 (;* 65 6' 67 6? (mplo$ees;US"4 (;* 65 6' 67 6? (;Name -urner$ Sally 8ent$ ,lar! Svendson$ Step"en Scott$ Step"en (;Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari

Using the UN*,N #ommand


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

SELECT E_Name FROM Em!lo"ees_Nor+a" 7NION SELECT E_Name FROM Em!lo"ees_7S6


+esult (;Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari -urner$ Sally 8ent$ ,lar! Scott$ Step"en Note: -"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

UN*,N "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 / 7NION 6LL SBL Statement 8

Using the UN*,N "LL #ommand


(.ample
List all employees in Norway and )SA4

SELECT E_Name FROM Em!lo"ees_Nor+a" 7NION 6LL SELECT E_Name FROM Em!lo"ees_7S6
+esult (;Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari -urner$ Sally 8ent$ ,lar! Svendson$ Step"en Scott$ Step"en

#reate a

atabase

-o create a database4

CRE6TE D6T6=6SE #ata ase_name

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

CRE6TE T6=LE ta le_name ( column_name/ #ata_t"!e, column_name8 #ata_t"!e, ....... ) (.ample


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

CRE6TE T6=LE Person

( LastName &arc)ar, FirstName &arc)ar, 6##ress &arc)ar, 6,e int )


-"is example demonstrates "ow you can specify a maximum lengt" for some columns4

CRE6TE T6=LE Person ( LastName &arc)ar(?C), FirstName &arc)ar, 6##ress &arc)ar, 6,e int(?) )
-"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 ata T$pe integer(siLe) int(siLe) smallint(siLe) tinyint(siLe) decimal(siLe$d) numeric(siLe$d) c"ar(siLe) varc"ar(siLe) date(yyyymmdd) escription 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 3siLe3 -"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 siLe is specified in parent"esis 1olds a variable lengt" string (can contain letters$ numbers$ and special c"aracters) -"e maximum siLe is specified in parent"esis 1olds a date

#reate *nde.
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 Note: )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" " Uni=ue *nde. ,reates a unique index on a table A unique index means t"at two rows cannot "ave t"e same index value

CRE6TE 7NIB7E INDED in#eE_name ON ta le_name (column_name)


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

" Simple *nde. ,reates a simple index on a table 0"en t"e )NIQ)+ !eyword is omitted$ duplicate values are allowed

CRE6TE INDED in#eE_name ON ta le_name (column_name)


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

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

CRE6TE INDED PersonIn#eE ON Person (LastName)


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

CRE6TE INDED PersonIn#eE ON Person (LastName DESC)


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

CRE6TE INDED PersonIn#eE ON Person (LastName, FirstName)

rop *nde.
Iou can delete an existing index in a table wit" t"e %/(. IN%+M statement Syntax for #icrosoft SQLKet (and #icrosoft Access)4

DROP INDED in#eE_name ON ta le_name


Syntax for #S SQL Server4

DROP INDED ta le_name9in#eE_name


Syntax for I&# %&' and (racle4

DROP INDED in#eE_name


Syntax for #ySQL4

6LTER T6=LE ta le_name DROP INDED in#eE_name

elete a Table or

atabase

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

DROP T6=LE ta le_name


-o delete a database4

DROP D6T6=6SE #ata ase_name

Truncate a Table
0"at if we only want to get rid of t"e data inside a table$ and not t"e table itself> )se t"e -/)N,A-+ -A&L+ command (deletes only t"e data inside t"e table)4

TR7NC6TE T6=LE ta le_name

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

6LTER T6=LE ta le_name 6DD column_name #atat"!e 6LTER T6=LE ta le_name DROP COL7MN column_name
Note: Some database systems don;t allow t"e dropping of a column in a database table (%/(. ,(L)#N columnJname)

)erson: LastName .ettersen !irstName 8ari "ddress Storgt '6

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

6LTER T6=LE Person 6DD Cit" &arc)ar(?C)


+esult: LastName .ettersen !irstName 8ari "ddress Storgt '6 #it$

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

6LTER T6=LE Person DROP COL7MN 6##ress


+esult: LastName .ettersen !irstName 8ari #it$

SQL has a lot of built-in functions for counting and calculations.

!unction S$nta.
-"e syntax for built<in SQL functions is4

SELECT >unction(column) FROM ta le

T$pes 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 Note: If used among many ot"er expressions in t"e item list of a S+L+,- statement$ t"e S+L+,must "ave a :/(). &I clause22

/)ersons/ table &used in most e.amples'


Name 1ansen$ (la Svendson$ -ove .ettersen$ 8ari "ge 7? ?G 5C

"ggregate functions in %S "ccess


!unction AN:(column) ,()N-(column) ,()N-(=) 9I/S-(column) LAS-(column) #AM(column) #IN(column) S-%+N(column) escription /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

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

"ggregate functions in SQL Ser5er


!unction AN:(column) &INA/IJ,1+,8S)# ,1+,8S)# ,1+,8S)#JA:: ,()N-(column) ,()N-(=) ,()N-(%IS-IN,- column) 9I/S-(column) LAS-(column) #AM(column) #IN(column) S-%+N(column) S-%+N.(column) S)#(column) NA/(column) NA/.(column) /eturns t"e total sum 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 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 escription /eturns t"e average value of a column

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

Useful 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$numberJofJc"ar) /I:1-(c$numberJofJc"ar) /()N%(c$decimals) #(%(x$y) N(0() 9(/#A-(c$format) %A-+%I99(d$date5$date') escription ,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

<+,U) B3...
:/(). &I 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 :/(). &I function it was impossible to find t"e sum for eac" individual group of column values -"e syntax for t"e :/(). &I function is4

SELECT column,S7M(column) FROM ta le ARO7P =- column

<+,U) B3 (.ample
-"is 3Sales3 -able4 #ompan$ 07Sc"ools I&# 07Sc"ools And -"is SQL4 "mount GG66 ?G66 A566

SELECT Com!an", S7M(6mount) FROM Sales


/eturns t"is result4 #ompan$ 07Sc"ools I&# 07Sc"ools SU%&"mount' 5A566 5A566 5A566

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

SELECT Com!an",S7M(6mount) FROM Sales ARO7P =- Com!an"


/eturns t"is result4 #ompan$ 07Sc"ools I&# SU%&"mount' 5'@66 ?G66

2">*N<...
1ANIN: was added to SQL because t"e 01+/+ !eyword could not be used against aggregate functions (li!e S)#)$ and wit"out 1ANIN: it would be impossible to test for result conditions -"e syntax for t"e 1ANIN: function is4

SELECT column,S7M(column) FROM ta le ARO7P =- column %65INA S7M(column) con#ition &alue


-"is 3Sales3 -able4 #ompan$ 07Sc"ools I&# 07Sc"ools -"is SQL4 "mount GG66 ?G66 A566

SELECT Com!an",S7M(6mount) FROM Sales ARO7P =- Com!an" %65INA S7M(6mount)./CCCC


/eturns t"is result #ompan$ 07Sc"ools SU%&"mount' 5'@66

The S(L(#T *NT, Statement


-"e S+L+,- IN-( statement is most often used to create bac!up copies of tables or for arc"iving records

S$nta. SELECT column_name(s) INTO ne+ta le FIN eEternal#ata aseG FROM source

%a0e a Bac0up #op$


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

SELECT * INTO Persons_ ac:u! FROM Persons


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

SELECT Persons9* INTO Persons IN (=ac:u!9m# ( 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 LastName,FirstName INTO Persons_ ac:u! FROM Persons

Iou can also add a 01+/+ clause -"e following example creates a 3.ersonsJbac!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 LastName,Firstname INTO Persons_ ac:u! FROM Persons $%ERE Cit"'(San#nes(


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

SELECT Em!lo"ees9Name,Or#ers9Pro#uct INTO Em!l_Or#_ ac:u! FROM Em!lo"ees INNER @OIN Or#ers ON Em!lo"ees9Em!lo"ee_ID'Or#ers9Em!lo"ee_ID

What is a >ie1?
In SQL$ a NI+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 Iou can add SQL functions$ 01+/+$ and K(IN statements to a view and present t"e data as if t"e data were coming from a single table Note: -"e database design and structure will N(- be affected by t"e functions$ w"ere$ or *oin statements in a view

S$nta. CRE6TE 5IE$ &ie+_name 6S SELECT column_name(s) FROM ta le_name $%ERE con#ition
Note: -"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

Using >ie1s
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

CRE6TE 5IE$ FCurrent Pro#uct ListG 6S SELECT Pro#uctID,Pro#uctName FROM Pro#ucts $%ERE Discontinue#'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

CRE6TE 5IE$ FPro#ucts 6 o&e 6&era,e PriceG 6S SELECT Pro#uctName,7nitPrice FROM Pro#ucts $%ERE 7nitPrice.(SELECT 65A(7nitPrice) FROM Pro#ucts)
0e can query t"e view above as follows4

SELECT * FROM FPro#ucts 6 o&e 6&era,e PriceG


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

CRE6TE 5IE$ FCate,or" Sales For /00<G 6S SELECT DISTINCT Cate,or"Name,Sum(Pro#uctSales) 6S Cate,or"Sales FROM FPro#uct Sales >or /00<G ARO7P =- Cate,or"Name
0e can query t"e view above as follows4

SELECT * FROM FCate,or" Sales For /00<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,or" Sales For /00<G $%ERE Cate,or"Name'(=e&era,es(

You might also like