Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to MySQL.

Similar presentations


Presentation on theme: "Introduction to MySQL."— Presentation transcript:

1 Introduction to MySQL

2 Relational Databases Relational databases model data by storing rows and columns in tables. The power of the relational database lies in its ability to efficiently retrieve data from those tables and in particular where there are multiple tables and the relationships between those tables involved in the query.

3 Terminology Database - Contains many tables
Relation (or table) - contains tuples and attributes Tuple (or row) - is a set of fields it generally represents an “object” like a person or a music track Attribute (also column or field) - One of possibly many elements of data corresponding to the object represented by the row

4 A relation is defined as a set of tuples that have the same attributes
A relation is defined as a set of tuples that have the same attributes. A tuple usually represents an object and information about that object. Objects are typically physical objects or concepts. A relation is usually described as a table, which is organized into rows and columns. All the data referenced by an attribute are in the same domain and conform to the same constraints. (wikipedia)

5 Columns / Attributes Rows / Tuples Tables / Relations

6 Application Structure
Software (i.e. PHP) Database Data Model End User SQL SQL Developer Database Tools (i.e. phpMyAdmin) DBA

7 Common Database Systems
Three Major Database Management Systems in wide use Oracle - Large, commercial, enterprise-scale, very very tweakable MySql - Simpler but very fast and scalable - commercial open source SqlServer - Very nice - from Microsoft (also Access) Many other smaller projects, free and open source HSQL, SQLite, Postgress, ...

8 MySQL MySQL is a very popular, open source database.
Officially pronounced “my Ess Que Ell” (not my sequel). Handles very large databases; very fast performance. Why are we using MySQL? Free (much cheaper than Oracle!) Each student can install MySQL locally. Easy to use Shell for creating tables, querying tables, etc. Easy to use with PHP, Java JDBC and others.

9 Crash Course Fundamentals
In order to write project 2 and 3, you need: a database. basic understand of SQL (Structured Query Language) Some students may have database backgrounds; others may not. The purpose of this lecture is to get all students up to speed on database fundamentals.

10 Use MySQL In order to use MySQL, you can use either:
Command Line. XAMPP Control Panel (then run MYSQL). After that you can click on Admin or go to the browser and type: Feel free to use the way that you feel comfortable with. But you have to remember the main SQLs commands for the final exam and the homework. Check these links:

11 SQL SQL (Structured Query Language) is the language we use to issue commands to the database Create a table Retrieve some data Insert data Delete data

12 Web interface to MySQL myPhpAdmin: A popular web interface to MySQL that comes bundled with XAMPP and WAMP The default URL: Note: On new MySQL installations the single user account defined is “root” and the password is blank or “”.

13 Connecting to MySQL MySQL provides an interactive shell for creating tables, inserting data, etc. On Windows, just go to c:\mysql\bin, and type: Mysql You can do that using command line.

14 Connecting to MySQL To login you have to provide username, password and host. By default you can use either: mysql -u root mysql -u root -p -h

15 Sample Session For example:
Enter password: ***** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 241 to server version: Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> To exit the MySQL Shell, just type QUIT or EXIT: mysql> QUIT mysql> exit

16 Using a Database To get started on your own database, first check which databases currently exist. Use the SHOW statement to find out which databases currently exist on the server: mysql> show databases; | Database | | mysql | | test | 2 rows in set (0.01 sec)

17

18 Your first MySQL Command
Kind of like print 'hello world‘ show databases;

19 If this does not work, stop and figure out why.
Some of these are part of MySQL and store internal data - don't mess with them.

20 Creating a Database Command Line: CREATE DATABASE People; USE People;

21 Use MySQL through PHPMyAdmin Make sure your MySQL service is running
Use MySQL through PHPMyAdmin Make sure your MySQL service is running. If using XAMPP, open the control panel. If the button for MySQL says Start, click it to start the service.

22 Open PHPMyAdmin (PMA) by clicking the Admin button or by navigating a browser to

23 Using phpmyadmin

24 Creating a Database To create a new database, issue the “create database” command: mysql> create database webdb; To use the selected the database, issue the “use” command: mysql> use webdb;

25 Showing current tables inside current DB
Once you have selected a database, you can view all database tables: mysql> show tables; Empty set (0.02 sec) An empty set indicates that I have not created any tables yet.

26 Start Simple - A Single Table
Lets make a table of Users in our People database. The table consists of two columns - Name and an CREATE TABLE Users( name VARCHAR(128), VARCHAR(128) ) To see the structure of the table use the command describe as follow. DESCRIBE Users;

27 Where it says Create database, enter a name and click on the Create button

28 Using phpmyadmin

29 Using phpmyadmin

30 Using phpmyadmin

31 Creating a Table Let’s create a table for storing pets. Table: pets
name: VARCHAR(20) owner: VARCHAR(20) species: VARCHAR(20) sex: CHAR(1) birth: DATE date: DATE VARCHAR is usually used to store string data.

32 Database Field Types In MySQL there are three main types : text number Date/Time.

33 Text Field Types CHAR(size)
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type TINYTEXT Holds a string with a maximum length of 255 characters TEXT Holds a string with a maximum length of 65,535 characters MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted.Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z')

34 Numeric Field Types TINYINT(size)
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis SMALLINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis MEDIUMINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis INT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis BIGINT(size) to normal. 0 to UNSIGNED*. The maximum number of digits may be specified in parenthesis FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

35 Date and Time Field Types
A date. Format: YYYY-MM-DDNote: The supported range is from ' ' to ' ' DATETIME() *A date and time combination. Format: YYYY-MM-DD HH:MM:SSNote: The supported range is from ' :00:00' to ' :59:59' TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch (' :00:00' UTC). Format: YYYY-MM-DD HH:MM:SSNote: The supported range is from ' :00:01' UTC to ' :14:07' UTC TIME() A time. Format: HH:MM:SSNote: The supported range is from '-838:59:59' to '838:59:59' YEAR() A year in two-digit or four-digit format.Note: Values allowed in four-digit format: 1901 to Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

36 Binary Large Object (BLOB)
Large raw data, files, images, word documents, PDF, Movies, etc etc.. No translation, indexing or character set TINYBLOB(n) - up to 255 BLOB(n) - up to 65K MEDIUMBLOB(n) - up to 16M LONGBLOB(n) - up to 4G

37 AUTO_INCREMENT Often as we make multiple tables and need to JOIN them together we need an integer, primary key for each row so we can efficiently add a reference to a row in a table, in some other table as a foreign key DROP TABLE Users; CREATE TABLE Users ( user_id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY, name VARCHAR(128), VARCHAR(128) ) DESCRIBE Users;

38 Use PHPMyAdmin to create a table Create a table to hold the data
Use PHPMyAdmin to create a table Create a table to hold the data. Give it a name. Select a number of columns and click Go.

39 Creating a Table Example 2
To create a table, use the CREATE TABLE command: mysql> CREATE TABLE pet ( -> name VARCHAR(20), -> owner VARCHAR(20), -> species VARCHAR(20), -> sex CHAR(1), -> birth DATE, death DATE); Query OK, 0 rows affected (0.04 sec)

40 Showing Tables To verify that the table has been created:
mysql> show tables; | Users | | pet | 1 row in set (0.01 sec)

41 Describing Tables To view a table structure, use the DESCRIBE command:
mysql> describe pet; | Field | Type | Null | Key | Default | Extra | | name | varchar(20) | YES | | NULL | | | owner | varchar(20) | YES | | NULL | | | species | varchar(20) | YES | | NULL | | | sex | char(1) | YES | | NULL | | | birth | date | YES | | NULL | | | death | date | YES | | NULL | | 6 rows in set (0.02 sec)

42 Deleting a Table To delete an entire table, use the DROP TABLE command: mysql> drop table pet; Query OK, 0 rows affected (0.02 sec)

43 Inset Data into a Table Use the INSERT statement to enter data into a table. INSERT INTO table [(column1, ... )] VALUES (value1, ...); INSERT INTO Users (name, ) VALUES ('Chuck', INSERT INTO Users (name, ) VALUES ('Sally', INSERT INTO Users (name, ) VALUES ('Somesh', INSERT INTO Users (name, ) VALUES ('Caitlin', INSERT INTO Users (name, ) VALUES ('Ted',

44 Insert Rules If columns are not specified, values must be in the same order in which they were defined (via CREATE command). Numeric values should not be quoted. String values must be quoted. Date and time values should be quoted.

45 Insert Rules SQL functions should not be quoted.
NULL should never be quoted. If a value is not specified, the value inserted is NULL, unless a default column value has been defined or column attribute is AUTO_INCREMENT. Quoting a column name is optional.

46

47

48 Inserting Without Columns Specified
Example: INSERT INTO recipe VALUES ( NULL, # id "Jello", # name "Add water", # content NULL, # creation 2 ); # category_id Note: Values must be specified in the order which the columns were created. No columns can be skipped. Every column must have a value or NULL. 48

49 Inserting With Columns Specified
Example: INSERT INTO notecard # COLUMNS ( name, content, category_id ) VALUES ( "Pudding", # name "Add milk.", # content 2 ); # category_id Note: The order of the column names must match the order of the values. 49

50 Loading/Insert Data Example 2
INSERT INTO pet VALUES ('Fluffy','Harold','cat','f', ' ',NULL); The next slide shows a full set of sample data.

51 More data… name owner species sex birth death Fluffy Harold cat f
Claws Gwen m Buffy dog Fang Benny Bowser Diane Chirpy bird Whistler Slim snake

52 Loading Sample Data You could create a text file `pet.txt' containing one record per line. Values must be separated by tabs, and given in the order in which the columns were listed in the CREATE TABLE statement. Then load the data via the LOAD DATA Command.

53 Sample Data File Fluffy Harold cat f 1993-02-04 \N
Claws Gwen cat m \N Buffy Harold dog f \N Fang Benny dog m \N Bowser Diane dog m Chirpy Gwen bird f \N Whistler Gwen bird \N \N Slim Benny snake m \N To Load pet.txt: mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; This Video shows how to use MySQL interface (not command line) to load data into a table

54 SQL Delete Delete: Used for removing row(s) in a table. Syntax:
DELETE FROM tableName [WHERE colName = const] [LIMIT n]; Pitfall: Failing to specify the WHERE or LIMIT clause deletes all the records in the table! Note: There is no “undo” on deleted data.

55 DELETE FROM Users WHERE email='ted@umich.edu'
SQL Delete Deletes a row in a table based on a selection criteria DELETE FROM Users WHERE

56 Delete Examples Examples: /* delete all rows (you sure?) */
DELETE FROM book; /* delete the first match */ DELETE FROM book WHERE lastName = "Wesley" LIMIT 1; /* delete via id (most common) */ WHERE id = 1; 56

57

58 SQL: Update UPDATE: Used for modifying existing table data. Syntax:
UPDATE tableName SET colName = newValue [WHERE colName = const] [LIMIT n];

59 UPDATE Users SET name='Charles' WHERE email='csev@umich.edu'
SQL: Update Pitfall: Failing to specify the WHERE or LIMIT clause modifies all the records in the table! Note: There is no “undo” on inadvertently modified data. UPDATE Users SET name='Charles' WHERE

60 Update Examples Examples: /* modify column 'content' on all rows */
UPDATE recipe SET content = "Mix ingredients"; /* replace "Drink" with "Beverage" (1st match) */ UPDATE category SET name = "Beverage" WHERE name = "Drink“ LIMIT 1; /* modify via unique id (most common) */ SET content = "Stir ingredients"; WHERE id = 1; 60

61

62 Select Command

63 Basic Queries Once logged in, you can try some simple queries.
For example: mysql> SELECT VERSION(), CURRENT_DATE; | VERSION() | CURRENT_DATE | | | | 1 row in set (0.00 sec) Note that most MySQL commands end with a semicolon (;) MySQL returns the total number of rows found, and the total time to execute the query.

64 Basic Queries Keywords may be entered in any lettercase.
The following queries are equivalent: mysql> SELECT VERSION(), CURRENT_DATE; mysql> select version(), current_date; mysql> SeLeCt vErSiOn(), current_DATE;

65 Basic Queries Here's another query. It demonstrates that you can use mysql as a simple calculator: mysql> SELECT SIN(PI()/4), (4+1)*5; | SIN(PI()/4) | (4+1)*5 | | | |

66 Basic Queries You can also enter multiple statements on a single line. Just end each one with a semicolon: mysql> SELECT VERSION(); SELECT NOW(); | VERSION() | | a-log | | NOW() | | :15:33 |

67 Multi-Line Commands mysql determines where your statement ends by looking for the terminating semicolon, not by looking for the end of the input line. Here's a simple multiple-line statement: mysql> SELECT -> USER() -> , -> CURRENT_DATE; | USER() | CURRENT_DATE | | | |

68 Canceling a Command If you decide you don't want to execute a command that you are in the process of entering, cancel it by typing \c mysql> SELECT -> USER() -> \c mysql>

69 SELECT: Used for extracting data contained in a table.
Syntax: SELECT column1 [, ...] FROM table1 [, ...] [WHERE clause] # no [SANTA clause] [ ORDER BY clause [ASC|DESC] ] [LIMIT n];

70 Retrieving Records: Select
The select statement retrieves a group of records - you can either retrieve all the records or a subset of the records with a WHERE clause The asterisk (*) can be used as a wildcard to specify all the columns in a query. SELECT * FROM Users SELECT * FROM Users WHERE

71

72

73 Sorting with ORDER BY You can add an ORDER BY clause to SELECT statements to get the results sorted in ascending or descending order SELECT * FROM Users ORDER BY SELECT * FROM Users ORDER BY name

74

75 The LIMIT Clause The LIMIT clause can request the first "n" rows, or the first "n" rows after some starting row. Note: the first row is zero, not one WHERE and ORDER BY clauses happen *before* the LIMIT is applied The limit can be a count or a starting row and count (starts from 0)

76 SELECT * FROM Users ORDER BY email DESC LIMIT 2;
The LIMIT Exmaple SELECT * FROM Users ORDER BY DESC LIMIT 2;

77

78

79 Counting Rows with SELECT
You can request to receive the count of the rows that would be retrieved instead of the rows SELECT COUNT(*) FROM Users; SELECT COUNT(*) FROM Users WHERE

80 For each of the examples, assume the following set of data.
name owner species sex birth death Fluffy Harold cat f Claws Gwen m Buffy dog Fang Benny Bowser Diane Chirpy bird Whistler Slim snake

81 SQL Select The SELECT statement is used to pull information from a table. The general format is: SELECT what_to_select FROM which_table WHERE conditions_to_satisfy

82 Selecting All Data The simplest form of SELECT retrieves everything from a table mysql> select * from pet; | name | owner | species | sex | birth | death | | Fluffy | Harold | cat | f | | NULL | | Claws | Gwen | cat | f | | NULL | | Buffy | Harold | dog | f | | NULL | | Fang | Benny | dog | m | | NULL | | Bowser | Diane | dog | m | | | | Chirpy | Gwen | bird | f | | NULL | | Whistler | Gwen | bird | | | NULL | | Slim | Benny | snake | m | | NULL | 8 rows in set (0.00 sec)

83 Selecting Particular Rows
You can select only particular rows from your table. For example, if you want to verify the change that you made to Bowser's birth date, select Bowser's record like this: mysql> SELECT * FROM pet WHERE name = "Bowser"; | name | owner | species | sex | birth | death | | Bowser | Diane | dog | m | | | 1 row in set (0.00 sec)

84 Selecting Particular Rows
To find all animals born after 1998 SELECT * FROM pet WHERE birth >= " "; To find all female dogs, use a logical AND SELECT * FROM pet WHERE species = "dog" AND sex = "f"; To find all snakes or birds, use a logical OR SELECT * FROM pet WHERE species = "snake" OR species = "bird";

85 Selecting Particular Columns
If you don’t want to see entire rows from your table, just name the columns in which you are interested, separated by commas. For example, if you want to know when your pets were born, select the name and birth columns. (see example next slide.)

86 Selecting Particular Columns
mysql> select name, birth from pet; | name | birth | | Fluffy | | | Claws | | | Buffy | | | Fang | | | Bowser | | | Chirpy | | | Whistler | | | Slim | | 8 rows in set (0.01 sec)

87 Sorting Data To sort a result, use an ORDER BY clause.
For example, to view animal birthdays, sorted by date: mysql> SELECT name, birth FROM pet ORDER BY birth; | name | birth | | Buffy | | | Claws | | | Slim | | | Whistler | | | Bowser | | | Chirpy | | | Fluffy | | | Fang | | 8 rows in set (0.02 sec)

88 Sorting Data To sort in reverse order, add the DESC (descending keyword) mysql> SELECT name, birth FROM pet ORDER BY birth DESC; | name | birth | | Fang | | | Fluffy | | | Chirpy | | | Bowser | | | Whistler | | | Slim | | | Claws | | | Buffy | | 8 rows in set (0.02 sec)

89 Working with NULLs NULL means missing value or unknown value.
To test for NULL, you cannot use the arithmetic comparison operators, such as =, < or <>. Rather, you must use the IS NULL and IS NOT NULL operators instead.

90 Working with NULLs For example, to find all your dead pets (what a morbid example!) mysql> select name from pet where death >IS NOT NULL; | name | | Bowser | 1 row in set (0.01 sec)

91 Pattern Matching MySQL provides: SQL Pattern matching:
standard SQL pattern matching; and regular expression pattern matching, similar to those used by Unix utilities such as vi, grep and sed. SQL Pattern matching: To perform pattern matching, use the LIKE or NOT LIKE comparison operators By default, patterns are case insensitive. Special Characters: _ Used to match any single character. % Used to match an arbitrary number of characters.

92 SELECT * FROM Users WHERE name LIKE '%e%'
The LIKE clause We can do wildcard matching in a WHERE clause using the LIKE operator SELECT * FROM Users WHERE name LIKE '%e%'

93

94 Pattern Matching Example
To find names beginning with ‘b’: mysql> SELECT * FROM pet WHERE name LIKE "b%"; | name | owner | species | sex | birth | death | | Buffy | Harold | dog | f | | NULL | | Bowser | Diane | dog | m | | |

95 Pattern Matching Example
To find names ending with `fy': mysql> SELECT * FROM pet WHERE name LIKE "%fy"; | name | owner | species | sex | birth | death | | Fluffy | Harold | cat | f | | NULL | | Buffy | Harold | dog | f | | NULL |

96 Pattern Matching Example
To find names containing a ‘w’: mysql> SELECT * FROM pet WHERE name LIKE "%w%"; | name | owner | species | sex | birth | death | | Claws | Gwen | cat | m | | NULL | | Bowser | Diane | dog | m | | | | Whistler | Gwen | bird | NULL | | NULL |

97 Pattern Matching Example
To find names containing exactly five characters, use the _ pattern character: mysql> SELECT * FROM pet WHERE name LIKE "_____"; | name | owner | species | sex | birth | death | | Claws | Gwen | cat | m | | NULL | | Buffy | Harold | dog | f | | NULL |

98 Regular Expression Matching
The other type of pattern matching provided by MySQL uses extended regular expressions. When you test for a match for this type of pattern, use the REGEXP and NOT REGEXP operators (or RLIKE and NOT RLIKE, which are synonyms).

99 Regular Expressions Some characteristics of extended regular expressions are: . matches any single character. A character class [...] matches any character within the brackets. For example, [abc] matches a, b, or c. To name a range of characters, use a dash. [a-z] matches any lowercase letter, whereas [0-9] matches any digit. * matches zero or more instances of the thing preceding it. For example, x* matches any number of x characters, [0-9]* matches any number of digits, and .* matches any number of anything. To anchor a pattern so that it must match the beginning or end of the value being tested, use ^ at the beginning or $ at the end of the pattern.

100 Reg Ex Example To find names beginning with b, use ^ to match the beginning of the name: mysql> SELECT * FROM pet WHERE name REGEXP "^b"; | name | owner | species | sex | birth | death | | Buffy | Harold | dog | f | | NULL | | Bowser | Diane | dog | m | | |

101 Reg Ex Example To find names ending with `fy', use `$' to match the end of the name: mysql> SELECT * FROM pet WHERE name REGEXP "fy$"; | name | owner | species | sex | birth | death | | Fluffy | Harold | cat | f | | NULL | | Buffy | Harold | dog | f | | NULL |

102 Counting Rows Databases are often used to answer the question, "How often does a certain type of data occur in a table?" For example, you might want to know how many pets you have, or how many pets each owner has. Counting the total number of animals you have is the same question as “How many rows are in the pet table?” because there is one record per pet. The COUNT() function counts the number of non-NULL results.

103 Counting Rows Example A query to determine total number of pets:
mysql> SELECT COUNT(*) FROM pet; | COUNT(*) | | |

104 Is that all there is to MySQL?
Of course not! Understanding databases and MySQL could take us several weeks (perhaps months!) For now, focus on: using the MySQL shell creating tables creating basic SQL queries

105 SQL Summary INSERT INTO Users (name, ) VALUES ('Ted', DELETE FROM Users WHERE UPDATE Users SET name='Charles' WHERE SELECT * FROM Users WHERE SELECT * FROM Users ORDER BY SELECT * FROM Users WHERE name LIKE '%e%' SELECT * FROM Users ORDER BY LIMIT 1,2; SELECT COUNT(*) FROM Users WHERE

106 This is not too exciting (so far)
Tables pretty much look like big fast programmable spreadsheet with rows, columns, and commands The power comes when we have more than one table and we can exploit the relationships between the tables

107 Summary SQL provides a structured language for querying/updating multiple databases. The more you know SQL, the better. The most important part of SQL is learning to retrieve data. selecting rows, columns, boolean operators, pattern matching, etc. Keep playing around in the MySQL Shell.


Download ppt "Introduction to MySQL."

Similar presentations


Ads by Google