7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
1/33
ICSE6105: Database ManagementSystems & Application
Lecture 1: Introduction RDBMS & MySQL
Semester II, Block II
June, 2012
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
2/33
Course Information
Course ICSE 6105: Database Management Systems and Application
2 Units Core Course
Hours20 Lecture hours
40 Practical hours
Instructor Dina Z. Machuve Tel: 0715 774 443 / 0767 774479
2
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
3/33
Course Objectives
To introduce students to the concepts and designmethods of database systems.
To be able to design and develop web based databasesystem.
Course Outcome:
At the end of the course students are expected to beknowledgeable and skilful in the concepts and designmethods of database management systems and theirapplications.
3
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
4/33
Course Contents
Introduction to database systems Relational Database concepts and terminology
Database programming language (MySQL, queries,programming and triggers)
PHP: Hypertext Preprocessor Overview Web Application Design
Physical database design using PHP-MySQL
Database security
4
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
5/33
References
Raghu Ranakrishnan, Johannes Gehrke, (2001) DatabaseManagement Systems, 2nd Edition
Carlos Coronel, Steven Morris and Peter Rob (2009), Database
Systems: Design, Implementation and Management, 9th Edition
Luke Welling & Laura Thompson, (2003), PHP and MySQL WebDevelopment, 2nd Edition
www.dev.mysql.com/doc
www.php.net/
5
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
6/33
Evaluation
Assessment:
One Test (20%)
Programming Assignments & Presentation (20%)
University Exam (60%)
6
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
7/33
Introduction
A Databaseis an organized collection of data.
A Database Management System (DBMS) providesmechanisms for storing, organizing, retrieving and
modifying data. DBMS allow for the access andstorage of data without concern for the internalrepresentation of the data in the database.
Todays most popular database systems areRelational Databases. Some popular RelationalDatabase Management Systems (RDBMs) areMicrosoft SQL Server, Oracle, Sybase, IBM DB2,Informix, PostgreSQL and MySQL.
7
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
8/33
Relational Databases
A relational database is a logical representation ofdata that allows the data to be accessed withoutconsideration of its physical structure.
A relational database stores data in tables. Tables
are composed of rows, and rows are composed ofcolumnsin which values are stored.
The tables primary key is a column in a table with aunique value that cannot be duplicated in other rows.
Good examples of primary key columns are socialsecurity numbers, an employee ID number and a partnumber in an inventory system.
8
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
9/33
Advantages of RDBMS (1/2)
A relational database management system (RDBMS)like MySQL takes things a step further, by enablingyou to create links between the various pieces ofdata in a database, and then use the relationships toanalyze the data in different ways.
Using a RDBMS allows you to quickly and easilyanswer queries about where your customers arefrom, which of your products is selling the best, or
what type of customers spend the most. Thisinformation can help you improve the site to keepmore users.
9
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
10/33
Advantages of RDBMs (2/2)
The advantages of using a RDBMS over a flat fileinclude:
RDBMSs can provide faster access to data than flatfiles.
RDBMs can be easily queried to extract sets of datathat fit certain criteria.
RDBMs provide random access to your data.
RDBMs have built-in privilege systems
RDBMs have built-in mechanisms for dealing withconcurrent access so that you as a programmerdont have to worry about it.
10
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
11/33
Relational Database Concepts (1/4)
Relational databases are, by far the most commonlyused type of database.
a) Tables: Relational databases are made up ofrelations, more commonly called tables. A tablecontains data.
CUSTOMERS
Fig. 1.1Rama Bookstore: Customer details are stored in a table
11
CustomerID Name Address City
1 Julie Smith 25 Oak Street Airport West2 Alan Wong 1/47 Haines Avenue Box Hill3 Michelle Arthur 357 North Road Yarraville
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
12/33
Relational Database Concepts (2/4)
The table has a name (Customers), a number ofcolumns, each corresponding to a different piece ofdata, and rows that correspond to individualcustomers.
b) Columns: Each column in a table has a uniquename and contains different data. Each column hasan associated data type. For instance, in theCustomers table in Fig. 1.1, you can see thatCustomerID is an integer and the other threecolumns are strings. Columns are sometimes calledfields or attributes.
12
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
13/33
Relational Database Concepts (3/4)
c) Rows: Each row in a table represents a differentcustomer. Because of the tabular format, they allhave the same attributes. Rows are also calledrecords or tuples.
d) Values: each row consists of a set of individualvalues that correspond to columns. Each valuemust have the datatype specified by its column.
e) Keys: the identifying column in a table is called thekeyor the primary key. Databases usually consistof multiple tables and use a key as a referencefrom one table to another.
13
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
14/33
Relational Database Concepts (4/4)
f) Schemas: The complete set of table designs for adatabase is called the database schema. A schemashould show the tables along with their columns, thedata types of the columns and indicate the primary
key of each table and any foreign keys. A schemadoes not include any data.
g)Relationships: Foreign keys represent arelationship between data in two tables. Three basickinds of relationships exist in a relational database.Relationships can be either one-to-one, one-to-many, or many-to-many.
14
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
15/33
MySQL (1/2)
In 1994, TcX, a Swedish consulting firm, needed a fastand flexible way to access its tables. Unable to find adatabase server that could accomplish the requiredtask adequately, Michael Widenius, the principaldeveloper at TcX, decided to create his own database
server. The resulting product was called MySQL, arobust and scalable relational database managementsystem (RDBMS).
MySQL is a multiuser, multithreaded (i.e. allowsmultiple simultaneous connections) RDBMS serverthat uses SQL to interact with and manipulate data.
15
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
16/33
MySQL (2/2)
According to its official web site, MySQL is "the world'smost popular open-source database." That's no smallclaim, but the numbers seem to back it up: today, overfive million sites are creating, using, and deploying
MySQL or MySQL-based applications. MySQL is well suited for developmentthe PHP
programming language has supported MySQL since itsearly days, and the PHP-MySQL combination hasbecome extremely popular for building database-drivenweb applications.
When creating applications with PHP and MySQL,you'll mostly be using DML statements.
16
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
17/33
Benefits of MySQL
1. Scalability.You can embed in an application or use it in massivedata warehousing environments.
2. Performance. You can optimize performance based on thepurpose of the database in your application.
3. Support for many programming languages. One can access
MySQL database from PHP and Ruby on Rails
4. Implementation of MySQL for Windows, Mac OS X, Linux andUNIX.
5. Handling large databases (e.g. tens of thousands of tables withmillions of rows).
MySQL is the database of choice for many businesses, universities
and individuals. MySQL is an open source software produce. Under
certain situations, a commercial license is required for MySQL.
17
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
18/33
Working with MySQL Database and Tables (1/5)
A large part of this chapter is focused on a singlecommand: the CREATE TABLE command. Whendesigning a database, this is one of the most importantcommands you must know, because it enables you to
decide the fundamental structure of your database.With the CREATE TABLE command, you can control,for example, how many fields each record mustcontain, which of those fields are optional, and whattype of data can be entered into each field. MySQL letsyou use different types of tables depending on yourstorage and data retrieval requirements. The CREATETABLE command enables you to specify thisinformation as well.
18
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
19/33
Working with MySQL Database and Tables (2/5)
How to... Name and create a MySQL database
Add tables to a database
Decide the names and default values for the fields ina table
Select the appropriate data type for a field
Use enumerations to limit field input to a predefined
list of values Specify which fields are optional and which are
mandatory
Select the table's primary and foreign key(s)
19
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
20/33
Working with MySQL Database and Tables (3/5)
How to. Index frequently used fields for better performance
Choose between MySQL's different table types (andselect the one best suited for your needs)
Alter a table definition after it's been created
Back up and restore a table or a database
View the structure and contents of a database or
table Empty a table of its records
Delete a database or table
20
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
21/33
Working with MySQL Database and Tables (4/5)
For the MySQL examples to execute correctly, youneed to set up a user account that allows users tocreate, delete and modify a database. After MySQL isinstalled, follow the steps below to set up a useraccount
Start the database server
Open a Command Prompt and start the MySQLcommand-line client tool so you can set up a useraccount, execute the command
mysql h localhost u root
The h option indicates the host (i.e. computer) onwhich the MySQL is running. The u option indicatesthe user account that will be used to log in to the
server. 21
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
22/33
Working with MySQL Database and Tables (5/5)
Next, youll add the icse6105 user account to themysql buil-in database. To create the icse6105user account with the password mccse, execute thefollowing commands from the mysql> prompt:
create user icse6105@localhost identified by mccse;grant select, insert, update, delete, create, drop,
references, execute on *.* to icse6105@localhost;
This creates the icse6105 user with the privilegesneeded to create the database.
Type the command exit; to terminate the MySQLmonitor.
22
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
23/33
MySQL Data Types (1/5)
23
Type
Used For
TINYINT, SMALLINT, MEDIUMINT,INT, BIGINT
Integer ValuesFLOAT Single- precision floating-point valuesDOUBLE Double-precision floating-point valuesDECIMAL Decimal valuesCHAR Fixed-length strings up to 255 charactersVARCHAR Variable-length strings up to 255 charactersTINYBLOB, BLOB, MEDIUMBLOB,LONGBLOB
Large blocks of binary dataTINYTEXT, TEXT, MEDIUMTEXT,LONGTEXT
Longer blocks of text dataDATE Date valuesTIME Time values or durationsYEAR Year valuesDATETIME Combined date and time valuesTIMESTAMP TimestampsENUM Fields that must contain one of a set of predefined
mutually exclusive valuesSET Fields that can contain zero, one or more of a set of
predefined values.
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
24/33
MySQL Data Types (2/5)
Choosing the data type best suited to the values youexpect to enter into the corresponding field isextremely important. When making this decision, takeinto account the following factors:
The range and type of values that the field will hold The types of calculations you expect to perform on
those values
The manner in which the data is to be formatted for
display purposes The manner in which the data is to be sorted and
compared against other fields
24
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
25/33
MySQL Data Types (3/5)
The available subtypes for each field and theirstorage efficiencies
Using the wrong data type can affect both the
performance of your RDBMS and the types ofoperations you can perform on that field. For example,using a VARCHAR type on a field that is meant fornumeric or date values could result in unexpected
behavior when you perform calculations on it, just asusing a large TEXT field for small string values couldlead to a waste of space and inefficient indexing.
25
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
26/33
MySQL Data Types (4/5)
Adding Field Modifiers and Keys You can apply a number of additional constraints, or modifiers,
to a field to increase the consistency of the data that will beentered into it, and to mark it as "special" in some way. Thesemodifiers can either appear as part of the field definition if they
apply only to that specific field (for example, a default value fora field) or after all the field definitions if they relate to multiplefields (for example, a multicolumn primary key).
The NULL and NOT NULL modifiers after each field definition
specify whether the field is allowed to be empty or if it must
necessarily be filled with data. The DEFAULT modifier :In the absence of a DEFAULT modifier
for NOT NULL fields, MySQL automatically inserts a
nonthreatening default value into the field.
26
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
27/33
MySQL Data Types (5/5)
The AUTO_INCREMENT modifier. This is particularly usefulwhen you need to generate row numbers for each record in thetable. However, the AUTO_INCREMENT modifier can only beapplied to numeric fields that are both NOT NULL and belongto the PRIMARY KEY. A table may only contain oneAUTO_INCREMENT field.
The PRIMARY KEY modifier. This serves as a unique identifier
for each record in the table, and it should be selected only aftercareful thought has been given to the inter-relationshipsbetween tables.
The FOREIGN KEY modifier. This links a field in one table to afield (usually a primary key) in another table, setting up a basefor relationships. However, foreign keys are only supported inMySQL's InnoDB table type
27
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
28/33
MySQL Table Types (1/5)
Following the field modifiers, the most frequently used one is theTYPE modifier, which tells MySQL which table type to use. A
number of such types of tables are available, each with differentadvantages. Here is a list:
a) MyISAM: The MyISAM format is optimized for speed and
reliability, it supports tables in excess of 4GB in size, and it canbe compressed to save space. This is MySQL's default tabletype and, as such, contains numerous MySQL-specificoptimizations and features.
Select this table type by adding TYPE = MYISAM to your
CREATE TABLE statement.b) InnoDB: The successor to the MyISAM format, the InnoDB
format, is the most sophisticated table type available inMySQL. It supports transactions and foreign keys (the onlyMySQL table type to do both).
28
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
29/33
MySQL Table Types (2/5)
and allows multiple simultaneous users to execute SELECTstatements; this improves performance and query responsetimes. InnoDB tables are fully portable between differentoperating systems, and include crash recovery features toavoid data corruption or loss.
Select this table type by adding TYPE = INNODB to your
CREATE TABLE statement.
c) HEAP : A HEAP table is stored in memory, making it extremelyfast. This format is optimized for temporary tables and it israrely used for other purposes. This is because the data in a
HEAP table is available only while the server is running, and isautomatically erased when the server shuts down and thememory is flushed.
Select this table type by adding TYPE = HEAP to yourCREATE TABLE statement.
29
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
30/33
MySQL Table Types (3/5)
d) BerkeleyDB : The BerkeleyDB format is one of the moreadvanced table formats supported by MySQL. It supportstransactions, checkpoints, crash recovery, and page-levellocking. However, it also has certain disadvantages:BerkeleyDB tables are not easily portable between differentoperating systems and they lack many of the optimizations of
the MyISAM format, making them slower and less memoryefficient.
Select this table type by adding TYPE = BDB to your CREATETABLE statement.
e) MERGE : The MERGE table format makes it possible for a
collection of MyISAM tables to be treated as one, bycombining them into a single "virtual" table. This table formatmakes improving performance or increasing query efficiencypossible in certain situations; however, it can only be used fortables that are completely identical in their internal structure.
30
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
31/33
MySQL Table Types (4/5)
Select this table type by adding TYPE = MERGE to yourCREATE TABLE statement.
f) ISAM : The forerunner of the newer MyISAM format, the ISAMformat is primarily offered for compatibility with older MySQLtables. It lacks many of the features of the MyISAM format,cannot handle large tables, and is more prone to fragmentation
(which degrades performance).Select this table type by adding TYPE = ISAM to yourCREATE TABLE statement.
Most of the time, you won't need to look further than the defaultMyISAM table type. Use the InnoDB table type only if you want
to use advanced features like transactions and foreign keys,use the MERGE table type if you need to query multiple similartables simultaneously, and use the HEAP table type if you need
a temporary data storage area.
31
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
32/33
MySQL Table Types (5/5)
The examples below correspond to the CREATE TABLEstatement and table type for each.
mysql> CREATE TABLE persons (
-> pid int(11) NOT NULL auto_increment,
-> pname varchar(255) NOT NULL default '',
-> PRIMARY KEY (pid)
-> ) TYPE=MyISAM;
Query OK, 0 rows affected (0.09 sec)
mysql> CREATE TABLE roles (
-> mid int(11) NOT NULL default '0',-> pid int(11) NOT NULL default '0',
-> role enum('A','D') NOT NULL default 'A',
-> PRIMARY KEY mid (mid,pid,role)
-> ) TYPE=MyISAM;
Query OK, 0 rows affected (0.11 sec)32
7/31/2019 ICSE6105 Lecture1 Introduction&MySQL
33/33
MySQL Operators
33
Operator What It DoesArithmetic operators
+ Addition- Subtraction* Multiplication/ Division; returns quotient% Division; returns modulus
Comparison operators= Equal to
aka != Not equal to NULL-safe equal to< Less than Greater than>= Greater than or equal to
BETWEEN Exists in specified rangeIN Exists in specified set
IS NULL Is not a NULL valueIS NOT NULL Is not a NULL value
LIKE Wildcard matchREGEXP aka RLINK Regular expression match
Logical operatorsNOT aka ! Logical NOT
AND aka && Logical ANDOR aka || Logical OR