1 introduction to my sql

64

Upload: prof-erwin-globio

Post on 14-Dec-2014

331 views

Category:

Education


2 download

DESCRIPTION

http://erwinglobio.wix.com/ittraininghttp://ittrainingsolutions.webs.com/http://erwinglobio.sulit.com.ph/

TRANSCRIPT

  • 1. To log in to mysql monitor: Mysql u root MySQL monitor To log out, just type exit or quit

2. Selecting a Database Mysql> show databases; Selecting a Database Mysql> use guitars; If you forget which database is selected usethe select database(); statement 3. Mysql> create database guitars; Mysql> use guitars; Mysql> select database(); 4. Mysql> drop database guitars; 5. The table creation command requires Name of the table Names of fields Definitions for each field The generic table creation syntax is: CREATE TABLE table_name (column_namecolumn_type); 6. The table name is up to you of course, butshould be a name that reflects the usage of thetable. For example, if you have a table that holds theinventory of a grocery store, you wouldnt namethe table s. You would probably name itsomething like grocery_inventory. Similarly, the field names you select should be asconcise as possible and relevant to the functionthey serve and the data they hold. For example,you might call a field holding the name of anitem item_name, not n. 7. mysql> CREATE TABLE grocery_inventory ( -> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,-> item_name VARCHAR (50) NOT NULL,-> item_desc TEXT,-> item_price FLOAT NOT NULL,-> curr_qty INT NOT NULL -> );Query OK, 0 rows affected (0.02 sec) The MySQL server responds with Query OK each time a command, regardless of type, is successful. 8. INSERT INTO table_name (column list) VALUES(column values); Within the parenthetical list of values, you must enclosestrings within quotation marks. The SQL standard is single quotes, but MySQL enablesthe usage of either single or double quotes. Rememberto escape the type of quotation mark used, if its withinthe string itself. Integers do not require quotation marks around them. 9. Two main parts of the INSERT statement: Column list Value List Only the value list is actually required, but ifyou omit the column list, you mustspecifically provide for each column in yourvalue list in the exact order. 10. A statement with all columns named: INSERT INTO grocery_inventory (id, item_name, item_desc,item_price, curr_qty) VALUES (1, Apples, Beautiful, ripeapples., 0.25, 1000); A statement that uses all columns but doesnot explicitly name them: INSERT INTO grocery_inventory VALUES (2, Bunches ofGrapes, Seedless grapes., 2.99, 500); 11. mysql> INSERT INTO grocery_inventory-> (id, item_name, item_desc, item_price, curr_qty)-> VALUES -> (1, Apples, Beautiful, ripe apples., 0.25, 1000); Query OK, 1 row affected (0.01 sec)mysql> INSERT INTO grocery_inventory VALUES (2, Bunchesof Grapes,-> Seedless grapes., 2.99, 500); Query OK, 1 row affected (0.01 sec) 12. Now for some more interesting methods of using INSERT.Because id is an auto-incrementing integer, you dont haveto put it in your value list.However, if theres a value you specifically dont want to list(such as id), you then must list the remaining columns in use.For example, the following statement does not list thecolumns and also does not give a value for id, and it producesan error: mysql> INSERT INTO grocery_inventory VALUES ->(Bottled Water (6-pack), 500ml spring water., 2.29, 250);ERROR 1136: Column count doesnt match value count atrow 1 13. Because you didnt list any columns, MySQLexpects all of them to be in the value list,causing an error on the previous statement. If the goal was to let MySQL do the work foryou by auto-incrementing the id field, youcould use either of these statements: 14. INSERT INTO grocery_inventory(item_name, item_desc, item_price,curr_qty) VALUES (Bottled Water (6-pack),500ml spring water., 2.29, 250); 15. A statement that uses all columns, but doesnot explicitly name them and indicates aNULL enTRy for id (so one is filled in for you): INSERT INTO grocery_inventory VALUES(NULL, Bottled Water (12-pack), 500mlspring water., 4.49, 500); 16. SELECT is the SQL command used to retrieverecords from your tables. This command syntax can be totallysimplistic or very complicated, depending onwhich fields you want to select, whether youwant to select from multiple tables, and whatconditions you plan to impose. 17. SELECT expressions_and_columns FROM table_name [WHERE some_condition_is_true] [ORDER BY some_column [ASC | DESC]][LIMIT offset, rows] 18. * stands for everything. So, to select everything (all rows, allcolumns) from the grocery_inventory table,your SQL statement would be: SELECT * FROM grocery_inventory; 19. If you only want to select specific columns,replace the * with the names of the columns,separated by commas. 20. Results of SELECT queries are ordered asthey were inserted into the table andshouldnt be relied on as a meaningfulordering system. If you want to order results a specific way,such as by date, ID, name, and so on, specifyyour requirements using the ORDER BYclause. 21. When selecting results from a table withoutspecifying a sort order, the results may or maynot be ordered by their key value. This occurs because MySQL reuses the spacetaken up by previously deleted rows. In other words, if you add records with ID valuesof 1 through 5, delete the record with ID number4, and then add another record (ID number 6),the records might appear in the table in thisorder: 1, 2, 3, 6, 5. 22. The default sorting of ORDER BY isascending (ASC); strings sort from A to Z,integers start at 0, dates sort from oldest tonewest. You can also specify a descendingsort, using DESC: 23. You can use the LIMIT clause to return only acertain number of records from your SELECTquery result. There are two requirements when using theLIMIT clause: the offset and the number of rows. The offset isthe starting position, and the number of rows should be self-explanatory. 24. Suppose you had more than two or threerecords in the grocery_inventory table, andyou wanted to select the ID, name, andquantity of the first two, ordered by curr_qty. In other words, you want to select the twoitems with the least inventory. The followingsingle-parameter limit will start at the 0(zero) position and go to the second record: 25. You have learned numerous ways to retrieveparticular columns from your tables but notspecific rows. This is when the WHERE clause comes in toplay. From the example SELECT syntax, yousee that WHERE is used to specify a particularcondition: SELECT expressions_and_columns FROMtable_name [WHERE some_condition_is_true] 26. Operator Meaning = Equal To !=Not equal to= Greater than or equal to > Greater than 27. Theres also a handy operator called BETWEEN, which isuseful with integer or data comparisons because it searchesfor results between a minimum and maximum value. Forexample: 28. Other operators include logical operators, whichenable you to use multiple comparisons withinyour WHERE clause. The basic logical operators are AND and OR. When using AND, all comparisons in the clausemust be true to retrieve results, whereas Using OR allows a minimum of one comparisonto be true.Also, you can use the IN operator to specify alist of items that you want to match. 29. You were introduced to matching stringswithin a WHERE clause by using = or !=, buttheres another useful operator for theWHERE clause when comparing strings: The LIKE operator. This operator uses twocharacters as wildcards in pattern matching: % Matches multiple characters Matches exactly one character 30. For example, if you want to find records inthe grocery_inventory table where the firstname of the item starts with the letter A, youwould use 31. Youre not limited to selecting only one tableat a time. That would certainly makeapplication programming a long and tedioustask! When you select from more than onetable in one SELECT statement, you arereally joining the tables together. Suppose you have two tables: fruit and color.You can select all rows from each of the twotables by using two separate SELECTstatements: 32. When you want to select from both tables atonce, there are a few differences in thesyntax of the SELECT statement. First, you must ensure that all the tablesyoure using in your query appear in theFROM clause of the SELECT statement. Using the fruit and color example, if yousimply want to select all columns and rowsfrom both tables, you might think you woulduse the following SELECT statement: 33. When you select from multiple tables, you must buildproper WHERE clauses to ensure that you really getwhat you want. In the case of the fruit and color tables, what youreally want is to see the fruitname and colornamerecords from these two tables where the IDs of eachmatch up. This brings us to the next nuance of the query how toindicate exactly which field you want when the fieldsare named the same in both tables! Simply, you append the table name to the field name,like this: tablename.fieldname 34. UPDATE is the SQL command used tomodify the contents of one or more columnsin an existing record or set of records. Themost basic UPDATE syntax looks like this: UPDATE table_name SET column1=newvalue, column2=new value2 [WHERE some_condition_is_true] 35. You must be careful and use a condition whenupdating a table, unless you really intend tochange all the columns for all records to thesame value. For the sake of argument, assume that "grape"is spelled incorrectly in the table, and you wantto use UPDATE to correct this mistake. Thisquery would have horrible results: mysql> UPDATE fruit SET fruit_name = grape;Query OK, 4 rows affected (0.00 sec) Rowsmatched: 4 Changed: 4 Warnings: 0 36. Assume your fruit table has not beencompletely filled with grapes but insteadcontains four records, one with a spellingmistake (grappe instead of grape). The UPDATE statement to fix the spellingmistake would be mysql> UPDATE fruit SET fruit_name =grape WHERE fruit_name = grappe; 37. When someone purchases a product, theinventory table should be updatedaccordingly. However, you wont knowexactly what number to enter in the curr_qtycolumn, just that you sold one. In this case,use the current value of the column andsubtract 1: mysql> UPDATE grocery_inventory SETcurr_qty = curr_qty - 1 WHERE id = 1; 38. Another method for modifying records is to usethe REPLACE command, which is remarkablysimilar to the INSERT command. REPLACE INTO table_name (column list)VALUES (column values); The REPLACE statement works like this: If therecord you are inserting into the table contains aprimary key value that matches a record alreadyin the table, the record in the table will bedeleted and the new record inserted in its place. 39. Using the grocery_inventory table, thefollowing command replaces the entry forApples: mysql> REPLACE INTO grocery_inventoryVALUES -> (1, Granny Smith Apples,Sweet!, 0.50, 1000); Query OK, 2 rows affected (0.00 sec) 40. The basic DELETE syntax is DELETE FROM table_name [WHERE some_condition_is_true] [LIMIT rows] Notice there is no column specification used inthe DELETE commandwhen you use DELETE,the entire record is removed. You might recall the fiasco earlier in this chapter,regarding grapes in the fruit table, whenupdating a table without specifying a conditioncaused all records to be updated. You must be similarly careful when usingDELETE. 41. Assuming the following structure and data ina table called fruit: mysql> SELECT * FROM fruit; 42. mysql> DELETE FROM fruit;You can always verify the deletion byattempting to SELECT data from the table. Ifyou issued this command after removing allthe records: mysql> SELECT * FROM fruit; Empty set (0.00 sec) 43. A conditional DELETE statement, just like aconditional SELECT or UPDATE statement, meansyou are using WHERE clauses to match specificrecords. You have the full range of comparison and logicaloperators available to you, so you can pick and choosewhich records you want to delete. A prime example would be to remove all records forrotten fruit from the fruit table: mysql> DELETE FROM fruit WHERE status =rotten; 44. DELETE FROM table_name [WHERE some_condition_is_true] [ORDER BY some_column [ASC | DESC]][LIMIT rows] 45. To remove the oldest record, first use ORDERBY to sort the results appropriately, and thenuse LIMIT to remove just one record: