Anda di halaman 1dari 27

SQL

Introduction to SQL 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 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
LastName 1ansen Svendson .ettersen FirstName (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.

SQL

A query li!e t"is4


S+L+,- LastName 9/(# .ersons

: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 Data #ani$ulation Lan%ua%e &D#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

S(L(!T < extracts data from a database table U)D T( < updates data in a database table D(L(T( < deletes data from a database table INS(*T INT+ < inserts new data into a database table

SQL Data De,inition Lan%ua%e &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
!*( T( T BL( < creates a new database table LT(* T BL( < alters (c"anges a database table D*+) T BL( < deletes a database table !*( T( IND(- < creates an index (searc" !ey D*+) IND(- < deletes an index

SQL The S(L(!T Statement


The S(L(!T Statement

-"e S+L+,- statement is used to select data from a table. -"e tabular result is stored in a result table (called t"e result<set . Syntax

'

SQL

S+L+,- column=name(s 9/(# table=name


Select Some !olumns

-o select t"e columns named 3LastName3 and 39irstName3$ use a S+L+,- statement li!e t"is4
S+L+,- LastName$9irstName 9/(# .ersons

.)ersons. table
LastName 1ansen Svendson .ettersen *esult LastName 1ansen Svendson .ettersen Select ll !olumns FirstName (la -ove 8ari FirstName (la -ove 8ari ddress -imoteivn 56 &orgvn '7 Storgt '6 !it" Sandnes Sandnes Stavanger

-o select all columns from t"e 3.ersons3 table$ use a > symbol instead of column names$ li!e t"is4
S+L+,- > 9/(# .ersons

*esult
LastName 1ansen Svendson .ettersen The *esult Set FirstName (la -ove 8ari ddress -imoteivn 56 &orgvn '7 Storgt '6 !it" Sandnes Sandnes Stavanger

-"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.
Semicolon a,ter 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.

SQL The S(L(!T DISTIN!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/ S+L+,- %IS-IN,- column=name(s 9/(# table=name
Usin% the DISTIN!T 0e"1ord

-o select ALL values from t"e column named 3,ompany3 we use a S+L+,- statement li!e t"is4
S+L+,- ,ompany 9/(# (rders .+rders. table !om$an" Sega 07Sc"ools -rio 07Sc"ools *esult !om$an" Sega 07Sc"ools -rio 07Sc"ools +rderNumber 7@5' '75' @ABC ABDC

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
S+L+,- %IS-IN,- ,ompany 9/(# (rders *esult: !om$an" Sega 07Sc"ools -rio

Now 307Sc"ools3 is listed only once in t"e result<set. SQL The W2(*( !lause

SQL

-"e 01+/+ clause is used to specify 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/
S+L+,- column 9/(# table 01+/+ column operator value

0it" t"e 01+/+ clause$ t"e following operators can be used4 +$erator E FG G F GE FE &+-0++N LI8+ Descri$tion +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

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


Usin% 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
S+L+,- > 9/(# .ersons 01+/+ ,ityE;Sandnes; .)ersons. table LastName 1ansen Svendson Svendson .ettersen *esult LastName 1ansen Svendson Svendson Usin% Quotes FirstName (la -ove Stale ddress -imoteivn 56 &orgvn '7 8aivn 5C !it" Sandnes Sandnes Sandnes 3ear 5DH5 5DBC 5DC6 FirstName (la -ove Stale 8ari ddress -imoteivn 56 &orgvn '7 8aivn 5C Storgt '6 !it" Sandnes Sandnes Sandnes Stavanger 3ear 5DH5 5DBC 5DC6 5DA6

Note t"at we "ave used single quotes around t"e conditional values in t"e examples.
H

SQL

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
-"is is correct4 S+L+,- > 9/(# .ersons 01+/+ 9irstNameE;-ove; -"is is wrong4 S+L+,- > 9/(# .ersons 01+/+ 9irstNameE-ove 9or numeric values4 -"is is correct4 S+L+,- > 9/(# .ersons 01+/+ IearG5DAH -"is is wrong4 S+L+,- > 9/(# .ersons 01+/+ IearG;5DAH; The LI4( !ondition

-"e LI8+ condition is used to specify a searc" for a pattern in a column. S"nta/
S+L+,- column 9/(# table 01+/+ column LI8+ pattern

A 3J3 sign can be used to define wildcards (missing letters in t"e pattern bot" before and after t"e pattern. Usin% LI4( -"e following SQL statement will return persons wit" first names t"at start wit" an ;(;4
S+L+,- > 9/(# .ersons 01+/+ 9irstName LI8+ ;(J;

-"e following SQL statement will return persons wit" first names t"at end wit" an ;a;4
S+L+,- > 9/(# .ersons 01+/+ 9irstName LI8+ ;Ja;

-"e following SQL statement will return persons wit" first names t"at contain t"e pattern ;la;4
S+L+,- > 9/(# .ersons 01+/+ 9irstName LI8+ ;JlaJ;

SQL The INS(*T INT+ Statement


The INS(*T INT+ Statement

-"e INS+/- IN-( statement is used to insert new rows into a table. S"nta/
INS+/- IN-( table=name KAL)+S (value5$ value'$....

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

SQL INS+/- IN-( table=name (column5$ column'$... KAL)+S (value5$ value'$.... Insert a Ne1 *o1

-"is 3.ersons3 table4


LastName .ettersen FirstName 8ari ddress Storgt '6 !it" Stavanger

And t"is SQL statement4


INS+/- IN-( .ersons KAL)+S (;1etland;$ ;,amilla;$ ;1agaba!!a '@;$ ;Sandnes;

0ill give t"is result4


LastName .ettersen 1etland FirstName 8ari ,amilla ddress Storgt '6 1agaba!!a '@ !it" Stavanger Sandnes

Insert Data in S$eci,ied !olumns

-"is 3.ersons3 table4


LastName .ettersen 1etland FirstName 8ari ,amilla ddress Storgt '6 1agaba!!a '@ !it" Stavanger Sandnes

And -"is SQL statement4


INS+/- IN-( .ersons (LastName$ Address KAL)+S (;/asmussen;$ ;Storgt AB;

0ill give t"is result4


LastName .ettersen 1etland /asmussen FirstName 8ari ,amilla ddress Storgt '6 1agaba!!a '@ Storgt AB !it" Stavanger Sandnes

SQL The U)D T( Statement The U$date Statement -"e ).%A-+ statement is used to modify t"e data in a table. S"nta/ ).%A-+ table=name S+- column=name E new=value 01+/+ column=name E some=value

SQL

)erson:
LastName Nilsen /asmussen U$date one !olumn in a *o1 FirstName 9red ddress 8ir!egt HA Storgt AB !it" Stavanger

0e want to add a first name to t"e person wit" a last name of 3/asmussen34
).%A-+ .erson S+- 9irstName E ;Nina; 01+/+ LastName E ;/asmussen;

*esult:
LastName Nilsen /asmussen FirstName 9red Nina ddress 8ir!egt HA Storgt AB !it" Stavanger

U$date se5eral !olumns in a *o1 0e want to c"ange t"e address and add t"e name of t"e city4
).%A-+ .erson S+- Address E ;Stien 5';$ ,ity E ;Stavanger; 01+/+ LastName E ;/asmussen;

*esult:
LastName Nilsen /asmussen FirstName 9red Nina ddress 8ir!egt HA Stien 5' !it" Stavanger Stavanger

SQL The Delete Statement The Delete Statement -"e %+L+-+ statement is used to delete rows in a table. S"nta/ %+L+-+ 9/(# table=name 01+/+ column=name E some=value )erson:
LastName Nilsen /asmussen FirstName 9red Nina ddress 8ir!egt HA Stien 5' !it" Stavanger Stavanger

SQL

Delete a *o1 3Nina /asmussen3 is going to be deleted4 %+L+-+ 9/(# .erson 01+/+ LastName E ;/asmussen; *esult
LastName Nilsen Delete ll *o1s FirstName 9red ddress 8ir!egt HA !it" Stavanger

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
%+L+-+ 9/(# table=name (r %+L+-+ > 9/(# table=name

SQL +*D(* B3 -"e (/%+/ &I !eyword is used to sort t"e result. Sort the *o1s -"e (/%+/ &I clause is used to sort t"e rows. +rders:
!om$an" Sega A&, S"op 07Sc"ools 07Sc"ools (/am$le +rderNumber 7@5' HABC '75' ABDC

-o display t"e companies in alp"abetical order4


S+L+,- ,ompany$ (rderNumber 9/(# (rders (/%+/ &I ,ompany *esult: !om$an" A&, S"op Sega 07Sc"ools 07Sc"ools (/am$le +rderNumber HABC 7@5' ABDC '75'

SQL

-o display t"e companies in alp"abetical order AN% t"e ordernumbers in numerical order4
S+L+,- ,ompany$ (rderNumber 9/(# (rders (/%+/ &I ,ompany$ (rderNumber

*esult: !om$an" A&, S"op Sega 07Sc"ools 07Sc"ools (/am$le -o display t"e companies in reverse alp"abetical order4 S+L+,- ,ompany$ (rderNumber 9/(# (rders (/%+/ &I ,ompany %+S, +rderNumber HABC 7@5' '75' ABDC

*esult: !om$an" 07Sc"ools 07Sc"ools Sega A&, S"op (/am$le -o display t"e companies in reverse alp"abetical order AN% t"e ordernumbers in numerical order4 S+L+,- ,ompany$ (rderNumber 9/(# (rders (/%+/ &I ,ompany %+S,$ (rderNumber AS, *esult: !om$an" 07Sc"ools 07Sc"ools Sega A&, S"op SQL ND 6 +* ND 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. +rderNumber '75' ABDC 7@5' HABC +rderNumber ABDC '75' 7@5' HABC

56

SQL

+ri%inal Table &used in the e/am$les' LastName 1ansen Svendson Svendson (/am$le )se AN% to display eac" person wit" t"e first name equal to 3-ove3$ and t"e last name equal to 3Svendson34 S+L+,- > 9/(# .ersons 01+/+ 9irstNameE;-ove; AN% LastNameE;Svendson; *esult: LastName Svendson FirstName -ove ddress &orgvn '7 !it" Sandnes FirstName (la -ove Step"en ddress -imoteivn 56 &orgvn '7 8aivn 5C !it" Sandnes Sandnes Sandnes

(/am$le )se (/ to display eac" person wit" t"e first name equal to 3-ove3$ or t"e last name equal to 3Svendson34 S+L+,- > 9/(# .ersons 01+/+ firstnameE;-ove; (/ lastnameE;Svendson; *esult: LastName Svendson Svendson (/am$le Iou can also combine AN% and (/ (use parent"eses to form complex expressions 4 S+L+,- > 9/(# .ersons 01+/+ (9irstNameE;-ove; (/ 9irstNameE;Step"en; AN% LastNameE;Svendson; *esult: LastName Svendson Svendson FirstName -ove Step"en ddress &orgvn '7 8aivn 5C !it" Sandnes Sandnes FirstName -ove Step"en ddress &orgvn '7 8aivn 5C !it" Sandnes Sandnes

55

SQL

SQL IN IN -"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. S+L+,- column=name 9/(# table=name 01+/+ column=name IN (value5,value'$.. +ri%inal Table &used in the e/am$les' LastName 1ansen Nordmann .ettersen Svendson (/am$le 7 -o display t"e persons wit" LastName equal to 31ansen3 or 3.ettersen3$ use t"e following SQL4 S+L+,- > 9/(# .ersons 01+/+ LastName IN (;1ansen;$;.ettersen; *esult: LastName 1ansen .ettersen SQL B(TW((N B(TW((N ... ND -"e &+-0++N ... AN% operator selects a range of data between two values. -"ese values can be numbers$ text$ or dates. S+L+,- column=name 9/(# table=name 01+/+ column=name &+-0++N value5 AN% value' +ri%inal Table &used in the e/am$les' LastName 1ansen Nordmann .ettersen Svendson (/am$le 7 FirstName (la Anna 8ari -ove ddress -imoteivn 56 Neset 5C Storgt '6 &orgvn '7 !it" Sandnes Sandnes Stavanger Sandnes FirstName (la 8ari ddress -imoteivn 56 Storgt '6 !it" Sandnes Stavanger FirstName (la Anna 8ari -ove ddress -imoteivn 56 Neset 5C Storgt '6 &orgvn '7 !it" Sandnes Sandnes Stavanger Sandnes

5'

SQL

-o display t"e persons alp"abetically between (and including 31ansen3 and exclusive 3.ettersen3$ use t"e following SQL4 S+L+,- > 9/(# .ersons 01+/+ LastName &+-0++N ;1ansen; AN% ;.ettersen; *esult: LastName 1ansen Nordmann FirstName (la Anna ddress -imoteivn 56 Neset 5C !it" Sandnes Sandnes

I#)+*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 (/am$le 9 -o display t"e persons outside t"e range used in t"e previous example$ use t"e N(- operator4 S+L+,- > 9/(# .ersons 01+/+ LastName N(- &+-0++N ;1ansen; AN% ;.ettersen; *esult: LastName .ettersen Svendson SQL liases 0it" SQL$ aliases can be used for column names and table names. !olumn Name lias -"e syntax is4 S+L+,- column AS column=alias 9/(# table Table Name lias -"e syntax is4 S+L+,- column 9/(# table AS table=alias (/am$le: Usin% a !olumn lias -"is table (.ersons 4 FirstName 8ari -ove ddress Storgt '6 &orgvn '7 !it" Stavanger Sandnes

57

SQL

LastName 1ansen Svendson .ettersen And t"is SQL4

FirstName (la -ove 8ari

ddress -imoteivn 56 &orgvn '7 Storgt '6

!it" Sandnes Sandnes Stavanger

S+L+,- LastName AS 9amily$ 9irstName AS Name 9/(# .ersons /eturns t"is result4 Famil" 1ansen Svendson .ettersen (/am$le: Usin% a Table lias -"is table (.ersons 4 LastName 1ansen Svendson .ettersen And t"is SQL4 S+L+,- LastName$ 9irstName 9/(# .ersons AS +mployees FirstName (la -ove 8ari ddress -imoteivn 56 &orgvn '7 Storgt '6 !it" Sandnes Sandnes Stavanger Name (la -ove 8ari

/eturns t"is result4 -able +mployees4 LastName 1ansen Svendson .ettersen SQL :oin :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. FirstName (la -ove 8ari

5@

SQL

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

(m$lo"ees4 (m$lo"ee;ID 65 6' 67 6@ +rders: )rod;ID '7@ AHB CAH )roduct .rinter -able ,"air (m$lo"ee;ID 65 67 67 Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari

*e,errin% to T1o Tables 0e can select data from two tables by referring to two tables$ li!e t"is4 (/am$le 0"o "as ordered a product$ and w"at did t"ey order? S+L+,- +mployees.Name$ (rders..roduct 9/(# +mployees$ (rders 01+/+ +mployees.+mployee=I%E(rders.+mployee=I% *esult Name 1ansen$ (la Svendson$ Step"en Svendson$ Step"en )roduct .rinter -able ,"air

5H

SQL

(/am$le 0"o ordered a printer? S+L+,- +mployees.Name 9/(# +mployees$ (rders 01+/+ +mployees.+mployee=I%E(rders.+mployee=I% AN% (rders..roductE;.rinter; *esult Name 1ansen$ (la Usin% :oins (/ we can select data from two tables wit" t"e L(IN !eyword$ li!e t"is4 (/am$le INN(* :+IN S"nta/ S+L+,- field5$ field'$ field7 9/(# first=table INN+/ L(IN second=table (N first=table.!eyfield E second=table.foreign=!eyfield 0"o "as ordered a product$ and w"at did t"ey order? S+L+,- +mployees.Name$ (rders..roduct 9/(# +mployees INN+/ L(IN (rders (N +mployees.+mployee=I%E(rders.+mployee=I% -"e INN+/ L(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 (/am$le L(FT :+IN S"nta/ S+L+,- field5$ field'$ field7 9/(# first=table L+9- L(IN second=table (N first=table.!eyfield E second=table.foreign=!eyfield )roduct .rinter -able ,"air

5A

SQL

List all employees$ and t"eir orders < if any. S+L+,- +mployees.Name$ (rders..roduct 9/(# +mployees L+9- L(IN (rders (N +mployees.+mployee=I%E(rders.+mployee=I% -"e L+9- L(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 (/am$le *I<2T :+IN S"nta/ S+L+,- field5$ field'$ field7 9/(# first=table /I:1- L(IN second=table (N first=table.!eyfield E second=table.foreign=!eyfield List all orders$ and w"o "as ordered < if any. S+L+,- +mployees.Name$ (rders..roduct 9/(# +mployees /I:1- L(IN (rders (N +mployees.+mployee=I%E(rders.+mployee=I% -"e /I:1- L(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 (/am$le 0"o ordered a printer? S+L+,- +mployees.Name )roduct .rinter -able ,"air -able ,"air )roduct .rinter

5B

SQL

9/(# +mployees INN+/ L(IN (rders (N +mployees.+mployee=I%E(rders.+mployee=I% 01+/+ (rders..roduct E ;.rinter; *esult Name 1ansen$ (la SQL UNI+N and UNI+N LL UNI+N -"e )NI(N command is used to select related information from two tables$ muc" li!e t"e L(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. SQL Statement 5 )NI(N SQL Statement ' (m$lo"ees;Nor1a"4 (m$lo"ee;ID 65 6' 67 6@ (m$lo"ees;US 4 (m$lo"ee;ID 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

Usin% the UNI+N !ommand (/am$le List all different employee names in Norway and )SA4 S+L+,- +=Name 9/(# +mployees=Norway )NI(N S+L+,- +=Name 9/(# +mployees=)SA *esult

5C

SQL

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. UNI+N LL -"e )NI(N ALL command is equal to t"e )NI(N command$ except t"at )NI(N ALL selects all values. SQL Statement 5 )NI(N ALL SQL Statement ' Usin% the UNI+N LL !ommand (/am$le List all employees in Norway and )SA4 S+L+,- +=Name 9/(# +mployees=Norway )NI(N ALL S+L+,- +=Name 9/(# +mployees=)SA *esult Name 1ansen$ (la Svendson$ -ove Svendson$ Step"en .ettersen$ 8ari -urner$ Sally 8ent$ ,lar! Svendson$ Step"en Scott$ Step"en SQL !reate Database= Table= and Inde/ !reate a Database -o create a database4
5D

SQL

,/+A-+ %A-A&AS+ database=name !reate a Table -o create a table in a database4 ,/+A-+ -A&L+ table=name ( column=name5 data=type$ column=name' data=type$ .......

(/am$le -"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 ,/+A-+ -A&L+ .erson ( LastName varc"ar$ 9irstName varc"ar$ Address varc"ar$ Age int -"is example demonstrates "ow you can specify a maximum lengt" for some columns4 ,/+A-+ -A&L+ .erson ( LastName varc"ar(76 $ 9irstName varc"ar$ Address varc"ar$ Age int(7 -"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 T"$e integer(siMe int(siMe smallint(siMe tinyint(siMe decimal(siMe$d numeric(siMe$d c"ar(siMe varc"ar(siMe Descri$tion 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 3siMe3. -"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 siMe is specified in parent"esis. 1olds a variable lengt" string (can contain letters$ numbers$ and special c"aracters . -"e maximum siMe is specified in parent"esis.

'6

SQL

date(yyyymmdd !reate Inde/

1olds a date

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 Inde/ ,reates a unique index on a table. A unique index means t"at two rows cannot "ave t"e same index value. ,/+A-+ )NIQ)+ IN%+N index=name (N table=name (column=name -"e 3column=name3 specifies t"e column you want indexed. Sim$le Inde/ ,reates a simple index on a table. 0"en t"e )NIQ)+ !eyword is omitted$ duplicate values are allowed. ,/+A-+ IN%+N index=name (N table=name (column=name -"e 3column=name3 specifies t"e column you want indexed. (/am$le -"is example creates a simple index$ named 3.ersonIndex3$ on t"e LastName field of t"e .erson table4 ,/+A-+ IN%+N .ersonIndex (N .erson (LastName If you want to index t"e values in a column in descendin% order$ you can add t"e reserved word D(S! after t"e column name4 ,/+A-+ IN%+N .ersonIndex (N .erson (LastName %+S, 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 ,/+A-+ IN%+N .ersonIndex (N .erson (LastName$ 9irstName SQL Dro$ Inde/= Table and Database Dro$ Inde/ Iou can delete an existing index in a table wit" t"e %/(. statement. %/(. IN%+N table=name.index=name

'5

SQL

Delete a Table or Database -o delete a table (t"e table structure$ attributes$ and indexes will also be deleted 4 %/(. -A&L+ table=name -o delete a database4 %/(. %A-A&AS+ database=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 -/)N,A-+ -A&L+ table=name SQL LT(* T BL( LT(* T BL( -"e AL-+/ -A&L+ statement is used to add or drop columns in an existing table. AL-+/ -A&L+ table=name A%% column=name datatype AL-+/ -A&L+ table=name %/(. ,(L)#N column=name Note: Some database systems don;t allow t"e dropping of a column in a database table (%/(. ,(L)#N column=name . )erson: LastName .ettersen (/am$le -o add a column named 3,ity3 in t"e 3.erson3 table4 AL-+/ -A&L+ .erson A%% ,ity varc"ar(76 *esult: LastName .ettersen (/am$le -o drop t"e 3Address3 column in t"e 3.erson3 table4 AL-+/ -A&L+ .erson %/(. ,(L)#N Address *esult: FirstName 8ari ddress Storgt '6 !it" FirstName 8ari ddress Storgt '6

''

SQL

LastName .ettersen SQL Functions

FirstName 8ari

!it"

SQL "as a lot of built<in functions for counting and calculations. Function S"nta/ -"e syntax for built<in SQL functions is4 S+L+,- function(column 9/(# table T"$es o, Functions -"ere are several basic types and categories of functions in SQL. -"e basic types of functions are4

Aggregate 9unctions Scalar functions

%%re%ate ,unctions 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/am$les' Name 1ansen$ (la Svendson$ -ove .ettersen$ 8ari %%re%ate ,unctions in #S ccess Function AK:(column ,()N-(column ,()N-(> 9I/S-(column LAS-(column #AN(column #IN(column S-%+K(column S-%+K.(column S)#(column /eturns t"e total sum of a column Descri$tion /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 t"e specified field /eturns t"e value of t"e last record in t"e specified field /eturns t"e "ig"est value of a column /eturns t"e lowest value of a column %e 7@ @H 5D

'7

SQL

KA/(column KA/.(column %%re%ate ,unctions in SQL Ser5er Function AK:(column &INA/I=,1+,8S)# ,1+,8S)# ,1+,8S)#=A:: ,()N-(column ,()N-(> ,()N-(%IS-IN,- column 9I/S-(column LAS-(column #AN(column #IN(column S-%+K(column S-%+K.(column S)#(column KA/(column KA/.(column Scalar ,unctions Scalar functions operate against a single value$ and return a single value based on t"e input value. Use,ul Scalar Functions in #S ccess Function ),AS+(c L,AS+(c #I%(c$startO$endP L+N(c INS-/(c L+9-(c$number=of=c"ar /I:1-(c$number=of=c"ar /()N%(c$decimals #(%(x$y Descri$tion ,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 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 t"e specified field (not supported in SQLServer'8 /eturns t"e value of t"e last record in t"e specified field (not supported in SQLServer'8 /eturns t"e "ig"est value of a column /eturns t"e lowest value of a column Descri$tion /eturns t"e average value of a column

'@

SQL

N(0( 9(/#A-(c$format %A-+%I99(d$date5$date' SQL <*+U) B3 and 2 ?IN<

/eturns t"e current system date ,"anges t"e way a field is displayed )sed to perform date calculations

Aggregate functions (li!e S)# often need an added :/(). &I functionality. <*+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 S+L+,- column$S)#(column 9/(# table :/(). &I column <*+U) B3 (/am$le -"is 3Sales3 -able4 !om$an" 07Sc"ools I&# 07Sc"ools And -"is SQL4 S+L+,- ,ompany$ S)#(Amount 9/(# Sales /eturns t"is result4 !om$an" 07Sc"ools I&# 07Sc"ools SU#& mount' 5B566 5B566 5B566 mount HH66 @H66 B566

-"e above code is invalid because t"e column returned is not part of an aggregate. A :/(). &I clause will solve t"is problem4 S+L+,- ,ompany$S)#(Amount 9/(# Sales :/(). &I ,ompany /eturns t"is result4 !om$an" 07Sc"ools I&# 2 ?IN<... SU#& mount' 5'A66 @H66

'H

SQL

1AKIN:... was added to SQL because t"e 01+/+ !eyword could not be used against aggregate functions (li!e S)# $ and wit"out 1AKIN:... it would be impossible to test for result conditions. -"e syntax for t"e 1AKIN: function is4 S+L+,- column$S)#(column 9/(# table :/(). &I column 1AKIN: S)#(column condition value -"is 3Sales3 -able4 !om$an" 07Sc"ools I&# 07Sc"ools -"is SQL4 S+L+,- ,ompany$S)#(Amount 9/(# Sales :/(). &I ,ompany 1AKIN: S)#(Amount G56666 /eturns t"is result !om$an" 07Sc"ools SQL The S(L(!T INT+ Statement The S(L(!T INT+ Statement -"e S+L+,- IN-( statement is most often used to create bac!up copies of tables or for arc"iving records. S"nta/ S+L+,- column=name(s IN-( newtable OIN externaldatabaseP 9/(# source #a0e a Bac0u$ !o$" -"e following example ma!es a bac!up copy of t"e 3.ersons3 table4 S+L+,- > IN-( .ersons=bac!up 9/(# .ersons -"e IN clause can be used to copy tables into anot"er database4 S+L+,- .ersons.> IN-( .ersons IN ;&ac!up.mdb; 9/(# .ersons If you only want to copy a few fields$ you can do so by listing t"em after t"e S+L+,- statement4 S+L+,- LastName$9irstName IN-( .ersons=bac!up 9/(# .ersons SU#& mount' 5'A66 mount HH66 @H66 B566

'A

SQL

Iou can also add a w"ere clause. -"e following example creates a 3.ersons=bac!up3 table wit" two columns (9irstName and LastName by extracting t"e persons w"o lives in 3Sandnes3 from t"e 3.ersons3 table4 S+L+,- LastName$9irstname IN-( .ersons=sandnes 9/(# .ersons 01+/+ ,ityE;Sandnes; Selecting data from more t"an one table is also possible. -"e following example creates a new table 3+mpl=(rd=bac!up3 t"at contains data from t"e two tables +mployees and (rders4 S+L+,- +mployees.Name$(rders..roduct IN-( +mpl=(rd=bac!up 9/(# +mployees INN+/ L(IN (rders (N +mployees.+mployee=I%E(rders.+mployee=I%

'B

Anda mungkin juga menyukai