Sie sind auf Seite 1von 55

SQL (Structured Query Language) is a computer language aimed to store, manipulate, and retrieve data stored in relational databases.

The first incarnation of SQL appeared in 19 !, "hen a group in #$% developed the first prototype of a relational database. The first commercial relational database "as released by &elational Soft"are (later becoming 'racle). Standards for SQL e(ist. )o"ever, the SQL that can be used on each one of the ma*or &+$%S today is in different flavors. This is due to t"o reasons, 1) the SQL standard is fairly comple(, and it is not practical to implement the entire standard, and -) each database vendor needs a "ay to differentiate its product from others. #n this tutorial, such differences are noted "here appropriate. This SQL programming help site lists commonly.used SQL statements, and is divided into the follo"ing sections, SQL Commands, $asic SQL statements for storing, retrieving, and manipulating data in a relational database. Table Manipulation, )o" SQL statements are used to manage tables inside the database. Advanced SQL, /dvanced SQL commands. SQL Syntax, / single page that lists the synta( for all the SQL commands in this tutorial.

0or each command, the SQL synta( "ill first be presented and e(plained, follo"ed by an e(ample. $y the end of this tutorial, you should have a good general understanding of the SQL synta(, and be able to "rite SQL 1ueries using the correct synta(. %y e(perience is that understanding the basics of SQL is much easier than mastering all the intricacies of this database language, and # hope you "ill reach the same conclusion as "ell. #f you are interested in ho" to retrieve data using SQL, "e recommend that you start "ith the SQL Commands section. #f you are interested in understanding ho" SQL can be used to manipulate database tables, "e recommend that you start "ith the Table Manipulation section. #f you are loo2ing for help on a specific SQL command, you can use the Site Map to find the command you are loo2ing for. '2ay, enough introduction. Bookmark this site now and start now to learn SQL3

SQL SELECT >>

4hat do "e use SQL commands for5 / common use is to select data from the tables located in a database. #mmediately, "e see t"o 2ey"ords, "e need to SELECT information !"M a table. (6ote that a table is a container that resides in the database "here the data is stored. 0or more information about ho" to manipulate tables, go to the Table Manipulation Section). )ence "e have the most basic SQL structure, SELECT #column$name# !"M #table$name# To illustrate the above e(ample, assume that "e have the follo"ing table,

Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

4e shall use this table as an e(ample throughout the tutorial (this table "ill appear in all sections). To select all the stores in this table, "e 2ey in, SELECT store7name !"M Store7#nformation Result: store_name Los Angeles San Diego Los Angeles Boston %ultiple column names can be selected, as "ell as multiple table names. SQL DISTINCT >>

The SELECT 2ey"ord allo"s us to grab all information from a column (or columns) on a table. This, of course, necessarily mean that there "ill be redundancies. 4hat if "e only "ant to select each %&ST&'CT element5 This is easy to accomplish in SQL. /ll "e need to do is to add %&ST&'CT after SELECT. The synta( is as follo"s, SELECT %&ST&'CT #column$name# !"M #table$name# 0or e(ample, to select all distinct stores in Table Store_Information, Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in,

SELECT %&ST&'CT store$name !"M Store$&n(ormation Result: store_name Los Angeles San Diego Boston SQL )*E!E ++

6e(t, "e might "ant to conditionally select the data from a table. 0or e(ample, "e may "ant to only retrieve stores "ith sales above 81,999. To do this, "e use the )*E!E 2ey"ord. The synta( is as follo"s, SELECT #column$name# !"M #table$name# )*E!E #condition# 0or e(ample, to select all stores "ith sales above 81,999 in Table Store_Information, Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT store$name !"M Store$&n(ormation )*E!E Sales + ,--Result: Store_name Los Angeles SQL A'% "! ++ #n the previous section, "e have seen that the )*E!E 2ey"ord can be used to conditionally select data from a table. This condition can be a simple condition (li2e the one presented in the previous section), or it can be a compound condition. :ompound conditions are made up of multiple simple conditions connected by A'% or "!. There is no limit to the number of simple conditions that can be present in a single SQL statement. The synta( for a compound condition is as follo"s,

SELECT #column$name# !"M #table$name# )*E!E #simple condition# ./A'%0"!1 #simple condition#23 The ;<= means that the e(pression inside the brac2et "ill occur one or more times. 6ote that A'% and "! can be used interchangeably. #n addition, "e may use the parenthesis sign () to indicate the order of the condition. 0or e(ample, "e may "ish to select all stores "ith sales greater than 81,999 or all stores "ith sales less than 8>99 but greater than 8- > in Table Store_Information, Table Store_Information
store_name Los Angeles San Diego San Francisco Boston Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT store$name !"M Store$&n(ormation )*E!E Sales + ,--"! 4Sales 5 6-- A'% Sales + 7869 Result: Store_name Los Angeles San Francisco SQL &' ++ #n SQL, there are t"o uses of the &' 2ey"ord, and this section introduces the one that is related to the )*E!E clause. 4hen used in this conte(t, "e 2no" e(actly the value of the returned values "e "ant to see for at least one of the columns. The synta( for using the &' 2ey"ord is as follo"s, SELECT #column$name# !"M #table$name# )*E!E #column$name# &' 4:value,:; :value7:; <<<9 The number of values in the parenthesis can be one or more, "ith each values separated by comma. ?alues can be numerical or characters. #f there is only one value inside the parenthesis, this commend is e1uivalent to )*E!E #column$name# = :value,:

0or e(ample, "e may "ish to select all records for the Los /ngeles and the San +iego stores in Table Store_Information, Table Store_Information
store_name Los Angeles San Diego San Francisco Boston Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT > !"M Store$&n(ormation )*E!E store$name &' 4:Los An?eles:; :San %ie?o:9 Result: Store_name Sales San Diego Date

Los Angeles $1500 an!05!1""" $#50 an!0$!1"""

SQL BET)EE' ++

4hereas the &' 2ey"ord help people to limit the selection criteria to one or more discrete values, the BET)EE' 2ey"ord allo"s for selecting a range. The synta( for the BET)EE' clause is as follo"s, SELECT #column$name# !"M #table$name# )*E!E #column$name# BET)EE' :value,: A'% :value7: This "ill select all ro"s "hose column has a value bet"een @value1@ and @value-@. 0or e(ample, "e may "ish to select vie" all sales information bet"een Aanuary B, 1999, and Aanuary 19, 1999, in Table Store_Information, Table Store_Information
store_name Los Angeles San Diego Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999

San Francisco Boston

$300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT > !"M Store$&n(ormation )*E!E %ate BET)EE' :@anA-BA,CCC: A'% :@anA,-A,CCC: 6ote that date may be stored in different formats in different databases. This tutorial simply choose one of the formats. Result: Store_name San Diego Boston Sales Date $#50 an!0$!1""" $$00 an!0&!1"""

San Francisco $%00 an!0&!1"""

SQL )ildcard ++ There are times "hen "e "ant to match on a string pattern. To do that, "e "ill need to employ the concept of "ildcard. #n SQL, there are t"o "ildcards in SQL, D (percent sign) represents Cero, one, or more characters. $ (underscore) represents e(actly one character. 4ildcards are used "ith the L&EE 2ey"ord in SQL. $elo" are some "ildcard e(amples, D @/7E@, /ll string that starts "ith @/@, another character, and end "ith @E@. 0or e(ample, @/$E@ and @/-E@ "ould both satisfy the condition, "hile @/FFE@ "ould not (because there are t"o characters bet"een / and E instead of one). D @/$:G@, /ll strings that start "ith @/$:@. 0or e(ample, @/$:+@ and @/$:/$:@ "ould both satisfy the condition. D @GHIE@, /ll strings that end "ith @HIE@. 0or e(ample, @4HIE@ and @EEHIE@ "ould both satisfy the condition. D @G/6G@, /ll strings that contain the pattern @/6@ any"here. 0or e(ample, @L'S /6JKLKS@ and @S/6 0&/6:#S:'@ "ould both satisfy the condition.

D @7/6G@, /ll strings that contain a character, then @/6@, follo"ed by anything else. 0or e(ample, @S/6 0&/6:#S:'@ "ould satisfy the condition, "hile @L'S /6JKLKS@ "ould not satisfy the condition. SQL L&EE ++

L&EE is another 2ey"ord that is used in the )*E!E clause. $asically, L&EE allo"s you to do a search based on a pattern rather than specifying e(actly "hat is desired (as in &') or spell out a range (as in BET)EE'). The synta( is as follo"s, SELECT #column$name# !"M #table$name# )*E!E #column$name# L&EE .FATTE!'2 ;L/TTK&6< often consists of "ildcards. 4e sa" several e(amples of wildcard matching in the previous section. $elo" "e use an e(ample to see ho" "ildcard is used in SQL, Table Store_Information
store_name L S A!"#L#S SA! D$#" SA! F%A!&$S& B S' ! Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

4e "ant to find all stores "hose name contains @/6@. To do so, "e 2ey in, SELECT > !"M Store$&n(ormation )*E!E store$name L&EE :DA'D: Result: Store_name L'S AN(ELES SAN DIE(' SAN F)ANCISC' Sales Date

$1500 an!05!1""" $#50 an!0$!1""" $%00 an!0&!1"""

SQL "!%E! BG ++ So far, "e have seen ho" to get data out of a table using SELECT and )*E!E commands. 'ften, ho"ever, "e need to list the output in a particular order. This could be in ascending order,

in descending order, or could be based on either numerical value or te(t value. #n such cases, "e can use the "!%E! BG 2ey"ord to achieve our goal. The synta( for an "!%E! BG statement is as follo"s, SELECT #column$name# !"M #table$name# /)*E!E #condition#1 "!%E! BG #column$name# /ASC; %ESC1 The MN means that the )*E!E statement is optional. )o"ever, if a )*E!E clause e(ists, it comes before the "!%E! BG clause. ASC means that the results "ill be sho"n in ascending order, and %ESC means that the results "ill be sho"n in descending order. #f neither is specified, the default is ASC. #t is possible to order by more than one column. #n this case, the "!%E! BG clause above becomes "!%E! BG #column$name,# /ASC; %ESC1; #column$name7# /ASC; %ESC1 /ssuming that "e choose ascending order for both columns, the output "ill be ordered in ascending order according to column 1. #f there is a tie for the value of column 1, "e then sort in ascending order by column -. 0or e(ample, "e may "ish to list the contents of Table Store_Information by dollar amount, in descending order, Table Store_Information
store_name Los Angeles San Diego San Francisco Boston Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT store$name; Sales; %ate !"M Store$&n(ormation "!%E! BG Sales %ESC Result: store_name Los Angeles Boston San Francisco Sales Date

$1500 an!05!1""" $$00 an!0&!1""" $%00 an!0&!1"""

San Diego

$#50 an!0$!1"""

#n addition to column name, "e may also use column position (based on the SQL 1uery) to indicate "hich column "e "ant to apply the "!%E! BG clause. The first column is 1, second column is -, and so on. #n the above e(ample, "e "ill achieve the same results by the follo"ing command, SELECT store$name; Sales; %ate !"M Store$&n(ormation "!%E! BG 7 %ESC SQL A??re?ate unctions ++

Since "e have started dealing "ith numbers, the ne(t natural 1uestion to as2 is if it is possible to do math on those numbers, such as summing them up or ta2ing their average. The ans"er is yes3 SQL has several arithematic functions, and they are, D AHI, /verage of the column. D C"J'T, 6umber of records. D MAK, %a(imum of the column. D M&', %inimum of the column. D SJM, Sum of the column. The synta( for using functions is, SELECT #(unction type# 4#column$name#9 !"M #table$name# K(amples of ho" these functions are used are presented individually in the ne(t fe" pages. #n addition to using functions, it is also possible to use SQL to perform simple tas2s such as addition (=) and subtraction (.). 0or character.type data, there are also several string functions available, such as concatenation, trim, and substrin? functions. +ifferent &+$%S vendors have different string functions implementations, and it is best to consult the references for your &+$%S to see ho" these functions are used. SQL Avera?e ++

SQL uses the /?J() function to calculate the average of a column. The synta( for using this function is, SELECT AHI4#column$name#9 !"M #table$name#

0or e(ample, if "e "ant to get the average of all sales from the follo"ing table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e "ould type in SELECT AHI4Sales9 !"M Store$&n(ormation Result: A*(+Sales, $-&$.5 8BO .> represents the average of all Sales entries, (81>99 = 8->9 = 8P99 = 8 99) Q !. SQL C"J'T ++

/nother arithmetic function is C"J'T. This allo"s us to C"J'T up the number of ro" in a certain table. The synta( is, SELECT C"J'T4#column$name#9 !"M #table$name# 0or e(ample, if "e "ant to find the number of store entries in our table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e@d 2ey in SELECT C"J'T4store$name9 !"M Store$&n(ormation Result:

Co/nt+store_name, 0 C"J'T and %&ST&'CT can be used together in a statement to fetch the number of distinct entries in a table. 0or e(ample, if "e "ant to find out the number of distinct stores, "e@d type, SELECT C"J'T4%&ST&'CT store$name9 !"M Store$&n(ormation Result: Co/nt+DISTINCT store_name, % SQL MAK ++

SQL uses the %/H function to find the ma(imum value in a column. The synta( for using the %/H function is, SELECT MAK4#column$name#9 !"M #table$name# 0or e(ample, if "e "ant to get the highest sales from the follo"ing table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e "ould type in SELECT MAK4Sales9 !"M Store$&n(ormation Result: 1A2+Sales, $1500 81>99 represents the ma(imum value of all Sales entries, 81>99, 8->9, 8P99, and 8 99. SQL M&' ++

SQL uses the %#6 function to find the ma(imum value in a column. The synta( for using the %#6 function is, SELECT M&'4#column$name#9 !"M #table$name# 0or e(ample, if "e "ant to get the lo"est sales from the follo"ing table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e "ould type in SELECT M&'4Sales9 !"M Store$&n(ormation Result: 1IN+Sales, $#50 8->9 represents the minimum value of all Sales entries, 81>99, 8->9, 8P99, and 8 99. SQL SJM ++ The SR% function is used to calculate the total for a column. The synta( is, SELECT SJM4#column$name#9 !"M #table$name# 0or e(ample, if "e "ant to get the sum of all sales from the follo"ing table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e "ould type in

SELECT SJM4Sales9 !"M Store$&n(ormation Result: S31+Sales, $#$50 8- >9 represents the sum of all Sales entries, 81>99 = 8->9 = 8P99 = 8 99. SQL I!"JF BG ++ 6o" "e return to the aggregate functions. &emember "e used the SJM 2ey"ord to calculate the total sales for all stores5 4hat if "e "ant to calculate the total sales for each store5 4ell, "e need to do t"o things, 0irst, "e need to ma2e sure "e select the store name as "ell as total sales. Second, "e need to ma2e sure that all the sales figures are ?rouped by stores. The corresponding SQL synta( is, SELECT #column$name,#; SJM4#column$name7#9 !"M #table$name# I!"JF BG #column$name,# Let@s illustrate using the follo"ing table, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

4e "ant to find total sales for each store. To do so, "e "ould 2ey in, SELECT store$name; SJM4Sales9 !"M Store$&n(ormation I!"JF BG store$name Result: store_name Los Angeles San Diego Boston> S31+Sales, $1&00 $#50 $$00

The I!"JF BG 2ey"ord is used "hen "e are selecting multiple columns from a table (or tables) and at least one arithmetic operator appears in the SELECT statement. 4hen that happens, "e need to I!"JF BG all the other selected columns, i.e., all columns e(cept the one(s) operated on by the arithmetic operator. SQL *AH&'I ++

/nother thing people may "ant to do is to limit the output based on the corresponding sum (or any other aggregate functions). 0or e(ample, "e might "ant to see only the stores "ith sales over 81,>99. #nstead of using the )*E!E clause in the SQL statement, though, "e need to use the *AH&'I clause, "hich is reserved for aggregate functions. The *AH&'I clause is typically placed near the end of the SQL statement, and a SQL statement "ith the *AH&'I clause may or may not include the I!"JF BG clause. The synta( for *AH&'I is, SELECT #column$name,#; SJM4#column$name7#9 !"M #table$name# I!"JF BG #column$name,# *AH&'I 4arithmetic (unction condition9 6ote, the I!"JF BG clause is optional. #n our e(ample, table Store_Information, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

"e "ould type, SELECT store$name; SJM4sales9 !"M Store$&n(ormation I!"JF BG store$name *AH&'I SJM4sales9 + ,6-Result: store_name Los Angeles S31+Sales, $1&00 SQL Alias ++ 4e ne(t focus on the use of aliases. There are t"o types of aliases that are used most fre1uently, column alias and table alias. #n short, column aliases e(ist to help organiCing output. #n the previous e(ample, "henever "e see total sales, it is listed as SJM(sales). 4hile this is comprehensible, "e can envision cases "here the column heading can be complicated (especially if it involves several arithmetic operations). Rsing a column alias "ould greatly ma2e the output much more readable. The second type of alias is the table alias. This is accomplished by putting an alias directly after the table name in the !"M clause. This is convenient "hen you "ant to obtain information from t"o separate tables (the technical term is @perform *oins@). The advantage of using a table alias "hen doing *oins is readily apparent "hen "e tal2 about *oins. $efore "e get into *oins, though, let@s loo2 at the synta( for both the column and table aliases,

SELECT #table$alias#<#column$name,# #column$alias# !"M #table$name# #table$alias# $riefly, both types of aliases are placed directly after the item they alias for, separate by a "hite space. 4e again use our table, Store_Information, Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

4e use the same e(ample as that in the SQL I!"JF BG section, e(cept that "e have put in both the column alias and the table alias, SELECT A,<store$name Store; SJM4A,<Sales9 #Total Sales# !"M Store$&n(ormation A, I!"JF BG A,<store$name Result: Store Los Angeles San Diego Boston Total Sales $1&00 $#50 $$00

6otice that difference in the result, the column titles are no" different. That is the result of using the column alias. #nstead of the some"hat cryptic SSum(Sales)S, "e no" have STotal SalesS, "hich is much more understandable, as the column header. The advantage of using a table alias is not apparent in this e(ample. )o"ever, they "ill become evident in the SQL @oins section. SQL AS ++ #n the SQL /lias section, "e sa" that the synta( for using table and column aliases is as follo"s, SELECT #table$alias#<#column$name,# #column$alias# !"M #table$name# #table$alias# The 2ey"ord AS is used to assign an alias to the column or a table. #t is insert bet"een the column name and the column alias or bet"een the table name and the table alias. The synta( for using /S is as follo"s, SELECT #table$alias#<#column$name,# AS #column$alias# !"M #table$name# AS #table$alias# Let@s ta2e a loo2 at the same e(ample as "e used in SQL /lias. /ssume "e have the follo"ing table, Store_Information,

Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

To find total sales by store using AS as part of the table and column alias, "e type in, SELECT A,<store$name Store; SJM4A,<Sales9 AS #Total Sales# !"M Store$&n(ormation AS A, I!"JF BG A,<store$name Result: Store Los Angeles San Diego Boston Total Sales $1&00 $#50 $$00 SQL @oin ++ 6o" "e "ant to loo2 at *oins. To do *oins correctly in SQL re1uires many of the elements "e have introduced so far. Let@s assume that "e have the follo"ing t"o tables, Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

and "e "ant to find out sales by region. 4e see that table Geography includes information on regions and stores, and table Store_Information contains sales information for each store. To get the sales information by region, "e have to combine the information from the t"o tables. K(amining the t"o tables, "e find that they are lin2ed via the common field, Sstore7nameS. 4e "ill first present the SQL statement and e(plain the use of each segment later,

SELECT A,<re?ion$name !EI&"'; SJM4A7<Sales9 SALES !"M Ieo?raphy A,; Store$&n(ormation A7 )*E!E A,<store$name = A7<store$name I!"JF BG A,<re?ion$name Result: )E(I'N East 4est SALES $$00 $#050

The first t"o lines tell SQL to select t"o fields, the first one is the field Sregion7nameS from table Geography (aliased as &KJ#'6), and the second one is the sum of the field SSalesS from table Store_Information (aliased as S/LKS). 6otice ho" the table aliases are used here, Jeography is aliased as /1, and Store7#nformation is aliased as /-. 4ithout the aliasing, the first line "ould become SELECT Ieo?raphy<re?ion$name !EI&"'; SJM4Store$&n(ormation<Sales9 SALES "hich is much more cumbersome. #n essence, table aliases ma2e the entire SQL statement easier to understand, especially "hen multiple tables are included. 6e(t, "e turn our attention to line P, the )*E!E statement. This is "here the condition of the *oin is specified. #n this case, "e "ant to ma2e sure that the content in Sstore7nameS in table Jeography matches that in table Store_Information, and the "ay to do it is to set them e1ual. This )*E!E statement is essential in ma2ing sure you get the correct output. 4ithout the correct )*E!E statement, a :artesian Aoin "ill result. :artesian *oins "ill result in the 1uery returning every possible combination of the t"o (or "hatever the number of tables in the !"M statement) tables. #n this case, a :artesian *oin "ould result in a total of ! ( ! T 1B ro"s being returned. SQL "uter @oin ++ Lreviously, "e had loo2ed at left *oin, or inner *oin, "here "e select ro"s common to the participating tables to a *oin. 4hat about the cases "here "e are interested in selecting elements in a table regardless of "hether they are present in the second table5 4e "ill no" need to use the SQL "JTE! @"&' command. The synta( for performing an outer *oin in SQL is database.dependent. 0or e(ample, in 'racle, "e "ill place an S(=)S in the )*E!E clause on the other side of the table for "hich "e "ant to include all the ro"s. Let@s assume that "e have the follo"ing t"o tables, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

and "e "ant to find out the sales amount for all of the stores. #f "e do a regular *oin, "e "ill not be able to get "hat "e "ant because "e "ill have missed S6e" Ior2,S since it does not appear in the Store_Information table. Therefore, "e need to perform an outer *oin on the t"o tables above, SELECT A,<store$name; SJM4A7<Sales9 SALES !"M Ieo?raphy A,; Store$&n(ormation A7 )*E!E A,<store$name = A7<store$name 439 I!"JF BG A,<store$name 6ote that in this case, "e are using the 'racle synta( for outer *oin. Result: store_name Boston Ne5 6or7 Los Angeles San Diego SALES $$00 $1&00 $#50

6ote, 6RLL is returned "hen there is no match on the second table. #n this case, S6e" Ior2S does not appear in the table Store_Information, thus its corresponding SS/LKSS column is 6RLL. SQL C"'CATE'ATE ++ The Substring function in SQL is used to grab a portion of the stored data. This function is called differently for the different databases, %ySQL, SR$ST&(), SR$ST&#6J() 'racle, SR$ST&() SQL Server, SR$ST&#6J()

The most fre1uent uses are as follo"s ("e "ill use SR$ST&() here), SJBST!4str;pos9, Select all characters from UstrV starting "ith position UposV. 6ote that this synta( is not supported in SQL Server. SJBST!4str;pos;len9, Starting "ith the UposVth character in string UstrV and select the ne(t UlenV characters.

/ssume "e have the follo"ing table, Table Geography


region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

K(ample 1, SELECT SJBST!4store$name; L9 !"M Ieo?raphy )*E!E store$name = :Los An?eles:M Result, :s An?eles: K(ample -, SELECT SJBST!4store$name;7;N9 !"M Ieo?raphy )*E!E store$name = :San %ie?o:M Result, :an %: SQL T!&M ++ The T&#% function in SQL is used to remove specified prefi( or suffi( from a string. The most common pattern being removed is "hite spaces. This function is called differently in different databases, %ySQL, T&#%(), &T&#%(), LT&#%() 'racle, &T&#%(), LT&#%() SQL Server, &T&#%(), LT&#%()

The synta( for these trim functions are, T!&M4//L"CAT&"'1 /remstr1 !"M 1 str9, ML':/T#'6N can be either LK/+#6J, T&/#L#6J, or $'T). This function gets rid of the MremstrN pattern from either the beginning of the string or the end of the string, or both. #f no MremstrN is specified, "hite spaces are removed. LT!&M4str9, &emoves all "hite spaces from the beginning of the string. !T!&M4str9, &emoves all "hite spaces at the end of the string.

K(ample 1, SELECT T!&M4: Sample :9M Result, :Sample: K(ample -, SELECT LT!&M4: Sample :9M Result, :Sample : K(ample P, SELECT !T!&M4: Sample :9M Result, : Sample: SQL Len?th ++ The Length function in SQL is used to get the length of a string. This function is called differently for the different databases, %ySQL, LK6JT)() 'racle, LK6JT)() SQL Server, LK6()

The synta( for the Length function is as follo"s, Len?th4str9, 0ind the length of the string str. Let@s ta2e a loo2 at some e(amples. /ssume "e have the follo"ing table, Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

K(ample 1,

SELECT Len?th4store$name9 !"M Ieo?raphy )*E!E store$name = :Los An?eles:M Result, ,, K(ample -, SELECT re?ion$name; Len?th4re?ion$name9 !"M Ieo?raphyM Result, region_name Lengt8+region_name, East East 4est 4est 0 0 0 0 SQL !eplace ++ The !eplace function in SQL is used to update the content of a string. The function call is &KLL/:K() for %ySQL, 'racle, and SQL Server. The synta( of the &eplace function is, !eplace4str,; str7; strL9, #n str1, find "here str- occurs, and replace it "ith strP.. /ssume "e have the follo"ing table, Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

#f "e apply the follo"ing &eplace function, SELECT !EFLACE4re?ion$name; :ast:; :astern:9 !"M Ieo?raphyM Result, region_name Eastern

Eastern 4est 4est SQL C!EATE TABLE ++ Tables are the basic structure "here data is stored in the database. Jiven that in most cases, there is no "ay for the database vendor to 2no" ahead of time "hat your data storage needs are, chances are that you "ill need to create tables in the database yourself. %any database tools allo" you to create tables "ithout "riting SQL, but given that tables are the container of all the data, it is important to include the C!EATE TABLE synta( in this tutorial. $efore "e dive into the SQL synta( for C!EATE TABLE, it is a good idea to understand "hat goes into a table. Tables are divided into ro"s and columns. Kach ro" represents one piece of data, and each column can be thought of as representing a component of that piece of data. So, for e(ample, if "e have a table for recording customer information, then the columns may include information such as 0irst 6ame, Last 6ame, /ddress, :ity, :ountry, $irth +ate, and so on. /s a result, "hen "e specify a table, "e include the column headers and the data types for that particular column. So "hat are data types5 Typically, data comes in a variety of forms. #t could be an integer (such as 1), a real number (such as 9.>>), a string (such as @s1l@), a dateQtime e(pression (such as @-999.A/6.-> 9P,--,--@), or even in binary format. 4hen "e specify a table, "e need to specify the data type associated "ith each column (i.e., "e "ill specify that @0irst 6ame@ is of type char(>9) . meaning it is a string "ith >9 characters). 'ne thing to note is that different relational databases allo" for different data types, so it is "ise to consult "ith a database.specific reference first. The SQL synta( for C!EATE TABLE is C!EATE TABLE #table$name# 4#column ,# #data$type$(or$column$,#; #column 7# #data$type$(or$column$7#; <<< 9 So, if "e are to create the customer table specified as above, "e "ould type in C!EATE TABLE customer 4 irst$'ame char46-9; Last$'ame char46-9; Address char46-9; City char46-9; Country char4769; Birth$%ate date9 Sometimes, "e "ant to provide a default value for each column. / default value is used "hen you do not specify a column@s value "hen inserting data into the table. To specify a default value, add S+efault MvalueNS after the data type declaration. #n the above e(ample, if "e "ant to default column S/ddressS to SRn2no"nS and :ity to S%umbaiS, "e "ould type in C!EATE TABLE customer 4 irst$'ame char46-9; Last$'ame char46-9;

Address char46-9 de(ault :Jnknown:; City char46-9 de(ault :Mumbai:; Country char4769; Birth$%ate date9 Iou can also limit the type of information a table Q a column can hold. This is done through the C"'ST!A&'T 2ey"ord, "hich is discussed ne(t. SQL C"'ST!A&'T ++ Iou can place constraints to limit the type of data that can go into a table. Such constraints can be specified "hen the table "hen the table is first created via the C!EATE TABLE statement, or after the table is already created via the ALTE! TABLE statement. :ommon types of constraints include the follo"ing, '"T 'JLL Constraint, Knsures that a column cannot have 6RLL value. %E AJLT Constraint, Lrovides a default value for a column "hen none is specified. J'&QJE Constraint, Knsures that all values in a column are different. C*ECE Constraint, %a2es sure that all values in a column satisfy certain criteria. Frimary Eey Constraint, Rsed to uni1uely identify a ro" in the table. orei?n Eey Constraint, Rsed to ensure referential integrity of the data.

Kach constraint is discussed in the follo"ing sections. SQL '"T 'JLL++

$y default, a column can hold 6RLL. #f you not "ant to allo" 6RLL value in a column, you "ill "ant to place a constraint on this column specifying that 6RLL is no" not an allo"able value. 0or e(ample, in the follo"ing statement, C!EATE TABLE Customer 4S&% inte?er '"T 'JLL; Last$'ame varchar 4L-9 '"T 'JLL; irst$'ame varchar4L-99M :olumns SS#+S and SLast76ameS cannot include 6RLL, "hile S0irst76ameS can include 6RLL. /n attempt to e(ecute the follo"ing SQL statement, &'SE!T &'T" Customer 4Last$'ame; irst$'ame9 values 4:)on?:;:Een:9M "ill result in an error because this "ill lead to column SS#+S being 6RLL, "hich violates the 6'T 6RLL constraint on that column. SQL %e(ault ++

The +K0/RLT constraint provides a default value to a column "hen the #6SK&T #6T' statement does not provide a specific value. 0or e(ample, if "e create a table as belo", C!EATE TABLE Student 4Student$&% inte?er JniOue; Last$'ame varchar 4L-9; irst$'ame varchar 4L-9; Score %E AJLT P-9M and e(ecute the follo"ing SQL statement, &'SE!T &'T" Student 4Student$&%; Last$'ame; irst$'ame9 values 4:,-:;:@ohnson:;:!ick:9M The table "ill loo2 li2e the follo"ing, Student7#+ Last76ame 0irst76ame Score 19 Aohnson &ic2 O9

Kven though "e didn@t specify a value for the SScoreS column in the #6SK&T #6T' statement, it does get assigned the default value of O9 since "e had already set O9 as the default value for this column. SQL JniOue ++ The R6#QRK constraint ensures that all values in a column are distinct. 0or e(ample, in the follo"ing :&K/TK T/$LK statement, C!EATE TABLE Customer 4S&% inte?er JniOue; Last$'ame varchar 4L-9; irst$'ame varchar4L-99M column SS#+S has a uni1ue constraint, and hence cannot include duplicate values. Such constraint does not hold for columns SLast76ameS and S0irst76ameS. So, if the table already contains the follo"ing ro"s, S#+ Last76ame 0irst76ame 1 P Aohnson Aames /aron Stella Jina &alph

K(ecuting the follo"ing SQL statement, &'SE!T &'T" Customer values 4:L:;:Lee:;:Irace:9M "ill result in an error because @P@ already e(ists in the S#+ column, thus trying to insert another ro" "ith that value violates the R6#QRK constraint.

Llease note that a column that is specified as a primary 2ey must also be uni1ue. /t the same time, a column that@s uni1ue may or may not be a primary 2ey. #n addition, multiple R6#QRK constraints can be defined on a table. SQL Check ++ The :)K:F constraint ensures that all values in a column satisfy certain conditions. 'nce defined, the database "ill only insert a ne" ro" or update an e(isting ro" if the ne" value satisfies the :)K:F constraint. The :)K:F constraint is used to ensure data 1uality 0or e(ample, in the follo"ing :&K/TK T/$LK statement, C!EATE TABLE Customer 4S&% inte?er C*ECE 4S&% + -9; Last$'ame varchar 4L-9; irst$'ame varchar4L-99M :olumn SS#+S has a constraint .. its value must only include integers greater than 9. So, attempting to e(ecute the follo"ing statement, &'SE!T &'T" Customer values 4:AL:;:IonQales:;:Lynn:9M "ill result in an error because the values for S#+ must be greater than 9. Llease note that the C*ECE constraint does not get enforced by %ySQL at this time. SQL Frimary Eey ++ / primary 2ey is used to uni1uely identify each ro" in a table. #t can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do "ith the actual record). / primary 2ey can consist of one or more fields on a table. 4hen multiple fields are used as a primary 2ey, they are called a composite 2ey. Lrimary 2eys can be specified either "hen the table is created (using C!EATE TABLE) or by changing the e(isting table structure (using ALTE! TABLE). $elo" are e(amples for specifying a primary 2ey "hen creating a table, MySQL, C!EATE TABLE Customer 4S&% inte?er; Last$'ame varchar4L-9; irst$'ame varchar4L-9; F!&MA!G EEG 4S&%99M "racle, C!EATE TABLE Customer 4S&% inte?er F!&MA!G EEG; Last$'ame varchar4L-9; irst$'ame varchar4L-99M SQL Server, C!EATE TABLE Customer

4S&% inte?er F!&MA!G EEG; Last$'ame varchar4L-9; irst$'ame varchar4L-99M $elo" are e(amples for specifying a primary 2ey by altering a table, MySQL, ALTE! TABLE Customer A%% F!&MA!G EEG 4S&%9M "racle, ALTE! TABLE Customer A%% F!&MA!G EEG 4S&%9M SQL Server, ALTE! TABLE Customer A%% F!&MA!G EEG 4S&%9M 6ote, $efore using the /LTK& T/$LK command to add a primary 2ey, you@ll need to ma2e sure that the field is defined as @6'T 6RLL@ .. in other "ords, 6RLL cannot be an accepted value for that field. SQL "!E&I' EEG ++ / foreign 2ey is a field (or fields) that points to the primary 2ey of another table. The purpose of the foreign 2ey is to ensure referential integrity of the data. #n other "ords, only values that are supposed to appear in the database are permitted. 0or e(ample, say "e have t"o tables, a :RST'%K& table that includes all customer data, and an '&+K&S table that includes all customer orders. The constraint here is that all orders must be associated "ith a customer that is already in the :RST'%K& table. #n this case, "e "ill place a foreign 2ey on the '&+K&S table and have it relate to the primary 2ey of the :RST'%K& table. This "ay, "e can ensure that all orders in the '&+K&S table are related to a customer in the :RST'%K& table. #n other "ords, the '&+K&S table cannot contain information on a customer that is not in the :RST'%K& table. The structure of these t"o tables "ill be as follo"s, Table CUSTOMER
col,mn name c-aracteristic S$D Last_!ame First_!ame .rimar/ 0e/

Table ORDERS
col,mn name r1er_$D r1er_Date &,stomer_S$D Foreign 0e/ Amo,nt c-aracteristic .rimar/ 0e/

#n the above e(ample, the :ustomer7S#+ column in the '&+K&S table is a foreign 2ey pointing to the S#+ column in the :RST'%K& table. $elo" "e sho" e(amples of ho" to specify the foreign 2ey "hen creating the '&+K&S table, MySQL, C!EATE TABLE "!%E!S 4"rder$&% inte?er; "rder$%ate date; Customer$S&% inte?er; Amount double; Frimary Eey 4"rder$&%9; orei?n Eey 4Customer$S&%9 re(erences CJST"ME!4S&%99M "racle, C!EATE TABLE "!%E!S 4"rder$&% inte?er primary key; "rder$%ate date; Customer$S&% inte?er re(erences CJST"ME!4S&%9; Amount double9M SQL Server, C!EATE TABLE "!%E!S 4"rder$&% inte?er primary key; "rder$%ate datetime; Customer$S&% inte?er re(erences CJST"ME!4S&%9; Amount double9M $elo" are e(amples for specifying a foreign 2ey by altering a table. This assumes that the '&+K&S table has been created, and the foreign 2ey has not yet been put in, MySQL, ALTE! TABLE "!%E!S A%% "!E&I' EEG 4customer$sid9 !E E!E'CES CJST"ME!4S&%9M "racle, ALTE! TABLE "!%E!S A%% 4C"'ST!A&'T (k$orders,9 "!E&I' EEG 4customer$sid9 !E E!E'CES CJST"ME!4S&%9M SQL Server, ALTE! TABLE "!%E!S A%% "!E&I' EEG 4customer$sid9 !E E!E'CES CJST"ME!4S&%9M SQL Hiew ++ / vie" is a virtual table. / vie" consists of ro"s and columns *ust li2e a table. The difference bet"een a vie" and a table is that vie"s are definitions built on top of other tables (or vie"s), and do not hold data themselves. #f data is changing in the underlying table, the same change is reflected in the vie". / vie" can be built on top of a single table or multiple tables. #t can also be built on top of another vie". #n the SQL :reate ?ie" page, "e "ill see ho" a vie" can be built. ?ie"s offer the follo"ing advantages,

,< Ease o( use, / vie" hides the comple(ity of the database tables from end users. Kssentially "e can thin2 of vie"s as a layer of abstraction on top of the database tables. 7< Space savin?s, ?ie"s ta2es very little space to store, since they do not store actual data. L< Additional data security, ?ie"s can include only certain columns in the table so that only the non.sensitive columns are included and e(posed to the end user. #n addition, some databases allo" vie"s to have different security settings, thus hiding sensitive data from prying eyes. SQL C!EATE H&E) ++ ?ie"s can be considered as virtual tables. Jenerally spea2ing, a table has a set of definition, and it physically stores the data. / vie" also has a set of definitions, "hich is build on top of table(s) or other vie"(s), and it does not physically store the data. The synta( for creating a vie" is as follo"s, C!EATE H&E) #H&E)$'AME# AS #SQL Statement# SSQL StatementS can be any of the SQL statements "e have discussed in this tutorial. Let@s use a simple e(ample to illustrate. Say "e have the follo"ing table, TABLE Customer 4 irst$'ame char46-9; Last$'ame char46-9; Address char46-9; City char46-9; Country char4769; Birth$%ate date9 and "e "ant to create a vie" called V_Customer that contains only the 0irst76ame, Last76ame, and :ountry columns from this table, "e "ould type in, C!EATE H&E) H$Customer AS SELECT irst$'ame; Last$'ame; Country !"M Customer 6o" "e have a vie" called V_Customer "ith the follo"ing structure, Hiew V_Customer 4 irst$'ame char46-9; Last$'ame char46-9; Country char47699 4e can also use a vie" to apply *oins to t"o tables. #n this case, users only see one vie" rather than t"o tables, and the SQL statement users need to issue becomes much simpler. Let@s say "e have the follo"ing t"o tables, Table Store_Information
store_name Sales Date

Los Angeles $1500 Jan-05-1999 San Diego Los Angeles Boston $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

and "e "ant to build a vie" that has sales by region information. 4e "ould issue the follo"ing SQL statement, C!EATE H&E) H$!EI&"'$SALES AS SELECT A,<re?ion$name !EI&"'; SJM4A7<Sales9 SALES !"M Ieo?raphy A,; Store$&n(ormation A7 )*E!E A,<store$name = A7<store$name I!"JF BG A,<re?ion$name This gives us a vie", V_REGION_S !ES, that has been defined to store sales by region records. #f "e "ant to find out the content of this vie", "e type in, SELECT > !"M H$!EI&"'$SALES Result: )E(I'N SALES East $$00 4est $#050 SQL &ndex ++ #nde(es help us retrieve data from tables 1uic2er. Let@s use an e(ample to illustrate this point, Say "e are interested in reading about ho" to gro" peppers in a gardening boo2. #nstead of reading the boo2 from the beginning until "e find a section on peppers, it is much 1uic2er for us to go to the inde( section at the end of the boo2, locate "hich pages contain information on peppers, and then go to these pages directly. Joing to the inde( first saves us time and is by far a more efficient method for locating the information "e need. The same principle applies for retrieving data from a database table. 4ithout an inde(, the database system reads through the entire table (this process is called a @table scan@) to locate the desired information. 4ith the proper inde( in place, the database system can then first go through the inde( to find out "here to retrieve the data, and then go to these locations directly to get the needed data. This is much faster.

Therefore, it is often desirable to create inde(es on tables. /n inde( can cover one or more columns. The synta( for creating a table inde( is sho"n in the :&K/TK #6+KH section. $elo" "e discuss some general strategies "hen building and using an inde(, ,< Build index on columns o( inte?er type #ntegers ta2e less space to store, "hich means the 1uery "ill be faster. #f the column you "ant to build an inde( for is not of type integer, consider creating a surrogate integer 2ey (or simply a surrogate column of type integer) "hich maps one.to.one to the column you "ant to build the inde( for. 7< Eeep index as narrow as possible 6arro"er inde(es ta2e less space, re1uire less time to process, "hich in turn means the 1uery "ill run faster. L< Column order is important 0or inde(es covering multiple columns, the order of the columns in the inde( is important. The best practice is to use the column "ith the lo"est cardinality first, and the column "ith the highest cardinality last. &ecall cardinality means the number of distinct values for that column. So, if SSKLK:T +#ST#6:T (:'LR%61) 0&'% T/$LK76/%KWS returns >, that means the cardinality for :'LR%61 is >. N< Make sure the column you are buildin? an index (or is declared '"T 'JLL This can decrease the siCe of the inde(, "hich in turn "ill speed up the 1uery. SQL C!EATE &'%EK ++ /s mentioned in the #nde( overvie" page, a table inde( helps SQL statements run faster. The synta( for creating an inde( is, C!EATE &'%EK #&'%EK$'AME# "' #TABLE$'AME# 4C"LJM'$'AME9 Let@s assume that "e have the follo"ing table, TABLE Customer 4 irst$'ame char46-9; Last$'ame char46-9; Address char46-9; City char46-9; Country char4769; Birth$%ate date9 and "e "ant to create an inde( on the column Last76ame, "e "ould type in, C!EATE &'%EK &%K$CJST"ME!$LAST$'AME on CJST"ME! 4Last$'ame9 #f "e "ant to create an inde( on both :ity and :ountry, "e "ould type in,

C!EATE &'%EK &%K$CJST"ME!$L"CAT&"' on CJST"ME! 4City; Country9 There is no strict rule on ho" to name an inde(. The generally accepted method is to place a prefi(, such as S#+H7S, before an inde( name to avoid confusion "ith other database ob*ects. #t is also a good idea to provide information on "hich table and column(s) the inde( is used on. Llease note that the e(act synta( for C!EATE &'%EK may be different for different databases. Iou should consult "ith your database reference manual for the precise synta(. SQL ALTE! TABLE ++ 'nce a table is created in the database, there are many occasions "here one may "ish to change the structure of the table. Typical cases include the follo"ing, . /dd a column . +rop a column . :hange a column name . :hange the data type for a column Llease note that the above is not an e(haustive list. There are other instances "here /LTK& T/$LK is used to change the table structure, such as changing the primary 2ey specification or adding a uni1ue constraint to a column. The SQL synta( for ALTE! TABLE is ALTE! TABLE #table$name# /alter speci(ication1 Malter specificationN is dependent on the type of alteration "e "ish to perform. 0or the uses cited above, the Malter specificationN statements are, /dd a column, /++ Scolumn 1S Sdata type for column 1S +rop a column, +&'L Scolumn 1S :hange a column name, :)/6JK Sold column nameS Sne" column nameS Sdata type for ne" column nameS :hange the data type for a column, %'+#0I Scolumn 1S Sne" data typeS

Let@s run through e(amples for each one of the above, using the ScustomerS table created in the C!EATE TABLE section, Table "ustomer
&ol,mn !ame Data '/2e First_!ame Last_!ame A11ress &it/ &o,ntr/ Birt-_Date c-ar3504 c-ar3504 c-ar3504 c-ar3504 c-ar3254 1ate

0irst, "e "ant to add a column called SJenderS to this table. To do this, "e 2ey in, ALTE! table customer add Iender char4,9 &esulting table structure, Table "ustomer
&ol,mn !ame Data '/2e First_!ame Last_!ame A11ress &it/ &o,ntr/ Birt-_Date "en1er c-ar3504 c-ar3504 c-ar3504 c-ar3504 c-ar3254 1ate c-ar314

6e(t, "e "ant to rename S/ddressS to S/ddrS. To do this, "e 2ey in, ALTE! table customer chan?e Address Addr char46-9 &esulting table structure, Table "ustomer
&ol,mn !ame Data '/2e First_!ame Last_!ame A11r &it/ &o,ntr/ Birt-_Date "en1er c-ar3504 c-ar3504 c-ar3504 c-ar3504 c-ar3254 1ate c-ar314

Then, "e "ant to change the data type for S/ddrS to char(P9). To do this, "e 2ey in, ALTE! table customer modi(y Addr char4L-9 &esulting table structure, Table "ustomer
&ol,mn !ame Data '/2e First_!ame Last_!ame c-ar3504 c-ar3504

A11r &it/ &o,ntr/ Birt-_Date "en1er

c-ar3304 c-ar3504 c-ar3254 1ate c-ar314

0inally, "e "ant to drop the column SJenderS. To do this, "e 2ey in, ALTE! table customer drop Iender &esulting table structure, Table "ustomer
&ol,mn !ame Data '/2e First_!ame Last_!ame A11r &it/ &o,ntr/ Birt-_Date c-ar3504 c-ar3504 c-ar3304 c-ar3504 c-ar3254 1ate

SQL %!"F TABLE ++ Sometimes "e may decide that "e need to get rid of a table in the database for some reason. #n fact, it "ould be problematic if "e cannot do so because this could create a maintenance nightmare for the +$/@s. 0ortunately, SQL allo"s us to do it, as "e can use the %!"F TABLE command. The synta( for %!"F TABLE is %!"F TABLE #table$name# So, if "e "anted to drop the table called customer that "e created in the C!EATE TABLE section, "e simply type %!"F TABLE customer. SQL T!J'CATE TABLE ++ Sometimes "e "ish to get rid of all the data in a table. 'ne "ay of doing this is "ith %!"F TABLE, "hich "e sa" in the last section. $ut "hat if "e "ish to simply get rid of the data but not the table itself5 0or this, "e can use the T!J'CATE TABLE command. The synta( for T!J'CATE TABLE is T!J'CATE TABLE #table$name# So, if "e "anted to truncate the table called customer that "e created in SQL C!EATE TABLE, "e simply type, T!J'CATE TABLE customer

SQL JSE ++ The JSE 2ey"ord is used to select a database in %ySQL. The synta( is as follo"s, JSE #%atabase 'ame# 0or e(ample, if you "ant to connect to a database called SScoresS, you can type in the follo"ing, JSE ScoresM #n %ySQL, you can access tables in multiple databases by specifying M+atabase 6ameN.MTable 6ameN. #f the table you "ant to access is currently in the database you use, there is no need to specify the database name. 0or e(ample, if you "ant to access table S:ourse7119S from database SScoresS and table SStudentsS from database SLersonnelS, you can type in the follo"ing, JSE ScoresM SELECT <<< !"M Course$,,-; Fersonnel<Students )*E!E <<< M SQL &'SE!T &'T"++ #n the previous sections, "e have seen ho" to retrieve information from tables. $ut ho" do these ro"s of data get into these tables in the first place5 This is "hat this section, covering the &'SE!T statement, and ne(t section, covering tbe JF%ATE statement, are about. #n SQL, there are essentially basically t"o "ays to &'SE!T data into a table, 'ne is to insert it one ro" at a time, the other is to insert multiple ro"s at a time. Let@s first loo2 at ho" "e may &'SE!T data one ro" at a time, The synta( for inserting data into a table one ro" at a time is as follo"s, &'SE!T &'T" #table$name# 4#column,#; #column7#; <<<9 HALJES 4#value,#; #value7#; <<<9 /ssuming that "e have a table that has the follo"ing structure, Table Store_Information
&ol,mn !ame Data '/2e store_name Sales Date c-ar3504 5loat 1atetime

and no" "e "ish to insert one additional ro" into the table representing the sales data for Los /ngeles on Aanuary 19, 1999. 'n that day, this store had 8999 in sales. 4e "ill hence use the follo"ing SQL script, &'SE!T &'T" Store$&n(ormation 4store$name; Sales; %ate9 HALJES 4:Los An?eles:; C--; :@anA,-A,CCC:9 The second type of &'SE!T &'T" allo"s us to insert multiple ro"s into a table. Rnli2e the previous e(ample, "here "e insert a single ro" by specifying its values for all columns, "e no" use a SELECT statement to specify the data that "e "ant to insert into the table. #f you are thin2ing "hether this means that you are using information from another table, you are correct. The synta( is as follo"s, &'SE!T &'T" #table,# 4#column,#; #column7#; <<<9 SELECT #columnL#; #columnN#; <<< !"M #table7# 6ote that this is the simplest form. The entire statement can easily contain )*E!E, I!"JF BG, and *AH&'I clauses, as "ell as table *oins and aliases. So for e(ample, if "e "ish to have a table, Store_Information, that collects the sales information for year 199O, and you already 2no" that the source data resides in the Sales_Information# ta$le, "e@ll type in, &'SE!T &'T" Store$&n(ormation 4store$name; Sales; %ate9 SELECT store$name; Sales; %ate !"M Sales$&n(ormation )*E!E Gear4%ate9 = ,CCP )ere # have used the SQL Server synta( to e(tract the year information out of a date. 'ther relational databases "ill have different synta(. 0or e(ample, in 'racle, you "ill use to7char(date,@yyyy@)T199O. SQL JF%ATE ++ 'nce there@s data in the table, "e might find that there is a need to modify the data. To do so, "e can use the JF%ATE command. The synta( for this is JF%ATE #table$name# SET #column$,# = /new value1 )*E!E .condition2 0or e(ample, say "e currently have a table as belo", Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

and "e notice that the sales for Los /ngeles on 91Q9OQ1999 is actually 8>99 instead of 8P99, and that particular entry needs to be updated. To do so, "e use the follo"ing SQL, JF%ATE Store$&n(ormation SET Sales = 6-)*E!E store$name = #Los An?eles# A'% %ate = #@anA-PA,CCC# The resulting table "ould loo2 li2e Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $500 Jan-08-1999 $700 Jan-08-1999

#n this case, there is only one ro" that satisfies the condition in the )*E!E clause. #f there are multiple ro"s that satisfy the condition, all of them "ill be modified. #f no )*E!E clause is specified, all ro"s "ill be modified. #t is also possible to JF%ATE multiple columns at the same time. The synta( in this case "ould loo2 li2e the follo"ing, JF%ATE #table$name# SET column$, = /value,1; column$7 = /value71 )*E!E .condition2 SQL %ELETE !"M ++ Sometimes "e may "ish to get rid of records from a table. To do so, "e can use the %ELETE !"M command. The synta( for this is %ELETE !"M #table$name# )*E!E .condition2 #t is easiest to use an e(ample. Say "e currently have a table as belo", Table Store_Information
store_name Sales San Diego Los Angeles Boston Date

Los Angeles $1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

and "e decide not to 2eep any information on Los /ngeles in this table. To accomplish this, "e type the follo"ing SQL,

%ELETE !"M Store$&n(ormation )*E!E store$name = #Los An?eles# 6o" the content of table "ould loo2 li2e, Table Store_Information
store_name Sales Date San Diego Boston $250 Jan-07-1999 $700 Jan-08-1999

Advanced SQL ++ #n this section, "e discuss the follo"ing SQL 2ey"ords and concepts, SQL J'&"' SQL J'&"' ALL SQL &'TE!SECT SQL M&'JS SQL L&M&T SQL T"F SQL SubOuery SQL EK&STS SQL CASE

The concept of 6RLL is uni1uely important in SQL. )ence, "e include a section on the use of 6RLL, as "ell as 6RLL.related functions, SQL 'JLL SQL &S'JLL unction SQL & 'JLL unction SQL 'HL unction SQL Coalesce unction SQL 'JLL& unction

#n addition, "e sho" ho" SQL can be used to accomplish some of the more comple( operations, !ank Median !unnin? Totals Fercent To Total Cumulative Fercent To Total SQL J'&"' ++

The purpose of the SQL J'&"' command is to combine the results of t"o 1ueries together. #n this respect, J'&"' is some"hat similar to @"&' in that they are both used to related information from multiple tables. 'ne restriction of J'&"' is that all corresponding columns need to be of the same data type. /lso, "hen using J'&"', only distinct values are selected (similar to SELECT %&ST&'CT). The synta( is as follo"s, /SQL Statement ,1 J'&"' /SQL Statement 71 Say "e have the follo"ing t"o tables, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Internet_Sales
Date Sales

Jan-07-1999 $250 Jan-10-1999 $535 Jan-11-1999 $320 Jan-12-1999 $750

and "e "ant to find out all the dates "here there is a sales transaction. To do so, "e use the follo"ing SQL statement, SELECT %ate !"M Store$&n(ormation J'&"' SELECT %ate !"M &nternet$Sales Result: Date an!05!1""" an!0$!1""" an!0&!1""" an!10!1""" an!11!1""" an!1#!1"""

Llease note that if "e type SSELECT %&ST&'CT %ateS for either or both of the SQL statement, "e "ill get the same result set. SQL J'&"' ALL ++ The purpose of the SQL J'&"' ALL command is also to combine the results of t"o 1ueries together. The difference bet"een J'&"' ALL and J'&"' is that, "hile J'&"' only selects distinct values, J'&"' ALL selects all values. The synta( for J'&"' ALL is as follo"s, /SQL Statement ,1 J'&"' ALL /SQL Statement 71 Let@s use the same e(ample as the previous section to illustrate the difference. /ssume that "e have the follo"ing t"o tables, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Internet_Sales
Date Sales

Jan-07-1999 $250 Jan-10-1999 $535 Jan-11-1999 $320 Jan-12-1999 $750

and "e "ant to find out all the dates "here there is a sales transaction at a store as "ell as all the dates "here there is a sale over the internet. To do so, "e use the follo"ing SQL statement, SELECT %ate !"M Store$&n(ormation J'&"' ALL SELECT %ate !"M &nternet$Sales Result: Date an!05!1""" an!0$!1""" an!0&!1""" an!0&!1"""

an!0$!1""" an!10!1""" an!11!1""" an!1#!1""" SQL &'TE!SECT ++ Similar to the J'&"' command, &'TE!SECT also operates on t"o SQL statements. The difference is that, "hile J'&"' essentially acts as an "! operator (value is selected if it appears in either the first or the second statement), the &'TE!SECT command acts as an A'% operator (value is selected only if it appears in both statements). The synta( is as follo"s, /SQL Statement ,1 &'TE!SECT /SQL Statement 71 Let@s assume that "e have the follo"ing t"o tables, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Internet_Sales
Date Sales

Jan-07-1999 $250 Jan-10-1999 $535 Jan-11-1999 $320 Jan-12-1999 $750

and "e "ant to find out all the dates "here there are both store sales and internet sales. To do so, "e use the follo"ing SQL statement, SELECT %ate !"M Store$&n(ormation &'TE!SECT SELECT %ate !"M &nternet$Sales Result: Date an!0$!1""" Llease note that the &'TE!SECT command "ill only return distinct values.

SQL M&'JS ++ The M&'JS operates on t"o SQL statements. #t ta2es all the results from the first SQL statement, and then subtract out the ones that are present in the second SQL statement to get the final ans"er. #f the second SQL statement includes results not present in the first SQL statement, such results are ignored. The synta( is as follo"s, /SQL Statement ,1 M&'JS /SQL Statement 71 Let@s continue "ith the same e(ample, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Internet_Sales
Date Sales

Jan-07-1999 $250 Jan-10-1999 $535 Jan-11-1999 $320 Jan-12-1999 $750

and "e "ant to find out all the dates "here there are store sales, but no internet sales. To do so, "e use the follo"ing SQL statement, SELECT %ate !"M Store$&n(ormation M&'JS SELECT %ate !"M &nternet$Sales Result: Date an!05!1""" an!0&!1""" SAan.9>.1999S, SAan.9 .1999S, and SAan.9O.1999S are the distinct values returned from S SELECT %ate !"M Store$&n(ormation.S SAan.9 .1999S is also returned from the second SQL statement, SSELECT %ate !"M &nternet$Sales,S so it is e(cluded from the final result set.

Llease note that the M&'JS command "ill only return distinct values. Some databases may use EKCEFT instead of M&'JS. Llease chec2 the documentation for your specific database for the correct usage. SQL Limit ++ #n the previous section, "e sa" ho" L&M&T can be used to retrieve a subset of records in %ySQL. #n %icrosoft SQL Server, this is accomplished using the T"F 2ey"ord. The synta( for T"F is as follo"s, SELECT T"F /T"F ar?ument1 #column$name# !"M #table$name# "here MT'L argumentN can be one of t"o possible types, 1. /'1, The first ' records are returned. -. /':1 FE!CE'T, The number of records corresponding to ':D of all 1ualifying records are returned. 0or e(ample, "e may "ish to sho" the t"o highest sales amounts in Table Store_Information , Table Store_Information
store_name Los Angeles San Diego San Francisco Boston Sales Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

"e 2ey in, SELECT T"F 7 store$name; Sales; %ate !"M Store$&n(ormation "!%E! BG Sales %ESCM Result: store_name Sales Boston Date

Los Angeles $1500 an!05!1""" $$00 an!0&!1"""

/lternatively, if "e "ant to sho" the top ->G of sales amounts from Table Store_Information, "e 2ey in,

SELECT T"F 76 FE!CE'T store$name; Sales; %ate !"M Store$&n(ormation "!%E! BG Sales %ESCM Result: store_name Sales Date SQL SubOuery ++ #t is possible to embed a SQL statement "ithin another. 4hen this is done on the )*E!E or the *AH&'I statements, "e have a sub1uery construct. The synta( is as follo"s, SELECT #column$name,# !"M #table$name,# )*E!E #column$name7# /Comparison "perator1 4SELECT #column$nameL# !"M #table$name7# )*E!E /Condition19 M:omparison 'peratorN could be e1uality operators such as T, V, U, VT, UT. #t can also be a te(t operator such as SL#FKS. The portion in red is considered as the Sinner 1ueryS, "hile the portion in ?reen is considered as the Souter 1ueryS. Let@s use the same e(ample as "e did to illustrate SQL *oins, Table Store_Information
store_name Sales San Diego Boston $250 $700 Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 an!05!1"""

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

and "e "ant to use a sub1uery to find the sales of all stores in the 4est region. To do so, "e use the follo"ing SQL statement,

SELECT SJM4Sales9 !"M Store$&n(ormation )*E!E Store$name &' 4SELECT store$name !"M Ieo?raphy )*E!E re?ion$name = :)est:9 Result: S31+Sales, #050 #n this e(ample, instead of *oining the t"o tables directly and then adding up only the sales amount for stores in the 4est region, "e first use the sub1uery to find out "hich stores are in the 4est region, and then "e sum up the sales amount for these stores. #n the above e(ample, the inner 1uery is first e(ecuted, and the result is then fed into the outer 1uery. This type of sub1uery is called a simple subOuery. #f the inner 1uery is dependent on the outer 1uery, "e "ill have a correlated subOuery. /n e(ample of a correlated subOuery is sho"n belo", SELECT SJM4a,<Sales9 !"M Store$&n(ormation a, )*E!E a,<Store$name &' 4SELECT store$name !"M Ieo?raphy a7 )*E!E a7<store$name = a,<store$name9 6otice the )*E!E clause in the inner 1uery, "here the condition involves a table from the outer 1uery. SQL EK&STS ++ #n the previous section, "e used &' to lin2 the inner 1uery and the outer 1uery in a sub1uery statement. &' is not the only "ay to do so .. one can use many operators such as V, U, or T. EK&STS is a special operator that "e "ill discuss in this section. EK&STS simply tests "hether the inner 1uery returns any ro". #f it does, then the outer 1uery proceeds. #f not, the outer 1uery does not e(ecute, and the entire SQL statement returns nothing. The synta( for EK&STS is, SELECT #column$name,# !"M #table$name,# )*E!E EK&STS 4SELECT > !"M #table$name7# )*E!E /Condition19 Llease note that instead of X, you can select one or more columns in the inner 1uery. The effect "ill be identical. Let@s use the same e(ample tables, Table Store_Information

store_name Sales San Diego Boston $250 $700

Date Jan-07-1999 Jan-08-1999 Jan-08-1999

Los Angeles $1500 Jan-05-1999 Los Angeles $300

Table Geography
region_name store_name #ast #ast +est +est Boston !e( )or* Los Angeles San Diego

and "e issue the follo"ing SQL 1uery, SELECT SJM4Sales9 !"M Store$&n(ormation )*E!E EK&STS 4SELECT > !"M Ieo?raphy )*E!E re?ion$name = :)est:9 4e@ll get the follo"ing result, S31+Sales, #$50 /t first, this may appear confusing, because the sub1uery includes the Mregion7name T @4est@N condition, yet the 1uery summed up stores for all regions. Rpon closer inspection, "e find that since the sub1uery returns more than 9 ro", the EK&STS condition is true, and the condition placed inside the inner 1uery does not influence ho" the outer 1uery is run. SQL CASE ++ CASE is used to provide if.then.else type of logic to SQL. #ts synta( is, SELECT CASE 4#column$name#9 )*E' #condition,# T*E' #result,# )*E' #condition7# T*E' #result7# <<< /ELSE #result'#1 E'% !"M #table$name# SconditionS can be a static value or an e(pression. The ELSE clause is optional. #n our Table Store_Information e(ample, Table Store_Information

store_name Los Angeles San Diego San Francisco Boston

Sales

Date

$1500 Jan-05-1999 $250 Jan-07-1999 $300 Jan-08-1999 $700 Jan-08-1999

if "e "ant to multiply the sales amount from @Los /ngeles@ by - and the sales amount from @San +iego@ by 1.>, "e 2ey in, SELECT store$name; CASE store$name )*E' :Los An?eles: T*E' Sales > 7 )*E' :San %ie?o: T*E' Sales > ,<6 ELSE Sales E'% #'ew Sales#; %ate !"M Store$&n(ormation S6e" SalesS is the name given to the column "ith the :/SK statement. Result: store_name Los Angeles San Diego San Francisco Boston Ne5 Sales Date $%000 an!05!1""" $%$5 an!0$!1""" $%00 an!0&!1""" $$00 an!0&!1"""

SQL 'JLL ++ #n SQL, 'JLL means that data does not e(ist. 6RLL does not e1ual to 9 or an empty string. $oth 9 and empty string represent a value, "hile 'JLL has no value. /ny mathematical operations performed on 'JLL "ill result in 'JLL. 0or e(ample, 19 = 6RLL T 6RLL /ggregate functions such as SR%, :'R6T, /?J, %/H, and %#6 e(clude 6RLL values. This is not li2ely to cause any issues for SR%, %/H, and %#6. )o"ever, this can lead to confusion "ith /?J and :'R6T. Let@s ta2e a loo2 at the follo"ing e(ample, Table Sales_Data

store_name Sales Store A Store B Store & Store D 300 200 100 !6LL

$elo" are the results for each aggregate function, SR% (Sales) T B99 /?J (Sales) T -99 %/H (Sales) T P99 %#6 (Sales) T 199 :'R6T (Sales) T P 6ote that the /?J function counts only P ro"s (the 6RLL ro" is e(cluded), so the average is B99 Q P T -99, not B99 Q ! T 1>9. The :'R6T function also ignores the 6RLL rol", "hich is "hy :'R6T (Sales) T P. SQL &S'JLL unction ++ The #S6RLL function is available in both SQL Server and %ySQL. )o"ever, their uses are different, SQL Server #n SQL Server, the #S6RLL() function is used to replace 6RLL value "ith another value. 0or e(ample, if "e have the follo"ing table, Table Sales_Data
store_name Sales Store A Store B 300 !6LL

The follo"ing SQL, SKLK:T SR%(#S6RLL(Sales,199)) 0&'% Sales7+ataW returns !99. This is because 6RLL has been replaced by 199 via the #S6RLL function. %ySQL

#n %ySQL, the #S6RLL() function is used to test "hether an e(pression is 6RLL. #f the e(pression is 6RLL, this function returns 1. 'ther"ise, this function returns 9. 0or e(ample, #S6RLL(PXP) returns 9 #S6RLL(PQ9) returns 1 SQL & 'JLL unction ++ The #06RLL() function is available in %ySQL, and not in SQL Server or 'racle. This function ta2es t"o arguments. #f the first argument is not 6RLL, the function returns the first argument. 'ther"ise, the second argument is returned. This function is commonly used to replace 6RLL value "ith another value. #t is similar to the 'HL (unction in 'racle and the &S'JLL unction in SQL Server. 0or e(ample, if "e have the follo"ing table, Table Sales_Data
store_name Sales Store A Store B 300 !6LL

The follo"ing SQL, SELECT SJM4& 'JLL4Sales;,--99 !"M Sales$%ataM returns !99. This is because 6RLL has been replaced by 199 via the #S6RLL function. SQL 'HL unction ++ The 6?L() function is available in 'racle, and not in %ySQL or SQL Server. This function is used to replace 6RLL value "ith another value. #t is similar to the & 'JLL unction in %ySQL and the &S'JLL unction in SQL Server. 0or e(ample, if "e have the follo"ing table, Table Sales_Data
store_name Sales Store A Store B Store & 300 !6LL 150

The follo"ing SQL, SKLK:T SR%(6?L(Sales,199)) 0&'% Sales7+ataW

returns >>9. This is because 6RLL has been replaced by 199 via the #S6RLL function, hence the sum of the P ro"s is P99 = 199 = 1>9 T >>9. SQL C"ALESCE unction ++ The 'JLL& function ta2es t"o arguments. #f the t"o arguments are e1ual, then 6RLL is returned. 'ther"ise, the first argument is returned. #t is the same as the follo"ing CASE statement, SELECT CASE 4#column$name#9 )*E' #expression , = expression 7 # T*E' #'JLL# /ELSE #expression ,#1 E'% !"M #table$name# 0or e(ample, let@s say "e have a table that trac2s actual sales and sales goal as belo", Table Sales_Data
Store_name Act,al "oal Store A Store B Store & 50 70 25 50 50 30

4e "ant to sho" 6RLL if actual sales is e1ual to sales goal, and sho" actual sales if the t"o are different. To do this, "e issue the follo"ing SQL statement, SELECT Store$name; 'JLL& 4Actual;Ioal9 !"M Sales$%ataM The result is,
Store_name N3LLIF+Act/al9(oal, Store A Store B Store C N3LL 00 #5

SQL !ank ++ +isplaying the ran2 associated "ith each ro" is a common re1uest, and there is no straightfor"ard "ay to do so in SQL. To display ran2 in SQL, the idea is to do a self.*oin, list out the results in order, and do a count on the number of records that@s listed ahead of (and including) the record of interest. Let@s use an e(ample to illustrate. Say "e have the follo"ing table, Table Total_Sales
!ame Jo-n Sales 10

Jenni5er 15

Stella So2-ia "reg Je55

20 70 50 20

"e "ould type, SELECT a,<'ame; a,<Sales; C"J'T4a7<sales9 Sales$!ank !"M Total$Sales a,; Total$Sales a7 )*E!E a,<Sales 5= a7<Sales or 4a,<Sales=a7<Sales and a,<'ame = a7<'ame9 I!"JF BG a,<'ame; a,<Sales "!%E! BG a,<Sales %ESC; a,<'ame %ESCM Result: Name (reg So:8ia Stella e;; enni;er o8n Sales 50 00 #0 #0 15 10 Sales_)an7 1 # % % 5 -

Let@s focus on the )*E!E clause. The first part of the clause, (a1.Sales UT a-.Sales), ma2es sure "e are only counting the number of occurrences "here the value in the Sales column is less than or e1ual to itself. #f there are no duplicate values in the Sales column, this portion of the )*E!E clause by itself "ould be sufficient to generate the correct ran2ing. The second part of the clause, (a1.SalesTa-.Sales and a1.6ame T a-.6ame), ensures that "hen there are duplicate values in the Sales column, each one "ould get the correct ran2. SQL Median ++ To get the median, "e need to be able to accomplish the follo"ing, Sort the ro"s in order and find the ran2 for each ro". +etermine "hat is the SmiddleS ran2. 0or e(ample, if there are 9 ro"s, the middle ran2 "ould be >. 'btain the value for the middle.ran2ed ro".

Let@s use an e(ample to illustrate. Say "e have the follo"ing table, Table Total_Sales
!ame Jo-n Sales 10

Jenni5er 15

Stella So2-ia "reg Je55

20 70 50 20

"e "ould type, SELECT Sales Median !"M 4SELECT a,<'ame; a,<Sales; C"J'T4a,<Sales9 !ank !"M Total$Sales a,; Total$Sales a7 )*E!E a,<Sales 5 a7<Sales "! 4a,<Sales=a7<Sales A'% a,<'ame 5= a7<'ame9 ?roup by a,<'ame; a,<Sales order by a,<Sales desc9 aL )*E!E !ank = 4SELECT 4C"J'T4>93,9 %&H 7 !"M Total$Sales9M Result: 1e<ian #0 Iou "ill find that Lines -.B are the same as ho" "e find the ran2 of each ro". Line finds the SmiddleS ran2. +#? is the "ay to find the 1uotient in %ySQL, the e(act "ay to obtain the 1uotient may be different "ith other databases. 0inally, Line 1 obtains the value for the middle.ran2ed ro". SQL !unnin? Totals ++ +isplaying running totals is a common re1uest, and there is no straightfor"ard "ay to do so in SQL. The idea for using SQL to display running totals similar to that for displaying ran2, first do a self.*oin, then, list out the results in order. 4here as finding the ran2 re1uires doing a count on the number of records that@s listed ahead of (and including) the record of interest, finding the running total re1uires summing the values for the records that@s listed ahead of (and including) the record of interest. Let@s use an e(ample to illustrate. Say "e have the follo"ing table, Table Total_Sales
!ame Jo-n Stella So2-ia "reg Je55 Sales 10 20 70 50 20

Jenni5er 15

"e "ould type,

SELECT a,<'ame; a,<Sales; SJM4a7<Sales9 !unnin?$Total !"M Total$Sales a,; Total$Sales a7 )*E!E a,<Sales 5= a7<sales or 4a,<Sales=a7<Sales and a,<'ame = a7<'ame9 I!"JF BG a,<'ame; a,<Sales "!%E! BG a,<Sales %ESC; a,<'ame %ESCM Result: Name (reg So:8ia Stella e;; enni;er o8n Sales 50 00 #0 #0 15 10 )/nning_Total 50 "0 110 1%0 105 155

The combination of the )*E!E clause and the "!%E! BG clause ensure that the proper running totals are tabulated "hen there are duplicate values. SQL Fercent To Total ++ To display percent to total in SQL, "e "ant to leverage the ideas "e used for ran2Qrunning total plus sub1uery. +ifferent from "hat "e sa" in the SQL SubOuery section, here "e "ant to use the sub1uery as part of the SELECT. Let@s use an e(ample to illustrate. Say "e have the follo"ing table, Table Total_Sales
!ame Jo-n Stella So2-ia "reg Je55 Sales 10 20 70 50 20

Jenni5er 15

"e "ould type, SELECT a,<'ame; a,<Sales; a,<SalesR4SELECT SJM4Sales9 !"M Total$Sales9 Fct$To$Total !"M Total$Sales a,; Total$Sales a7 )*E!E a,<Sales 5= a7<sales or 4a,<Sales=a7<Sales and a,<'ame = a7<'ame9 I!"JF BG a,<'ame; a,<Sales "!%E! BG a,<Sales %ESC; a,<'ame %ESCM Result: Name Sales =ct_To_Total

(reg So:8ia Stella e;; enni;er o8n

50 00 #0 #0 15 10

0.%##0.#5&1 0.1#"0 0.1#"0 0.0"-& 0.0-05

The sub1uery SSKLK:T SR%(Sales) 0&'% Total7SalesS calculates the sum. 4e can then divide the individual values by this sum to obtain the percent to total for each ro". SQL Cumulative Fercent To Total ++ To display cumulative percent to total in SQL, "e use the same idea as "e sa" in the Fercent To Total section. The difference is that "e "ant the cumulative percent to total, not the percentage contribution of each individual ro". Let@s use the follo"ing e(ample to illuatrate, Table Total_Sales
!ame Jo-n Stella So2-ia "reg Je55 Sales 10 20 70 50 20

Jenni5er 15

"e "ould type, SELECT a,<'ame; a,<Sales; SJM4a7<Sales9R4SELECT SJM4Sales9 !"M Total$Sales9 Fct$To$Total !"M Total$Sales a,; Total$Sales a7 )*E!E a,<Sales 5= a7<sales or 4a,<Sales=a7<Sales and a,<'ame = a7<'ame9 I!"JF BG a,<'ame; a,<Sales "!%E! BG a,<Sales %ESC; a,<'ame %ESCM Result: Name (reg So:8ia Stella e;; enni;er o8n Sales 50 00 #0 #0 15 10 =ct_To_Total 0.%##0.5&00.$0"$ 0.&%&$ 0."%55 1.0000

The sub1uery SSKLK:T SR%(Sales) 0&'% Total7SalesS calculates the sum. 4e can then divide the running total, SSR%(a-.Sales)S, by this sum to obtain the cumulative percent to total for each ro".

SQL > SQLSyntax


#n this page, "e list the SQL synta( for each of the SQL commands in this tutorial. 0or detailed e(planations of each SQL synta(, please go to the individual section by clic2ing on the 2ey"ord. The purpose of this page is to have a 1uic2 reference page for SQL synta(, so you can learn SQL more 1uic2ly. Bookmark this page no" by pressing ControlA% so you can have this synta( page handy. Select Statement SKLK:T Scolumn7nameS 0&'% Stable7nameS %istinct SKLK:T +#ST#6:T Scolumn7nameS 0&'% Stable7nameS )here SKLK:T Scolumn7nameS 0&'% Stable7nameS 4)K&K SconditionS AndR"r SKLK:T Scolumn7nameS 0&'% Stable7nameS 4)K&K Ssimple conditionS ;M/6+Y'&N Ssimple conditionS<= &n SKLK:T Scolumn7nameS 0&'% Stable7nameS 4)K&K Scolumn7nameS #6 (@value1@, @value-@, ...) Between SKLK:T Scolumn7nameS 0&'% Stable7nameS 4)K&K Scolumn7nameS $KT4KK6 @value1@ /6+ @value-@ Like SKLK:T Scolumn7nameS 0&'% Stable7nameS 4)K&K Scolumn7nameS L#FK ;L/TTK&6< "rder By SKLK:T Scolumn7nameS 0&'% Stable7nameS M4)K&K SconditionSN '&+K& $I Scolumn7nameS M/S:, +KS:N Count SKLK:T :'R6T(Scolumn7nameS) 0&'% Stable7nameS

Iroup By SKLK:T Scolumn7name1S, SR%(Scolumn7name-S) 0&'% Stable7nameS J&'RL $I Scolumn7name1S *avin? SKLK:T Scolumn7name1S, SR%(Scolumn7name-S) 0&'% Stable7nameS J&'RL $I Scolumn7name1S )/?#6J (arithematic function condition) Create Table Statement :&K/TK T/$LK Stable7nameS (Scolumn 1S Sdata7type7for7column71S, Scolumn -S Sdata7type7for7column7-S, ... ) %rop Table Statement +&'L T/$LK Stable7nameS Truncate Table Statement T&R6:/TK T/$LK Stable7nameS &nsert &nto Statement #6SK&T #6T' Stable7nameS (Scolumn1S, Scolumn-S, ...) ?/LRKS (Svalue1S, Svalue-S, ...) Jpdate Statement RL+/TK Stable7nameS SKT Scolumn71S T Mne" valueN 4)K&K ;condition< %elete rom Statement +KLKTK 0&'% Stable7nameS 4)K&K ;condition<

Das könnte Ihnen auch gefallen