Professional Documents
Culture Documents
What Is SQL?: SQL Is A Standard Computer Language For Accessing and Manipulating Databases
What Is 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
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
SQL
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
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
LastName 1ansen Svendson .ettersen The result LastName 1ansen Svendson .ettersen
The S(L(#T
*ST*N#T Statement
-"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
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
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(
Using L*4(
-"e following SQL statement will return persons wit" first names t"at start wit" an ;(;4
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
-"is 3.ersons3 table4 LastName .ettersen 1etland !irstName 8ari ,amilla "ddress Storgt '6 1agaba!!a '? #it$ Stavanger Sandnes
0ill give t"is result4 LastName .ettersen 1etland /asmussen !irstName 8ari ,amilla "ddress Storgt '6 1agaba!!a '? Storgt @A #it$ Stavanger Sandnes
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
7PD6TE Person SET FirstName ' (Nina( $%ERE LastName ' (Rasmussen(
+esult: LastName Nilsen /asmussen !irstName 9red Nina "ddress 8ir!egt G@ Storgt @A #it$ Stavanger
7PD6TE Person SET 6##ress ' (Stien /8(, Cit" ' (Sta&an,er( $%ERE LastName ' (Rasmussen(
+esult: LastName !irstName "ddress #it$
Nilsen /asmussen
9red Nina
Stavanger Stavanger
The
(L(T( Statement
)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
07Sc"ools 07Sc"ools
'75' @ACB
(.ample
-o display t"e company names in alp"abetical order4
(.ample
-o display t"e company names in alp"abetical order AN% t"e (rderNumber in numerical order4
(.ample
-o display t"e company names in reverse alp"abetical order4
(.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
(.ample
)se AN% to display eac" person wit" t"e first name equal to 3-ove3$ and t"e last name equal to 3Svendson34
(.ample
)se (/ to display eac" person wit" t"e first name equal to 3-ove3$ or t"e last name equal to 3Svendson34
(.ample
Iou can also combine AN% and (/ (use parent"eses to form complex expressions)4
*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
(.ample 7
-o display t"e persons wit" LastName equal to 31ansen3 or 3.ettersen3$ use t"e following SQL4
SELECT column_name FROM ta le_name $%ERE column_name =ET$EEN &alue/ 6ND &alue8
(.ample 7
-o display t"e persons alp"abetically between (and including) 31ansen3 and exclusive 3.ettersen3$ use t"e following SQL4
*%),+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
-"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
65 67 67
(.ample
0"o "as ordered a product$ and w"at did t"ey order>
(.ample
0"o ordered a printer>
Using :oins
(/ we can select data from two tables wit" t"e K(IN !eyword$ li!e t"is4
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
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
(.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
(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
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
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
#reate a Table
-o create a table in a database4
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
" Simple *nde. ,reates a simple index on a table 0"en t"e )NIQ)+ !eyword is omitted$ duplicate values are allowed
(.ample
-"is example creates a simple index$ named 3.ersonIndex3$ on t"e LastName field of t"e .erson table4
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
elete a Table or
atabase
-o delete a table (t"e table structure$ attributes$ and indexes will also be deleted)4
Truncate a Table
0"at if we only want to get rid of t"e data inside a table$ and not t"e table itself> )se t"e -/)N,A-+ -A&L+ command (deletes only t"e data inside t"e table)4
"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)
(.ample
-o add a column named 3,ity3 in t"e 3.erson3 table4
(.ample
-o drop t"e 3Address3 column in t"e 3.erson3 table4
!unction S$nta.
-"e syntax for built<in SQL functions is4
T$pes of !unctions
-"ere are several basic types and categories of functions in SQL -"e basic types of functions are4
"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
Scalar functions
Scalar functions operate against a single value$ and return a single value based on t"e input value
<+,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
<+,U) B3 (.ample
-"is 3Sales3 -able4 #ompan$ 07Sc"ools I&# 07Sc"ools And -"is SQL4 "mount GG66 ?G66 A566
-"e above code is invalid because t"e column returned is not part of an aggregate A :/(). &I clause will solve t"is problem4
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
S$nta. SELECT column_name(s) INTO ne+ta le FIN eEternal#ata aseG FROM source
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 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
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
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