SlideShare a Scribd company logo
1 
DDaattaabbaassee aapppplliiccaattiioonn 
CChhaapptteerr 11:: IInnttrroodduuccttiioonn ttoo MMyySSQQLL DDaattaabbaassee 
FFaaccuullttyy ooff PPhhyyssiiccaall aanndd BBaassiicc 
EEdduuccaattiioonn 
CCoommppuutteerr SScciieennccee 
BByy:: MMsscc.. KK aarrwwaann MM.. 
KKaarreeeemm 
22001155 -- 22001144 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
2 
RRooaadd MMaapp 
 Introducing Relational Databases 
 Terminology 
 MySQL Database 
 MySQL Command Line Client 
 Managing Databases 
 Manipulating data 
 Summary 
 Examples 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
 Database is involved like everywhere in our world 
• If we go to bank to deposit or withdraw. 
• Make hotel and airline reservation. 
• Purchase something on line. 
• Buy groceries in supermarkets. 
 More recent online applications 
• Youtube 
• iTunes 
• Geographic Information Systems (GIS) 
• Data Warehouses 
• Many other applications 
 IRS: assume it has 100 million taxpayers and each taxpayer file 5 forms 
with 400 characters of information per form=800 Gbyte. 
 Amazon.com: 15 million people visit per day; about 1000 people are 
responsible for database update. 
3 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
 DBMS contains information about a particular enterprise 
o Collection of interrelated data 
o Set of programs to access the data 
o An environment that is both convenient and efficient to use 
 Database Applications: 
o Banking: all transactions 
o Airlines: reservations, schedules 
o Universities: registration, grades 
o Sales: customers, products, purchases 
o Online retailers: order tracking, customized recommendations 
o Manufacturing: production, inventory, orders, supply chain 
o Human resources: employee records, salaries, tax deductions 
 Databases touch all aspects of our lives 
4 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
 A relational database manages data in tables. 
 Databases are managed by a relational database management system 
(RDBMS). 
 An RDBMS supports a database language to create and delete databases 
and to manage and search data. 
 The database language used in almost all DBMSs is SQL. 
 After creating a database, the most common SQL statements used are 
 INSERT to add data 
 UPDATE to change data 
 DELETE to remove data 
 SELECT to search data 
 A database table may have multiple columns, or attributes, each of which 
has a name. 
5 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
6 
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
 Tables usually have a primary key, which is one or more values that 
uniquely identify each row in a table (Figure 3.1.) 
 Typical DBMS Functionality are 
 Define a particular database in terms of its data types, structures, and 
constraints 
 Construct or Load the initial database contents on a secondary 
storage medium 
 Manipulate the database: 
o Retrieval: Querying, generating reports 
o Modification: Insertions, deletions and updates to its content 
o Accessing the database through Web applications 
 Share a database allows multiple users and programs to access the 
database simultaneously 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
7 
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
Figure 3-1. An example of relational database containing two related tables 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
8 
IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee 
 A database is modeled using entity-relationship (ER) modeling. 
(Figure 3.2.) 
Figure 3-2. An example of relational model of the winery database 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
9 
TTeerrmmiinnoollooggyy 
 Database 
 A repository to store data. 
 Data 
 Known facts that can be recorded and have an implicit meaning. 
 Table 
The part of a database that stores the data. A table has columns or 
attributes, and the data stored in rows. 
 Attributes 
 The columns in a table. All rows in table entities have the same 
attributes. For example, a customer table might have the attributes 
name, address, and city. Each attribute has a data type such as string, 
integer, or date. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
10 
TTeerrmmiinnoollooggyy 
 Rows 
 The data entries in a table. Rows contain values for each attribute. 
For example, a row in a customer table might contain the values 
"Matthew Richardson," "Punt Road," and "Richmond." Rows are also 
known as records. 
 Relational model 
 A model that uses tables to store data and manage the relationship 
between tables. 
 Relational database management system 
 A software system that manages data in a database and is based on 
the relational model. 
 Entity-relationship modeling 
 A technique used to describe the real-world data in terms of entities, 
attributes, and relationships. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
11 
TTeerrmmiinnoollooggyy 
 Constraints 
 Restrictions or limitations on tables and attributes. For example, a 
wine can be produced only by one winery, an order for wine can't 
exist if it isn't associated with a customer, having a name attribute 
could be mandatory for a customer. 
 Primary key 
 One or more attributes that contain values that uniquely identify 
each row. For example, a customer table might have the primary key 
of cust ID. The cust ID attribute is then assigned a unique value for 
each customer. A primary key is a constraint of most tables. 
 Index 
 A data structure used for fast access to rows in a table. An index is 
usually built for the primary key of each table and can then be used 
to quickly find a particular row. Indexes are also defined and built for 
other attributes when those attributes are frequently used in queries. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
12 
TTeerrmmiinnoollooggyy 
 Normalized database 
 A correctly designed database that is created from an ER model. 
There are different types or levels of normalization, and a third-normal 
form database is generally regarded as being an acceptably 
designed relational database. 
 Foreign key 
 A foreign key is the linking pin between two tables. 
 SQL 
 A query language that interacts with a DBMS. SQL is a set of 
statements to manage databases, tables, and data. 
Database system: Database Management System + Database 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
13 
MMyySSQQLL DDaattaabbaassee 
 MySQL Database 
MySQL is an open source relational database management system (RDBMS) 
based on Structured Query Language (SQL). 
 MySQL is originally developed, distributed, and supported by the Swedish 
company ( MySQL AB) , was acquired by Oracle in 2008. Developers can 
still use MySQL under the GNU General Public License (GPL). 
 Applications which use MySQL databases include: TYPO3, MODx, Joomla, 
WordPress, phpBB, MyBB, Drupal. 
 MySQL is also used in many high-profile, large-scale websites, including 
Google, Facebook, Twitter, Flickr, and YouTube. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
14 
MMyySSQQLL DDaattaabbaassee 
 Why are we using MySQL? 
 MySQL is released under an open-source license. So you have nothing 
to pay to use it. 
 MySQL is a very powerful program in its own right. It handles a large 
subset of the functionality of the most expensive and powerful 
database packages. 
 MySQL uses a standard form of the well-known SQL data language. 
 MySQL works on many operating systems ( Windows, UNIX and Linux) 
and with many languages including PHP, PERL, C, C++, JAVA etc. 
 MySQL works very quickly and works well even with large data sets. 
 MySQL is customizable. The open source GPL license allows 
programmers to modify the MySQL software to fit their own specific 
environments. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
15 
MMyySSQQLL DDaattaabbaassee 
 Why are we using MySQL? 
 MySQL is very friendly to PHP and JSP which are most appreciated 
languages for web development. 
 MySQL supports large databases, up to 50 million rows or more in a 
table. The default file size limit for a table is 4GB, but you can increase 
this to a theoretical limit of 8 million terabytes (TB). 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
16 
MMyySSQQLL DDaattaabbaassee 
 Why are we using MySQL? 
 The following diagrams show the enterprise database market share 
covered by Gartner and Cloud Database market. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
17 
MMyySSQQLL DDaattaabbaassee 
Interfaces ( Relative MySQL Tools) 
Free graphical administration applications (or "front ends") are available that 
integrate with MySQL and enable users to work with database structure and 
data visually. 
LAMP 
 It’s a Web development platform that uses Linux as the operating 
system, Apache as the Web server, MySQL as the relational database 
management system and PHP as the object-oriented scripting 
language. (Sometimes Perl or Python is used instead of PHP.) 
MySQL Command Line Client 
 MySQL Command Line Client is a single exe that allows connecting 
and running a sample query. it is a simple SQL shell for creating 
tables, inserting data, ..etc (with GNU readline capabilities). 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
18 
MMyySSQQLL DDaattaabbaassee 
 phpMyAdmin 
 It's a PHP-driven tool and handles every aspect of creating and 
managing a MySQL database application. phpMyAdmin also allows 
for the execution of MySQL commands from within the interface. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
19 
MMyySSQQLL DDaattaabbaassee 
 MySQL Workbench 
 It is a unified visual tool for database architects, developers. MySQL 
Workbench provides data modeling, SQL development, and 
administration tools for server configuration, user administration, 
backup etc.. MySQL Workbench is available on Windows, Linux and 
Mac OS X. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
20 
MMyySSQQLL DDaattaabbaassee 
 HeidiSQL 
 HeidiSQL – a full featured free front end that runs on Windows, and 
