SQL Basics2

download SQL Basics2

of 32

Transcript of SQL Basics2

  • 8/11/2019 SQL Basics2

    1/32

  • 8/11/2019 SQL Basics2

    2/32

    ommon SQL Questions'onstandard SQLSynta# Summary-#ercisesmportant Links

    Basics of the SELECT Statement

    n a relational database, data is stored in tables! %n e#ample table would relate SocialSecurity 'umber, 'ame, and %ddress?@ABC=A 2oe Smith AD 7irst Street :oward "hio

    B=AC?EE>? $ary Scott AC? 8ine %ve! Losantiville "hio

    >E??=CAF@ Sam 2ones DD -lm St! 3aris 'ew *ork

    AB@=>?=@D Sarah %ckerman CCE 0!S! >>E 0pton $ichigan

    'ow, letGs say you want to see the address of each employee! 0se the S-L-T statement,like so=EEE $anager

    >=? @EEEE >=EEE $anager ?>= @EEEE >?=EE $anager

    ?CC =EEEE >?EEE Staff

    DEE C=EEE >EEEE Staff

    DD= CEEEE >EEEE Staff

    CEE D?EEE B=EE -ntryILevel

    CC> ?AEEE B=EE -ntryILevel

    "elational #perators

    There are si# .elational "perators in SQL, and after introducing them, weGll see howtheyGre usedE,EEE in benefits, listed together, use the following 6uery 2ones ill

    E? Smith ob

    >= Lawson 3atricia

    ?> %kins 2ane

    =E 7owler Sam

    #rders

    #(nerI Itemesired

    E? Table

    E? 4esk

    ?> hair

  • 8/11/2019 SQL Basics2

    7/32

    >= $irror

    Anti'ues

    SellerI BuyerI Item

    E> =E ed

    E? >= Table>= E? hair

    ?> =E $irror

    =E E> 4esk

    E> ?> abinet

    E? ?> offee Table

    >= =E hair

    E> >= 2ewelry o#

    E? ?> 3ottery

    ?> E? ookcase

    =E E> 3lant Stand

    )eys

    7irst, letGs discuss the concept of #eys! %$rimary #eyis a column or set of columns thatuni6uely identifies the rest of the data in any given row! 7or e#ample, in the%nti6ue"wners table, the "wner4 column uni6uely identifies that row! This means twothings< no two rows can have the same "wner4, and, even if two owners have the samefirst and last names, the "wner4 column ensures that the two owners will not beconfused with each other, because the uni6ue "wner4 column will be used throughoutthe database to track the owners, rather than the names!

    %%oreign #eyis a column in a table where that column is a primary key of another table,

    which means that any data in a foreign key column must have corresponding data in theother table where that column is the primary key! n 4$SIspeak, this correspondence isknown as re%erential integrity! 7or e#ample, in the %nti6ues table, both the uyer4 andSeller4 are foreign keys to the primary key of the %nti6ue"wners table ("wner4H forpurposes of argument, one has to be an %nti6ue "wner before one can buy or sell anyitems), as, in both tables, the 4 rows are used to identify the owners or buyers andsellers, and that the "wner4 is the primary key of the %nti6ue"wners table! n otherwords, all of this &4& data is used to refer to the owners, buyers, or sellers of anti6ues,themselves, without having to use the actual names!

    !erforming a &oin

    The purpose of these #eysis so that data can be related across tables, without having torepeat data in every tableIIthis is the power of relational databases! 7or e#ample, you canfind the names of those who bought a chair without having to list the full name of thebuyer in the %nti6ues table!!!you can get the name by relating those who bought a chairwith the names in the %nti6ue"wners table through the use of the "wner4, whichrelatesthe data in the two tables! To find the names of those who bought a chair, use thefollowing 6uery

  • 8/11/2019 SQL Basics2

    8/32

    SELECT O%NERLASTNAME, O%NERF"RSTNAME

    FROM ANT"9:EO%NERS, ANT"9:ES

    %&ERE $:!ER"# ( O%NER"# AN# "TEM ( /Cair/;

    'ote the following about this 6uery!!!notice that both tables involved in the relation arelisted in the 7."$ clause of the statement! n the W:-.- clause, first notice that the

    T-$ J GhairG part restricts the listing to those who have bought (and in this e#ample,thereby own) a chair! Secondly, notice how the 4 columns are related from one table tothe ne#t by use of the 0*-.4 J "W'-.4 clause! "nly where 4Gs match acrosstables and the item purchased is a chair (because of the %'4), will the names from the%nti6ue"wners table be listed! ecause the oining condition used an e6ual sign, this oinis called an equi"oin! The result of this 6uery is two names< Smith, ob / 7owler, Sam!

    Dot notationrefers to prefi#ing the table names to column names, to avoid ambiguity, asfollows?=EE!

    SELECT CO:NT4*5

    FROM EMLO!EESTAT"ST"CSTA$LE

    %&ERE OS"T"ON ( /Sta11/;

    This 6uery tells you how many employees have Staff status (D)!

    -ie(s

    n SQL, you might (check your 4%) have access to create views for yourself! What aview does is to allow you to assign the results of a 6uery to a new, personal table, thatyou can use in other 6ueries, where this new table is given the view name in your 7."$clause! When you access a view, the 6uery that is defined in your view creation statement

  • 8/11/2019 SQL Basics2

    11/32

    is performed (generally), and the results of that 6uery look ust like another table in the6uery that you wrote invoking the view! 7or e#ample, to create a view"E% ANT>"E% AS SELECT "TEM#ES"RE# FROM OR#ERS;

    'ow, write a 6uery using this view as a table, where the table is ust a listing of all tems4esired from the "rders table"E%

    %&ERE "TEM#ES"RE# ( "TEM;

    This 6uery shows all Seller4Gs from the %nti6ues table where the tem in that tablehappens to appear in the %ntview view, which is ust all of the tems 4esired in the"rders table! The listing is generated by going through the %nti6ue tems oneIbyIoneuntil thereGs a match with the %ntview view! 8iews can be used to restrict database access,as well as, in this case, simplify a comple# 6uery!

    Creating Ne( Tables

    %ll tables within a database must be created at some point in time!!!letGs see how wewould create the "rders tableAL:ES 4-, , /Ottoman/, -.5;This inserts the data into the table, as a new row, columnIbyIcolumn, in the preIdefinedorder! nstead, letGs change the order and leave 3rice blankAL:ES 4, -, /Ottoman/5;

    eleting ata

    LetGs delete this new row back out of the database"N? R"CE ' ;

    ,ore S-./-eries

    %nother common usage of sub6ueries involves the use of operators to allow a Wherecondition to include the Select output of a sub6uery! 7irst, list the buyers who purchasedan e#pensive item (the 3rice of the item is M>EE greater than the average price of all itemspurchased)! Why canGt ust ask for the first three rows in a table IIecause in relationaldatabases, rows are inserted in no particular order, that is, the system inserts themin an arbitrary orderH so, you can only re6uest rows using valid SQL features, like".4-. *, etc!

    ?! What is this 44L and 4$L hear about II44L (4ata 4efinition Language)refers to (in SQL) the reate Table statement!!!4$L (4ata $anipulationLanguage) refers to the Select, 0pdate, nsert, and 4elete statements! %lso, Q$L,referring to Select statements, stands for Query $anipulation Language!

    D! %renGt database tables ust files IIWell, 4$SGs store data in files declared by

    system managers before new tables are created (on large systems), but the systemstores the data in a special format, and may spread data from one table overseveral files! n the database world, a set of files created for a database is called ata)les$ace! n general, on small systems, everything about a database (definitionsand all table data) is kept in one file!

    C! (.elated 6uestion) %renGt database tables ust like spreadsheets II'o, for tworeasons! 7irst, spreadsheets can have data in a cell, but a cell is more than ust a

  • 8/11/2019 SQL Basics2

    19/32

    rowIcolumnIintersection! 4epending on your spreadsheet software, a cell mightalso contain formulas and formatting, which database tables cannot have(currently)! Secondly, spreadsheet cells are often dependent on the data in othercells! n databases, &cells& are independent, e#cept that columns are logicallyrelated (hopefullyH together a row of columns describe an entity), and, other than

    primary key and foreign key constraints, each row in a table is independent fromone another!

    =! :ow do import a te#t file of data into a database IIWell, you canGt do itdirectly!!!you must use a utility, such as "racleGs SQLPLoader, or write a programto load the data into the database! % program to do this would simply go througheach record of a te#t file, break it up into columns, and do an nsert into thedatabase!

    @! What web sites and computer books would you recommend for more informationabout SQL and databases II7irst, look at the sites at the bottom of this page! would especially suggest the following< 4 ngredients(more theorical topics),4$S Lab5Links(comprehensive academic 4$S link listing), Tutorial 3age

    (listing of other tutorials), and miniSQL(more information about the best knownfree 4$S)!

    %lso, if you wish to practice SQL on an interactive site (using 2ava technologies), highly recommend 7rank TorresG (torresfRuswest!net) site athttp

  • 8/11/2019 SQL Basics2

    20/32

    conditional output based on the value of a column or function! The synta# lookslike this (from the "racle< omplete .eference series)alue, "1, Ten, "1 -, Ten -, ...,

    Else5 ...From ...;

    The 8alue is the name of a column, or a function (conceivably based on a column

    or columns), and for each f included in the statement, the corresponding Thenclause is the output if the condition is true! f none of the conditions are true, thenthe -lse value is output! LetGs look at an e#ampleG to anothervalue, those Seller 4 values would be updated to that new value too!

    >E! Show me an e#ample of an outer "oin.IIWell, from the 6uestions receive, this isan e#tremely common e#ample, and Gll show you both the "racle and %ccess6ueries!!!

    Think of the following -mployee table (the employees are given numbers, forsimplicity)E

    ?E

    DE

    CE

    'ow suppose you want to oin the tables, seeing all of the employees and all ofthe departments together!!!youGll have to use an outer oin which includes a nullemployee to go with 4ept! CE!

    n the book, &"racle B< the omplete .eference&, about outer oins, &think of the(), which must immediately follow the oin column of the table, as saying add ane#tra (null) row anytime thereGs no match&! So, in "racle, try this 6uery (the goes on -mployee, which adds the null row on no match) 2ones ill E? Table

    E> 2ones ill E? 4esk

    E> 2ones ill ?> hair

    E> 2ones ill >= $irror

    E? Smith ob E? Table

    E? Smith ob E? 4esk

    E? Smith ob ?> hair

    E? Smith ob >= $irror

    >= Lawson 3atricia E? Table

    >= Lawson 3atricia E? 4esk

    >= Lawson 3atricia ?> hair

    >= Lawson 3atricia >= $irror

    ?> %kins 2ane E? Table

    ?> %kins 2ane E? 4esk

    ?> %kins 2ane ?> hair ?> %kins 2ane >= $irror

    =E 7owler Sam E? Table

    =E 7owler Sam E? 4esk

    =E 7owler Sam ?> hair

    =E 7owler Sam >= $irror

    The number of rows in the result has the number of rows in the first table timesthe number of rows in the second table, and is sometimes called a rossI2oin!

    f you think about it, you can see how oins work! Look at the artesian productresults, then look for rows where the "wner4Gs are e6ual, and the result is what

    you would get on an e6uioin!"f course, this is not how 4$SGs actually perform oins because loading thisresult can take too much memoryH instead, comparisons are performed in nestedloops, or by comparing values in inde#es, and then loading result rows!

    >D! What isRelational Alge)ra II.elational %lgebra is the mathematical notationused to describe relational database theory, and to rigorously define a 6uery! tsuggests an algorithm used to perform a 6uery, but does not necessary correspond

  • 8/11/2019 SQL Basics2

    24/32

    to SQL, or represent optimiNed code needed to actually run the 6uery! t is sort ofa mental approach to solve a 6uery problem, by forcing the programmer to thinkin terms of sets of rows! n fact, many of the functions described in the followingrelational algebraic operations table are similar to regular set operations!

    When first learned relational databases, didnGt start with SQL! nstead,

    learned to write all my definitions (Table'ame olumn%, olumn, !!!X) and6ueries in relational algebraic notation! t forces one to think of getting the 6ueryresults one wants by set inclusion and e#clusion! $any college courses indatabases start with this topic! n the e#amples, consider two new tables,%nti6ues> and %nti6ues?, defined the same as %nti6ues!

    #peration efinition E0ample

    .ename.ename Table %ttribute(olumn)

    ren"wner4I"wn4(%nti6ue"wners)

    0nionnclude all rows from twosimilarly defined tables intoone table (append operation)

    %nti6ues> 0 %nti6ues?

    ntersection

    List rows where the e#actsame row appears in twosimlarly defined tables (actualsymbol is upsideIdown &0&)

    %nti6ues> intersection%nti6ues?

    4ifference

    9ive all rows in one table thatdo not appear in anothersimilarly defined table(similar to a left5right outeroin)

    %nti6ues> I %nti6ues?

    artesian 3roduct See Y>? above %nti6ue"wners ; "rders

    3roection Select certain attributes from atable or view, showing allrows

    $ro""wner4, "wnerLast'ame(%nti6ue"wners)

    SelectionShow certain rows specifiedby a where condition

    selSeller4 J &E>& ". Seller4 J &E?&(%nti6ues)

    -6uiI2oin

    2oin on an e6ual condition (aspreviously stated, this conceptcan be e#pressed by taking theartesian 3roduct and pickingout the rows where thespecified key attributes are

    e6ual)

    %nti6ue"wners equi,"oin"wner4 JSeller4%nti6ues

    'atural 2oin

    3erform an e6uiIoin, but donot return both of the oincolumnsH the e#ample doesnot give the "wner4 columnfrom the %nti6ue"wnerstable!

    "rders nat,"oin%nti6ue"wners

    Theta 2oin 2oin on any operation (J, K, %nti6ue"wners t*eta,"oin"wner4 K

  • 8/11/2019 SQL Basics2

    25/32

    K, , KJ, J), thoughgenerally performed onnumeric attributes!

    Seller4%nti6ues

    SemiIoin

    3erform a oin, but ust showcolumns from one table, and

    include nulls, like in the outeroin from Y>E!

    -mployee le%t,semi,"oin-mployee!4epartment J 4epartment!4epartment

    4epartment

    % oin 6uery such asanced %sers #nly

    :ere are the general forms of the statements discussed in this tutorial, plus some e#traimportant ones (e#planations given)! "E,E,BE"that all of these statements may ormay not be available on your system, so check documentation regarding availability"N? 2CON#"T"ON'

    OR#ER $! 2OR#ER"N? COL:MN4S5' ASCV#ESC; IIwhere %S[4-S allows the

    ordering to be done in %Sending or 4-Sending order

    U!DATE2TA$LE NAME'

    SET 2COL:MN NAME' ( 2>AL:E'

    %&ERE 2CON#"T"ON'; IIif the Where clause is left out, all rows will be updated

    according to the Set statement!

    E$ercises

    Queries0sing the e#ample tables in the tutorial, write a SQL statement to! Show each %nti6ues order and the last and first names of the person who ordered the

  • 8/11/2019 SQL Basics2

    31/32

    item!?! Show each column in the -mployeeStatisticsTable in alphabetical order by 3osition,then by -mployee4'o!D! Show the annual budget for enefits from the -mployeeStatisticsTable!C! 0sing the ' "perator, show the names of the owners of hairs!

    =! Show the names of all %nti6ues "wners who have do not have an order placed!@! Show the names of those who have placed %nti6ue orders, with no duplicates (:int)!F! reate a table called -mployees, with columns -mployee4'o (donGt worry abouttrailing Neroes), 7irst'ame, and Last'ame!>E! (hallenger) Show the annual budget for Salary by each position from the-mployeeStatisticsTable (:int< Try 9."03 *)!

    atabases

    >>! What is the relationship between the %nti6ue"wners table and the "wners table>?! f you do not have a primary key in a table, the addition of what type of column ispreferred to give the table a primary key>D! Which function will allow you to substitute a given value for any 'ull values arisingfrom a Select statement>C! When using -mbedded SQL, what do you need to create in order to iterate throughthe results of a multiIrow 6uery, one row at a time>=! f all of the columns in all of the tables in your schema are dependent solely on thevalue of the primary key in each table, in which 'ormal 7orm is your design>@! What term is used to describe the event of a database system automatically updatingthe values of foreign keys in other tables, when the value of a primary key is updated

    >B! What database obect provides fast access to the data in the rows of a table>A! What type of SQL statement is used to change the attributes of a column>F! n a reate Table statement, when a column is designated as '"T '0LL, what doesthis mean?E! f you wish to write a 6uery that is based on other 6ueries, rather than tables, what dothese other 6ueries need to be created as

    Ans"ers49ueries may aJe more tan one orret ans=er5. SELECT AntiGueO=ners.O=nerLastName, AntiGueO=ners.O=nerFirstName,

    Orders."tem#esired

    FROM AntiGueO=ners, Orders

    %&ERE AntiGueO=ners.O=ner"# ( Orders.O=ner"#;

    orSELECT AntiGueO=ners.O=nerLastName, AntiGueO=ners.O=nerFirstName,

    Orders."tem#esiredFROM AntiGueO=ners R"?&T DO"N Orders ON AntiGueO=ners.O=ner"# (

    Orders.O=ner"#;

    -. SELECT *

    FROM EmployeeStatistisTable

    OR#ER $! osition, Employee"#No;

  • 8/11/2019 SQL Basics2

    32/32

    6. SELECT Sum4$ene1its5

    FROM EmployeeStatistisTable;

    . SELECT O=nerLastName, O=nerFirstName

    FROM AntiGueO=ners, AntiGues

    %&ERE "tem "n 4/Cair/5

    AN# AntiGueO=ners.O=ner"# ( AntiGues.$uyer"#;). SELECT O=nerLastName, O=nerFirstName

    FROM AntiGueO=ners

    %&ERE O=ner"# NOT "N

    4SELECT O=ner"#

    FROM Orders5;

    3. SELECT #"ST"NCT O=nerLastName, O=nerFirstName

    FROM Orders, AntiGueO=ners

    %&ERE AntiGueO=ners.O=ner"# ( Orders.O=ner"#;

    or to use DO"N notationSELECT #"ST"NCT AntiGueO=ners.O=nerLastName,

    AntiGueO=ners.O=nerFirstNameFROM AntiGueO=ners R"?&T DO"N Orders ON AntiGueO=ners.O=ner"# (

    Orders.O=ner"#;

    X. #ELETE FROM OR#ERS

    %&ERE O%NER"# ( -;

    @. "NSERT "NTO OR#ERS >AL:ES 4-, /Roie=s.