Elementary Queries

Embed Size (px)

Citation preview

  • 8/22/2019 Elementary Queries

    1/53

    ELEMENTARY QUERIES

    Retrieving data from a table

    The SELECT command is used in SQL fro all forms of data retrieval. As such, it

    is a very powerful and versatile command, and it has a number of suclauses andvariations. It is, however, essentially a very simple command to use as allSELECT commands tae the same basic form. Informally, we can re!ard allSELECT commands as bein! structured thus"

    SELECT ### !ive a list of columns ###$%&' ### state the table (s) bein! used ###(*+E%E ### state any constraints on what is bein! retrieved###)

    As stated in Chapter -, relational databases store data in tables. *hen we uerya relational database, what we !et bac is a table. The purpose of the SELECT

    command is to build a table usin! data derived from the tables in a relationaldatabase.

    $or this reason, the first line in a select command is a list of columns. This linedescribes the columns that will appear in the result of our uery. The $%&' linestates the table/s0 that are reuired to service the uery. There is optionally a*+E%E line which places some sort of constraint on what is bein! retrieved.%ealistically, the vast ma1ority of SELECT commands include the *+E%Eclause.

    2sin! the T+E%A3ISTS table from C+A3TE% -, to retrieve a list of therapists

    and their numbers we would say"

    SELECT thno, name$%&' therapists

    !ivin! the result"

    T+4& 4A'E

    - 5r 6ray7 5r Lan!

    8 5r Crippen

    This is an unconstrained command, resultin! in all the rows from the !iven table.It is so happens that we have retrieved all of the columns from the !iven table.The same result would have been achieved by sayin!"

    SELECT #$%&' therapists

  • 8/22/2019 Elementary Queries

    2/53

    If we 1ust wanted to find out the names of the therapists, we would say"

    SELECT name$%&' therapists

    !ivin!"

    4A'E

    5r 6ray5r Lan!5r Crippen

    As stated above, the vast ma1ority of SQL commands will have some form ofconstraint placed on them. 2sers will usually wish to retrieve data from rows withparticular ualifyin! conditions. Suppose we wanted to find the therapist number

    for 5r Crippen. To discover this, we would say"

    SELECT thno$%&' therapists*+E%E name 9 :5r Crippen;

    !ivin!"

    T+4&

    8

    Such ueries could return a set of rows. $or instance, the uery"

    SELECT no, type$%&' members*+E%E surname 9 :Sharif;

    would !ive the result

    4& Tunior? >unior

    *e would !et this result as we have two members with the surname :Shari; bothof whom are of type :>unior;. The two rows in this result clearly refer to twodifferent members. +owever, had we said"

  • 8/22/2019 Elementary Queries

    3/53

    SELECT type$%&' members*+E%E surname 9 :Sharif;

    our result would have been"

    Tunior>unior

    Tables !enerated from SELECT commands that have duplicate rows are uitele!al. In fact, they can sometimes be uite result. The above result tells us thatthere must be two Sharifs on the members; list, both with the same type ofmembership. Sometimes we do not want to !et duplicate rows. $or instance,suppose we wished to arran!e a hocey match on a weeday. *e mi!ht want to

    chec our A@AILALE table to see if there was anyone able to play on aweeday. The uery"

    SELECT day$%&' available

    would !ive us

    5A3 6ettysbur!6 Li!htly

    which euates to the ri!ht answer.

    There are many other situations where nested ueries are reuired to provide theri!ht answer. These will be eamined in later chapters.

    T"e nested INSERT

    In the previous chapter, the use of I4SE%T for creatin! sin!le rows of data wasdemonstrated. I4SE%T can also be used for creatin! rows of data that arecopied from another table /or tables0. This is done by nestin! a SELECTcommand into the I4SE%T command.

    Suppose, for instance, we had access to a database table of potential players forour +ocey and Lacrosse Club, which had the columns 3L4&, 3L4A'E,TEL4& that euated to and have the same data type as the 4&, S2%4A'Eand TELE3+&4E4& columns in our 'E'E%S table. *e could copy this dataover thus"

    I4SE%T I4T& 'E'E%S /4&, S2%4A'E, TELE3+&4E4&0SELECT plno, plname, telno$%&' players

  • 8/22/2019 Elementary Queries

    16/53

    The nested SELECT command may itself have a 1oin, a further nested SELECTor a constraint. $or instance, if we wished to debar any players with the nameMEarnshaw;, we would say"

    I4SE%T I4T& 'E'E%S /4&, S2%4A'E, TELE3+&4E4&0

    SELECT plno, plname, telno$%&' players*+E%E plname D :Earnshaw;

    *hen two tables have a completely compatible set of columns, we can do astrai!htforward copy thus"

    I4SE%T I4T& %ETI%E5'E'E%SSELECT # $%&' 'E'E%S

    This would copy the entire 'E'E%S table into another table called

    %ETI%E5'E'E%S. This would wor as lon! as this other table had the samenumber of columns as the 'E'E%S table, and the data type of each'E'E%S column was compatible with the correspondin! column in the%ETI%E5'E'E%S table. y correspondin!, we mean the first column in onetable corresponds to the first column in another table, the second column to thesecond and so on. It is the column positions that correspond. They may havedifferent names.

    A further constraint on the successful eecution of inserts is the eistence ofprimary eys and uniue indees. Each of the commands above would fall if,amon!st the set of rows to be copied from one table to another, there eisted in

    the relevant correspondin! columns any values that represented a duplication ofprimary ey values or any other column values specified as bein! uniue in thetar!et table. $or instance, if there was any player whose 3L4& value replicated a4& value that already eisted in the 'E'E%S table, then the entire I4SE%Tcommand would fail.

    A !uard a!ainst this would be to etend the command thus"

    I4SE%T I4T& 'E'E%S /4&, S2%4A'E, TELE3+&4E4&0SELECT plno, plname, teleno$%&' players*+E%E plno 4&T I4

    /SELECT no $%&' 'E'E%S0

    This mi!ht result not all player rows bein! copied across. The user would alsoneed to issue the command.

    SELECT # $%&' 3LA

  • 8/22/2019 Elementary Queries

    17/53

    /SELECT no $%&' members0

    to discover who, if anyone, had not been copied.

    Altering data in tables

    *e have eamined until now how to enter and retrieve data from tables. In arealistic database, we would also wish to chan!e the content of tables by deletin!and alterin! data.

    #eleting ro$s

    In SQL, the 5ELETE command removes rows from tables. It is used thus"

    5ELETE $%&' ### table ###*+E%E ### rows meetin! some condition ###

    $or instance, if we wished to remove 5r. Crippen from our database, we wouldsay"

    5ELETE $%&' therapists*+E%E name 9 :5r Crippen;

    This command would remove the third row from the eample table of Therapists.

    The followin! command would remove two rows from the 'E'E%S table"

    5ELETE $%&' members*+E%E surname 9 :Sharif;

    This is because there are two rows that satisfy the !iven condition.

    *e mi!ht have decided to remove 5r Crippen from the database because hehad the misfortune to have illed off all of his patients. Thus, before issuin! thefirst 5ELETE command above, we could have said"

    5ELETE $%&' clients*+E%E clno I4

    /SELECT clno $%&' administration, therapists *+E%E therapists.thno 9 administration.thno and name 9 :5r Crippen;0

    This would have the effect of removin! all clients treated by 5r. Crippen. The*+E%E clause contains a nested SQL statement that yields the client numbers

  • 8/22/2019 Elementary Queries

    18/53

    of all patients whose administration record has a therapist number that matchesthat of 5r Crippen. This is done by performin! a conditional 1oin of

    A5'I4IST%ATI&4 and T+E%A3ISTS. Any patient whose CL4& is in theresultin! set is removed from the CLIE4TS table.

    The *+E%E line is optional in the 5ELETE command. The followin! commandhas no *+E%E clause and would thus have the effect of removin! all data fromthe !iven table"

    5ELETE $%&' clients

    The table would still, however, eist in the database. Complete removal wouldonly be achieved by the 5%&3 TALE command.

    C"anging ro$s

    The 235ATE command is used for chan!in! data values in tables.

    A simple 235ATE follows"

    235ATE membersSET surname 9 :+ari;*+E%E no 9 -

    This has the effect of chan!in! the surname of member 4& - from Swanson to+ari. This chan!es 1ust one row as there is only one row that meets this

    condition. *e can update a whole set of rows. $or instance, if we wished toredesi!nate the >unior title to Colt, we would say"

    235ATE membersSET type 9 :Colt;*+E%E type 9 :>unior;

    This would chan!e all rows with the value :>unior; for T

  • 8/22/2019 Elementary Queries

    19/53

    Sets of columns can be used in the 235ATE command. The followin! commandwould have the effect of settin! all members with the name :$ uniortype membership with the telephone number -78K=N"

    235ATE members

    SET type 9 :>unior; telephoneno 9 :-78K=N;*+E%E surname 9 :

  • 8/22/2019 Elementary Queries

    20/53

    SUMMARY

    -. The SQL SELECT command is used for all forms of data retrieval.7. The SELECT command builds tables usin! data from one or more tables

    within a database.

    8. Queries that reuire more than one table may be built usin! 1oins ornested ueries.. 4ested ueries can be used with I4SE%T to build rows usin! data from

    other tables.K. The 5ELETE command removes rows from tables.=. The 235ATE command chan!es data in tables. It can mae use of

    nested ueries in order to copy data from other tables or within tables.

    %IE&S

    *hat is views

    2p to this point in tet, we have been considerin! relational databases in terms ofbase table only.

    A base table is a representation of the data that is physically stored in a relationaldatabase. The data content of a relational database is the sum of all of its basetables. There is, however, another form of table in a relational database view.

    A view is a table that is derived from one or more other tables. It can be thou!ht

    of as a lo!ical table rather than a physical table. $or instance, with our'E'E%S table, there may be occasions where we only wish to deal with thesubset that represents senior members only. Such as subset would be thus"

    SE4I&%S4& I4IT S2%4A'E TELE3+&4E4& T

  • 8/22/2019 Elementary Queries

    21/53

    The view above has an element of redundancy. The T

  • 8/22/2019 Elementary Queries

    22/53

    C%I33E4SC&4S2LTA4CIESCLIE4T T%EAT'E4T

    5 6reen ody 5eodoriFation3 3an Emer!ency Liposuction

    *hy do we have views in a relational database +ere are some reasons statedinformally"

    Convenience. @iews may be re!arded as a form of shorthand for writin!

    ueries. In the SE4I&%S eample above, the SQL for retrievin! thisinformation usin! the base table would be"

    SELECT no, init, surname, telephoneno$%&' members*+E%E type 9 :Senior;

    2sin! the view, we would say"

    SELECT # $%&' Seniors

    *ith a view over a 1oin, the savin! in codin! effort is even more dramatic.Thus, views provide form of :macro; capability for an SQL pro!rammer.

    %ersatilit'. A lar!e database may have many different types of user, sharin!

    the same data but main! different uses of it. &ne representation of thedatabase may appear lo!ical and useful to one class of user but may be

    completely useless for another. y creatin! views, a database may belo!ically restructured in a variety of ways enablin! different types of user tofocus on those aspects that are of particular interest to them.

    Sec!rit'. In a multiJuser database system, it is freuently the case that you

    do not wish all users to have access to all of the data. &ne level of securityrestriction is to bar access to certain base tables to certain users. +owever,this may be too crude a mechanism, resultin! in some users bein! loced outfrom information that they le!itimately reuire. Typically, they may reuireaccess to subset of various tables. The view mechanism allows a databaseadministrator provide controlled access to subset of data. y !rantin! accessthrou!h views, the administrator can effectively hide sections of the database

    from unauthoriFed users while still enablin! them to have access to the datathat they reuire.

    (rotection against restr!ct!ring. It is in the nature of a lon!Jterm database

    that it will !row and occasionally be restructured. Columns may be added totables. ase tables may be subdivided, either horiFontally or vertically. /AhoriFontal subdivision would be to create tables based on subset of rows froman eistin! table. A vertical subdivision would be able to create new tablesbased on the subsets of columns from an eistin! table. In each situation, the

  • 8/22/2019 Elementary Queries

    23/53

    eistin! base table should then be destroyed otherwise the database willhave an unnecessary and dan!erous duplication of information.0 This willhave the effect of renderin! obsolete the SQL ueries that use such basetables. %ather than rewrite all these ueries, it is far more convenient andproductive to create views that lo!ically recreate the previous structure of the

    database. y !ivin! the views the same names as the previously eistin!tables, the SQL uery code invoed by the database users can remainunaltered.

    @iews are thus an important and useful feature of relational databases. In SQL,we have the ability to define and use views.

    )!ilding vie$s in SQL

    In SQL, we use the C%EATE @IE* command to define a view.

    As stated above, a view is a table that derives its content from one or moretables in a relational database. In SQL, we derive a view by embeddin! aSELECT command within a C%EATE @IE* command.

    In the first eample above, we had a view called SE4I&%S which was derivedfrom the 'E'E%S table, it definin! condition bein! all members with the T

  • 8/22/2019 Elementary Queries

    24/53

    In this eample, we have declared the column titles for the view on the C%EATE@IE* line. These titles derive their data from the euivalent column positions inthe first line of the definin! SELECT command, i.e. CLIE4T is derived fromclients.name, T%EAT'E4T from treatments.description and T+E%A3IST fromtherapists.name.

    *e could have declared column titles in the first of our C%EATE @IE*commands above, but this is not necessary when the column titles are !oin! tobe the same as those in the tables that service the view.

    &ur third eample of a view above was one that was derived from another view"all consultancies by 5r Crippen. The simplest and most ele!ant way to declarethis would be"

    C%EATE @IE* CrippensConsultanciesAS SELECT client, treatment

    $%&' consultancies*+E%E therapist 9 :5r Crippen;

    *e do not need to provide column titles as we are usin! the titles from the viewused to service the new view. $urthermore, this demonstrates clearly howCrippensConsultancies is merely a subset of Consultancies.

    @iews may be removed from a database with the 5%&3 @IE* command, foreample"

    5%&3 @IE* C&4S2LTA4CIES

    This simply removes the name and definition of this view from the database. Ithas no effect on any underlyin! base tables or views. It will, however, have theeffect of renderin! invalid any views that use this view in their definition.

    Mani*!lating vie$s in SQL

    SELECT commands $it" vie$s

    Any valid SELECT command can be used on a view. $or instance, to find thetelephone number for the Senior member Gent, we could say"

    SELECT telephoneno$%&' Seniors*+E%E surname 9 :Gent;

  • 8/22/2019 Elementary Queries

    25/53

    !ivin!"TELE3+&4E4&

    8KJ7-8-

    *e stated :could say; because the same information could have been obtainedby ueryin! the base table 'E'E%S. +owever, as stated in .- above, someusers may only have access, for security reasons, to a database throu!h viewsand would only be able to eecute SELECT statements on view.

    The user should tae care to use the view names of any reJtitled columns. $orinstance, the command"

    SELECT description$%&' consultancies

    would be re1ected as 5ESC%I3TI&4 does not eist as a column name in theC&4S2LTA4CIES view. It has been retitled as T%EAT'E4T. Thus, thecommand should read"

    SELECT treatment$%&' consultancies

    !ivin!

    T%EAT'E4T

    'a1or +air Transplantody 5eodoriFationEmer!ency Liposuction

    >oins may be eecuted usin! views. @iews may be 1oined with other views orwith base tables. $or instance, to find out how much each treatment is !oin! tocost in the C&4S2LTA4CIES view, we could 1oin it with the T%EAT'E4TStable"

    SELECT treatment, char!e$%&' consultancies, treatment*+E%E consultancies.treatment 9treatment.description

    !ivin!"

    T%EAT'E4T C+A%6E

    'a1or +air Transplant KBB.BB

  • 8/22/2019 Elementary Queries

    26/53

    ody 5eodoriFation -BB.BBEmer!ency Liposuction -7K.BB

    The above is a 1oin based on nonJey columns. *e have matched the name of atreatment in the C&4S2LTA4CIES view with its description in the T%EAT'E4T

    table. If we had two treatments with the same description, we would !et a resultwith two rows indicatin! two different char!es for that treatment. In order toremove the possibility for such ambi!uities, views that are built over 1oins shouldusually contain any forei!n ey columns within their definition. Thus, a :better;definition of C&4S2LTA4CIES would have been"

    C%EATE @IE* C&4S2LTA4CIES /CL4&, CLIE4T, %E$4&,T%EAT'E4T, T+4&, T+E%A3IST0

    ASSELECT clients.clno, clients.name, treatment.refno, description,

    therapists.thno, therapists.name$%&' clients, treatment, therapists, administration*+E%E clients.clno 9 administration.clnoand treatment.refno 9 administration.refnoand therapists.thno 9 administration.thno

    *e would then do the 1oin eample !iven above as"

    SELECT treatment, char!e$%&' consultancies, treatment*+E%E consultancies.refno 9 treatment.refno

    The 1oin is now based on a forei!n ey, meanin! that each row in theC&4S2LTA4CIES view cannot be 1oined with more than one row in theT%EAT'E4TS table, !ivin! unambi!uous char!e for each consultancy.

    U(#ATE+ #ELETE and INSERT commands $it" vie$s

    *hereas any valid SELECT command may be used with a view, in SQL thereare restrictions placed on the use of 235ATE, 5ELETE and I4SE%T commands.These commands may only be used on views that derive their data, eitherdirectly or indirectly, from one base table. In the eample views !iven in thischapter, SE4I&%S may have its contents altered by the use of these commands,whereas C&4S2LTA4CIES and C%I33E4SC&4S2LTA4CIES may not. Thisis because SE4I&%S is derived from the base table 'E'E%S alone, whereasthe other two are derived from a 1oin of CLIE4TS, T%EAT'E4TS,

    A5'I4IST%ATI&4 and T+E%A3ISTS. @iews that may have these commandseecuted on them are termed :updateable;. A more precise definition of

  • 8/22/2019 Elementary Queries

    27/53

    updateable views is !iven later in the tet when we have presented some moreadvanced aspects of SQL.

    A view that is derived from an updateable view may also be updateable. Thus aview such as"

    C%EATE @IE* TELE4&SAS SELECT no, telephoneno$%&' Seniors

    is updateable as it is derived from an updateable view.

    +owever, the view"

    C%EATE @IE* T%EAT'E4TSAs select treatment, client

    $%&' consultancies

    would not be updateable as it is derived from a nonJupdateable view"

    *hen a view is updateable, then the full synta of I4SE%T, 235ATE and5ELETE may be used on it. Care should be taen when usin! these commandson views as they directly affect the rows in the underlyin! base table. Conversely,any 235ATE', 5ELETE, and I4SE%T commands on a base table will affect anyviews derived from the base table. $or instance, the command"

    5ELETE $%&' Seniors

    *+E%E surname 9 :Gent;

    will be translated by the system into"

    5ELETE $%&' members*+E%E surname 9 :Gent;and type 9 :Senior;

    the last line of this command indicates the condition upon which the viewSE4I&%S is derived.

    The command"

    235ATE SeniorsSET name 9 :Clapton;*+E%E name 9 :ec;

    will cause the correspondin! row in the 'E'E%S table to have its namechan!ed.

  • 8/22/2019 Elementary Queries

    28/53

    The command"

    235ATE membersSET type 9 :>unior;*+E%E surname 9 :Gent;

    will have the effect of removin! this row from the SE4I&%S as it no lon!ersatisfies the definin! condition.

    In theory, rows may be inserted throu!h an updateable view. +owever, thefollowin! command would be ambi!uous semantically"

    I4SE%T I4T& Seniors@AL2ES /-7, :A;, :4other;, :7=J?-B-7;0

    This command is syntactically correct and would have the effect of creatin! a

    new row in the 'E'E%S base table with the !iven values fro 4&, I4IT,S2%4A'E, and TELE3+&4E4&. +owever, this row would not appear in anysubseuent SELECT commands performed on the Seniors view. This is becausethe view is defined as bein! all members with the T

  • 8/22/2019 Elementary Queries

    29/53

    (R,CESSIN #ATA

    In previous chapters, we have !iven eamples of ueries that retrieve and alterdata held in tables. SQL also provides facilities for processin! the data derived ina SELECT command. In this chapter, we shall eamine how simple reports can

    be !enerated usin! these SQL facilities.

    SQL e.*ressions

    In all of the SQL SELECT eamples !iven in previous chapters, we retrieved alist of columns usin! a list of tables. Columns and tables are, in themselves, SQLepressions. An SQL epression can also tae the form of a literal, a columnepression, a pseudonym or a function. In this section, we shall eamine columnepressions and pseudonyms and !ive incidental eamples of literals. $unctionsare considered in the net section.

    Col!mn e.*ressions

    A column epression may be defined informally as an operation usin! columnsandor literal values.

    4umeric columns may be included in epressions usin! arithmetic operators. $orinstance, suppose that we wished to discover the effect of increasin! the char!esin the T%EAT'E4T table by -BP. *e could do this by retrievin! the char!evalues and multiplyin! them by the literal value -.- thus"

    SELECT description, char!e#-.-

    $%&' treatment

    !vin!"

    5ESC%I3TI&4 C+A%6E

    Emer!ency Liposuction -8N.KB'a1or +air Transplant KKB.BB'inor +air Transplant 7NK.BBody 5eodoriFation --B.BB

    *e have issued a command that increases the C+A%6E values by -BP. This isfro display purposes only. It this has no effect on the data in the underlyin! table.This can only be chan!ed by the 235ATE command. 4ote how the literal /:#-.-;0appears in the column headin!.

    The followin! operators can be used on numeric columns"

  • 8/22/2019 Elementary Queries

    30/53

    add" subtract" Jmultiply" #divide"

    &perators on numeric columns may combine columns with literal values or withother numeric columns. In our members database, we introduced tablesindicatin! the transport levy for playin! on a particular day and the match fee fordifferent types of player. *e discovered the cost to players playin! on a Saturdayusin! the followin! command"

    SELECT init, surname, amount, char!e$%&' members, fees, available, levy*+E%E fees.type 9 members.typeand members.no 9 available.noand available.day 9 levy.day

    and available.day 9 :Saturday;

    !ivin!"

    I4IT S2%4A'E A'&24T C+A%6E

    6 Swanson -.KB -.KB$ ec 7.KB -.KB& Sharif -.KB -.KB

    If we wished to discover the total cost to each player, we could include an etracolumn epression /A'&24TC+A%6E0"

    SELECT init, surname, amount, char!e, amountchar!e$%&' members, fees, available, levy*+E%E fees.type 9 members.typeand members.no 9 available.noand available.day 9 levy.dayand available.day 9 :Saturday;

    !ivin!I4IT S2%4A'E A'&24T C+A%6E A'&24TC+A%6E

    6 Swanson -.KB -.KB 8.BB$ ec 7.KB -.KB .BB& Sharif -.KB -.KB 8.BB

  • 8/22/2019 Elementary Queries

    31/53

    Column epressions can be included in the *+E%E clause. If we now wished toinclude only those payers to whom the cost would be less than .BB, we wouldsay"

    SELECT init, surname, amount, char!e, amountchar!e

    $%&' members, fees, available, levy*+E%E fees.type 9 members.typeand members.no 9 available.noand available.day 9 levy.dayand available.day 9 :Saturday;and /amountchar!e0 .BB

    !ivin!"

    I4IT S2%4A'E A'&24T C+A%6E A'&24TC+A%6E

    6 Swanson -.KB -.KB 8.BB& Sharif -.KB -.KB 8.BB

    Character type columns may also be combined in epressions. Some versions ofSQL allow the :; operator to be used to concatenate strin!s. The SQL standardspecifies the use of the :U U; operator for this purpose. Thus, to concatenate initialsand surnames in the above command, we would say"

    SELECT init U U surname, amount, char!e, char!eamount$%&' members, fees, available, levy*+E%E fees.type 9 members.type

    and members.no 9 available.noand available.day 9 levy.dayand available.day 9 :Saturday;and /char!eamount0 .BB

    !ivin!"

    I4IT U US2%4A'E A'&24T C+A%6E A'&24TC+A%6E

    6Swanson -.KB -.KB 8.BB&Sharif -.KB -.KB 8.BB

    This particular command would benefit from the insertion of a period /: /;0 andspace /: :0 between the member;s initial and surname. This can be achieved asfollows"

    SELECT init U U : / : U U surname, amount, char!e, amount char!e$%&' members, fees, available, levy*+E%E fees.type 9 members.type

  • 8/22/2019 Elementary Queries

    32/53

    and members.no 9 available.noand available.day 9 levy.dayand available.day 9 :Saturday;and /amountchar!e0 .BB

    !ivin!"

    I4IT U U :/ : U U S2%4A'E A'&24T C+A%6E A'&24TC+A%6E

    6. Swanson -.KB -.KB 8.BB&. Sharif -.KB -.KB 8.BB

    +ere we have combined two character type columns with a literal value /: /:0.Strin! type literal such as these must be enclosed in uotation mars. *hen astrin! type literal is specified in a column headin!, it will then appear on everyrow of output under that column.

    (s!edon'ms

    Column and table epressions may be assi!ned pseudonyms or :aliases. In thelast of the eamples !iven above, a more desirable output would have involvedthe reJtitlin! of those columns used in epressions. This can be achieved by useof the AS clause"

    SELECT init U U :. : U U surname AS name,amount, char!e, amountchar!e AS cost

    $%&' members, fees, available, levy*+E%E fees.type 9 members.typeand member.no 9 available.noand available.day 9 levy.dayand available.day 9 :Saturday;and /amountchar!e0 .BB

    !ivin!"

    4A'E A'&24T C+A%6E C&ST6.Swanson -.KB -.KB 8.BB&. Sharif -.KB -.KB 8.BB

    Tables can also be renamed usin! an AS clause. The use of AS is optional, andis usually omitted. This facility can be very useful when writin! 1oin commands asabove. y usin! aliases, we can save a lot of typin!"

  • 8/22/2019 Elementary Queries

    33/53

    SELECT init U U :. : U U surname 4A'E,amount, char!e, amountchar!e C&ST

    $%&' members m, fees f, available a, levy l*+E%E f.type 9 m.typeand m.no 9 a.no

    and a.day 9 l.dayand a.day 9 :Saturday;and /amountchar!e0 .BB

    In this eample, we have specified an alias for each table on the $%&' line, andthen used these abbreviated aliases for our table reference in the 1oins.

    There are occasions when a uery mi!ht wish to compare the contents of therows in a table a!ainst rows in the same table. In this situation, the use of aliasesis vital in order to remove ambi!uities. $or instance, suppose we wished todiscover if there were any two members with the same telephone number. This

    would involve eaminin! each row in the 'E'E%S table and comparin! itstelephone number a!ainst all other rows in the 'E'E%S table. *e can achievethis as follows"

    SELECT first.surname, first.init, second.surname, second.init, first.telephoneno

    $%&' members first, members second*+E%E first.telephoneno 9 second.telephoneno

    !ivin!"

    S2%4A'E I4IT S2%4A'E I4IT TELE3+&4E4&

    Swanson 6 Swanson 6 B7-JK=J?NR= Gent C 8KJ7-8-ec > ec > 8KJ7-8-6reen 3 6reen 3 =?RJ78-

    This command matches two tables a!ainst each other /:first; and :second;0 whichare both aliases for the 'E'E%S table. The output tells us that Gent and ecboth have the same telephonenumber. +owever, it tells us this twice as eachtable is matched a!ainst the other. 2nfortunately, it also tells us that everymember has the same telephoneno as themselvesV *e can remove thisredundant information by specifyin! that the 'E'E% 4& in $irst must be lessthe 'E'E% 4& in second. This removes all matchin! members in either tablewho have the same 4&, thus eliminatin! rows that tell us that everyone has their

  • 8/22/2019 Elementary Queries

    34/53

    own phone number. It also removes the duplication of twice tellin! us that Gentand ec have the same number /which a strai!ht test of 4o ineuality would notachieve0. Thus the command"

    SELECT first.surname, first.init, second.surname,

    second.init, first.telephoneno$%&' members first, members second*+E%E first.telephoneno 9 second.telephonenoand first.no second.no

    would !ive us"

    S2%4A'E I4IT S2%4A'E I4IT TELE3+&4E4&

    Gent C ec > B8KJ7-8-

    *e can combine column aliases and literals to mae this output much morereadable thus"

    SELECT first.surname U U : : U U first.init U U; /: 4A'E-,:has the same phone number as : TEWT,

    second.surname U U : : U U second.init U U : /; 4A'E7, first.telephoneno 3+&4E

    $%&' members first, members second*+E%E first.telephoneno 9 second.telephoneno andfirst.no second.no

    !ivin!"

    4A'E- TEWT 4A'E7 3+&4E

    Gent C. has the same phone ec >. B8KJ7-8-number as

    In this eample, the literal :has the same phone number as; has been specifiedas a column epression, meanin! that it will appear on every row of the output.

    SQL f!nctions

    Statistical functions

    SQL has a number of builtJin a!!re!ate functions that can be used to providestatistical information derived from a table.

    These are as follows"

  • 8/22/2019 Elementary Queries

    35/53

    C&24T" returns the number of values in a columnor the number of rows in a table

    'I4" returns the lowest value in a column'AW" returns the hi!hest value in a column

    S2'" returns the sum of values in a columnA@6 returns the mean of all values in a column.

    $or instance, to find how many members we have in the 'E'E%S table, wewould say"

    SELECT C&24T /#0 $%&' members

    !ivin!"

    C&24T /#0

    ?

    The /#0 with the C&24T functions indicates that it is bein! used to count entirerows. C&24T can also be used on columns. To discover how many of ourmembers had a telephoneno, we would say"

    SELECT C&24T /telephoneno0$%&' members

    !ivin!"

    C&24T /TELE3+&4E4&0

    =

    This counts the number of rows with a telephoneno value. It so happens thattwo of our members have the same telephoneno. If we wanted to find out howmany different telephone numbers eisted in the 'E'E%S table, we wouldhave to ualify the column reference with the 5ISTI4CT functions"

    SELECT C&24T /5ISTI4CT telephoneno0$%&' members

    !ivin!"

    C&24T /5ISTI4CT TELE3+&4E4&0

    K

  • 8/22/2019 Elementary Queries

    36/53

    *e can include more than one C&24T function call in a SELECT command. Tofind the number of members we have and the number of different types ofmember, we would say"

    SELECT C&24T /#0, C&24T /5ISTI4CT type0

    $%&' members

    !ivin!"

    C&24T /#0 C&24T /5ISTI4CT T

  • 8/22/2019 Elementary Queries

    37/53

    'AW and 'I4 may also be used on character type columns. To find the memberwith the surname that would come first alphabetically, we would say"

    SELECT 'I4 /surname0$%&' members

    !ivin!"

    'I4 /S2%4A'E0

    andar

    It is ille!al in SQL to mi column references and a!!re!ate functions to!ether ina SELECT command unless the command includes a 6%&23 < clause /seenet section0. Suppose we wished to discover the full name and membershiptype of the member with the lowest surname. The command"

    SELECT surname, init, type, 'I4 /surname0$%&' members

    would be re1ected 'I4 /surname0 returns one value, whereas surname, init, typewill return values for all rows in the table as there is no constrainin! *+E%Eclause. If we wished to find out more about this member, we would have to issuea nested uery"

    SELECT surname, init, type$%&' members

    *+E%E surname 9 /SELECT 'I4/surname0$%&' members0

    !ivin!"

    S2%4A'E I4IT T

  • 8/22/2019 Elementary Queries

    38/53

    C&24T/#0 'I4/char!e0

    - -BB

    The S2' function can be used on any numeric column. $or instance, the total

    cost of all treatments currently administered would be"

    SELECT S2'/char!e0$%&' treatment t, administration a*+E%E t.refno 9 a.refno

    !ivin!"

    S2'/C+A%6E0

    N7K

    A@6 returns the arithmetic mean of a numeric column. Thus, the avera!e char!efor all treatments would be"

    SELECT A@6/char!e0$%&' treatment t, administration a*+E%E t.refno 9 a.refno

    !ivin!"

    A@6/C+A%6E0

    7-.=N

    A composite report !ivin! the number of treatments administered, the hi!hestand lowest char!e, the sum of all char!es and the avera!e char!e can beretrieved with one command"

    SELECT C&24T /#0, 'AW/char!e0, 'I4/char!e0, S2'/char!e0, A@6/char!e0$%&' treatments t, administration a*+E%E t.refno 9 a.refno

    6ivin!"

    'AW 'I4 S2' A@6C&24T/#0 /C+A%6E0 /C+A%6E0 /C+A%6E0 /C+A%6E0

    8 KBB -BB N7K 7-.=N

  • 8/22/2019 Elementary Queries

    39/53

    ro!*ing statistical f!nctions

    The eamples !iven in the previous section are all wholeJtable functions, that isthey derive their result from performin! the !iven function on all rows in a table. It

    is possible in SQL to perform a function on subsets of a table. This depends onthe facility to define an epression by which rows may be !rouped into subsets.

    $or instance, in our +ealth Clinic database, there are currently three treatmentsbein! administered to two clients. If we wanted to find out the sum of all char!eson a clientJbyJclients basis, we would have to !roup the clients accordin! to thatwhich differentiates them /their CL4& value0. *e achieve this as follows"

    SELECT c.clno, S2'/char!e0$%&' clients c, treatment t, administration a*+E%E c.clno 9 a.clno

    And a.refno 9 t.refno 6%&23 < c.clno

    !ivin!"

    C.CL4& S2'/C+A%6E0

    =7K7 -BB

    The above output indicates the sum of all char!es for clients with the same

    CL4& value who satisfy the !iven 1oin. *hen usin! scalar functions, it is onlyle!al to SELECT column epressions that are included in a 6%&23 < clause.Thus, the followin! command is ille!al"

    SELECT c.clno, name, S2'/char!e0$%&' clients c, administration a, treatment t*+E%E c.clno 9 a.clno

    and t.refno 9 a.refno 6%&23 < c.clno

    This is because there eists a column /name0 in the headin! that is not includedin the 6%&23 < clause. +owever, the followin! command would be uite le!al"

    SELECT c.clno, name, S2'/char!e0$%&' clients c, administration a, treatment t*+E%E c.clno 9 a.clno

    and t.refno 9 a.refno 6%&23 < c.clno, name

  • 8/22/2019 Elementary Queries

    40/53

    !ivin!"

    CL4& 4A'E S2'/C+A%6E0

    3 3an =7K

    7 5 6reen -BB

    This is because we have now included name in the 6%&23 < clause, meanin!that the system will now process and return subsets of rows with the samecombination of clno and name values.

    As in the eamples in the previous section, more than one function can be calledin a SELECT command usin! a 6%&23 < clause. $or instance, the sum of alltreatment char!es, the avera!e cost of each treatment and the number oftreatments !iven to each client would be"

    SELECT c.clno, name, S2'/char!e0, A@6/char!e0,C&24T/#0$%&' treatment t, administration a, clients c*+E%E t.refno 9 a.refno

    and c.clno 9 a.clno 6%&23 < c.clno, name

    !ivin!"

    CL4& 4A'E S2'/C+A%6E0 A@6/C+A%6E0 C&24T/#0

    3 3an =7K 8-7.K 7

    7 5 6reen -BB -BB -

    This depth of analysis is not very meanin!ful for clients; currently receivin! onlyone treatment. It would be useful to constrain this to only those who havereceived more than one treatment. *e can constrain 6%&23 < clauses by theuse of +A@I46 thus"

    SELECT c.clno, name, S2'/char!e0, S2'/char!e0,C&24T/#0$%&' treatment t, administration a, clients c*+E%E t.refno 9 a.refno

    and c.clno 9 a.clno 6%&23 < c.clno, name +A@I46 C&24T/#0 D -

    This would now return 1ust the first row from the previous result, +A@I46 testseach subset returned by the 6%&23 < clause with a function value. In thiscase, the C&24T/#0 function is applied to each subset and the result compareda!ainst the value -. All subsets rows which cannot satisfy the condition

  • 8/22/2019 Elementary Queries

    41/53

    epressed in the +A@I46 clause /C&24T/#0D-0 are eliminated from the output. Ifwe wished to retrieve only those clients whose avera!e char!es were !reaterthan the avera!e char!e for all treatments currently bein! administered, wewould say"

    SELECT c.clno, name, S2'/char!e0, S2'/char!e0,C&24T/#0$%&' treatment t, administration a, clients c*+E%E t.refno 9 a.refno

    and c.clno 9 a.clno 6%&23 < c.clno, name +A@I46 A@6/char!e0 D /SELECT A@6/char!e0

    $%&' treatment , administration y *+E%E .refno 9 y.refno0

    !ivin!"

    S2' A@6CL4& 4A'E /C+A%6E0 /C+A%6E0 C&24T/#0

    3 3an =7K 8-7.K 7

    This row is returned because the A@6/C+A%6E0 value of 8-7.K for 3 3an;streatments is !reater than the avera!e for all treatments currently administered/7-.=N0.

    A client whose most epensive treatment was less than the avera!e for alltreatments currently administered would be"

    SELECT c.clno, name, S2'/char!e0, A@6/char!e0,C&24T/#0$%&' treatment t, administration a, clients c*+E%E t.refno 9 a.refno

    and c.clno 9 a.clno 6%&23 < c.clno, name +A@I46 'AW/char!e0 /SELECT A@6/char!e0

    $%&' treatment , administration y *+E%E .refno 9 y.refno0

    !ivin!"

    S2' A@6CL4& 4A'E /C+A%6E0 /C+A%6E0 C&24T/#0

    7 5 6reen -BB -BB -

    In the last two eamples, we have used a function call in a nested command toreturn a value for comparison purposes.

  • 8/22/2019 Elementary Queries

    42/53

    &rderin! data

    SQL provides the &%5E% < clause to enable the pro!rammer to determine theseuence in which rows are retrieved by a SELECT command. y default, rowsare displayed in the order that they are stored. &ur 'E'E%S table has been

    stored in primary seuence. If we wished to display it in seuence of members;surnames, we would say"

    SELECT surname, init, type$%&' members&%5E% < surname

    !ivin!"

    S2%4A'E I4IT T Senior 6reen 3 Senior Gent C Senior Sharif & >unior Sharif & >unior Swanson 6 >unior

  • 8/22/2019 Elementary Queries

    43/53

    S2%4A'E I4IT Tunior Sharif & >unior

    Swanson 6 >unior andar O 4oviceec > Senior Gent C Senior 6reen 3 Senior

  • 8/22/2019 Elementary Queries

    44/53

    SELECT c.clno, name, S2'/char!e0$%&' clients a, administration a, t*+E%E t.refno 9 a.refno

    and c.clno 9 a.clno !roup by c.clno, name

    order by S2'/char!e0 5ESC

    !ivin! the same output as before, but in a reversed seuence with 3 3an;sdetails at the top.

    S!mmar'

    -. SQL SELECT commands may use column epressions and tableepressions.

    7. Column epressions may include literal value.

    8. 4umeric columns may be combined into epressions usin! arithmeticoperators.. Alphanumeric columns may be concatenated usin! the :U U; operator.K. Tables and columns may be assi!ned pseudonyms.=. SQL provides functions /C&24T, 'AW, 'I4, S2', A@60 for returnin!

    values from a table.N. $unctions may return values from table subsets usin! the 6%&23 < and

    +A@I46 clauses.?. &utput may be seuenced usin! the &%5E% < clause.

    C,M)ININ QUERIES

    SET o*erators

    Every SQL SELECT command returns a table. A table is, in itself, a set of rows.In SQL, we can use set operators to combine one set of rows with another.Suppose we had two ueries which returned the followin! sets of rows"

    Query A Query A A

    C W5 3 6ettysbur!6 Li!htly

    T"e INTERSECT o*erator

    I4TE%SECT returns only those rows that are returned by all of the !ivenSELECT commands in a combination. Thus, the command"

  • 8/22/2019 Elementary Queries

    50/53

    SELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Saturday;0I4TE%SECT

    SELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Sunday;0

    would !ive"

    4& S2%4A'E I4IT

    - Swanson 6 Gent C

    ? Sharif &

    This returns those rows present in both sets of data, i.e. those membersavailable on both the !iven days.

    The A45 operator is to I4TE%SECT what &% is to 24I&4. Thus, the aboveresult would also be obtained usin!"

    SELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Saturday;0A45 no I4 /SELECT no $%&' available *+E%E day 9 :Sunday;0

    As with &%, A45 cannot be used to retrieve the intersection of two commandsusin! separate tables, for eample"

    SELECT name $%&' clientsI4TE%SECTSELECT name $%&' therapists

    It so happens that the above command would yield no rows from our eampledatabase. +owever, if there were any clients and therapists with the same name,it would reveal such a fact.

    As with 24I&4, I4TE%SECT removes duplicates from the result unlessI4TE%SECT ALL is specified.

  • 8/22/2019 Elementary Queries

    51/53

    T"e E0CE(T o*erator

    EWCE3T returns all rows that are in one select command but not the net. 2nlie24I&4 and I4TE%SECT, EWCE3T is not commutative. An operator is said to becumulative when the same result is achieved re!ardless of the order in which the

    operands are !iven. Thus, A 24I&4 will !ive the same results as 24I&4and A I4TE%SECT will !ive the same result as I4TE%SECT A.

    /4" Some SQL products use the word 'I42S rather than EWCE3T0

    In all of the eamples above, we would have obtained the same set of rowsre!ardless of the order of the SELECT commands !iven /thou!h the seuencin!of the sets may have differed0. +owever,

    SELECT no, surname, init$%&' members

    *+E%E no I4 /SELECT no $%&' available*+E%E day 9 :Saturday;0EWCE3TSELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Sunday;0

    would !ive"

    4& S2%4A'E I4IT

    7

    whereas"

    SELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Sunday;0EWCE3TSELECT no, surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Saturday;0

    would !ive"

  • 8/22/2019 Elementary Queries

    52/53

    4& S2%4A'E I4IT

    8 andar OK 6reen 3? Sharif &

    This is because the first command !ives those who are available on Saturdayonly whereas the second one !ives those who are available on Sunday only.

    The command"

    SELECT name $%&' clientsEWCE3TSELECT name $%&' therapists

    would !ive the names of all CLIE4TS who are not therapists, whereas"

    SELECT name $%&' therapistsEWCE3TSELECT name $%&' clients

    would !ive the names of all therapists who are not clients.

    EWCE3T can always be replicated by use of 4&T I4 and a nested uery, foreample"

    SELECT name $%&' therapists

    *+E%E name 4&T I4 /SELECT name $%&' clients0

    ,rdering combined commands

    The &%5E% < clause can be used with commands combined around a setoperator. Column names may differ between tables combined around a setoperator. The &%5E% < clause must therefore use column reference numbersrather than literal column names. The clause may only appear at the end of thecombined uery thus"

    SELECT surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

    *+E%E day 9 :Saturday;024I&4SELECT surname, init$%&' members*+E%E no I4 /SELECT no $%&' available

  • 8/22/2019 Elementary Queries

    53/53

    *+E%E day 9 :Sunday;0&%5E% < -, 7

    !ivin!"

    S2%4A'E I4IT

    andar Oec >6reen 3Gent CSharif &Swanson 6