can connect to local or remote MySQL servers to manage databases, 
tables, column structure, and individual data records. Also supports 
specialized GUI features for date/time fields and enumerated 
multiple-value fields 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
21 
MMyySSQQLL DDaattaabbaassee 
 PHPMaker 
 PHPMaker is a powerful automation tool that can generate a full set 
of PHP quickly from MySQL, PostgreSQL, Microsoft Access, Microsoft 
SQL Server and Oracle databases. 
 Using PHPMaker, you can instantly create web sites that allow users 
to view, edit, search, add and delete records on the web. 
 PHPMaker is designed for high flexibility, numerous options enable 
you to generate PHP database applications that best suits your 
needs. 
 The generated codes are clean, straightforward and easy-to-customize. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
22 
MMyySSQQLL DDaattaabbaassee 
 PHP Report Maker 
 PHP Report Maker is a powerful reporting tool that can generate 
dynamic PHP Web reports from MySQL, PostgreSQL, Microsoft 
Access, Microsoft SQL Server and Oracle database. 
 You can instantly create live detail and summary reports or crosstabs 
reports for your Database Application. 
 PHP Report Maker is designed for high flexibility, numerous options 
enable you to generate the reports that best suits your needs. 
 PHP Report Maker can save you tons of time and is suitable for both 
beginners and experienced developers alike. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
23 
MMyySSQQLL DDaattaabbaassee 
 Apache web server 
 Apache is a web server package that works under Linux as well as 
under other operating systems (window, Unix, Etc...) 
 Apache 1.0 was released on 12/1/1995. 
 Apache web server developed by the Apache group. 
 The primary advantage of Apache is that it is generally free or 
available at modest costs. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
24 
MMyySSQQLL DDaattaabbaassee 
 MySQL data type 
MySQL uses many different data types, broken into three categories: 
numeric, date and time, and string types. 
 Numeric Data Types 
The MySQL numeric data types are: 
 INT - A normal-sized integer that the allowable range is from 
-2147483648 to 2147483647. You can specify a width of up to 11 
digits. 
 TINYINT - A very small integer, the allowable range is from -128 to 
127. You can specify a width of up to 4 digits. 
 SMALLINT - A small integer, the allowable range is from -32768 to 
32767. You can specify a width of up to 5 digits. 
 MEDIUMINT - A medium-sized integer, the allowable range is from 
-8388608 to 8388607. You can specify a width of up to 9 digits. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
25 
MMyySSQQLL DDaattaabbaassee 
 Numeric Data Types 
 BIGINT - A large integer, the allowable range is from 
-9223372036854775808 to 9223372036854775807. You can specify a 
width of up to 11 digits. 
 FLOAT(M,D) - A floating-point number. You can define the display 
length (M) and the number of decimals (D). Decimal precision can go 
to 24 places for a FLOAT. 
 DOUBLE(M,D) - A double precision floating-point number. You can 
define the display length (M) and the number of decimals (D). Decimal 
precision can go to 53 places for a DOUBLE. 
 DECIMAL(M,D) - An unpacked floating-point number. In unpacked 
decimals, each decimal corresponds to one byte. Defining the display 
length (M) and the number of decimals (D) is required. 
..Note: MySQL uses all the standard ANSI SQL numeric data types 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
26 
MMyySSQQLL DDaattaabbaassee 
 Date and Time Types 
The MySQL date and time data types are: 
 DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 
9999-12-31. For example, December 30th, 1973 would be stored as 
1973-12-30. 
 DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS 
format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For 
example, 3:30 in the afternoon on December 30th, 1973 would be 
stored as 1973-12-30 15:30:00. 
 TIMESTAMP- This looks like the previous DATETIME format, only 
without the hyphens between numbers; 3:30 in the afternoon on 
December 30th, 1973 would be stored as 19731230153000 
( YYYYMMDDHHMMSS ). 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
27 
MMyySSQQLL DDaattaabbaassee 
 Date and Time Types 
 TIME - Stores the time in HH:MM:SS format. 
 YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is 
specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 
69). If the length is specified as 4, YEAR can be 1901 to 2155. The 
default length is 4. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
28 
MMyySSQQLL DDaattaabbaassee 
 String Types 
The MySQL String types are: 
 CHAR(M) - A fixed-length string between 1 and 255 characters in 
length (for example CHAR(5)). Defining a length is not required, but 
the default is 1. 
 VARCHAR(M) - A variable-length string between 1 and 255 characters 
in length; for example VARCHAR(25). You must define a length when 
creating a VARCHAR field. 
 BLOB or TEXT - A field with a maximum length of 65535 characters. 
BLOBs are "Binary Large Objects" and are used to store large amounts 
of binary data, such as images or other types of files. Defining a length 
is not required. 
 TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum 
length of 255 characters. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
29 
MMyySSQQLL DDaattaabbaassee 
 String Types 
 MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a 
maximum length of 16777215 characters. 
 LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum 
length of 4294967295 characters. 
 ENUM - An enumeration, which is a fancy term for list. When defining 
an ENUM, you are creating a list of items from which the value must 
be selected (or it can be NULL). For example, if you wanted your field 
to contain "A" or "B" or "C", you would define your ENUM as ENUM 
('A', 'B', 'C'). 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
30 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 Connecting to MySQL 
 MySQL provides an interactive shell for creating tables, inserting data, 
etc… 
 On Windows, just go to C:AppServMySQLbinMySQL.exe 
 Or, go to start menu all rograms  Appserve click on the 
Windows icon 
..Connecting to MySQL Command Line Client 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
31 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 Sample Session 
Enter password: ***** 
Welcome to the MySQL monitor. Commands end with ; or g. 
Your MySQL connection id is 241 to server version: 5.0.51b-community-nt-log MySQL 
Community Edition < GPL> 
Type 'help;' or 'h' for help. Type 'c' to clear the buffer. 
mysql> 
…MySQL Command Line Client 
 To exit the MySQL Command , just type QUIT or EXIT: 
mysql> QUIT 
mysql> exit 
Note: MySQL Command Line Client is a single exe that 
allows connecting and running a sample query. it is a 
simple SQL shell (with GNU readline capabilities). 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
32 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 Basic Queries 
 Once logged in, you can try some simple queries. 
 For example: 
