SQL 4 English Majors

Embed Size (px)

Citation preview

  • 8/3/2019 SQL 4 English Majors

    1/20

    by: Will Kotheimer

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 1

  • 8/3/2019 SQL 4 English Majors

    2/20

    TABLE of CONTENTS:

    Part I: Beginnings1.Introduction1.1 What is SQL?

    1.2 Why Study SQL?1.3 Audience and Scope:? pg. 3

    Part II: Te soware program2.1 phpmyadmin Graphical User interace.2.2 How to set up XAMPP, localhost, and phpmyadmin. pg. 4

    Part III : A glossary o terms pg. 5

    Part IV: Visual Approaches

    Databases: A visual approach. pg. 6

    Part V: Instructions or creating a database in phpmyadmin pg. 7

    Part VI: Some SQL Querying in action. pg. 115.1 Te Generic SELEC statement pg. 115.2 SELEC specic categories, GROUP BY, ASC, DESC pg. 125.3 JOINS and aliases: helps you make meaningulconnections pg. 135.4 Further explanation o JOIN example pg. 14

    5.5 Aggregate Functions ` pg. 155.5 LIKE clause pg. 16

    Part VII Conclusion.

    Part VIII Appendix.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 2

  • 8/3/2019 SQL 4 English Majors

    3/20

    INTRODUCTION:

    WHY SUDY SQL?

    You would want to study SQL i you are working in an oce environomentand your company used databases. An example o some o the environmentswhere SQL would be used include a doctors oce, a university oce, acorporate website, and an auto parts supplier. Tere are many places wheredatabases can be used.

    WHA IS SQL?

    SQL is Structured Query Language, a language developed during the 1970sto be used in databases.

    WHO IS HIS MANUAL INENDED FOR, AND JUS HOW

    GOOD IS I? (AUDIENCE AND SCOPE)

    Tis manual is primarily or people without technical saavy, such as thosegied with understanding the world through a lense o metaphor, art, andstories. My hope is that it will be user riendly or those who normally ndtechnical manuals challenging. Tis manual is not or advanced users but Ido hope that technically minded people could enjoy it as well.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 3

    Part I: Beginnings

  • 8/3/2019 SQL 4 English Majors

    4/20

    PART II: The Software program

    The phpmyadmin GUI

    PHPMYADMIN is a graphical user interace that allows you to create tables and do querieswith relative ease. It is also the ocial database creator or mysql, a popular open sourceversion o SQL.

    SEP 1: go to google and type in xammp.

    SEP 2: it is the rst entry- Apacheends-xampp, click on it.

    SEP 4: Wait while it downloads.

    SEP 3: Click on the one or your operating system.

    SEP 5: Use the install procedures provided by the Apache company.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 4

    Setting up XAMPP on your computer

  • 8/3/2019 SQL 4 English Majors

    5/20

    PART III: A Glossary of SQL Terms

    DAABASE: A collection o values organized by categories usually connectd to id numbers reerring tospecic people, items, or locations; larger databases are urther organized by tables.

    QUERY: A search or inormation in a database.

    SELEC: A statement in SQL used at the begining o a query that allows the computer to know to queryand display the inormation that ollows it.

    FROM: A statement in SQL that tells the computer to make the query with the table categories ollow-ing FROM.

    WHERE: A statement in SQL that liits the result o a query to a specic request.

    INNER JOIN . . . ON: A statement in SQL that allows two or more tables to be connected and displayed.

    GROUP BY: A statement in SQL that species what category will be used to order the display.

    ALIASES: one or two letters that stand in or a table name in a JOIN or WHERE clause, to keepthe syntax more readable. Aer the one or two letter aliase, there is a period then a category name thatcomes rom that eld,( e.g. p.description).

    LIKE: A statement in SQL that allows you to do a search query without actually knowing exactly thename o what you are looking or.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 5

  • 8/3/2019 SQL 4 English Majors

    6/20

    Part IV: Visual ApproachesDatabases: a visual approach

    Figure 1: A visual approach to the order database structure.

    Explanation:

    Each o these icons represent some piece o inormation. Row 1 has a persons name, address, and per-sonal id number. Row 2 carries the product number, category, description, and price. In row 3, the cashregister represents when the order was placed, the calendar with the $ by it represents when the orderwas paid, the rocket ship represents when the order was sent, and the shopping cart represents an item.Tere would be more icons than this in a real database, but this is just to show how these are structured.Row 4 has all the personal inormation: the credit card number, password, username, and the personal idnumber. It is good to keep the shoppers name and address apart rom this or obvious reasons.

    quantity

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 6

    Row1: Person inormation

    Row2: Product inormation

    Row3: Invoice inormation

    Row4: Personal inormation

  • 8/3/2019 SQL 4 English Majors

    7/20

    PART V: Instructions for creating a database in

    phpmyadminWe are now going to delve into creatingthese databases. I you set up XAMPPon your computer, then you can ollowalong below.

    1) Press the buttons to turn on apache and mysql.2) Open your browser

    3)In Browser url type: http://localhost

    Figure 24)Go to the le side o the screen and click on phpmyadmin.

    Figure 3

    5)You will see a bar that says CREAE DAABASE, type thename o the database. Figure 2. Since this is an ecommerce site, Iwill choose the name Ecommerce_site. Press Enter.

    Figure 4

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 7

    Behind the scenes: More than youwant to know about databases. Yeah,I know, you dont understand muchabout that either.

  • 8/3/2019 SQL 4 English Majors

    8/20

    6) It will take you to a screen that will prompt you to create a new table or your database. Here itwill also prompt you to enter the number o elds. Here I will do a simple products table. Belowis a graphical display o the products table with the relevant categories:

    PRODUCS ABLEDescription Item# Category Price

    Umbrella 9999 Accessories 12.99Jacket 9296 Outerwear 20.00Blouse 8918 Womens 25.00Black t-shirt 7902 Shirts 15.00Diamond Pendant 9268 Jewelry 999.00

    Okay, they are random categories, and the items wouldnt likely be grouped together like this(but this is just or an example.) In the next step I am going to show you how you would createthis database.

    Filling out the table categoriesNow it takes you to a screen where you will type the categories o each o the elds.

    Figure 6: In order to enter theseinto your database, you must rstenter the name o your table andthe number o elds. In the caseabove, you would enter Productsas the table name and 4 as thenumber o elds. And press Go.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 8

    Figure 6

    Figure 7: Tis is where you

    type the catgories. you willuse.

    Figure 7

    Figure 5: For

    this products table, theelds are description,item#, category, andprice.

    Figure 5:

  • 8/3/2019 SQL 4 English Majors

    9/20

    Figure 8: You can llout these elds howeveryou would like to, butI lled them out orthe products table, andincluded a heading

    or each category.

    We are not typing in vaues yet. We re creating the the homes, or boxes the values willl live in. It is

    important to realize that each eld can only hold one type o value. An integer (IN) would hold onetype, a variable character (VARCHAR) i.e. or word, or phrase, would hold another diferent type. AFLOA (decimal) would hold a third type such as a price.

    Also, each value must have a length, or how many characters the database will allow it to be (somethingthat would hold the number 1000 would have a length o 4). It also has a value that tells the databasewhether it will accept NULL values, which are not values at all, but are place holders.

    8) As you can see, I have lled in the attributes eld, type, length, values, andcollation. For English speakers, latin1_swedish_ci is the correct collation, because English has no specialcharacters.

    9) Phpmyadmin will prompt you as to whether you want to save, or add more elds. In this case youwill save. Aer you do this, it will take you to a screen that shows you these elds:

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 9

    Figure 8

    Figure 9

    Figure 9: Completedelds.

  • 8/3/2019 SQL 4 English Majors

    10/20

    11) Now its time to enter the values. Goto the INSER tab at the top o the screen.FIGURE A, Figure B Figure C

    Aer you press enter, you will see this message:

    12) As you can see in gure 11, once you have entered your rows, you are sent to another screen, wherethere is some code that looks like this:

    INSER INO `Ecommerce_site`.`Products` (`Description`, `Item_num`, `Category`, `Price`) VALUES(Umbrella, 9999, Accessories, 12.99), (Jacket, 9296, Outerwear, 20.00), (Blouse, 8918, Womensclothes, 25.00), (Black -shirt, 7902, Shirts, 15.00), (Diamond Pendant, 9268, Jewelry, 999.00);

    Tat is the data manipulation language o SQL, and you have seen the rst kind o actual SQL that you will

    Figure 10: Beore what youwere doing was creating theboxes that the values wouldgo in; now you are actually

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 10

    Figure 10

    Figure 11

  • 8/3/2019 SQL 4 English Majors

    11/20

    see. Tis is what is actually going on under the hood o SQL but you can learn how to do this as well, and thenenter into the database directly.

    Basically, this may require a little explanation, but aer you understand the concept, it will be easier.

    phpmyadmin is automatically inserting records into the site you set up. First its inserting into ecommerce data-

    base, products table then in parentheses its telling the phpmyadmin which elds (or boxes, as it were) to put theValues. Aer this, there is another set o parentheses that give the actual values that it has inserted.

    Tis is very useul to know, because it can help you set up a database in SQL rom the beginning.

    I you wanted to do that, eel ree to look at the appendix, you can also get a book on SQL syntax.Next I will show how this current database can be used in a useul way to learn to make queries with databases.

    Part VI: SQL Queries in Action

    I youve made it this ar, congratulations! You are on your way to learning Mysql. You have at leastbecome amiliar with how to set up a database in phpmyadmin, and have become a little amiliar with the code.

    Now you will learn some o the basics o queries, and learn the meanings o many o the common syntax types oMysql (and SQL, by extension). I you have created the databases, then you will be able to do the queries as well.I not, dont ret, there are screen shots included so you can still ollow along.

    I you have created the tables, you should open phpmyadmin and go to the SQL tab at the top, where you will beable to enter the queries as stated in the text.

    6.1 The Generic SELECT statement

    Te SELEC is the cornerstone o Structured Query Language. Tis is because it is what allows youto query in the rst place. Here is an example o a simple select statement:

    SELEC * FROM products WHERE price > 20;

    Lets break this down a little. SELEC * means to select everything, meaning, all categories in the productstable. It wouldnt necessarily useul to ask or everything though. Tere is another term in the syntax that givesa limit to this query, making it more useul. Te clause WHERE price > 20 indicates that the search should belimited to those products that have a price greater than $20.00.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 11

  • 8/3/2019 SQL 4 English Majors

    12/20

    Here is the result o the query:

    SELEC * FROM products WHERE price > 20;

    6.2 SELECT specifc categories: GROUP BY, desc, and asc

    Sometimes you may not want to select everything, at these times you most likelywant to select only specic categories. Heres a way you can do that with the preceding database:

    SELEC rstname, lastname FROM person GROUP BY lastname desc;

    Tis code will do two things both selects only the rstname and lastname, and alsoputs the categories in reverse alphabetical order, and the GROUP BY statement makes theresult ordered by last name. An alternative is the asc (or ascending) statement.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 12

    Te SELEC *statement inaction.

    Figure 12

    Figure 13

  • 8/3/2019 SQL 4 English Majors

    13/20

    6.3 JOINS and aliases: helps you make meaningful connections

    Joins are a very useul part o SQL. Consider the diferent tables weve been working with:

    Products table: elds- Description, Item_num, Category, price.

    Person table: elds rstname, lastname, streetaddress,city,state, zip, person_num.

    Purchases table: elds- Item_num, Invoice_num, person_num, quanitity, purchase_date, ship_date, paid_date.

    Personal Ino table: elds- creditcardnumber, threedigitcode, username, password, personnumber.

    First o all, you might be asking why we would split them up this way. Its a good question, requiring a bito explanation. First o all, the products table is not something that is connected to any particular person,so it must be independent. Likewise personal ino could be stored in a protected table, where only certainpeople could access the credit card numbers. Tese are just a ew reasons its useul to put these in separatetables.

    However, sometimes we want to see these tables side by side. Tats when joins are useul, and joins alsocan use aliases. Aliases are names we give tables to make them more manageable. A products table couldbe aliased as p, then to reer to the description category in the products table, we could say something likep.description.

    Suppose we wanted to merge three tables: we wanted the lastname description and price, but to do this,remember that the common link between the products table and person table is a purchase.

    Ten depending upon the aliases used (in this case I used c or person (customer) since theres more thanone p) the join would look something like this:

    SELEC lastname, pr.description, pr.price FROM person c inner join purchases p onc.person_num = p.person_num inner join products pr on p.item_num = pr.item_num OR-DER BY c.lastname;

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 13

  • 8/3/2019 SQL 4 English Majors

    14/20

    A key or this statement:

    pr.description: this is taking description category rom the table products.

    Te aliases in the statement are: pr or products, c or person, and p or purchases.

    For the tables person and purchases and the inner join brings them together when the person id is thesame.

    For the tables purchases and products the inner join brings them together when the item number is the

    same.

    Tereore, the person is connected to their products by way o their purchases.

    No inormation rom the purchases table is displayed though. Tis is accomplished because the tables arejoined, however only the three categories lastname, pr.description and pr.price are selected or display.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 14

    SELEC lastname,pr.description, pr.priceFROM person c in-ner join purchases pon c.person_num =p.person_num inner joinproducts pr on p.item_

    num = pr.item_numORDER BY c.lastname;

    You will noticethat thisstatement merges twotables that are connectedby a single table pur-chases.

    Te result o the query:

    Figure 14

    6.4 Further Explanation of Join Example

  • 8/3/2019 SQL 4 English Majors

    15/20

    GOOD JOB! Joins are hard. Now that you have some idea o what JOINS are, I would like to introduce you toa ew more useul tools to use in database queries. AGGREGAE FUNCIONS and the LIKE statement.

    AVG (category) . . . Gets the avg o all o a specic category.SUM (category) . . .Gets the sum o all o a specic category.

    MIN (category) . . .Gets the minimum o all o a specic category.MAX (category) . . .Gets the maximum o all o a specic category.COUN (category) . . .Gets the Count o all o a specic category.COUN (*) . . .Gets the count o all values.

    For instance:

    SELEC MIN(price) AS lowestprice;MAX(price) AS highestprice;AVG(price) AS averageprice;rom products;

    Tis would return the ollowing table:

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 15

    Notice the AS clause. Tis essentially is a way to rename the price, since its no longer applicableto just call it price. However, you could use the AS clause to rename any eld you were selectingsuch as saying SELEC lastname AS name; Tis would allow you to rename any eld into anothername.

    Figure 15

    6.5 Aggregate Functions:(adapted from Murachs PHP and Mysql pg. 595)

  • 8/3/2019 SQL 4 English Majors

    16/20

    6.6 The Like Clause:

    Te ollowing should help you understand the LIKE clause (and perhaps even like it!). . .suppose you were trying to remember the name o a band to tell your riend but youcould not remember the name. It sounds like Melana. With sql you could use the LIKEclause and say SELEC * FROM bands WHERE name LIKE %ana;

    Amongst those entries you would nd nirvana because the wildcard % was placed atthe beginning. Likewise, i you wanted to nd anything related to Pink you could useSELEC * FROM bands WHERE name LIKE PINK%; Tis would get you a bunch o

    entries such as Pink Floyd, Pink Fairies, and Pink.

    For the person database, we could use:SELEC * FROM person WHERE lastname LIKE Sing%; would get you John Singleton

    Likewise, by extension: SELEC *FROM person WHERE lastnameLIKE %EN%; would get you the result:

    result: Amy Benton

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 16

    Figure 16

  • 8/3/2019 SQL 4 English Majors

    17/20

    Well, I hope youve enjoyed this lesson on SQL and phpmyadmin.

    I you have questions there is a very large online community who support Mysql and who denitely desire tohelp others to learn it. Also, i youve gotten this ar, and you still think SQL is cool, congratulations, you shouldknow that theres some decent money to be made in database administration.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 17

    Part VII: Conclusion

  • 8/3/2019 SQL 4 English Majors

    18/20

    APPENDIX

    SETTING UP A DATABASE USING SQL

    Remember the part where you entered everything into tables? We are going back so we can set up the

    database with SQL. I you wanted to do that, you would go to the top tab on phpmyadmin and you wouldselect SQL. Into the command prompt box you would enter

    For the sake o this illustration, since the table Products already exists, I will use products_test to showhow this works.

    CREAE ABLE Products_test (Description VARCHAR(50) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,Item_Num IN(6) NO NULL,Category VARCHAR(50) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,PRICE FLOA(6) NO NULL) ENGINE = MYISAM

    Successul test graphic

    NOW HA YOU HAVE SEEN A LILE OF DAA MANIPULAION LANGUAGE, WE SHOULD BEABLE O FINISH HE ABLES.

    Te table we already set up is

    Products table: elds- Description, Item_num, Category, price.

    Te other tables are :

    Person table: elds rstname, lastname, streetaddress,city,state, zip, person_num.

    Purchases table: elds- Item_num, Invoice_num, person_num, quanitity, purchase_date, ship_date, paid_date.

    Personal Ino table: elds- creditcardnumber, threedigitcode, username, password, personnumber.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 1

  • 8/3/2019 SQL 4 English Majors

    19/20

    Tese are set up the same way, through the two step process o Creating a table, then INSERING values intothat table. o save time I will give an example o doing one table with SQL, then I will do the rest o the tableswith the phpmyadmin. Feel ree to try them yoursel, i you want to, or you can just ollow along.

    CREATING THE PERSON TABLE

    1) First we want to open the SQL tab on phpmyadmin (make sure ECOMMERCE-SIE is selected on the sidetab, or you might be creating a table in another database.)

    2) Ten well put in the SQL to create the table:

    CREAE ABLE person (rstname VARCHAR(20) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,lastname VARCHAR(20) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,address VARCHAR(30) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,city VARCHAR(20) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,state VARCHAR(2) CHARACER SE latin1 COLLAE latin1_swedish_ci NO NULL ,zipcode IN(5) NO NULL ,person_num IN(7) NO NULL) ENGINE = MYISAM

    Tis looks like a lot, but really its just the same thing over and over. We needed several o the same types oentered values. Firstname, Lastname, Address and City are all the same type. State was limited to two letters, sothere can be consistency, and zipcode were limiting to 5.

    Now i we complete the SQL or values o person, this is the result:

    INSER INO `Ecommerce_site`.`Person` (`rstname`, `lastname`, `address`, `city`, `state`, `zipcode`, `per-son_num`) VALUES (Abbey, Smith, 315 State Street,Louisville,KY, 40220, 100112), (John, Apple, 4000 DixieHwy, Louisville,KY,40312,101113), (Lee, Singleton, 15 Jesuit Way, Boulder, CO, 80301, 101114), (Amy,Benton, 143 Mary Lane, Bowling Green, KY, 42101, 101115), (Polly, Harvey, 190 Kensington Ct, London,England, 45654, 10799)

    In this instance, there is no error, however, i you encounter an error, it might be in the quotes. Notice the rstquotes must be backticks (this is located on the top le o your keyboard), and the second quotes must be singlequotes . I they are apostrophes, slightly slanted, this will not work. Tis can happen i you simply cut and pasteyour data and replace it with new data rom a previous SQL entry. Sometimes it doesnt enter correctly.

    SQL PRIMER FOR ECHWRIING ENG 307 -- pg. 1

  • 8/3/2019 SQL 4 English Majors

    20/20

    SOURCES:

    Book Sources:

    1) Harris, Ray, and Mike Murach. Murachs PHP and Mysql. United States: Mike Murachand Associates: 2010.

    2) Markel, Mike. echnical Communication. New York: Bedord St. Martins: 2010.

    Other sources:

    1) Lindsey, Jim. Mysql CI 436 Blackboard Lecture. Bowling Green 2011.

    Photocredits:

    Nerdy ront cover image: inspiredeater.comUnder the hood image: rides.musclemustangastords.comLadies restroom icon: http://www.mricons.com/show/ladies-iconsCity icon: iconarchive.comStreet sign icon: iconarchive.comKy state icon: istockphoto.comNumber sign icon: hash sign rom twitter.Drawer icon: iconarchive.comShopping cart icon: id18536.securedata.netDescription icon: stockphotos.itMoney symbol icon: history.nd.govCash register icon: moi-meme.comCalendar icon: iconarchive.comRocketship icon: easyvectors.comCredit card icon: iconarchive.comUsername icon: savoot.comPassword icon: ratedapartments.deexercising man: scienticamerican.comyawning women: psychologytoday.comDiferent height kids: almightydad.comWedding: styleityou.com);

    Villain: netpowersystem.comLike OMG Hailey Williams: Fanpop.com