;mysql> SELECT VERSION(), CURRENT_DATE 
+---------------------------+-----------+ 
| VERSION() | CURRENT_DATE |+ 
---------------------------+-----------+ 
| 2002-05-26 | 3.23.49 | 
+---------------------------+-----------+ 
(row in set (0.00 sec 1 
 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. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
33 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 Basic Queries 
 Keywords may be entered in any letter case. 
 The following queries are equivalent: 
mysql> SELECT VERSION(), CURRENT_DATE; 
mysql> select version(), current_date; 
mysql> SeLeCt vErSiOn(), current_DATE; 
 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| 
+-------------+-------------+ 
| 0.707107 | 25 | 
+-------------+-------------+ 
1 row in set (0.00 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
34 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 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() | 
+------------------+ 
| 3.22.20a-log | 
+------------------+ 
+---------------------+ 
| NOW() | 
+---------------------+ 
| 2004 00:15:33 | 
+---------------------+ 
1 row in set (0.00 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
35 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 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 | 
+--------------------+------------------------+ 
| Karwan@localhost | 1999-03-18 | 
+--------------------+------------------------+ 
1 row in set (0.00 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
36 
MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt 
 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> 
 Using and selecting Database 
 To the select a database, issue the “use” command: 
mysql> use test; 
 Show status 
 Reports details of the MySQL DBMS performance and statistics. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
37 
MMaannaaggiinngg DDaattaabbaasseess 
 The Data Definition Language (DDL) is the set of SQL statements used to 
manage a database. 
 Creating Databases 
 The CREATE DATABASE statement can create a new, empty database 
without any tables or data. 
mysql> CREATE DATABASE webdb; 
mysql> use webdb; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
38 
MMaannaaggiinngg DDaattaabbaasseess 
 Creating Tables 
 After issuing the use Database command, you then usually issue 
commands to create the tables in the database. 
 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 
 To create a table, use the CREATE TABLE command: 
…Note: VARCHAR is usually used to store string data 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
39 
MMaannaaggiinngg DDaattaabbaasseess 
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) 
 To verify that the table has been created: 
mysql> show tables; 
+------------------------- + 
| Tables_in_webdb | 
+------------------------- + 
| pet | 
+------------------------- + 
1 row in set (0.01 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
40 
MMaannaaggiinngg DDaattaabbaasseess 
 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) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
41 
MMaannaaggiinngg DDaattaabbaasseess 
 Show Indexes 
 Presents the details of all indexes on the table, including the 
PRIMARY KEY. 
SHOW INDEX FROM tablename; 
 Altering Tables and Indexes 
 Indexes can be added or removed from a table after creation. 
 To add an index to the customer table, you can issue the following 
statement: 
ALTER TABLE customer ADD INDEX cities (city); 
 To remove an index from the customer table, use the following 
statement: 
ALTER TABLE customer DROP INDEX names; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
42 
MMaannaaggiinngg DDaattaabbaasseess 
 Displaying Database Structure with SHOW 
 Details of databases, tables, and indexes can be displayed with the 
SHOW command. 
 The SHOW command isn't part of the SQL standard and is MySQL-specific. 
 Show Data bases 
» Lists the databases that are accessible by the MySQL DBMS. 
» 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: 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
43 
MMaannaaggiinngg DDaattaabbaasseess 
mysql> show databases; 
+----------- --+ 
| Database | 
+----------- --+ 
| mysql | 
| webdb | 
+------------ -+ 
2 rows in set (0.01 sec) 
 Show tables 
» Shows the tables in the database once a database has been 
selected with the use command. 
mysql> show tables; 
Empty set (0.02 sec) 
» An empty set indicates that I had dropped all tables. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
44 
MMaannaaggiinngg DDaattaabbaasseess 
 Describing Tables 
» Shows the attributes, types of attributes, key information, 
whether NULL is permitted, defaults, and other information for a 
table. 
» 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) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
45 
MMaannaaggiinngg DDaattaabbaasseess 
» Or use “SHOW COLUMNS FROM tablename“ command to view a 
table structure. 
mysql> show columns from 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) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
46 
MMaanniippuullaattiinngg DDaattaa 
 The Data Manipulation Language (DML) encompasses all SQL 
statements used for manipulating data. There are four statements 
that form the DML statement set: 
» INSERT 
» DELETE 
» UPDATE 
» SELECT 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
47 
MMaanniippuullaattiinngg DDaattaa 
 Inserting Data 
 Having created a database and the accompanying tables and indexes, 
the next step is to insert data. 
 Inserting a row of data into a table can follow two different 
approaches. 
» First approach: 
Use the INSERT statement to enter data into a table. 
For example: 
INSERT INTO pet VALUES ('Fluffy','Harold','cat','f', 
'1999-02-04',NULL); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
48 
MMaanniippuullaattiinngg DDaattaa 
»Second approach: 
INSERT INTO pet SET 
Name = 'Fluffy', 
Owner = 'Harold', 
Species = 'cat', 
Sex = 'f', 
Birth = '1999-02-04', 
Date = NULL ; 
…Loading Data to pet table 
The first approach can actually be varied to function in a 
similar way to the second by including parenthesized 
attribute names before the VALUES keyword. 
INSERT INTO pet (Name, Owner ) VALUES ('Fluffy', 'Harold'); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
49 
MMaanniippuullaattiinngg DDaattaa 
 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. 
..pet.txt: Sample Data File 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
50 
MMaanniippuullaattiinngg DDaattaa 
 Loading Sample Data 
» To Load pet.txt: 
mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; 
» For each of the examples, assume the following set of data. 
..loading pet.txt into table pet 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
51 
MMaanniippuullaattiinngg DDaattaa 
 Deleting Data 
 There is an important distinction between dropping and deleting in 
SQL. 
» DROP is used to remove tables or databases. 
» DELETE is used to remove data. 
DELETE FROM pet; 
DELETE FROM pet WHERE name= ‘claws’; 
Deleting ‘Claws’ from table 
..pet University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
52 
MMaanniippuullaattiinngg DDaattaa 
 Updating Data 
 Data can be updated using a similar syntax to that of the INSERT 
statement. 
UPDATE pet SET owner=‘ali’; 
UPDATE pet SET owner= ‘ali' WHERE name = ‘fang’; 
…Updating table pet 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
53 
MMaanniippuullaattiinngg DDaattaa 
 Querying with SQL SELECT 
 The SELECT statement is used to query a database and for all output 
operations in SQL. 
» The simplest form of SELECT retrieves everything from a table 
mysql> select * from pet; 
8 rows in set (0.00 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
54 
MMaanniippuullaattiinngg DDaattaa 
 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"; 
1 row in set (0.00 sec) 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
55 
MMaanniippuullaattiinngg DDaattaa 
 Selecting Particular Rows 
» To find all animals born after 1998 
SELECT * FROM pet WHERE birth >= "1998-1-1"; 
» 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"; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
56 
MMaanniippuullaattiinngg DDaattaa 
 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. 
mysql> select name, birth from pet; 
(rows in set (0.01 sec 8 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
57 
MMaanniippuullaattiinngg DDaattaa 
 Sorting and Grouping Output 
 Sorting data (ORDER BY) 
» The ORDER BY clause sorts the data after the query has been 
evaluated. 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; 
(rows in set (0.01 sec 8 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
58 
MMaanniippuullaattiinngg DDaattaa 
 Sorting and Grouping Output 
 Sorting data (DESC) 
» To sort in reverse order, add the DESC (descending keyword) 
mysql> SELECT name, birth FROM pet ORDER BY birth DESC; 
(rows in set (0.01 sec 8 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
59 
MMaanniippuullaattiinngg DDaattaa 
 Working with NULLs 
» To sort in reverse order, add the DESC (descending keyword) 
» 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. 
» For example, to find all your dead pets (what a morbid 
example!) 
mysql> select name from pet where death >IS NOT NULL; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
60 
MMaanniippuullaattiinngg DDaattaa 
 Pattern Matching 
 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. 
Note: MySQL provides 
standard SQL pattern matching. 
regular expression pattern matching, similar to those 
used by Unix utilities such as vi, grep and sed. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
61 
MMaanniippuullaattiinngg DDaattaa 
 Pattern Matching Example 
 To find names beginning with ‘b’: 
mysql> SELECT * FROM pet WHERE name LIKE "b%"; 
 To find names ending with `fy': 
mysql> SELECT * FROM pet WHERE name LIKE "%fy"; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
62 
MMaanniippuullaattiinngg DDaattaa 
 Pattern Matching Example 
 To find names containing a ‘w’: 
mysql> SELECT * FROM pet WHERE name LIKE "%w%"; 
 To find names containing exactly five characters, use the _ pattern 
character: 
mysql> SELECT * FROM pet WHERE name LIKE "_____"; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
63 
MMaanniippuullaattiinngg DDaattaa 
 GROUP BY 
» The GROUP BY clause is different from ORDER BY because it 
doesn't sort the data for output. Instead, it sorts the data early in 
the query process, for the purpose of grouping or aggregation. 
SELECT city, COUNT(*) FROM customer 
GROUP BY city; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
64 
MMaanniippuullaattiinngg DDaattaa 
 There are several functions that can be used in aggregation with the 
GROUP BY clause. Five particularly useful functions are: 
» AVG( ): Finds the average value of a numeric attribute in a set. 
» MIN( ): Finds a minimum value of a string or numeric attribute in 
a set. 
» MAX( ): Finds a maximum value of a string or numeric attribute 
in a set. 
» SUM( ): Finds the sum total of a numeric attribute. 
» COUNT( ): Counts the number of rows in a set. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
65 
MMaanniippuullaattiinngg DDaattaa 
 Counting Rows Example 
» 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. 
» A query to determine total number of pets: 
mysql> SELECT COUNT(*) FROM pet; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
66 
MMaanniippuullaattiinngg DDaattaa 
 HAVING 
» The HAVING clause permits conditional aggregation of data into 
groups. 
SELECT city, count(*), max(salary) 
FROM customer GROUP BY city 
HAVING count(*) > 10; 
 DISTINCT 
» The DISTINCT operator presents only one example of each 
row from a query. 
SELECT DISTINCT surname FROM customer; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
67 
MMaanniippuullaattiinngg DDaattaa 
 Join Queries / Cartesian Product 
» A join query is a querying technique that matches rows from two 
or more tables based on a join condition in a WHERE clause and 
outputs only those rows that meet the condition. 
SELECT winery_name, region_name FROM winery, region 
ORDER BY winery_name, region_name; 
» The query produces all possible combinations of the four region 
names and 300 wineries in the sample database! In fact, the size 
of the output can be accurately calculated as the total number of 
rows in the first table multiplied by the total rows in the second 
table. In this case, the output is 4 x 300 = 1,200 rows. 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
68 
MMaanniippuullaattiinngg DDaattaa 
 Elementary Natural Joins 
» A cartesian product isn't the join we want. Instead, we want to 
limit the results to only the sensible rows. 
SELECT winery_name, region_name 
FROM winery, region 
WHERE winery.region_id = region.region_id 
ORDER BY winery_name; 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
69 
SSuummmmaarryy 
 Is that all there is to MySQL? 
» Of course not! 
» Understanding databases and MySQL could take us several 
months(perhaps years!) 
» For now, focus on: 
» using the MySQL shell with phpMyadmin 
» creating database 
» creating general and standard SQL queries 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
70 
SSuummmmaarryy 
 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 with phpMyadmin . 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
71 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE wine ( 
wine_id int(5) DEFAULT '0' NOT NULL auto_increment, 
wine_name varchar(50) DEFAULT '' NOT NULL, 
winery_id int(4), 
type varchar(10) DEFAULT '' NOT NULL, 
year int(4) DEFAULT '0' NOT NULL, 
description blob, 
PRIMARY KEY (wine_id), 
KEY name (wine_name) 
KEY winery (winery_id) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
72 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE winery ( 
winery_id int(4) DEFAULT '0' NOT NULL auto_increment, 
winery_name varchar(100) DEFAULT '' NOT NULL, 
region_id int(4), 
description blob, 
phone varchar(15), 
fax varchar(15), 
PRIMARY KEY (winery_id), 
KEY name (winery_name) 
KEY region (region_id) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
73 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE region ( 
region_id int(4) DEFAULT '0' NOT NULL auto_increment, 
region_name varchar(100) DEFAULT '' NOT NULL, 
description blob, 
map mediumblob, 
PRIMARY KEY (region_id), 
KEY region (region_name) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
74 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE customer ( 
cust_id int(5) NOT NULL auto_increment, 
surname varchar(50) NOT NULL, 
firstname varchar(50) NOT NULL, 
initial char(1), 
title varchar(10), 
addressline1 varchar(50) NOT NULL, 
addressline2 varchar(50), 
addressline3 varchar(50), 
city varchar(20) NOT NULL, 
state varchar(20), 
zipcode varchar(5), 
country varchar(20), 
phone varchar(15), 
fax varchar(15), 
email varchar(30) NOT NULL, 
birth_date date( ), 
salary int(7), 
PRIMARY KEY (cust_id), KEY names (surname,firstname) ); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
75 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE users ( 
cust_id int(4) DEFAULT '0' NOT NULL, 
user_name varchar(50) DEFAULT '' NOT NULL, 
password varchar(15) DEFAULT '' NOT NULL, 
PRIMARY KEY (user_name), 
KEY password (password) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
76 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE grape_variety ( 
variety_id int(3), 
variety_name varchar(20), 
PRIMARY KEY (variety_id), 
KEY var (variety) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
77 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE inventory ( 
wine_id int(5) DEFAULT '0' NOT NULL, 
inventory_id int(3) NOT NULL, 
on_hand int(5) NOT NULL, 
cost float(5,2) NOT NULL, 
case_cost float(5,2) NOT NULL, 
dateadded timestamp(12) DEFAULT NULL, 
PRIMARY KEY (wine_id,inventory_id) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
78 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE orders ( 
cust_id int(5) DEFAULT '0' NOT NULL, 
order_id int(5) DEFAULT '0' NOT NULL, 
date timestamp(12), 
discount float(3,1) DEFAULT '0.0', 
delivery float(4,2) DEFAULT '0.00', 
note varchar(120), 
PRIMARY KEY (cust_id,order_no) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
79 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE items ( 
cust_id int(5) DEFAULT '0' NOT NULL, 
order_id int(5) DEFAULT '0' NOT NULL, 
item_id int(3) DEFAULT '1' NOT NULL, 
wine_id int(4) DEFAULT '0' NOT NULL 
qty int(3), 
price float(5,2), 
date timestamp(12), 
PRIMARY KEY (cust_id,order_no,item_id) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
80 
EExxaammppllee 
 Example. The complete winestore DDL statements 
CREATE TABLE wine_variety ( 
wine_id int(5) DEFAULT '0' NOT NULL, 
variety_id int(3) DEFAULT '0' NOT NULL, 
id int(1) DEFAULT '0' NOT NULL, 
PRIMARY KEY (wine_id, variety_id) 
); 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
81 
EENNDD 
EENNDD…… 
AAnnyy qquueessttiioonnss....?? 
HHooppee yyoouu hhaavvee bbeeeenn hhaappppyy 
TThhaannkk yyoouu 
BByy:: MMsscc.. KKaarrwwaann MM.. 
KKaarreeeemm 
22001155 -- 22001144 
University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©

More Related Content

What's hot

What's hot (19)

[PHPUGPH] PHP Roadshow - MySQL
[PHPUGPH] PHP Roadshow - MySQL[PHPUGPH] PHP Roadshow - MySQL
[PHPUGPH] PHP Roadshow - MySQL
 
relational database
relational databaserelational database
relational database
 
Bank mangement system
Bank mangement systemBank mangement system
Bank mangement system
 
data-spread-demo
data-spread-demodata-spread-demo
data-spread-demo
 
Week 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data ModelWeek 4 The Relational Data Model & The Entity Relationship Data Model
Week 4 The Relational Data Model & The Entity Relationship Data Model
 
Rdbms
RdbmsRdbms
Rdbms
 
Dbms
DbmsDbms
Dbms
 
Managing experiment data using Excel and Friends
Managing experiment data using Excel and FriendsManaging experiment data using Excel and Friends
Managing experiment data using Excel and Friends
 
Database management system
Database management systemDatabase management system
Database management system
 
Database management system
Database management systemDatabase management system
Database management system
 
12 SQL
12 SQL12 SQL
12 SQL
 
Introduction To Sas
Introduction To SasIntroduction To Sas
Introduction To Sas
 
NORMALIZATION - BIS 1204: Data and Information Management I
NORMALIZATION - BIS 1204: Data and Information Management I NORMALIZATION - BIS 1204: Data and Information Management I
NORMALIZATION - BIS 1204: Data and Information Management I
 
Database language
Database languageDatabase language
Database language
 
RDBMS
RDBMSRDBMS
RDBMS
 
Ch1- Introduction to dbms
Ch1- Introduction to dbmsCh1- Introduction to dbms
Ch1- Introduction to dbms
 
Normalization
NormalizationNormalization
Normalization
 
Sas Macro Examples
Sas Macro ExamplesSas Macro Examples
Sas Macro Examples
 
Transaction
TransactionTransaction
Transaction
 

Viewers also liked

Tutorial aplikasi toko online berbasis web dengan PHP
Tutorial aplikasi toko online berbasis web dengan PHPTutorial aplikasi toko online berbasis web dengan PHP
Tutorial aplikasi toko online berbasis web dengan PHPDeka M Wildan
 
Tutorial php membuat Aplikasi Inventaris
Tutorial php membuat Aplikasi InventarisTutorial php membuat Aplikasi Inventaris
Tutorial php membuat Aplikasi InventarisDeka M Wildan
 
Introduction to Information Technology (IT)
Introduction to Information Technology (IT)Introduction to Information Technology (IT)
Introduction to Information Technology (IT)Amber Bhaumik
 
introduction to web technology
introduction to web technologyintroduction to web technology
introduction to web technologyvikram singh
 
Basic IT knowledge
Basic IT knowledgeBasic IT knowledge
Basic IT knowledgeTechsailor
 
Information Technology
Information TechnologyInformation Technology
Information TechnologyViraj Kansara
 
Information technology ppt
Information technology ppt Information technology ppt
Information technology ppt Babasab Patil
 
Introduction to information technology lecture 1
Introduction to information technology   lecture 1Introduction to information technology   lecture 1
Introduction to information technology lecture 1CBAKhan
 
Tutorial Pembuatan Aplikasi Website Beserta Databasenya
Tutorial Pembuatan Aplikasi Website Beserta DatabasenyaTutorial Pembuatan Aplikasi Website Beserta Databasenya
Tutorial Pembuatan Aplikasi Website Beserta DatabasenyaRCH_98
 

Viewers also liked (12)

Tutorial aplikasi toko online berbasis web dengan PHP
Tutorial aplikasi toko online berbasis web dengan PHPTutorial aplikasi toko online berbasis web dengan PHP
Tutorial aplikasi toko online berbasis web dengan PHP
 
Tutorial php membuat Aplikasi Inventaris
Tutorial php membuat Aplikasi InventarisTutorial php membuat Aplikasi Inventaris
Tutorial php membuat Aplikasi Inventaris
 
Buku Ajar Pemrograman Web
Buku Ajar Pemrograman WebBuku Ajar Pemrograman Web
Buku Ajar Pemrograman Web
 
Introduction to Information Technology (IT)
Introduction to Information Technology (IT)Introduction to Information Technology (IT)
Introduction to Information Technology (IT)
 
introduction to web technology
introduction to web technologyintroduction to web technology
introduction to web technology
 
Basic IT knowledge
Basic IT knowledgeBasic IT knowledge
Basic IT knowledge
 
Information Technology
Information TechnologyInformation Technology
Information Technology
 
Basic Concepts Of Information Technology (It)
Basic Concepts Of Information Technology (It)Basic Concepts Of Information Technology (It)
Basic Concepts Of Information Technology (It)
 
IT ppt
IT pptIT ppt
IT ppt
 
Information technology ppt
Information technology ppt Information technology ppt
Information technology ppt
 
Introduction to information technology lecture 1
Introduction to information technology   lecture 1Introduction to information technology   lecture 1
Introduction to information technology lecture 1
 
Tutorial Pembuatan Aplikasi Website Beserta Databasenya
Tutorial Pembuatan Aplikasi Website Beserta DatabasenyaTutorial Pembuatan Aplikasi Website Beserta Databasenya
Tutorial Pembuatan Aplikasi Website Beserta Databasenya
 

Similar to Database Application with MySQL

PROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTPROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTTushar Dhoot
 
Report on Dental treatment & management system
Report on Dental treatment &  management system Report on Dental treatment &  management system
Report on Dental treatment & management system Zakirul Islam
 
Sql interview question part 9
Sql interview question part 9Sql interview question part 9
Sql interview question part 9kaashiv1
 
Sql interview-question-part-9
Sql interview-question-part-9Sql interview-question-part-9
Sql interview-question-part-9kaashiv1
 
Data processing in Industrial Systems course notes after week 5
Data processing in Industrial Systems course notes after week 5Data processing in Industrial Systems course notes after week 5
Data processing in Industrial Systems course notes after week 5Ufuk Cebeci
 
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docxrhetttrevannion
 
L1-Introduction to Cloud Computing.ppt
L1-Introduction to Cloud Computing.pptL1-Introduction to Cloud Computing.ppt
L1-Introduction to Cloud Computing.pptGarvitChadha
 
Fbdl enabling comprehensive_data_services
Fbdl enabling comprehensive_data_servicesFbdl enabling comprehensive_data_services
Fbdl enabling comprehensive_data_servicesCindy Irby
 
Sql interview question part 5
Sql interview question part 5Sql interview question part 5
Sql interview question part 5kaashiv1
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational Databasessharing notes123
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesSharing Slides Training
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesSharing Slides Training
 

Similar to Database Application with MySQL (20)

Dbms_class _14
Dbms_class _14Dbms_class _14
Dbms_class _14
 
Pp 09-new
Pp 09-newPp 09-new
Pp 09-new
 
Pp 09-new
Pp 09-newPp 09-new
Pp 09-new
 
Cse ii ii sem
Cse ii ii semCse ii ii sem
Cse ii ii sem
 
PROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTPROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOT
 
Issue in Data warehousing and OLAP in E-business
Issue in Data warehousing and OLAP in E-businessIssue in Data warehousing and OLAP in E-business
Issue in Data warehousing and OLAP in E-business
 
Report on Dental treatment & management system
Report on Dental treatment &  management system Report on Dental treatment &  management system
Report on Dental treatment & management system
 
Ebook9
Ebook9Ebook9
Ebook9
 
Sql interview question part 9
Sql interview question part 9Sql interview question part 9
Sql interview question part 9
 
Sql interview-question-part-9
Sql interview-question-part-9Sql interview-question-part-9
Sql interview-question-part-9
 
Ebook9
Ebook9Ebook9
Ebook9
 
Data processing in Industrial Systems course notes after week 5
Data processing in Industrial Systems course notes after week 5Data processing in Industrial Systems course notes after week 5
Data processing in Industrial Systems course notes after week 5
 
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx
2DATA WAREHOUSING SYSTEMAchyut Sai Chillara50215.docx
 
L1-Introduction to Cloud Computing.ppt
L1-Introduction to Cloud Computing.pptL1-Introduction to Cloud Computing.ppt
L1-Introduction to Cloud Computing.ppt
 
Fbdl enabling comprehensive_data_services
Fbdl enabling comprehensive_data_servicesFbdl enabling comprehensive_data_services
Fbdl enabling comprehensive_data_services
 
Ebook5
Ebook5Ebook5
Ebook5
 
Sql interview question part 5
Sql interview question part 5Sql interview question part 5
Sql interview question part 5
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational Databases
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational Databases
 
Ais Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational DatabasesAis Romney 2006 Slides 04 Relational Databases
Ais Romney 2006 Slides 04 Relational Databases
 

More from Karwan Mustafa Kareem

More from Karwan Mustafa Kareem (8)

Computer and network security
Computer and network securityComputer and network security
Computer and network security
 
Java programming: Elementary practice
Java programming: Elementary practiceJava programming: Elementary practice
Java programming: Elementary practice
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
Java programming: Elementary programming
Java programming: Elementary programmingJava programming: Elementary programming
Java programming: Elementary programming
 
Introduction to Java Programming Language
Introduction to Java Programming Language Introduction to Java Programming Language
Introduction to Java Programming Language
 
Cryptography
Cryptography Cryptography
Cryptography
 
MySQL Database with phpMyAdmin
MySQL Database with  phpMyAdminMySQL Database with  phpMyAdmin
MySQL Database with phpMyAdmin
 

Recently uploaded

SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisNeo4j
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandIES VE
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsGlobus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILNatan Silnitsky
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAlluxio, Inc.
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
 

Recently uploaded (20)

SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 

Database Application with MySQL

  • 1. 1 DDaattaabbaassee aapppplliiccaattiioonn CChhaapptteerr 11:: IInnttrroodduuccttiioonn ttoo MMyySSQQLL DDaattaabbaassee FFaaccuullttyy ooff PPhhyyssiiccaall aanndd BBaassiicc EEdduuccaattiioonn CCoommppuutteerr SScciieennccee BByy:: MMsscc.. KK aarrwwaann MM.. KKaarreeeemm 22001155 -- 22001144 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 2. 2 RRooaadd MMaapp  Introducing Relational Databases  Terminology  MySQL Database  MySQL Command Line Client  Managing Databases  Manipulating data  Summary  Examples University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 3. IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee  Database is involved like everywhere in our world • If we go to bank to deposit or withdraw. • Make hotel and airline reservation. • Purchase something on line. • Buy groceries in supermarkets.  More recent online applications • Youtube • iTunes • Geographic Information Systems (GIS) • Data Warehouses • Many other applications  IRS: assume it has 100 million taxpayers and each taxpayer file 5 forms with 400 characters of information per form=800 Gbyte.  Amazon.com: 15 million people visit per day; about 1000 people are responsible for database update. 3 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 4. IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee  DBMS contains information about a particular enterprise o Collection of interrelated data o Set of programs to access the data o An environment that is both convenient and efficient to use  Database Applications: o Banking: all transactions o Airlines: reservations, schedules o Universities: registration, grades o Sales: customers, products, purchases o Online retailers: order tracking, customized recommendations o Manufacturing: production, inventory, orders, supply chain o Human resources: employee records, salaries, tax deductions  Databases touch all aspects of our lives 4 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 5. IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee  A relational database manages data in tables.  Databases are managed by a relational database management system (RDBMS).  An RDBMS supports a database language to create and delete databases and to manage and search data.  The database language used in almost all DBMSs is SQL.  After creating a database, the most common SQL statements used are  INSERT to add data  UPDATE to change data  DELETE to remove data  SELECT to search data  A database table may have multiple columns, or attributes, each of which has a name. 5 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 6. 6 IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee  Tables usually have a primary key, which is one or more values that uniquely identify each row in a table (Figure 3.1.)  Typical DBMS Functionality are  Define a particular database in terms of its data types, structures, and constraints  Construct or Load the initial database contents on a secondary storage medium  Manipulate the database: o Retrieval: Querying, generating reports o Modification: Insertions, deletions and updates to its content o Accessing the database through Web applications  Share a database allows multiple users and programs to access the database simultaneously University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 7. 7 IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee Figure 3-1. An example of relational database containing two related tables University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 8. 8 IInnttrroodduucciinngg RReellaattiioonnaall DDaattaabbaassee  A database is modeled using entity-relationship (ER) modeling. (Figure 3.2.) Figure 3-2. An example of relational model of the winery database University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 9. 9 TTeerrmmiinnoollooggyy  Database  A repository to store data.  Data  Known facts that can be recorded and have an implicit meaning.  Table The part of a database that stores the data. A table has columns or attributes, and the data stored in rows.  Attributes  The columns in a table. All rows in table entities have the same attributes. For example, a customer table might have the attributes name, address, and city. Each attribute has a data type such as string, integer, or date. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 10. 10 TTeerrmmiinnoollooggyy  Rows  The data entries in a table. Rows contain values for each attribute. For example, a row in a customer table might contain the values "Matthew Richardson," "Punt Road," and "Richmond." Rows are also known as records.  Relational model  A model that uses tables to store data and manage the relationship between tables.  Relational database management system  A software system that manages data in a database and is based on the relational model.  Entity-relationship modeling  A technique used to describe the real-world data in terms of entities, attributes, and relationships. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 11. 11 TTeerrmmiinnoollooggyy  Constraints  Restrictions or limitations on tables and attributes. For example, a wine can be produced only by one winery, an order for wine can't exist if it isn't associated with a customer, having a name attribute could be mandatory for a customer.  Primary key  One or more attributes that contain values that uniquely identify each row. For example, a customer table might have the primary key of cust ID. The cust ID attribute is then assigned a unique value for each customer. A primary key is a constraint of most tables.  Index  A data structure used for fast access to rows in a table. An index is usually built for the primary key of each table and can then be used to quickly find a particular row. Indexes are also defined and built for other attributes when those attributes are frequently used in queries. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 12. 12 TTeerrmmiinnoollooggyy  Normalized database  A correctly designed database that is created from an ER model. There are different types or levels of normalization, and a third-normal form database is generally regarded as being an acceptably designed relational database.  Foreign key  A foreign key is the linking pin between two tables.  SQL  A query language that interacts with a DBMS. SQL is a set of statements to manage databases, tables, and data. Database system: Database Management System + Database University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 13. 13 MMyySSQQLL DDaattaabbaassee  MySQL Database MySQL is an open source relational database management system (RDBMS) based on Structured Query Language (SQL).  MySQL is originally developed, distributed, and supported by the Swedish company ( MySQL AB) , was acquired by Oracle in 2008. Developers can still use MySQL under the GNU General Public License (GPL).  Applications which use MySQL databases include: TYPO3, MODx, Joomla, WordPress, phpBB, MyBB, Drupal.  MySQL is also used in many high-profile, large-scale websites, including Google, Facebook, Twitter, Flickr, and YouTube. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 14. 14 MMyySSQQLL DDaattaabbaassee  Why are we using MySQL?  MySQL is released under an open-source license. So you have nothing to pay to use it.  MySQL is a very powerful program in its own right. It handles a large subset of the functionality of the most expensive and powerful database packages.  MySQL uses a standard form of the well-known SQL data language.  MySQL works on many operating systems ( Windows, UNIX and Linux) and with many languages including PHP, PERL, C, C++, JAVA etc.  MySQL works very quickly and works well even with large data sets.  MySQL is customizable. The open source GPL license allows programmers to modify the MySQL software to fit their own specific environments. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 15. 15 MMyySSQQLL DDaattaabbaassee  Why are we using MySQL?  MySQL is very friendly to PHP and JSP which are most appreciated languages for web development.  MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this to a theoretical limit of 8 million terabytes (TB). University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 16. 16 MMyySSQQLL DDaattaabbaassee  Why are we using MySQL?  The following diagrams show the enterprise database market share covered by Gartner and Cloud Database market. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 17. 17 MMyySSQQLL DDaattaabbaassee Interfaces ( Relative MySQL Tools) Free graphical administration applications (or "front ends") are available that integrate with MySQL and enable users to work with database structure and data visually. LAMP  It’s a Web development platform that uses Linux as the operating system, Apache as the Web server, MySQL as the relational database management system and PHP as the object-oriented scripting language. (Sometimes Perl or Python is used instead of PHP.) MySQL Command Line Client  MySQL Command Line Client is a single exe that allows connecting and running a sample query. it is a simple SQL shell for creating tables, inserting data, ..etc (with GNU readline capabilities). University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 18. 18 MMyySSQQLL DDaattaabbaassee  phpMyAdmin  It's a PHP-driven tool and handles every aspect of creating and managing a MySQL database application. phpMyAdmin also allows for the execution of MySQL commands from within the interface. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 19. 19 MMyySSQQLL DDaattaabbaassee  MySQL Workbench  It is a unified visual tool for database architects, developers. MySQL Workbench provides data modeling, SQL development, and administration tools for server configuration, user administration, backup etc.. MySQL Workbench is available on Windows, Linux and Mac OS X. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 20. 20 MMyySSQQLL DDaattaabbaassee  HeidiSQL  HeidiSQL – a full featured free front end that runs on Windows, and can connect to local or remote MySQL servers to manage databases, tables, column structure, and individual data records. Also supports specialized GUI features for date/time fields and enumerated multiple-value fields University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 21. 21 MMyySSQQLL DDaattaabbaassee  PHPMaker  PHPMaker is a powerful automation tool that can generate a full set of PHP quickly from MySQL, PostgreSQL, Microsoft Access, Microsoft SQL Server and Oracle databases.  Using PHPMaker, you can instantly create web sites that allow users to view, edit, search, add and delete records on the web.  PHPMaker is designed for high flexibility, numerous options enable you to generate PHP database applications that best suits your needs.  The generated codes are clean, straightforward and easy-to-customize. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 22. 22 MMyySSQQLL DDaattaabbaassee  PHP Report Maker  PHP Report Maker is a powerful reporting tool that can generate dynamic PHP Web reports from MySQL, PostgreSQL, Microsoft Access, Microsoft SQL Server and Oracle database.  You can instantly create live detail and summary reports or crosstabs reports for your Database Application.  PHP Report Maker is designed for high flexibility, numerous options enable you to generate the reports that best suits your needs.  PHP Report Maker can save you tons of time and is suitable for both beginners and experienced developers alike. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 23. 23 MMyySSQQLL DDaattaabbaassee  Apache web server  Apache is a web server package that works under Linux as well as under other operating systems (window, Unix, Etc...)  Apache 1.0 was released on 12/1/1995.  Apache web server developed by the Apache group.  The primary advantage of Apache is that it is generally free or available at modest costs. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 24. 24 MMyySSQQLL DDaattaabbaassee  MySQL data type MySQL uses many different data types, broken into three categories: numeric, date and time, and string types.  Numeric Data Types The MySQL numeric data types are:  INT - A normal-sized integer that the allowable range is from -2147483648 to 2147483647. You can specify a width of up to 11 digits.  TINYINT - A very small integer, the allowable range is from -128 to 127. You can specify a width of up to 4 digits.  SMALLINT - A small integer, the allowable range is from -32768 to 32767. You can specify a width of up to 5 digits.  MEDIUMINT - A medium-sized integer, the allowable range is from -8388608 to 8388607. You can specify a width of up to 9 digits. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 25. 25 MMyySSQQLL DDaattaabbaassee  Numeric Data Types  BIGINT - A large integer, the allowable range is from -9223372036854775808 to 9223372036854775807. You can specify a width of up to 11 digits.  FLOAT(M,D) - A floating-point number. You can define the display length (M) and the number of decimals (D). Decimal precision can go to 24 places for a FLOAT.  DOUBLE(M,D) - A double precision floating-point number. You can define the display length (M) and the number of decimals (D). Decimal precision can go to 53 places for a DOUBLE.  DECIMAL(M,D) - An unpacked floating-point number. In unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. ..Note: MySQL uses all the standard ANSI SQL numeric data types University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 26. 26 MMyySSQQLL DDaattaabbaassee  Date and Time Types The MySQL date and time data types are:  DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.  DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.  TIMESTAMP- This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ). University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 27. 27 MMyySSQQLL DDaattaabbaassee  Date and Time Types  TIME - Stores the time in HH:MM:SS format.  YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can be 1901 to 2155. The default length is 4. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 28. 28 MMyySSQQLL DDaattaabbaassee  String Types The MySQL String types are:  CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example CHAR(5)). Defining a length is not required, but the default is 1.  VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example VARCHAR(25). You must define a length when creating a VARCHAR field.  BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary Large Objects" and are used to store large amounts of binary data, such as images or other types of files. Defining a length is not required.  TINYBLOB or TINYTEXT - A BLOB or TEXT column with a maximum length of 255 characters. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 29. 29 MMyySSQQLL DDaattaabbaassee  String Types  MEDIUMBLOB or MEDIUMTEXT - A BLOB or TEXT column with a maximum length of 16777215 characters.  LONGBLOB or LONGTEXT - A BLOB or TEXT column with a maximum length of 4294967295 characters.  ENUM - An enumeration, which is a fancy term for list. When defining an ENUM, you are creating a list of items from which the value must be selected (or it can be NULL). For example, if you wanted your field to contain "A" or "B" or "C", you would define your ENUM as ENUM ('A', 'B', 'C'). University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 30. 30 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  Connecting to MySQL  MySQL provides an interactive shell for creating tables, inserting data, etc…  On Windows, just go to C:AppServMySQLbinMySQL.exe  Or, go to start menu all rograms  Appserve click on the Windows icon ..Connecting to MySQL Command Line Client University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 31. 31 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  Sample Session Enter password: ***** Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 241 to server version: 5.0.51b-community-nt-log MySQL Community Edition < GPL> Type 'help;' or 'h' for help. Type 'c' to clear the buffer. mysql> …MySQL Command Line Client  To exit the MySQL Command , just type QUIT or EXIT: mysql> QUIT mysql> exit Note: MySQL Command Line Client is a single exe that allows connecting and running a sample query. it is a simple SQL shell (with GNU readline capabilities). University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 32. 32 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  Basic Queries  Once logged in, you can try some simple queries.  For example: ;mysql> SELECT VERSION(), CURRENT_DATE +---------------------------+-----------+ | VERSION() | CURRENT_DATE |+ ---------------------------+-----------+ | 2002-05-26 | 3.23.49 | +---------------------------+-----------+ (row in set (0.00 sec 1  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. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 33. 33 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  Basic Queries  Keywords may be entered in any letter case.  The following queries are equivalent: mysql> SELECT VERSION(), CURRENT_DATE; mysql> select version(), current_date; mysql> SeLeCt vErSiOn(), current_DATE;  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| +-------------+-------------+ | 0.707107 | 25 | +-------------+-------------+ 1 row in set (0.00 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 34. 34 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  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() | +------------------+ | 3.22.20a-log | +------------------+ +---------------------+ | NOW() | +---------------------+ | 2004 00:15:33 | +---------------------+ 1 row in set (0.00 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 35. 35 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  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 | +--------------------+------------------------+ | Karwan@localhost | 1999-03-18 | +--------------------+------------------------+ 1 row in set (0.00 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 36. 36 MMyySSQQLL CCoommmmaanndd LLiinnee CClliieenntt  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>  Using and selecting Database  To the select a database, issue the “use” command: mysql> use test;  Show status  Reports details of the MySQL DBMS performance and statistics. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 37. 37 MMaannaaggiinngg DDaattaabbaasseess  The Data Definition Language (DDL) is the set of SQL statements used to manage a database.  Creating Databases  The CREATE DATABASE statement can create a new, empty database without any tables or data. mysql> CREATE DATABASE webdb; mysql> use webdb; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 38. 38 MMaannaaggiinngg DDaattaabbaasseess  Creating Tables  After issuing the use Database command, you then usually issue commands to create the tables in the database.  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  To create a table, use the CREATE TABLE command: …Note: VARCHAR is usually used to store string data University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 39. 39 MMaannaaggiinngg DDaattaabbaasseess 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)  To verify that the table has been created: mysql> show tables; +------------------------- + | Tables_in_webdb | +------------------------- + | pet | +------------------------- + 1 row in set (0.01 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 40. 40 MMaannaaggiinngg DDaattaabbaasseess  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) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 41. 41 MMaannaaggiinngg DDaattaabbaasseess  Show Indexes  Presents the details of all indexes on the table, including the PRIMARY KEY. SHOW INDEX FROM tablename;  Altering Tables and Indexes  Indexes can be added or removed from a table after creation.  To add an index to the customer table, you can issue the following statement: ALTER TABLE customer ADD INDEX cities (city);  To remove an index from the customer table, use the following statement: ALTER TABLE customer DROP INDEX names; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 42. 42 MMaannaaggiinngg DDaattaabbaasseess  Displaying Database Structure with SHOW  Details of databases, tables, and indexes can be displayed with the SHOW command.  The SHOW command isn't part of the SQL standard and is MySQL-specific.  Show Data bases » Lists the databases that are accessible by the MySQL DBMS. » 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: University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 43. 43 MMaannaaggiinngg DDaattaabbaasseess mysql> show databases; +----------- --+ | Database | +----------- --+ | mysql | | webdb | +------------ -+ 2 rows in set (0.01 sec)  Show tables » Shows the tables in the database once a database has been selected with the use command. mysql> show tables; Empty set (0.02 sec) » An empty set indicates that I had dropped all tables. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 44. 44 MMaannaaggiinngg DDaattaabbaasseess  Describing Tables » Shows the attributes, types of attributes, key information, whether NULL is permitted, defaults, and other information for a table. » 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) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 45. 45 MMaannaaggiinngg DDaattaabbaasseess » Or use “SHOW COLUMNS FROM tablename“ command to view a table structure. mysql> show columns from 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) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 46. 46 MMaanniippuullaattiinngg DDaattaa  The Data Manipulation Language (DML) encompasses all SQL statements used for manipulating data. There are four statements that form the DML statement set: » INSERT » DELETE » UPDATE » SELECT University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 47. 47 MMaanniippuullaattiinngg DDaattaa  Inserting Data  Having created a database and the accompanying tables and indexes, the next step is to insert data.  Inserting a row of data into a table can follow two different approaches. » First approach: Use the INSERT statement to enter data into a table. For example: INSERT INTO pet VALUES ('Fluffy','Harold','cat','f', '1999-02-04',NULL); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 48. 48 MMaanniippuullaattiinngg DDaattaa »Second approach: INSERT INTO pet SET Name = 'Fluffy', Owner = 'Harold', Species = 'cat', Sex = 'f', Birth = '1999-02-04', Date = NULL ; …Loading Data to pet table The first approach can actually be varied to function in a similar way to the second by including parenthesized attribute names before the VALUES keyword. INSERT INTO pet (Name, Owner ) VALUES ('Fluffy', 'Harold'); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 49. 49 MMaanniippuullaattiinngg DDaattaa  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. ..pet.txt: Sample Data File University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 50. 50 MMaanniippuullaattiinngg DDaattaa  Loading Sample Data » To Load pet.txt: mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; » For each of the examples, assume the following set of data. ..loading pet.txt into table pet University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 51. 51 MMaanniippuullaattiinngg DDaattaa  Deleting Data  There is an important distinction between dropping and deleting in SQL. » DROP is used to remove tables or databases. » DELETE is used to remove data. DELETE FROM pet; DELETE FROM pet WHERE name= ‘claws’; Deleting ‘Claws’ from table ..pet University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 52. 52 MMaanniippuullaattiinngg DDaattaa  Updating Data  Data can be updated using a similar syntax to that of the INSERT statement. UPDATE pet SET owner=‘ali’; UPDATE pet SET owner= ‘ali' WHERE name = ‘fang’; …Updating table pet University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 53. 53 MMaanniippuullaattiinngg DDaattaa  Querying with SQL SELECT  The SELECT statement is used to query a database and for all output operations in SQL. » The simplest form of SELECT retrieves everything from a table mysql> select * from pet; 8 rows in set (0.00 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 54. 54 MMaanniippuullaattiinngg DDaattaa  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"; 1 row in set (0.00 sec) University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 55. 55 MMaanniippuullaattiinngg DDaattaa  Selecting Particular Rows » To find all animals born after 1998 SELECT * FROM pet WHERE birth >= "1998-1-1"; » 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"; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 56. 56 MMaanniippuullaattiinngg DDaattaa  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. mysql> select name, birth from pet; (rows in set (0.01 sec 8 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 57. 57 MMaanniippuullaattiinngg DDaattaa  Sorting and Grouping Output  Sorting data (ORDER BY) » The ORDER BY clause sorts the data after the query has been evaluated. 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; (rows in set (0.01 sec 8 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 58. 58 MMaanniippuullaattiinngg DDaattaa  Sorting and Grouping Output  Sorting data (DESC) » To sort in reverse order, add the DESC (descending keyword) mysql> SELECT name, birth FROM pet ORDER BY birth DESC; (rows in set (0.01 sec 8 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 59. 59 MMaanniippuullaattiinngg DDaattaa  Working with NULLs » To sort in reverse order, add the DESC (descending keyword) » 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. » For example, to find all your dead pets (what a morbid example!) mysql> select name from pet where death >IS NOT NULL; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 60. 60 MMaanniippuullaattiinngg DDaattaa  Pattern Matching  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. Note: MySQL provides standard SQL pattern matching. regular expression pattern matching, similar to those used by Unix utilities such as vi, grep and sed. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 61. 61 MMaanniippuullaattiinngg DDaattaa  Pattern Matching Example  To find names beginning with ‘b’: mysql> SELECT * FROM pet WHERE name LIKE "b%";  To find names ending with `fy': mysql> SELECT * FROM pet WHERE name LIKE "%fy"; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 62. 62 MMaanniippuullaattiinngg DDaattaa  Pattern Matching Example  To find names containing a ‘w’: mysql> SELECT * FROM pet WHERE name LIKE "%w%";  To find names containing exactly five characters, use the _ pattern character: mysql> SELECT * FROM pet WHERE name LIKE "_____"; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 63. 63 MMaanniippuullaattiinngg DDaattaa  GROUP BY » The GROUP BY clause is different from ORDER BY because it doesn't sort the data for output. Instead, it sorts the data early in the query process, for the purpose of grouping or aggregation. SELECT city, COUNT(*) FROM customer GROUP BY city; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 64. 64 MMaanniippuullaattiinngg DDaattaa  There are several functions that can be used in aggregation with the GROUP BY clause. Five particularly useful functions are: » AVG( ): Finds the average value of a numeric attribute in a set. » MIN( ): Finds a minimum value of a string or numeric attribute in a set. » MAX( ): Finds a maximum value of a string or numeric attribute in a set. » SUM( ): Finds the sum total of a numeric attribute. » COUNT( ): Counts the number of rows in a set. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 65. 65 MMaanniippuullaattiinngg DDaattaa  Counting Rows Example » 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. » A query to determine total number of pets: mysql> SELECT COUNT(*) FROM pet; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 66. 66 MMaanniippuullaattiinngg DDaattaa  HAVING » The HAVING clause permits conditional aggregation of data into groups. SELECT city, count(*), max(salary) FROM customer GROUP BY city HAVING count(*) > 10;  DISTINCT » The DISTINCT operator presents only one example of each row from a query. SELECT DISTINCT surname FROM customer; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 67. 67 MMaanniippuullaattiinngg DDaattaa  Join Queries / Cartesian Product » A join query is a querying technique that matches rows from two or more tables based on a join condition in a WHERE clause and outputs only those rows that meet the condition. SELECT winery_name, region_name FROM winery, region ORDER BY winery_name, region_name; » The query produces all possible combinations of the four region names and 300 wineries in the sample database! In fact, the size of the output can be accurately calculated as the total number of rows in the first table multiplied by the total rows in the second table. In this case, the output is 4 x 300 = 1,200 rows. University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 68. 68 MMaanniippuullaattiinngg DDaattaa  Elementary Natural Joins » A cartesian product isn't the join we want. Instead, we want to limit the results to only the sensible rows. SELECT winery_name, region_name FROM winery, region WHERE winery.region_id = region.region_id ORDER BY winery_name; University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 69. 69 SSuummmmaarryy  Is that all there is to MySQL? » Of course not! » Understanding databases and MySQL could take us several months(perhaps years!) » For now, focus on: » using the MySQL shell with phpMyadmin » creating database » creating general and standard SQL queries University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 70. 70 SSuummmmaarryy  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 with phpMyadmin . University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 71. 71 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE wine ( wine_id int(5) DEFAULT '0' NOT NULL auto_increment, wine_name varchar(50) DEFAULT '' NOT NULL, winery_id int(4), type varchar(10) DEFAULT '' NOT NULL, year int(4) DEFAULT '0' NOT NULL, description blob, PRIMARY KEY (wine_id), KEY name (wine_name) KEY winery (winery_id) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 72. 72 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE winery ( winery_id int(4) DEFAULT '0' NOT NULL auto_increment, winery_name varchar(100) DEFAULT '' NOT NULL, region_id int(4), description blob, phone varchar(15), fax varchar(15), PRIMARY KEY (winery_id), KEY name (winery_name) KEY region (region_id) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 73. 73 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE region ( region_id int(4) DEFAULT '0' NOT NULL auto_increment, region_name varchar(100) DEFAULT '' NOT NULL, description blob, map mediumblob, PRIMARY KEY (region_id), KEY region (region_name) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 74. 74 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE customer ( cust_id int(5) NOT NULL auto_increment, surname varchar(50) NOT NULL, firstname varchar(50) NOT NULL, initial char(1), title varchar(10), addressline1 varchar(50) NOT NULL, addressline2 varchar(50), addressline3 varchar(50), city varchar(20) NOT NULL, state varchar(20), zipcode varchar(5), country varchar(20), phone varchar(15), fax varchar(15), email varchar(30) NOT NULL, birth_date date( ), salary int(7), PRIMARY KEY (cust_id), KEY names (surname,firstname) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 75. 75 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE users ( cust_id int(4) DEFAULT '0' NOT NULL, user_name varchar(50) DEFAULT '' NOT NULL, password varchar(15) DEFAULT '' NOT NULL, PRIMARY KEY (user_name), KEY password (password) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 76. 76 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE grape_variety ( variety_id int(3), variety_name varchar(20), PRIMARY KEY (variety_id), KEY var (variety) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 77. 77 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE inventory ( wine_id int(5) DEFAULT '0' NOT NULL, inventory_id int(3) NOT NULL, on_hand int(5) NOT NULL, cost float(5,2) NOT NULL, case_cost float(5,2) NOT NULL, dateadded timestamp(12) DEFAULT NULL, PRIMARY KEY (wine_id,inventory_id) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 78. 78 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE orders ( cust_id int(5) DEFAULT '0' NOT NULL, order_id int(5) DEFAULT '0' NOT NULL, date timestamp(12), discount float(3,1) DEFAULT '0.0', delivery float(4,2) DEFAULT '0.00', note varchar(120), PRIMARY KEY (cust_id,order_no) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 79. 79 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE items ( cust_id int(5) DEFAULT '0' NOT NULL, order_id int(5) DEFAULT '0' NOT NULL, item_id int(3) DEFAULT '1' NOT NULL, wine_id int(4) DEFAULT '0' NOT NULL qty int(3), price float(5,2), date timestamp(12), PRIMARY KEY (cust_id,order_no,item_id) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 80. 80 EExxaammppllee  Example. The complete winestore DDL statements CREATE TABLE wine_variety ( wine_id int(5) DEFAULT '0' NOT NULL, variety_id int(3) DEFAULT '0' NOT NULL, id int(1) DEFAULT '0' NOT NULL, PRIMARY KEY (wine_id, variety_id) ); University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©
  • 81. 81 EENNDD EENNDD…… AAnnyy qquueessttiioonnss....?? HHooppee yyoouu hhaavvee bbeeeenn hhaappppyy TThhaannkk yyoouu BByy:: MMsscc.. KKaarrwwaann MM.. KKaarreeeemm 22001155 -- 22001144 University of Sulaimani, Faculty of Physical & Basic Education, Department of Computer Science 2014 / 2015©