Вы находитесь на странице: 1из 725

MusIer Ihe

leuding epen seurte

reluIienul duIubuse
munugemenI sysIem
1une perfermunte
und seturiIy en
duIubuse servers
ßuild My$0l
duIubuse upplituIiens
using Perl, PkP, ¡uvu,
und 00ßC
Steve See|t|aç
"The M+SQT B1hIe introduces the essential concepts and
skills you'll need to get started with MySQL."
- Jevem+ ZuuvJu+, Seu1vv EJ1tvv vJ Linux Magazine
uuJ tne M+SQT Jutuhuse expevt ut Yunvv! T1uuuce
Pet|, scmp|e te6e
Item t|e |eek, ca6 mete
0 k £ k ü k 0 k £ 0 P £ k C £ k 1
A UT h0 k I TAT I V E
0 k £ k ü k 0 k £ 0 P £ k C £ k 1
¹ ¹
Steve Suehring
PubÌished by:
Wiley Publishing, lnc.
9O9 Third Avenue
New York, NY 1OO22
Coµyright © 2OO2 WiÌey PubÌishing, Inc. AÌÌ rights reserved. No µnrt of this book, incÌuding interior design, cover design,
nnd icons, mny be reµroduced or trnnsmitted in nny form, by nny menns (eÌectronic, µhotocoµying, recording, or
otherwise) without the µrior written µermission of the µubÌisher.
Librnry of Congress ControÌ Number: 2OO21O829O
IS8N: O-764b-4982-4
Printed in the United Stntes of Americn
1O 9 8 7 6 b 4 8 2 1
Distributed in the United Stntes by WiÌey PubÌishing, Inc.
Distributed by CDG 8ooks Cnnndn Inc. for Cnnndn, by TrnnsworÌd PubÌishers Limited in the United Kingdom, by IDG Norge
8ooks for Norwny, by IDG Sweden 8ooks for Sweden, by IDG 8ooks AustrnÌin PubÌishing Corµorntion Pty. Ltd. for AustrnÌin
nnd New ZenÌnnd, by TrnnsQuest PubÌishers Pte Ltd. for Singnµore, MnÌnysin, ThniÌnnd, Indonesin, nnd Hong Kong, by
Gotoµ Informntion Inc. for Tniwnn, by ICG Muse, Inc. for 1nµnn, by Intersoft for South Africn, by LyroÌÌes for Irnnce, by
InternntionnÌ Thomson PubÌishing for Germnny, Austrin, nnd SwitzerÌnnd, by Distribuidorn Cusµide for Argentinn, by LR
InternntionnÌ for 8rnziÌ, by GnÌiÌeo Libros for ChiÌe, by Ldiciones ZLTA S.C.R. Ltdn. for Peru, by WS Comµuter PubÌishing
Corµorntion, Inc., for the PhiÌiµµines, by Contemµornnen de Ldiciones for VenezueÌn, by Lxµress Comµuter Distributors for
the Cnribbenn nnd West Indies, by Micronesin Medin Distributor, Inc. for Micronesin, by Chiµs Comµutndorns S.A. de C.V.
for Mexico, by LditorinÌ Normn de Pnnnmn S.A. for Pnnnmn, by Americnn 8ookshoµs for IinÌnnd.
Ior genernÌ informntion on WiÌey`s µroducts nnd services µÌense contnct our Customer Cnre deµnrtment, within the U.S. nt
8OO-762-2974, outside the U.S. nt 817-b72-8998 or fnx 817-b72-4OO2.
Ior snÌes inquiries nnd reseÌÌers informntion, incÌuding discounts, µremium nnd buÌk qunntity snÌes nnd foreign Ìnngunge
trnnsÌntions µÌense contnct our Customer Cnre deµnrtment nt 8OO-484-8422, fnx 817-b72-4OO2 or write to WiÌey PubÌishing,
Inc., Attn: Customer Cnre deµnrtment, 1O47b Crossµoint 8ouÌevnrd, IndinnnµoÌis, IN 462b6.
Ior informntion on Ìicensing foreign or domestic rights, µÌense contnct our Sub-Rights Customer Cnre deµnrtment nt
Ior informntion on using WiÌey`s µroducts nnd services in the cÌnssroom or for ordering exnminntion coµies, µÌense contnct
our LducntionnÌ SnÌes deµnrtment nt 8OO-484-2O86 or fnx 817-b72-4OOb.
Ior µress review coµies, nuthor interviews, or other µubÌicity informntion, µÌense contnct our PubÌic ReÌntions deµnrtment
nt 6bO-6b8-7OOO or fnx 6bO-6b8-7bOO.
Ior nuthorizntion to µhotocoµy items for corµornte, µersonnÌ, or educntionnÌ use, µÌense contnct Coµyright CÌenrnnce
Center, 222 Rosewood Drive, Dnnvers, MA O1928, or fnx 978-7bO-447O.
Trndemnrks: MySQL is n trndemnrk of MySQL A8. AÌÌ other trndemnrks nre the µroµerty of their resµective owners. WiÌey
PubÌishing, Inc., is not nssocinted with nny µroduct or vendor mentioned in this book.
About the Author
Steve Suehring is n Senior Systems Lngineer for n Ìnrge Internet µrovider ns weÌÌ ns
n consuÌtnnt for dntnbnse, security, nnd Internet µro|ects. Steve hns worked with
numerous cÌients to deveÌoµ nnd imµÌement dntnbnse nnd Internet µro|ects.
Through these µro|ects, Steve hns worked with MySQL, OrncÌe, nnd SQL server for
both ndministrntion nnd deveÌoµment. Steve currentÌy hoÌds certificntions from
Microsoft nnd Cisco. Steve hns nÌso written nrticÌes for Linux Moµozinc.
When not in front of n comµuter screen, Steve en|oys sµending time with his wife.
Steve nÌso µÌnys guitnr, drums, nnd µinno (though seÌdom simuÌtnneousÌy) nnd gets
into µickuµ gnmes of bnsketbnÌÌ nnd footbnÌÌ whenever µossibÌe.
Acquisitions Editor
Terri Vnrveris
Project Editor
Pnt O`8rien
Technical Editor
Scott Hofmnnn
Copy Editor
8nrry ChiÌds-HeÌton
Proof Editor
TLCH8OOKS Production Services
Editorial Manager
Mnry 8eth WnkefieÌd
Permissions Editor
Lnurn Moss
Media Development Specialist
Gregory Steµhens
Media Development Coordinator
Mnrisn Penrmnn
Project Coordinator
Nnncee Reeves
Graphics and Production Specialists
8eth 8rooks, Senn Decker,
1oyce Hnughey, 1nckie NichoÌns,
Henther Poµe, 8etty SchuÌte
Quality Control Technicians
Lnurn AÌbert, 1ohn Greenough,
Andy HoÌÌnndbeck, CnrÌ Pierce
Proofreading and lndexing
TLCH8OOKS Production Services
To Rcbccco
eÌcome to MySQL 8ibÌe. A comµÌete reference for the MySQL dntnbnse
server nnd environment. Whether you`re n dntnbnse ndministrntor Ìooking
to instnÌÌ MySQL, nn existing MySQL ndministrntor, n deveÌoµer Ìooking to use
MySQL ns n bnckend, or n combinntion of nÌÌ three, this book cnn he̵.
Why I Wrote Ihis ßook
I wrote this book to give you one µÌnce to go for hnnds-on exnmµÌes, reference, nnd
best-µrnctices. I`ve been working with MySQL in renÌ-worÌd situntions for yenrs. I
beÌieve MySQL to be n robust dntnbnse soÌution for |ust nbout every tyµe of nµµÌi-
cntion. Combine the stnbiÌity of MySQL with its Ìow of ownershiµ nnd you quickÌy
come to find it indisµensnbÌe.
This book Ìooks to µrovide everything you`ÌÌ need to know to get MySQL running
nnd exµnnd uµon thnt by exnmining deveÌoµment nnd best-µrnctices for MySQL
What You Need to Know
You don`t need to know nnything nbout MySQL. However, you shouÌd hnve nt Ìenst n
ÌittÌe fnmiÌinrity with the conceµts of dntnbnses. I`ve covered those conceµts within
the µnges of the book, but knowing n ÌittÌe nbout dntnbnses cnn`t hurt.
Of course, you need to know how to use n comµuter.
What You Need to Have
Since MySQL runs on mnny µÌntforms, you need nccess to n comµuter cnµnbÌe of
running Windows 9b, 98, NT, 2OOO, XP, or somewhere in between, Linux, or n Mnc
with OS X. Deµending on whnt you wnnt to do with MySQL, you mny need more
RAM or n better µrocessor. I hnve successfuÌÌy run MySQL in Linux with Ìess thnn 2O
megnbytes of RAM nnd no swnµ fiÌe.
MY5OL ßibIe
The book is written with version 4 of MySQL in mind. Mnny of the screenshots were
tnken using MySQL 8.28.X ns version 4 wns being stnbiÌized. However, ns I wrote it
version 4 wns being deveÌoµed. Like mnny µeoµÌe, I nssisted in testing MySQL 4 nnd
so I wns nbÌe to write this book to incÌude those fentures.
What the Icons Mean
There nre n certnin number of icons used throughout the book to highÌight vnrious
µoints. This section iÌÌustrntes whnt some of those menn.
The Note icon is used to illustrate a point that I thought should be highlighted
separately from the main text.
You'll see this icon throughout the book to denote software, scripts, or the like
from a particular section.
When you see a Warning icon, pay particular attention. These are typically things
that I've done wrong in the past. I highlight them so you don't do the same!
The Cross-Reference icon points you to another section of the book for more infor-
How Ihis ßook Is Organized
The book is divided into five mnin µnrts nnd n µnrt of nµµendixes.
Part I: Cetting 5tarted
The first section of the book Ìooks nt the µrerequisites for instnÌÌing MySQL, the
nctunÌ instnÌÌntion of MySQL, nnd the conceµts of dntnbnse design. InstnÌÌntion is
exnmined on Linux, Windows, nnd Mnc. Within the Linux chnµter, both binnry nnd
source instnÌÌntion of MySQL is exnmined.
Part II: 5OL EssentiaIs
Lxnminntion of SQL nnd some of the tooÌs used with MySQL is the highÌight of the
second section. The first chnµter within the section gives n fuÌÌ Ìook nt the MySQL
commnnd-Ìine interfnce µrogrnm. AÌternntives to the CLI nre exnmined incÌuding
üo the
WInMySQLAdmin, nnd MySQLGUI. The second chnµter exnmines vnrious SQL stnte-
ments in MySQL. The finnÌ chnµter of the section is covers some toµics thnt fit into
this section nnd µreµnre for other sections.
Part III: Administration
In this µnrt, some server configurntions nre exnmined nÌong with vnrinbÌes nnd
oµtions for the MySQL server. MySQL server security is within this section, ns weÌÌ
ns debugging nnd reµniring MySQL dntnbnses nnd servers.
Part IV: DeveIopment
Iour µoµuÌnr methods for deveÌoµing nµµÌicntions with MySQL nre exnmined in sec-
tion four. This incÌudes PerÌ, PHP, connecting MySQL to OD8C, nnd 1D8C with 1nvn.
NotnbÌy, I did not incÌude C or C-- into this section ns I strongÌy feeÌ thnt mnny
nµµÌicntions for MySQL nren`t deveÌoµed in C or C--. I wiÌÌ grnnt thnt there nre
some, but the widesµrend Ìnngunges used thnt I`ve seen nre PerÌ, 1nvn, nnd PHP.
Part V: Advanced Performance
The finnÌ grouµ of chnµters Ìooks nt some toµics thnt don`t renÌÌy fit into nnother
section. These incÌude reµÌicntion, integrntion of MySQL with PAM in Linux, nnd
NuSµhere MySQL.
Part VI: Appendixes
The Aµµendixes incÌude stnndnrd MySQL reference mnterinÌ, n nifty GÌossnry, nnd
instructions for the CD-ROM.
About the Companion CD-kOM
Much of the softwnre discussed in the book is incÌuded on the CD-ROM with this
book. Since softwnre frequentÌy chnnges versions, you mny find n newer version of
the softwnre on the resµective websites. The MySQL softwnre cnn be downÌonded
from the MySQL A8 web site.
I`ve nÌso incÌuded softwnre nnd scriµts thnt I used within the book ns exnmµÌes.
AÌso on the CD-ROM nre Ìinks thnt I use frequentÌy nnd most ÌikeÌy highÌight within
the µnges of the book ns weÌÌ.
MY5OL ßibIe
How to Use Ihis ßook
If you don`t nÌrendy know nbout dntnbnses in genernÌ, or you`re getting stnrted with
n MySQL system, I recommend rending this book from cover to cover. If you hnve n
chnÌÌenging tnsk with nn existing MySQL system, try the Index nnd the TnbÌe of
Contents for your sµecific µrobÌem.
IaIk Io Me
I`d Ìike to henr feedbnck on this book. Since the book is my first of this Ìength, I`ÌÌ be
quite hnµµy to know thnt someone out there nctunÌÌy rend it. WhiÌe I`ve done my
best to mnke this book nccurnte, I won`t be surµrised if you find nn error, tyµo-
grnµhicnÌ or otherwise. I`ÌÌ do whnt I cnn to get it fixed, short of going nnd crossing
out ench tyµo with n mnrker.
I`ÌÌ be hnµµy to try to nnswer sµecific questions nbout MySQL. However, I cnn`t
gunrnntee thnt I`ÌÌ be nbÌe to nnswer questions fuÌÌy.
You cnn send emniÌ to me nt:
I nÌso hnve n website thnt contnins some fun stuff, ns weÌÌ ns other µro|ects thnt I`m
working on:
his book wouÌdn`t hnve been µossibÌe without he̵ from mnny µeoµÌe. Iirst, I
need to thnnk Terri Vnrveris for her unending µntience with n writer on his
first book ns weÌÌ ns Pnt O`8rien. Lveryone nt WiÌey hns been n µÌensure to work
with. Adnm Goodmnn nnd 1eremy Znwodny from Linux Moµozinc offered some grent
he̵ to n fÌedgÌing writer.
There nre mnny others who shouÌd get some credit nnd nre too numerous to men-
tion by nnme. InevitnbÌy I`m going to Ìenve someone out nnd I nµoÌogize in ndvnnce.
My wife Rebeccn exhibited grent understnnding, not onÌy with this book, but with
me in genernÌ. My fnmiÌy, which hns nÌwnys been there to he̵ nnd offer guidnnce
deserves thnnks, ns does my friend Chris Tuescher. He wouÌdn`t hesitnte to do nny-
thing to he̵ n friend in need.
The Nightmnre Productions nnd CnµitoÌ Lntertninment grouµ of µeoµÌe he̵ed
shnµe who I nm. 8ob, Mike IeÌtz, Lrnie TnyÌor, nnd Chris Tuescher stnnd out first
nnd foremost. However, Chris Steffen, Ron Mnckny, Chnd Chnsteen, Pnt Quimby,
nnd the rest of the gnng hnd their µnrts too. 1ust one more time nt for Mike nt
Mnnnwn MiddÌe or LÌÌen nt Mosinee wouÌd be nice, wouÌdn`t it"
Of course, 1im Leu, 1ohn Hein, 1eremy Guthrie, Andy 8erkvnm, 8rnndon, Dnn, Lrich,
Mnrk, Snrnh, 1ustin, Tnrn, the CORL DigitnÌ gnng from Stevens Point. 8rinn nnd 1iÌÌ
nnd Deb Pnge nnd 1ny Schrnnk gnve me the oµµortunity nnd deserve thnnks with
everyone eÌse. WiÌÌ you renÌÌy ever forget the time we hnd nt CORL"
The crew from LxecPC}Voynger}CoreComm needs thnnks, too. MichneÌ MitteÌstndt
for hnving fnith in me. A1, Anron, AÌ, Denise, 1nmes, 1erry, 1oey Z, Mntt, Nic, both
Rynns, nnd the whoÌe gnng from #mcµ nnd #|bs. The LxecPC stnff nnd former CORL
DigitnÌ stnff nre some of the smnrtest µeoµÌe to ever wnÌk the fnce of the enrth .
Professors RiÌey, MiÌÌer, nnd Cntes hnve been n grent infÌuence on my Ìife, ns hnve
Duff Dnmos nnd Gnry Wescott. SµecinÌ thnnks to 9Ofm, Nightmnre Sqund, 1im OÌivn,
nnd 1ohn Lckendorf nre in order ns weÌÌ for tnking the time nnd effort every yenr to
bring the WorÌd`s Lnrgest Trivin Contest to Ìife. Yes, it renÌÌy is the WorÌd`s Lnrgest.
The book wouÌdn`t hnve been written without the never ending Ìunches from Mike
MitcheÌÌ nnd 11 nt HiÌÌtoµ. Thnnks to Tim nt Pnrtner`s.
MY5OL ßibIe
WhiÌe I wns writing the book, Kent Lnnbs Ìet me borrow one of his drum kits. Quite
n few evenings were sµent hnmmering nwny. Though Kent mny find out by the time
he rends this, I beÌieve I owe him n new cymbnÌ. Who knows, somedny mnybe Pnt
Dunn wiÌÌ Ìet me µÌny with Sµicy Tie 8nnd ngnin.
IinnÌÌy, Lddie Vnn HnÌen deserves thnnks ns weÌÌ. His music hns offered insµirntion
throughout the writing of the book nnd beyond. It`s nÌmost ns if I feeÌ the need to
cut him in on the book denÌ. AÌmost. If I get thnt invite to b1bO sometime...
Contents at a Clance
Prefnce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
AcknowÌedgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
PAkI 1: Cetting 5tarted . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chnµter 1: ReÌntionnÌ Dntnbnse Mnnngement . . . . . . . . . . . . . . . . . . . . . . 8
Chnµter 2: Preµnring for InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Chnµter 8: Linux InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8b
Chnµter 4: Windows InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . b8
Chnµter b: Mncintosh InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Chnµter 6: Stnrting MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Chnµter 7: Dntnbnse Conceµts nnd Design . . . . . . . . . . . . . . . . . . . . . . 1Ob
PAkI II: 5OL EssentiaIs . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Chnµter 8: Commnnd Line Interfnce (CLI) . . . . . . . . . . . . . . . . . . . . . . 188
Chnµter 9: SQL According to MySQL . . . . . . . . . . . . . . . . . . . . . . . . . 171
Chnµter 1O: Dntnbnse nnd Dntn . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
PAkI III: Administration . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Chnµter 11: Server Configurntions . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Chnµter 12: Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Ob
Chnµter 18: Debugging nnd Reµniring Dntnbnses . . . . . . . . . . . . . . . . . . 887
Chnµter 14: Performnnce Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . 878
PAkI IV: DeveIopment . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Chnµter 1b: PerÌ DeveÌoµment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 898
Chnµter 16: PHP DeveÌoµment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Chnµter 17: OD8C}1D8C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
PAkI V: Advanced Performance . . . . . . . . . . . . . . . . . . . . . . 523
Chnµter 18: ReµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b2b
Chnµter 19: Integrntion of Internet Services . . . . . . . . . . . . . . . . . . . . . b49
Chnµter 2O: NuSµhere Lnhnnced MySQL . . . . . . . . . . . . . . . . . . . . . . . b71
PAkI VI: Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Aµµendix A: AµµÌicntion Reference . . . . . . . . . . . . . . . . . . . . . . . . . . b9b
Aµµendix 8: Lnngunge Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Aµµendix C: Iunction nnd Oµerntor Reference . . . . . . . . . . . . . . . . . . . 62b
Aµµendix D: Dntntyµe Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 64b
Aµµendix L: GÌossnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b8
Aµµendix I: About the CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b9
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Why I Wrote This 8ook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Whnt You Need to Know . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Whnt You Need to Hnve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Whnt the Icons Menn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
How This 8ook Is Orgnnized . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
Pnrt I: Getting Stnrted . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
Pnrt II: SQL LssentinÌs . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
Pnrt III: Administrntion . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Pnrt IV: DeveÌoµment . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Pnrt V: Advnnced Performnnce . . . . . . . . . . . . . . . . . . . . . . . xi
Pnrt VI: Aµµendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
About the Comµnnion CD-ROM . . . . . . . . . . . . . . . . . . . . . . . . . . xi
How to Use This 8ook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
TnÌk To Me . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
PAkI I: Cetting 5tarted 1
Chapter 1: keIationaI Database Management . . . . . . . . . . . . . . . 3
AµµÌicntions for Dntnbnses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Customer dntnbnses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Internet service µroviders` dntnbnses . . . . . . . . . . . . . . . . . . . b
CriminoÌogy nnd dntnbnses . . . . . . . . . . . . . . . . . . . . . . . . . 6
Advnntnges of using dntnbnses . . . . . . . . . . . . . . . . . . . . . . . 7
Comµnring SQL ImµÌementntions . . . . . . . . . . . . . . . . . . . . . . . . . 7
OrncÌe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Microsoft SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O
Informix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Introducing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
MySQL versions nnd fentures . . . . . . . . . . . . . . . . . . . . . . . 11
Stnndnrds nnd comµntibiÌity . . . . . . . . . . . . . . . . . . . . . . . . 18
MySQL-sµecific µroµerties . . . . . . . . . . . . . . . . . . . . . . . . . 16
Whnt MySQL Does 8est . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Whnt MySQL Cnn`t Do~Quite Yet . . . . . . . . . . . . . . . . . . . . 19
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2O
MY5OL ßibIe
Chapter 2: Preparing for InstaIIation . . . . . . . . . . . . . . . . . . . 21
Prerequisites for MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Licensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Suµµort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Oµernting system nnd nrchitecture . . . . . . . . . . . . . . . . . . . . 28
DeveÌoµment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Lxisting dntn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
DefnuÌt Ìnngunge nnd chnrncter set . . . . . . . . . . . . . . . . . . . . 28
Mnnngement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Where to Obtnin MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8O
Overview of MySQL Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . 8O
MySQL numbering scheme . . . . . . . . . . . . . . . . . . . . . . . . . 8O
8innry versions of MySQL . . . . . . . . . . . . . . . . . . . . . . . . . 8O
Source-code versions of MySQL . . . . . . . . . . . . . . . . . . . . . . 82
MySQL for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
MySQL for Mnc OS X . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Chapter 3: Linux InstaIIation . . . . . . . . . . . . . . . . . . . . . . . . 35
Common 8innry, RPM, nnd Source MySQL InstnÌÌntion Tnsks . . . . . . . . 8b
MySQL server stnrtuµ nnd shutdown . . . . . . . . . . . . . . . . . . . 8b
Common commnnd-Ìine oµtions for mysqÌd . . . . . . . . . . . . . . . 88
Crenting defnuÌt dntnbnses nnd comµÌeting instnÌÌntion . . . . . . . . 42
Setting nn ndministrntor µnssword for MySQL . . . . . . . . . . . . . 44
MySQL Linux 8innry InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . 4b
MySQL Linux RPM InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . 47
MySQL Linux Source InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . 48
Choosing Oµtions for MySQL . . . . . . . . . . . . . . . . . . . . . . . 48
ComµiÌing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b1
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b2
Chapter 4: Windows InstaIIation . . . . . . . . . . . . . . . . . . . . . . 53
Tnsks Common to 8innry nnd Source MySQL InstnÌÌntion . . . . . . . . . . b8
MySQL server ndministrntion
the Windows wny . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b8
MySQL server stnrtuµ nnd shutdown . . . . . . . . . . . . . . . . . . . b6
Common commnnd-Ìine oµtions for mysqÌd . . . . . . . . . . . . . . . b8
Setting nn Administrntor µnssword for MySQL . . . . . . . . . . . . . 62
InstnÌÌing MySQL on Windows 2OOO . . . . . . . . . . . . . . . . . . . . . . . 68
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Chapter 5: Macintosh InstaIIation . . . . . . . . . . . . . . . . . . . . . 69
8innry nnd Source-Code MySQL InstnÌÌntion in Mnc OS X:
Tnsks in Common . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Setting uµ MySQL to stnrt nutomnticnÌÌy . . . . . . . . . . . . . . . . . 69
Shutting down MySQL Server . . . . . . . . . . . . . . . . . . . . . . . 78
Setting nn ndministrntor µnssword for MySQL . . . . . . . . . . . . . 78
InstnÌÌing MySQL With Mnc OS X Server . . . . . . . . . . . . . . . . . . . . . 74
InstnÌÌing MySQL 8innry on Mnc OS X . . . . . . . . . . . . . . . . . . . . . . 74
InstnÌÌing MySQL Source Code on Mnc OS X . . . . . . . . . . . . . . . . . . 7b
Crenting the MySQL User . . . . . . . . . . . . . . . . . . . . . . . . . . 7b
ComµiÌing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Configuring MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Testing MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8O
Chapter 6: 5tarting My5OL . . . . . . . . . . . . . . . . . . . . . . . . . 81
MySQL Server Administrntion nnd Security . . . . . . . . . . . . . . . . . . 81
Using mysqÌndmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Setting the root µnssword . . . . . . . . . . . . . . . . . . . . . . . . . 82
Checking MySQL server stntus . . . . . . . . . . . . . . . . . . . . . . 88
DenÌing with innctive connections . . . . . . . . . . . . . . . . . . . . . 84
Shut down the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
8nsic MySQL security . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
IrequentÌy Used MySQL Dntnbnse Iunctions . . . . . . . . . . . . . . . . . . 88
Crenting n dntnbnse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Crenting tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Inserting nnd uµdnting dntn . . . . . . . . . . . . . . . . . . . . . . . . 92
Preµnring n new user for nccess to the dntnbnse . . . . . . . . . . . . 97
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O2
Chapter 7: Database Concepts and Design . . . . . . . . . . . . . . . 105
Conceµts of Dntnbnses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ob
Whnt is dntn" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ob
Whnt is n dntnbnse" . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Ob
Why use n Dntnbnse" . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O6
How nre dntnbnses used" . . . . . . . . . . . . . . . . . . . . . . . . . 1O7
Dntnbnse Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O7
The Dntnbnse Life CycÌe . . . . . . . . . . . . . . . . . . . . . . . . . . 1O8
LogicnÌ Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O9
Lntities nnd nttributes . . . . . . . . . . . . . . . . . . . . . . . . . . . 1O9
ReÌntionshiµs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Lntity-reÌntionshiµ dingrnms . . . . . . . . . . . . . . . . . . . . . . . 118
AnnÌysis of dingrnms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Constrnints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
NormnÌizntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12O
Dntn Definition Lnngunge nnd Dntn Mnrkuµ Lnngunge . . . . . . . . 122
Producing the SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
PhysicnÌ Design nnd ImµÌementntion . . . . . . . . . . . . . . . . . . . . . . 124
Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12b
ImµÌementntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18O
MY5OL ßibIe
Part II: 5OL EssentiaIs 131
Chapter 8: Command Line Interface (CLI) . . . . . . . . . . . . . . . . 133
Introducing the CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Stnrting the CLI ~the 8nsics . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Sµecifying the usernnme . . . . . . . . . . . . . . . . . . . . . . . . . 187
Sµecifying the µnssword . . . . . . . . . . . . . . . . . . . . . . . . . 188
Sµecifying the host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Sµecifying the dntnbnse . . . . . . . . . . . . . . . . . . . . . . . . . . 14O
MySQL CLI Lnvironment VnrinbÌes . . . . . . . . . . . . . . . . . . . . . . . 141
Determining nnd chnnging defnuÌt vnrinbÌes . . . . . . . . . . . . . . 141
Using the CLI in Internctive Mode . . . . . . . . . . . . . . . . . . . . . . . 146
Sµeeding stnrtuµ of the CLI . . . . . . . . . . . . . . . . . . . . . . . . 147
Mnking the CLI quieter . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Using n µnger to work with Ìnrger nmounts of dntn . . . . . . . . . . 147
DisµÌnying query resuÌts verticnÌÌy . . . . . . . . . . . . . . . . . . . . 148
Using tee to snve outµut . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Printing outµut in HTML formnt . . . . . . . . . . . . . . . . . . . . . 1bO
Suµµressing coÌumn nnmes . . . . . . . . . . . . . . . . . . . . . . . . 1bO
Using bntch mode to µroduce tnb deÌimited outµut . . . . . . . . . . 1bO
Using the CLI in Non-Internctive Mode . . . . . . . . . . . . . . . . . . . . . 1b2
Lxecuting n stntement . . . . . . . . . . . . . . . . . . . . . . . . . . . 1b2
Printing HTML outµut . . . . . . . . . . . . . . . . . . . . . . . . . . . 1b2
Suµµressing coÌumn nnmes . . . . . . . . . . . . . . . . . . . . . . . . 1b4
Printing resuÌts verticnÌÌy . . . . . . . . . . . . . . . . . . . . . . . . . 1bb
Using bntch mode to µroduce tnb-deÌimited outµut . . . . . . . . . . 1bb
Crenting n UsefuÌ MySQL CLI Lnvironment . . . . . . . . . . . . . . . . . . 1b6
A bnsic MySQL CLI configurntion . . . . . . . . . . . . . . . . . . . . 1b6
A MySQL ndministrntion configurntion . . . . . . . . . . . . . . . . . 1b7
A cÌient-onÌy MySQL CLI configurntion . . . . . . . . . . . . . . . . . 1b7
Your MySQL CLI configurntion . . . . . . . . . . . . . . . . . . . . . . 1b7
Common CLI Lrrors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1b8
Access Denied errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 1b8
AÌternntives to the CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16O
The bnsics of MySQLGUI . . . . . . . . . . . . . . . . . . . . . . . . . 16O
Running SQL stntements with MySQLGUI . . . . . . . . . . . . . . . . 168
Administrntion with MySQLGUI . . . . . . . . . . . . . . . . . . . . . 166
The bnsics of µhµMyAdmin . . . . . . . . . . . . . . . . . . . . . . . . 168
Running SQL stntements with µhµMyAdmin . . . . . . . . . . . . . . 168
Administrntion with µhµMyAdmin . . . . . . . . . . . . . . . . . . . . 169
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Chapter 9: 5OL According to My5OL . . . . . . . . . . . . . . . . . . . 171
UtiÌity nnd Administrntive Stntements nnd Commnnds . . . . . . . . . . . 171
SHOW stntements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
USL}CONNLCT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
DLSCRI8L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18O
KILL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18O
OPTIMIZL TA8LL ·tnbÌennme· . . . . . . . . . . . . . . . . . . . . . . 18O
Dntn Definition Lnngunge . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
DeÌeting tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
DeÌeting nnd crenting dntnbnses . . . . . . . . . . . . . . . . . . . . . 182
Crenting tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
AÌtering tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18b
Dntn Mnrkuµ Lnngunge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Inserting dntn into the dntnbnse with INSLRT . . . . . . . . . . . . . 191
Gnthering dntn with SLLLCT . . . . . . . . . . . . . . . . . . . . . . . 197
Uµdnting dntn with the UPDATL stntement . . . . . . . . . . . . . . . 228
DeÌete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28O
Chapter 10: Databases and Data . . . . . . . . . . . . . . . . . . . . . 231
Choosing the Right MySQL TnbÌe Tyµe . . . . . . . . . . . . . . . . . . . . 281
MySQL tnbÌe tyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
MyISAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
MLRGL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24O
ISAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24O
HLAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
InnoD8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
8erkeÌeyD8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24b
Administering Your Dntnbnse with mysqÌndmin . . . . . . . . . . . . . . . 246
Common switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
SµecinÌ switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Iunctions with mysqÌndmin . . . . . . . . . . . . . . . . . . . . . . . 249
Lxµorting Dntn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26O
mysqÌdumµ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26O
SLLLCT INTO OUTIILL . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Imµorting Dntn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
LOAD DATA INIILL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
mysqÌimµort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Part III: Administration 279
Chapter 11: 5erver Configurations . . . . . . . . . . . . . . . . . . . . 281
MySQL Server VnrinbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Viewing current server vnrinbÌes . . . . . . . . . . . . . . . . . . . . . 281
MySQL 8enchmnrking nnd Testing . . . . . . . . . . . . . . . . . . . . . . . 292
Requirements for the nµµÌicntions . . . . . . . . . . . . . . . . . . . . 292
Running the tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
MY5OL ßibIe
SnmµÌe Configurntion IiÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Lxnminntion of the snmµÌe configurntion fiÌes . . . . . . . . . . . . . 296
DeveÌoµing your own configurntion fiÌe . . . . . . . . . . . . . . . . . . . . 298
8ringing it nÌÌ together . . . . . . . . . . . . . . . . . . . . . . . . . . . 8O2
Running More Thnn One MySQL Server on the Snme Mnchine . . . . . . . 8O8
Configurntion of muÌtiµÌe MySQL servers . . . . . . . . . . . . . . . . 8O8
Connecting to muÌtiµÌe MySQL servers . . . . . . . . . . . . . . . . . 8O8
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8O4
Chapter 12: 5ecurity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Security of the MySQL Host Server . . . . . . . . . . . . . . . . . . . . . . . 8Ob
Locnting security informntion . . . . . . . . . . . . . . . . . . . . . . 8O6
AµµÌy µntches nnd fixes . . . . . . . . . . . . . . . . . . . . . . . . . . 8O8
DisnbÌe unused µrogrnms nnd services . . . . . . . . . . . . . . . . . 8O8
MySQL Softwnre Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81O
MySQL uµdntes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81O
Run the server ns n non-µriviÌeged user . . . . . . . . . . . . . . . . . 811
IirewnÌÌing the MySQL server . . . . . . . . . . . . . . . . . . . . . . 812
Communicnting secureÌy with the MySQL server . . . . . . . . . . . 812
Using socket-bnsed connections . . . . . . . . . . . . . . . . . . . . . 818
Chnnging the MySQL defnuÌt µort . . . . . . . . . . . . . . . . . . . . 818
Monitoring dntn sent to MySQL . . . . . . . . . . . . . . . . . . . . . 81b
DisnbÌing DNS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
Dynnmic MySQL monitoring of Web µnges . . . . . . . . . . . . . . . 816
MySQL Authenticntion nnd PriviÌeges . . . . . . . . . . . . . . . . . . . . . 828
Overview of MySQL nuthenticntion . . . . . . . . . . . . . . . . . . . 828
MySQL µriviÌeges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
Security of µnsswords . . . . . . . . . . . . . . . . . . . . . . . . . . . 82b
MySQL µnsswords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
MySQL User Mnnngement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826
Adding users nnd grnnting µriviÌeges . . . . . . . . . . . . . . . . . . 827
DeÌeting users nnd revoking µriviÌeges . . . . . . . . . . . . . . . . . 88O
Chnnging µnsswords nnd other µnrnmeters . . . . . . . . . . . . . . 881
Common ProbÌems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
Access denied . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
Ooµs, I forgot the root µnssword . . . . . . . . . . . . . . . . . . . . . 884
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88b
Chapter 13: Debugging and kepairing Databases . . . . . . . . . . . 337
Performing Dntnbnse 8nckuµs . . . . . . . . . . . . . . . . . . . . . . . . . 888
mysqÌhotcoµy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
mysqÌdumµ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 848
8ACKUP TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8bO
TroubÌeshooting nnd Reµniring TnbÌe ProbÌems . . . . . . . . . . . . . . . 8b1
mysqÌcheck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8b2
myisnmchk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8b6
ANALYZL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
OPTIMIZL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
CHLCK TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86b
RLPAIR TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86b
Restoring n MySQL Dntnbnse . . . . . . . . . . . . . . . . . . . . . . . . . . 86b
mysqÌhotcoµy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866
RLSTORL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866
The MySQL CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 868
Devising n PÌnn for Dntnbnse 8nckuµs . . . . . . . . . . . . . . . . . . . . . 869
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 871
Chapter 14: Performance Iuning . . . . . . . . . . . . . . . . . . . . . 373
TroubÌeshooting Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 878
MySQL ÌogfiÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
TroubÌeshooting nnd µerformnnce functions
with mysqÌndmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877
MySQL CLI troubÌeshooting nnd
µerformnnce functions . . . . . . . . . . . . . . . . . . . . . . . . . 882
mysqÌshow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 884
Oµtimizing Dntnbnses nnd TnbÌes . . . . . . . . . . . . . . . . . . . . . . . . 886
Oµtimizing Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889
PAkI IV: DeveIopment 391
Chapter 15: PerI DeveIopment . . . . . . . . . . . . . . . . . . . . . . 393
InstnÌÌing the PerÌ D8I And MySQL D8D . . . . . . . . . . . . . . . . . . . . 894
Where to get the D8I nnd D8D . . . . . . . . . . . . . . . . . . . . . . 894
InstnÌÌing the D8I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
InstnÌÌing the MySQL D8D . . . . . . . . . . . . . . . . . . . . . . . . . 898
Introducing the D8I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4O2
8nsic D8I Usnge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4O2
Connecting to nnd disconnecting
from the dntnbnse with the D8I . . . . . . . . . . . . . . . . . . . . 4O4
HnndÌing errors with the D8I . . . . . . . . . . . . . . . . . . . . . . . 41O
Iunctions with the D8I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41b
8uiÌding 8nsic AµµÌicntions . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
MySQL User Mnnnger . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
8uiÌding Web Pnges with the D8I . . . . . . . . . . . . . . . . . . . . . . . . 428
A simµÌe Web nµµÌicntion to query MySQL . . . . . . . . . . . . . . . 429
Acceµting inµut from n form . . . . . . . . . . . . . . . . . . . . . . . 481
Producing nn L-Commerce Web site . . . . . . . . . . . . . . . . . . . . . . 484
Dntnbnse Ìnyout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48b
8uiÌding nn inventory-inµut µrogrnm . . . . . . . . . . . . . . . . . . 486
8uiÌding n simµÌe µroduct senrch engine . . . . . . . . . . . . . . . . 441
Present nnd future exµnnsion . . . . . . . . . . . . . . . . . . . . . . . 448
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
MY5OL ßibIe
Chapter 16: PHP DeveIopment . . . . . . . . . . . . . . . . . . . . . . 449
PHP InstnÌÌntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Whnt you need for instnÌÌntion . . . . . . . . . . . . . . . . . . . . . . 4bO
Where to get the softwnre . . . . . . . . . . . . . . . . . . . . . . . . . 4b1
InstnÌÌing PHP on n Linux system . . . . . . . . . . . . . . . . . . . . . 4b2
8rnss Tncks: PHP LssentinÌs . . . . . . . . . . . . . . . . . . . . . . . . . . . 4b9
A PHP Web µnge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4b9
PHP nnd forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
PHP MySQL Configurntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
Configurntion settings . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
PHP MySQL Iunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46b
The functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46b
Connecting to MySQL with PHP . . . . . . . . . . . . . . . . . . . . . 467
SeÌecting dntn from n MySQL dntnbnse . . . . . . . . . . . . . . . . . 468
Inserting nnd uµdnting dntn in MySQL . . . . . . . . . . . . . . . . . 472
8uiÌding MySQL-LnnbÌed AµµÌicntions With PHP . . . . . . . . . . . . . . . 474
A PHP version of the user mnnnger . . . . . . . . . . . . . . . . . . . 474
Cookies with no miÌk . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Chapter 17: ODßC/¡DßC. . . . . . . . . . . . . . . . . . . . . . . . . . . 493
An Introduction to MyOD8C . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
Where to get MyOD8C . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
InstnÌÌing MyOD8C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
Chnnging MyOD8C Oµtions . . . . . . . . . . . . . . . . . . . . . . . . 497
Using MyOD8C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Imµorting MySQL dntn into Microsoft Access . . . . . . . . . . . . . 499
Imµorting dntn into Microsoft Word . . . . . . . . . . . . . . . . . . . bO4
An Introduction to 1D8C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b1O
The 1D8C interfnce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b11
Where to get the 1D8C nnd MySQL 1D8C Driver . . . . . . . . . . . . b11
InstnÌÌing the MySQL 1D8C Driver . . . . . . . . . . . . . . . . . . . . b11
Using the 1D8C nnd the MySQL Driver . . . . . . . . . . . . . . . . . . . . . b14
The conceµts nnd terms of 1D8C . . . . . . . . . . . . . . . . . . . . . b14
The bnsics of hnndÌing stntements nnd resuÌts . . . . . . . . . . . . . b1b
Dntnbnse metndntn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b16
Working with 1D8C errors . . . . . . . . . . . . . . . . . . . . . . . . . b17
Testing for NULL vnÌues . . . . . . . . . . . . . . . . . . . . . . . . . . b17
Cnched connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . b18
Connecting to MySQL with the 1D8C API nnd
MySQL Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b18
Crenting n bnsic MySQL 1D8C Progrnm . . . . . . . . . . . . . . . . . b2O
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b21
Part V: Advanced Performance 523
Chapter 18: kepIication . . . . . . . . . . . . . . . . . . . . . . . . . . 525
PÌnnning nnd Preµnring for ReµÌicntion . . . . . . . . . . . . . . . . . . . . b2b
Considerntions for reµÌicntion . . . . . . . . . . . . . . . . . . . . . . b26
MySQL server versions . . . . . . . . . . . . . . . . . . . . . . . . . . b27
Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b27
Configuring ReµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b27
ReµÌicntion vnrinbÌes nnd settings . . . . . . . . . . . . . . . . . . . . b27
A bnsic reµÌicntion configurntion . . . . . . . . . . . . . . . . . . . . . b8O
MuÌtiµÌe sÌnve reµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . . b88
MuÌtiµÌe mnster reµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . b84
Pnss-through sÌnve reµÌicntion . . . . . . . . . . . . . . . . . . . . . . b87
Monitoring ReµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b87
Monitoring reµÌicntion with PerÌ . . . . . . . . . . . . . . . . . . . . . b87
Monitoring reµÌicntion through the Web . . . . . . . . . . . . . . . . b4O
Kick-stnrting ReµÌicntion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b48
When good reµÌicntion goes bnd . . . . . . . . . . . . . . . . . . . . . b44
Kick-stnrting reµÌicntion revenÌed . . . . . . . . . . . . . . . . . . . . b44
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b46
Chapter 19: Integration of Internet 5ervices. . . . . . . . . . . . . . . 549
PAM nnd NSS User Authenticntion in MySQL . . . . . . . . . . . . . . . . . bbO
InstnÌÌing PAM-MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . bb1
PAM-MySQL syntnx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bb2
Testing PAM-MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . bb8
InstnÌÌing NSS-MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . bbb
Configurntion of NSS-MySQL . . . . . . . . . . . . . . . . . . . . . . . bbb
DNS Mnnngement with MySQL . . . . . . . . . . . . . . . . . . . . . . . . . bb6
Crenting n DNS mnnngement interfnce . . . . . . . . . . . . . . . . . . bb6
MySQL nnd RADIUS Integrntion . . . . . . . . . . . . . . . . . . . . . . . . . b61
A cÌoser Ìook nt Rndintor . . . . . . . . . . . . . . . . . . . . . . . . . b61
L-MniÌ Integrntion nnd Mnnngement with MySQL . . . . . . . . . . . . . . . b62
8uiÌding n virtunÌ users tnbÌe for SendmniÌ . . . . . . . . . . . . . . . b62
A virtunÌ e-mniÌ dntnbnse . . . . . . . . . . . . . . . . . . . . . . . . . b68
Imµorting existing virtunÌ e-mniÌ entries . . . . . . . . . . . . . . . . b64
A Web interfnce for virtunÌ e-mniÌ mnnngement . . . . . . . . . . . . b66
8uiÌding n IuÌÌ-ScnÌe VirtunÌ-Services Interfnce . . . . . . . . . . . . . . . . b69
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b69
Chapter 20: Nu5phere Enhanced My5OL . . . . . . . . . . . . . . . . 571
NuSµhere MySQL Advnntnge: A CÌoser Look . . . . . . . . . . . . . . . . . b72
Gemini: A new tnbÌe tyµe . . . . . . . . . . . . . . . . . . . . . . . . . b72
NuSµhere integrntion with µoµuÌnr softwnre . . . . . . . . . . . . . . b72
NuSµhere mnnngement tooÌs . . . . . . . . . . . . . . . . . . . . . . . b72
MY5OL ßibIe
InstnÌÌing NuSµhere Pro Advnntnge on Linux . . . . . . . . . . . . . . . . . b78
The NuSµhere instnÌÌntion µrocess . . . . . . . . . . . . . . . . . . . b78
NuSµhere ndministrntion . . . . . . . . . . . . . . . . . . . . . . . . . b78
Crenting Gemini tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . b79
Gemini configurntion oµtions . . . . . . . . . . . . . . . . . . . . . . . b81
InstnÌÌing NuSµhere Pro Advnntnge on Windows 2OOO . . . . . . . . . . . . b82
The NuSµhere instnÌÌntion µrocess . . . . . . . . . . . . . . . . . . . b88
NuSµhere ndministrntion . . . . . . . . . . . . . . . . . . . . . . . . . b87
Crenting Gemini tnbÌes . . . . . . . . . . . . . . . . . . . . . . . . . . . b88
Gemini configurntion oµtions . . . . . . . . . . . . . . . . . . . . . . . b9O
Summnry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b91
Part VI: Appendixes 593
Appendix A: AppIication keference . . . . . . . . . . . . . . . . . . . 595
A.1 Dntn-Access AµµÌicntions . . . . . . . . . . . . . . . . . . . . . . . . . . b9b
mysqÌ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b9b
mysqÌdumµ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . b98
mysqÌshow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6OO
A.2 Server-Administrntion AµµÌicntions . . . . . . . . . . . . . . . . . . . . 6O1
mysqÌndmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6O1
mysqÌcheck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6O8
mysqÌimµort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6O4
mysqÌtest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6O6
A.8 The mysqÌd Server Dnemon . . . . . . . . . . . . . . . . . . . . . . . . . 6O6
Appendix ß: Language keference . . . . . . . . . . . . . . . . . . . . . 611
8.1 Dntn Definition Lnngunge nnd Dntn Mnrkuµ Lnngunge . . . . . . . . . . 611
ALTLR TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
CRLATL DATA8ASL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
CRLATL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
DLSCRI8L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
DLLLTL IROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
LXPLAIN SLLLCT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
HANDLLR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
INSLRT INTO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61b
SLLLCT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61b
SHOW TA8LLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
UPDATL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
8.2. Administrntive Commnnds . . . . . . . . . . . . . . . . . . . . . . . . . 618
ANALYZL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
ILUSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
KILL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
OPTIMIZL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62O
RLSLT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62O
SHOW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62O
8.8 8nckuµ } Recovery Commnnds . . . . . . . . . . . . . . . . . . . . . . . 621
8ACKUP TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
CHLCK TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
RLPAIR TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
RLSTORL TA8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
8.4. User-Account Commnnds . . . . . . . . . . . . . . . . . . . . . . . . . . 628
GRANT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
RLVOKL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Appendix C: Function and Operator keference . . . . . . . . . . . . 625
C.1. MySQL Oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62b
Comµnrison oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . 62b
IÌow-controÌ oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . 626
LogicnÌ oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Stntement oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
String oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
C.2. MySQL Iunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
8innry mnth functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Dnte functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
DecimnÌ mnth functions . . . . . . . . . . . . . . . . . . . . . . . . . . 684
SeÌect oµerntors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
String functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
System functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
Trigonometric mnth functions . . . . . . . . . . . . . . . . . . . . . . 648
Appendix D: Datatype keference . . . . . . . . . . . . . . . . . . . . . 645
D.1. Integer Dntntyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64b
8IGINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64b
INT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64b
MLDIUMINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
SMALLINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
TINYINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
D.2. DecimnÌ Dntntyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
ILOAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
DLCIMAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
DOU8LL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
D.8 Dnte Dntntyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
DATL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
DATLTIML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
TIMLSTAMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
TIML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
YLAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
D.4. STRING Dntntyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
8LO8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
CHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6bO
TLXT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6bO
VARCHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6bO
MY5OL ßibIe
D.b. Grouµing Dntntyµes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b1
LNUM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b1
SLT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b1
Appendix E: CIossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Appendix F: About the CD-kOM . . . . . . . . . . . . . . . . . . . . . 659
System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b9
Whnt`s on the CD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6b9
If You Hnve ProbÌems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66O
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
Cetting 5tarted
ln Ihis Porl
Chopler J
Relollonol Dolobose
Chopler 2
Preporlng lor
Chopler 3
Llnux lnslollollon
Chopler 4
Vlndows lnslollollon
Chopler 5
Moclnlosh lnslollollon
Chopler 6
Slorllng MySCL
Chopler 7
Dolobose Concepls
ond Deslgn
P A k I
efore you sound the deµths of MySQL, it wouÌd be he̵-
fuÌ to Ìook nt some nµµÌicntions for dntnbnses nnd nt
other imµÌementntions of SQL servers.
This chnµter Ìnys out some groundwork for the rest of the
book ~in µnrticuÌnr, with tnbÌes thnt iÌÌustrnte MySQL`s
extensions to the SQL-92 stnndnrd nnd comµnre some µoµuÌnr
functions of dntnbnse servers.
AppIications for Databases
Dntnbnses nre n µnrt of everydny Ìife, usunÌÌy without your
knowÌedge. Irom obvious nµµÌicntions (Ìike customer
dntnbnses for insurnnce comµnnies) to not-so-obvious uses
(such ns storing nctunÌ imnges within n dntnbnse for
recognition), dntnbnse use is µervnsive nnd incrensing.
Customer databases
Not n dny goes without teÌeµhone cnÌÌs from µeoµÌe trying to
seÌÌ µroducts or new Ìong-distnnce µÌnns. You nnd I nre in
more thnn n few customer dntnbnses ~nnd some of the
µÌnces I`ve done business with hnve shnred my teÌeµhone
number with some of their friends, who`ve then shnred it with
some of their friends ~nnother fnct of Ìife thnt`s trncenbÌe to
the µroÌiferntion of dntnbnses.
Tnking n Ìook nt some informntion stored in n few ¨everydny"
dntnbnses cnn serve ns nn exnmµÌe of the different tyµes of
informntion ench one coÌÌects, trncks, nnd sometimes stores ~
nbout you, me, nnd µrobnbÌy everyone you know. Whntever
your views on issues of µoÌitics nnd µrivncy, these common
exnmµÌes form n µicture of dntnbnses in nction.
C H A P I E k
ln Ihis Chopler
oppllcollons lor
Comporlng SCL
lnlroduclng MySCL
Part I Cetting 5tarted
IeIephone companies
The teÌeµhone comµnny thnt owns my nren stores bnsic informntion nbout me~first
nnd Ìnst nnme, nddress, city, stnte, ZIP code, nnd teÌeµhone number ~informntion
thnt`s not onÌy bnsic but nÌso common ncross nÌmost nÌÌ customer dntnbnses. 8eyond
the bnsic informntion, the ÌocnÌ teÌeµhone comµnny nÌso requires my socinÌ security
number (which he̵s them find me shouÌd I nttemµt to forego µnyment nnd Ìenve
the nren).
Within the teÌeµhone comµnny dntnbnse is n system to keeµ notes nnd corresµon-
dence. Ior exnmµÌe, ench time I cnÌÌ to tnÌk with n customer service reµresentntive,
n note goes into my fiÌe ~indicnting whnt I wns cnÌÌing nbout, the outcome (if nny),
ns weÌÌ ns the dnte, time, nnd reµresentntive`s nnme ~nÌÌ of which is recorded
nutomnticnÌÌy when the note is entered.
8eyond the µersonnÌ informntion nnd corresµondence notes, the teÌeµhone comµnny
dntnbnse nÌso serves ns n biÌÌing system thnt generntes my µhone biÌÌ nutomnticnÌÌy
on the fourth dny of every month. The dntnbnse trncks whnt services I hnve (such ns
CnÌÌ Wniting, CnÌÌer ID, nnd so forth), nssocintes ench service with n µrice, nnd tnÌÌies
my biÌÌ for the month.
Hnving customer, biÌÌing, nnd rnte informntion in n dntnbnse nÌÌows the teÌeµhone
comµnny to µroduce reµorts thnt cnn µinµoint how mnny customers hnve n certnin
rnte grouµ, how mnny Ìive in n certnin nren, how mnny hnve deÌinquent µnyments,
nnd so on.
8eyond customer reµorts, the teÌeµhone comµnny hns become much more soµhis-
ticnted in its use of the dntn. PreviousÌy when I wouÌd cnÌÌ for customer service, I
wouÌd get to tnÌk to n Ìive µerson nfter n bit of n wnit. They then imµroved their
customer service by nÌÌowing me to µunch in my 1O-digit teÌeµhone number nnd
Ìook uµ my records. Irom there, I might eventunÌÌy get to tnÌk to n Ìive µerson (if
I didn`t seÌect nny of the common tnsks on the voice-mniÌ menu). The Ìntest
imµrovement is the use of cnÌÌer identificntion to nsk me whether I`m cnÌÌing in
regnrd to the number thnt I`m cnÌÌing from. After more menus nnd µromµts, I mny
be nbÌe to rench n Ìive oµerntor.
8ehind the scenes during this µrocess is n dntnbnse thnt cnn Ìook uµ my informn-
tion when it is fed my 1O-digit number. The teÌeµhone comµnny dntnbnse cnn then
give me choices bnsed on the current stntus of my nccount. I once hnd the misfor-
tune of frnuduÌent chnrges on my teÌeµhone biÌÌ ~nbout $6bO worth. I immedinteÌy
µut thnt nmount into disµute nnd wns toÌd to µny my normnÌ $4b biÌÌ ~but I stiÌÌ
ended uµ receiving n disconnection notice. When I cnÌÌed bnck to inquire into the
notice, I wns forwnrded nutomnticnÌÌy to the coÌÌections deµnrtment (who, nfter
some discussion, hnnded me off to the reguÌnr customer service deµnrtment).
MornÌ: Dntnbnses cnn sµeed uµ onÌy those nsµects of n trnnsnction thnt don`t
require the use of common sense.
Chapter 1 keIationaI Database Management
OnIine or maiI-order stores
Another tyµe of customer dntnbnse is keµt by nn onÌine store such ns Amnzon.com
or n mniÌ-order cntnÌog store. The bnsic informntion is keµt (nnme, nddress, nnd so
on), most onÌine nnd mnny cntnÌog stores nÌso keeµ your e-mniÌ nddress ns weÌÌ. In
nddition, mnny stores trnck µnyment informntion so you don`t hnve to give your
credit cnrd number every time you wnnt to mnke n µurchnse.
As monoµoÌies, most teÌeµhone comµnnies cnn nfford to do minimnÌ mnrketing of
their µroducts nnd services. To survive in n comµetitive mnrket, however, cntnÌog
nnd onÌine stores keeµ trnck of how their customers henrd nbout them. Irom thnt
informntion, they cnn µroduce n reµort thnt he̵s identify the most effective menns
of ndvertising (or Ìook for wiser wnys to sµend mnrketing money).
Mn|or cntnÌog nnd onÌine stores nÌso trnck your µurchnses through n dntnbnse nnd
offer recommendntions bnsed uµon µrevious µurchnse µntterns. Ior exnmµÌe, if you
frequentÌy buy books on Linux, Amnzon.com might custom-buiÌd n µnge for you of
newÌy reÌensed Linux books. AÌÌ such informntion is stored in one or more
CntnÌog nnd onÌine stores cnn use the reµorting cnµnbiÌities of nn eÌectronic dntnbnse
to wntch which items nre seÌÌing best, discern nnd trnck µntterns of visitors, nnd
gnther dntn on snÌes totnÌs for items nnd deµnrtments.
Custom-service Web sites
Another interesting use of customer tyµe dntnbnses is to trnck user µreferences. An
exnmµÌe of this wouÌd be the Web site SÌnshdot, . At
SÌnshdot, they don`t keeµ informntion Ìike credit cnrd number or nddress, but they
do keeµ trnck of your e-mniÌ nddress nnd whnt news moduÌes you wnnt to see,
nmong other things. In this mnnner, you cnn customize the news you see, ns weÌÌ ns
other SÌnshdot fentures. Some user-µreference sites do keeµ µersonnÌ informntion
such ns nnme nnd nddress.
Though nÌÌ three exnmµÌes of customer dntnbnses ~teÌeµhone comµnny, onÌine
store, nnd user-µreferences site ~trnck some of the snme informntion, they nÌso
trnck their own, tnsk-sµecific informntion. This mnkes it difficuÌt for nn identity thief
to gnin nccess to nÌÌ your µersonnÌ informntion in one µÌnce. However, µersonnÌ
informntion security seems to be tnking n bncksent to the rise of nÌÌ-in-one trncking
services thnt keeµ informntion centrnÌÌy. Imngine whnt the teÌemnrketers couÌd do if
they hnd nccess to nÌÌ my µurchnse histories nnd even my e-mniÌ nddress!
Internet service providers' databases
Internet service µroviders (ISPs) use eÌectronic dntnbnses more henviÌy thnn mnny
other industries. AÌmost everything nn ISP does is in eÌectronic formnt, being reÌn-
tiveÌy young ns nn industry, they`ve grown uµ with good dntnbnse tooÌs rendiÌy
nvniÌnbÌe. In mnny wnys, ISP dntnbnses combine the functions of nÌÌ three tyµes of
customer dntnbnses I referred to enrÌier.
Part I Cetting 5tarted
The most obvious dntnbnse use for nn ISP is ns n customer dntnbnse~contnining the
usunÌ (bnsic) nnme-nnd-nddress informntion. Like the onÌine or cntnÌog stores,
the ISP dntnbnse nÌso stores informntion such ns credit cnrd or other biÌÌing dntn.
Corresµondence notes nre keµt inside n dntnbnse ns weÌÌ ns mnrketing nnd referrnÌ
records to trnck mnrketing effectiveness. An ISP dntnbnse usunÌÌy hns your e-mniÌ
nddress ns weÌÌ.
ISPs nÌso use user-µreference dntnbnses to remember your settings nnd mnke your
onÌine exµerience more µroductive ~they use the snme tyµes of dntnbnse informn-
tion ns n news site.
One nren thnt mnny µeoµÌe overÌook with ISPs whnt the industry cnÌÌs occouniinµ
Joio ~not the doÌÌnrs-nnd-cents kind, but rnther nn nccounting of who wns using
whnt modem or IP nddress nt n given µoint in time. This nccounting dntn cnn then
be trncked to find usnge µntterns of n µnrticuÌnr user or grouµ of users. In nddition,
when nn nbuse reµort or subµoenn is received, the ISP cnn quickÌy Ìocnte the user
in question nnd tnke nction or fuÌfiÌÌ the subµoenn request.
Many people wrongly believe they are anonymous when online. The reality is
quite the contrary. With the use of databases to track accounting information, find-
ing any given user who was online at any given time is almost trivially easy.
Some ISPs use dntnbnses ns n menns to trnck µossibÌe nttncks ngninst their equiµ-
ment. Dntnbnses nre nn efficient wny to wntch for µntterns of nttnck nnd keeµ dntn
from nn nttnck for µossibÌe future Ìitigntion or nction ngninst the nttncker.
As you wouÌd exµect, ISPs nÌso use the reµorting fentures of their dntnbnses.
Reµorts cnn quickÌy be genernted on revenue, high usnge customers, or nnything
eÌse trncked in the dntnbnse.
CriminoIogy and databases
Lnw enforcement hns been quick to ndoµt eÌectronic dntnbnses ns nn effective tooÌ
for he̵ing to cntch criminnÌs. Through identificntion dntnbnses, offender trncking,
nnd fnce recognition, Ìnw enforcement cnn efficientÌy nssembÌe vnried µieces of
informntion to nssist in investigntions.
AÌthough fingerµrinting technoÌogy is not new, the use of eÌectronic dntnbnses to
store nnd retrieve fingerµrints is n new (nnd µowerfuÌ) extension of the technique.
Other identificntion dntn cnn nÌso be gnthered nnd trncked for Ìnw enforcement ~
tnx records, µermits, nnd driver`s-Ìicense informntion cnn he̵ Ìnw enforcement find
µeoµÌe. Thnt informntion cnn ensiÌy be shnred with other Ìnw enforcement ngencies
nt sµeeds thnt weren`t imnginnbÌe |ust n generntion ngo.
The eÌectronic dntnbnse is nn idenÌ tooÌ for certnin other forms of informntion. Ior
exnmµÌe, when trncking offenders by moJus opcronJi (n µnttern thnt emerges in
Chapter 1 keIationaI Database Management
crimes), the investigntor cnn query n dntnbnse to find susµects who might fit the
µnttern. Storing nctunÌ imnges of fnces (for exnmµÌe, mug shots) in n dntnbnse cnn
he̵ investigntors find mntches to fnces. However, use of this technoÌogy in µÌnces
other thnn investigntions hns Ìed µrivncy grouµs to exµress some concerns.
Advantages of using databases
The sµeed, nccurncy, nnd thoroughness of eÌectronic dntnbnses mnke them criticnÌ
to todny`s 24}7 high-sµeed exchnnge of informntion. Lven the hnndfuÌ of exnmµÌes
in this chnµter shouÌd strongÌy suggest the ndvnntnges ~some of which nµµenr in
TnbÌe 1-1 ~of using nnd deveÌoµing nµµÌicntions for dntnbnses.
Table 1-1
Advantages of Using Databases
4dvontoge 0escriµtion
Speed Format means quick storage and retrieval of information. Users and
applications have a quick means for asynchronous reads and writes
of data.
Reporting Information can be gathered, quantified, and custom-analyzed with
greater flexibility.
Accuracy Civen careful data input, databases provide accurate and consistent
results based on their data.
Thoroughness Databases can store and report results as complete and detailed as
their holdings -at electronic speed.
Comparing 5OL ImpIementations
SQL, or Structured Query Lnngunge, is n sµecinÌized tyµe of µrogrnmming Ìnngunge
deveÌoµed to work with reÌntionnÌ dntnbnses such ns MySQL, OrncÌe, Microsoft SQL
Server, PostgreSQL, Informix, nnd others.
The SQL stnndnrd is defined by ANSI, the Americnn NntionnÌ Stnndnrds Institute in
their ISO}ILC 9O7b:1992 document. (The stnndnrd is commonÌy referred to ns ANSI
SQL-92.) Lvery reÌntionnÌ dntnbnse nµµÌies its own version of the SQL stnndnrd, mnny
enhnnce thnt stnndnrd. Stnndnrdizing the µrogrnmming Ìnngunge nÌÌows the deveÌ-
oµer to nddress the dntnbnse in much the snme wny from µÌntform to µÌntform~nnd
every mn|or µÌntform hns such µroducts written for it. TnbÌe 1-2 comµnres some
µoµuÌnr reÌntionnÌ-dntnbnse µroducts ns iÌÌustrntive exnmµÌes.
Part I Cetting 5tarted
Table 1-2
Comparison of 5OL ImpIementations
R0BM5 4dvontoges 0rowbocks
Cracle versatile, stable, and secure. Potentially high TCC.
MS SCL Server Stable and secure; Microsoft Relatively high TCC;
offers excellent support. proprietary.
PostgreSCL Up-and-coming database Has yet to be widely
with low TCC. implemented in large-scale
business use.
Informix Stable; has good support Cenerally higher TCC.
MySCL Cffers a best-case-scenario Not all available versions can
database in many ways; low offer the full range of MySCL
TCC, high stability, high security, capabilities.
and excellent support.
OrncÌe Corµorntion, , is nrgunbÌy the Ìender in enterµrise-
ÌeveÌ dntnbnse server softwnre for e-commerce. The OrncÌe dntnbnse µroduct is
wideÌy used in vnrious tyµes of Ìnrge nµµÌicntions ~incÌuding those mentioned in
the µrevious section ~nnd is µoµuÌnr ÌnrgeÌy becnuse its chnrncteristics nµµnrentÌy
hnve n minimnÌ downside:
Versatility: OrncÌe Corµorntion offers mnny e-commerce µroducts thnt integrnte
with their dntnbnses, which cnn he̵ strenmÌine the µrocess of designing, buiÌd-
ing, nnd using dntnbnse nµµÌicntions.
Stability: Administrntors reµort thnt OrncÌe dntnbnse servers rnreÌy fniÌ ~
renssuring if your nµµÌicntions require 24}7 uµtime.
Available graphical user interface: OrncÌe offers mnny GUI tooÌs for mnnng-
ing the dntnbnse server (though whether this fenture is n µÌus or minus
deµends on which ndministrntor you nsk).
Security: Versions of OrncÌe now incÌude n security tooÌkit thnt nÌÌows encryµ-
tion of sensitive dntn uiihin ihc Joiobosc. Like other RD8MS µroducts, OrncÌe
nÌso µrovides user-ÌeveÌ security within n dntnbnse to µrotect the dntn from
mnÌicious users or oµerntor errors.
Support: OrncÌe Corµorntion hns historicnÌÌy been resµonsive to customer
requests for new fentures in the dntnbnse µroduct. OrncÌe moves quickÌy to
seize new oµµortunities ns weÌÌ ~Ìistening to customers, wntching mnrket
trends, nnd mnintnining thorough onÌine documentntion through the OrncÌe
TechnoÌogy Network (see Iigure 1-1).
Chapter 1 keIationaI Database Management
Figure 1-1: The Cracle Technology Network is just one of many support offerings
for Cracle.
Cross-platform capability: PoµuÌnr versions incÌude OrncÌe on Microsoft
Windows ns weÌÌ ns Linux. OrncÌe nÌso suµµorts ANSI-92 SQL stnndnrds with
modificntions nnd enhnncements.
Potentially high Total Cost of Ownership (TCO): OrncÌe`s dntnbnse server
requires considernbÌe high-end hnrdwnre resources (such ns µrocessor sµeed
nnd RAM cnµncity) to run nt nn ncceµtnbÌe ÌeveÌ.
Microsoft 5OL 5erver
Like OrncÌe, Microsoft hns been n key µÌnyer in the dntnbnse mnrket ~though
Microsoft hns hnd to µÌny constnnt cntch-uµ in the renÌm of the Internet nnd
e-commerce. AÌthough Microsoft is the ncknowÌedged Ìender in desktoµ oµernting
systems (thnnks to its good sense of the mnrketµÌnce nnd emµhnsis on fuÌfiÌÌing
the needs of consumers), thnt ndvnntnge hns not trnnsÌnted smoothÌy to the
e-commerce mnrket.
The chnrncteristics of Microsoft SQL Server itseÌf nre consistent with its mnker`s
trnditionnÌ strengths, strntegies, nnd Ìimitntions:
Part I Cetting 5tarted
Fairly high stability: MS SQL Server offers n degree of stnbiÌity thnt is
designed to be comµntibÌe with Windows OS. However, due to numerous
security µrobÌems in thnt underÌying oµernting system, some corµornte
customers nre reÌuctnnt to invest in MS SQL Server ns n soÌution for their
dntnbnse needs. In nddition, hnving to reboot the host comµuter (Windows-
styÌe) to uµdnte the server or dntnbnse softwnre is comµÌeteÌy unncceµtnbÌe
to µotentinÌ customers who require mnximum server uµtime.
Ease of use: MS SQL Server oµerntes vin Windows-styÌe GUI, which cnn he̵
ense the Ìenrning curve nnd ndd the nµµenÌ of fnmiÌinrity for customers seek-
ing hnssÌe-free trnnsnctions.
Compliance with ANSl SQL-92: MS SQL Server not onÌy ndheres to the entry-
ÌeveÌ stnndnrd, but nÌso extends it (nrgunbÌy no Ìess thnn other reÌntionnÌ
Accessible support: SQL Server is nvniÌnbÌe directÌy from Microsoft, ns weÌÌ
ns from outside vendors. Microsoft µrovides n grent denÌ of suµµort informn-
tion on their SQL Server Web site (nnd in the Microsoft KnowÌedge 8nse) ~
sometimes too much to find exnctÌy whnt you nre Ìooking for.
High Total Cost of Ownership: Like the oµernting systems it runs on, SQL
Server is extremeÌy resource-intensive of both CPU sµeed nnd RAM cnµncity.
This nsµect of the µroduct reduces its nµµenÌ to mnny smnÌÌ businesses.
Adding to the cost is the Ìicensing ~running into thousnnds of doÌÌnrs in fees
for SQL Server itseÌf ~not counting the oµernting system or other softwnre
nnd hnrdwnre to mnke the dntnbnse work. However, thorough suµµort nnd
bncking for Microsoft µroducts mnke them worth the cost for some IT µrofes-
sionnÌs (µrovided their comµnnies cnn nfford the outÌny).
Proprietary vendor: Since MS SQL Server is not cross-µÌntform, some µoten-
tinÌ buyers nre nfrnid to imµÌement it Ìest they reÌy too much on one vendor. If
the vendor suddenÌy decides to chnrge too much for n new fenture or µntch to
the server, the comµnny might hnve to µny more thnn it µÌnnned.
A reÌntive newcomer to the RD8MS fieÌd, PostgreSQL, (
) hns quickÌy gnthered quite n foÌÌowing. PostgreSQL is n work in µrogress ~
whnt softwnre isn`t" ~but is remnrknbÌy stnbÌe for such n young n µroduct, ns n Ìist
of its chnrncteristics shows:
Compliance with SQL-92: PostgreSQL foÌÌows most of the SQL-92 stnndnrd,
nnd is nvniÌnbÌe for mnny oµernting systems ~incÌuding Windows 2OOO}NT
(through the use of sµecinÌ tooÌs) nnd MncOS X. An oµen-source µroduct,
PostgreSQL is bundÌed with mnny versions of the Linux oµernting system.
Low Total Cost of Ownership: The PostgreSQL dntnbnse-server softwnre is
nvniÌnbÌe for minimnÌ outÌny ~the softwnre is free of chnrge ~n µotentinÌ
ndvnntnge when comµnred to OrncÌe or Microsoft SQL Server.
Chapter 1 keIationaI Database Management
Support: Like MySQL, PostgreSQL offers commercinÌ suµµort through different
indeµendent consuÌting firms (though its nctunÌ documentntion is reÌntiveÌy
Relatively limited adoption: AÌthough PostgreSQL suµµorts some imµortnnt
functions of Ìnrger RD8MS µroducts ~in µnrticuÌnr, trnnsnctions ~it cnn be
sÌower thnn some of its comµetitors (incÌuding OrncÌe) when keeµing trnnsnc-
tionnÌ dntn. Sµeed mny be one renson thnt not mnny Ìnrge-scnÌe businesses
hnve chosen PostgreSQL, desµite some ndvnntnges over its more exµensive
dntnbnse brethren.
I8M`s Informix series of dntnbnse servers nre µoised to comµete for Ìnrge-scnÌe
dntnbnse nµµÌicntions. Informix is n µoµuÌnr RD8MS thnt hns the bncking of I8M, ns
is refÌected in its chnrncteristics:
Diverse product line: Informix offers n wide nrrny of dntnbnse servers deµend-
ing on the needs of the nµµÌicntion. Irom onÌine trnnsnctions to µnrnÌÌeÌ µro-
cessing to high nvniÌnbiÌity nnd more, Informix µroduces nn oµtimized server
for nenrÌy nÌÌ uses.
Cross-platform capabilities: Informix runs on n vnriety of µÌntforms nnd nÌso
offers n rnnge of tooÌs to nssist with the deveÌoµment of both bnck-end nnd
front-end dntnbnse nµµÌicntions.
Potentially high Total Cost of Ownership: Like its other commercinÌ counter-
µnrts, the TCO for Informix cnn become µrohibitive for smnÌÌ business.
Documentation and support: Documentntion for Informix is exceÌÌent ~nnd
much of it is nvniÌnbÌe free from the I8M Web site. As you wouÌd exµect, I8M
µrovides soÌid bncking of the µroduct nnd suµµort for Informix customers.
Introducing My5OL
Where does MySQL fit in with nÌÌ the other RD8MS µroducts nvniÌnbÌe" In mnny
wnys, MySQL offers n best-of-nÌÌ worÌds scennrio: It runs on mnny µÌntforms, en|oys
n Ìow TCO, nnd is stnbÌe. The documentntion for MySQL is exceÌÌent. MySQL A8 hns
n thorough Web site contnining reference mnterinÌ, ns weÌÌ ns n Ìink to mniÌing-Ìist
nrchives. MySQL A8 nÌso offers high-qunÌity suµµort for their µroducts, incÌuding n
service thnt nÌÌows MySQL deveÌoµers to Ìog in to your server to correct µrobÌems
nnd µronctiveÌy he̵ with oµtimizntion. MySQL is gnining RD8MS mnrket shnre
becnuse it offers stnbiÌity, suµµort, nnd Ìow cost.
My5OL versions and features
MySQL is nvniÌnbÌe for mnny different oµernting systems on n vnriety of comµuter
nrchitectures. MySQL currentÌy hns versions for Linux, Windows 9b}98}NT}2OOO,
Part I Cetting 5tarted
SoÌnris, Iree8SD, MncOS X, HP-UX, AIX, SCO, SCI Irix, Dec OSI, nnd 8SDi. The Linux
version runs on n rnnge of nrchitectures thnt incÌudes InteÌ Ìibc6, A̵hn, IA64,
SPARC, nnd S}89O. The nvniÌnbiÌity of cross-µÌntform versions hns enhnnced the µoµ-
uÌnrity of MySQL.
In nddition to the stnndnrd MySQL dntnbnse server, nn enhnnced version of MySQL
is nvniÌnbÌe ~MySQL-Mnx. MySQL-Mnx incÌudes the stnndnrd MySQL server, µÌus
suµµort for trnnsnction-snfe tnbÌes such ns InnoD8 or 8erkeÌey D8 (8D8). TnbÌe 1-8
shows the µÌntforms nnd the trnnsnctionnÌ tnbÌes incÌuded with MySQL-Mnx.
Table 1-3
Iransaction-5afe IabIes in My5OL-Max Versions
Plotlorm ol Version Berkeley 0B 4voiloble7 Inno0B 4voiloble7
AIX 4.3 No Yes
HP-UX 11.0 No Yes
Linux (Alpha) No Yes
Linux (Intel) Yes Yes
Linux (IA64) No Yes
Solaris (Intel) Yes Yes
Solaris (SPARC) Yes Yes
Windows 2000/NT Yes Yes
MySQL is nvniÌnbÌe ns either n binnry or n source-code downÌond, if you wnnt to ndd
n fenture to MySQL for your nµµÌicntion, you cnn downÌond the source code nnd
modify it to your Ìiking.
Downloading the source code also allows you to include support for transaction-
safe tables when you compile the code.
MySQL is covered under the GNU GenernÌ PubÌic License (GPL) nnd the GNU Lesser
GenernÌ PubÌic License (LGPL). To thnt end, most versions of MySQL require no
Ìicense or µurchnse.
The CNU CPL and LCPL are included for reference in Appendixes ß and C, respec-
tively. Additional information on licensing is in Chapter 2.
MySQL nÌso hns mnny AµµÌicntion Progrnmming Interfnces (APIs) to give the
deveÌoµer to nccess nnd shnµe the dntnbnse vin µrogrnms in vnrious Ìnngunges.
APIs nre nvniÌnbÌe for C, C--, TcÌ, Python, PHP, nnd PerÌ. Some of the most µoµuÌnr
for µrogrnmming Web interfnces nre PHP nnd PerÌ. MyOD8C mnkes MySQL OD8C-
comµÌinnt ns weÌÌ.
Chapter 1 keIationaI Database Management
5tandards and compatibiIity
MySQL foÌÌows nenrÌy the entire SQL-92 stnndnrd. As is the cnse with other RD8MS
µroducts, MySQL extends the SQL stnndnrd in distinctive wnys (though it cnn be run
in nn ANSI-onÌy mode). AÌso, ns you wouÌd exµect, if you use some of the MySQL
sµecific extensions to the stnndnrd, your dntnbnse mny no Ìonger be µortnbÌe to
nnother RD8MS shouÌd you choose to chnnge it nt n Ìnter dnte.
You cnn he̵ your MySQL system mnintnin comµntibiÌity with other dntnbnses by
encÌosing nny non-stnndnrd (MySQL-sµecific) extensions Ìike this:
Other RD8MS systems shouÌd ignore the encÌosed stntement, which snves you from
hnving to recode. MySQL simµÌy ignores the brnckets nnd µrocesses the MySQL-
sµecific stntement ns normnÌ.
AÌso, if you ndd n version number nfter the excÌnmntion mnrk, MySQL ignores the
stntement within the brnckets unlcss it foÌÌows thnt version number. Ior exnmµÌe,
consider the foÌÌowing Ìine of code:
On versions oÌder thnn 8.28.48, the stntement within the brnckets wouÌd be ignored.
TnbÌe 1-4 Ìists n substnntinÌ snmµÌe of the numerous MySQL extensions to the
SQL-92 stnndnrd.
Not all extensions listed in Table 1-4 are unique to MySCL, but their use in the
specific context mentioned in the table may be unique to MySCL (or an extension
to the standard).
Table 1-4
My5OL Extensions to 5OL-92
Extension Iyµe/oµµlicotion 0escriµtion or context
% Cperator Used as a substitute for the
Cperator Escape character. Used where an
operation would include a normally
reserved character.
Cperator Used to enclose strings.
Cperator Logical
Part I Cetting 5tarted
Table 1-4 (cont/nµed)
Extension Iyµe/oµµlicotion 0escriµtion or context
Cperator Used as (not to concatenate).
Cperator Used to set variables.
Statement extension Used with to indicate the
order for results.
Statement Used to examine a table.
Field attribute Increments a value.
Field attribute Controls case sensitivity.
Statement extension Used with for ing of bits.
Function Returns the number of bits.
Statement extension Used with for ing of bits.
Type Extensions to type.
Function Flow-control option.
Statement extension Used with to modify a
Statement Used to examine a table.
Statement extension Counts multiple items.
Statement Creates a database.
Function String function.
Statement extension Used with or . Causes
statements to wait for a free table.
Statement extension Used with to indicate the
order for results.
Statement extension Used with to delete a
column from a table.
Statement Removes a database.
Statement extension Used with to remove an
index from a table.
Statement extension Drops multiple tables.
Function String function.
Function String function.
Function Creates acceptable values.
Statement Describes joined tables.
Statement Clears MySCL caches.
Chapter 1 keIationaI Database Management
Extension Iyµe/oµµlicotion 0escriµtion or context
Function Changes the way a value is displayed.
Function Returns the number of days.
Function Control function.
Statement extension Used with command to
perform the action only if the table exists.
Statement extension Used with that only
performs action if table does not exist.
Statement extension Used with to ignore
repeat values.
Statement extension Used with to create an
Statement extension Used with to redirect output to
a file.
Statement extension Used with to create a
key column.
Function Cbtains number of last insert.
Cperator Allowed on numeric values.
Statement extension Used with to limit the number
of rows deleted.
Statement Imports data.
Statement extension Used with , , ,
and to indicate that the
operation should wait until there are no
other threads working with the table.
Function Used to create an md5 of a value.
Field type Indicates a type of column.
Cperator Extends regular expressions.
Field attribute Indicates nothing.
Statement Performs optimizations on a table to
improve performance.
Function Encrypts a string.
Function Performs a date-related function.
Function Performs a date-related function.
Cperator Extends regular expressions.
Part I Cetting 5tarted
Table 1-4 (cont/nµed)
Extension Iyµe/oµµlicotion 0escriµtion or context
Statement extension Used with to change the
Statement Changes table name.
Statement Performs repairs on a table.
Statement Instead of deleting, inserts.
Field type Sets a value.
Statement Sets an option.
Statement Lists objects.
Statement extension Used with .
Statement extension Used with to indicate the
Statement extension Used with to perform a join of
Statement extension Used with to create a
temporary table.
Field type Extensions to text type.
Function Performs a date-related function.
Statement extension Allows substring trimming.
Field attribute Indicates an attribute for a column.
Function Performs a date-related function.
Field attribute Pads a string.
My5OL-specific properties
In nddition to the extensions, fieÌd tyµes, nnd functions Ìisted in TnbÌe 1-4, MySQL
hns the foÌÌowing µroµerties thnt nre not µnrt of the SQL-92 stnndnrd:
When n dntnbnse is crented, MySQL crentes n directory within the MySQL
directory structure to hoÌd dntnbnse fiÌes.
When the oµernting system hns n cnse-sensitive fiÌe system (ns does Linux),
MySQL dntnbnse nnd tnbÌe nnmes nre cnse-sensitive.
Ob|ects such ns the nnmes of dntnbnses, tnbÌes, indexes, coÌumns, or nÌinses
mny begin with~but not comµÌeteÌy consist of ~digits.
Chapter 1 keIationaI Database Management
To move, coµy, or deÌete dntnbnses, you cnn use oµernting-system functions
such ns ( ) or ( ).
To nccess ob|ects in other dntnbnses, MySQL uses the foÌÌowing syntnx:
String comµnrisons nre not cnse-sensitive. This behnvior cnn be chnnged with
the stntement extension.
MySQL ennbÌes you to use more thnn one , , , or
stntement with nn stntement.
Comµnrison oµerntors mny be used to the Ìeft of the cÌnuse within n
MySQL suµµorts the nÌinsing of mnny commnnds to nssist users who nre
fnmiÌinr with other SQL imµÌementntions.
The functions nnd cnn be used with more thnn one nrgument.
When using n grouµ by function, you don`t need to nnme nÌÌ seÌected coÌumns.
MySQL does offer trnnsnctionnÌ tnbÌes, most other enterµrise-ÌeveÌ dntnbnse
functionnÌity (such ns views, cursors, foreign keys, nnd the Ìike) is either in testing
or µÌnnned for n nenr-future reÌense of MySQL. TnbÌe 1-b iÌÌustrntes some of these
fentures nnd their current deveÌoµmentnÌ stntus with MySQL.
Table 1-5
My5OL Enterprise-LeveI Database Features
0otobose leoture 5uµµorted in (extont or exµected version)
Subselects 4.1
Foreign keys Support (4.0)
views 4.2
Stored procedures 4.1
Unions Supported (4.0)
Full join Supported
Triggers 4.1
Constraints 4.1
Cursors 4.1 or later
Part I Cetting 5tarted
What My5OL Does ßest
To nssist the render, I`ve Ìisted some tnsks thnt MySQL does esµecinÌÌy weÌÌ:
Web applications: Web nµµÌicntions tyµicnÌÌy fenture mnny rends nnd few
writes. MySQL is fnst nnd cnn meet the demnnds of Internet sµeed. In my
exµerience, MySQL hns µroven time nnd ngnin thnt it outµerforms other
RD8MS µroducts in Web nµµÌicntions.
Enterprise-level applications: MySQL offers suµµort directÌy through the
µnrent comµnny, MySQL A8. MySQL`s fenture set incÌudes |ust nbout every-
thing thnt nn enterµrise-ÌeveÌ nµµÌicntion wouÌd need. Refer bnck to TnbÌe 1-4
for more detniÌs.
Open-source support: MySQL A8 is resµonsive to requests for fentures ns
weÌÌ. MySQL is oµen-source, everyone is weÌcome to downÌond nnd extend the
code to meet his or her needs.
Low overhead: MySQL runs comfortnbÌy for mnny nµµÌicntions on nn InteÌ
Pentium-cÌnss comµuter with 82 M8 of RAM or Ìess. I wouÌdn`t rccommcnJ
running nn enterµrise-ÌeveÌ MySQL imµÌementntion on such n system, but
consider the utter futiÌity of trying to run n Web nµµÌicntion on Internet
Informntion Server with Microsoft SQL Server thnt runs under Windows 2OOO
on n Pentium-cÌnss comµuter with 82 M8 of RAM.
Available large table size: MySQL tnbÌes cnn grow Ìnrge, though they do
sometimes encounter fiÌe-size Ìimitntions of the host oµernting system. Some
nrchitectures, however, cnn nccommodnte uµ to 8 ternbytes (T8) µer tnbÌe
using MySQL.
Stability: AÌÌ softwnre is in deveÌoµment. Some fentures in MySQL nre newer
thnn others, mnking them µossibÌy Ìess stnbÌe thnn others. TnbÌe 1-6 shows
some of the fentures within MySQL nnd their stnbiÌity ÌeveÌ.
Table 1-6
My5OL 5tabiIity
Feoture 5tobility level
Standard table types Stable
Transactional Tables ßecoming more stable
ßasic SCL Functionality Stable
Client Software Stable
C API Stable
Perl and PHP APIs Stable
Replication Stable, though always adding features
Chapter 1 keIationaI Database Management
MySQL comµnres with ~nnd bents ~some of its commercinÌ counterµnrts in mnny
nrens. PnrticuÌnrÌy in µerformnnce, scnÌnbiÌity, nnd stnbiÌity, MySQL cnn µerform ns
good or better thnn its comµetitors. TnbÌe 1-7 comµnres some µoµuÌnr fentures in
MySQL with other RD8MS. As you cnn see, MySQL meets or bents the others with
two trnnsnctionnÌ tnbÌe tyµes to choose from, mnny deveÌoµment Ìnngunges, n Ìow
TotnÌ Cost of Ownershiµ, nnd other fentures.
Table 1-7
My5OL Comparison to other kDßM5 Products
Feoture My5DL Drocle M5 5DL 5erver Postgre5DL
Transactional Yes Yes Yes Yes
Cpen-source Yes No No Yes
TCC Low High High Low
Development languages Many Many Fewer Many
Enterprise user base Yes Yes Yes No
Company support Yes Yes Yes No!
Cross-platform Yes Yes No Yes
MySQL hns recentÌy ndded GrnµhicnÌ User Interfnce (GUI) tooÌs for dntnbnse
What My5OL Can't Do¬Ouite Yet
MySQL is n stnbÌe nnd extensive RD8MS, but there nre simµÌy some things thnt
MySQL cnnnot do or nre unsuµµorted nt this time.
Foreign keys: A forciµn hcy is n vnÌue thnt reÌntes to (nnd reÌies on) the Primnry
key in nnother tnbÌe. This is n µoµuÌnr fenture, used frequentÌy in OrncÌe nnd
other RD8MS µroducts. MySQL stnrted suµµort for foreign keys in version 4.O
nnd wiÌÌ enhnnce thnt suµµort in Ìnter versions. In nddition, Unions nre now
suµµorted in MySQL.
Views: This µoµuÌnr method for obtnining dntn from the dntnbnse, n µÌnnned
fenture for MySQL, mny hnve been imµÌemented by the time you rend this.
R-Tree and other extensible index types: Suµµort for these µowerfuÌ fentures
wiÌÌ be incÌuded in n Ìnter version of MySQL.
Inherited tables are not planned for any version of MySCL. Note
Part I Cetting 5tarted
Subselects: This tyµe of stntement (such ns those using the cÌnuse) is not
suµµorted in MySQL (though it mny be in the nenr future). Ior exnmµÌe, the
foÌÌowing subseÌect is not vnÌid MySQL syntnx:
Though subselects are not yet supported, you can many times get around the
missing function by using joins or other commands. If I rewrite the earlier invalid
statement as a valid statement in MySCL, it looks like this:
In the event that rewriting a subselect doesn't work, I recommend using a front-
end application written in Perl (or in your favorite language) to issue multiple
statements to the database.
Stored procedures or triggers: MySQL doesn`t suµµort either one yet,
nÌthough the MySQL deveÌoµment tenm is working hnrd to bring triggers to
MySQL for version 4.1.
MySCL current and planned features change rapidly. I recommend checking with
MySCL's Web site for the status of any feature necessary for your application.
ShouÌd you nbsoÌuteÌy need n function not nvniÌnbÌe in MySQL, Ìook into suµµort
contrncts with MySQL A8. Often the deveÌoµers nre wiÌÌing to µrioritize n mn|or
fenture ~or even customize n version of MySQL |ust for you!
Dntnbnses nre wideÌy used in mnny nµµÌicntions to trnck customer informntion,
µreferences, nnd history. Dntnbnses offer sµeed, nccurncy, reµorting, nnd thorough-
ness ns ndvnntnges.
There nre mnny imµÌementntions of ReÌntionnÌ Dntnbnse Mnnngement Systems
incÌuding OrncÌe, Microsoft SQL Server, PostgreSQL, nnd Informix.
Lnch RD8MS offers ndvnntnges nnd disndvnntnges nnd shnres mnny common
MySQL is nn oµen source RD8MS thnt offers mnny ndvnntnges over other
RD8MS with few disndvnntnges.
MySQL suµµorts the SQL-92 stnndnrd nenrÌy comµÌeteÌy nnd extends the
stnndnrd with other fentures.
Preparing for
hnµter 1 iÌÌustrnted some bnsics of n ReÌntionnÌ Dntnbnse
Mnnngement System (RD8MS), ns weÌÌ ns the stnndnrds
thnt MySQL foÌÌows nnd extensions to those stnndnrds. 8efore
you get your hnnds dirty instnÌÌing MySQL, it wouÌd be wise to
know which version you`re going to instnÌÌ. Sounds ensy, right"
1ust downÌond MySQL (or use the CD incÌuded with this book)
nnd go. UnfortunnteÌy ~nnd fortunnteÌy~it`s not renÌÌy thnt
MySQL incÌudes mnny vnrinnts of the server, ench oµtimized
for n different scennrio. You cnn nÌso downÌond the source
code nnd customize MySQL further for your nµµÌicntion.
This chnµter µresents some issues to think nbout before you
instnÌÌ nny version of MySQL. In nddition, it Ìists nnd describes
those versions so you cnn decide which one is right for you.
Prerequisites for My5OL
You shouÌd nnswer some essentinÌ questions before instnÌÌing
MySQL. This section reviews some of those questions, nÌong
with common requirements for n MySQL instnÌÌntion.
Question: WiÌÌ you be required to µurchnse n Ìicense for
MySQL server is covered under the GNU GenernÌ PubÌic License
(GPL). In genernÌ, you shouÌdn`t hnve to µurchnse n Ìicense
from MySQL A8 for most uses. This incÌudes internnÌ uses ns
weÌÌ ns commercinÌ Web or other nµµÌicntions. MySQL A8 nsks
thnt you µurchnse n suµµort contrnct or some other ÌeveÌ of
suµµort to nssist them in continuing to deveÌoµ MySQL.
C H A P I E k
ln Ihis Chopler
Checklng syslem
prerequlslles lor
Cblolnlng MySCL
Selecllng o MySCL
Part I Cetting 5tarted
However, if you shouÌd downÌond the source code nnd mnke n new nµµÌicntion
using nÌÌ or µnrt of the MySQL code bnse ~nnd you wnnt to mnrket thnt nµµÌicntion
or mnke it µroµrietnry ~you wouÌd need n commercinÌ Ìicense to µrevent your
code from becoming GPL'J (thnt is, nutomnticnÌÌy sub|ect to the terms of the GNU
GenernÌ PubÌic License). MySQL A8 offers n commercinÌ Ìicense thnt nÌÌows you to
use nÌÌ or µnrt of the MySQL code bnse within your nµµÌicntion.
AdditionnÌÌy, if you distribute your own version of MySQL, you must incÌude the
source code, if you hnve nn nµµÌicntion thnt works onÌy with MySQL nnd you
choose to distribute MySQL with thnt nµµÌicntion, you wouÌd need to µurchnse n
commercinÌ Ìicense. Other situntions nÌso cnÌÌ for n Ìicense, nnd Ìicensing require-
ments frequentÌy chnnge. I recommend checking with MySQL`s Web site,
, for more informntion.
License fees nre very rensonnbÌe for MySQL. At the time of writing, n MySQL server
Ìicense is roughÌy $2OO.OO, deµending on the currency-conversion rnte (from Luros
to Americnn doÌÌnrs).
Some older versions of MySCL were covered under a stricter license. This is true
for distribution of MySCL with programs or derivations based on the MySCL code
for those older versions. In the event that you have an older version of MySCL,
make sure you obtain the MySCL Free Public License.
Question: WiÌÌ you require suµµort directÌy from MySQL A8 for your instnÌÌntion"
MySQL A8 offers tiered suµµort, with tiered µricing to mntch. 8ecnuse µrices
chnnge, I won`t incÌude costs here. However, I think it wouÌd be usefuÌ to Ìook nt the
different ÌeveÌs of suµµort nvniÌnbÌe, though there mny be more or fewer oµtions
nvniÌnbÌe when you rend this.
E-mail support: Ior n fÌnt fee µer yenr, you cnn obtnin suµµort vin e-mniÌ for
MySQL. Much of the suµµort cnn be obtnined on MySQL mniÌing Ìists, but this
oµtion does give you the nbiÌity to reµort µrobÌems nnd nsk questions vin n
sµecinÌ suµµort e-mniÌ nddress.
Priority e-mail support: A ÌeveÌ nbove the bnsic e-mniÌ suµµort, this oµtion
gives your e-mniÌ µriority over others. AdditionnÌÌy, requests for fentures nnd
ndditions to MySQL nre given more considerntion.
Login support: This oµtion gives you the benefits of the extended e-mniÌ
suµµort nÌong with the nbiÌity to hnve n MySQL deveÌoµer nttemµt to nctunÌÌy
connect to your dntnbnse server to troubÌeshoot nnd fix µrobÌems. With Login
suµµort, your suggestions nre given n high ÌeveÌ of considerntion nnd mnny
cnn even be imµÌemented quickÌy. You cnn nÌso contnct MySQL deveÌoµers vin
teÌeµhone. MySQL deveÌoµers wiÌÌ nÌso give you, when µossibÌe, suggestions
on imµroving your dntnbnse imµÌementntion nnd oµtimizntion suggestions
ns weÌÌ.
Chapter 2 Preparing for InstaIIation
Priority login support: This oµtion gives you nÌÌ the benefits of the Ìower-tiered
ÌeveÌs ns weÌÌ ns the nbiÌity to hnve your own extensions ndded to MySQL nnd
custom binnry editions of MySQL crented for you. In nddition, with some other
costs, n MySQL deveÌoµer wiÌÌ visit your site to consuÌt nnd offer suggestions
for imµrovements.
Telephone support: Like the others, this oµtion incÌudes the Ìower-tiered
ÌeveÌs nnd nÌso gives you nccess to n Web site thnt Ìists current on-cnÌÌ µhone
numbers for MySQL deveÌoµers (in the event of nn emergency).
If you are using transactional table types such as or , an additional fee
is charged, based on the level of support you purchase.
Operating system and architecture
Question: Which one of the mnny µÌntforms do you run MySQL on"
MySQL runs on different µÌntforms. Irom AIX to Windows, nnd mnny µoints in
between, MySQL is truÌy cross µÌntform. TnbÌe 2-1 shows the oµernting systems nnd
µÌntforms thnt MySQL is nvniÌnbÌe for. The nrchitecture nnd µÌntform you choose
couÌd determine how Ìnrge dntnbnse ob|ects such ns tnbÌes cnn be.
Table 2-1
My5OL Operating 5ystems and Architecture
D5/4rchitecture 5uµµort 4voiloble7
AIX 4.x Yes
Amiga Yes
ßeCS Soon
ßSDi 2.x-4.x Yes
DEC UNIX 4.x Yes
FreeßSD 2.x-4.x Yes
HP-UX 10.20-11.x Yes
Linux (Kernel 2.0 or later) Yes
MacCS X Yes
NetßSD 1.3-1.4 (Intel) Yes
NetßSD 1.3 (Alpha) Yes
CpenßSD Yes
CS/2 Warp Yes
Part I Cetting 5tarted
Table 2-1 (cont/nµed)
D5/4rchitecture 5uµµort 4voiloble7
SCC CpenServer Yes
SCC Unixware 7.0.1 Yes
SCI Irix 6.x Yes
Solaris 2.5 or higher Yes
SunCS 4.x Yes
Tru64 UNIX Yes
Windows 95, 98, NT, 2000 Yes
Some versions of MySCL for some operating systems require additional tools or
components. Please consult MySCL's Web site for more information.
MySQL is nÌso more wideÌy suµµorted on certnin µÌntforms. MySQL in Linux is n
µoµuÌnr nµµÌicntion nnd you hnve mnny nvenues to µursue for nssistnnce shouÌd
you need it. MySQL on other oµernting systems mny not be so common nnd thus it
might be more difficuÌt to obtnin suµµort.
MySQL runs best on x86 Linux µÌntforms simµÌy becnuse thnt hns historicnÌÌy been
where the most deveÌoµment nnd testing hns been done. Other UNIX-vnrinnt oµernt-
ing systems Ìike SoÌnris or Iree8SD nÌso hnve gone through extensive testing. This
is not to sny thnt MySQL is unstnbÌe on nny other µÌntform.
Aside from the oµernting system itseÌf, nnother essentinÌ choice to mnke (nssuming
thnt cost is no obstncÌe) is whether to use more thnn one µrocessor. MySQL cnn
tnke ndvnntnge of Symmetric MuÌti-Processing (SMP) ~n cnµnbiÌity thnt drnmnti-
cnÌÌy increnses µrocessing sµeed by using muÌtiµÌe µrocessors ~but the version
you downÌond mny or mny not hnve suµµort for SMP. Check before you instnÌÌ.
Question: Whnt nµµÌicntion or nµµÌicntions do you use to deveÌoµ n MySQL
MySQL incÌudes or hns nvniÌnbÌe for downÌond mnny AµµÌicntion Progrnmming
Interfnces (APIs). Ior our µurµoses, nn API defines how n µrogrnm connects to the
Chapter 2 Preparing for InstaIIation
dntnbnse. Once connected, the API defines the oµerntions thnt cnn be µerformed.
When you cÌick n senrch tooÌ nt nn onÌine store, mnny times you nre using nn API on
the bnckend nnd do not even know it. The API is used in n µrogrnm, such ns n PHP
scriµt, to connect to the dntnbnse nnd run your senrch.
Knowing which APIs you`ÌÌ need couÌd he̵ you determine which µÌntform to use
with MySQL. The foÌÌowing APIs nre nvniÌnbÌe for MySQL:
The C API hns been deveÌoµed the most. This is becnuse MySQL is written in C nnd
the deveÌoµers themseÌves frequentÌy use the C API. Ior Web nµµÌicntions nnd
most dntnbnse-connectivity nµµÌicntions, you use nnother API (such ns PerÌ, PHP,
or OD8C).
The Perl, PHP, and CDßC APIs are discussed in Part Iv of this book.
PerÌ is usunÌÌy incÌuded with Linux, so if you exµect to be using MySQL nnd
PerÌ, you shouÌd give serious considerntion to Linux ns your µÌntform. PerÌ nÌso
runs on other µÌntforms ns weÌÌ, incÌuding Windows, through the use of ndditionnÌ
Ior OD8C suµµort to connect MySQL to nnother nµµÌicntion, you wiÌÌ µrobnbÌy
wnnt to use MySQL in Windows. MySQL offers the MyOD8C API to connect n
Windows cÌient to MySQL. MyOD8C wiÌÌ nÌso work under UNIX vnrinnts with the use
of nn ndditionnÌ tooÌ. Iigure 2-1 shows how nn OD8C connection Ìooks when you set
it uµ by using MyOD8C in Windows.
Part I Cetting 5tarted
Figure 2-1: The MyCDßC connector includes
many options (most covered in a later chapter).
Existing data
Question: WiÌÌ you be imµorting dntn from nnother dntnbnse"
Though not renÌÌy n µrerequisite to instnÌÌing MySQL, determining whnt, if nny, dntn
wiÌÌ be imµorted from other nµµÌicntions or dntnbnses is usefuÌ to tnke into
nccount. You cnn then exµort thnt dntn into n formnt MySQL cnn imµort ~or you
cnn downÌond n tooÌ to nssist with the exµort-nnd-imµort µrocess.
MySQL suµµorts Ìonding dntn from deÌimited text fiÌes ~for exnmµÌe, those con-
tnining commn-seµnrnted vnÌues (CSV) ~nnd mnny µrogrnms cnn exµort dntn into
deÌimited vnÌues, mnking it ensy to Ìond dntn into MySQL. If you nre migrnting
between versions of MySQL, you hnve n utiÌity cnÌÌed thnt cnn quickÌy
dumµ nÌÌ the contents of nn entire dntnbnse (or even muÌtiµÌe dntnbnses) nnd then
Ìond thnt informntion bnck into MySQL ~where it nutomnticnÌÌy crentes the tnbÌe
structure ns weÌÌ! Iigure 2-2 shows snmµÌe outµut from n oµerntion.
On the MySQL Web site you hnve tooÌs for converting from other nµµÌicntions nnd
dntnbnses, though MySQL A8 does not directÌy suµµort most of those tooÌs. In fnct,
most were not written by the mnin MySQL deveÌoµment tenm, but by other deveÌoµ-
ers nround the worÌd. Such is the benuty of Oµen Source! Of course, nny softwnre ~
even (nnd sometimes esµecinÌÌy) thnt µroduced by the biggest comµnnies ~cnn
hnve bugs, nnd the MySQL tooÌs nre no exceµtion. You shouÌd nÌwnys hnve extrn
coµies of your dntn on hnnd in cnse something goes wrong (yet nnother renson to
µerform reguÌnr bnckuµs).
Chapter 2 Preparing for InstaIIation
Figure 2-2: The mysqldump utility makes migrating or upgrading
MySCL easy.
TnbÌe 2-2 shows some µoµuÌnr conversion tooÌs.
Some conversion and import tools are examined in Chapter 10.
Table 2-2
Conversion IooIs for My5OL
Driginol µrogrom Iool nome 0escriµtion ol conversion
Microsoft Access Access to MySCL From Access to MySCL
ExportSCL Improved tool that replaces "Access to
MyAccess Work with MySCL within Access
Microsoft Excel From Excel to MySCL
FoxPro From .dbf files to MySCL
mSCL From mSCL to MySCL
Cracle From Cracle to MySCL
Microsoft SCL Server From SCL Server to MySCL
Some tools have similar names, may change names, be unavailable, broken, or
otherwise problematic. Check the MySCL Web site for the latest availability.
If you nre µorting from OrncÌe to MySQL nnd hnve nµµÌicntions currentÌy in OrncÌe,
chnnces nre you`ÌÌ hnve to rewrite some of those nµµÌicntions. AÌthough MySQL
strives to µrovide the snme functionnÌity ns OrncÌe nnd nt Ìenst µrovide the snme
syntnx, not nÌÌ queries wiÌÌ work the snme between the two RD8MS. A Ìine-by-Ìine
Part I Cetting 5tarted
exnminntion of nµµÌicntion code is the onÌy wny to ensure thnt the roÌÌout of MySQL
wiÌÌ go smoothÌy.
If you wnnt to get dntn oui of MySQL, the µrocess is much ensier. MySQL exµorts
into common fiÌe tyµes thnt mnny other RD8MS nnd nµµÌicntions cnn recognize. If
Microsoft Access is the destinntion, you hnve n comµnnion µrogrnm to the
LxµortSQL µrogrnm thnt nÌÌows dntn to be imµorted into Access through OD8C.
Exporting from MySCL is covered in Chapter 10.
DefauIt Ianguage and character set
Question: Whnt defnuÌt Ìnngunge nnd chnrncter set shouÌd I choose for my instnÌÌn-
tion of MySQL"
The defnuÌt Ìnngunge nnd chnrncter set you choose for the MySQL server wiÌÌ deter-
mine things Ìike sorting nnd grouµing order for seÌect stntements, error messnge
Ìnngunge, nnd nÌÌownbÌe chnrncters. The MySQL binnry versions come µrecomµiÌed
with the Lntin1 chnrncter set by defnuÌt. This chnrncter set is ncceµtnbÌe for sorting
nnd grouµing in the United Stntes nnd Western Luroµe.
If you require ndditionnÌ chnrncter sets, comµiÌe MySQL from source code with the
or oµtion. In nddition, you`ÌÌ hnve to
stnrt the server with n commnnd-Ìine oµtion of
MySQL cnn µrint error messnges in mnny different Ìnngunges. To mnke MySQL do
so, use the syntnx when you stnrt the server.
ßy default, language names are displayed in lowercase and located in the
Twenty Ìnngunges nre nvniÌnbÌe to MySQL. In n̵hnbeticnÌ order, they nre Czech,
Dnnish, Dutch, LngÌish (defnuÌt), Lstoninn, Irench, Germnn, Greek, Hungnrinn,
ItnÌinn, 1nµnnese, Korenn, Norweginn, PoÌish, Portuguese, Romnninn, Russinn,
SÌovnk, Sµnnish, nnd Swedish.
With some languages (especially those using non-Western alphabets), you have to
load a different default character set.
Question: How do you mnnnge the server nnd how do cÌients connect to the
Connection nnd mnnngement nre two nsµects of the snme question. MySQL offers n
few different methods for mnnngement of the server. The most common is vin the
MySQL Commnnd-Line Interfnce (CLI). Another common method for mnnngement is
Chapter 2 Preparing for InstaIIation
through n tooÌ cnÌÌed PHPMyAdmin thnt runs vin n Web interfnce with PHP. MySQL
A8 nÌso hns n GrnµhicnÌ User Interfnce (GUI) mnnngement nnd cÌient interfnce cnÌÌed
MySQLGUI, see Iigure 2-8.
Figure 2-3: MySCLCUI is a new application for working with MySCL.
One of the simµÌest wnys to mnnnge nnd work with MySQL is vin the MySQL CLI.
Using the MySQL CLI or the commnnd from the commnnd Ìine, you cnn inter-
nct with the server to crente nnd nÌter tnbÌes, run queries, dingnose the server, nnd
much more. See Iigure 2-4 for nn exnmµÌe of the MySQL CLI in nction.
Figure 2-4: The MySCL CLI is the traditional method for working
with MySCL.
The MySCL CLI is discussed in greater detail throughout the book and in Chapter 8.
Part I Cetting 5tarted
If you nre hnving users connect to the MySQL server vin the CLI or other tooÌs, you
wiÌÌ hnve to instnÌÌ those tooÌs on the cÌient comµuters. In nddition, you must grnnt
nccess for those users so they cnn connect nnd work with the MySQL server.
Where to Obtain My5OL
Question: Where cnn I get MySQL, nnd do µnrticuÌnr sources offer ndvnntnges"
8y fnr the most µoµuÌnr method for obtnining n coµy of MySQL is vin the MySQL A8
Web site nt . Irom thnt site, you cnn get the version of
MySQL thnt you need for your µnrticuÌnr instnÌÌntion, ns weÌÌ ns obtnin other tooÌs
reÌnted to MySQL. You hnve geogrnµhicnÌÌy disµersed Mirror sites Ìisted so thnt you
cnn downÌond from the nenrest site.
Another wny to obtnin MySQL is on CD-ROM with vnrious Linux reÌenses. AÌso,
some Linux versions, notnbÌy Debinn Linux, nÌÌow you to downÌond MySQL vin their
grent or µncknge tooÌs.
In nddition, n comµnny cnÌÌed NuSµhere hns its own version of MySQL nvniÌnbÌe.
Thnt reÌense, obtninnbÌe directÌy from NuSµhere, nnd is covered in more deµth in
Chnµter 2O.
Overview of My5OL Versions
Question: Which version of MySQL is nµµroµrinte for my dntnbnse"
Aside from the oµernting system nnd µÌntform for MySQL, different versions nvniÌ-
nbÌe for downÌond. Choosing the right version cnn mnke the difference between n
successfuÌ nnd nn unsuccessfuÌ instnÌÌntion.
My5OL numbering scheme
MySQL uses n three-digit numbering scheme for versions, for exnmµÌe, 4.OO.OO. The
first number indicntes the filc formoi used. Therefore, bewnre if you nre nttemµting
to uµgrnde from n 8.xx.xx version to n 4.xx.xx version, the fiÌe formnt is different.
The second number is known ns the rclcosc lcccl. MySQL usunÌÌy hns two different
reÌense-ÌeveÌ numbers nvniÌnbÌe nt nny one time, n sioblc version nnd n Jccclopmcni
version. If you use n deveÌoµment brnnch, it mny be unstnbÌe. The finnÌ number is
the nctunÌ reÌense number nnd contnins bug fixes nnd usunÌÌy some imµrovements
over the µrevious reÌense.
ßinary versions of My5OL
In genernÌ, it`s good µrnctice to downÌond nnd instnÌÌ the binnry version of MySQL.
This crentes n stnndnrd instnÌÌntion thnt`s ensier to suµµort in the Ìong run.
Chapter 2 Preparing for InstaIIation
Ior Linux, n binnry version of MySQL is nvniÌnbÌe nnd it works on most versions of
the oµernting system. I hesitnte to sny thnt MySQL works on oll versions of Linux,
too mnny idiosyncrntic versions of Linux exist for thnt to be ÌikeÌy. I feeÌ comfort-
nbÌe snying thnt the binnry versions work on mosi versions of Linux, esµecinÌÌy the
µoµuÌnr ones.
Linux binnry versions come comµressed, nnd nre mennt to be uncomµressed right
into the foÌder where they nre to be instnÌÌed.
If you nre working with n version of Linux thnt suµµorts the Red Hnt Pncknge
Mnnnger (RPM) formnt, then you cnn use n coµy of MySQL with the extension.
The RPM versions shouÌd work on Linux OSs thnt suµµort RPM nnd . TnbÌe
2-8 covers the different RPM-bnsed versions of MySQL.
Table 2-3
My5OL kPM ßinary Versions
Version nome 0escriµtion
The main MySCL server installation.
The MySCL client only. Used to connect to
a MySCL server located on another
A suite of testing and benchmarking tools
for MySCL.
The libraries and include files. This is
needed if you want to use APIs such as
Perl or PHP with MySCL.
Client libraries.
Source code that contains everything
listed above.
You cnn instnÌÌ individunÌ µncknges thnt hnve onÌy the µortions of MySQL needed
for your work. If you need onÌy the MySQL CLI cÌient, for exnmµÌe, you don`t hnve to
instnÌÌ n fuÌÌ server on your comµuter.
Installation of MySCL in Linux is covered in Chapter 3.
Aside from the RPM binnry versions of MySQL, different binnry µncknges nvniÌnbÌe
for the different µÌntforms nnd oµernting systems. (Refer to TnbÌe 2-1 for n Ìist of
suµµorted µÌntforms nnd oµernting systems.) Ior the most µnrt, you hnve binnry
µncknges nÌrendy nvniÌnbÌe.
Part I Cetting 5tarted
5ource-code versions of My5OL
If you wnnt to comµiÌe MySQL for other µÌntforms (such ns A̵hn or SPARC), or if
no binnry µncknge is nvniÌnbÌe for your oµernting system, you cnn downÌond the
source code for MySQL. The source code is nvniÌnbÌe in nn RPM or in }
formnt (for UNIX vnrinnts) or ziµµed source code for Windows. TnbÌe 2-4 shows the
different source-code versions of MySQL.
Table 2-4
My5OL 5ource Versions
Version nome 0escriµtion
Ceneral UNIX-variant source code to compile MySCL.
Source-code RPM that contains everything listed in
this section of the book.
Source code to compile under Windows.
DownÌonding n source-code version wiÌÌ nÌÌow you to customize the MySQL server
instnÌÌntion much more thnn you cnn with n binnry version. You cnn tniÌor the
server softwnre to fit your needs nnd even edit nnd chnnge the source code itseÌf.
Oµtions Ìike debugging, RAID (Redundnnt Arrny of Inexµensive Disks), or incÌuding
|ust one of the two trnnsnctionnÌ tnbÌe tyµes cnn be nccomµÌished by comµiÌing the
source code. In nddition, if you ever hnve to rewrite n µortion of the code or µntch n
µortion of the code, hnving the source code is the onÌy oµtion.
Chapter 3 covers installation from source code and from binary packages.
My5OL for Windows
MySQL with Windows in binnry version runs on Windows 9b, 98, Me, NT, nnd 2OOO.
The binnry version incÌudes the reguÌnr MySQL server ns weÌÌ ns the MySQL-MAX
server thnt incÌudes trnnsnctionnÌ tnbÌes. If your work requires the server to
suµµort trnnsnctionnÌ tnbÌes, the commnnd Ìine thnt stnrts MySQL is different.
Therefore, if you don`t need trnnsnctionnÌ-tnbÌe suµµort, I recommend stnying with
the normnÌ MySQL server, it uses fewer resources. TnbÌe 2-b shows the MySQL exe-
cutnbÌes for Windows.
Not all executables will run on Windows 9x, Me, or XP. Note
Chapter 2 Preparing for InstaIIation
Table 2-5
My5OL Windows ExecutabIes
Nome 0escriµtion
A binary installation specifically for NT/2000. Includes support for
named pipes.
An optimized binary version with no transactional table support.
ßinary version that includes debugging, memory allocation,
transactional table types, and symbolic links.
ßinary version that includes transactional tables and symbolic
links. Note that no named pipe support is included in this version.
This binary version also includes support for named pipes as well
as everything included in the mysqld-max version.
8y defnuÌt, when you instnÌÌ MySQL on Windows 2OOO, the mysqÌ-nt version wiÌÌ
stnrt. If you wnnt to choose n different version, you cnn set the nµµroµrinte vnÌue in
the fiÌe (which resides in the directory). AÌternntiveÌy, you hnve n
GUI ndmin tooÌ cnÌÌed WinMySQLAdmin thnt you cnn use to chnnge the server
executnbÌe ensiÌy. Iigure 2-b shows WinMySQLAdmin in nction.
Figure 2-5: WinMySCLAdmin allows changing of the MySCL server executable as
well as many other options.
Part I Cetting 5tarted
WinMySCLAdmin is covered in greater detail in Chapter 3.
You hnve mnny oµtions, even within n µnrticuÌnr oµernting system, for choosing the
version of MySQL you`d Ìike to run. Know whnt you need before you nctunÌÌy instnÌÌ
MySQL ~it snves n Ìot of time nnd hendnches in the future.
My5OL for Mac O5 X
MySQL A8 nÌso µroduces n version of the server for Mnc OS X. MySQL is incÌuded
with Mnc OS X Server or cnn be downÌonded through the Web site.
MySQL for Mnc is nvniÌnbÌe ns source code onÌy. At this time no binnry versions of
MySQL nre nvniÌnbÌe for Mnc OS X.
Chapter 5 describes installation of MySCL on a Mac CS X system.
You hnve severnÌ questions to consider when instnÌÌing MySQL incÌuding Ìicensing,
suµµort, nnd oµernting system.
MySQL ennbÌes you to use mnny chnrncter sets nnd defnuÌt Ìnngunges.
MySQL cnn imµort mnny different vnrieties of existing dntn, third-µnrty tooÌs
nre nÌso nvniÌnbÌe to nssist with dntn imµort.
MySQL hns tooÌs such ns the commnnd-Ìine interfnce nnd MySQLGUI to
mnnnge nnd work with your dntn nnd the dntnbnse server.
MySQL hns versions nvniÌnbÌe for mnny oµernting systems nnd nrchitectures,
the most µoµuÌnr of which nre Linux nnd Windows.
nny µeoµÌe (incÌuding myseÌf) skiµ the first couµÌe of
chnµters in n book to get to the henrt of the sub|ect
mntter. If you`re one of those µeoµÌe, weÌcome! I encournge
you to review the exquisite µrose contnined in the first two
chnµters. Not onÌy did I work hnrd to bring these chnµters to
you, they nctunÌÌy contnin informntion you might find usefuÌ.
At the very Ìenst, skim the contents of Chnµter 2, it contnins
informntion thnt wiÌÌ he̵ you decide which version of MySQL
you shouÌd instnÌÌ for your µnrticuÌnr needs.
Ior those of you who hnve been with me throughout, thnnk
you. I`ÌÌ now get into some hnnds-on instnÌÌntion tnsks. This
chnµter concentrntes soÌeÌy on the Linux oµernting system. If
you wiÌÌ be instnÌÌing MySQL on nnother oµernting system,
this chnµter µrobnbÌy isn`t for you.
Common ßinary, kPM, and 5ource
My5OL InstaIIation Iasks
RegnrdÌess of the method you choose for instnÌÌntion (or the
version of Linux you hnve), some tnsks or oµtions nre common
to nÌÌ of them. Rnther thnn cover those snme oµtions ench
time, I`ÌÌ cover them here.
My5OL server startup and shutdown
If you nre running n System V~bnsed Linux version such ns
Red Hnt nnd you wnnt the MySQL server to stnrt whenever
the server is rebooted, you shouÌd coµy the fiÌe
to the
directory on your server. Then mnke the symboÌic
Ìinks to the directories. AÌternntiveÌy, you cnn use the
commnnd to ndd the scriµt nuto-
mnticnÌÌy, ns shown in Iigure 8-1.
C H A P I E k
ln Ihis Chopler
Llsllng losks lhol
blnory, RPM, ond
lnslollollon hove ln
lnslolllng MySCL
lnslolllng MySCL
lnslolllng MySCL
Part I Cetting 5tarted
Figure 3-1: The chkconfig command can be used to configure the
mysql.server script for automatic startup and shutdown of the
MySCL server.
If you nre running n 8SD-styÌe Linux version such ns SÌnckwnre, you cnn stiÌÌ use the
scriµt. However, you`ÌÌ need to chnnge the µermissions on the fiÌe to
mnke it executnbÌe ~nnd then ndd it to the scriµt to stnrt the server.
Iigures 8-2 nnd 8-8 show the commnnds nnd editing of the
scriµt on n SÌnckwnre Linux system.
Figure 3-2: Copy the file to the /etc/rc.d directory and be sure to
make the file executable.
Configuring the MySQL dntnbnse to stoµ nutomnticnÌÌy when the server is rebooted
or hnÌted is µrobnbÌy more imµortnnt thnn mnking the dntnbnse stnrt nutomnticnÌÌy.
If the MySQL dntnbnse is not shut down µroµerÌy, you mny find broken tnbÌes or
even Ìoss of dntn. On SysV systems such ns Red Hnt nnd Mnndrnke, you needn`t
worry nbout this steµ if you`ve used to configure the
Chapter 3 Linux InstaIIation
scriµt. The foÌÌowing configurntion steµs nre necessnry for 8SD-styÌe systems.
Sometimes these configurntion steµs nre not necessnry, ns the MySQL server wiÌÌ
shut down when given n kiÌÌ commnnd by the system. However, I beÌieve dntn
integrity is too imµortnnt to Ìenve to chnnce.
Figure 3-3: Edit the /etc/rc.d/rc.local file to add the command
/etc/rc.d/mysql.server start.
If you hnven`t nÌrendy coµied the scriµt to nnd mnde the
fiÌe executnbÌe, now is the time to do so. On SÌnckwnre, simµÌy edit the
fiÌe nnd ndd to the fiÌe nenr ~but not nt ~
the toµ of the fiÌe, ns shown in Iigure 8-4.
Figure 3-4: Add the mysql.server stop command to your shutdown
Part I Cetting 5tarted
Should you need to stop the MySCL server manually, you can do so with the
command. For example, the following command would
stop the MySCL server on the local machine:
Notice the use of the switch that causes the command to prompt for a password.
Command-line switches are frequent topics throughout the book, most notably
Chapters 6 and 10 and Appendix A.
Common command-Iine options for mysqId
The mnin server executnbÌe fiÌe for MySQL is cnÌÌed . Here nre some imµor-
tnnt µoints to keeµ in mind when you seÌect its commnnd-Ìine oµtions:.
OÌder versions often run from n uroppcr scripi such ns
Cptions that you can set or call when running the wrapper script can change the
behavior of the server.
You cnn set mnny oµtions from inside the fiÌe (Ìocnted in the
directory or sometimes in the directory).
As a rule of thumb, use the file for changing the command-line behavior
of MySCL. If you edit the file, your changes will be lost if the
mysql.server script is overwritten by future upgrades of the MySCL software.
The fiÌe is n µowerfuÌ wny to controÌ mnny nsµects of the MySQL
softwnre. Ior Linux instnÌÌntions, the fiÌe is usunÌÌy Ìocnted inside the
directory with the fiÌennme , where
indicntes the estimnted resource nmounts of your MySQL server host
Chapter 11 examines various configurations that use the configuration file.
5etting options in the my.cnf fiIe
Within the fiÌe nre sections thnt nffect the behnvior of the comµonents thnt
mnke uµ n MySQL instnÌÌntion. These sections incÌude both the cÌient nnd server,
nnd they use the foÌÌowing ndditionnÌ commnnds:
Chapter 3 Linux InstaIIation
Using the [mysqId] section
Lnch section in the fiÌe stnrts with the brncketed nnme of the commnnd or
nren thnt identifies the section. In Iigure 8-b, for exnmµÌe, you cnn see some oµtions
Ìisted under the word .
Figure 3-5: The my.cnf file contains many options that can affect the
behavior of the MySCL server and client.
If your server is set to run ns uµon stnrtuµ, you shouÌd ndd to
the section of f nnd restnrt the server. To find out whnt oµtions
MySQL wiÌÌ use for stnrtuµ of the server, use the µrogrnm
contnined in the directory of your MySQL instnÌÌntion. Iigure 8-6 shows the
outµut for on n snmµÌe server, your oµtions mny differ
Part I Cetting 5tarted
Figure 3-6: The my_print_defaults script shows the default options
that MySCL uses for many components.
Some non-defnuÌt oµtions for the section thnt you mny wnnt to consider
nre nnd , which work ns foÌÌows:
The oµtion cnuses the server to run ns n non-µriviÌeged user,
which he̵s enhnnce security.
The mny be usefuÌ if you hnve n muliihomcJ host (more thnn
one IP nddress) nnd onÌy wnnt to Ìisten for connections on n certnin IP
nddress. In Iigure 8-7, the nddress thnt is bound is the Lthernet IP nddress for
thnt mnchine, .
Figure 3-7: Using ifconfig to determine the Ethernet address of
the server
Thus, given the correct µriviÌeges, I cnn estnbÌish n connection between nnother
mnchine on the network nnd the host cnÌÌed or , ns shown in
Iigure 8-8.
Chapter 3 Linux InstaIIation
Figure 3-8: Connecting from another machine is possible with the
MySCL client.
Using the commnnd, I cnn see the current connection to
the dntnbnse from the remote cÌient, ns shown in Iigure 8-9.
Figure 3-9: Using mysqladmin processlist, the connection from the other machine,
"testbox.braingia.com," is shown.
However, if I onÌy needed to connect to the MySQL server from the server itseÌf, I
couÌd remove the comµÌeteÌy nnd use the oµtion.
With the oµtion MySQL uses Unix sockets nnd no Ìonger Ìistens
for connections vin TCP}IP. I`ve edited my.cnf nnd restnrted the server. The outµut
of is now shown in Iigure 8-1O. Notice thnt the
oµtion hns been reµÌnced with the oµtion.
Part I Cetting 5tarted
Figure 3-10: Using bind-address in my.cnf to bind only the loopback
address for security purposes
Now when I nttemµt to connect from the remote comµuter, I receive nn error, ns
shown in Iigure 8-11.
Figure 3-11: A failed attempt to connect to a MySCL server that is
no longer listening on its Ethernet address results in an error.
Cther options for and the MySCL server are discussed in Chapter 11.
Creating defauIt databases
and compIeting instaIIation
The finnÌ steµs invoÌved in n MySQL instnÌÌntion nre common to nÌÌ Linux versions
covered in this book. PÌense feeÌ free to refer bnck to this section when you`re
through the initinÌ instnÌÌ rnther thnn rending this now.
Chapter 3 Linux InstaIIation
Irom where you nre now, chnnge into the MySQL directory, . One of the
finnÌ steµs is to run the scriµt to instnÌÌ the defnuÌt dntnbnses. Within the mysqÌ
directory, this is nccomµÌished using the com-
mnnd. The outµut wiÌÌ µrobnbÌy scroÌÌ µnst your screen rnther quickÌy, so I`ve
incÌuded some of it in Iigure 8-12.
Make sure you type these commands exactly as they appear. Failure to do so could
cause problems for your server.
Figure 3-12: The beginning of the output from the
mysql_install_db script
The finnÌ steµ before stnrting the server is to chnnge the µermissions for the MySQL
fiÌes nnd directories. You cnn do so with n series of commnnds, shown in Iigure 8-18.
Figure 3-13: Changing ownership on the MySCL files and directories
is an important step.
Part I Cetting 5tarted
It is now time to stnrt the server. Use the foÌÌowing commnnd:
The character at the end of this command is important because it places the
MySCL server in the background.
AÌternntiveÌy, you cnn set the user in the fiÌe. Under the section,
µÌnce the foÌÌowing Ìine nnd restnrt the server:
5etting an administrator password for My5OL
The first steµ immedinteÌy nfter stnrting n MySQL server is to set n µnssword for the
server ndministrntor nccount known ns . This user is different from the
user on your system, setting the µnssword for this user does not nffect the µnss-
word for the user on your system. (Lven so, use cnre when crenting nny
µnssword, incÌuding this one.)
The utiÌity is whnt you use to set the initinÌ µnssword for the
user. To set the µnssword, the commnnd is run twice ~once for the
connection nnd once for connections vin the hostnnme. When the
commnnd is run, it wiÌÌ µromµt you for the µnssword. If you hnve not set the
µnssword, |ust µress Lnter without tyµing nnything nnd the commnnd wiÌÌ run
Some versions of MySQL now come with the oµtion ennbÌed by
defnuÌt. This cnuses MySQL to Ìisten onÌy for connections from the nnd
not vin the network. The oµtion is contnined in the
section of the MySQL configurntion fiÌe . If this oµtion is ennbÌed, you cnn`t
set the µnssword by using the . If you remove this oµtion from the
configurntion fiÌe, MySQL Ìistens for connections vin the network ~in which cnse,
the oµtion uill work.
The syntnx for setting the µnssword with is ns foÌÌows:
An exnmµÌe of setting the µnssword is shown in Iigure 8-14.
Chapter 3 Linux InstaIIation
Figure 3-14: Setting the root password with mysqladmin is your first task as
a server administrator.
My5OL Linux ßinary InstaIIation
MySQL hns binnry versions nvniÌnbÌe in . nnd gziµµed formnts. To use the RPM
versions, your version of Linux must suµµort RPMs nnd nÌso hnve . To find
out whether your Linux instnÌÌntion µrocedure suµµorts RPMs, Ìog in ns nnd
tyµe or . If you receive n
messnge (or n simiÌnr error messnge), you µrobnbÌy don`t hnve suµµort for RPMs
nnd wiÌÌ hnve to instnÌÌ MySQL ns n binnry or from source code. (RPM instnÌÌntion is
covered Ìnter in this chnµter.)
When you`ve obtnined the MySQL binnry distribution nµµroµrinte for your hnrdwnre,
instnÌÌntion is simµÌy n mntter of unµncking the distribution nnd running some scriµts
to configure the dntnbnse. is the stnndnrd µÌnce to instnÌÌ MySQL for n
binnry version. Therefore, µrior to going further, you shouÌd cd to thnt directory.
Once in , ns shown in Iigure 8-1b, you cnn unµnck the distribution.
SimµÌy tyµe the foÌÌowing commnnd:
The next steµ is to ndd n user nccount nnd grouµ to your server. I strongÌy
recommend tnking this steµ for security rensons. ShouÌd there be n comµromise
or brench of security through the MySQL server, the nttncker wouÌd not gnin
or suµeruser µriviÌeges on your system. Adding the grouµ nnd user is ensy (see
Iigure 8-16).
Part I Cetting 5tarted
Figure 3-15: Unpacking the binary distribution creates a directory
containing the MySCL server files.
Figure 3-16: Addition of the mysql user and group is strongly
recommended for security.
To further stnndnrdize the instnÌÌntion, mnke n symboÌic Ìink between
nnd , which wiÌÌ ennbÌe you to move nround
the fiÌe system with ense. Within the directory, tyµe the foÌÌowing:
You wiÌÌ now hnve n directory cnÌÌed thnt is nctunÌÌy n symboÌic
Ìink to the MySQL server directory, ns shown in Iigure 8-17.
At this µoint, refer to the section in this chnµter cnÌÌed ¨Crenting defnuÌt dntnbnses
nnd comµÌeting instnÌÌntion" for instructions to tnke you through the rest of this
MySQL instnÌÌntion µrocedure.
Chapter 3 Linux InstaIIation
Figure 3-17: Standardization of the MySCL install by making a
symbolic link for the MySCL server directory
My5OL Linux kPM InstaIIation
The instnÌÌntion using fiÌes hns five µortions, from which you seÌect nccording to
your needs: server, testing suite, cÌient, deveÌoµment Ìibrnries, nnd cÌient Ìibrnries.
This section iÌÌustrntes n comµÌete instnÌÌntion thnt incÌudes nÌÌ of them. At the most
bnsic ÌeveÌ, versions nre simµÌy binnry versions of MySQL roÌÌed into fiÌes.
The Ìocntions of fiÌes within n binnry instnÌÌntion mny differ from the instnÌÌ.
Lnch of the fiÌes within nn instnÌÌ simµÌy requires nn commnnd foÌÌowed
by the µncknge nnme, ns in the foÌÌowing exnmµÌe:
InstnÌÌing the mnin fiÌe nctunÌÌy instnÌÌs ~nnd nutomnti-
cnÌÌy stnrts ~the MySQL server. The RPM even runs the scriµt
so you don`t hnve to do it Ìnter.
You don't need to run (as you're told to do later when you
install the main server from RPM).
To instnÌÌ the shnred nnd deveÌoµment Ìibrnries nnd cÌient for MySQL, simµÌy instnÌÌ
them vin the commnnd. If you wish to instnÌÌ the benchmnrking utiÌities you
wiÌÌ need the PerÌ MySQL ModuÌe nvniÌnbÌe for downÌond from MySQL A8.
The Development and ßenchmarking RPMs also depend on the MySCL client.
Therefore you will need to install the MySCL client RPM prior to installing the
Development or ßenchmarking RPMs.
RPM instnÌÌntion is quite ensy though the fiÌe Ìocntions mny be somewhnt different
thnn the other instnÌÌntion methods.
Part I Cetting 5tarted
At this µoint, refer to the section in this chnµter cnÌÌed ¨Crenting defnuÌt dntnbnses
nnd comµÌeting InstnÌÌntion" for instructions to tnke you through the rest of this
MySQL instnÌÌntion µrocedure.
My5OL Linux 5ource InstaIIation
The most configurnbÌe nnd comµÌicnted of the instnÌÌ tyµes for MySQL is nn instnÌÌn-
tion from source code. This method requires you to comµiÌe the server directÌy nnd
therefore is not for everyone. However, with n source-code instnÌÌ:
You hnve the most controÌ over the comµonents instnÌÌed.
You cnn edit or modify the source code to fit your instnÌÌntion.
The source code for MySCL for Linux on Intel/x86 systems is contained on the
CD included with this book.
The source code wiÌÌ be comµressed nnd tnrred, therefore you`ÌÌ need to untnr nnd
uncomµress it, then into the nµµroµrinte directory ns foÌÌows:
Ior security rensons, I recommend ndding n grouµ nnd user for MySQL:
To ennbÌe your instnÌÌntion to cÌoseÌy reµÌicnte n binnry instnÌÌ, you mny wnnt to
consider crenting n directory in .
Doing so enses ndministrntion nnd future uµgrndes.
Choosing Options for My5OL
There nre n Ìnrge number of oµtions you cnn set with n source code instnÌÌ. The
oµtions rnnge from simµÌe oµtions nbout how the configure scriµt wiÌÌ run, to tnbÌe
tyµes to comµiÌe, nnd directories to instnÌÌ comµonents into. The foÌÌowing tnbÌes
Ìist those oµtions nnd the defnuÌts nre contnined in brnckets.
üo the
Chapter 3 Linux InstaIIation
Table 3-1
Configure Options for a My5OL 5ource InstaIIation
Conligurotion Dµtion 0escriµtion
The results from testing will be sent to .
Stops creation of output files.
Suppresses printing of 'creating' messages.
Same as the option.
Source code is in .
Table 3-2
Directory and FiIe Options for My5OL 5ource InstaIIation
Conligurotion oµtion 0escriµtion
Place architecture-independent files in
Place architecture-dependent files in
User executables in
Data files that are read-only and architecture-
independent .
C header files in DIR .
Info style documentation in .
Program executables in .
Cbject code libraries in .
Data that is modifiable and single-machine in
Man documentation in .
C header files for non-gcc in .
Prepend to installed program names.
Append to installed program names.
System executables in .
Data files that are modifiable and architecture-
independent in .
Data files that are read-only and single-machine data in
Part I Cetting 5tarted
Table 3-3
Features and Add-ons for My5OL 5ource InstaIIation
Conligurotion Dµtion 0escriµtion
Cmits support for large files.
Includes ßerkeleyDß table types and
places them in .
MySCL can locate header files for
ßerkeley Dß tables in .
MySCL can locate library files for ßerkeley
Dß tables in .
Includes support for
(Cptions are: , ,
, , , , ,
, , , ,
, , , ,
, , , ,
, , , ,
, , , ).
Uses additional charsets. Can be specified
by group (for example, , ,
or ), or individually comma-separated
from the preceding list.
Includes table types and
place them in DIR.
Includes support for table types.
Minimizes use of available memory. Use
this option if compiling has a problem
because of a shortage of memory.
Specifies a user account as which to run
the server (can be set in ).
Enables RAID (Redundant Array of
Inexpensive Disk) support.
Specifies port to use for MySCL services
(for example, 3306); can be set in .
Absolute location for the UNIX-domain
Does not include debugging code.
Does not build the MySCL server, only the
client programs.
Chapter 3 Linux InstaIIation
Conligurotion Dµtion 0escriµtion
Does not build the documentation.
Does not build the testing and
benchmarking programs.
X include files are in .
X library files are in .
The oµtions you choose whiÌe comµiÌing nre ÌnrgeÌy uµ to you ~deµending on the
requirements of your nµµÌicntion. Ior exnmµÌe, if you wnnt to ¨comµiÌe in" the
needed suµµort for different chnrncter sets, use the or the
oµtion. To incÌude suµµort for the trnnsnc-
tionnÌ tnbÌe tyµe, use the oµtion. The exnmµÌe in the next
section gives n common commnnd Ìine for comµiÌing MySQL. Once your oµtions
nre chosen, instnÌÌntion is strnightforwnrd.
CompiIing My5OL
To comµiÌe with ndditionnÌ oµtions, simµÌy seµnrnte them by n sµnce on the config-
ure commnnd Ìine. Ior the exnmµÌe server, I instnÌÌ into nnd
incÌude suµµort for 8D8 tnbÌe tyµes, Ìike this:
The scriµt runs through ench comµonent nnd µreµnre it for comµiÌntion.
LventunÌÌy you shouÌd see outµut simiÌnr to thnt in Iigure 8-18.
Figure 3-18: The configure script prepares the various components
of MySCL to be compiled.
Part I Cetting 5tarted
After the scriµt is comµÌete, comµiÌe the softwnre by using the commnnd:
The µrocess wiÌÌ tnke nt Ìenst n few minutes deµending on the sµeed of your
mnchine nnd whnt eÌse is running on it nt the time. Once the softwnre is done
comµiÌing, instnÌÌ it with the commnnd:
In nddition, coµy the fiÌe nµµroµrinte for your imµÌementntion to the
MySCL Aß recommends the file for medium installations be used in most
implementations, as follows:
At this µoint, refer to the section in this chnµter cnÌÌed ¨Crenting defnuÌt dntnbnses
nnd comµÌeting instnÌÌntion" for instructions to tnke you through the rest of this
MySQL instnÌÌntion µrocedure.
AÌwnys choose secure µnsswords, for MySQL nnd nÌÌ of your comµuter systems. A
good µnssword incÌudes n mix of n̵hnnumeric nnd non-n̵hnnumeric chnrncters
ns weÌÌ ns n minimum Ìength nnd other fnctors.
There nre n number of common tnsks thnt you need to µerform regnrdÌess of
instnÌÌntion method. These incÌude crenting the defnuÌt dntnbnses, setting
oµtions in the fiÌe, configuring MySQL for nutomntic stnrtuµ nnd
shutdown, nnd setting the root ndministrntor µnssword for MySQL.
The MySQL binnry instnÌÌntion for Linux is the ensiest nnd most recommended
method for instnÌÌntion.
The MySQL RPM instnÌÌntion is renÌÌy n binnry instnÌÌntion in RPM formnt.
However, fiÌe Ìocntions nre usunÌÌy different with nn RPM instnÌÌntion.
The MySQL source code instnÌÌntion is the most configurnbÌe, you cnn set
oµtions during comµiÌntion nnd edit the source code directÌy.
his chnµter gets down to the nitty-gritty of instnÌÌing
MySQL on n Windows system. (The Linux instnÌÌntion
chnµter might be of he̵ if you`re migrnting to Windows from
Linux, nnd wnnt to doubÌe-check the differences in µroce-
dure.) As groundwork for this chnµter, rend Chnµter 2 (if you
hnven`t nÌrendy), it gives you some imµortnnt µoints to
consider before you begin MySQL instnÌÌntion.
MySQL offers two methods for instnÌÌntion under Windows: n
binnry nnd n source-code version. The binnry version is whnt
most Windows users nre fnmiÌinr with~n setuµ µrogrnm thnt
you move through by cÌicking the Next button. The source-
code version is for nµµÌicntions thnt require ndditions or
chnnges to MySQL before they cnn run correctÌy.
Compiling from source code requires a visual C++
Since there nre five versions of MySQL incÌuded with n binnry
version, instnÌÌing from source code is beyond the scoµe of
this book. This chnµter begins, however, with some tnsks thnt
binnry nnd source-code instnÌÌntion hnve in common.
Iasks Common to ßinary and
5ource My5OL InstaIIation
RegnrdÌess of the method you choose for your MySQL instnÌÌn-
tion, some tnsks or oµtions nre common to both versions.
My5OL server administration
the Windows way
IncÌuded with the binnry version of MySQL for Windows is
nn ndministrntion tooÌ cnÌÌed WinMySQLAdmin. Using this
C H A P I E k
ln Ihis Chopler
Chooslng ellecllve
Llsllng lhe common
losks lor blnory ond
source lnslollollon ol
lnslolllng MySCL
lrom lhe blnory
Part I Cetting 5tarted
µrogrnm, you cnn configure nnd chnnge mnny µnrnmeters of the MySQL instnÌÌn-
tion. Ior Windows ndministrntors who nre nverse to the commnnd Ìine, this µro-
grnm µrovides n tooÌ thnt cnn µerform most ndministrntive tnsks from within
Windows. To stnrt WinMySQLAdmin, use Windows LxµÌorer nnd µoint to the
directory of your MySQL instnÌÌntion (usunÌÌy ). Within the
directory, doubÌe-cÌick to stnrt the µrogrnm. The first time you
stnrt WinMySQLAdmin, you`re µromµted to crente n defnuÌt usernnme nnd
µnssword (see Iigure 4-1).
Figure 4-1: Set a default username and password
for use with WinMySCLAdmin.
!ust a reminder: As an administrator of a MySCL server, you must keep the
account secure from unauthorized access. That means (as with all computer sys-
tems) choosing secure passwords for MySCL -such passwords have a mix of
alphanumeric and non-alphanumeric characters, as well as a minimum length and
other attributes that make them hard to guess.
As of this writing, immedinteÌy minimizes itseÌf into the tnskbnr
once you`ve crented its defnuÌt usernnme nnd µnssword. Therefore, to nctunÌÌy bring
uµ the interfnce, right-cÌick the stoµÌight icon in the tnskbnr nnd seÌect ¨Show Me."
Since WinMySCLAdmin automatically minimizes, you may not think the program
has started. ße careful not to start the program more than once.
Once WinMySQLAdmin hns stnrted, you see n number of tnbs nenr the toµ of the
µrogrnm screen (see Iigure 4-2).
The tnbs nenr the toµ of the WinMySQLAdmin screen corresµond to nctions you
cnn µerform or informntion you cnn find out nbout the MySQL server. Some tnbs
µrovide their own context menus when you right-cÌick them (ns in Iigure 4-8).
Chapter 4 Windows InstaIIation
Figure 4-2: WinMySCLAdmin is a powerful, CUI-based program for administering a
MySCL server in Windows 2000.
Figure 4-3: Some areas within WinMySCLAdmin have right-click menus that enable
you to perform additional functions.
Part I Cetting 5tarted
To minimize WinMySQLAdmin, right-cÌick nenr the toµ nnd seÌect ¨Hide Me."
The other, nnd more trnditionnÌ, method for mnnnging n MySQL server is vin the
commnnd-Ìine utiÌity . You cnn use it to controÌ the behnvior of the
MySQL server, ns weÌÌ ns to crente (nnd droµ) dntnbnses nnd gnin informntion nbout
the server.
Using the utility is covered in Chapter 6.
My5OL server startup and shutdown
The MySQL server runs ns n service in Windows 2OOO. You cnn find more informn-
tion nbout the service through the Services nµµÌet in Windows 2OOO by seÌecting
Stnrt Progrnms Administrntive TooÌs Services (see Iigure 4-4).
Figure 4-4: The Services applet in Windows 2000 is where you
can find more information about the behavior of the MySCL server.
As µnrt of the Services frnmework in Windows 2OOO, you cnn controÌ the behnvior of
MySQL when stnrting Windows. MySQL cnn stnrt nutomnticnÌÌy with Windows or
you cnn hnve it stnrt when mnnunÌÌy stnrted by nn ndministrntor (see Iigure 4-b).
There nre five different versions of the MySQL server incÌuded with the binnry dis-
tribution, ns shown in TnbÌe 4-1. Using WinMySQLAdmin (or by editing the
fiÌe Ìocnted in ), you cnn choose which server stnrts by defnuÌt.
Chapter 4 Windows InstaIIation
Figure 4-5: The Services applet in
Windows 2000 enables you to control
the MySCL server startup parameters.
Table 4-1
My5OL 5erver Versions for Windows 2000
Executoble Nome 0escriµtion
Compiled with full debugging enabled, along with memory-
allocation checks. Requires TCP/IP.
Includes support for ßDß and transactional tables.
Includes support for ßDß and tables, as well as for
named pipes.
Contains support for named pipes as a connection method.
Cptimized for Pentium processor, no debugging. Requires
8y normnÌ defnuÌt, stnrts when Windows 2OOO stnrts ~nnd this is fine
for most instnÌÌntions. Using WinMySQLAdmin (nnd cÌicking the tnb ns
shown in Iigure 4-6), you cnn chnnge µnrnmeters ns needed ~incÌuding which
executnbÌe runs for your MySQL server.
Part I Cetting 5tarted
Figure 4-6: Use WinMySCLAdmin to change the server executable to start the
MySCL server.
Common command-Iine options for mysqId
The defnuÌt server executnbÌe fiÌe for MySQL in Windows 2OOO is cnÌÌed .
Some of the oµtions you cnn set or cnÌÌ when you run nctunÌÌy chnnge
the behnvior of the server. In nddition, mnny oµtions cnn be set inside the
fiÌe (Ìocnted in the directory or sometimes in |ust the root directory).
I strongly recommend that you don't make a batch file or script to start MySCL;
instead, use the file for changing the command-line behavior of MySCL.
The fiÌe is n µowerfuÌ method for controÌÌing mnny nsµects of the MySQL
softwnre. Within the fiÌe there nre n number of sections thnt nffect the
behnvior of the vnrious comµonents mnking uµ n MySQL instnÌÌntion. These sec-
tions incÌude both the cÌient nnd server, nnd offer some ndditionnÌ commnnds:
Chapter 4 Windows InstaIIation
Lnch section in the fiÌe stnrts with n nnme in brnckets, which identifies the
commnnd or nren for thnt section. To find out which oµtions MySQL uses for stnrt-
ing uµ the server, use the WinMySQLAdmin tooÌ. CÌick the tnb to see which
executnbÌe wiÌÌ run, nnd to check the other µnrnmeters for MySQL instnÌÌntion.
(Refer to Iigure 4-6 for nn exnmµÌe: oµtions contnined under the section, or
the section undernenth the word .)
If you make changes to the section of the file, you must restart
the server. Cne way to do so is through the Services applet in Windows 2000.
A non-defnuÌt oµtion for the section thnt you mny wnnt to consider is
, it`s esµecinÌÌy usefuÌ if you hnve n muliihomcJ host (one thnt hns
more thnn one IP nddress) nnd wnnt onÌy to Ìisten for connections on n µnrticuÌnr
IP nddress. In Iigure 4-7, the nddress bound is the Lthernet IP nddress for thnt
mnchine, .
Figure 4-7: Using the ipconfig command to determine the ip address
for this host
Hnving MySQL Ìisten for connections on nn Lthernet IP menns thnt, given the
correct µriviÌeges, I cnn connect from nnother mnchine within the network by using
, ns shown in Iigure 4-8.
Part I Cetting 5tarted
Figure 4-8: Connecting from another machine is possible with the
MySCL client
Using WinMySQLAdmin (or the commnnd), I cnn see
the current connection to the dntnbnse from the remote cÌient. An exnmµÌe with
WinMySQLAdmin is shown in Iigure 4-9.
Figure 4-9: Using WinMySCLAdmin displays the connection from the other machine,
Chapter 4 Windows InstaIIation
However, if I onÌy wnnted to connect to the MySQL server from the snme server, I
couÌd remove the comµÌeteÌy nnd use n different oµtion: The
oµtion uses sockets nnd no Ìonger Ìistens for connections vin TCP}IP. If
I choose to foÌÌow thnt route, I edit nnd restnrt the server. Then the
section of WinMySQLAdmin Ìooks Ìike the one shown in Iigure 4-1O. Notice thnt the
oµtion hns been reµÌnced with the oµtion.
Figure 4-10: Using the skip-networking option in my.ini to stop MySCL from
listening for TCP/IP connections
Now, if I nttemµt to connect from the remote comµuter, I receive nn error messnge
(ns shown in Iigure 4-11).
For more about options for and the MySCL server, see Chapter 11.
Part I Cetting 5tarted
Figure 4-11: Error message following a failed attempt to connect to
a MySCL server that's no longer listening on its Ethernet address
5etting an Administrator password for My5OL
The first steµ immedinteÌy nfter stnrting n MySQL server is to set n µnssword for the
server ndministrntor nccount known ns . This user nccount is different from
the or user on your system, setting the µnssword for this
user does not nffect the µnssword for the root user on your system.
The utiÌity sets the initinÌ µnssword for the user. (The
WinMySQLAdmin utiÌity cnn be used ns weÌÌ.) To set the µnssword, you run the
commnnd twice ~once for the ÌocnÌhost connection nnd once for connection vin
the hostnnme. Then, when you run the commnnd, it µromµts you for
the µnssword. (If you hnve not set the µnssword, |ust µress Lnter without tyµing
nnything nnd the commnnd wiÌÌ run successfuÌÌy.) The syntnx for setting the
µnssword is ns foÌÌows:
If you receive an error message that says you can't connect to the server when you
try to run the second command, it may be because the MySCL server is not listen-
ing for connections via TCP/IP. Make sure the option is not in
the MySCL configuration file. If it is, you will need to remove that line and then
restart the MySCL server.
An exnmµÌe of setting the µnssword is shown in Iigure 4-12.
Chapter 4 Windows InstaIIation
Figure 4-12: Setting the root password with mysqladmin is your first
task as a Server Administrator.
InstaIIing My5OL on Windows 2000
InstnÌÌntion of MySQL on Windows 2OOO is incredibÌy simµÌe. MySQL A8 hns gone to
grent Ìengths to ensure n hnssÌe-free instnÌÌntion µrocess.
The first steµ is to downÌond the instnÌÌntion fiÌes or use the ones you cnn find on
the CD-ROM with this book.
The MySCL binary version for Windows is on the CD-RCM that accompanies this
Once the fiÌes nre downÌonded or coµied, you`ÌÌ need n µrogrnm such ns WinZiµ to
uncomµress the instnÌÌntion fiÌes (see Iigure 4-18).
DoubÌe-cÌick to stnrt MySQL instnÌÌntion. The instnÌÌer for MySQL guides
you through the µrocedure, wiznrd-styÌe. Anyone who hns instnÌÌed n µrogrnm in
Windows shouÌd find this instnÌÌntion µretty strnightforwnrd.
After nn initinÌ WeÌcome screen, the instnÌÌer µresents you with nn Informntion
screen (see Iigure 4-14). The informntion screen is there to remind you thnt if you
chnnge the Ìocntions of the directories for your MySQL comµonents, you must cre-
nte n fiÌe in the root directory thnt contnins the Ìocntion of the MySQL
instnÌÌntion nnd dntn fiÌes.
üo the
Part I Cetting 5tarted
Figure 4-13: Use a program such as WinZip to uncompress the setup and
installation files.
Figure 4-14: Create a my.cnf file if you change
the location of the MySCL installation.
Chapter 4 Windows InstaIIation
The next screen determines where you instnÌÌ the MySQL servers nnd cÌients, ns
shown in Iigure 4-1b. I recommend Ìenving it ns unÌess you hnve n
sµecific renson for not wnnting to ncceµt the defnuÌt.
This chapter assumes that you use as your base directory. Should you
choose to install into a different directory, please take that change into account
and make the necessary adjustments when you follow the instructions herein.
Figure 4-15: Determining where you want to install MySCL
Next is the µromµt for instnÌÌntion tyµe, TyµicnÌ, Comµnct, or Custom. I recommend
Ìenving the oµtion nt TyµicnÌ (see Iigure 4-16). The TyµicnÌ oµtion instnÌÌs nÌÌ com-
µonents of MySQL. If you don`t wnnt to instnÌÌ nÌÌ comµonents, cÌick the Custom
rndio button nnd you get n Ìist of oµtions to unseÌect (see Iigure 4-17).
Part I Cetting 5tarted
Figure 4-16: The Typical option installs all components and is the default.
Figure 4-17: ßy selecting the Custom option, you can unselect components
that you don't want to install.
Chapter 4 Windows InstaIIation
Once you hnve chosen nn instnÌÌntion oµtion (TyµicnÌ, Comµnct, or Custom),
MySQL begins the instnÌÌntion by coµying the nµµroµrinte fiÌes (see Iigure 4-18).
Figure 4-18: MySCL takes over and starts copying files as part of the installation
CongrntuÌntions! You shouÌd see n Iinish screen ~the steµ thnt concÌudes this
stnge of the instnÌÌntion (see Iigure 4-19).
As I usually recommend with Windows, restart the server before going farther.
Irom here, you shouÌd mnke sure you`ve done the µost-instnÌÌntion tnsks (men-
tioned enrÌier in the chnµter), incÌuding setting the } µnssword
nnd determining which binnry version of MySQL to run.
Part I Cetting 5tarted
Figure 4-19: Finish up by clicking Finish and
restarting the server.
8efore you instnÌÌ MySQL, refer to Chnµter 2 for n review of some imµortnnt ground-
work µrocedures. Then you cnn use nn ndministrntive utiÌity (WinMySQLAdmin for
Windows or ) to instnÌÌ MySQL.
With MySQL for Windows, you cnn use the WinMySQLAdmin µrogrnm to
ndminister most functions of n MySQL server vin n GUI.
Iive different versions of MySQL nre incÌuded with n stnndnrd binnry
distribution for Windows. You cnn choose which server to run by using the
WinMySQLAdmin µrogrnm or by editing the fiÌe.
A number of oµtions exist for the vnrious comµonents of n MySQL instnÌÌntion,
you cnn set them in the fiÌe.
ImmedinteÌy nfter you stnrt the MySQL server for the first time, you must set n
µnssword for the user with the commnnd.
ShouÌd you chnnge the defnuÌt Ìocntion of the MySQL instnÌÌntion, you must
crente n fiÌe cnÌÌed in the directory of the drive to teÌÌ MySQL
the where to find the instnÌÌntion.
Choosing n TyµicnÌ instnÌÌntion tyµe instnÌÌs nÌÌ comµonents. If you don`t nctu-
nÌÌy need nÌÌ the comµonents, you cnn choose n Custom instnÌÌntion tyµe nnd
de-seÌect nny comµonents you don`t need.
Ìthough trnditionnÌÌy the Mncintosh hns not been
weÌÌ suited for work ns n server, this chnnged with the
reÌense of Mnc OS X. AµµÌe`s next-generntion oµernting system
hns n Unix-bnsed foundntion, which mnkes it n good choice for
running servers nnd server nµµÌicntions.
Mnc OS X comes in two versions:
Mac OS X Server: This version comes with MySQL
nÌrendy instnÌÌed.
Mac OS X: No MySQL instnÌÌed, but it cnn ensiÌy be
This chnµter Ìooks nt some tnsks common to nÌÌ versions of
MySQL, ns weÌÌ ns instnÌÌing MySQL from source code.
ßinary and 5ource-Code My5OL
InstaIIation in Mac O5 X: Iasks
in Common
There nre severnÌ tnsks thnt you mny wnnt to do no mntter how
you decide to instnÌÌ MySQL. MySQL cnn be configured to stnrt
nutomnticnÌÌy when Mnc OS X is stnrted, it cnn be mnnunÌÌy
shut down, nnd you cnn chnnge the ndministrntor µnssword.
5etting up My5OL to start automaticaIIy
Mnc OS X cnn stnrt nµµÌicntions nutomnticnÌÌy when the sys-
tem is booted~but its stnrtuµ µrocess differs significnntÌy
from thnt of n stnndnrd Unix system.
C H A P I E k
ln Ihis Chopler
Revlewlng common
losks lor blnory ond
sourcecode MySCL
lnslolllng MySCL wllh
Moc CS / Server
lnslolllng MySCL
blnory on Moc CS /
lnslolllng MySCL
lrom source code on
Moc CS /
Part I Cetting 5tarted
Mnc OS X uses n foÌder to nutomnticnÌÌy stnrt nµµÌicntions, nÌthough
n foÌder exists by defnuÌt, thnt is reserved for
AµµÌe`s use. PersonnÌ stnrtuµ items shouÌd be Ìocnted in the
Creating the /Library/5tartupItems foIder
8ecnuse the foÌder doesn`t exist by defnuÌt, you must
crente it if someone eÌse hnsn`t nÌrendy.
1. Using the commnnd, check to see whether this foÌder exists, if it does not,
crente it with the commnnd. The code thnt nccomµÌishes these µreµn-
rntions is ns foÌÌows (boÌd indicntes the commnnds to tyµe):
2. Preµnre to ndd n stnrtuµ item to the foÌder by crenting three things:
º A foÌder with n descriµtive nnme
º A commnnd-Ìine scriµt with the snme nnme ns the foÌder (see the steµs
in the uµcoming subsection, ¨Crenting the fiÌe for the stnrtuµ scriµt").
º A stnrtuµ µnrnmeters fiÌe (see the steµs in the uµcoming subsection,
¨Crenting the fiÌe").
To crente the foÌder, nnvignte to the }Librnry}StnrtuµItems foÌder nnd crente the
new foÌder with the commnnd.
You wiÌÌ hnve to use n text editor to crente the fiÌes you need: one to contnin the
stnrtuµ scriµt nnd one to contnin stnrtuµ µnrnmeters.
This example uses the text editor, which operates much like any other typi-
cal text editor: When you run , you can type and move around with the arrow
keys. When you're done editing the file, simply press Control-X (the Mac equiva-
lent of Ctrl+X) and a prompt asks whether you want to save the file and exit. Press
Y to save the file and return to the command line.
Creating the fiIe for the startup script
The first fiÌe needed for nutomntic stnrtuµ is the sioriup scripi fiÌe. This is the sheÌÌ
scriµt thnt wiÌÌ nctunÌÌy stnrt MySQL.
1. Crente the fiÌe nnd oµen it for editing in µico with the foÌÌowing commnnd.
Chapter 5 Macintosh InstaIIation
2. Lnter the foÌÌowing scriµt into µico.
3. Use Commnnd-X to exit nnd snve the fiÌe.
Creating the 5tartupParameters fiIe
The second fiÌe needed for nutomntic stnrtuµ is the sioriup poromcicrs fiÌe. This fiÌe
gives Mnc OS X ndditionnÌ informntion needed for nutomnticnÌÌy running MySQL.
1. Oµen the fiÌe by tyµing the foÌÌowing Ìine.
2. Lnter the foÌÌowing scriµt into µico.
3. Use Commnnd-X to exit nnd snve the fiÌe.
4. The ownershiµ nnd µermissions of some fiÌes must be chnnged to secureÌy
run the stnrtuµ item. You must use the sudo commnnd to chnnge ownershiµ.
Lnter your ndministrntor µnssword when you nre µromµted for it.
Part I Cetting 5tarted
Modifying the hostconfig fiIe
The Ìnst thing you hnve to do is to modify the fiÌe so it teÌÌs Mnc OS X
thnt you wnnt to run this service. IoÌÌow these steµs:
1. Lnter the foÌÌowing commnnd it wiÌÌ oµen uµ nn existing fiÌe in µico.
2. ScroÌÌ to the bottom of this fiÌe nnd enter MYSQL--YLS- on its own Ìine. This is
how it shouÌd Ìook.
3. Use Commnnd-X to exit nnd snve the fiÌe.
When you hnve nÌÌ these fiÌes in µÌnce nnd µroµerÌy set uµ, MySQL is rendy to stnrt
nutomnticnÌÌy every time you stnrt uµ Mnc OS X. If you ever wnnt to stoµ MySQL
from stnrting uµ nutomnticnÌÌy, simµÌy edit the fiÌe nnd chnnge the Ìine
thnt rends - to .
Chapter 5 Macintosh InstaIIation
5hutting down My5OL 5erver
If you wnnt to mnnunÌÌy shut down the server, you shouÌd use the
A bug in versions of MySCL prior to 3.23.45 and 4.0.1 prevents the MySCL server
from shutting down properly. Make sure you are using these versions or later.
To shut down the server, foÌÌow these steµs:
1. Log in to the terminnÌ ns the user.
2. Run the commnnd with the µnrnmeter, ns foÌÌows:
5etting an administrator password for My5OL
The first steµ immedinteÌy nfter stnrting n MySQL server is to set n µnssword for the
server ndministrntor nccount known ns .
This user account is different from the user on your system; setting the pass-
word for this user doesn't affect the password for the user on your system.
The utiÌity is used to set the initinÌ µnssword for the user. To set
the µnssword, the commnnd is run twice ~once for the connection nnd
once for connections vin the hostnnme. When the commnnd is run, it
wiÌÌ µromµt you for the µnssword. If you hnve not set the µnssword, |ust µress Lnter
without tyµing nnything nnd the commnnd wiÌÌ run successfuÌÌy. The syntnx to set
the µnssword with is ns foÌÌows:
An exnmµÌe of setting the µnssword is shown in Iigure b-1.
Part I Cetting 5tarted
Figure 5-1: Setting the root password with mysqladmin is your first task as a
server administrator.
InstaIIing My5OL With Mac O5 X 5erver
AµµÌe incÌudes MySQL with Mnc OS X Server 1O.O.4 nnd Ìnter. It is instnÌÌed in the
directory but it is neither configured nor set to run by
defnuÌt. AµµÌe hns severnÌ knowÌedge-bnse nrticÌes thnt cover how to instnÌÌ nnd
configure MySQL on n Mnc OS X server. To find them, go to AµµÌe`s suµµort site nt
nnd senrch the knowÌedge bnse for .
Refer to the section cnÌÌed ¨8innry nnd Source-Code MySQL InstnÌÌntion in Mnc OS
X: Tnsks in Common" (enrÌier in this chnµter) for more informntion on stnrting nnd
stoµµing MySQL nnd setting n µnssword for the ndministrntive user.
InstaIIing My5OL ßinary on Mac O5 X
ComµiÌing nnd instnÌÌing your own version of MySQL cnn be n dnunting µrocess.
There is nn officinÌ binnry distribution of MySQL for Mnc OS X nvniÌnbÌe for down-
Ìond nnd instnÌÌntion. Mnny µeoµÌe hnve crented unofficinÌ binnry distributions of
their own thnt cnn be used instend of the officinÌ version. Any of these binnry ver-
sions mny be used. They tnke Ìess time to instnÌÌ nnd mny not require the AµµÌe
deveÌoµer tooÌs to be instnÌÌed. The drnwbncks nre thnt you hnve Ìess controÌ over
the oµtions used nnd the Ìntest version of the MySQL code mny not be nvniÌnbÌe.
The Ìntest officinÌ binnry version of MySQL for Mnc OS X cnn nÌwnys be found nt
. DownÌond the Mnc OS X binnry nµµroµrinte for your
Mnc OS (Mnc OS X or Mnc OS X Server).
Chapter 5 Macintosh InstaIIation
One of the best indeµendent OS X binnry distributions hns been crented by Mnrc
Liynnnge nnd is nvniÌnbÌe nt his Web site
( ).
InstnÌÌntion of ench binnry distribution is different. DownÌond the instnÌÌer µncknge
nnd foÌÌow the instructions for thnt distribution.
InstaIIing My5OL 5ource Code on Mac O5 X
The most fÌexibÌe nµµronch to instnÌÌing MySQL for Mnc OS X is to use the MySQL
source code nnd comµiÌe it yourseÌf.
You wiÌÌ need two bnsics to comµiÌe MySQL yourseÌf:
The latest version of the MySQL source code. This cnn nÌwnys be found nt
. DownÌond the ¨tnrbnÌÌ" source µncknge for MySQL.
Apple's developer tools. lf you don`t nÌrendy hnve these instnÌÌed, they cnn be
found on the DeveÌoµer TooÌs CD thnt is incÌuded with every coµy of Mnc OS
X or downÌonded from .
Once you hnve these µrerequisites, you cnn µroceed with the instnÌÌntion.
Creating the My5OL User
To run the MySQL server secureÌy, you hnve to crente n user nccount for the MySQL
server itseÌf. IoÌÌow these steµs:
1. Oµen System Preferences nnd seÌect the Users µreference µnneÌ.
2. If you nre not nÌrendy Ìogged in ns nn ndministrntor, cÌick the Ìock icon nnd
enter nn ndministrntor nnme nnd µnssword in the window shown in Iigure b-2.
Figure 5-2: Entering the Administrator name
and password
Part I Cetting 5tarted
3. CÌick the New User button. Lnter mysql for the Nnme nnd Short Nnme, ns
shown in Iigure b-8.
Figure 5-3: Entering the mysql user
4. SeÌect the Pnssword tnb nnd enter n µnssword for the user, ns shown
in Iigure b-4.
Figure 5-4: Entering the mysql password
5. CÌick Snve nnd cÌose System Preferences.
Chapter 5 Macintosh InstaIIation
CompiIing My5OL
The nctunÌ MySQL nµµÌicntion is instnÌÌed by unµncking, configuring, nnd comµiÌing
the code you hnve downÌonded. The µrocedure Ìooks Ìike this:
1. Oµen the TerminnÌ nµµÌicntion nnd nnvignte to the Ìocntion to which you
downÌonded the MySQL ¨tnrbnÌÌ" source µncknge, much Ìike this:
2. Use the commnnd to exµnnd the source µncknge into its own foÌder:
3. Nnvignte into the new foÌder nnd run the scriµt, which µreµnres
the µncknge to be comµiÌed on your µnrticuÌnr system:
4. Run the commnnd, which nctunÌÌy comµiÌes the MySQL µncknge.
Compilation normally takes quite some time, even on a fast Macintosh.
The µrocedure Ìooks Ìike this:
5. InstnÌÌ MySQL by running the commnnd. Since instnÌÌing
MySQL requires ndministrntive µriviÌeges you must use the commnnd
before you use the instnÌÌntion commnnd. When the commnnd µromµts
you for n µnssword, enter your Mnc OS X ndministrntion µnssword (see the
second Ìine of code in this sniµµet):
Part I Cetting 5tarted
Configuring My5OL
MySQL must be configured before it cnn be run. Run the scriµt
with the commnnd to configure MySQL. The µrocedure Ìooks Ìike this:
1. Configure MySQL by running the scriµt with the
commnnd. The µrocedure Ìooks Ìike this:
2. You must chnnge the ownershiµ of n fiÌe nnd n foÌder in order to run MySQL.
Use the commnnd with to do so, ns foÌÌows:
Chapter 5 Macintosh InstaIIation
Iesting My5OL
You shouÌd test your instnÌÌntion to mnke sure everything instnÌÌed correctÌy. Do so
by stnrting the MySQL server nnd hnving it disµÌny its version, ns foÌÌows:
1. To stnrt the MySQL server, you hnve to Ìog in ns the user you crented
enrÌier. You cnn do so with the commnnd. Lnter the user`s µnssword
when you nre µromµted for it, ns shown in the second Ìine of the code sniµµet
thnt foÌÌows:
2. Once MySQL is running, check it by using the commnnd to check
the version of the MySQL server. The µrocedure Ìooks Ìike this:
Part I Cetting 5tarted
A number of instnÌÌntion tnsks must be µerformed regnrdÌess of instnÌÌntion method.
These incÌude configuring MySQL for nutomntic stnrtuµ nnd shutdown, nnd setting
the ndministrntor µnssword for MySQL.
Mnc OS X Server incÌudes MySQL µreinstnÌÌed, not much configurntion is nec-
There is nn officinÌ MySQL binnry instnÌÌntion for Mnc OS X ns weÌÌ ns severnÌ
unofficinÌ indeµendent binnry distributions (the most notnbÌe of which is
Mnrc Liynnnge`s).
The ndvnntnges of binnry distributions (Ìess time, simµÌer) hnve to be
weighed ngninst the disndvnntnges (Ìess controÌ, Ìntest versions mny not be
InstnÌÌing MySQL from source code is the most configurnbÌe method, oµtions
nre nvniÌnbÌe even during comµiÌntion, nnd editing the source code directÌy is
the most efficient wny to customize your imµÌementntion of MySQL.
5tarting My50L
ySQL is n Ìnrge nnd often comµÌex coÌÌection of cÌient
nnd server softwnre to store nnd retrieve dntn.
Sometimes n µerson who is new to MySQL or SQL entireÌy is
overwheÌmed by the deµth nnd number of oµtions invoÌved
with whnt seems to be n simµÌe dntnbnse tnsk. In this chnµter
I`ÌÌ cover some of the bnsic conceµts thnt deveÌoµers nnd
ndministrntors nÌike wiÌÌ µrobnbÌy encounter. My gonÌ is to
he̵ the render become comfortnbÌe with MySQL nnd show
some of the common dny-to-dny tnsks µerformed with MySQL.
My5OL 5erver Administration
and 5ecurity
This section shows you some common nnd usefuÌ commnnds
thnt cnn get n MySQL server running nnd to keeµ it running.
The first of these ~ ~is criticnÌÌy imµortnnt, fre-
quentÌy used by ndministrntors, nnd one you shouÌd nÌwnys
run on n newÌy instnÌÌed MySQL server to ensure the security
of the ¨suµeruser" nccount.
AÌso, though MySQL is n very stnbÌe nµµÌicntion (even in Ìnrge
imµÌementntions), sooner or Ìnter you mny fnce common
ndministrntive chnÌÌenges such ns these:
Preventing, Ìimiting, or undoing the effects of n security
Integrnting new comµonents into the system
Removing (or chnnging the µriviÌeges grnnted to) sµecific
user nccounts
DenÌing with troubÌe reµorts from users who encounter
µrobÌems with the dntnbnse
The versntiÌe commnnd is n good stnrting µoint
for understnnding nnd imµÌementing good security nnd
sound ndministrntive µoÌicy. This section exµÌores some of
its mn|or uses.
C H A P I E k
ln Ihis Chopler
lnlroduclng MySCL
server odmlnlslrollon
ond securlly
lrylng oul lrequenlly
used MySCL
dolobose luncllons
Part I Cetting 5tarted
Using mysqIadmin
You cnn use to nccomµÌish vnrious gonÌs, such ns
Restoring or enhnncing the security of the nccount
Determining the stntus of the MySQL server whiÌe it`s running
Shutting down the server for uµgrndes or emergency hnrdwnre reµÌncements
This section gives you n gÌimµse of whnt you cnn do with this usefuÌ commnnd.
A very usefuÌ ndministrntion µrogrnm for MySQL is . With ,
the oµerntor cnn µerform mnny ndministrntive functions without hnving to enter
into the MySQL Commnnd Line Interfnce (CLI). Ior exnmµÌe, dntnbnses cnn be cre-
nted nnd droµµed vin , nnd the server cnn be dingnosed or even shut
down. Chnµter 1O wiÌÌ cover in grenter detniÌ. Ior now I`ÌÌ concentrnte
on n few usefuÌ oµtions to get you stnrted.
5etting the root password
As shown in Chnµters 8 through b, the commnnd is whnt you use to
set uµ the initinÌ µnssword for the user in MySQL, nnd thnt is the first thing
you shouÌd do once you get n MySQL server running. To set the µnssword,
issue the foÌÌowing commnnd:
If the µnssword hns nÌrendy been set for the user, you must ndd the switch
to the commnnd nnd µrovide the existing µnssword when µromµted. Doing so Ìooks
Ìike this:
Choose a password carefully. Passwords based on dictionary words (or which are
otherwise easily guessable) are not acceptable for most environments. For better
data protection, choose a password that is at least 6 characters and includes non-
alphanumeric characters.
Most oµerntions with require the switch to be set. If the switch
is not set, you wiÌÌ µrobnbÌy see nn error messnge (ns shown in Iigure 6-1):
Chapter 6 5tarting My5OL
Figure 6-1: Common error message when password (-p) is not
Checking My5OL server status
You cnn use to check the stntus of the MySQL server vin the
switch. The commnnd Ìooks Ìike this:
A brief stntus summnry of the MySQL server is nvniÌnbÌe vin the switch. An
extended version of the switch is (covered in Chnµter
1O). The outµut of the stntement wiÌÌ Ìook something Ìike Iigure 6-2, in
which the uµtime for this µnrticuÌnr server is 18bO seconds (of course, this server
isn`t very busy ~onÌy one thrend running nnd no oµen tnbÌes).
Figure 6-2: Cutput of the mysqladmin status statement
Part I Cetting 5tarted
Your output can (and probably will) be substantially different from what's
shown here.
DeaIing with inactive connections
Sometimes cÌients connect to the MySQL server but don`t disconnect. As n resuÌt,
the server cnn quickÌy exceed its mnximum number of connections (esµecinÌÌy if it`s
normnÌÌy busy) in which cnse MySQL refuses further cÌient connections tiÌÌ the
trnffic Ìets uµ.
The number of connections nÌÌowed in MySQL vnries nccording to the system
hnrdwnre, but the ndministrntor cnn nÌso set some vnrinbÌes to Ìimit. I cover differ-
ent size imµÌementntions in nnother chnµter. To find out whnt connections nre
nctive to the MySQL server, use the switch ns shown in Iigure 6-8:
Figure 6-3: Cutput of the mysqladmin processlist statement
Irom the outµut in Iigure 6-8, you cnn see n user nnmed is connected
from to the dntnbnse. The user is currentÌy idÌe, ns shown by the
word under the coÌumn. AÌso shown is the user running n
query to show the .
With the commnnd, you cnn end n connection to the MySQL
dntnbnse ns weÌÌ. The syntnx for kiÌÌing n connection is n foÌÌows:
Ior exnmµÌe, to kiÌÌ `s connection to the dntnbnse, you wouÌd issue the
foÌÌowing commnnd:
Chapter 6 5tarting My5OL
Looking nt the outµut in Iigure 6-4 you cnn see thnt the connection
by no Ìonger exists:
Figure 6-4: A processlist statement after a thread has been killed
If wns connected vin the MySQL CLI, the user wiÌÌ receive the foÌÌowing
messnge when they nttemµt to µerform nn oµerntion:
If the connection nttemµt is successfuÌ, the connection is issued n new ID nnd the
oµerntion is executed, ns shown by the new in Iigure 6-b:
Figure 6-5: A new connection was created for the user.
Part I Cetting 5tarted
5hut down the server
cnn nÌso be used to shut down the MySQL server. The syntnx is
intuitive for this oµerntion:
hns n wide rnnge of such usefuÌ switches, which µrovide the versntiÌity
thnt nn ndministrntive tooÌ must hnve.
ßasic My5OL security
One of the first things you shouÌd do ns n MySQL dntnbnse ndministrntor is chnnge
the µnssword. AccomµÌishing this tnsk with is exµÌnined in
Chnµters 8, 4, nnd b deµending on your instnÌÌntion nnd is covered in this chnµter
ns weÌÌ. If you hnve not nÌrendy done so, now is the time to configure n secure
µnssword for your MySQL server. No nmount of dntnbnse security wiÌÌ he̵ if the
nccount cnn connect with n bÌnnk µnssword or no µnssword nt nÌÌ!
Another imµortnnt, but sometimes overÌooked, nren of security for MySQL is the
security of the mnchine thnt houses the MySQL server. If thnt comµuter, regnrdÌess
of oµernting system, is not keµt secure by nµµÌying the Ìntest µntches nnd rigor-
ousÌy mnintnining security, no nmount of dntnbnse security wiÌÌ keeµ your dntn
snfe. If µossibÌe, utiÌize n firewnÌÌ to µrevent outside connections to the MySQL
server or restrict connections to the MySQL server mnchine in nnother wny such
ns or in Linux or vin nn nccess Ìist on n router.
Numerous oµtions exist for the wny thnt the MySQL server itseÌf is run. Those oµtions
nre beyond the scoµe of this chnµter but nre covered in nnother chnµter . Some
oµtions to consider when stnrting the server nre the oµtion
which µrevents the server from Ìisten for network connections nnd the
oµtion which µrevents users from showing the nnmes of the dntnbnses
nvniÌnbÌe on the server.
Adding a user to My5OL
It is neither customnry nor wise to give n mechnnic the keys to your house so he or
she cnn fix your cnr, doing so onÌy crentes unnecessnry risks. The snme cnn be snid
for grnnting nccess to your dntn: Using MySQL`s user nccount to µerform
everydny dntnbnse oµerntions is n bnd iden. It is much more µrefernbÌe to grnnt
onÌy the necessnry nccess to sµecific users. OnÌy nÌÌow ns mnny µriviÌeges ns nre
necessnry for ench user to comµÌete his or her |ob.
MySQL nccess is bnsed on n µriviÌege system. MySQL hoÌds nn internnÌ dntnbnse
nµtÌy titÌed with tnbÌes for housing µriviÌege dntn cnÌÌed , , ,
, nnd . A given user`s nccess to dntn cnn be defined
down to which coÌumns the user cnn µerform oµerntions on in n µnrticuÌnr
dntnbnse tnbÌe.
Chapter 6 5tarting My5OL
Ior exnmµÌe, n user crented for nccessing µroduct informntion for n Web site cnn be
given rend nccess to the µroduct nnme nnd µrice coÌumns in the inventory dntnbnse`s
µroduct tnbÌe. In this mnnner, if n mnÌicious or even weÌÌ intentioned user were to gnin
nccess to your dntn through thnt usernnme nnd µnssword, they couÌd onÌy rend the
dntn nnd not modify it.
As stnted nbove, nccess is bnsed uµon n µriviÌege system. PriviÌeges nre grnnted
nnd revoked bnsed uµon the usernnme, host connecting from, oµerntion requested,
dntnbnse, tnbÌe, nnd coÌumn. Since MySQL hoÌds the µriviÌege dntn within tnbÌes,
normnÌ insert, deÌete, seÌect, nnd uµdnte oµerntions work ns exµected.
The bnsic stntement to ndd n user nnd nÌÌow nccess to MySQL is the stnte-
ment. RecnÌÌ from my discussion on conventions used in this book thnt brnckets
such ns denote required µortions of syntnx for the commnnd, squnre brnckets
such ns denote ndditionnÌ modifiers nnd µnrentheses such ns denote
oµtionnÌ µortions of commnnds. The syntnx for the stntement is ns foÌÌows:
MySQL µrovides n couµÌe of mncros for nssigning common µriviÌeges. These incÌude
nnd . 8y using the mncro, you grnnt nÌÌ µossibÌe µriviÌeges to n user
(ns you mny imngine, it`s best to use this one sµnringÌy). The mncro is for
ndding n user nccount to MySQL without grnnting nny µriviÌeges (nnd it`s µrobnbÌy
best not to Ìenve it thnt wny, since n user without µriviÌeges cnn`t do nnything on the
system, incÌuding work).
As nn exnmµÌe, I`ÌÌ show you how to ndd n more-or-Ìess tyµicnÌ user nccount to
MySQL ~nfter which you cnn use it throughout the book to try out mnny dntnbnse
oµerntions. AÌthough you don`t grnnt this snmµÌe user nccount nny µriviÌeges, you
wouÌd ndd µriviÌeges in n renÌ network situntion (or there wouÌd be no renson to
crente the user). Adding users nnd grnnting µriviÌeges is covered in more detniÌ in
Ìnter chnµters, incÌuding Chnµter 12.
Connect to the dntnbnse ns the user from the MySQL CLI, ns foÌÌows:
It is not necessary to connect to the mysql database in order to grant and revoke
access to the database via the and statements.
Lnter on in the chnµter, n different exercise ndds sµecific µriviÌeges for this user
nccount so it cnn connect to the dntnbnse thnt you`re nbout to crente.
Part I Cetting 5tarted
FrequentIy Used My5OL Database Functions
Mnny of the functions thnt you use often with MySQL nre covered in this section.
Hnving worked with dntnbnses nnd MySQL for yenrs, I encounter the snme tnsks on
n frequent bnsis: Inserting nnd uµdnting dntn, ns weÌÌ ns simµÌe seÌecting, nre the
brend nnd butter of mnny dntnbnse oµerntors nnd ndministrntors` ÌiveÌihoods. Lven
if you don`t crente dntnbnses often, you`ÌÌ µrobnbÌy crente one with MySQL nt some
µoint. Therefore this section shows you how to crente your first dntnbnse, offers n
few snmµÌe tnbÌes, nnd Ìnys out the buiÌding bÌocks for understnnding Structured
Query Lnngunge (SQL).
Creating a database
AÌthough the fuÌÌ syntnx of the MySQL cÌient interfnce cnn be nbout ns comµÌex ns
you need it to be (it`s covered in Chnµter 8), crenting n dntnbnse in MySQL is
nctunÌÌy µretty simµÌe.
As a prerequisite for creating a MySCL database, make sure your MySCL software
is installed and running already. (If it's not, refer to Chapter 3, 4, or 5 to install the
version of MySCL that's appropriate for your platform.)
There nre two wnys to crente n dntnbnse with MySQL:
vin the ' ` commnnd, Ìike this:
from within the MySQL CLI, using the foÌÌowing syntnx:
The keyword produces an error message if a database already
exists with the name given.
RecnÌÌ thnt stntements cnn sµnn muÌtiµÌe Ìines in the MySQL CLI, nnd thnt you
terminnte n stntement with n semicoÌon (,). Therefore, to crente nn exnmµÌe
dntnbnse from within the MySQL CLI, tyµe the foÌÌowing:
The next steµ is to crente tnbÌes within the dntnbnse you |ust crented. To crente
tnbÌes, you`ÌÌ need to connect to the nctunÌ dntnbnse you wnnt to use. MySQL
nctunÌÌy does not require you to be connected to the dntnbnse in order to crente
tnbÌes. AÌthough you cnn crente tnbÌes by using n
syntnx from within the MySQL CLI, it`s often Ìess confusing (which snves debugging
time) if you connect to the dntnbnse itseÌf. If you nre nÌrendy within the MySQL CLI,
you cnn tyµe the foÌÌowing:
Chapter 6 5tarting My5OL
If you nre nt the commnnd µromµt, you cnn get into the MySQL CLI nnd connect to
the dntnbnse by issuing the foÌÌowing commnnd:
Ior exnmµÌe, here`s one thnt connects the nccount to the
Creating tabIes
RegnrdÌess of the method you choose, working with the dntnbnse vin the MySQL CLI
menns you cnn crente tnbÌes to store informntion for n Web site. 8efore you cnn cre-
nte the tnbÌes, however, you need n design for the dntnbnse.
For help with developing a database design, review Chapter 7.
Assessing the needs of your site cnn suggest n µrncticnÌ direction for dntnbnse
design. Ior exnmµÌe, the Web site e-commerce dntnbnse must trnck n rnnge of dif-
ferent vnrinbÌes ~incÌuding nnme of µroduct, tyµe of µroduct, mnnufncturer, µrice,
nnd qunntity on hnnd. The initinÌ design cnÌÌs for three individunÌ tnbÌes within the
dntnbnse, TnbÌes 6-1, 6-2, nnd 6-8 µrovide exnmµÌes of how such tnbÌes contribute to
the design of the exnmµÌe dntnbnse.
Table 6-1
Product IabIe
Column Iitle Column Iyµe Constroints
not-null primary key
Part I Cetting 5tarted
Table 6-2
Manufacturer IabIe
Column Iitle Column Iyµe Constroints
not-null primary key
Table 6-3
Category IabIe
Column Iitle Column Iyµe Constroints
not-null primary key
The bnsic syntnx for tnbÌe crention in MySQL is ns foÌÌows:
The keyword crentes n tnbÌe thnt exists onÌy for the durntion of the
If there is n tnbÌe of the snme nnme, the existing tnbÌe is hidden.
Two seµnrnte connections cnn utiÌize the snme temµornry tnbÌe nnme.
The keyword µrevents the tnbÌe from being crented if n tnbÌe of the
snme nnme exists. MySQL onÌy verifies the nnme of the tnbÌe nnd does not nttemµt to
verify if the tnbÌe structures nre the snme. When the keyword is used,
the oµerntion returns nn regnrdÌess of the success or fniÌure of the stntement.
As indicnted by the brnckets ( ) nround the coÌumn definition, it is not necessnry
to ndd nÌÌ of the definitions for the coÌumns when crenting n tnbÌe. At Ìenst one coÌ-
umn definition is required. The coÌumn definition cnn be modified Ìnter through the
use of the stntement.
nre used to crente different tyµes of tnbÌes. The bnsic tnbÌe tyµes with
MySQL nre , nnd . Some tnbÌe tyµes, incÌuding ( ),
, nnd mny or mny not be incÌuded with your MySQL distribution,
Chapter 6 5tarting My5OL
deµending on the version of MySQL you hnve nnd the oµtions chosen whiÌe comµiÌing
(if nµµÌicnbÌe). TnbÌe 6-4 iÌÌustrntes the tyµes of tnbÌes in MySQL.
is the default table type in MySCL. If you try to create a table using a table
type that is not supported by your version, MySCL creates it as instead-
with no warning or error message (though future versions of MySCL will produce
a warning when the table type is not supported).
Table 6-4
My5OL IabIe Iypes
Ioble Iyµe 4ttribute
or Transactional, page-locking.
Transactional, row-level locking, not open-source. Available
with NuSphere MySCL.
Data is only stored in volatile memory.
Normal or standard table.
Another type of transactional, row-level locking table.
Collection of tables to be used as a single table.
As the newer version of , this is the default table type.
You cnn he̵ ensure the snfety of your dntn by using n trnnsnctionnÌ tnbÌe tyµe such
ns , , or , nnd here`s why:
If n µrobÌem occurs within the dntnbnse or system housing the dntnbnse, the
dntn within n trnnsnctionnÌ tnbÌe cnn be recovered through the use of n roÌÌ-
bnck or the bnckuµ nnd uµdnte Ìogs.
Chnnges mnde to dntn cnn be roÌÌed bnck or nutomnticnÌÌy undone if n µortion
of the uµdnte fniÌs.
Transactional tables require more disk space, memory usage, and processor usage
than tables.
The exnmµÌe dntnbnse wiÌÌ not need enhnncements of trnnsnctionnÌ tnbÌes, there-
fore the defnuÌt MyISAM tnbÌe tyµe wiÌÌ be ncceµtnbÌe.
More information on table types is available in Chapter 10.
Part I Cetting 5tarted
Ior exnmµÌe, to crente nÌÌ three of the exnmµÌe tnbÌes, you wouÌd tyµe in the foÌÌow-
ing code:
The constrnints µÌnced on the coÌumns in the tnbÌes crente n µrimnry key, which
is not tied sµecificnÌÌy to nny renÌ-worÌd use. AccordingÌy, it`s both snfe nnd desirnbÌe
to the vnÌue ns new records nre ndded to the tnbÌe.
You now hnve n working dntnbnse system thnt cnn trnck inventory for nn e-commerce
Web site.
Inserting and updating data
A dntnbnse is onÌy ns usefuÌ ns the dntn it contnins. Therefore, you need to ndd
µroducts to the inventory dntnbnse. In this section I`ÌÌ Ìook nt how to insert dntn ns
weÌÌ ns how to uµdnte the dntn, which is often |ust ns imµortnnt ns the initinÌ insert
of the dntn itseÌf.
Inserting data
You`re rendy to insert n few records into the dntnbnse. You`ÌÌ nccomµÌish this tnsk
vin the MySQL CLI. You cnn insert dntn into n dntnbnse vin n number of methods
incÌuding imµorting from n fiÌe or inserting through n µrogrnm or scriµt. Those toµ-
ics nre covered eÌsewhere in this book. Ior now, the MySQL CLI wiÌÌ work becnuse
you nre onÌy going to ndd n few records. The bnsic syntnx for nn insert is ns foÌÌows:
Cther syntax for the insert statement is discussed in Chapter 9 and in Appendix A.
Chapter 6 5tarting My5OL
The keyword deÌnys the insert untiÌ no other cÌients nre rending
from the tnbÌe. Use of the keyword is not recommended for
tnbÌe tyµes becnuse simuÌtnneous inserts nre not µossibÌe in such usnge.
Use the keyword if some cÌients cnnnot wnit for nn insert to comµÌete.
This keyword onÌy works with nnd tnbÌe tyµes. The cÌient receives nn
for the stntement immedinteÌy, nnd the insert is run when the tnbÌe is not in use
by nnother thrend.
Sµecifying the keyword cnuses duµÌicnte rows to be ignored nnd not
entered when n vnÌue coÌÌides with n µrimnry key or unique vnÌue. If this keyword is
not sµecified, nn error occurs nnd the insert is nborted. It is imµortnnt to note thnt
records wiÌÌ be inserted uµ to the record where the coÌÌision occurred. Ior exnmµÌe,
if you imµort n number of records nnd n coÌÌision occurs nt record number 482, nÌÌ
records uµ to number 482 wiÌÌ be inserted into the dntnbnse.
The keyword is not required, though it cnn be usefuÌ for imµroving rendnbiÌity.
If you don't want to insert values into all columns in a table, specify the column
names in parentheses, separated by commas, before you type the required
You cnn now insert n few rows of dntn into the exnmµÌe dntnbnse, the SQL for the
insert is ns foÌÌows:
The snmµÌe dntn |ust given shows the most common tyµe of insert. Notice thnt you
µÌnced the keyword in the first vnÌue. RecnÌÌ thnt the first coÌumn in the tnbÌe
definition is , which is nn nuto-incrementing fieÌd, therefore, it is not
ncceµtnbÌe to enter n vnÌue for this fieÌd. The keyword is used ns n µÌncehoÌder
in this exnmµÌe nnd wiÌÌ be substituted nutomnticnÌÌy with the correct vnÌue by
5eIecting data
8ecnuse seÌecting is nt Ìenst ns common ns inserting, I`ÌÌ |umµ nhend sÌightÌy nnd
use n simµÌe stntement. Iigure 6-6 shows the three records you |ust
Part I Cetting 5tarted
Figure 6-6: Sample output of a basic SELECT statement
For the full syntax of the statement, see Chapter 9.
Since I`m Ìooking to |umµstnrt your usnge of MySQL, the bnsic syntnx for the
stntement is ns foÌÌows:
The exnmµÌe nbove seÌects nÌÌ coÌumns nnd rows from the µroduct tnbÌe.
Use of the cÌnuse modifies the seÌect stntement to Ìook onÌy for rows thnt
mntch the . Ior exnmµÌe, if you wnnted to Ìook for µroducts thnt
hnd n µrice Ìess thnn $8O.OO you couÌd issue the stntement in Iigure 6-7.
Figure 6-7: Selecting records that show a price less than $30.00.
Chapter 6 5tarting My5OL
The cÌnuse is extremeÌy usefuÌ (nnd nÌmost constnntÌy in use) whenever you
work with dntn in n MySQL dntnbnse.
The cÌnuse modifies the resuÌts of the seÌect by ordering the coÌumns by
simiÌnr dntn. The cÌnuse nrrnnges the resuÌting dntn from n seÌect stnte-
ment into the order sµecified by the order-by cÌnuse. Ior exnmµÌe, to seÌect nÌÌ the
µroducts in order by µrice (from Ìowest to highest), you issue the stntement Ìike
the foÌÌowing (its resuÌts nre shown in Iigure 6-8):
Figure 6-8: Selecting records in a certain order
It just happens that the price is in order of product ID for the example database.
Such a neat result rarely happens with live data.
If you hnd n Ìnrge nmount of dntn in n tnbÌe nnd you needed to Ìook nt the first n
rows of dntn, you couÌd do so by ndding the cÌnuse onto the end of the
stntement. An exnmµÌe is shown in Iigure 6-9.
Figure 6-9: Limiting rows of a SELECT statement
Part I Cetting 5tarted
There are many more options for the statement. Those options, along
with additional coverage of the , , , and
clauses, appear in greater detail in Chapter 9 and in Appendix A.
Updating data
Uµdnting your dntn is |ust ns imµortnnt ns inserting the originnÌ dntn ~if not more
so. CommonÌy used syntnx for the stntement Ìooks Ìike this:
Ior exnmµÌe, to uµdnte the µrice of one of the µroducts you couÌd do the foÌÌowing:
Iigure 6-1O shows the outµut of n stntement thnt ennbÌes the ndministrntor
to Ìook nt thnt µroduct nfter uµdnting.
Figure 6-10: The updated product is now shown in the database
If you wnnted to uµdnte both the µrice nnd qunntity of n µroduct, you couÌd do so
with the foÌÌowing exnmµÌe:
Iigure 6-11 shows the finnÌ tnbÌe. Notice the µrice for the
is once ngnin $14.9b nnd the qunntity is now 6O.
Chapter 6 5tarting My5OL
Figure 6-11: The final table layout after updates
Preparing a new user for access to the database
Uµ untiÌ now you`ve been doing the inserts, seÌects, nnd uµdntes in the inventory
dntnbnse ns the user. RecnÌÌ (from n bit enrÌier in this chnµter) thnt you ndded n
user to the dntnbnse but you couÌdn`t grnnt nny nccess rights since you didn`t hnve
the dntnbnse buiÌt. It`s now time to nÌÌow the new user nccess to the
Since you`ve nÌrendy ndded the user nccount, you cnn utiÌize the stntement
to revise the µermissions nnd µriviÌeges for thnt user. If you nre stiÌÌ in the MySQL
CLI, connect to the dntnbnse cnÌÌed by tyµing the foÌÌowing:
The stntement shouÌd hnve simiÌnr outµut to this:
You nre now connected to the dntnbnse, which hoÌds the grnnt tnbÌes for
µriviÌeges within the server ncross nÌÌ dntnbnses.
You could have remained connected to the database and still granted
privileges. For simplicity's sake (and to save time in the jumpstart), I had you con-
nect to the database instead.
Since you grnnted the µriviÌege for the new user in n µrevious section, the
bnsic frnmework hns nÌrendy been crented for us within the user tnbÌe. To verify
thnt the user exists, issue the foÌÌowing query:
Part I Cetting 5tarted
You shouÌd see outµut simiÌnr to the Iigure 6-12.
Figure 6-12: The new user in the database server
If you don`t see the outµut shown in Iigure 6-12 when the query hns finished, you
mny wnnt to review the ¨Adding Users to MySQL" section in this chnµter nnd do
some troubÌeshooting.
Assuming thnt you hnve the snme outµut ns given in Iigure 6-12, it`s now time to
modify the µriviÌeges for this user nccount so you cnn connect to the
dntnbnse nnd µerform the necessnry oµerntions snfeÌy. The user nccount must be
nbÌe to seÌect rows from the dntnbnse, ns weÌÌ ns insert, uµdnte, nnd deÌete records.
The stntement thnt grnnts these µriviÌeges Ìooks Ìike this:
Lxit the MySQL CLI by tyµing or . Reconnect ns the new user, Ìike this:
You shouÌd now be µromµted for the µnssword thnt you used to crente the user.
Uµon entering the µnssword you wiÌÌ be grnnted nccess to the inventory dntnbnse.
Test out your new µriviÌeges by issuing n simµÌe query.
Your resuÌts shouÌd be simiÌnr to the exnmµÌe in the µrevious section.
You now hnve n simµÌified version of nn eÌectronic-commerce dntnbnse.
AItering tabIes
RegnrdÌess of how much time, money, nnd effort is µut into dntnbnse design,
inevitnbÌy dntnbnses need some redesigning or modificntion now nnd then. The
renson is simµÌe: 8usiness ruÌes chnnge. The wny you use dntn ~nnd the wny dntn
is gnthered nnd stored~chnnges ns time goes by. MySQL nÌÌows the dntnbnse
Chapter 6 5tarting My5OL
ndministrntor to chnnge the Ìnyout of tnbÌes within n dntnbnse ~ndding, removing,
or modifying coÌumns ~vin the stntement. The bnsic syntnx of this
commnnd is ns foÌÌows:
Common vnrinbÌes to use with the stntement
incÌude the foÌÌowing:
For more about variables, see Chapter 9.
The modifier hnndÌes instnnces where there nre duµÌicnte vnÌues for n
coÌumn thnt is being modified to n tyµe where uniqueness is enforced. With
sµecified the first row is keµt where vnÌues coÌÌide nnd nÌÌ others nre discnrded. If
is not sµecified nnd n coÌÌision occurs between two vnÌues, the chnnge is
nborted nnd nny sµecified chnnges nre roÌÌed bnck.
The dntnbnse shows thnt the tnbÌe is not tied to the
tnbÌe in nny wny, there`s no convenient wny to Ìink n µroduct with n mnnufnc-
turer. This wns n µurµosefuÌ fÌnw in the dntnbnse design so you couÌd use the
stntement to modify the µroduct tnbÌe nnd remedy this situntion. Irom the
MySQL CLI, enter the foÌÌowing commnnd:
If you`ve foÌÌowed nÌong thus fnr, you shouÌd receive nn error messnge when you
µerform this oµerntion. Thnt`s becnuse you connected to the MySQL
dntnbnse ns the you crented~but you didn`t grnnt thnt user the µriviÌege
to nÌter tnbÌes. The error messnge you receive shouÌd Ìook Ìike this:
Disconnect from the CLI nnd reconnect to the dntnbnse ns the user:
When you run the stntement from nbove ngnin you shouÌd hnve much
better Ìuck nnd the dntnbnse wiÌÌ now be uµdnted so thnt you cnn
Part I Cetting 5tarted
incÌude n mnnufncturer ID in the tnbÌe. However, since you nnmed the
coÌumn the snme in both the µroduct nnd the tnbÌes, you
shouÌd µrobnbÌy rennme the coÌumn in the tnbÌe so
you don`t get them mixed uµ Ìnter. Here`s the necessnry commnnd:
After you`ve run this commnnd, disconnect from the CLI nnd reconnect ns the
thnt you crented enrÌier.
Describing tabIes
You shouÌd now be connected vin the MySQL CLI ns the usernnme thnt you
crented enrÌier. A descriµtion of n coÌumn or coÌumns in nny tnbÌe is nvniÌnbÌe when
you issue the stntement. Its bnsic syntnx is ns foÌÌows:
The statement may be abbreviated to and like other statements
and commands in MySCL, it is not case-sensitive.
You cnn use the oµtionnÌ nnd nrguments to obtnin descriµ-
tions of the coÌumn or coÌumns sµecified.
The stntement (which works much Ìike the stntement) shows the
coÌumns in n tnbÌe, though it`s quicker to use the stntement (or even its
nbbrevintion) to do so. The commnnd syntnx Ìooks Ìike this:
Ior exnmµÌe, Iigure 6-18 shows the chnnges you mnde in the Ìnst section, using the
Figure 6-13: Using desc to describe a table layout
Chapter 6 5tarting My5OL
The snme commnnd using the stntement is ns foÌÌows:
An exnmµÌe of n coÌumn senrch uses the foÌÌowing query to see nÌÌ coÌumns
in the tnbÌe thnt stnrt with the Ìetter (the outµut is shown in Iigure 6-14):
Figure 6-14: Using a wildcard in a DESCRIßE statement
The snme stntement using the stntement Ìooks Ìike this:
Looking at other database objects
The µrevious section covered the stntement ns weÌÌ ns the stnte-
ment for Ìooking nt coÌumn informntion within n tnbÌe. Using the stntement,
you cnn get n Ìist of dntnbnse ob|ects. This section Ìooks nt some tyµicnÌ nnd usefuÌ
exnmµÌes of this stntement.
Full coverage of the statement is in Chapter 9.
Consider the foÌÌowing commnnd ns nn initinÌ exnmµÌe:
This stntement shows nÌÌ the dntnbnses in MySQL. If n wiÌdcnrd is sµecified, the
stntement returns dntnbnses mntching the wiÌdcnrd, if nny.
The capability of merely looking at the names of the databases does not imply that
the current user has permissions to connect or use those databases.
Part I Cetting 5tarted
To see the tnbÌes in detniÌ, you wouÌd issue the foÌÌowing commnnd:
The stntement is very usefuÌ to find out nnmes of tnbÌes in the
current dntnbnse or nny dntnbnse through the use of the modifier.
Sometimes you mny hnve to dumµ tnbÌe structure if you wnnt to recrente the tnbÌes
Ìnter (or on nnother system) for some different use. Ior exnmµÌe, ns shown in
Iigure 6-1b, some outµut from the stntement from the
dntnbnse Ìooks Ìike this:
Figure 6-15: Cutput of the SHCW CREATE TAßLE statement for the
product table
With the informntion from the stntement, the dntnbnse ndmin-
istrntor couÌd coµy the outµut to crente n coµy of the tnbÌe or snve the outµut for
Ìnter use.
This chnµter gnve n brief overview of some of the most common tnsks invoÌved in
crenting nnd mnnnging n dntnbnse.
is n usefuÌ commnnd for obtnining stntus informntion of the
server, chnnging µnsswords, kiÌÌing server µrocesses, nnd shutting down the
server itseÌf.
Chapter 6 5tarting My5OL
8nsic security incÌudes not onÌy crenting strong µnsswords, but nÌso grnnting
users onÌy those µriviÌeges thnt nre necessnry to comµÌete their tnsks.
You cnn crente n dntnbnse crention by using or by issuing the
nµµroµrinte commnnds from the MySQL Commnnd-Line Interfnce (CLI).
Crenting nnd nÌtering tnbÌes ns weÌÌ ns inserting nnd uµdnting dntn is n com-
mon tnsk in MySQL.
The stntement is nnother versntiÌe commnnd, used frequentÌy in the
course of ndministering n MySQL system.
and 0esign
hough mnny dntnbnse books begin with n chnµter on
dntnbnse conceµts nnd design, we get our hnnds dirty
with whnt you shouÌd know both with dntnbnses nnd with
MySQL in µnrticuÌnr. However, the underÌying conceµts of
dntnbnses nnd their design nre imµortnnt.
Concepts of Databases
Dntnbnses nre mnny things to mnny µeoµÌe. It is n mistnke to
sny thnt nÌÌ dntnbnses nre eÌectronic. Some other dntnbnses
incÌude n Ìibrnry nnd n reciµe cnrd fiÌe.
What is data!
Dntn is |ust nbout nnything you cnn imngine onJ ouoniify. Ior
exnmµÌe, the records nnd numbers you keeµ in n checkbook
register nre dntn. The stnts you write down if you keeµ score
nt n bnsebnÌÌ gnme nre dntn.
Ior our µurµoses, I ignore checkbook registers nnd concen-
trnte on the eÌectronic form of dntn. However, you couÌd enter
µersonnÌ checks or bnsebnÌÌ stnts into n comµuter dntnbnse
µrogrnm. At the bnsic ÌeveÌ, dntn is dntn.
What is a database!
Dntnbnses nre not simµÌy eÌectronic µÌnces to store dntn. As
nÌrendy nÌÌuded to, thinking of dntnbnses in terms not Ìimited
to comµuters is one of the first steµs to understnnding the
ln Ihis Chopler
Comporlng concepls
ol doloboses
Creollng o dolobose
requlremenls ond
dellnlng loglcol
physlcol deslgn ond
C H A P I E k
Part I Cetting 5tarted
MySCL is not a database. It is software for creqt/nq qnd mqnqq/nq a database.
Dntnbnses keeµ informntion in ioblcs. A tnbÌe is n structure consisting of nt
Ìenst one coÌumn, but usunÌÌy mnny more. A dntnbnse is then n coÌÌection of
one or more tnbÌes of reÌnted informntion. Sorting, indexing, nnd queries
orgnnize dntn to he̵ the dntnbnse user.
The Ìetters SQL stnnd for Structured Query Lnngunge.
Why use a Database!
Someone much wiser thnn I nm snid, ¨AÌwnys use the right tooÌ for the |ob" ~nnd it`s
no Ìess true in the worÌd of comµuting. I`ve seen countÌess uses of nµµÌicntions such
ns sµrendsheets nnd word µrocessors (instend of dntnbnses) to store dntn. Ior nn
nnnunÌ hoÌidny cnrd Ìist, this is fine, the time required to set uµ n dntnbnse is µrobn-
bÌy out of µroµortion to the modest nmount of dntn invoÌved. In the business worÌd,
however, n sµrendsheet is not nn ncceµtnbÌe tooÌ for storing Ìnrge nmounts of dntn.
Ior such nµµÌicntions ns µroduct cntnÌogs nnd customer informntion, n dntnbnse is
by fnr the best method of storing nnd retrieving dntn. Dntnbnses offer n wny to uti-
Ìize dntn efficientÌy.
Most enterµrise-ÌeveÌ dntnbnses must be crented vin softwnre designed for the µur-
µose: n ReÌntionnÌ Dntnbnse Mnnngement System (RD8MS). Such µrogrnms, incÌud-
ing MySQL, suµµort ironsociionol ioblc iypcs ÷tnbÌes designed to hnndÌe the
frequent uµdntes nnd modificntions thnt eÌectronic commerce entniÌs. Lnch oµern-
tion µerformed on dntn within n dntnbnse is known ns n ironsociion.
A transactional system can recreate its steps in case of data corruption. In the
event of a system crash, data could be restored from the last tape backup and
then the transaction log could be played against the database to restore the data
to its condition just before the system crash.
Transactional tables are not completely free from the risk of data loss. Even the
best RDßMS cannot offer a 100-percent guarantee that no data loss will occur in a
catastrophic system failure.
A successfuÌ RD8MS meets the AClD test for these issues:
Atomicity: When n trnnsnction is sent from the user to the dntnbnse server, the
oµerntion is either committed fuÌÌy or roÌÌed bnck. In other words, if the hnrd
disk cnn`t hoÌd the whoÌe trnnsnction, the trnnsnction wouÌd be roÌÌed bnck ns
if it hnd never hnµµened. In this mnnner, dntn cnn nÌwnys be keµt consistent.
Consistency: Oµerntions thnt vioÌnte n ruÌe or n simiÌnr mechnnism nre not
committed to the dntnbnse. If n user doesn`t hnve nccess µermission,
nttemµts to write to the tnbÌe nre re|ected.
Chapter 7 Database Concepts and Design
lsolation: An oµerntion on the dntnbnse is comµÌete before nnother oµerntion
becomes nwnre of it. If n user is ndding records to tnbÌes whiÌe nnother user is
rending from the snme tnbÌes, the render isn`t shown resuÌts from µnrtinÌ oµer-
ntions. Such µnrtinÌ informntion couÌd Ìend to inconsistent nnd confusing
resuÌts for the render.
Durability: Once n trnnsnction is committed to the dntnbnse, it is gunrnnteed to
be there. If n cntnstroµhic event hnµµens to the disk, the dntnbnse wiÌÌ stiÌÌ hoÌd
thnt trnnsnction (nssuming no other hnrdwnre fniÌure cnuses n disk corruµtion).
How are databases used!
Dntnbnses nre used in nÌÌ nrens of business. Comµnnies trnck informntion nbout
their customers inside of dntnbnses. Lver wonder why insurnnce costs more in
some geogrnµhicnÌ nrens thnn others" 8ehind the nnswer is n dntnbnse. Insurnnce
comµnnies keeµ genernÌ cÌnim informntion so they mny sort nnd query the dntn to
find µntterns thnt exhibit higher risks ~nnd µnss the cost of those risks on to the
customer ns higher µremiums.
Dntnbnses hnve nÌso been there for the exµÌosive growth of the Internet. OnÌine
shoµµing is driven by dntnbnses ~some of them running on MySQL. When you
senrch for the Ìntest Vnn HnÌen CD nt your fnvorite onÌine music store, your senrch
is hnnded bnck to n dntnbnse thnt then Ìooks uµ nnd retrieves the right informntion,
hoµefuÌÌy within n few seconds. Dntnbnses cnn retrieve informntion Ìightning-quick
nnd most dntnbnse server imµÌementntions, incÌuding MySQL, suµµort rcplicoiion
so thnt the dntnbnse ndministrntor cnn ndd more servers to hnndÌe requests.
Dntnbnses nre becoming more visibÌe in Ìnw enforcement. Dntnbnses to nid Ìnw
enforcement nre nothing new. (Wntching nn eµisode of Droµnci from the Sixties, you
cnn see the use of µunch cnrds to senrch for SocinÌ Security records). 8ut dntnbnses
nre more wideÌy used nnd in wnys bnreÌy imngined when 1nck Webb cnught teÌevi-
sion bnndits.
Database Design
Doiobosc Jcsiµn is the µrocess of determining nnd orgnnizing the informntion to
trnck. Mnny iterntions of n dntnbnse design occur ns you try to nchieve nn efficient
design nnd mnximize your use of resources.
Many simple database applications don't need a strict database design. The effort
isn't warranted for the application. I may be invoking the ire of traditional database
administrators and designers by stating this. However, spending three months in
design meetings for a database that is used once a month for non-critical func-
tions is a waste of resources. For complicated business processes, I strongly rec-
ommend spending time designing the database.
Part I Cetting 5tarted
The µrocess of designing n comµÌicnted dntnbnse correctÌy is not ensy. It tnkes time
nnd effort, but the resuÌt is worth it. Dntn modeÌing is usunÌÌy the first steµ in the
µrocess. This incÌudes defining the business µrocesses nnd buiÌding nn Lntity
ReÌntionshiµ Dingrnm.
One of the first µrocesses to design n dntnbnse is to meet with the end user of the
dntnbnse or dntn. If you nre thnt µerson, hoÌd n meeting with yourseÌf. Offer yourseÌf
refreshments, too. If you nre meeting with cÌients (internnÌ or externnÌ), µreµnre to
get ns much informntion ns µossibÌe nbout the business µrocess or dntnbnse to be
designed. The extrn work nt this stnge goes n Ìong wny townrds mnking the
dntnbnse successfuÌ. A qunÌity dntn modeÌ ensiÌy trnnsÌntes into n dntnbnse.
Ihe Database Life CycIe
LsµecinÌÌy in the business worÌd, n dntnbnse system behnves much Ìike n Ìiving
thing. Lnch stnge of its Ìife cycÌe hns distinctive concerns nnd tnsks thnt fnÌÌ into n
rough sequence much Ìike the foÌÌowing:
1. Requirements analysis: This first steµ is mnde uµ of whnt seemingÌy endÌess
meetings thnt nnnÌyze whnt is required for the new dntnbnse. The owners nnd
users of the dntnbnse define their business µrocesses nnd document the enti-
ties, nttributes, nnd reÌntionshiµs thnt wiÌÌ mnke uµ the dntnbnse.
This nnnÌysis is most imµortnnt to the success of the dntnbnse µro|ect. Without
n comµÌete µicture of the business µrocess ~or fuÌÌ documentntion of whnt
the nµµÌicntion must hnve nnd be ~the µro|ect wiÌÌ fniÌ. RegnrdÌess of how
much time goes into the next µhnses of the µro|ect, it`s hended for disruµtion
(nt best) or disnster (nt worst) if you overÌook n mn|or item in this steµ.
Sometimes the systems nnnÌyst (you, ns ndministrntor) cnn get so wrnµµed uµ
in the µro|ect itseÌf thnt he or she negÌects to µut much thought into the end
user. I`ve found it most he̵fuÌ to invoÌve the nctunÌ end user of the nµµÌicn-
tion during the first µhnse of the design~through interviews nnd observn-
tion. In most instnnces, you nre designing n reµÌncement or imµrovement for
nn existing system. The end users nre your best source of idens for imµrove-
ments in the next version.
InvoÌvement of the end user cnn come in mnny forms. Lnd users cnn be in
µÌnnning meetings where the nµµÌicntion functions nnd needs cnn be deter-
mined. However, n more successfuÌ method for Ìenrning how nn nµµÌicntion is
used nnd cnn be imµroved is obscrcoiion of the end users doing their |obs.
Mnny times those being observed wiÌÌ nÌter their behnvior, either consciousÌy
or subconsciousÌy, thus Ìessening the effectiveness of the informntion gnth-
ered. I recommend n combinntion of interviews or meetings, nnd direct obser-
vntion for n successfuÌ nnnÌysis.
2. Logical design of the database: This steµ Ìnys out the ÌogicnÌ structure of the
µrogrnm in terms of its tnbÌes nnd their reÌntionshiµs. Three tnsks µredominnte:
º Designing the Ìnyout of the dntnbnse tnbÌes (often stnrting with nn Lntity-
ReÌntionshiµ Dingrnm)
Chapter 7 Database Concepts and Design
º NormnÌizing the cnndidnte tnbÌes
º Writing the SQL to µroduce the dntnbnse nnd tnbÌes
This second stnge cnn quickÌy sÌow n µro|ect to n snniÌ`s µnce. If you get too
mnny cooks in the kitchen during the first µhnse, the µroverbinÌ dntnbnse
souµ cnn sµoiÌ. Keeµing the second µhnse orgnnized nnd on trnck tnkes effort.
Mnny times µeoµÌe wiÌÌ wnnt to iternte over n dntnbnse design not renÌizing
thnt business ruÌes chnnge nnd the dntnbnse wiÌÌ hnve to chnnge with it.
3. Physical design of the database: This steµ invoÌves nctunÌÌy deveÌoµing nnd
µÌnnning the µhysicnÌ Ìnyout of the dntn within your network nnd system
toµoÌogy. In n distributed environment, this steµ incÌudes
º PÌnnning for dntn distribution
º Orgnnizing such µhysicnÌ eÌements ns memory use, tnbÌe-cnche size, nnd
buffer size
MySCL server variables are discussed in a later chapter.
4. lmplementation and subsequent modification of the database: During these
Ìnst steµs in the dntnbnse Ìife cycÌe, you enter the SQL or other Ìnngunge into
your dntnbnse, nÌong with other scriµts nnd mnnngement tooÌs thnt you`ve
deveÌoµed whiÌe µÌnnning nnd designing the dntnbnse.
If nÌÌ goes weÌÌ, then by the time you rench this Ìnst steµ, you`ve found nÌÌ the
ob|ects thnt shouÌd be incÌuded in the dntnbnse. Don`t worry if you suddenÌy imµÌe-
ment the dntnbnse nnd find thnt you shouÌd ndd n coÌumn to nÌÌ its tnbÌes. MySQL
syntnx cnn nÌter tnbÌe structure rnther µninÌessÌy.
Regardless of how much research and planning you do, a long-term application
will must change to be useful. ßusiness rules and processes change over time, so
the database and applications must change, too. Cood planning in the beginning
will make those changes easier and less costly.
LogicaI Design
After you gnther informntion on the business µrocess nnd items to be documented,
you nre rendy to crente the loµicol Jcsiµn. This mnster µÌnn for the ÌogicnÌ entities
(nnd their reÌntionshiµs) thnt mnke uµ the dntnbnse shouÌd be ns comµÌete nnd
thorough ns µossibÌe. A good ÌogicnÌ design hns mnny fncets nnd µhnses, incÌuding
the nnnÌysis of reÌntionshiµs nnd the setting of constrnints.
Entities and attributes
At n bnsic ÌeveÌ of n dntn modeÌ nre cniiiics ~ob|ects thnt you nre interested in ns
µnrt of the dntn modeÌ you nre crenting. Ior exnmµÌe, if you were mnking nn onÌine
Part I Cetting 5tarted
store, you wouÌd wnnt to know the customer`s nnme. Siccc Suchrinµ is nn exnmµÌe
of nn entity. The sµecific nnme, Steve Suehring, is the entity. Ior n successfuÌ onÌine
store, you µrobnbÌy wnnt more thnn one customer. Therefore you shouÌd obsiroci the
entity into n genernÌ cniiiy iypc. Ior this exnmµÌe, the entity tyµe wouÌd be Cusiomcr.
Lntities hnve identifying qunÌities ~oiiribuics. Ior exnmµÌe, the Cusiomcr entity of
Steve Suehring hns such nttributes ns height, weight, home nddress, nnd teÌeµhone
number. To mnnnge nÌÌ the nttributes of nÌÌ the entities, you nbstrnct the nttributes
into oiiribuic iypcs thnt become µnrt of nÌÌ the entity tyµes.
At the initinÌ meeting(s) for µroducing n dntn modeÌ, you define the entities ~nnd
subsequent entity tyµes ~thnt you nre interested in. In nddition, you wiÌÌ most
ÌikeÌy stnrt determining nttributes nnd nttribute tyµes ns weÌÌ. Ior now, the entity
tyµes cnn be written down ns n simµÌe Ìist. Ior exnmµÌe, suµµose you know thnt
both customer informntion nnd µroduct informntion nre to be keµt in the dntnbnse.
You couÌd crente n Ìist somewhnt Ìike the one given here ~which, though incom-
µÌete, works fine for n bnsic site:
Thnt gives you three entity tyµes. At this µoint in the resenrch µrocess, I usunÌÌy
|umµ right into Ìisting some nttribute tyµes for ench entity tyµe, Ìike this:
SuµµÌementnÌ Address
TeÌeµhone Number
L-mniÌ Address
Credit Cnrd Number
Credit Cnrd Lxµirntion
Nnme on Cnrd
Product Nnme
Product Price
Qunntity on Hnnd
Product Cntegory
Chapter 7 Database Concepts and Design
You can add fun things like Ratings and Reviews for products later. (And if the
attribute types in the list are starting to resemble column headings, that's not acci-
dental. More about that later.)
Uµon further review, I beÌieve Nnme shouÌd be broken into two seµnrnte nttributes,
Iirst Nnme nnd Lnst Nnme. I nÌso beÌieve TeÌeµhone Number shouÌd be broken
nµnrt to nccount for nren code nnd number. (I nssume thnt the onÌine store onÌy
shiµs within the United Stntes, otherwise I wouÌd ndd Country Code ns weÌÌ.) It
wouÌd nÌso be usefuÌ to know the credit cnrd tyµe, even though this informntion cnn
usunÌÌy be gÌenned from the digits of the cnrd. Hnving the credit-cnrd tyµe nÌÌows
some soniiy chcchinµ (the use of n sµecinÌ µrogrnm to ferret out nnd reµort system
µrobÌems) Ìnter in the µrocess. In nddition, it wouÌd be usefuÌ to keeµ informntion
nbout the mnnufncturers such ns their nddress nnd contnct informntion ns weÌÌ.
Here`s whnt the new nttribute tyµe Ìist Ìooks Ìike:
Iirst Nnme
Lnst Nnme
SuµµÌementnÌ Address
Aren Code
TeÌeµhone Number
L-mniÌ Address
Credit Cnrd Tyµe
Credit Cnrd Number
Credit Cnrd Lxµirntion
Nnme on Cnrd
Product Nnme
Product Price
Qunntity On Hnnd
Mnnufncturer Nnme
Mnnufncturer Address
Mnnufncturer City
Mnnufncturer Stnte
Mnnufncturer Ziµ
Part I Cetting 5tarted
Mnnufncturer Contnct
Mnnufncturer Aren Code
Mnnufncturer TeÌeµhone Number
Product Cntegory
Now thnt I hnve n Ìist of entity tyµes nnd nttribute tyµes for the dntn modeÌ, I cnn
stnrt to nnnÌyze how they reÌnte.
In my exnmµÌe, it`s obvious thnt some nttribute tyµes reÌnte to ench other. Ior
exnmµÌe, ench Iirst nnd Lnst Nnme µnir cnn hnve one or more Addresses,
SuµµÌementnÌ Addresses, Cities, Stntes, nnd Ziµs.
As shouÌd be evident, Iirst Nnme}Lnst Nnme (which I wiÌÌ refer to ns Customer
Nnme for brevity`s snke), Address, SuµµÌementnÌ Address, City, Stnte, Ziµ (which I
wiÌÌ refer to simµÌy ns Address), nnd so on nre nÌÌ items reÌnting to the Customer
entity tyµe. It quickÌy becomes cÌenr thnt I couÌd go down n sÌiµµery sÌoµe becnuse
one Customer Nnme couÌd hnve more thnn one Address nnd one Address couÌd
hnve more thnn one Customer Nnme.
However, whnt mny nµµenr cÌenr is not necessnriÌy ns cÌenr ns you mny think. WhiÌe
it is true thnt n Customer Nnme couÌd hnve more thnn one Address, n Customer
Record is mnde uµ of one nnd onÌy one Address. Whnt nµµenred to be n µrobÌem in
the design is nctunÌÌy n fnÌse reÌntionshiµ.
ßy adding other entity types, you can add support for more than one address to
allow the customer to ship to different addresses.
Lnch reÌntionshiµ hns n degree of corJinoliiy. In other words, there cnn be one nnd
onÌy one Mnnufncturer of n certnin µroduct, but thnt Mnnufncturer cnn hnve mnny
µroducts. Determining the reÌntionshiµs is nn nrt thnt tnkes µrnctice. Thinking
through the business µrocess thoroughÌy wiÌÌ he̵ to work out the true reÌntion-
shiµs for your dntn modeÌ.
Iigure 7-1 shows nn exnmµÌe of reÌntionshiµs in nn Lntity-ReÌntionshiµ Dingrnm. The
exnmµÌe iÌÌustrntes the reÌntionshiµ between mnnufncturer nnd µroducts.
Lnch mnnufncturer cnn hnve one or more µroducts, reµresented by the
crow`s-foot Ìine nenr the Product box.
Lnch µroduct cnn nnd must hnve one nnd onÌy one mnnufncturer, ns reµre-
sented by the singÌe Ìine nenr the mnnufncturer box.
Chapter 7 Database Concepts and Design
The C shape near the Product entity type indicates that the existence of a product
is not required for a Manufacturer to exist in the database. This C is missing from
the Manufacturer side of the relationship because a manufacturer is required if
there is a product in the database.
Figure 7-1: Relationships among some example entity types
Entity-reIationship diagrams
With n Ìist of entity nnd nttribute tyµes for n dntn modeÌ in µÌnce ~nnd n bnsic
understnnding of how to reÌnte them to ench other ~you crente n dingrnm thnt for-
mnÌÌy shows the reÌntionshiµs of ench entity tyµe. The dingrnm simµÌy grouµs
together Ìike informntion. This wiÌÌ he̵ to normnÌize the dntn nnd understnnd the
business µrocesses, nnd µossibÌy find ndditionnÌ entities, nttributes, nnd reÌntion-
shiµs thnt must be incÌuded in the dntn modeÌ.
Souorc or rccionµulor boxes on the dingrnm reµresent entities. ReÌntionshiµs cnn be
reµresented by number of Ìine formnts.
In Ìooking ngnin nt the Ìist of nttribute tyµes in the exnmµÌe, it is evident thnt certnin
customer-reÌnted informntion is stored in the dntnbnse. My initinÌ drnft of nn Lntity-
ReÌntionshiµ Dingrnm (LRD) for the exnmµÌe dntnbnse is shown in Iigure 7-2.
AnaIysis of diagrams
As I touched on enrÌier, the mnnufncturer nnd µroduct reÌntionshiµs nre (mostÌy)
fine. One mnnufncturer cnn hnve mnny µroducts, but n given µroduct cnn hnve onÌy
one mnnufncturer. Lxnmining customer nnd credit-cnrd reÌntionshiµs in the drnft of
the LRD in Iigure 7-2, you cnn see thnt ench customer cnn hnve more thnn one
credit cnrd stored in the dntnbnse. However, ench credit cnrd cnn onÌy be nssoci-
nted with one customer. This is not whnt I wouÌd Ìike ~I wnnt the entire fnmiÌy to
crente nccounts nnd use Dnd`s credit cnrd to buy. To nÌÌevinte this µrobÌem, I must
mnke both sides of the reÌntionshiµ mnny-to-mnny. The second drnft of the LRD, in
Iigure 7-8, shows the new mnny-to-mnny reÌntionshiµ.
Manufacturer Naue
Manufacturer Address
Manufacturer Citv
Manufacturer State
Manufacturer Zio
Froduct Naue
Froduct Frice
0uantitv 0n hand
Part I Cetting 5tarted
Figure 7-2: First Draft of an ERD for the online store
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Citv
Custouer State
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Credit Card
Credit Card Tvoe
Credit Card Nuuber
Credit Card Exoiration
Credit Card Naue on Card
Manufacturer Naue
Manufacturer Address
Manufacturer Citv
Manufacturer State
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Chapter 7 Database Concepts and Design
Figure 7-3: Customers can use more than one card, and more than one customer can
use the card.
However, n mnny-to-mnny reÌntionshiµ shouÌd be broken down into two seµnrnte
one-to-mnny reÌntionshiµs. AÌong with brenking the mnny-to-mnny reÌntionshiµ
nµnrt, I must senrch for extrn nttributes thnt mny be disguising themseÌves ns
reÌntionshiµs. The resuÌt of this nnnÌysis is shown in Iigure 7-4.
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Citv
Custouer State
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Credit Card
Credit Card Tvoe
Credit Card Nuuber
Credit Card Exoiration
Credit Card Naue on Card
Manufacturer Naue
Manufacturer Address
Manufacturer Citv
Manufacturer State
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Part I Cetting 5tarted
Figure 7-4: Results from breakdown of many-to-many relationship.
One mn|or nren for imµrovement in this dntn modeÌ is in the nren of the City, Stnte
nnd Ziµ stornge. Since Ziµ codes define nnd nre nÌwnys tied to one city nnd stnte,
there is no renson to store the City nnd Stnte in both the Customer entity tyµe nnd
the Mnnufncturer entity tyµe. It wouÌd be much more efficient to mnke nnother entity
tyµe to house the City nnd Stnte nnd reÌnte thnt entity tyµe to both the Customer nnd
Mnnufncturer entity tyµes. This drnft of the LRD is shown in Iigure 7-b.
As you cnn see from the new drnft of the dntn modeÌ shown in Iigure 7-b, the Ziµ
nttribute tyµe is duµÌicnted in both the Customer}Mnnufncturer entity tyµes nnd in
the LocnÌe entity tyµe ns weÌÌ. This is so I cnn |oin or mntch the informntion
together. Ior exnmµÌe, I hnve n customer with n Ziµ code of b4481. I cnn then Ìook
uµ the city nnd stnte for the ziµ code of b4481 in the LocnÌe tnbÌe. Without the ziµ
code being stored in the Customer tnbÌe, I wouÌd hnve no wny to know where the
customer Ìives or where to shiµ their goodies!
The Ziµ Code nttribute within the Customer entity is known ns n foreign key. A for-
eign key ennbÌes you to reÌnte nn nttribute in one entity to the nttribute of nnother
entity. In this cnse, the Ziµ Code nttribute in the Customer entity tyµe is reÌnted to
the Ziµ Code nttribute of the LocnÌe entity tyµe.
8nsed on informntion nbout foreign keys, the nstute observer mny hnve nÌrendy
noticed the fÌnw in the Customer to Credit Cnrd reÌntionshiµ. There is no wny to tie
customers to their credit cnrd informntion. Lither I chnrge rnndom cnrds or don`t
chnrge nt nÌÌ. A reciµe for disnster no mntter how you Ìook nt it. I must choose n wny
to reÌnte n customer with their credit cnrd info. Customer nnme is out becnuse I
hoµe to hnve more thnn one 1ohn Smith shoµ nt my store. I must find nn nttribute
tyµe thnt wiÌÌ nÌwnys be unique within the Customer entity tyµe.
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Citv
Custouer State
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Custouer Card lnfo
Custouer CC Nuuber
Custouer CC Exoiration
Custouer Naue on Card
Credit Card Tvoe
Credit Card Tvoe
Manufacturer Naue
Manufacturer Address
Manufacturer Citv
Manufacturer State
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Chapter 7 Database Concepts and Design
Figure 7-5: Placing City, State, and Zip in another entity type makes the model
more efficient.
Mnny onÌine stores choose L-mniÌ Address ns the unique nttribute in n customer`s
informntion. I beÌieve this is n good iden, so I imµÌement my customers` e-mniÌ
nddresses to reÌnte their credit cnrd informntion to them, ns shown in Iigure 7-6.
Figure 7-6: Relating customers to their credit cards is rather important.
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Custouer Card lnfo
Custouer CC Nuuber
Custouer CC Exoiration
Custouer Naue on Card
Custouer Euail Address
Locale Citv
Locale State
Locale Zio
Credit Card Tvoe
Credit Card Tvoe
Manufacturer Naue
Manufacturer Address
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Custouer Card lnfo
Custouer CC Nuuber
Custouer CC Exoiration
Custouer Naue on Card
Locale Citv
Locale State
Locale Zio
Credit Card Tvoe
Credit Card Tvoe
Manufacturer Naue
Manufacturer Address
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Part I Cetting 5tarted
Yet nnother iterntion of the dntn modeÌ is needed becnuse I must crente n reÌntionshiµ
between the credit-cnrd tyµe nnd the credit cnrd. RecnÌÌ thnt the tyµe of cnrd couÌd
be determined by Ìooking nt the digits of the cnrd itseÌf. However, I`d Ìike to do some
error checking, so hnving the customer choose the cnrd tyµe is usefuÌ. To reÌnte cnrd
tyµe to cnrd number, I couÌd simµÌy ndd n fieÌd to the Customer Cnrd Info tnbÌe.
However, doing so wouÌd nuÌÌify nny efficiency gnined from seµnrnting those entity
tyµes. Therefore I wiÌÌ crente n Cnrd ID nttribute tyµe thnt is simµÌy nn integer. Ior
exnmµÌe, I wiÌÌ give Visn credit cnrds nn ID of 1, MnsterCnrd nn ID of 2, nnd so on.
Iigure 7-7 shows the next drnft of the dntn modeÌ.
Figure 7-7: Addition of the Card ID entity type enables joining of the Customer
Card Info and Card Type tables.
An exnminntion of the Product entity tyµe revenÌs thnt the Product Cntegory
nttribute renÌÌy doesn`t beÌong with thnt entity tyµe. Therefore I crente n new entity
tyµe for Product Tyµes. I cnn now ndd n Product ID nttribute to reÌnte thnt entity
tyµe bnck to the Product entity tyµe. The resuÌt is shown in Iigure 7-8.
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Custouer Card lnfo
Custouer CC Nuuber
Custouer CC Exoiration
Custouer Naue on Card
Custouer Euail Address
Card l0
Locale Citv
Locale State
Locale Zio
Credit Card Tvoe
Card l0
Manufacturer Naue
Manufacturer Address
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Credit Card Tvoe
Chapter 7 Database Concepts and Design
Figure 7-8: Separation of the Product Category from the Product Table
Consiroinis nre Ìimitntions or controÌs µÌnced on nttributes within nn entity. They
nre used to mnintnin order nnd keeµ the modeÌ true to the business µrocess it is
The Uniqueness constrnint is one thnt you encounter frequentÌy. Ior the onÌine
store modeÌ to work, the e-mniÌ nddress of ench customer wiÌÌ need to be unique.
AdditionnÌ nttributes within other entities nÌso must be gunrnnteed to be unique,
such ns the Ziµ Code nttributes in the LocnÌe entity.
The Uniqueness constraint is sometimes called a µr/mqrv /ev within a database
table though Uniqueness is only one of the attributes of a primary key.
An Lxclusion consiroini is n ÌogicnÌÌy excÌusive reÌntionshiµ. With such n constrnint,
one nnd onÌy one entity mny µnrticiµnte in n reÌntionshiµ with n root entity. Ior exnm-
µÌe, if you mnnufnctured widgets nnd couÌd get µnrts from nn internnÌ or externnÌ suµ-
µÌier, one nnd onÌy one suµµÌier wouÌd suµµÌy the µnrt for n sµecific order.
Any entity thnt exists nnd hns n µrimnry key must nÌso ensure thnt the µrimnry key
exists to meet the constrnint of Lniiiy lnicµriiy. Since e-mniÌ nddress is the µrimnry
key for the customer entity, if you stnrt n customer record for your onÌine store,
they must hnve nn e-mniÌ nddress to exist nt nÌÌ nccording to this constrnint.
Custouer First Naue
Custouer Last Naue
Custouer Address
Custouer Suooleuental Address
Custouer Zio
Custouer Area Code
Custouer Teleohone Nuuber
Custouer Euail Address
Custouer Card lnfo
Custouer CC Nuuber
Custouer CC Exoiration
Custouer Naue on Card
Custouer Euail Address
Card l0
Locale Citv
Locale State
Locale Zio
Credit Card Tvoe
Card l0
Manufacturer Naue
Manufacturer Address
Manufacturer Zio
Manufacturer Area Code
Manufacturer Teleohone Nuuber
Manufacturer Contact
Froduct Naue
Froduct Frice
Froduct 0uantitv 0n hand
Froduct Cateuorv
Credit Card Tvoe
Froduct Tvoe
Froduct l0
Froduct Cateuorv
Part I Cetting 5tarted
Rcfcrcniiol inicµriiy menns thnt nny foreign key thnt exists within one tnbÌe must
nÌso hnve n corresµonding row nnd µrimnry key within the reÌnted tnbÌe. Ior exnm-
µÌe, if n Ziµ Code exists within n customer`s record in the exnmµÌe, there must be n
corresµonding Ziµ Code record in the tnbÌe for referentinÌ integrity.
Long the woe of mnny n coÌÌege student Ìenrning dntnbnse conceµts, normnÌizntion
is the µrnctice of getting n dntnbnse design into n formnt with no duµÌicntions or
redundnncy of dntn within the dntnbnse so the dntnbnse oµerntes ns efficientÌy ns
µossibÌe. This hns obvious benefits of efficiency. However, it cnn nÌso µrevent
cntnstroµhic inconsistencies.
There nre five forms thnt n dntn modeÌ µnsses through on its wny to being normnÌ-
ized. Ior our µurµoses, I`ÌÌ denÌ with onÌy the first three forms. As n dntn modeÌ is
normnÌized, it is snid to be in (nnd µnss through) Iirst NormnÌ Iorm, Second NormnÌ
Iorm, Third NormnÌ Iorm, nnd so on, Ìike this:
First Normal Form (1NF). This form is nchieved when there nre no rcpcoiinµ
oiiribuics. TnbÌe 7-1 shows such n tnbÌe. Ior mnny smnÌÌ µro|ects this tyµe of
tnbÌe is fine. WhiÌe there is reµented dntn such ns the Tenm nnd Locntion, hnv-
ing the reµents doesn`t ndverseÌy nffect µerformnnce on smnÌÌ tnbÌes nnd µro-
|ects. However, if you hnd to mnke n chnnge to the Tenm for one of the µeoµÌe
in the tnbÌe, the uµdnte couÌd tnke Ìonger. AdditionnÌÌy, if you deÌete the Steve
Suehring record from the tnbÌe, you wouÌd Ìose nÌÌ of the Tenm nnd Locntion
info, resuÌting in unforeseen dntn Ìoss.
Table 7-1
IabIe in First NormaI Form
I0 Nome Locotion Loc_I0 Ieom Ieom_I0
3 Don Sutton ßaseball Hall of Fame 355 ßraves 95
4 Steve Suehring ßat ßoy 515 Dodgers 78
5 Creg Maddux ßaseball Hall of Fame 355 ßraves 95
6 !erry Rice NFL Hall of Fame 400 49ers 94
7 Mika Hakkinen Formula Cne 411 McLaren 99
8 Steve Young NFL Hall of Fame 400 49ers 94
Chapter 7 Database Concepts and Design
Second Normal Form (2NF): This form incÌudes the 1NI definition nnd
requires thnt nÌÌ nttributes of n sµecific entity deµend on the cniirc hcy coluc.
If the key vnÌue is onÌy one vnÌue, then nttributes thnt deµend on it nÌrendy
deµend on the entire vnÌue, ns shown in Iigure 7-9.
Figure 7-9: Making sure all attributes depend on the key
Third Normal Form (3NF): This form incÌudes the 2NI definition nnd requires
thnt nÌÌ nttributes of n sµecific entity JcpcnJ only on ihc hcy. not on other
nttributes. In other words, the Tenm is deµendent onÌy on the Tenm_ID, not on
the Nnme of the µerson. Iigure 7-1O iÌÌustrntes the finnÌ tnbÌes for this exnmµÌe.
Note thnt foreign-key constrnints couÌd be used to remove TnbÌe4 from the
Ferson l0
Ferson Naue
0on Sutton
Steve Suehrinu
0reu Maddux
Jerrv Fice
Mika hakkinen
Steve Younu
ßaseball hall of Faue
ßat ßov
ßaseball hall of Faue
NFL hall of Faue
Foruula 0ne
NFL hall of Faue
Teau l0
Teau Naue
Ferson l0
Loc_l0 Teau l0
Part I Cetting 5tarted
Figure 7-10: Final example tables, normalized
Data Definition Language and Data Markup Language
Doio Dcfiniiion Lonµuoµc íDDL) nnd Doio Morhup Lonµuoµc íDML) nre common
nnmes for the tooÌs nnd syntnx used to crente nnd work with n dntnbnse.
DDL defines how the dntn is nddressed. DDL exnmµÌes incÌude ,
, nnd such µriviÌege oµtions ns nnd .
DDL statements do not work with data directly.
DML stntements nctunÌÌy work with renÌ dntn. LxnmµÌes of such stntements
nre nnd .
Producing the 5OL
The Ìnst steµ of LogicnÌ Design is crention of the SQL for the dntnbnse. As this µoint,
you must mnke some imµortnnt decisions invoÌving coÌumn tyµes nnd constrnints
for the cnndidnte tnbÌes. There nre n number of coÌumn tyµes suµµorted by MySQL.
Ferson l0
Ferson Naue
0on Sutton
Steve Suehrinu
0reu Maddux
Jerrv Fice
Mika hakkinen
Steve Younu
ßaseball hall of Faue
ßat ßov
NFL hall of Faue
Teau l0
Teau Naue
Ferson l0
Loc_l0 Teau l0
Chapter 7 Database Concepts and Design
Refer to Appendix A for a complete listing of column types supported by MySCL.
RecnÌÌing Iigure 7-1O`s cnndidnte tnbÌes, I recommend using tyµe for the
coÌumns in nÌÌ tnbÌes. Iurther, I wouÌd recommend coÌumn tyµes of for the
nnme coÌumns.
Ior constrnints, the coÌumn in nÌÌ tnbÌes shouÌd be required nnd unique. This
mnkes them µrimnry keys.
To create a primary key in MySCL, you must specify the column as and
The SQL to crente the exnmµÌe tnbÌes in MySQL is ns foÌÌows:
Going bnck to my ongoing exnmµÌe of nn e-commerce Web site, the cnndidnte tnbÌes
for the structure nre crented by the foÌÌowing code:
Part I Cetting 5tarted
The coÌumn tyµe is chosen becnuse it uses sµnce more efficientÌy thnn the
tyµe. The coÌumn tyµe µnds the coÌumn with extrn sµnces to fiÌÌ the
Ìength of the coÌumn, the tyµe ndds onÌy one extrn byte to store the Ìength
of the coÌumn. Ior exnmµÌe, if the coÌumn tyµe for the coÌumn, the
dntnbnse wouÌd nÌwnys use bO bytes, regnrdÌess of whether the city wns nnmed
or . The tyµe is fine for nren-code nnd teÌeµhone-number
coÌumns (which nre nÌwnys the snme Ìength for U.S. µhone numbers). The
coÌumn tyµe is chosen for the tnbÌe`s coÌumn becnuse the µrecision
cnn be sµecified before nnd nfter the decimnÌ µoint. In the exnmµÌe, I use the (9,2)
definition thnt cnÌÌs for uµ to 9 digits before the decimnÌ nnd 2 digits nfter the deci-
mnÌ. Therefore I cnn Ìist µrices of uµ to 999,999,999.99 for µroducts in the dntnbnse.
For a summary of MySCL's column types, see Appendix A.
PhysicaI Design and ImpIementation
Once you hnve n normnÌized design, turning thnt design into the nctunÌ dntnbnse
nnd tnbÌes on the server is ensy.
Chapter 7 Database Concepts and Design
The PhysicnÌ Design µhnse is the third steµ in the dntnbnse Ìife cycÌe. Now is the
time to decide how mnny servers you nre going to use for your dntnbnse nµµÌicn-
tion, where they wiÌÌ be µhysicnÌÌy Ìocnted, nnd so on.
The finnÌ steµ nfter PhysicnÌ Design µÌnnning is to tnke the SQL stntements nnd cre-
nte the dntnbnse. Since you`ve nÌrendy designed the SQL for the normnÌized tnbÌes,
it is now n mntter of simµÌy executing the code to mnke the dntnbnse nnd tnbÌes.
There are a number of ways to import data into MySCL, many of which are cov-
ered in another chapter.
Much Ìike nn index entry in n book, nn index entry in n dntnbnse nÌÌows the server
to quickÌy Ìocnte informntion. As you crente the µhysicnÌ design of your dntnbnse,
you shouÌd choose indices thnt ncceÌernte queries nnd thus ncceÌernte the oµern-
tion of your dntnbnse server nnd nµµÌicntions.
With MySQL, nn index cnn be crented either during the initinÌ DDL to crente the
tnbÌe or during Ìnter oµerntion. An exnmµÌe of crenting the index with the initinÌ
DDL is ns foÌÌows:
To sµecify nn index nfter the initinÌ tnbÌe hns been crented, the syntnx is genernÌÌy
MySQL hns commnnds thnt cnn he̵ you determine whnt indices to crente. The
commnnd nÌÌows you to describe n stntement ns weÌÌ, to see µos-
sibÌe keys or indices to crente. Another nnme for the commnnd in this
context is the commnnd. Some dntnbnse oµerntors mny be fnmiÌinr with
one or the other of these commnnds, their functions overÌnµ somewhnt.
Ior the exnmµÌe, I`ve crented n test dntnbnse cnÌÌed thnt uses the snme
exnmµÌe tnbÌes ns the rest of the chnµter.
Part I Cetting 5tarted
I write table definitions in a text editor such as in Linux or Notepad in Windows,
as shown in Figures 7-11 and 7-12. ßy using a text editor to create long DDL and
DML commands, you can easily copy and paste them into the MySCL CLI or typing
them in through the command line. This can be a lifesaver if you run into prob-
lems with the database server (or if your syntax or spelling is wrong for a particu-
lar command).
The example database tables are on the CD-RCM so you don't have to type them
(though it is good practice).
Figure 7-11: Using vi to write DDL and DML can be a great timesaver.
Ior the indexing exnmµÌe, I cnn ndd n record into the nnd tnbÌes.
Indexing wiÌÌ usunÌÌy not he̵ n simµÌe stntement such ns
. To confirm this, you cnn try the commnnd, ns shown in
Iigure 7-18.
In Iigure 7-18, you cnn see informntion on the seÌect stntement nnd extrn informn-
tion nbout how MySQL rnn the query. Ior determining µossibÌe indices, the imµor-
tnnt µÌnce to Ìook is the coÌumn, it teÌÌs you whnt coÌumns couÌd be
crented ns nn index to imµrove the µerformnnce of the query. Ior the exnmµÌe,
MySQL did not need nny indices to efficientÌy hnndÌe the query (ns evidenced by
the in the coÌumn).
üo the
Chapter 7 Database Concepts and Design
Ior n more comµÌicnted query (shown in Iigure 7-14), MySQL beÌieves thnt it couÌd
use n µrimnry key index in the tnbÌe to boost efficiency. Since the coÌ-
umn is nÌrendy n µrimnry key, the query cnn run efficientÌy.
Figure 7-12: Notepad can be used as a source for creating long DDL and DML
Figure 7-13: Indexing usually doesn't assist with simple queries.
Part I Cetting 5tarted
Figure 7-14: The primary key index on the locale table assists MySCL
in performing this query.
To confirm the existence of the µrimnry key index on the tnbÌe, the
commnnd cnn be used (see Iigure 7-1b).
Figure 7-15: The show index command gives useful information
about indexes.
MySQL nÌÌows you to crente indexes in n number of wnys (even whiÌe crenting the
tnbÌe itseÌf), vin the commnnd or the commnnd.
Indexing and other optimizations for MySCL are discussed in Chapter 12.
Chapter 7 Database Concepts and Design
The finnÌ steµ in the dntnbnse Ìife cycÌe is imµÌementntion, which incÌudes:
Crention of the µhysicnÌ dntnbnse nnd tnbÌes on the server
Ongoing ndministrntion nnd mnintennnce of the dntnbnse
PhysicnÌÌy crenting the tnbÌes for n normnÌized dntnbnse design on the dntnbnse
server is simµÌe. The nctunÌ writing of the SQL for tnbÌe crention wns done during
the LogicnÌ Design. Now it is n mntter of executing thnt code on the server.
To crente the exnmµÌe dntnbnse, I use the tooÌ, ns shown in
Iigure 7-16. I`m highÌighting this commnnd inside n whoÌe figure to show thnt it is
normnÌ for the commnnd to return no messnge when it succeeds. If you hnve nn
error, wiÌÌ Ìet you know.
Syntax for mysqladmin is contained in Chapter 8.
Figure 7-16: The mysqladmin command returns no message upon
successful completion of a database creation.
Once the dntnbnse is crented, you cnn crente the tnbÌes within the dntnbnse bnsed
uµon the SQL you wrote during the ÌogicnÌ design µhnse. You`re rendy to enter the
DDL to crente the tnbÌes into the MySQL CLI to crente the tnbÌes.
CongrntuÌntions, the dntnbnse is comµÌete! However, the dntnbnse Ìife cycÌe isn`t
over. You now hnve to mnintnin the dntnbnse server by
Mnking sure queries nre oµernting ns efficientÌy ns µossibÌe
Checking tnbÌe henÌth nnd reµniring tnbÌes when needed
ActiveÌy nµµÌying bug fixes nnd security nudits.
Part I Cetting 5tarted
Since databases are practically living things, changes often are required in the life
cycle. Using DDL statements like alter table, you can keep the database useful as
business rules and processes change.
Dntn is renÌÌy nnything you cnn imngine nnd qunntify. Though it`s not |ust informn-
tion in n comµuter or within n dntnbnse, ReÌntionnÌ Dntnbnse Mnnngement Systems
(of which MySQL is nn exnmµÌe) mnke Ìnrge nmounts of dntn efficientÌy retrievnbÌe
nnd usnbÌe.
A dntnbnse is n grouµ of orgnnized informntion, not necessnriÌy on n comµuter.
The dntnbnse Ìife cycÌe incÌudes nnnÌysis, ÌogicnÌ design, µhysicnÌ design, nnd
imµÌementntion of the dntnbnse.
Lntities, Attributes, nnd ReÌntionshiµs nre the ob|ects thnt mnke uµ n dntnbnse
An Lntity-ReÌntionshiµ Dingrnm (LRD) modeÌs the Ìnyout of the entities,
nttributes, nnd reÌntionshiµs. The LRD cnn be trnnsformed ensiÌy into normnÌ-
ized form nnd then into the µhysicnÌ Ìnyout of the dntnbnse.
NormnÌizntion is the µrocess of reducing redundnncy nnd wnste in n dntnbnse
whiÌe imµroving µerformnnce nnd µossibÌy removing errors.
Indexing he̵s n dntnbnse to quickÌy retrieve informntion.
The nctunÌ imµÌementntion of the dntnbnse onto the server is the first steµ in
the finnÌ µhnse of the dntnbnse Ìife cycÌe. Mnintnining nnd ndministering the
dntnbnse server is nn ongoing µrocess throughout the Ìifetime of the
50L Essentials
ln Ihis Porl
Chopler 8
Commond Llne
lnlerloce [CLlì
Chopler 9
SCL Accordlng lo
Chopler J0
Doloboses ond Dolo
P A k I
Command Line
lnterface (CLl)
he MySQL Commnnd-Line Interfnce ~nbbrevinted CLI
nnd nÌso known ns the commonJlinc iool ~is the µro-
grnm through which the users hnndÌe most of their dniÌy inter-
nctions with the dntnbnse. You nccess the CLI by issuing the
This chnµter Ìooks nt some normnÌ CLI tnsks, ns weÌÌ ns some
thnt mny not be obvious but nre stiÌÌ usefuÌ. An introduction to
the CLI Ìnys the groundwork, before Ìong, you cnn get your
hnnds dirty with some renÌ functions nnd try out some uses of
the CLI.
Introducing the CLI
8efore the ndvent of GUIs nnd third-µnrty tooÌs, the MySQL
CLI µrovided the onÌy wny to internct with the dntnbnse.
However the CLI offers ndvnntnges over some of its newer
counterµnrts insofnr ns it is tested nnd stnbÌe, it is Ìightweight,
nnd it comes stnndnrd with most instnÌÌntions of MySQL.
The bnsic syntnx for to use the MySQL CLI is ns foÌÌows:
The oµtions for this commnnd he̵ mnke the MySQL CLI con-
figurnbÌe ns weÌÌ ns µowerfuÌ. ShouÌd you forget the oµtions
nnd not hnve this book nvniÌnbÌe, you cnn get he̵ from the
commnnd itseÌf by ndding the or - switches
nfter you tyµe it, ns shown in Iigure 8-1.
C H A P I E k
ln Ihis Chopler
lnlroduclng lhe CLl
Slorllng lhe
CLl ÷boslcs
Üslng envlronmenl
vorlobles ln
Chooslng when lo
use lhe CLl lnlerocllve
Conllgurlng o uselul
Avoldlng common
CLl user errors
Llsllng ollernollves lo
lhe CLl
Part II 5OL EssentiaIs
Figure 8-1: Here I use the help switch to remind myself of the
correct syntax for the mysql command.
The CLI cnn be used in internctive mode where you nre tnÌking directÌy with the
server nnd it is tnÌking bnck to you, in n sense. In internctive mode the commnnds
you tyµe nre sent directÌy to the server nnd the resuÌts nre given bnck to you within
the CLI. An exnmµÌe of the CLI in internctive mode is in Iigure 8-2. You cnn obtnin
he̵ from within in CLI by tyµing or .
Figure 8-2: The CLI in interactive mode
Internctive-mode CLI is n grent tooÌ for troubÌeshooting dntnbnse µrobÌems. Ior
exnmµÌe, you cnn use the CLI in internctive mode to mnke sure queries return the
exµected resuÌts or see why they nren`t running correctÌy. You cnn use commnnds
to nnnÌyze tnbÌes nnd queries with the CLI ~nnd you cnn nÌter tnbÌes to ndd
indexes, chnnge structure, nnd more. In nddition, when using the CLI in internctive
mode n history fiÌe is recorded. Not onÌy is this n grent wny to snve keystrokes for
frequentÌy (or infrequentÌy) used commnnds, but it cnn nÌso µrovide n menns
(though insecure) of trncking whnt n user did to brenk something. Using the CLI
internctiveÌy mnkes n number of dntnbnse tnsks ensier, incÌuding these:
Chapter 8 Command Line Interface (CLI)
TroubÌeshooting queries
Adding users to MySQL
AnnÌyzing tnbÌes
AnnÌyzing queries
AÌtering tnbÌes
Checking reµÌicntion stntus
Looking nt server henÌth
The commnnd cnn nÌso be used in non-internctive mode, directÌy from the
commnnd Ìine or commnnd µromµt. The CLI is nÌso usefuÌ in non-internctive mode,
ns shown in Iigure 8-8.
Figure 8-3: The CLI in non-interactive mode in Linux
In non-internctive mode, the CLI µrovides mnny of the snme functions ns in internc-
tive mode. However, in non-internctive mode you don`t receive the snme feedbnck
from the server (nÌong with the resuÌts).
Ior exnmµÌe, if you µerform nn oµerntion using the switch in non-
internctive mode, you won`t receive n messnge thnt teÌÌs you the number of rows
inserted. When you insert rows in internctive mode, the server gives you feedbnck
thnt incÌudes the number of rows from the stntement.
Some CLI switches nre usefuÌ onÌy in non-internctive mode, most notnbÌy is the
or switch. An exnmµÌe of the switch is shown in Iigure 8-4. In the
exnmµÌe in Iigure 8-4, the switch sµecifies thnt MySQL shouÌd µromµt for n µnss-
word nnd the word nt the end of the commnnd indicntes the dntnbnse I`d Ìike
to connect to~nnd within which I µÌnn to execute the query thnt nµµenrs in quotes
nfter the switch. (I µrovide more informntion on these switches, nnd on the syn-
tnx of the CLI, Ìnter in this chnµter.)
Part II 5OL EssentiaIs
Figure 8-4: Using the -e switch to execute a query in
non-interactive mode
AÌthough it is µossibÌe to execute other commnnds with the switch, I don`t
normnÌÌy recommend executing DDL (Dntn Definition Lnngunge) commnnds such ns
with the switch. MySQL stiÌÌ µrints error messnges bnck to the
commnnd Ìine, but I`ve found thnt DDL commnnds usunÌÌy require more thnn one
commnnd to be run (for exnmµÌe, n commnnd to describe n tnbÌe) before nÌterntion
cnn begin.
CommonJ rccoll ÷reusing the commnnd or stntement you Ìnst tyµed by µressing
the uµ-nrrow on the keybonrd~is one of the best fentures of the MySQL CLI. This
fenture snves countÌess keystrokes when you mnke n tyµogrnµhicnÌ or sµeÌÌing error
in the middÌe of n Ìong query nnd hnve to run it ngnin. AdditionnÌÌy, commnnd recnÌÌ
mnkes Ìnrge nnd comµÌex queries ensier to work with, if you find thnt the outµut is
not exnctÌy ns you wnnt it, simµÌy use the uµ-nrrow nnd twenk the query when it
nµµenrs on-screen.
5tarting the CLI ¬the ßasics
8y now you`ve µrobnbÌy nÌrendy been introduced to the CLI through some enrÌier
chnµters or the introduction in this chnµter. Don`t worry if you hnven`t rend those
chnµters, the CLI itseÌf mnkes onÌy n brief nµµenrnnce there.
The commnnd to stnrt the MySQL CLI is contnined normnÌÌy in the bin directory of
the MySQL instnÌÌntion. However, it mny be Ìocnted in nnother directory deµending
on how you instnÌÌed MySQL or the oµernting system you nre using. In Linux, I`ve
seen the commnnd Ìocnted in , ,
nnd somewhere in the mount.
Chapter 8 Command Line Interface (CLI)
How you stnrt the MySQL CLI deµends ÌnrgeÌy on whnt you wnnt to do. To work
with n dntnbnse internctiveÌy, you hnve to suµµÌy credentinÌs to estnbÌish n connec-
tion. NormnÌÌy those credentinÌs come in the form of n usernnme nnd n µnssword ~
though they cnn incÌude nn oµtionnÌ nnme of the dntnbnse you`re working with, ns
weÌÌ ns the hostnnme (or IP nddress) of the server. In Iigure 8-b, for exnmµÌe, I`m
connecting to the ÌocnÌ server ( ) ns usernnme nnd teÌÌing the
µrogrnm to µerform two tnsks: Ask me for n µnssword nnd connect me to the
Figure 8-5: Connecting as username suehring to the ecommerce
database and specifying a password
The examples throughout this chapter assume that the user account you're using
has sufficient access privileges to perform the operations. If this is not the case,
consult Chapter 12 for a description of how to add a user account with specified
5pecifying the username
When using in Linux, normnÌÌy you need not ndd the (usernnme) switch.
If the usernnme switch is not sµecified, the commnnd uses the usernnme
from your environment vnrinbÌes. Ior thnt nuthenticntion to work, the MySQL
server must hnve n user entry with correct µriviÌeges in its user tnbÌe. In Iigure 8-6,
the switch is not used, so MySQL grnbs the usernnme from the envi-
ronment vnrinbÌes. 8ecnuse n user exists in the MySQL dntnbnse nnd hns
the µroµer µriviÌeges, I cnn connect to the dntnbnse server nfter suµµÌying the
correct µnssword.
Part II 5OL EssentiaIs
Figure 8-6: MySCL uses the username of the current user if the
-u switch is not used.
AccordingÌy, if you nre using the CLI ns the user, MySQL nttemµts to connect
ns the user if the switch is not used.
If you wnnt to override the defnuÌt user nnd hnve the MySQL CLI nuthenticnte ns n
different user every time, you cnn ndd the cÌnuse to the
MySQL configurntion fiÌe.
For details on how to set and change default variables for the MySCL CLI, see the
"MySCL CLI Environment variables" section later in this chapter.
5pecifying the password
One source of confusion for some is the use of the switch to sµecify the µnss-
word. Often µeoµÌe beÌieve thnt whnt foÌÌows the is nctunÌÌy the µnssword~but
this isn`t nÌwnys the cnse. The switch simµÌy teÌÌs the µrogrnm to prompi
for the µnssword if none is given. In the exnmµÌe in Iigure 8-b, n sµnce nµµenrs nfter
the switch~it`s µromµting you for the µnssword. If you wnnt to sµecify the
µnssword on the commnnd Ìine, you cnn do so by µÌncing the µnssword immedi-
nteÌy nfter the switch, ns shown in Iigure 8-7.
Specifying the password on the command line should be considered a security
risk because the password is right in plain sight for a would-be attacker to see.
AdditionnÌÌy, the switch cnn be substituted for the switch nnd is
used much the snme wny. If you µrovide |ust the switch you nre
µromµted for the µnssword. However, unÌike the switch, the syntnx
requires you to sµecify the µnssword on the commnnd Ìine by using nn equnÌs sign
( ), ns shown in Iigure 8-8.
Chapter 8 Command Line Interface (CLI)
Figure 8-7: Specifying the password immediately following the
-p switch prevents the CLI from prompting for a password.
Figure 8-8: The syntax for the --password switch is slightly different
from the -p switch.
The switch cnn be ndded into the MySQL configurntion fiÌe
nnd thus snved between sessions. This is nÌso n security risk. AÌternntiveÌy, you
couÌd simµÌy µÌnce the word under the section of the configurn-
tion fiÌe nnd you nre µromµted for the µnssword |ust ns if you used the switch.
(See this chnµter`s ¨MySQL CLI Lnvironment VnrinbÌes" section for more nbout
working with CLI vnrinbÌes.)
5pecifying the host
In much the snme wny thnt MySQL uses the current user if the switch is not
used, not using the switch mnkes MySQL nssume you menn to connect to the
server on the locolhosi (the current mnchine). If you wnnt to connect to n MySQL
server on nnother mnchine, you cnn sµecify the IP nddress or hostnnme of the
other MySQL server vin the switch, ns shown in Iigure 8-9.
Part II 5OL EssentiaIs
Figure 8-9: Use the -h switch to connect to another MySCL server
or leave it blank to connect to the local machine.
If you wnnt to set n defnuÌt host other thnn ÌocnÌhost without hnving to sµecify
the switch every time you cnn set the host inside the configurntion
fiÌe, see the discussion of environment vnrinbÌes (Ìnter in this chnµter) for detniÌs
on how to set nnd chnnge defnuÌt vnrinbÌes for the MySQL CLI. Any host sµecified in
n configurntion fiÌe is overridden if you sµecify nnother on the com-
mnnd Ìine.
5pecifying the database
The MySQL CLI ennbÌes you to sµecify the dntnbnse to use without the nddition of
nny switches to the commnnd Ìine. The commnnd exµects the dntnbnse to be sµeci-
fied ns the Ìnst µnrt of the commnnd Ìine. Ior exnmµÌe, to use n dntnbnse cnÌÌed
, simµÌy ndd it to the commnnd nt the end, Ìike this:
If no dntnbnse is sµecified on the commnnd Ìine (nssuming you hnve nccess µrivi-
Ìeges), you return nutomnticnÌÌy to the MySQL CLI ~in internctive mode but not
connected to nny dntnbnse. To connect nnd use n dntnbnse, issue the
stntement. In Iigure 8-1O, I connect to the MySQL server without sµecifying n
dntnbnse. I cnn then connect to n dntnbnse by using the stntement.
If you wnnt to sµecify the dntnbnse nt n Ìocntion other thnn the end of the commnnd
Ìine, you cnn use the or switches. To set n defnuÌt
dntnbnse for MySQL to use uµon stnrtuµ, ndd n to the
MySQL configurntion fiÌe, see the section on Lnvironment VnrinbÌes in this chnµter
for detniÌs on how to set nnd chnnge defnuÌt vnrinbÌes for the MySQL CLI.
Chapter 8 Command Line Interface (CLI)
Figure 8-10: Using the CLI and specifying a database from within
the CLI
My5OL CLI Environment VariabIes
RegnrdÌess of whether you use the CLI in internctive mode, vnrinbÌes nre nvniÌnbÌe to
controÌ how the CLI oµerntes. When rend from configurntion fiÌes, those vnrinbÌes
cnn be set gÌobnÌÌy with the use of configurntion fiÌes ~in µnrticuÌnr, or
(usunÌÌy Ìocnted in the or Linux directory or the
directory in Windows 2OOO).
If you want to set the variables on a per-user basis, a file in each user's
home directory can provide customized individual use of the MySCL CLI. Make
sure that a dot ( ) immediately precedes each user's filename -for
example, . Since the configuration file can reside in each user's home
directory, it is only applied when logged in as that user.
Determining and changing defauIt variabIes
To determine the vnrinbÌes the MySQL CLI uses for n µnrticuÌnr session, use the
switch, ns shown in Iigure 8-11.
Chnnging n defnuÌt vnrinbÌe is ns simµÌe ns editing the configurntion fiÌe. Ior
exnmµÌe, if I wnnt to chnnge the socket thnt MySQL connects through from the
defnuÌt , I couÌd mnke n fiÌe (ns shown in Iigure 8-12)
nnd incÌude n section for the MySQL CLI in brnckets with the oµtion
Part II 5OL EssentiaIs
Figure 8-11: The --print-defaults switch shows you which
environment variables MySCL uses for your session.
Figure 8-12: Creating a .my.cnf file in my home directory so I can
set defaults for the MySCL CLI
In Iigure 8-18, the outµut of the switch, note the new socket
nnme ~nctunÌÌy iuo socket defnuÌts. 8ecnuse ÌocnÌ oµtions nre rend Ìnst, the Ìnst
oµtion to be rend is nµµÌied.
Chapter 8 Command Line Interface (CLI)
Figure 8-13: The --print-defaults switch now shows the new defaults that go into effect
the next time you start the MySCL CLI.
In the exnmµÌe in Iigure 8-18, I chnnged the socket to n bogus fiÌennme thnt won`t
nctunÌÌy connect to the MySQL server. The resuÌt is the error messnge you see in
Iigure 8-14.
Figure 8-14: The socket name I used doesn't exist; therefore I receive an error message
when I try to connect.
Some of the more usefuÌ cÌient or CLI vnrinbÌes nre shown in TnbÌe 8-1.
Part II 5OL EssentiaIs
Table 8-1
FrequentIy Used My5OL CLI VariabIes
Vorioble 0se
Changes the socket for local connections.
Changes the port for connections via TCP/IP.
Sets the password to be used by the CLI. Potential
security risk.
Sets the pager such as the more or less commands to
control scroll.
Sets a default host to connect to with all connections.
Sets a default database.
Suppresses the printing of column names with the
Prints output from queries vertically.
Produces output in HTML format, useful when operating in
non-interactive mode.
Appends output from interactive mode into the file named
When cnÌÌing the MySQL µrogrnm, you cnn set its vnrinbÌes either in the
fiÌe or on the commnnd Ìine.
variables set on the command line supersede those set in configuration files.
In nddition to setting vnrinbÌes, n commnnd-Ìine oµtion ennbÌes
you to override nny defnuÌts in configurntion fiÌes. This is usefuÌ if your fiÌe
hns n number of defnuÌt vnÌues set, nnd you wnnt to override them nÌÌ to use some
non-defnuÌt oµtions. In Iigure 8-1b, for exnmµÌe, I hnve set some oµtions thnt ennbÌe
me to work more efficientÌy (since most of the work is done on the ÌocnÌ mnchine).
Chapter 8 Command Line Interface (CLI)
Figure 8-15: Using mysql --print-defaults to see the default options
I have for this client
Performing n query with these oµtions yieÌds the resuÌts shown in Iigure 8-16.
Figure 8-16: Running a query with the default options
However, now I hnve to connect to nnother MySQL server ~nnd I don`t wnnt the
or oµtions but I do need coÌumn nnmes µrinted. To turn off nÌÌ
the defnuÌts nt once ~nnd set my own, bnsing them on the new host ~I use the
oµtion (ns shown in Iigure 8-17).
Part II 5OL EssentiaIs
Figure 8-17: Using the --no-defaults option on the command line
to override all defaults at once
Performing n query shows thnt the other oµtions (such ns nnd )
hnve been turned off, ns shown in Iigure 8-18.
Figure 8-18: A query with the defaults turned off yields the
expected results.
Using the CLI in Interactive Mode
When you use the CLI in internctive mode, n µromµt nkin to n sheÌÌ µromµt nµµenrs~
you get functions, switches, nnd settings thnt nffect how the CLI oµerntes. Some of
these fentures nre better used with the CLI in non-internctive mode, others work
more efficientÌy in internctive mode.
When using the MySCL CLI in interactive mode, all commands must be terminated
with a semicolon ( ). The only three exceptions to this rule are the com-
mand, the command, and the command.
Chapter 8 Command Line Interface (CLI)
5peeding startup of the CLI
When the CLI stnrts, it rends in tnbÌe informntion to nÌÌow for comµÌetion, which cnn
sometimes sÌow the stnrtuµ. To turn off this defnuÌt nnd get n quicker CLI stnrtuµ,
use the or switch. Adding to the MySQL
configurntion fiÌe under the section mnkes this quicker stnrtuµ µermnnent.
Making the CLI quieter
When you stnrt the CLI, n weÌcoming messnge µrints (nÌong with version nnd ses-
sion informntion). In nddition, stntus messnges nµµenr on-screen so you cnn see the
µrogress of the stntements you execute. If you`d Ìike to stoµ thnt informntion from
showing uµ, use the or oµtion. To mnke this nrrnngement µermnnent
(exceµt for error messnges, which stiÌÌ nµµenr ns needed), ndd the oµtion
under the section of your MySQL configurntion fiÌe.
Using a pager to work with Iarger amounts of data
Often the resuÌts of n stntement scroÌÌ µnst the screen when the µrogrnm
hns to hnndÌe n Ìnrge (or not even very Ìnrge) set of dntn. Through the use of the
oµtion you cnn set MySQL to return query resuÌts sµÌit over n number of
screens. Using n poµcr commnnd such ns the or , you cnn controÌ the
scroÌÌing on n µnge-by-µnge bnsis.
You cnn set the oµtion, whether from inside n configurntion fiÌe or on the
commnnd Ìine, by ndding the oµtion to the commnnd,
ns shown in Iigure 8-19.
Figure 8-19: Using the --pager option on the command line specifies
the program to control scrolling
Part II 5OL EssentiaIs
If the option is set in a MySCL configuration file, you can turn it off by using
the switch on the command line.
DispIaying query resuIts verticaIIy
Often the coÌumns in n query resuÌt wrnµ nwkwnrdÌy nround the edges of the
screen. Not onÌy is this situntion ugÌy, it`s nÌso confusing, the wrnµµing mnkes the
coÌumns hnrd to mntch with their vnÌues, ns shown in Iigure 8-2O.
Figure 8-20: Without the vertical option, the output from this query
wraps around the screen.
In Iigure 8-2O, it cnn be difficuÌt to determine whether n given user nctunÌÌy hns the IiÌe
µriviÌege. However, with the use of the or switch, the dntn is disµÌnyed
with coÌumns foÌÌowing ench other verticnÌÌy. Adding the oµtion to the
fiÌe in my home directory~nÌong with the use of n µnger commnnd~grentÌy
imµroved the Ìook nnd usnbiÌity of my query`s outµut (ns shown in Iigure 8-21).
Figure 8-21: Using the vertical option and the pager option to make
the output more comprehensible
Chapter 8 Command Line Interface (CLI)
I ndded the foÌÌowing Ìines to the section of the configurntion fiÌe
to µroduce the outµut in Iigure 8-21.
The use of won't work when using the CLI in non-interactive mode.
Using tee to save output
The commnnd tnkes the entire session ~incÌuding inµut nnd outµut from n
commnnd~nnd nµµends it to n fiÌe thnt you sµecify. This function cnn be he̵fuÌ
when debugging (for security µurµoses), or simµÌy ns nn ensy wny to get dntn into
n fiÌe. The switch to use this function with MySQL is .
AÌternnteÌy the switch cnn be set in the MySQL configurntion fiÌe with the use of
Ior exnmµÌe, Iigure 8-22 uses the function to nµµend the
session onto n fiÌe cnÌÌed .
Figure 8-22: Using the tee function to append session data to the
content of a file
Iigure 8-28 shows session dntn thnt hns been snved to the fiÌe.
If the option is set in a MySCL configuration file, it can be turned off by using
the switch on the command line.
Part II 5OL EssentiaIs
Figure 8-23: Here the Tee function has saved session data in the file.
Printing output in HIML format
Though using the CLI in non-internctive mode is genernÌÌy the more usefuÌ nµµronch,
sometimes you mny wnnt to run n simµÌe query nnd then coµy nnd µnste its outµut
into n Web µnge ns HTML outµut. To do so, use the or switch (or µut the
word in your MySQL configurntion fiÌe under the section).
5uppressing coIumn names
At times I`ve found it usefuÌ to run n query without hnving the coÌumn nnmes µrint
in the outµut. Irom within the CLI, this technique cnn sometimes µrevent some con-
fusion by keeµing the outµut from wrnµµing nround on-screen. As with the switch
thnt µroduces HTML outµut, this function mny be best used in non-internctive
mode ~though it`s sometimes usefuÌ in internctive mode ns weÌÌ.
To suµµress coÌumn nnmes, stnrt the MySQL CLI with the or
switch. To mnke this suµµression µermnnent, ndd to
your MySQL configurntion fiÌe in the section.
Using batch mode to produce tab deIimited output
The MySQL CLI nÌso oµerntes in n bntch mode thnt suµµresses trnditionnÌ feedbnck
from the CLI nnd µresents query outµut in tnb-deÌimited formnt (see Iigure 8-24).
If you enter bntch mode nnd get nn error messnge, the session is immedinteÌy termi-
nnted. You nre sent bnck to the sheÌÌ with nn echo of the error messnge (ns shown
in Iigure 8-2b).
Chapter 8 Command Line Interface (CLI)
Figure 8-24: Using the CLI in batch mode to get tab-delimited output while
suppressing other information and feedback from the CLI.
Figure 8-25: Errors that occur while you're using batch mode kick
you back out to the command shell.
You still have to terminate commands with a semicolon (;) while using batch
mode interactively.
If you wnnt to µrevent MySQL from terminnting your session uµon error when in
bntch mode, use the f or switch. With the Iorce oµtion set, the error
messnge is disµÌnyed but the session continues, ignoring the error.
Use the option with care; one error in the beginning of a series of SCL
statements can wreak havoc on the rest of the statements -and possibly the data.
Part II 5OL EssentiaIs
Using the CLI in Non-Interactive Mode
The CLI need not be used internctiveÌy, sometimes running n simµÌe query or com-
mnnd on the server does the |ob. Ior exnmµÌe, you mny wnnt to redirect the outµut
of n stntement to n fiÌe, or use n scheduÌer (such ns ) to scheduÌe the running
of n µnrticuÌnr commnnd. In such instnnces, the MySQL CLI cnn be used in n non
inicrociicc moJc thnt mnkes it oµernte Ìike nny bnsic, strnightforwnrd commnnd.
Executing a statement
When you`re oµernting in non-internctive mode, one of the most frequent nnd usefuÌ
oµerntions is to execute n stntement. To do so, you use the or
switch. Ior exnmµÌe, to run n simµÌe query thnt finds the users nnd
hosts nÌÌowed to connect to n µnrticuÌnr dntnbnse, you cnn use the switch ns
iÌÌustrnted in Iigure 8-26.
Figure 8-26: Using the -e switch to run a simple query
In Iigure 8-26, I sµecified the switch to hnve MySQL µromµt for the µnssword.
Next comes the switch, foÌÌowed by the stntement to execute in quotes. IinnÌÌy
comes the nnme of the dntnbnse to connect to (in this cnse, , becnuse thnt`s
where user dntn is stored).
Printing HIML output
One esµecinÌÌy hnndy fenture of the MySQL CLI is thnt it cnn outµut n query in
HTML formnt ~n cnµnbiÌity you cnn use to crente n simµÌe Web µnge from n query
without much effort. The switch thnt µroduces HTML outµut is or . Ior
exnmµÌe, suµµose I wnnt to mnke n Web µnge consisting of n simµÌe reµort of the
µroducts in the dntnbnse exnmµÌe (yes, nÌÌ three of them.) In Iigure 8-27,
I rnn the commnnd to µroduce the outµut.
Chapter 8 Command Line Interface (CLI)
Figure 8-27: The output from a HTML-formatted query that uses
the CLI
In Iigure 8-27, the switches nnd the order of the commnnd nre whnt you wouÌd
Whenever you add an option or a switch to the command, be sure to use
the correct case. For example, adding the option gives MySCL different instruc-
tions from those specified by the switch (lowercase h). Adding instead of
would have made MySCL think you were specifying a host instead of calling for
HTML output. As you can see from Figure 8-27, the output isn't pretty.
The grentest usefuÌness of the HTML switch is redirecting outµut to n fiÌe, ns shown
in Iigure 8-28.
Figure 8-28: Redirecting the output from an HTML-formatted query
Part II 5OL EssentiaIs
In Iigure 8-28, the outµut is redirected by using the grenter-thnn sign ( ) nnd the
nnme of the fiÌe thnt receives the outµut is .
In Linux, the single greater-than sign ( ) causes the redirected output to overwrite
whatever is in the receiving file. If you want merely to append the output instead
of using it to replace what's in the file, use two greater-than signs ( ).
After moving or coµying the fiÌe (with the newÌy nµµended outµut) to n µÌnce where
the Web server cnn get hoÌd of it, I hnve n Web µnge consisting of n simµÌe tnbÌe thnt
shows the µroducts in the inventory. Iigure 8-29 shows whnt it Ìooks Ìike.
Figure 8-29: A simple Web page produced with the output from the -H switch
5uppressing coIumn names
Lvery time MySQL runs n query, the outµut of the query incÌudes coÌumn nnmes nt
the toµ. If you wnnt to excÌude coÌumn nnmes (ns when you nµµend the outµut to n
different fiÌe), you cnn use nn oµtion to suµµress them.
To suµµress coÌumn nnmes, stnrt the MySQL CLI with the or
switch. To mnke this function µermnnent, ndd to your
MySQL configurntion fiÌe in the section.
Chapter 8 Command Line Interface (CLI)
Printing resuIts verticaIIy
1ust ns the MySQL CLI cnn µrint resuÌts verticnÌÌy when being used internctiveÌy to
he̵ imµrove Ìnyout, verticnÌ outµut is sometimes usefuÌ in non-internctive mode ns
weÌÌ. This is esµecinÌÌy true for nµµending dntn to n fiÌe to be exnmined Ìnter.
The switch to turn on the nµµroµrinte oµtion is L or . This formnt cnn
be mnde µermnnent by ndding the word to your MySQL configurntion fiÌe
under the section.
Using batch mode to produce tab-deIimited output
To µroduce outµut thnt uses tnbs ns deÌimiters, you cnn use MySQL in bntch mode.
Turn bntch mode on with the or switch (or ndd the word to your
MySQL configurntion fiÌe under the section). In bntch mode, the outµut
from n stntement wouÌd show vnÌues seµnrnted by tnbs instend of by
coÌumns (usefuÌ if you`re imµorting dntn into nnother nµµÌicntion, becnuse most
nµµÌicntions recognize the tnb chnrncter ns n vnÌid fieÌd seµnrntor).
In Iigure 8-8O, I issue n simµÌe stntement in normnÌ mode, which formnts the
fieÌds ns n tnbÌe.
Figure 8-30: A query in normal mode produces tabular-formatted output
In Iigure 8-81, I issue thnt snme stntement, this time in bntch mode. Notice
thnt the outµut no Ìonger hns the tnbuÌnr formnt. Instend, it shows tnbs ns deÌim-
iters. Using bntch mode, I couÌd redirect the outµut fiÌe nnd imµort it into nnother
dntnbnse nµµÌicntion.
Part II 5OL EssentiaIs
Figure 8-31: Using batch mode to produce output with tab delimiters
Some other commands and statements -such as or
-may be better suited to exporting data. Those commands are
discussed in Chapter 10.
Creating a UsefuI My5OL CLI Environment
With nÌÌ the oµtions covered in this chnµter, you mny be wondering which ones you
shouÌd use ~nnd whether to set the oµtions gÌobnÌÌy (for nÌÌ users of the CLI), or
onÌy for your user nccount, or onÌy in your home directory. The nnswers nre fÌexi-
bÌe, determined by whnt you need your dntnbnse nµµÌicntion to do.
Ior exnmµÌe, if nÌÌ users on the comµuter use the snme usernnme to connect to n
µnrticuÌnr dntnbnse, you couÌd mnke thnt usnge n gÌobnÌ setting in the MySQL con-
figurntion fiÌe. AÌternntiveÌy, if you use n µnrticuÌnr usernnme but everyone eÌse
uses n different one, you couÌd sµecify thnt setting in your ÌocnÌ or µersonnÌ MySQL
configurntion fiÌe.
Programmers still debate the matter of which pager command is best for display-
ing results. For practicality's sake, you may want to avoid the debate by specifying
that setting only in a local or personal configuration file.
A usefuÌ environment for the CLI cnn be ns comµÌicnted or ns simµÌe ns you`d Ìike it
to be. IdenÌÌy, you couÌd µroduce n configurntion fiÌe µersonnÌized for your use of
the MySQL CLI. With n good configurntion, you couÌd snve time nnd incrense µro-
ductivity by not hnving to sµecify the snme oµtions every time you stnrt the CLI.
A basic My5OL CLI configuration
The foÌÌowing configurntion exnmµÌe might be n fine stnrting µoint for nnyone`s use
of MySQL. The configurntion µrovides n defnuÌt µnger of Ìess for resuÌts thnt wouÌd
Chapter 8 Command Line Interface (CLI)
scroÌÌ more thnn one screen nnd it wiÌÌ nÌso teÌÌ the CLI to nutomnticnÌÌy µromµt for
the µnssword on stnrtuµ. This shouÌd be set in your ÌocnÌ configurntion fiÌe such ns
the fiÌe in your home directory in Linux.
A My5OL administration configuration
The foÌÌowing is nn exnmµÌe of whnt nn ndministrntor`s configurntion might Ìook Ìike
for MySQL. You wouÌd hnve to ndd n usernnme of with µroµer µriviÌeges to
the dntnbnse. The configurntion wiÌÌ connect ns the user nnd µromµt for n
µnssword. The defnuÌt dntnbnse to connect to is the dntnbnse thnt
houses user rights nnd µriviÌeges. I`ve chosen n defnuÌt µnger of to sµecify
fewer resuÌts on-screen (Ìess to scroÌÌ through). I ndded the oµtion
becnuse I`ve found thnt disµÌnying the grnnt tnbÌes verticnÌÌy renÌÌy he̵s comµre-
hension since most of the grnnt tnbÌes wiÌÌ wrnµ nround the screen. IinnÌÌy, nÌÌ
oµerntions within the CLI wiÌÌ be nµµended to n ÌogfiÌe for trncking
The option does not provide complete security or tracking for operations per-
formed within a database.
A cIient-onIy My5OL CLI configuration
If you connect to n remote MySQL server frequentÌy, ndding n
Ìine to the bnsic configurntion might he̵. With the configurn-
tion, the CLI nutomnticnÌÌy connects to the remote host without requiring you to
sµecify the switch on the commnnd Ìine.
Your My5OL CLI configuration
Your MySQL CLI configurntion mny Ìook somewhnt different from the ones I`ve
given ns exnmµÌes. 8uiÌding nnd tniÌoring the configurntion to your nµµÌicntion nnd
instnÌÌntion is one of mnny wnys you cnn imµrove your exµerience with MySQL.
Part II 5OL EssentiaIs
Common CLI Errors
Using the CLI myseÌf (nnd working with mnny µeoµÌe who nre new to dntnbnses nnd
the CLI), I`ve seen quite n few error messnges. Often the errors croµ uµ simµÌy
becnuse I cnn`t seem to tyµe weÌÌ thnt dny, but |ust ns often they show uµ for other
rensons thnt cnÌÌ for some simµÌe troubÌeshooting.
Access Denied errors
The error hns n number of vnrintions, three of which nre shown in
Iigure 8-82.
Figure 8-32: Three variations of the Access Denied error with the CLI
Here`s whnt µroduced the errors shown in Iigure 8-82:
In the first exnmµÌe I nm trying to obtnin nccess to the CLI ns the user
but I nm not sµecifying n µnssword vin the switch. This try fniÌs,
the error messnge hints (not too subtÌy) why: .
In the second nttemµt, I ndd the switch but then µress Lnter instend of tyµ-
ing the µnssword. Notice the simiÌnrity of resuÌt between the second nnd first
nttemµts (though I didn`t use the switch in the first one).
In the third nttemµt, I use the switch but mistyµe the µnssword. Notice this
time thnt the end of the error messnge is different: .
Another vnrintion of the error is shown in Iigure 8-88: I try to con-
nect to n dntnbnse on which I hnve no µriviÌeges or rights. As you cnn see, the error
number is different, ns is the messnge.
Chapter 8 Command Line Interface (CLI)
Figure 8-33: Another variation of an Access Denied error occurs when
the user doesn't have sufficient privileges to connect to the database.
Iigure 8-84 iÌÌustrntes n common error thnt cnn croµ uµ when you try to connect to
n MySQL dntnbnse. There nre differing rensons for this error messnge, the first nnd
foremost is thnt the MySQL server isn`t running. NormnÌÌy you cnn soÌve this µrob-
Ìem by stnrting the MySQL server nnd nttemµting to connect ngnin.
Figure 8-34: A common error can mean one of several different
problems may exist.
Another cnuse of the µrobÌem shown in Iigure 8-84 is thnt the CLI is nttemµting to
connect through n socket fiÌe thnt doesn`t exist. The remedy for this issue is
usunÌÌy to determine uhy the fiÌe doesn`t exist ~for exnmµÌe, becnuse of µermis-
sions µrobÌems, n fiÌe crented in the wrong µÌnce, or (ngnin) n MySQL server thnt
isn`t running.
Part II 5OL EssentiaIs
AIternatives to the CLI
The CLI is by no menns the onÌy method for working with dntnbnse nnd dntn. With
the numerous MySQL APIs nvniÌnbÌe, you cnn write your own method for interncting
with the dntnbnse nnd dntn, using mnny µrogrnmming Ìnngunges ~or use nny of the
µre-written µrogrnms thnt were written for working with dntnbnses nnd dntn. In this
section I`m going to discuss two such µrogrnms, the MySQLGUI µrogrnm dis-
tributed by MySQL A8 ns weÌÌ ns the Web-bnsed tooÌ µhµMyAdmin.
Of course, since the ndvent of the Mncintosh nnd Windows grnµhicnÌ user inter-
fnces, the GUI hns Ìong been nn nÌternntive to the CLI (though some nrgue thnt n
server oµernting system shouÌdn`t be required to hnve n GUI). AÌthough MySQLGUI
µerforms the snme functions ns the MySQL CLI, it nbnndons the text-bnsed interfnce
of n trnditionnÌ CLI nnd ndoµts n Ìook thnt mny be more comfortnbÌe for Ìongtime
Windows nnd Mnc users. You cnn obtnin n coµy of the MySQLGUI µrogrnm directÌy
from MySQL A8.
The MySQLGUI doesn`t come with nÌÌ the beÌÌs nnd whistÌes thnt some GUI users
exµect ~in µnrticuÌnr, it hns no instnÌÌntion or setuµ µrogrnm. After you unµnck the
nrchive, you hnve to crente your own directories nnd shortcuts to the µrogrnm.
The µhµMyAdmin suite is n coÌÌection of PHP scriµts thnt µerform mnny of the
snme tnsks ns the MySQL CLI nnd its commnnd. With µhµMyAdmin,
you cnn µerform seÌects, insert, deÌetes, crention of dntnbnses nnd tnbÌes ns weÌÌ ns
ndministrntion tnsks such ns ndding users, showing µrocesses nnd so forth, nÌÌ
through n Web-bnsed interfnce.
InstnÌÌntion of µhµMyAdmin requires PHP nnd n Web server such ns Aµnche. You
cnn obtnin µhµMyAdmin nt . 8ecnuse µhµMyAdmin runs
on n Web server, you cnn use it to work with your dntnbnse server nnd dntnbnses
from nny comµuter with n Web browser, regnrdÌess of µÌntform.
The Apache Web server is included on the CD-RCM with this book, as is PHP.
Ihe basics of My5OLCUI
At first stnrtuµ, MySQLGUI µromµts you for the µnssword (see Iigure 8-8b). If you
enter n µnssword nnd continue, MySQLGUI nttemµts to connect ns 'root` to the
ÌocnÌhost server. If you µress the Lsc key, however, you get to the MySQLGUI mnin
screen without connecting to the dntnbnse server.
üo the
Chapter 8 Command Line Interface (CLI)
Figure 8-35: MySCLCUI prompts for the
password at startup. Pressing Esc bypasses
the Password screen.
8efore you cnn µerform nny nctions on the dntnbnse server, you must suµµÌy cre-
dentinÌs such ns usernnme nnd µnssword. MySQLGUI nÌso Ìooks for informntion in
configurntion fiÌes such ns nnd . To set or chnnge these oµtions,
cÌick Mnnnge Oµtions, nÌternntiveÌy, cÌick the Oµtions button on the tooÌbnr. You
shouÌd see n screen simiÌnr to Iigure 8-86.
Figure 8-36: The Cptions screen in MySCLCUI is where you set
the credentials for connecting to the database server, as well as
other program options.
Note thnt Iigure 8-86 nÌso shows n row of tnbs ncross the toµ of the dinÌog box. 8y
defnuÌt, MySQLGUI nttemµts n connection to the ÌocnÌhost dntnbnse server (or the
mnchine on which MySQLGUI is running). You cnn nÌso suµµÌy nn IP nddress or DNS
nnme for nnother MySQL server. If you wnnt to connect to n sµecific dntnbnse such
ns the defnuÌt dntnbnse, you cnn set thnt on this screen ns weÌÌ.
The CÌient tnb, shown in Iigure 8-87, is for estnbÌishing some bnsic settings for the
cÌient ~for exnmµÌe, usernnme (which is by defnuÌt) nnd the timeout intervnÌ
for the connection. Ior my exnmµÌe, I connect ns the user ~chnnging the
The username should be reserved for one user only -the administrative
"superuser." I strongly recommend that you don't use MySCL's root user to
perform day-to-day tasks with MySCL.
Part II 5OL EssentiaIs
Figure 8-37: The Client tab is where you set options such as
username and connection timeout.
When you cÌick the AµµÌy button, the Oµtions dinÌog box cÌoses. If you wnnt to snve
your settings for the next time you run the µrogrnm, you must cÌick the Snve button
nfter cÌicking AµµÌy
ße sure to click the Save button if you want the options to be saved for the next
time you run MySCLCUI.
When your oµtions nre set, cÌick the Connect button (in the uµµer-Ìeft nren of the
MyQSLGUI window). A µnssword µromµt simiÌnr to thnt in Iigure 8-8b nµµenrs,
mistyµing the µnssword µroduces resuÌts thnt Ìook Ìike Iigure 8-88: An informn-
tionnÌ or error messnge nµµenrs nt the bottom of the screen ~strikingÌy simiÌnr to
the one you`d receive with the MySQL CLI.
Figure 8-38: I deliberately mistyped my password to show you the
error message you get when you do that.
Chapter 8 Command Line Interface (CLI)
CÌicking the Connect button nnd then tyµing your µnssword correctÌy resuÌts (Ìogi-
cnÌÌy enough) in n connection to the dntnbnse server. Notice thnt if more thnn one
dntnbnse is nvniÌnbÌe on the server, you cnn cÌick the droµ-down box next to the
Connect button nnd see n comµÌete Ìist (ns shown in Iigure 8-89). You stiÌÌ see n com-
µÌete Ìist of dntnbnses, even if you don`t hnve nny µriviÌeges on them. Attemµting to
connect to n dntnbnse for which you don`t hnve µriviÌeges wiÌÌ resuÌt in nn error. In
nddition, when MySQLGUI connects, it µÌnces the Ìist of dntnbnses in n̵hnbeticnÌ
order. If you don`t hnve µriviÌeges on the first dntnbnse in thnt Ìist, you won`t be
nÌÌowed to connect. To correct this µrobÌem, set n defnuÌt dntnbnse by cÌicking IiÌe
Figure 8-39: Connecting to the database server and looking at the
databases available on the server
kunning 5OL statements with My5OLCUI
Running n query or other SQL stntement is renÌÌy quite simµÌe with MySQLGUI.
SimµÌy tyµe the query into the box ns shown in Iigure 8-4O, using n simµÌe query on
the dntnbnse such ns .
Part II 5OL EssentiaIs
Figure 8-40: Executing SCL statements with MySCLCUI is easy,
as shown by this simple query.
You cnn choose of whnt you`d Ìike to do with the resuÌts from the stntement.
Iigures 8-86 through 8-89 show three buttons ncross the toµ of the mnin MySQLGUI
screen~Screen, IiÌe, nnd Count ~thnt nÌso reµresent those choices:
Screen: 8y defnuÌt, the Screen oµtion is seÌected, which µrints the resuÌts of
nny stntement on-screen onÌy. The resuÌts of the query
oµen n new dinÌog box, ns shown in Iigure 8-41.
Figure 8-41: When you print the results of a statement to the screen,
a new dialog box opens automatically.
Chapter 8 Command Line Interface (CLI)
The ResuÌts box gives you the oµtion to snve your resuÌts to n fiÌe.
File: If you wnnt to snve the resuÌts to n fiÌe directÌy, cÌick the IiÌe button. A
dinÌog box simiÌnr to the one shown in Iigure 8-42 nµµenrs, µromµting you for
the Ìocntion to which you wnnt to send the resuÌts. In resµonse to the µromµt
for n fiÌennme, you cnn choose to crente n new fiÌe or nµµend the resuÌts to nn
existing fiÌe.
Figure 8-42: To save the results to a file, you
must select the location and filename for
MySCLCUI to send the results to.
Count: SeÌect this button if you wnnt to see n count of the resuÌts instend of
µrinting the outµut to the screen or to n fiÌe. The count nµµenrs in the
Informntion section nt the bottom of the MySQLGUI screen. Ior exnmµÌe, the
query returns 9 rows, ns shown in Iigure 8-48. The
count resuÌts nµµenr in the Informntion section nt the bottom of the figure.
You cnn nÌso use MySQLGUI to Ìimit the number of rows returned by n query. CÌick
Commnnds Query With Limit. A sÌider-bnr nµµenrs nt the bottom of the mnin
MySQLGUI µrogrnm screen, ns shown in Iigure 8-44. SimµÌy sÌide the bnr to the Ìeft
or right, by Ìeft-cÌicking with the mouse nnd drngging the bnr.
Part II 5OL EssentiaIs
Figure 8-43: Select the Count option displays the number of rows
returned by the statement in the Information section of the
MySCLCUI screen.
Figure 8-44: You can limit the rows returned by a query by
selecting the With Limit option.
Administration with My5OLCUI
In nddition to µerforming stnndnrd MySQL CLI duties (such ns running SQL stnte-
ments), you cnn use MySQLGUI to µerform mnny ndministrntive tnsks such ns crent-
ing nnd droµµing dntnbnses, checking the stntus of the server, nnd even shutting
the server down.
Chapter 8 Command Line Interface (CLI)
The Administrntion menu (beÌow the Commnnds menu bnr) is where you cnn find
numerous commnnds for monitoring nnd governing the oµerntion of MySQL
dntnbnse server, ns shown in Iigure 8-4b.
Figure 8-45: The Administration commands available with MySCLCUI
To µerform some of these snme ndministrntive tnsks on the MySQL dntnbnse server,
you cnn bring uµ nn Administrntion PnneÌ there ns weÌÌ (ns shown in Iigure 8-46).
Figure 8-46: The Administration Panel of MySCLCUI
Part II 5OL EssentiaIs
Administrative commands and tasks are discussed in individual detail throughout
this book, most notably in Chapter 9 and Appendix A.
Ihe basics of phpMyAdmin
is n Web-bnsed interfnce for working with dntnbnses nnd dntnbnse
servers. cnn be used to µerform dntnbnse ndministrntion ns weÌÌ ns
Dntn Definition Lnngunge (DDL) nnd Dntn Mnrkuµ Lnngunge (DML) stntements. Ior
exnmµÌe, with you cnn crente dntnbnses nnd tnbÌes nnd µerform stnte-
ments such ns , , nnd .
As nn ndded bonus, runs on vnrious µÌntforms ~µrovided the
mnchines using them cnn meet the system requirements. To run , your
system must hnve not onÌy n MySQL dntnbnse server, but nÌso the foÌÌowing:
A Web server cnµnbÌe of running PHP (for exnmµÌe, Aµnche Server).
PHP version 8 or nbove.
A Web browser such ns Netscnµe Nnvigntor, Microsoft Internet LxµÌorer, or
Though instnÌÌntion of the µrerequisites to is beyond the scoµe of this
book, the nctunÌ instnÌÌntion of is renÌÌy quite ensy. SimµÌy crente n
directory on your Web server nnd unµnck the nrchive to thnt directory.
After unµncking the nrchive edit the configurntion fiÌe to set µnrnmeters
for your MySQL server, currentÌy this fiÌe is cnÌÌed but
thnt nnme mny chnnge in future versions of µhµMyAdmin. There is documentntion
incÌuded with to nssist with steµs necessnry for instnÌÌntion on your
You must restrict access to the Web server directory into which you install
phpMyAdmin. Failure to do so can leave your database server and data open to
unauthorized access.
kunning 5OL statements with phpMyAdmin
As stnted µreviousÌy, cnn µerform DDL nnd DML with ense. Mnny SQL
stntements cnn be buiÌt through the use of PHP forms or you cnn tyµe in your own
SQL stntements to be executed on the server.
In the bnsic (or Home) screen for , the frnme on the Ìeft side Ìists nÌÌ the
dntnbnses thnt the given user hns nccess to. A µÌus sign (-) next to the dntnbnse
nnme indicntes the existence of tnbÌes within the dntnbnse, cÌicking the µÌus sign
exµnnds the Ìist nnd shows which tnbÌes nre in the dntnbnse.
CÌicking the nctunÌ dntnbnse nnme in the Ìeft frnme chnnges the right frnme to n Ìist
of tnbÌes. The Ìist nÌso mentions nctions you cnn tnke to chnnge the tnbÌe(s).
Chapter 8 Command Line Interface (CLI)
ScroÌÌing down on the right-hnnd frnme, you cnn see n number of other nctions to
µerform on the dntnbnse nnd tnbÌes. These incÌude writing your own SQL stnte-
ments, viewing the schemn, nnd crenting n new tnbÌe. The defnuÌt nctions for n tnbÌe
incÌude 8rowse, SeÌect, Insert, Proµerties, Droµ, nnd Lmµty. Using these defnuÌt
nctions, you cnn buiÌd nn SQL stntement vin PHP forms without hnving to know the
underÌying SQL. Ior exnmµÌe, to issue n stntement to show the user nnd
host within the user tnbÌe of the MySQL dntnbnse you cnn cÌick the dntnbnse
on the Ìeft side, cÌick SeÌect nnd then buiÌd n query.
The resuÌts of the query nre then µrinted to the screen in n resuÌting µnge. You cnn
nÌso redirect the resuÌts to n fiÌe by seÌecting thnt oµtion from the screen. Using n
different set of oµtions, you cnn Ldit or DeÌete n given row of the resuÌt set. CÌicking
Ldit for the user resuÌts in nnother µnge, with oµtions for editing bnsed on
the coÌumns in the tnbÌe.
Administration with phpMyAdmin
Among the ndministrntion tnsks thnt you cnn µerform with nre cre-
ntion of dntnbnses, editing µriviÌeges for users, reÌonding the server, nnd dingnosing
server vnrinbÌes. The mnin interfnce µnge for in Iigure 8-47 shows the
nctions you cnn µerform. The oµtions nre seÌf-exµÌnnntory nnd where you need fur-
ther nssistnnce, there is n Documentntion Ìink thnt connects you directÌy to MySQL
A8`s onÌine documentntion.
The ndministrntive tnsks you cnn µerform~incÌuding the nssignment of µriviÌeges,
crention of dntnbnses, nnd choosing the vnrinbÌes you cnn see with ~
nre discussed in grenter detniÌ throughout the book.
The MySQL CLI is n commnnd-Ìine µrogrnm for working with dntnbnses nnd the
dntnbnse server.
The CLI cnn be used internctiveÌy or non-internctiveÌy.
The bnsic syntnx for using the MySQL CLI is
You cnn set n number of commnnd-Ìine oµtions nnd vnrinbÌes thnt nffect the
behnvior of the CLI.
Three imµortnnt nnd frequentÌy used commnnd-Ìine oµtions nre
for sµecifying the usernnme
for teÌÌing the CLI to µromµt for the µnssword
ns the Ìnst nrgument to sµecify the dntnbnse to connect to
with the CLI
Part II 5OL EssentiaIs
You cnn crente n µersonnÌized CLI environment through the use of the MySQL
configurntion fiÌes (for exnmµÌe, in Linux).
Common errors when connecting to the CLI incÌude errors
when you tyµe your µnssword incorrectÌy or the user doesn`t hnve sufficient
µriviÌeges on the dntnbnse, nnd n error
when the dntnbnse server isn`t running or the socket fiÌe doesn`t exist.
Two µoµuÌnr nÌternntives to the text-bnsed CLI nre MySQLGUI nnd
, n cross-µÌntform nÌternntive.
MySQLGUI distributed by MySQL A8 ns nn nÌternntive nnd nddition to the text-
bnsed CLI. With MySQLGUI you cnn µerform SQL stntements ns weÌÌ ns
dntnbnse ndministrntion.
is n cross-µÌntform nÌternntive (nnd nddition) to the text-bnsed
CLI. cnn he̵ buiÌd nnd µerform SQL stntements, ns weÌÌ ns some
ndministrntive tnsks.
50L According
to My50L
ySQL ndheres to nenrÌy nÌÌ ANSI SQL stnndnrds. In
fnct, MySQL frequentÌy extends those stnndnrds,
offering more functionnÌity nnd µower for dntnbnse oµerntions
nnd working with dntn.
This chnµter exµnnds uµon the dntnbnse exnmµÌe
thnt I`ve been deveÌoµing throughout the book. As µnrt of the
exµnnsion, I exnmine mnny SQL stntements, their syntnx, nnd
their use.
Iirst, I exnmine some utiÌity nnd ndministrntive commnnds in
MySQL, which Ìny the groundwork for Ìnter stntements. Dntn
Definition Lnngunge (DDL) is covered next, nÌong with the
steµs to tnke when you crente or deÌete dntnbnses nnd tnbÌes.
An exnminntion of Dntn Mnrkuµ Lnngunge (DML) wrnµs uµ the
UtiIity and Administrative
5tatements and Commands
8esides Dntn Definition Lnngunge (DDL) or Dntn Mnrkuµ
Lnngunge (DML) stntements, other stntements nnd commnnds
in MySQL serve vitnÌ µurµoses. Some of these µurµoses nre
ndministrntive, others nre bnsic to the oµerntion of the
dntnbnse nnd the use of its dntn.
5HOW statements
As one who works with numerous comµnnies` dntnbnse sys-
tems, I frequentÌy encounter n new dntnbnse (or revisit one I
hnven`t seen for n yenr or more) nnd need n quick uµdnte. The
stntement quickÌy gets me ncquninted with the structure
C H A P I E k
ln Ihis Chopler
lssulng ullllly ond
commonds ond
Moklng use ol Dolo
Dellnlllon Longuoge
Ünderslondlng dolo
morkup longuoge
Addlng exomples ol
ond reloled
Part II 5OL EssentiaIs
of n dntnbnse (or thnt of its individunÌ tnbÌes), from there I cnn troubÌeshoot µrob-
Ìems nnd Ìook nt the stnte of the server itseÌf.
The syntnx for the stntement is ns foÌÌows:
In Iigure 9-1, I show two exnmµÌes of the stntement: n simµÌe
stntement, nnd then using the oµtionnÌ modifier. The
modifier is usefuÌ if you don`t know the nnme of the dntnbnse you`re Ìooking for or if
you`d simµÌy Ìike to Ìimit the resuÌts to certnin dntnbnses.
Figure 9-1: Using a SHCW DATAßASES statement to learn about
the databases on the MySCL server.
Chapter 9 5OL According to My5OL
The stntement nnd reÌnted modifiers ennbÌe you to find out whnt
tnbÌes nre in n given dntnbnse. As with the stntement, the
stntement ennbÌes Ìisting of tnbÌes thnt mntch n certnin µnttern vin the
modifier. It is nÌso µossibÌe to Ìist tnbÌes from nnother dntnbnse on the snme server,
even if you`re connected to n different dntnbnse nt the time. In Iigure 9-2, I nm con-
nected to the defnuÌt dntnbnse but I use the stntement to Ìist
tnbÌes from the dntnbnse.
Figure 9-2: The SHCW TAßLES statement is flexible enough that
you can list tables from another database, even if you're not
connected to it at the time.
The stntement cnn nssist in troubÌeshooting nnd evnÌunting
dntnbnse µerformnnce. The stntement gives ndditionnÌ informntion such ns number
of cnched nnd in-use coµies of the tnbÌe. In Iigure 9-8 I connect to the MySQL
server, show tnbÌes from the dntnbnse, nnd then connect with nnother
thrend to µerform n simµÌe seÌection from the customer tnbÌe. Looking nt the oµen
tnbÌes from the dntnbnse, you cnn see thnt the tnbÌe is oµen.
Using the stntement, you cnn gnther informntion nbout the coÌumns
in n tnbÌe. Ior some uses of the stntement, the stntement
cnn be substituted. As with other stntements, the stntement
suµµorts the use of wiÌdcnrds. As with the stntement, the oµtionnÌ
modifier cnn be used to Ìook nt coÌumns from nnother
dntnbnse`s tnbÌes.
Part II 5OL EssentiaIs
Figure 9-3: Looking at open tables in a database
Using the stntement, you cnn determine whnt µriviÌeges you
hnve for the coÌumns in thnt tnbÌe. In Iigure 9-4, I Ìook nt the µriviÌeges for my user-
nnme, , in the coÌumns of the tnbÌe.
Figure 9-4: Using the SHCW FULL CCLUMNS command to look
at the privileges the current user has for the table
Chapter 9 5OL According to My5OL
The stntement nÌso suµµorts the oµtionnÌ
nrgument. The outµut from the commnnd is worth some exµÌnnntion.
Iigure 9-b iÌÌustrntes the outµut from the stntement run ngninst the
tnbÌe from the dntnbnse.
Figure 9-5: Cutput from the SHCW INDEX statement on the
customer table of the ecommerce database
I am using the or output type for the statement to
produce output that is easier to understand.
Irom the outµut in Iigure 9-b, you cnn see the tnbÌe nnme is nnd the
vnÌue of is O. A vnÌue of O in the fieÌd menns thnt the index
cnnnot contnin duµÌicntes, which is the cnse for the tnbÌe. The
is which shows thnt this index is nctunÌÌy the Primnry Key index for the
tnbÌe. As no records nre in the tnbÌe yet, the vnÌue is 1. The
is nn nbbrevintion for Sequence In Index.
The vnÌue in the fieÌd shows the nnme of the indexed coÌumn (in this
cnse, the coÌumn). The coÌÌntion coÌumn indicntes the sorting for
the index (in this cnse, A for osccnJinµ), this vnÌue couÌd nÌso be , which wouÌd
indicnte no sorting. indicntes the number of unique vnÌues in the
index. 8ecnuse no records exist in this tnbÌe, the vnÌue is O in the exnmµÌe.
The fieÌd indicntes how much of n coÌumn is indexed when onÌy n certnin
number of chnrncters nre indexed. This vnÌue is when the entire key is
indexed, ns is the cnse in the exnmµÌe. IinnÌÌy, the fieÌd serves to deter-
mine whether the index is n index, which it is not for the exnmµÌe shown.
Part II 5OL EssentiaIs
The stntement is much Ìike other stntements, it wiÌÌ
ncceµt wiÌdcnrds. If no wiÌdcnrd nrgument is given, the stntement returns the
tnbÌe stntus for ench tnbÌe in the dntnbnse. This cnn be quite n bit of informntion, so
I recommend using n µnger to sµÌit the outµut ~or using n wiÌdcnrd to Ìimit
the outµut to the tnbÌe(s) you wnnt informntion nbout.
If you're unsure of how to use a pager to divide data, refer to Chapter 8.
Using the stntement, nÌong with the modifier to Ìimit the
outµut, I cnn exnmine the outµut in grenter detniÌ, ns in Iigure 9-6.
Figure 9-6: Limiting the output of the SHCW TAßLE STATUS
statement with the LIKE modifier
The nnme of the tnbÌe, , shouÌd be obvious. The of the tnbÌe is the
defnuÌt for this dntnbnse server, .
Cther table types are covered in Chapter 10.
The for the tnbÌe is but couÌd nÌso be or .
8ecnuse this tnbÌe contnins no dntn, the , , nnd
nÌÌ hnve vnÌues. A couµÌe of infrequentÌy used vnÌues nre the
vnÌue (which indicntes the mnximum ncceµtnbÌe vnÌue for the dntn fiÌe) nnd the
vnÌue (which indicntes the Ìength of the index). The
vnÌue wouÌd indicnte nny nÌÌocnted-but-unused bytes of dntn in the dntnbnse.
A sometimes-usefuÌ vnÌue is the fieÌd, which in this instnnce is
becnuse this tnbÌe contnins no nuto-incremented coÌumns. I`ve been invoÌved in cnses
Chapter 9 5OL According to My5OL
where n dntnbnse oµerntor uµdntes nn nuto-increment fieÌd nnd thus throw it out of
sync. Using the stntement I cnn find out whnt the next vnÌue is
nnd work from there to determine whnt it needs to be with n stntement.
The nnd show when the tnbÌe wns crented nnd when it
wns uµdnted, if different. As you cnn see from the exnmµÌe in Iigure 9-6, the tnbÌe
hnsn`t been uµdnted. The vnÌue of the is for this tnbÌe, which
indicntes thnt it hnsn`t been checked using n tooÌ such ns or nn
stntement. The fieÌd is nÌso bÌnnk ns there were no
extrn oµtions given to the stntement thnt µroduced this tnbÌe. IinnÌÌy, the
vnÌue of the fieÌd is bÌnnk ns weÌÌ becnuse no comment wns given with the
stntement for this tnbÌe.
The stntement Ìists the stntus of mnny server vnrinbÌes. The outµut is
the snme ns the extended- commnnd. SimiÌnrÌy, the
stntement nÌso hns informntion thnt cnn be obtnined
through n commnnd. The stntement shows vnrious
settings for vnrinbÌes of the MySQL Server. 8oth stntements return quite n bit of
informntion so I recommend using n µnger in the CLI to mnke the outµut more mnn-
For more information on the and statements,
see Appendix A or in Chapter 10.
The stntement shows the current thrends oµen on the
dntnbnse incÌuding the first 1OO chnrncters of the query thnt the thrend is running.
Given the modifier, the stntement shows the entire query.
5HOW CkANI5 FOk <user>
The stntement, which I refer to simµÌy ns ,
ennbÌes you to find out quickÌy the µriviÌeges thnt n given user hns on n server ~
nnd the stntements you wouÌd hnve to issue if you were to give thnt user those
snme µriviÌeges.
Ior exnmµÌe, one tnsk I nm confronted with frequentÌy is giving n user nccess to n
new dntnbnse system ns new servers nre imµÌemented. The user nÌmost nÌwnys
needs the snme nccess ns they hnve on the existing system. Using the
stntement, I cnn quickÌy find out their current µriviÌege ÌeveÌ nnd recrente it on the
new server. The stntement cnn be n grent timesnver (even if some IT
µros stiÌÌ teÌÌ the user thnt the chnnge tnkes nt Ìenst 48 hours nnd use the extrn time
to µÌny video gnmes).
Iigure 9-7 shows the grnnts for n few different users in my test dntnbnse. As you cnn
see, the nccount hns µriviÌeges onÌy from the ~nnd onÌy on the
dntnbnse. In nddition, nn error is shown in Iigure 9-7 ns weÌÌ. This error
occurs becnuse the given user doesn`t hnve µriviÌeges to connect from other hosts.
To correct the error, I simµÌy sµecify the host from which the user hns µriviÌeges.
Part II 5OL EssentiaIs
Figure 9-7: The SHCW CRANTS statement is quite useful in
determining what privileges a given user has on a database.
The outµut from the stntement gives you the
SQL required to recrente the tnbÌe sµecified by . In Iigure 9-8, I exe-
cute the stntement for the tnbÌe of the
exnmµÌe dntnbnse. Notice thnt I use the switch to µroduce outµut in
verticnÌ mode to mnke the on-screen disµÌny ensier to comµrehend.
Figure 9-8: The SHCW CREATE TAßLE statement executed against
the manufacturer table in the ecommerce example database
Chapter 9 5OL According to My5OL
Using the outµut from the stntement in Iigure 9-8, you couÌd coµy nnd µnste the
SQL into n text editor for nrchivnÌ µurµoses ~or you couÌd µnste it into nnother
MySQL CLI nnd quickÌy recrente the tnbÌe.
For other methods of creating and recreating tables in MySCL, see Chapter 10.
The , , nnd stnte-
ments nre used with reµÌicntion nnd nre thus beyond the scoµe of this chnµter.
For more information on the , , and
commands, see Chapter 18 or Appendix A.
Though not incredibÌy difficuÌt to use, I beÌieve it usefuÌ to cover the or
mntching stntement. I`ve been using the stntement throughout the
exnmµÌes in the book. 8oth the USL nnd CONNLCT stntements µerform the snme
nction, the stntement wns ndded to MySQL for Sybnse comµntibiÌity. Use the
} stntement to connect to nnother dntnbnse from in the CLI.
The syntnx for the or stntements is
Ior exnmµÌe, in Iigure 9-9, I utiÌize the nnd stntements to µerform
stntements nnd queries on n few different dntnbnses. Notice the difference in feed-
bnck from the server between the two stntements.
Figure 9-9: Using the CCNNECT and USE statements to perform
queries on different databases
Part II 5OL EssentiaIs
The stntement µrovides much of the snme functionnÌity ns the
stntement. The stntement, which is µrovided to for OrncÌe com-
µntibiÌity, cnn be nbbrevinted ns nnd cnn nÌso be utiÌized with wiÌdcnrd chnrnc-
ters such ns underscore ( ) nnd µercent ( ). The syntnx for the
stntement is
The stntement destroys n sµecified thrend thnt is using the MySQL dntnbnse
server. The syntnx for the stntement is
The vnÌue for · cnn be obtnined vin n stnte-
ment or with the commnnd. The
commnnd cnn nÌso kiÌÌ thrends ~n µrocess simiÌnr to kiÌÌing nnother user`s µrocess
in Linux (the oµerntion requires suµeruser stntus). In MySQL, you must hnve the
µriviÌege before you cnn kiÌÌ thrends owned by other users.
OPIIMIIE IAßLE <toblenome>
The stntement exnmines n tnbÌe nnd mnkes it more
efficient where µossibÌe. The stntement µerforms the oµtimizntions by reµniring the
tnbÌe nnd defrngmenting the dntnbnse fiÌe. The syntnx for the
stntement is
Ior tnbÌes thnt hnve suffered mnny deÌetes or chnnges to fieÌds such ns ,
, or , the stntement cnn mnke
reµnirs nnd uµdnte indexes to mnke the tnbÌe oµernte more efficientÌy. Using the
stntement chnnges the vnÌue of the fieÌd when µer-
forming n stntement. (The stntement is
much the snme ns running n on the tnbÌe, though with onÌy certnin
oµtions set.)
Although the statement is running, the table is locked.
Chapter 9 5OL According to My5OL
Data Definition Language
Dntn Definition Lnngunge (DDL) refers to the stntements nnd functions used to cre-
nte the frnmework nnd ruÌes for working with dntn. Using n DDL stntement, you
don`t work with dntn directÌy, rnther, you crente or nÌter the dntnbnse itseÌf (or the
tnbÌes in the dntnbnse).
DDL stntements cnn crente nnd deÌete dntnbnses or crente, nÌter, nnd deÌete tnbÌes.
I`ÌÌ exnmine mnny DDL stntements in the uµcoming µnges in the context of the
dntnbnse exnmµÌe thnt I`ve been deveÌoµing throughout the book.
In addition to the DDL statements covered here, Appendix A also contains an in-
depth walk-through of SCL syntax.
DeIeting tabIes
LventunÌÌy I`m going to |ust deÌete nnd re-crente the dntnbnse exnmµÌe
thnt I`ve been working with throughout the book. Though it isn`t renÌÌy necessnry to
deÌete or droµ n dntnbnse, I thought it wouÌd be he̵fuÌ to show nn exnmµÌe of
deÌeting}droµµing n tnbÌe from the exnmµÌe dntnbnse thnt I`ve been
working on.
The syntnx for droµµing n tnbÌe is
The keywords cnn be given to µrevent nn error if the tnbÌe doesn`t exist.
You cnn nÌso deÌete more thnn one tnbÌe with the commnnd, ns indicnted by the
In Iigure 9-1O I connect to the MySQL server nnd connect to the
dntnbnse so I cnn droµ the tnbÌe, ns shown.
Figure 9-10: Deleting a table from the ecommerce database
Part II 5OL EssentiaIs
Deleting tables is a permanent action with no confirmation. Deleting a table
deletes not only the table structure, but also the data contained in the table. In
addition, deleting a table is not a transactional process; when a
statement is issued, it is immediately committed.
DeIeting and creating databases
As the next steµ in continuing my dntnbnse exnmµÌe, I`d Ìike to stnrt
fresh so everyone is using the snme dntnbnse design nnd dntn. To do so, I use the
stntement to deÌete the existing dntnbnses crented in µrevious
The syntnx for the stntement is
The syntnx for droµµing n dntnbnse with is
In µrevious chnµters, I crented n couµÌe of different dntnbnses, one cnÌÌed
nnd the other cnÌÌed . Dntnbnses cnn be deÌeted using the MySQL
CLI or with the commnnd. An exnmµÌe of ench is shown in Iigure 9-11.
Figure 9-11: Dropping databases via the MySCL CLI and the
mysqladmin command
As you cnn see in Iigure 9-11, droµµing n dntnbnse in the MySQL CLI offers no con-
firmntion, thus I recommend using the commnnd to droµ dntnbnses ns
it offers n confirmntion µromµt before droµµing the dntnbnse.
Chapter 9 5OL According to My5OL
Now thnt the dntnbnses hnve been droµµed, I cnn stnrt n new dntnbnse ~nÌso
cnÌÌed (becnuse I µÌnn to use it with the site I deveÌoµ in
Ìnter chnµters). The syntnx for crenting n dntnbnse is
A dntnbnse cnn nÌso be crented with the commnnd:
In Iigure 9-12 I recrente the dntnbnse using the
Figure 9-12: Creating the ecommerce database via the CLI
Creating tabIes
Now thnt I hnve n dntnbnse, it`s time to crente the tnbÌes to nctunÌÌy hoÌd the dntn.
The syntnx for the stntement is
As you cnn see the stntement is quite simµÌe on its fnce. However numerous
oµtions, mnny of which nre beyond the scoµe of this chnµter, mnke the
stntement µowerfuÌ.
The statement and its options are detailed completely in
Appendix A.
Part II 5OL EssentiaIs
The µortion of the stntement is where you incÌude sµecific
informntion such ns coÌumn nnmes nnd tyµes, µrimnry keys, indexes, nnd con-
strnints. The snmµÌe stntements for the dntnbnse
(shown Ìnter in the chnµter) give you n Ìook nt coÌumn tyµes nnd some of their
One frequentÌy nsked question~nnd source of confusion~is the
oµtion. You cnn ndd the keyword ns n coÌumn oµtion when crent-
ing n tnbÌe. A tnbÌe cnn hnve onÌy one coÌumn, thnt coÌumn must
be n key ns weÌÌ.
When you insert dntn into n tnbÌe with nn coÌumn, the dntnbnse
nutomnticnÌÌy ndds 1 to the Ìnst vnÌue of the nuto-incremented coÌumn. 8y defnuÌt,
the vnÌue stnrts with 1. If you wnnt the dntnbnse to stnrt with n
different initinÌ vnÌue, you cnn ndd this µreference ns n tnbÌe oµtion when you crente
the tnbÌe.
In the µrevious exnmµÌe, the tnbÌe wouÌd be crented nnd the first vnÌue inserted into
the tnbÌe wouÌd receive n vnÌue of 1O in the coÌumn.
With the dntnbnse crented, I cnn now crente the tnbÌes from the dntn
design µroduced in Chnµter 7. The dntnbnse design is ns foÌÌows:
Chapter 9 5OL According to My5OL
The table layout is available in electronic format on the CD-RCM so you can
easily import the design into MySCL.
Using the tnbÌe Ìnyout from the CD-ROM, you cnn coµy nnd µnste tnbÌes into the
MySQL CLI. AÌternntiveÌy, you couÌd rend the fiÌe through the CLI directÌy (though
doing so is beyond the scoµe of this chnµter).
In Chapter 10 I'll show examples of importing data and definitions into MySCL.
In Iigure 9-18, I tnke n coµy of the tnbÌe definitions nnd µnste them into the CLI. As
you cnn see the commnnds comµÌete successfuÌÌy. 8y µroducing stntements in
nnother nµµÌicntion nnd snving them, you nÌwnys hnve n quick nnd ensy nÌternntive
to re-crenting or redoing those stntements from scrntch.
AItering tabIes
InevitnbÌy there comes in time in nÌÌ dntnbnses` Ìives when their tnbÌes wiÌÌ need to
be nÌtered. This cnn hnµµen for nny number of rensons ~incÌuding n chnnge in
business ruÌes, nn uµgrnde to nn nµµÌicntion, or nn oversight during the design of
the dntnbnse. The syntnx for the stntement is ns foÌÌows:
üo the
Part II 5OL EssentiaIs
As you cnn see, this is quite n comµÌex stntement with mnny oµtions (some of
which nre beyond the scoµe of this chnµter).
In Appendix A you'll find more information on the statement.
8ehind the scenes, the stntement mnkes n temµornry coµy of the
tnbÌe nnd then µerforms the chnnge on the new tnbÌe before deÌeting the oÌd tnbÌe.
The onÌy exceµtion to this behnvior is the function, which does not crente n
temµornry coµy of the tnbÌe. Any uµdntes mnde whiÌe nn stntement is
being µerformed wiÌÌ be mnde on the temµornry coµy nnd thus not Ìost.
Figure 9-13: Pasting statements into the CLI is a good way to
increase productivity.
Chapter 9 5OL According to My5OL
MySQL offers some extensions to the ANSI92 SQL stnndnrd with the
stntement. SµecificnÌÌy, this incÌudes the keyword, which cnuses MySQL to
ignore nny duµÌicnte vnÌues in n µrimnry key or in n unique coÌumn tyµe. When n
duµÌicnte vnÌue is found, MySQL onÌy uses the first instnnce of thnt vnÌue. MySQL
nÌso ennbÌes muÌtiµÌe nÌterntions to be µerformed in the snme
Mnny tnbÌe nÌterntions invoÌve chnnging n coÌumn tyµe or ndding n coÌumn. 1ust ns
common for the dntnbnse ndministrntor, however, nre tnsks such ns rennming n
tnbÌe nnd ndding indexes.
Ior exnmµÌe, Iigure 9-14 nÌters the tnbÌe to ndd n coÌumn. The figure
shows the tnbÌe structure before nnd nfter this µrocess, vin n stntement
(exµÌnined enrÌier in this chnµter).
Figure 9-14: The Customer table layout before an ALTER TAßLE
statement, the ALTER TAßLE statement, and the table structure after
the ALTER TAßLE statement
8ecnuse I don`t wnnt the coÌumn to be ndded to the tnbÌe, I
hnve n good oµµortunity to demonstrnte how to deÌete or droµ n coÌumn from n
tnbÌe. Iigure 9-1b describes the tnbÌe structure both before nnd nfter the
stntement droµs n coÌumn.
Part II 5OL EssentiaIs
Figure 9-15: The Customer table layout with the extra column both
before and after the column is dropped
As you cnn see by Iigure 9-1b, the new coÌumn, , wns ndded to the end of
the tnbÌe definition. If I wnnted to ndd the new coÌumn to the beginning of the tnbÌe,
or µut it in n Ìocntion where it might be more intuitive ~sny, nenr the nddress or
ZIP code ~I couÌd use the or keywords on the stntement to do so.
Iigures 9-16 nnd 9-17 describe the current tnbÌe Ìnyout, run the stnte-
ment with the nnd keywords, nnd then describe the tnbÌe Ìnyout nfter
the µrocess is comµÌete.
ßehind the scenes, I dropped the column between examples to assist with this
Don't forget to drop the extra column from the table before
You cnn chnnge coÌumn nnmes nnd definitions nt the snme time with the
keyword. Ior exnmµÌe, I`d Ìike to chnnge the coÌumn to
simµÌy becnuse I`m nn inherentÌy Ìnzy tyµist nnd thnt`s four Ìetters shorter. In Iigure
9-18, I used the keyword to rennme the coÌumn, note thnt both coÌumns
shnre the snme coÌumn definition.
Chapter 9 5OL According to My5OL
Figure 9-16: Altering the Customer table to add the new column at
the top of the table, using the FIRST keyword
Figure 9-17: Altering the Customer table to add a new column at a
specific location in the table definition
Part II 5OL EssentiaIs
Figure 9-18: Using the CHANCE keyword to rename a column
I couÌd use n different definition when chnnging the coÌumn ns weÌÌ. Since
Iigure 9-18 wns n reÌntiveÌy simµÌe exnmµÌe of rennming n coÌumn, I didn`t need to
chnnge the coÌumn definition. To mnintnin consistency with the tnbÌe definitions
used throughout the book, I chnnged the coÌumn nnme bnck to
, µÌense do so in your dntnbnse ns weÌÌ.
You cnn nÌso modify the coÌumn definition through the use of the keyword.
In Iigure 9-19, I modify the coÌumn in the tnbÌe to
nÌÌow nnme Ìengths of uµ to 7b chnrncters.
ße sure to change the length of the column back to 50 to main-
tain consistency with later examples.
AÌthough I don`t need to ndd nny µrimnry keys to the exnmµÌe tnbÌes, it is usefuÌ for
you to know thnt this cnn be done with the stntement. You mny hnve
to ndd n µrimnry key when you`re imµroving n tnbÌe design.
Another method for imµrovement ~nfter the tnbÌe hns been crented ~is to ndd n
non-µrimnry key index. You cnn use the 8LL stntement to ndd nn index to
the tnbÌe nt nny time nfter the tnbÌe is crented. In effect, the stnte-
ment is nn nÌins for nn stntement.
You mny hnve to rennme n tnbÌe nt some µoint, the stntement cnn
µerform this tnsk ns weÌÌ. The syntnx for rennming n tnbÌe is
Chapter 9 5OL According to My5OL
Figure 9-19: Using the MCDIFY keyword to lengthen the
contact_name column
The word in brackets, though it's optional, can help make the statement more
easily understandable.
Data Markup Language
Dntn Mnrkuµ Lnngunge (DML for short) refers to SQL stntements thnt work with nnd
mnniµuÌnte dntn in n dntnbnse. RecnÌÌ thnt Dntn Definition Lnngunge or DDL stnte-
ments work with the nctunÌ structure of ob|ects in n dntnbnse such ns the dntnbnse
itseÌf, or tnbÌes nnd coÌumns in n dntnbnse.
DML incÌudes such stntements ns , , , nnd . I wiÌÌ exnm-
ine ench in the context of the dntnbnse exnmµÌe where µossibÌe.
In addition to the DML statements covered here, Appendix A also contains an in-
depth walk-through of SCL syntax.
Inserting data into the database with IN5EkI
Any considerntion of DML brings uµ the question of which DML stntement to cover
first ~ or . It is nnother version of the chicken-nnd-egg question.
AÌthough you cnn`t seÌect dntn without first inserting it, the stntement is not
the onÌy wny to insert dntn (see Chnµter 1O for more informntion). 8ecnuse the
stntement is (µerhnµs) the most obvious method, I exnmine it first.
Part II 5OL EssentiaIs
The syntnx for the stntement is
Three vnrintions of the stntement exist. The syntnx is renÌÌy strnightforwnrd
for nÌÌ three vnrintions, with the µossibÌe exceµtion of the keywords ,
, nnd . The oµtionnÌ keyword is µrovided to imµrove rendnbiÌ-
ity of the stntement. Though it mny come ns n surµrise (since I`m histori-
cnÌÌy n Ìnzy tyµist), I use the stntement in most, if not nÌÌ, of my
Commns seµnrnte vnÌues for coÌumns in nn stntement. If you don`t sµecify
coÌumn nnmes, MySQL exµects thnt you wiÌÌ µrovide vnÌues for ench coÌumn in the
tnbÌe. If no vnÌue is µrovided for n given coÌumn, the insert fniÌs nnd returns nn
error. You cnn use ns n µÌncehoÌder for coÌumns thnt you don`t wnnt to µro-
vide vnÌues for with the insert. AdditionnÌÌy, you cnn use two singÌe or doubÌe
quotes to Ìenve those fieÌds bÌnnk. However, using singÌe or doubÌe quotes instend
of in n coÌumn µuts different vnÌues in those coÌumns thnn wouÌd be there if
they were sµecified ns .
If you wnnt to onÌy set vnÌues for certnin coÌumns you must enumernte those
coÌumns in the stntement. Ior exnmµÌe, in the dntnbnse exnm-
µÌe I hnve n smnÌÌ mnnufncturer for one of the µroducts. The mnnufncturer does not
require n seµnrnte contnct nnme. 8y enumernting the coÌumns thnt I wnnt to insert
into, I cnn forego µÌncing nny vnÌue in the coÌumn for this entry, ns in
Iigure 9-2O.
You shouÌd execute the stntement in Iigure 9-2O to µreµnre for other exnm-
µÌes (Ìnter in this chnµter) thnt use it. The commnnd Ìooks Ìike this:
If you nttemµt to insert n vnÌue Ìonger thnn the coÌumn for coÌumn tyµes such ns
, , nnd , the µortion of the vnÌue thnt exceeds the coÌumn Ìength
wiÌÌ be Ìost. In Iigure 9-21, I Ìook nt the exnmµÌe tnbÌe cnÌÌed , which
hns one coÌumn cnÌÌed . The coÌumn nÌÌows n mnximum Ìength of
Chapter 9 5OL According to My5OL
1O chnrncters for dntn. I nttemµt to insert the 14-chnrncter nnme
into the coÌumn. As you cnn see by the stntement foÌÌowing the
, the vnÌue wns truncnted to ten chnrncters.
Figure 9-20: Inserting values into some columns of a table is
possible by specifying the column names.
Figure 9-21: Inserting a value longer than the designated length
truncates the data.
When inserting n vnÌue, nn exµression cnn be used on n µreviousÌy inserted vnÌue.
An exnmµÌe is Iigure 9-22, in which I connect to n test dntnbnse nnd show n descriµ-
tion of the exnmµÌe tnbÌe cnÌÌed . Two coÌumns refer to qunntity in this
tnbÌe ~ nnd . I insert n vnÌue of 1O for , nnd
wouÌd Ìike to hnve n totnÌ of - 2O of these widgets on hnnd. Therefore I
use nn exµression to ndd 2O to whntever the vnÌue of is for the
Part II 5OL EssentiaIs
Figure 9-22: Using an expression with an INSERT statement to
insert a value that's based on a previously inserted value.
The nnd keywords modify how, or more nµµroµrinteÌy,
when the insert is done. With the keyword the insert is heÌd untiÌ no
other cÌients nre rending from the tnbÌe. Ior mnny tnbÌes, this cnn tnke quite n Ìong
time ~nnd the cÌient thrend cnn`t continue untiÌ the oµerntion is com-
µÌeted. If you use the keyword with n MyISAM tnbÌe tyµe, you cnn`t
run more thnn one stntement nt n time, I don`t recommend using the
keyword with n tnbÌe tyµe unÌess you hnve sµecific needs.
The keyword, n MySQL extension to the ANSI SQL stnndnrd, returns nn OK
to the inserting cÌient immedinteÌy. This cnn grentÌy imµrove µerformnnce of nµµÌi-
cntions where n tnbÌe mny be under henvy use nnd where the nµµÌicntion or cÌient
cnnnot wnit for the to comµÌete. Ior exnmµÌe, if you run n stnte-
ment on n tnbÌe nnd thnt stntement tnkes n Ìong time to comµÌete, the nµµÌicntion
nttemµting to µerform nn insert on the tnbÌe mny nµµenr to be Ìocked uµ or frozen.
Using the stntement for such nn nµµÌicntion mny µrove beneficinÌ.
However, since tnbÌes suµµort simuÌtnneous seÌects nnd inserts, using the
stntement might not µrovide nny µerformnnce imµrovement.
The nctunÌ stntement is µÌnced in n voÌntiÌe-memory-bnsed queue to be exe-
cuted when no other thrends nre using the tnbÌe. ShouÌd the MySQL server crnsh,
be kiÌÌed, or otherwise stoµ for nny renson, the contents of the
queue thnt hnven`t been executed nre Ìost. Ior exnmµÌe, if you hnve four inserts
thnt nÌÌ use the stntement, two of them get executed nnd then the
MySQL server dies, the remnining two stntements nre Ìost.
The statement only works with the and table
Chapter 9 5OL According to My5OL
The keyword teÌÌs MySQL to ignore nny duµÌicnte vnÌues for n µrimnry key
or unique coÌumn. If the keyword is not sµecified nnd n duµÌicnte vnÌue is
encountered, MySQL stoµs the insert µrocess nnd returns nn error. If n duµÌicnte
vnÌue is encountered nnd the keyword is used, thnt row of dntn is not
inserted into the tnbÌe.
The uµcoming sections exnmine ench of the three vnrintions in turn.
Ihe IN5EkI ... VALUE5 ... variation
The syntnx for such nn stntement is
I`ve nÌrendy given n couµÌe exnmµÌes using this syntnx. At the most bnsic ÌeveÌ, the
syntnx for this vnrintion of the INSLRT stntement is
To fnciÌitnte exnmµÌes thnt nµµenr Ìnter in this chnµter, I insert some snmµÌe dntn
for two of the tnbÌes in the dntnbnse ~nnd into ndditionnÌ tnbÌes by
using the other vnrintions of the stntement. The oµerntion Ìooks Ìike this:
Iigure 9-28 shows the resuÌts of the stntements |ust given, ns they nµµenr when you
use the CLI in internctive mode.
Another method for inserting vnÌues into n tnbÌe is to seµnrnte them with n commn
in the snme stntement.
Part II 5OL EssentiaIs
Figure 9-23: Running an INSERT statement to insert sample data
into the ecommerce database
Ihe IN5EkI ... 5EI ... variation
Another method for inserting dntn into n tnbÌe with the stntement is vin the
syntnx. Using the vnrintion you cnn set vnÌues for
coÌumns individunÌÌy. This is µnrticuÌnrÌy usefuÌ when you onÌy need to set n smnÌÌ
number of coÌumns in n Ìnrge tnbÌe. The bnsic syntnx of this vnrintion is ns foÌÌows:
In nddition, the syntnx cnn nÌso he̵ rendnbiÌity. I`ÌÌ go bnck to the
exnmµÌe nnd insert some cities into the tnbÌe by using the syntnx:
Ihe IN5EkI ... 5ELECI ... variation
The third vnrintion of the stntement is the vnrintion.
Using this method you cnn bnse the vnÌues for the on the resuÌts from n
stntement. The syntnx for such nn insert is
Chapter 9 5OL According to My5OL
To quickÌy µoµuÌnte the customer tnbÌe with the e-mniÌ nddresses thnt I µut in the
tnbÌe enrÌier, I cnn use nn stntement. I cnn then
uµdnte the rows of dntn Ìnter to fiÌÌ in the rest of the dntn:
The µrevious stntement nnd the resuÌts nre shown in Iigure 9-24.
Figure 9-24: Using the INSERT ... SELECT ... statement to populate
the customer table of the ecommerce example, using data contained
in the locale table
Cathering data with 5ELECI
8y nnd Ìnrge, the stntement is used more frequentÌy thnn the stnte-
ment. NormnÌÌy you wouÌd use the stntement to µut dntn into the dntnbnse
onÌy once, n query for Ìooking for dntn uses the stntement more thnn once.
The nctunÌ rntio of queries to inserts is ÌnrgeÌy determined by the nµµÌicntion.
The syntnx for the stntement is ns foÌÌows:
Part II 5OL EssentiaIs
As you cnn see the stntement hns mnny oµtions, some of which nre beyond
the scoµe of this chnµter. Numerous oµerntors nnd functions cnn be used in n
stntement, I`ÌÌ Ìook nt some of them through exnmµÌes.
In Appendix A the statement's syntax is examined along with a complete
list of operators and functions to be used with the statement.
ProbnbÌy the most bnsic of stntements is n simµÌe:
The exµression in this exnmµÌe uses the nsterisk wiÌdcnrd to nsk MySQL for
nÌÌ dntn in nÌÌ coÌumns in the tnbÌe cnÌÌed . Ior exnmµÌe, in Iigure 9-2b I
µerform n query for nÌÌ dntn in the tnbÌe of the MySQL dntnbnse.
Figure 9-25: Cne of the most basic queries is a SELECT * from
<tqb/enqme>. In this case, the query calls for all data in the user
table of the database that contains MySCL privileges and grants.
In n seÌect exµression you cnn use nÌinsing through the use of the keyword. This
cnn be usefuÌ when using n comµÌicnted exµression nnd you wnnt to mnke
the resuÌts return ns n more user-friendÌy or rendnbÌe coÌumn nnme. An nÌins cnn
nÌso nssist if you wnnt to recnÌÌ n µortion of the exµression in nnother µor-
tion of the stntement.
Chapter 9 5OL According to My5OL
CÌenrÌy, the µower of the stntement Ìies in the modifier, you use thnt
modifier to sµecify the resuÌts thnt you wouÌd Ìike to see from the query. Ior exnm-
µÌe, using the modifier with the µrevious stntement I
cnn determine informntion nbout onÌy n certnin user. Adding n modifier to
the Ìook for informntion on the user mnkes the resuÌts more usefuÌ:
The resuÌts of the query nre in Iigure 9-26.
Figure 9-26: Adding a WHERE modifier to the SELECT statement
to make the results more useful
As you cnn see from the simµÌe exnmµÌes I`ve µrovided, the stntement
ncceµts wiÌdcnrd chnrncters. You cnn nÌso µÌnce wiÌdcnrd chnrncters in the
µortion of the stntement ns weÌÌ. To ennbÌe the wiÌdcnrd chnrncters to work, you
sÌightÌy modify the µortion by substituting the word for the equnÌs sign
( ). The nsterisk ( ) is frequentÌy the wiÌdcnrd to mntch or chnrncters
~but the nsterisk does not work in the µortion of n stntement. The
µercent sign ( ) is n substitute for -or wiÌdcnrd. Ior exnm-
µÌe, µeoµÌe frequentÌy forget how to sµeÌÌ my Ìnst nnme, Suchrinµ. Using the
function in the stntement, I couÌd µut n µortion of my nnme in nnd stiÌÌ
come uµ with vnÌid resuÌts, ns shown in Iigure 9-27.
Now the stntement Ìooks Ìike this:
Part II 5OL EssentiaIs
Figure 9-27: Using the LIKE function instead of the equals sign for
finding information with a wildcard
Another wiÌdcnrd, the underscore ( ), cnn be used to substitute one chnrncter.
Going bnck to the sµeÌÌing of my nnme ns nn exnmµÌe, µeoµÌe frequentÌy trnnsµose
the h nnd the r, missµeÌÌing the nnme ns Sucrhinµ. To find such instnnces, I couÌd
use two underscores together, Ìike this:
As you cnn see from Iigure 9-28, the resuÌts end uµ the snme.
Figure 9-28: Using the underscore as a wildcard to match one
character inside a SELECT statement
Chapter 9 5OL According to My5OL
I`ÌÌ come bnck to the modifier. Ior now, I need to |umµ bnck to the nctunÌ
seÌect µortion of the stntement. Uµ untiÌ this µoint I`ve been using the nster-
isk to seÌect nÌÌ coÌumns. You cnn nÌso seÌect mnny other items with the
stntement incÌuding sµecific coÌumns nnd the resuÌts of functions on coÌumns. Ior
exnmµÌe, if I wnnted to onÌy determine which hosts the user is nÌÌowed
to connect from, I couÌd µerform the foÌÌowing query (the resuÌts of which nre
shown in Iigure 9-29):
Figure 9-29: Selecting certain columns with the SELECT statement
5ELECI functions
Numerous functions cnn be used in stntements ~some nre usefuÌ to know
(nnd hnve nround for reference), regnrdÌess of whether you use them with n
dntnbnse. This section, however, highÌights some functions thnt iÌÌustrnte how µow-
erfuÌ MySQL cnn be.
In Appendix A all functions and operators for the statement are covered in
As with mnny other µortions of stntements, functions cnn be nested inside
ench other. Ior exnmµÌe, the foÌÌowing stntement uses two functions, the
nnd the functions. The stntement resuÌts in two dnys being ndded to the cur-
rent dnte, ns determined by the MySQL server:
MySQL nÌso uses functions such ns grenter thnn ( ), Ìess thnn ( ), equnÌs ( ), nnd
the Ìike. Iurther, the use of ÌogicnÌ , , nnd is nÌso suµµorted by MySQL
nnd cÌnuses. Usnge of these functions is µretty intuitive, I µrovide
exnmµÌes throughout this section nnd the rest of the book.
Part II 5OL EssentiaIs
MySQL cnn |oin tnbÌes together in n number of wnys so you cnn seÌect records from
muÌtiµÌe tnbÌes ~or senrch them for mntching records. SeÌecting from muÌtiµÌe
tnbÌes is quite simµÌe, |ust incÌude the tnbÌe nnmes in the stntement nnd
incÌude n method for finding mntching rows. More comµÌicnted |oins nnd unions
cnn nÌso be nccomµÌished with MySQL so you cnn µerform cross-|oins on different
coÌumns in n tnbÌe.
In Appendix A you can see examples of and .
Dates and times with 5ELECI
MySQL incÌudes mnny functions to work with dntes nnd times. These incÌude func-
tions for conversion of dntes nnd times nnd functions to determine where n given
dnte fnÌÌs in n yenr. In TnbÌe 9-1, I Ìist some dnte nnd time functions for use with the
stntement. I`ÌÌ give exnmµÌes of usnge for them foÌÌowing the tnbÌe.
Table 9-1
Date and time functions with the 5ELECI statement
Function Nome Purµose
Returns the current date.
As with , this returns the current time.
Adds onto date, D.
Returns the date in the format specified, see example later
in the chapter.
Subtracts from date, D.
Returns the day of the week for a given date in time.
Returns the day of month for a given date, D.
Returns the day of the week that a given date falls upon.
Returns the day of the year for a given date.
Returns the actual date that is a number of days, D, away.
) Converts a Unix/Linux timestamp from native seconds to a
Return the hour from a given time value, T.
Returns the minute value from a given time, T.
Returns the month value from a given date, D.
Returns the name of the month from a given date, D.
Returns the current date and timestamp.
Chapter 9 5OL According to My5OL
Function Nome Purµose
Adds the number of months, M, to the given date, D.
Subtracts the two dates, D1 and D2.
Returns the quarter of the year for the given date, D.
Returns the second value from a given time, T.
Converts seconds, S, to a time value.
Converts a given time, T, to seconds.
Returns a value for the number of days from now until
date, D.
Converts date, D, to Unix time or returns current Unix
Returns the week of the year for a given date, D.
Returns the day of the week beginning with Monday for a
given date, D.
Returns the year value for a given date, D.
As you cnn see, MySQL incÌudes quite n few functions for working with dntes nnd
times. Some functions convert dntes nnd times, some ndd or subtrnct dntes nnd
time, nnd some functions simµÌy µrovide informntion.
Among those stntements thnt µrovide informntion nre , , nnd
. To use these stntements simµÌy cnÌÌ them with n , ns shown in
Iigure 9-8O.
Figure 9-30: Using the CURTIME() function with select to
determine the current time
Part II 5OL EssentiaIs
Other informntionnÌ functions incÌude those thnt determine n µortion of n dnte or
whnt dny of the week n given dnte fnÌÌs on nnd the Ìike. These incÌude ,
, , , , , , , ,
nnd . Usnge of nÌÌ these is quite simiÌnr, however you mny be curious whnt the
difference is between nnd . Lnch of the two functions returns n
number vnÌue reµresenting n dny of the week. However, returns 1 ns
Sundny, 2 ns Mondny nnd so forth whiÌe returns O ns Mondny, 1 ns
Tuesdny, nnd so forth. Syntnx exnmµÌes foÌÌow, resuÌts nre shown in Iigures 9-81
nnd 9-82.
Figure 9-31: various date determination functions. Note the
difference in determining the DAYCFWEEK versus WEEKDAY
for today (Friday)
Chapter 9 5OL According to My5OL
Figure 9-32: Cther MySCL date determination functions for week,
month, quarter, and year
As with the functions thnt µnrse n dnte nnd return informntion, other functions
µnrse n given time nnd return informntion. These incÌude , , nnd
. As with the functions for working with dnys nnd weeks, the time-bnsed
functions nÌso ncceµt n given dnte}time nrgument nnd return informntion bnsed
on thnt nrgument.
Some MySQL dnte nnd time functions ndd or subtrnct dntes nnd time. Ior exnmµÌe,
nnd µerform nddition nnd subtrnction of dntes, resµectiveÌy.
8oth functions require two nrguments, n dnte nnd nn intervnÌ to ndd or subtrnct. As
stnted µreviousÌy, you cnn nest functions in stntements, this might be n µÌnce where
you wouÌd nest the function in the function to quickÌy determine
the current dnte.
8oth the nnd functions hnve synonyms: nnd
, resµectiveÌy. In nddition, you cnn nÌso use n µÌus sign ( ) nnd minus sign
(~) ns substitutes for the nnd functions. The functions ncceµt
nny vnÌid time intervnÌ such ns yenr, month, dny, hour, nnd even second. ResuÌts
from the foÌÌowing exnmµÌes nre shown in Iigure 9-88.
Part II 5OL EssentiaIs
Figure 9-33: Examples of various date addition and subtraction
functions with MySCL
The functions nnd nÌso ndd nnd subtrnct dntes, though
ench works with months onÌy. With , you ndd n number of months to n
give dnte. With you cnn determine the number of months between
two µseudo-dnte vnÌues. The syntnx Ìooks Ìike these exnmµÌes (resuÌts nµµenr in
Iigure 9-84):
Figure 9-34: Using MySCL's PERICD_ADD and PERICD_DIFF
functions to work with months
Chapter 9 5OL According to My5OL
The nnd functions nre simiÌnr insofnr ns they teÌÌ you the num-
ber of dnys to or from n certnin dnte (see Iigure 9-8b). Ior exnmµÌe, to determine
the dnte in n certnin number of dnys, use the with the number ns the
nrgument. To determine the number of dnys from yenr O to n certnin dnte, use the
function Ìike this:
The functions work with numbers of days since year zero; therefore the values you
use will be quite large.
Figure 9-35: The FRCM_DAYS and TC_DAYS functions in action.
Note the large values used as both of the functions work with
the number of days since year 0.
Some dnte nnd time functions convert dntes nnd times from one formnt to nnother.
These functions incÌude , , , nnd
. Using these functions in con|unction with other time nnd dnte
functions, you cnn trnnsform the dntes nnd times so they nre ensier to understnnd.
In Unix}Linux, mnny nre bnsed uµon the number of seconds. If you hnve n Unix
timestnmµ nnd need to convert thnt to n more ensiÌy rendnbÌe dnte, use the
function. The function gives you the vnÌue of the
Unix time in seconds. You couÌd nest the two functions to retrieve the current dnte,
but why not |ust use the function" The nnd
functions work with times though not necessnriÌy reÌnted to times you`d see on n
cÌock. Thus you cnn use the function to determine how mnny hours n
session wns nctive. Syntnx exnmµÌes foÌÌow (with resuÌts in Iigure 9-86):
Part II 5OL EssentiaIs
Figure 9-36: Time and second based conversion functions in MySCL
Out of the functions, the stntement stnnds out ns unique. This func-
tion tnkes n dnte nnd then determines how you wouÌd Ìike the dnte resuÌt formntted.
Quite n few oµtions exist. TnbÌe 9-2 Ìists the vnrious formntting nrguments thnt you
cnn µrovide to the function.
Table 9-2
Arguments for use with the DAIE_FOkMAI function
4rgument 0elinition
A literal percent sign.
Abbreviated weekday names such as Sun, Mon, and so on.
Abbreviated month names, !an, Feb, and so on.
The month number, where 1 is !anuary.
Numeric day of month with suffix such as 1st, 2nd, and so on.
Two-digit numeric day of month starting with 00, 01, and so on.
Cne-digit numeric day of month starting with 0.
Two-digit numeric hour starting with 00 in 24-hour format.
Chapter 9 5OL According to My5OL
4rgument 0elinition
Cne-digit numeric hour starting with 0 in 12-hour format.
Two-digit numeric hour starting with 01 in 12-hour format.
Two-digit numeric minute starting with 00.
Three-digit day of year starting with 001.
Cne-digit numeric hour starting with 0 in 24-hour format.
Cne-digit numeric hour starting with 1 in 12-hour format.
Long format month name, !anuary, February, and so on.
Two-digit numeric month starting with 01.
AM or PM designation based on the time.
Time in 12-hour format including AM or PM.
Two-digit numeric seconds.
Two-digit numeric seconds, same as %S.
Time in 24-hour format.
Cne-digit numeric week where Sunday is first day of week.
Cne-digit numeric week where Monday is first day of week.
Long format weekday name such as Monday, Tuesday.
Numeric day of week where 0 is Sunday.
Four-digit numeric year.
Two-digit numeric year.
Don`t Ìet the oµtions for the function overwheÌm you. Some syntnx
exnmµÌes for the function nre ns foÌÌows:
The resuÌts from the syntnx exnmµÌes for the function nre shown in
Iigure 9-87.
Part II 5OL EssentiaIs
Figure 9-37: The DATE_FCRMAT function allows customizing of
date and time output to fit your application.
NumericaI functions with 5ELECI
As is the cnse with dntes nnd times, MySQL nÌso incÌudes n rich fenture set of
numericnÌ functions. TnbÌe 9-8 Ìists some of those functions.
Table 9-3
NumericaI functions with the 5ELECI statement
Returns the absolute value of a number, N.
Returns the binary value for the given number, N.
Formats the number, N, to the given decimal place, D.
Provides the highest or greatest number in the given set,
N1, N2, and so on.
Cives the hexadecimal value for a given decimal number, D.
Returns the smallest or least number in the list N1, N2, and
so on.
Returns the modulo value of the two numbers, N1 and N2.
Returns the value of Pi.
Raises a number, N1 to the power of another number, N2.
Rounds a number, N, to the optional decimal places, D.
Determines whether a value is negative, positive, or zero.
Chapter 9 5OL According to My5OL
MySQL`s numericnÌ functions nÌso incÌude nddition, subtrnction, muÌtiµÌicntion, nnd
division. Addition nnd subtrnction functions cnn be cnÌÌed through the use of the
µÌus nnd minus signs, muÌtiµÌicntion uses the nsterisk, nnd division uses the front-
sÌnsh ( ). Ior exnmµÌe, the stntement wouÌd render n resuÌt of 8. The
function returns the moduÌo or remninder from n division of numbers. This
function cnn nÌso be cnÌÌed with the µercent sign ( ).
8eyond the functions Ìisted nbove, MySQL nÌso incÌudes functions for cosine, tnn-
gent, nrc cosine, cotnngent, rnndom, nnd more. Mnny of these functions nre used
onÌy in sµecinÌized nµµÌicntions.
The additional numerical functions for use with MySCL are detailed in Appendix A.
The numericnÌ functions nre renÌÌy strnightforwnrd in their use. Most ncceµt n num-
ber ns nn nrgument. Some interesting functions incÌude the , , nnd
functions. The nnd functions convert n number between formnts binnry
nnd hexndecimnÌ resµectiveÌy. The formnt function is usefuÌ when you hnve extrn
decimnÌ µÌnces nnd wnnt onÌy to use n certnin number of decimnÌ µÌnces in your
nµµÌicntion. Syntnx exnmµÌes nnd resuÌts foÌÌow (see Iigure 9-88). Notice thnt I
snenked in n nested function, , in the function cnÌÌ.
Figure 9-38: Some of MySCL's numerical functions in action
Part II 5OL EssentiaIs
The nnd functions nre simiÌnr insofnr ns they find the mnximum or
minimum vnÌue given n Ìist of numbers, ns shown in Iigure 9-89.
Figure 9-39: The CREATEST and LEAST functions in action
The function cnn be cnÌÌed with or without nn extrn nrgument sµecifying the
number of digits to incÌude nfter the decimnÌ (see Iigure 9-4O). If no extrn nrgument
is given, the function wiÌÌ round to the nenrest whoÌe number.
Figure 9-40: The RCUND function can be called with or without
an argument depending on the precision of rounding that you need.
5tring functions with the 5ELECI statement
Iunctions for working with strings nnd chnrncters nre nn imµortnnt µnrt of MySQL`s
nnd stntements. As with the dnte nnd time functions nnd numericnÌ
functions, mnny string functions nre used in sµecinÌized cnses nnd nµµÌicntions.
TnbÌe 9-4 Ìists mnny string functions used in MySQL.
Chapter 9 5OL According to My5OL
Table 9-4
5tring functions with the 5ELECI statement
Returns the ASCII value of the given character, C.
Returns the actual character when given an ASCII
number(s), N.
Concatenates (joins) the strings, S1, S2 and so on.
Concatenates the strings S1, S2 and so on using separator, S.
Returns the number indicating the position of a string, S, as
located in the field list, S1, S2, and so on.
Converts string, S, into lowercase.
Returns the character length of string, S.
Compares strings via pattern matching.
Loads the contents of file, F, as a string.
Left-pads the string, S, with the number, N, of characters, C.
Trims whitespace from the left of string, S.
Determines the first position of substring, S, in string, S1.
Compares strings with regular expression pattern matching.
Replaces old string, C, with new string, N, in a given string, S.
Reverses string, S.
Right-pads the string, S, with the number, N, of characters, C.
Trims whitespace from the right of string, S.
Returns a string consisting of N spaces.
Compares the two strings, S1 and S2.
Remove string, RS, from string, S (see example following
this list)
Converts string, S, into uppercase.
Out of the string functions, the ASCII nnd functions stnnd out ns unique.
These two functions work with strings to determine or return their ASCII vnÌue.
(See Iigure 9-41.) The function cnn ncceµt more thnn one ASCII number in the
nrgument Ìist.
Part II 5OL EssentiaIs
Figure 9-41: The ASCII and CHAR functions. Notice that when given
more than one argument, the CHAR value returns the corresponding
values without any separation.
The nnd functions nÌong with the nnd functions both µer-
form simiÌnr duties. The nnd functions oµernte on the Ìeft side of n
string whiÌe the nnd functions oµernte on, you guessed it, the right side
of n string. The nnd functions remove whitesµnce from n string whiÌe
the nnd functions ndd n sµecified number of chnrncters to n string to
mnke it n certnin Ìength. The chnrncters to be ndded with nnd cnn be
whitesµnce or other chnrncters. The totnÌ Ìength of the string wiÌÌ be the Ìength
sµecified, nny initinÌ string Ìonger thnn thnt Ìength gets trimmed. (See Iigure 9-42.)
A somewhnt different function for removing chnrncters from n string is . 8oth
the nnd functions onÌy remove whitesµnce chnrncters. However, with
you cnn sµecify the chnrncter or string to remove. With you cnn nÌso
sµecify whether to remove the chnrncters from the Ìeft side, right side, or both
sides of the string. The syntnx is somewhnt sµecific for the function. If you
incÌude oµtions such ns , , or TRAILING, you must incÌude the word
in the stntement. The function wiÌÌ remove whitesµnce if you don`t
incÌude nny oµtions such ns , , , or the string to remove. The
commnnd Ìooks Ìike this:
Syntnx exnmµÌes foÌÌow (ns weÌÌ ns resuÌts in Iigure 9-48):
Chapter 9 5OL According to My5OL
Figure 9-42: Some MySCL string functions in action
Figure 9-43: Examples of the MySCL TRIM function
The nnd functions nre nÌso reÌnted. converts n string to nÌÌ Ìower-
cnse chnrncters whiÌe converts the string to nÌÌ uµµercnse chnrncters. The syn-
tnx for their use is the snme nnd is quite simµÌe. The resuÌts nre shown in Iigure 9-44.
Part II 5OL EssentiaIs
Figure 9-44: The UCASE and LCASE functions for converting strings
to upper and lowercase.
Sometimes you |ust need some sµnce. The good news is thnt MySQL incÌudes n
function to µrovide you with ns mnny sµnces ns you`d Ìike. The function is nµtÌy
titÌed nnd exµects the number of sµnces ns nn nrgument. I`ÌÌ use the SPACL
function in nn exnmµÌe with the function.
8oth nnd µerform simiÌnr functions. 8oth functions tnke strings
nnd concntennte or |oin them together. The _WS function ennbÌes you to
sµecify n seµnrntor between the strings, such ns n sµnce. One wny to use the
function is to |oin n first nnme nnd Ìnst nnme seµnrnted by n sµnce:
As nn nÌternntive to the function, you couÌd use the function in
the nrgument Ìist with , Ìike this:
The resuÌts from the syntnx exnmµÌes given here nµµenr in Iigure 9-4b.
Chapter 9 5OL According to My5OL
Figure 9-45: The CCNCAT and CCNCAT_WS functions as well as an
example of the SPACE function
The function tnkes two strings ns nrguments nnd determines whether they
nre the snme. Ior exnmµÌe, consider the foÌÌowing instnnces:
If the strings nre the snme, the function wiÌÌ return O. If the first string is
smnÌÌer thnn the second nccording to the current ordering, the function returns ~1.
The function returns 1 in nÌÌ other cnses. (See Iigure 9-46.)
Part II 5OL EssentiaIs
Figure 9-46: The STRCMP function compares strings and returns an
integer value based upon the results.
Other methods exist for comµnring strings in MySQL. Most notnbÌe is the
function. The syntnx for the function is different from the others thnt I`ve been
covering in the sections on nnd functions. As with the other func-
tions thnt utiÌize µnrentheses for their nrguments, the function comµnres the
strings much Ìike nn equnÌs sign ( ) wouÌd. However, the function mntches n
µnttern instend of n |ust n ÌiternÌ string.
The function returns 1 if the comµnrison mntches or O otherwise. The µower
of renÌÌy emerges with the use of wiÌdcnrds such ns the underscore nnd the
µercent sign, ns shown in Iigure 9-47. Iurther, the function is most used in the
µortion of n stntement for non-exnct mntches.
If you wnnt to mntch n ÌiternÌ µercent sign or underscore in n µnttern, be sure to
escnµe the µercent with n bncksÌnsh. Ior exnmµÌe, if I wnnted to find n vnÌue thnt
contnined n µercent sign, I cnn query for thnt by ndding n bncksÌnsh before the µer-
cent sign, Ìike this:
Chapter 9 5OL According to My5OL
Figure 9-47: Some basic examples with the LIKE function to match
patterns, some with wildcards
The function hns two usefuÌ modifiers: the nnd keywords.
(See Iigure 9-48.) The modifier chnnges the chnrncter used to escnµe n Ìit-
ernÌ µercent sign or underscore in n µnttern. The keyword chnnges the
cnse-sensitivity of the µnttern mntch. However, if n coÌumn is n binnry coÌumn
nÌrendy (such ns the coÌumn of the MySQL dntnbnse), the
keyword does not chnnge the behnvior.
MySQL nÌso incÌudes reguÌnr exµression tyµe mntching vin the or
function. Using the function, of which the function is synonym for
, you cnn utiÌize more comµÌicnted µnttern mntching inside the nnd
The nnd functions cnn be negnted with the use of the keyword, in
effect, using wiÌÌ mntch those records unÌike the µnttern.
The nnd functions nre somewhnt simiÌnr nnd nt the snme time dif-
ferent. The simiÌnrity between the two functions is thnt they both Ìook for n string
µosition. Consider the foÌÌowing exnmµÌes:
Part II 5OL EssentiaIs
Figure 9-48: Pattern matching with LIKE and the ESCAPE and
ßINARY modifiers
The difference is thnt the function returns the number of the nrgument in the
nrgument Ìist thnt mntches n given string. The function returns the µosi-
tion of n substring in one string. The function Ìooks for the first instnnce of
the string the first nrgument in the Ìist. In the foÌÌowing exnmµÌe, the function
serves to determine the Ìocntion of the string in the Ìist of nnmes.
The function Ìooks for n substring in the instnnce of the given string.
(See Iigure 9-49.) Note the difference in syntnx between the two stntements. If the
string or substring is not found, both functions return n vnÌue of O.
Figure 9-49: The FIELD and PCSITICN functions in action. Note the
difference in syntax between the two statements.
The function cnn be usefuÌ when µreµnring for Ìnrge-scnÌe chnnges to
records. The syntnx for the reµÌnce function cnÌÌs for three nrguments. The first
nrgument is the string you`re Ìooking to senrch in. The second nrgument is the oÌd
string or the one you wnnt to senrch for nnd reµÌnce. The third nnd finnÌ nrgument
Chapter 9 5OL According to My5OL
for the function is the new string, or the one thnt you wouÌd Ìike to use ns
n reµÌncement. See Iigure 9-bO for the resuÌts from the foÌÌowing syntnx exnmµÌe:
The function cnn nÌso be quite he̵fuÌ. The function determines the
Ìength of n given string. A couµÌe exnmµÌes foÌÌow incÌuding n nesting of the
function. The resuÌts from the foÌÌowing exnmµÌes nre shown in Iigure 9-bO:
One finnÌ exnmµÌe to incÌude in Iigure 9-bO is the function. As you mny
hnve guessed, the function reverses n string:
I`m not sure how usefuÌ this cnµnbiÌity wouÌd be in the context I`m using it, but
when combined or nested with other functions, the function cnn µrovide n
menningfuÌ µurµose.
Figure 9-50: The REPLACE, LENCTH, and REvERSE functions. Note the
use of nesting with the LENCTH function.
Part II 5OL EssentiaIs
The finnÌ string-reÌnted } function thnt I cover in this chnµter is the
function. You cnn use this function to teÌÌ MySQL to ¨rend in" the con-
tents of n given fiÌe ns n string. Note thnt the contents of the fiÌe must be smnÌÌer
thnn the MySQL vnrinbÌe . The syntnx for the
function cnÌÌs for you to µrovide the fuÌÌ µnth nnd fiÌennme. The function wiÌÌ return
if you don`t hnve µermission to rend the fiÌe from the oµernting system.
LxnmµÌes of successfuÌ nnd fniÌed usnge of the function Ìook Ìike this:
The resuÌts of these exnmµÌes nµµenr in Iigure 9-b1.
You must have the privilege before you can use the function. In
addition, you must have appropriate permissions to work with the file itself.
Figure 9-51: A successful and failed use of the LCAD_FILE function
Chapter 9 5OL According to My5OL
Other functions with the 5ELECI statement
Some functions in MySQL don`t fnÌÌ into nny sµecific cntegory (such ns n string or
numericnÌ). TnbÌe 9-b Ìists some of those functions.
Table 9-5
Other functions with the 5ELECI statement
Function 0escriµtion
Returns the name of the current database.
Encrypt string, S, using optional .
!ust like a normal statement, runs a test, T and returns
value R1 if true or value R2 if false.
If R1 is not , return R1, else return R2.
Returns 1 if expression, E, is .
Returns the value of the last ID inserted, useful with
Returns an MD5 sum for string, S.
) Returns an encrypted string, S. Similar to the
Returns the current version of the MySCL server.
As you cnn see from TnbÌe 9-b, these functions nre renÌÌy simµÌe in their use. Most
nre sµecinÌized for use with n µnrticuÌnr nµµÌicntion or tnsk. Here nre exnmµÌes for
some of these functions (with resuÌts shown in Iigure 9-b2):
Notice the difference between the nnd functions. Use the
function to encryµt n µnssword for use in the MySQL grnnt tnbÌes.
Part II 5OL EssentiaIs
Use the function to create a password entry for the user table of the
MySCL grant tables.
A frequentÌy nsked question nmong MySQL users is how to determine the number
of the Ìnst ID used on nn coÌumn. The function
is for this µurµose. SimµÌy cnÌÌ ns n stntement nnd you
wiÌÌ receive the ID of the Ìnst insert. The ID is vnÌid onÌy on n µer-connection bnsis,
so you wiÌÌ need to cnÌÌ this nfter the inserts in the snme session.
Figure 9-52: Examples of various other functions in MySCL.
The , , nnd functions nÌÌ µerform tests nnd return n vnÌue bnsed on
the resuÌts of the test. The function runs n test on the first nrgument nnd returns
the second vnÌue if the first exµression is true, the function returns the finnÌ nrgu-
ment if the exµression is fnÌse. The function returns the second nrgument if
the first nrgument is , otherwise it returns the first nrgument. IinnÌÌy, the
function returns 1 if the nrgument is (otherwise the function returns
O). Here nre some exnmµÌes, with resuÌts shown in Iigure 9-b8:
Chapter 9 5OL According to My5OL
Figure 9-53: Functions to test an expression or whether a value is NULL
Crouping, ordering, and Iimiting with 5ELECI
The SLLLCT stntement ennbÌes µowerfuÌ grouµing nnd ordering functions thnt he̵
to sort the resuÌts of the stntements nnd thus mnke them more usefuÌ. TnbÌe 9-6 Ìists
some grouµing functions.
Table 9-6
Crouping functions with 5ELECI
Function 0elinition
Returns a count of the results from expression, X.
Returns the unique non-null results from expression, X.
Returns the average of expression, X.
Returns the minimum value of expression, X.
Returns the maximum value of expression, X.
) Returns the sum of expression, X.
Part II 5OL EssentiaIs
I cnn show these functions best in the foÌÌowing exnmµÌes, resuÌts nre in Iigure 9-b4:
Figure 9-54: Examples of the CCUNT function for grouping the results
from a query
The next set of exnmµÌes comes from the snmµÌe dntnbnse thnt I`ve
been working with in this chnµter nnd throughout the book (resuÌts in Iigure 9-bb):
Chapter 9 5OL According to My5OL
IrequentÌy I hnve to test n stntement. Ior exnmµÌe, I might hnve the
µortion of the stntement wrong, or n tyµo mny croµ uµ eÌsewhere in the stntement. I
nÌso frequentÌy work with fnirÌy Ìnrge tnbÌes thnt hoÌd miÌÌions of records. Thus the
keyword hns he̵ed me countÌess times. Using , I cnn set the
stntement to onÌy return n subset of the resuÌts, thus µotentinÌÌy snving me from
running n Ìnrge nnd Ìong query on n huge tnbÌe.
Figure 9-55: The results from some mathematical grouping functions
Looking nt one of the µrevious exnmµÌes, if you wnnted to order the resuÌts
you couÌd use the function. The function cnn sort the resuÌts
in either nscending or descending order through the use of the or key-
words. In nddition, you cnn use the keyword for even further µnrsing of
resuÌts from n cÌnuse. I`ÌÌ exµnnd on some enrÌier exnmµÌes here (nnd
show the resuÌts in Iigure 9-b6):
Part II 5OL EssentiaIs
Figure 9-56: Using CRDER ßY and HAvINC to sort the results from
Updating data with the UPDAIE statement
I`ve been nttemµting to come uµ with n witty nnecdote to begin this section nnd I
cnnnot. It`s certninÌy not thnt I don`t Ìike the stntement or thnt I don`t
beÌieve it is usefuÌ. The stntement is renÌÌy simµÌe nnd intuitive, with onÌy n
few oµtions. The equnÌÌy simµÌe truth is thnt the stntement is for mnking
chnnges to existing records in the dntnbnse. Its syntnx Ìooks Ìike this:
As does , the stntement incÌudes the nnd
keywords ~nnd using these keywords hns the exnct snme effects. The
keyword teÌÌs the stntement to wnit untiÌ no other cÌients nre rending
from the tnbÌe. The stntement cnuses nny coÌÌisions in non-unique coÌumns
to be ignored (nnother simiÌnrity to the stntement).
As with the stntement, you cnn use n cÌnuse in the stntement
to modify or driÌÌ down to the records you wnnt to uµdnte. If you don`t incÌude n
cÌnuse, you uµdnte nÌÌ the records in the tnbÌe. Another imµortnnt simiÌnrity
to is thnt you cnn use the modifier to Ìimit the number of records
nffected by the stntement. Syntnx exnmµÌes foÌÌow (with resuÌts in Iigure 9-b7):
Chapter 9 5OL According to My5OL
Figure 9-57: A look at the product table prior to the UPDATE statements, the three
UPDATE statements, and a look at the product table after the updates
The stntement cnn be used to deÌete sµecific records or the entire contents
of tnbÌes, its syntnx is ns foÌÌows:
I`ÌÌ disµense with some syntncticnÌ commonnÌities nmong mnny of the DML stnte-
ments. The keyword cnuses the to wnit untiÌ no other
cÌients nre using the tnbÌe. The cÌnuse teÌÌs the stntement which
records to deÌete. The cÌnuse determines the order by which the
wiÌÌ occur. The modifier cnuses the to onÌy deÌete the sµecified num-
ber of rows. Though not common to other DML stntements, the modifier cnn
nssist to sµeed uµ certnin stntements.
Part II 5OL EssentiaIs
The stntement hns two versions. The first version of the stntement
simµÌy deÌetes from one tnbÌe. The second version of the stntement ennbÌes
deÌetion from muÌtiµÌe tnbÌes. I`ÌÌ show n syntnx exnmµÌe or two for ench tyµe of
In the Ìnst of these exnmµÌes, nny mntching rows nre deÌeted from the
nnd tnbÌes onÌy.
Showing my true System Administrntor coÌors, I ndmit thnt my fnvorite nction is
µerforming deÌetes. Iew wnys of stnrting n dny nre more rewnrding thnn removing n
few hundred thousnnd records.
MySQL incÌudes n Ìnrge number of commnnds nnd stntements used for ndministrn-
tion ns weÌÌ ns µerformnnce tuning nnd informntionnÌ µurµoses. These stntements
incÌude the , , nnd .
MySQL nÌso incÌudes most ANSI92 comµntibiÌity in the Dntn Definition
Lnngunge (DDL) stntements.
MySQL extends the ANSI92 stnndnrd in some DDL stntements.
As with DDL, MySQL fentures comµntibiÌity with most ANSI92 Dntn Mnrkuµ
Lnngunge (DML) stntements.
Like DDL, MySQL extends the ANSI92 stnndnrd in the nren of DML.
and 0ata
dntnbnse is µrimnriÌy n tooÌ for orgnnizing dntn into nn
nccessibÌe nnd usnbÌe form. Thnt mny seem obvious,
but some of questions I`m nsked most frequentÌy nbout nre
the brnss-tncks of orgnnizing dntn in MySQL dntnbnse ~
choosing the right tnbÌe tyµe, imµorting nnd exµorting dntn,
nnd using the commnnd to dingnose dntnbnse
µrobÌems correctÌy.
Choosing the right tnbÌe tyµe is imµortnnt, different nµµÌicn-
tions mny benefit from µnrticuÌnr tnbÌe tyµes. Imµorting dntn
into MySQL from other nµµÌicntions (such ns Microsoft Access
or OrncÌe) is n frequent tnsk fncing ndministrntors migrnting
to MySQL. IinnÌÌy, using the commnnd success-
fuÌÌy is nn imµortnnt µnrt of working with n MySQL server.
This chnµter exnmines nÌÌ these sub|ects in detniÌ.
Choosing the kight My5OL
IabIe Iype
A ioblc iypc is one of vnrious sets of chnrncteristics thnt you
cnn nµµÌy to n dntnbnse tnbÌe in MySQL ~usunÌÌy for n sµe-
cinÌized µurµose, even though the nµµenrnnce of MySQL
tnbÌes mny be simiÌnr from tyµe to tyµe. 1ust ns you couÌd use
n kitchen tnbÌe to µerform surgery, or n µicnic tnbÌe ns n desk,
you couÌd use n MySQL tnbÌe for n µurµose other thnn thnt for
which it`s designed~but why"
C H A P I E k
ln Ihis Chopler
lnlroduclng lhe
MySCL loble lypes
Flnelunlng lhe synlox
when uslng lhe
Exporllng dolo lrom
MySCL doloboses
lmporllng dolo lnlo
MySCL doloboses
Part II 5OL EssentiaIs
All MySCL table types store data-but there's usually a best type for any
This section exnmines the tnbÌe tyµes suµµorted in MySQL. With n soÌid under-
stnnding of the nvniÌnbÌe tnbÌe tyµes, you`re better equiµµed to choose the correct
tnbÌe tyµe for your nµµÌicntion.
My5OL tabIe types
The six tyµes of MySQL tnbÌes nre best considered ns three grouµs for the snke of
Non-transactional tables. Ior mnny nµµÌicntions, non-trnnsnctionnÌ tnbÌe
tyµes wiÌÌ be sufficient nnd wiÌÌ use fewer resources thnn trnnsnctionnÌ tnbÌes.
Ior exnmµÌe, nn onÌine cntnÌog, customer dntnbnse, nµµÌicntion dntnbnse, nnd
mnny other nµµÌicntions cnn utiÌize non-trnnsnctionnÌ tnbÌes successfuÌÌy. The
defnuÌt tnbÌe tyµe in MySQL is the non-trnnsnctionnÌ MyISAM tyµe. MyISAM is
the tnbÌe tyµe of choice for nenrÌy nÌÌ nµµÌicntions. The three non-trnnsnctionnÌ
tnbÌe tyµes nre
The tyµe is stored in voÌntiÌe memory. If you nre using n tnbÌe
tyµe nnd MySQL crnshes or is shut down, nÌÌ dntn in the tnbÌe is Ìost!
However, the tnbÌe tyµe is fnst, mnking it n good choice for temµo-
rnry tnbÌes.
8nsed on the tnbÌe tyµe, is the defnuÌt for MySQL.
The tnbÌe tyµe is n sµecinÌ extension of the tnbÌe.
Transaction-safe (transactional) tables. TrnnsnctionnÌ tnbÌes cnn combine
stntements nnd then commit or roÌÌ them bnck if some fniÌ. TrnnsnctionnÌ
tnbÌes nre much snfer in the event of MySQL or system crnshes. These two
tnbÌe tyµes nre
The tnbÌe tyµes you cnn use deµend on the version of MySQL instnÌÌed on your
server. Some tnbÌe tyµes weren`t nvniÌnbÌe in enrÌier versions of MySQL. Iurther, the
tnbÌes nvniÌnbÌe foÌÌow these genernÌ ruÌes:
If you comµiÌed MySQL from source code, you hnd the oµtion to choose tnbÌe
tyµes during the comµiÌntion µrocess.
Chapter 10 Databases And Data
If you instnÌÌed MySQL from n binnry version, you mny or mny not hnve trnns-
nctionnÌ tnbÌes incÌuded. The MySQL-MAX version incÌudes both InnoD8 nnd
8erkeÌeyD8. Some MySQL versions sµecific to fÌnvors of Linux such ns Debinn
incÌude 8erkeÌeyD8.
Chapter 2 reviews the advantages of transactional and non-transactional tables.
To determine which tnbÌe tyµes your server suµµorts, you cnn use the
Running the command outputs quite a bit of informa-
tion so you may need to pipe the output to a pager such as more or /ess.
Iigure 1O-1 shows the outµut for the commnnd mysqÌndmin -µ vnrinbÌes. I check for
the Ìines thnt indicnte whether 8erkeÌeyD8 nnd InnoD8 tnbÌes nre ennbÌed. Iigure 1O-1
shows thnt onÌy 8erkeÌeyD8 is nvniÌnbÌe on this server. Therefore, I must use one of
two nµµronches to choosing n tnbÌe tyµe:
I cnn choose 8erkeÌeyD8.
Since non-trnnsnctionnÌ tnbÌes nre nvniÌnbÌe by defnuÌt I cnn choose non-
trnnsnctionnÌ tnbÌes, such ns
Figure 10-1: Using the mysqladmin -p variables command to
determine whether InnoDß or ßerkeleyDß tables are supported
Part II 5OL EssentiaIs
Iigure 1O-2 shows the outµut of the mysqÌndmin vnrinbÌes commnnd on n server
where both the nnd tnbÌes ennbÌed.
Figure 10-2: The mysqladmin variables command on a server with
both ßerkeleyDß and InnoDß tables enabled
The defnuÌt tnbÌe tyµe for tnbÌes crented in MySQL is . The MyISAM tnbÌe
tyµe is nn extension of the tnbÌe tyµe.
The My SAM table type will eventually replace the table type. In a future ver-
sion of MySCL, the table type will no longer be offered.
uses n 8-tree index tyµe nnd comµresses indexes whenever µossibÌe. Ior
string-bnsed indexes such ns those on nnd coÌumns, tnbÌes
sµnce-comµress the index. To use comµressed numeric-bnsed indexes ndd
1 in the µrocess of crenting the tnbÌe.
TnbÌes cnn be dnmnged by n system crnsh, n crnsh of the MySQL server, or nny
number of unforeseen events. If queries fniÌ to return comµÌete resuÌts or other
unexµÌnined errors occur, the tnbÌe mny need reµnir. Corruµt or broken
tnbÌes cnn be reµnired with the commnnd.
Chapter 13 shows how to repair broken tables and solve other MySCL problems.
There nre three tnbÌe formnts for tnbÌes:
Chapter 10 Databases And Data
MySQL chooses or tnbÌe formnts nutomnticnÌÌy when you crente
the tnbÌe. The tnbÌe formnt must be crented mnnunÌÌy through the use
of the utiÌity.
5tatic format
The tnbÌe formnt is the defnuÌt nnd is used when there nre no vnrinbÌe-
Ìength coÌumn tyµes in the tnbÌe such ns or . If vnrinbÌe-Ìength
coÌumns nre used, MySQL wiÌÌ choose the formnt for the tnbÌe.
An exnmµÌe of n tnbÌe definition Ìooks Ìike this ns foÌÌows:
In the µreceding exnmµÌe tnbÌe, nÌÌ coÌumns nre fixed Ìength ns shown by the
stntement in Iigure 1O-8.
Figure 10-3: The SHCW TAßLE STATUS command reveals that the
table is in Fixed row format.
Stntic tnbÌes hnve two ndvnntnges:
With the exceµtion of voÌntiÌe-memory tnbÌe tyµes such ns HLAP, the
tnbÌe formnt is the fnstest of the three oµtions becnuse its coÌumns nre
n uniform size. Ior exnmµÌe, n coÌumn is µndded with extrn whitesµnce
chnrncters to bring the coÌumn uµ to the defined size, n coÌumn is
not µndded with extrn chnrncters. Since the coÌumn is nÌwnys the snme size,
MySQL cnn sort through the dntn quicker ns it knows thnt the coÌumn is n
constnnt Ìength regnrdÌess of the size of the dntn heÌd within the coÌumn.
Pndding of fieÌds to the snme size mnkes tnbÌes snfer. The reµnir utiÌity
cnn ensiÌy µredict the boundnries of coÌumns in n row.
Part II 5OL EssentiaIs
The trade-off for table speed is d/s/ sµqce. ßecause each record must be
padded with characters to bring it to the defined length, each row consumes the
maximum defined disk space, even if the actual data is short. Cf course, if each
record is exactly same fixed length as the definition there is no additional disk
space consumption with a table.
Dynamic format
Dynnmic tnbÌes minimize disk-sµnce usnge becnuse the size of the tnbÌe deµends on
the nctunÌ size of the dntn.
ßytes are stored for each column in a table to keep track of the length of
the data.
If you µerform nn on n dntn record, the uµdnted dntn mny nctunÌÌy be stored
in n different Ìocntion in the dntnfiÌe. Ior exnmµÌe, if you insert n vnÌue into n coÌ-
umn such ns nn nddress nnd then uµdnte thnt nddress to n much Ìonger nddress,
the uµdnted coÌumn mny nctunÌÌy be stored in n different Ìocntion or frngmented
nwny from the rest of the record. This frngmentntion cnn be reµnired with the
Moving fixed-Ìength or stntic dntn coÌumns into nnother tnbÌe mny ncceÌernte those
tnbÌes, if it is µossibÌe nnd rensonnbÌe to orgnnize your dntn this wny. You shouÌd
determine whether frngmentntion or vnrinbÌe-Ìength coÌumns ndverseÌy nffects
µerformnnce enough to wnrrnnt dividing the tnbÌes. To nccomµÌish this, comµnre
the number of vnrinbÌe-Ìength coÌumns in the tnbÌe to the number of stntic Ìength
coÌumns. If nn index reÌies on stntic coÌumns, it mny be beneficinÌ to move the
vnrinbÌe-Ìength coÌumn to nnother tnbÌe. However, moving the vnrinbÌe-Ìength coÌumn
to nnother tnbÌe cnn ndd overhend ns thnt tnbÌe is |oined with the originnÌ tnbÌe.
tables can be more difficult for MySCL to repair after a crash. ßecause
updates to the data can cause fragmentation, some pieces of a record may be lost
when repairing the table. table repairs are easier because all columns are
of the same defined length.
Using the foÌÌowing stntement, I hnve nÌtered the exnmµÌe tnbÌe defini-
tion shown µreviousÌy in this section.
Changing one column from to changes all columns to the
variable-length format.
Running the stntement ngnin ns shown in Iigure 1O-4 shows
the row formnt is now (one or more coÌumns in the tnbÌe is now n vnrinbÌe-
Ìength tyµe).
Chapter 10 Databases And Data
Figure 10-4: The SHCW TAßLE STATUS statement now shows the
row format has changed due to the alteration of the table definition.
Compressed format
tnbÌes nre rend-onÌy. 8ecnuse they nre rend-onÌy, tnbÌes
nre good for rnreÌy chnnged dntn ~nnd they tnke uµ ÌittÌe disk sµnce. Ior exnmµÌe,
n Ìibrnry mny hnve reference mnterinÌ sorted in n dntnbnse. The book titÌes,
nuthors, nnd other informntion nre stntic. Tnking such informntion nnd storing it in
n comµressed tnbÌe in n dntnbnse snves disk sµnce thus ennbÌing the Ìibrnry to
store n huge nmount of dntn nt n Ìower cost.
tnbÌes nre comµressed with the myisompoch utiÌity.
tnbÌes cnn be either or nnd cnn be unµncked with the
Compressed tables cannot have or column types.
MyI5AM variabIes
There nre n number of vnrinbÌes nnd µnrnmeters thnt cnn chnnge the behnvior of
tnbÌes. The vnrinbÌes nnd µnrnmeters controÌ things Ìike
Automntic recovery of crnshed tnbÌes
Size of buffers nnd cnches
How indexes nre crented
To determine the current values for the variables and parameters, use the
command, as shown in Figure 10-5.
Part II 5OL EssentiaIs
Figure 10-5: The default values for four of the MyISAM table
variables and parameters
You may see a slightly different value for the options shown in Figure 10-5
depending on the version of MySCL you're using and the architecture the server is
running on.
The vnrinbÌes nnd µnrnmeters cnn be set two wnys:
On the commnnd Ìine when stnrting the MySQL server µrocess
Inside n configurntion fiÌe (such in Linux)
MySQL cnn be configured to reµnir MyISAM tnbÌes nutomnticnÌÌy nt stnrtuµ. When
n tnbÌe is cÌosed, MySQL sets n vnÌue in the hender of the .MYI dntnbnse fiÌe. If this
vnÌue indicntes thnt the tnbÌe wns not cÌosed µroµerÌy, n tnbÌe reµnir is necessnry.
Using the vnrinbÌe, you cnn controÌ if nnd how nn nutomntic
reµnir is µerformed. The vnrinbÌe ncceµts nny combinntion of
four µnrnmeters:
Setting the oµtion vnÌue to is the snme ns simµÌy using
with no oµtion.
Using crentes n bnckuµ of the dntnfiÌe (identified with the
extension) to µrevent Ìoss of dntn during recovery.
The oµtion reµnirs the tnbÌe, regnrdÌess of how mnny rows nre
This oµtion nttemµts onÌy to reµnir the index. The oµtion cnn
onÌy be used in con|unction with the µnrnmeter.
If you are going to use the option it is a good idea to use the
option to prevent unforeseen data loss.
Chapter 10 Databases And Data
In Iigure 1O-b, the vnÌue of indicntes thnt there nre
no oµtions set for recovery in the exnmµÌe. When n tnbÌe is oµened with the
set, MySQL checks the tnbÌe to mnke sure it wns
cÌosed µroµerÌy.
You cnn set oµtions either with on the commnnd Ìine (ns the
server is stnrted), or in n configurntion fiÌe. Ior exnmµÌe, to use the nnd
oµtions with I ndd the foÌÌowing Ìine to the
section of the fiÌe in Linux.
After ndding the µreceding Ìine to the my.cnf configurntion fiÌe nnd restnrting the
server the commnnd refÌects the chnnge, ns shown in
Iigure 1O-6.
Figure 10-6: Using the ßACKUP and FCRCE automatic recovery
options as shown by the mysqladmin variables command
Some versions of MySCL may show different values for the variables shown in
Figure 10-6.
MySCL makes a backup file when using the option. This file can
be the same size as the table file.
Another oµtion used when recovering tnbÌes is . This
oµtion controÌs how Ìnrge the buffers shouÌd be for recovery. Set this vnrinbÌe
either on the commnnd Ìine using or inside n con-
figurntion fiÌe, using n Ìine in the section.
Part II 5OL EssentiaIs
A couµÌe of oµtions denÌ with indexes nnd tnbÌes. These oµtions incÌude
nnd . The
oµtions controÌ how to crente indexes nnd when to use other methods to crente
them. 8oth oµtions nre set on the commnnd Ìine or in the configurntion fiÌe with
n set-vnrinbÌe oµtion.
The tnbÌe tyµe is n reÌntive newcomer to MySQL. A tnbÌe is n coÌÌection
of identicnÌ tnbÌes grouµed together ns if they were one tnbÌe. OnÌy certnin
oµerntions nre nÌÌowed with tnbÌes, such ns
The tables must contain the same column definitions and layout. If the
tables are not defined exactly the same, you cannot create a table.
tnbÌes sµeed uµ oµerntions when identicnÌ tnbÌes need to be |oined.
However, crenting n tnbÌe nÌso increnses the number of IiÌe Descriµtors
needed. If you hnve muÌtiµÌe tnbÌes with the snme Ìnyout where you wouÌd normnÌÌy
be µerforming n on the tnbÌes, n tnbÌe cnn be beneficinÌ.
As of this writing, performing a or a with no
specification on a table only drops or deletes the table specification,
not the data contained in the merged tables.
To crente n tnbÌe, use the foÌÌowing syntnx:
If you do not sµecify nn or set the to , you cnn`t
µerform nn on the newÌy crented tnbÌe.
Though tnbÌes wiÌÌ be disnµµenring from MySQL, some oÌder or Ìegncy
dntnbnses stiÌÌ use them.
Use for new databases. Iip
Chapter 10 Databases And Data
As with tnbÌes, tnbÌes use n 8-tree index nnd cnn comµress keys to
snve on sµnce. tnbÌes cnn be reµnired with the utiÌity.
tables are dependent upon the architecture or CS in which they are created.
For example, datafiles of an table running on an Alpha processor can't be
moved or copied to a computer running an x86-type processor.
-tyµe tnbÌes exist onÌy in coloiilc mcmory. When the MySQL server dies for nny
renson, nÌÌ existing tnbÌes die ~nÌong with nny dntn they contnined. 8ecnuse
they reside in memory onÌy, tnbÌes nre usefuÌ for temµornry tnbÌes nnd nre fnst.
Think of a table much like a RAM drive. The RAM drive exists only in memory
and is therefore fast -but the contents of the drive go away as soon as the
machine is turned off.
Don't store any permanent data in a table!
tnbÌes nre different enough from other tnbÌes thnt knowing their chnrncteris-
tics mny he̵ you nvoid misusing them. Ior instnnce, tnbÌes do not suµµort
coÌumns, nor do tnbÌes suµµort or coÌumn tyµes.
ßecause a table stores data in RAM, one table can potentially use all
the available memory in your system! To prevent such excess, you can create the
table with the modifier or you can control the maximum size for the
table through the server variable.
Using the commnnd, I note the
vnÌue of 16777216 for the MySQL server, ns shown in Iigure 1O-7.
Figure 10-7: The default value for the max_heap_table_size
determines how much memory a HEAP table can use.
Part II 5OL EssentiaIs
To chnnge the vnÌue, edit the section of your MySQL server configurntion
fiÌe, on some Linux fÌnvors, nnd ndd the foÌÌowing (where X is the new
Ior exnmµÌe, I wnnt to set the mnximum memory usnge for n tnbÌe on my
server to 8M8 of RAM. I ndd the foÌÌowing to the fiÌe:
After restnrting the MySQL server, I re-run the commnnd,
ns shown in Iigure 1O-8.
Figure 10-8: Changing the default value for max_heap_table_size in
the MySCL server configuration file
is one of two nntive trnnsnctionnÌ tnbÌes incÌuded with MySQL (the other is
Gemini, distributed with NuSµhere Lnhnnced MySQL). is not incÌuded with
n normnÌ MySQL binnry distribution. To ennbÌe , you must comµiÌe it in or
use n MySQL-Mnx version of MySQL. Iurther, you must set nt Ìenst one vnrinbÌe in
the , the vnrinbÌe. The vnrinbÌe shouÌd be
set under the section. AdditionnÌ vnrinbÌes nnd µnrnmeters cnn be set to
nssist with µerformnnce of tnbÌes.
NuSphere Enhanced MySCL is discussed in greater depth in Chapter 20.
tnbÌes offer row-ÌeveÌ Ìocking nnd trnnsnctionnÌ fentures such ns
nnd . The ndvnntnge of such n tnbÌe tyµe is thnt you cnn µrevent incom-
µÌete uµdntes from writing or chnnging dntn in the event of n system crnsh or other
Chapter 10 Databases And Data
event. AdditionnÌÌy, suµµorts the use of Ioreign Keys to µrotect referentinÌ
To crente nn InnoD8 tnbÌe you must sµecify with your CRLATL
stntement. A syntnx exnmµÌe foÌÌows:
If you currently have tables and want to convert them to , the eas-
iest method for doing so is simply to create an identical table and then
import or re-insert the data from the existing table.
InnoD8 tnbÌes hnve n number of Ìimitntions.
You cnnnot hnve n 8LO8 or TLXT coÌumn tyµe in nn tnbÌe.
TnbÌes cnnnot hnve more thnn 1,OOO coÌumns.
Unique indexes cnnnot be crented on n µrefix.
InnoDß variabIes and parameters
A number of oµtions cnn be set to boost the µerformnnce of tnbÌes. AÌÌ of
these oµtions shouÌd be set under the section of the configurntion fiÌe.
The must be set to to be ennbÌed. The syntnx for
this µnrnmeter is ns foÌÌows:
The µnrnmeter sµecifies the nnme of the dntnbnse. The ·size·
µnrnmeter is usunÌÌy given with nn M for Megnbytes nnd must be nt Ìenst ten
megnbytes (1OM). Uµon stnrtuµ, MySQL crentes n in the of
the MySQL instnÌÌntion in the size of ns sµecified in the configurntion fiÌe.
AdditionnÌÌy, ÌogfiÌes nre crented in the . The µnrnmeters cnn nÌso be seµn-
rnted by semicoÌons to ndd more dntnbnses nnd cnn nÌso be given reÌntive µnths.
Ior exnmµÌe, to use two dntnbnses Ìocnted in n directory ~ nnd
, ench 2bO megnbytes in size ~use the foÌÌowing syntnx:
You cnn chnnge the Ìocntion of the dntn fiÌe nnd the ÌogfiÌes with the µnrnmeters
nnd resµectiveÌy. These
oµtions nre nÌso set in the section of the MySQL configurntion fiÌe. The
oµtions exµect µnths ns vnÌues. Any directories sµecified with the
nre reÌntive from the stnndµoint of . Ior
Part II 5OL EssentiaIs
exnmµÌe, to set ns the µnth for the dntn, the syntnx
wouÌd be ns foÌÌows:
In the exnmµÌe enrÌier, the dntn fiÌes for the two
dntnbnses wouÌd be nnd
Check to make sure that the directories you specify actually exist -and that MySCL
has permission to access them.
ÌogfiÌes nre rotnted in n circuÌnr µnttern. You cnn set the number of ÌogfiÌes
keµt using the vnrinbÌe. The defnuÌt vnÌue is 2. Set
this vnrinbÌe vin the µnrnmeter in the MySQL configurntion fiÌe or
using the switch on the commnnd Ìine.
Another oµtion nffecting the ÌogfiÌes of tnbÌes is .
The vnrinbÌe determines how Ìnrge to mnke the ÌogfiÌes.
The bigger the vnÌue, the Ìess disk nctivity is needed due to fÌushing. However, set-
ting the vnÌue of too Ìnrge cnn cnuse recovery time to
Ìengthen. The vnÌue cnn be n mnximum of 4 gignbytes for
nÌÌ ÌogfiÌes combined.
The vnrinbÌe controÌs how Ìnrge the buffer shouÌd be
µrior to writing to the Ìog. As with the , n Ìnrger
vnÌue resuÌts in fewer disk oµerntions. The mnximum
vnÌue for this vnrinbÌe is hnÌf the .
Another vnrinbÌe thnt nffects disk writes ~nnd thus sµeed nnd µerformnnce ~
is . The defnuÌt vnÌue for
is 1. The vnÌue of 1 for this vnrinbÌe
indicntes thnt nfter every , the trnnsnction wiÌÌ be written to the ÌogfiÌe
nnd thus mnde µermnnent. If you wnnt to comµromise this snfety for sµeed,
you cnn set the vnÌue for to O.
Yet nnother vnrinbÌe to nffect disk µerformnnce is the
vnrinbÌe. Though it does not nffect Ìogging Ìike the µreceding vnrinbÌes, the
ize nffects how memory is used. With the
e vnrinbÌe, you teÌÌ the MySQL server how much memory to use when it
cnches tnbÌe nnd index dntn. The Ìnrger you set this vnÌue, the more dntn nnd
indexes cnn be cnched in memory, which cuts down on disk oµerntions. 8e cnrefuÌ,
however, not to set this vnÌue too Ìnrge ~if you do, the server mny do so mnny µng-
ing or swnµ-to-disk oµerntions thnt not enough µhysicnÌ memory is Ìeft for normnÌ
server µrocesses. Windows-bnsed servers, or other servers thnt ¨wnste" resources
to suµµort n GUI, nre esµecinÌÌy µrone to such memory shortnges.
Chapter 10 Databases And Data
The defines the nmount of memory thnt
MySQL shouÌd use to store dntn dictionnry informntion. MySQL A8 recommends
this vnÌue be two megnbytes (2M). However, if you hnve n Ìnrge number of tnbÌes,
you mny wnnt to consider incrensing this vnÌue.
An imµortnnt vnrinbÌe to know nbout even though you mny never need to chnnge
the defnuÌt is . In the event of n Ìock thnt the
hnndÌer cnnnot detect or cÌenr, this vnrinbÌe nutomnticnÌÌy stnrts the µrocess to roÌÌ
the trnnsnction bnck nnd reÌense the Ìock.
(which you mny see nbbrevinted ns ) is nnother tyµe of trnnsnc-
tionnÌ tnbÌe nvniÌnbÌe in the A8 version of MySQL. As with ,
tnbÌes require ndditionnÌ suµµort, which you cnn get in one of two wnys:
The MySQL MAX version of MySQL offers buiÌt-in suµµort.
You cnn comµiÌe suµµort for tnbÌes into your version of MySQL
if you nre instnÌÌing from source code.
AÌso ns with , nÌso offers nnd for trnnsnc-
tions. is, however, nvniÌnbÌe on onÌy n Ìimited rnnge of nrchitectures:
Linux on InteÌ
SoÌnris on Sµnrc
SCO OµenServer
SCO UnixWnre
UnÌike , requires no µnrticuÌnr oµtions be set to ennbÌe it.
ßerkeIeyDß variabIes and parameters
As with , some vnrinbÌes nnd µnrnmeters cnn be set for to
nffect the behnvior of the tnbÌes.
If you wnnt to stnrt the server without suµµort, use the
To set the home directory for fiÌes use the
The ÌogfiÌe directory for tnbÌes is set with the
The temµornry directory is set with the .
Part II 5OL EssentiaIs
Other oµtions to chnnge the behnvior nre the nnd
µnrnmeters. These oµtions nffect the recovery of 8erkeÌeyD8 tnbÌes.
To chnnge the Ìocking behnvior, the (or if on the commnnd
Ìine) shouÌd be set. This vnrinbÌe controÌs the mnximum
number of Ìocks nvniÌnbÌe for tnbÌes. Ior exnmµÌe, within the
section of the MySQL configurntion fiÌe you wouÌd µÌnce:
The µnrnmeter sets how MySQL works with Ìocks on
tnbÌes. VnÌid vnÌues for X nre
The variables and parameters can be set on the command line or in the
MySCL configuration file.
Administering Your Database
with mysqIadmin
The commnnd serves to µerform ndministrntion tnsks on MySQL
dntnbnses nnd dntnbnse servers. With the commnnd you cnn crente
nnd deÌete dntnbnses, stoµ the server, kiÌÌ thrends, µerform server mnintennnce,
nnd exnmine server vnrinbÌes. ShouÌd you forget the syntnx or usnge of the
commnnd, you cnn nÌwnys tyµe with no nrguments or
with the or the switches nnd get n summnry of the commnnds nnd syn-
tnx of the commnnd. Pnrt of the outµut from this he̵ is shown in
Iigure 1O-9.
Common switches
Running the commnnd with no nrguments, you see n number of
switches exnctÌy Ìike those used for the MySQL CLI commnnd . These oµtions
incÌude the or switch, the or µ switch, the or
switch, the switch, nnd the or switch.
Chapter 8 covers switches the same as the MySCL CLI.
Chapter 10 Databases And Data
Figure 10-9: Should you forget the commands or syntax of the
mysqladmin command, you can simply type mysqladmin with no
arguments and get a summary.
5peciaI switches
There nre nÌso switches sµecific to the commnnd.
A switch thnt cnn be usefuÌ for monitoring MySQL µerformnnce is the or --
switch. Using this switch, you cnn set to rerun the sµecified commnnd
every N seconds. In Iigure 1O-1O, I use the switch to run the
commnnd every 2 seconds. As you cnn see, the server isn`t busy but the exnmµÌe is
stiÌÌ usefuÌ.
Figure 10-10: Using the -i switch, you can configure mysqladmin to
run the specified command at regular intervals.
Part II 5OL EssentiaIs
Another switch to use with the commnnd is the or
switch. Using the switch together with the commnnd, you
cnn see the chnnges in the vnÌues µrovided by the commnnd
over the sµecified time intervnÌ. In Iigure 1O-11 you cnn see the initinÌ run of the
commnnd. In Iigure 1O-12 you cnn see the next run nfter n
1O-second intervnÌ hns eÌnµsed, note the is onÌy 1O becnuse 1O seconds
hnve eÌnµsed.
Figure 10-11: First output of the
command with the -r switch for keeping track of relative values
Figure 10-12: The second output of the mysqladmin extended-status
command using the -r switch to track relative or changed values
Chapter 10 Databases And Data
The or switch currently only works with the
Functions with mysqIadmin
I`ve shown quite n few exnmµÌes of the mysqÌndmin commnnd throughout the book.
It`s now time to exnmine the commnnds nnd functions thnt mnke the mysqÌndmin
commnnd so usefuÌ.
Chapter 8 on MySCL CLI explains adding the switches for specifying command line
parameters such as user ( ) and password ( ).
Creating and dropping databases
The commnnd serves to crente nnd droµ or deÌete dntnbnses. The
syntnx for crenting n dntnbnse with the commnnd is ns foÌÌows:
SimiÌnrÌy, the syntnx for droµµing n dntnbnse is much the snme:
In Iigure 1O-18, I crente nnd droµ n dntnbnse. Notice the verificntion thnt µrecedes
the nctunÌ deÌetion of the dntnbnse.
Figure 10-13: Creating and then dropping a database, using the
mysqladmin command
Part II 5OL EssentiaIs
Obtaining server status information
An imµortnnt µnrt of monitoring server µerformnnce nnd dingnosing µrobÌems is
done by Ìooking nt the vnÌues of server µnrnmeters. A concise overview of mnny
imµortnnt server vnÌues is obtnined using the functions in this section.
Status. The function returns n quick overview of some imµortnnt
server µnrnmeters:
º The µnrnmeter is the number of seconds the server hns been
º The coÌumn contnins the qunntity of the number of nctive
cÌients or thrends running or connected nt the time.
º The vnÌue of is the number of questions or stntements thnt
the MySQL server hns received since stnrtuµ.
º The vnÌue indicntes the number of times thnt n query hns
tnken Ìonger thnn the vnÌue set for n sÌow query. This vnÌue,
, cnn be set by the ndministrntor nnd mny be he̵fuÌ
in tuning the server.
º The vnÌue indicntes the totnÌ number of tnbÌes thnt MySQL hns
oµened since stnrtuµ.
º The µnrnmeter indicntes the number of times n ,
, or stntement hns been executed.
º The vnÌue indicntes the number of tnbÌes currentÌy oµen.
º indicntes how much memory is currentÌy nÌÌocnted to
º used indicntes the mnximum memory nmount nÌÌocnted to
An exnmµÌe of the outµut from the function is shown in Iigure 1O-14.
Figure 10-14: Cutput from the mysqladmin status command
Chapter 10 Databases And Data
Extended-status. As you might exµect, the function returns
much more informntion nbout server µnrnmeters nnd µerformnnce thnn does
the function. When you tune server vnrinbÌes to get better µerfor-
mnnce from the MySQL server, the is frequentÌy
Chapter 11 and Chapter 13 cover tuning your server parameters.
Iigure 1O-1b shows nn exnmµÌe of µnrt of the outµut from the
Figure 10-15: Partial output from the mysqladmin extended-status
Processlist. The function Ìists the currentÌy nctive or oµen con-
nections to n MySQL server. These cnn be from nµµÌicntions, the CLI, other
MySQL servers, or through nny other communicntion with the MySQL server.
The eight coÌumns in the function outµut µrovide n snnµshot of
nctivity on the dntnbnse server nt the instnnt the commnnd wns run.
º The coÌumn is n counter of the connections to the dntnbnse server
nnd is incremented with ench new connection.
º The is the user µerforming the nction.
º The is where the user`s connection originnted.
Part II 5OL EssentiaIs
º A coÌumn indicntes whether the commnnd or stntement invoÌved n
º The coÌumn indicntes the tyµe of commnnd thnt wns run.
º The coÌumn indicntes the time of the connection.
º The coÌumn indicntes whnt the µrocess is doing, from wniting, to
oµening connection, estnbÌishing communicntion, nnd so forth.
º The coÌumn shows whnt stntement or commnnd the µrocess is
An exnmµÌe of the µrocessÌist function is shown in Iigure 1O-16.
Figure 10-16: The MySCL processlist function for use with the
mysqladmin command
Using the function I was able to troubleshoot a problem where a
developer was opening multiple connections to the database and closing none of
them. The clients would issue a command and then sit idle until they timed out.
The server would reach its client connection limit quickly and start refusing legiti-
mate connections. The function showed that there were a number
of connections from the application user and the connections remained open. ßy
changing the value and restarting the server, I was able to
solve the problem. Without the processlist command troubleshooting this issue
would have been difficult.
Variables. The vnrinbÌes function outµuts the vnrious oµtions nnd server
µnrnmeters thnt the MySQL server oµerntes with. These incÌude µnrnmeters
º Connection timeouts
º Tyµes of tnbÌes incÌuded with the server
Chapter 10 Databases And Data
º Server version
º Sizes of cnches nnd buffers
An exnmµÌe of the outµut from the commnnd is
shown in Iigure 1O-17. The commnnd to reµroduce this outµut is
Figure 10-17: The output from the mysqladmin variables command
shows the options that the MySCL server uses.
Functions for cIearing server parameters
The commnnd µrovides numerous functions for fÌushing or cÌenring
server µnrnmeters. The functions nre ns foÌÌows:
This function cÌenrs the MySQL DNS host cnche. 8y defnuÌt
MySQL stores the connecting hosts to IP resoÌution. If you chnnge the host`s
DNS entry or n number of errors occur during n connection, the host mny be
bÌocked by MySQL. Performing n oµerntion cÌenrs
the DNS host cnche nnd soÌves the µrobÌem.
Part II 5OL EssentiaIs
MySQL nÌso keeµs n number of ÌogfiÌes. These cnn incÌude
uµdnte Ìogs nnd binnry uµdnte Ìogs. The function µurges ÌogfiÌes
nnd restnrts the Ìogging µrocess. Ior uµdnte Ìogs done with the stnndnrd num-
bering extension, the new ÌogfiÌe hns the Ìnst ÌogfiÌe`s extension incremented
by one. The function does not touch the error Ìog,
, tyµicnÌÌy Ìocnted in your dntn directory.
This function tnkes vnrinbÌes nnd resets them to
zero~usefuÌ for debugging server µerformnnce nnd µnrnmeters. Iigure 1O-18,
for exnmµÌe, shows µnrtinÌ outµut from the function nfter
I run the function. Iigure 1O-19 shows the resuÌts of nnother
run of the function immedinteÌy nfter I run the
function. The commnnd to fÌush the stntus vnrinbÌes is
Figure 10-18: A snapshot of server parameters prior to running the
mysqladmin flush-status command
The fÌush-tnbÌes function shouÌd be used with cnre. This func-
tion cÌoses nny nnd nÌÌ oµen tnbÌes. Lven if n tnbÌe is in use, the fÌush-tnbÌes
functions cÌoses those ns weÌÌ. This cnn resuÌt in errors to the cÌient. I`ve
found thnt this function sometimes must be used on extremeÌy busy servers
thnt seem unresµonsive to n shutdown commnnd.
Chapter 10 Databases And Data
Figure 10-19: Another snapshot of server parameters immediately
after the flush-status function
The refresh function is n combinntion of the fÌush-tnbÌes nnd fÌush-
Ìogs functions.
A frequentÌy used function, though mnybe not vin the
mysqÌndmin commnnd, is the function. The fÌush-µriviÌeges
function cnuses the tnbÌes to be reÌonded, mnking MySQL nwnre of
nny chnnges to those tnbÌes. If stntements working with those tnbÌes nre done
with n or stntement, using the function in
unnecessnry. However, if using nny other SQL stntement on nny of the grnnts
tnbÌes, you must or oµtionnÌÌy reÌond the server.
The reÌond function is n synonym for the fÌush-µriviÌeges function.
KiIIing My5OL processes
The word hill sounds somewhnt hnrsh, but this is the nnme of the function to termi-
nnte n cÌient µrocess or thrend in the server. Using the
commnnd, you cnn determine the id of n cÌient or µrocess thnt needs to be termi-
nnted. Issuing the function terminntes thnt µrocess. This does
not stoµ the cÌient from reconnecting, in fnct, the CLI reconnects nutomnticnÌÌy.
Part II 5OL EssentiaIs
Here`s n simµÌe exnmµÌe of the function:
1. Using the MySQL CLI, I connect to the MySQL CLI nnd issue n simµÌe
stntement, ns shown in Iigure 1O-2O.
Figure 10-20: Connecting to the MySCL CLI and performing a basic
SELECT statement
2. In Iigure 1O-21 I run the commnnd to determine
the ID of the other cÌient connection. As you cnn see it is 189 ns shown by the
coÌumn of the outµut. AÌso in Iigure 1O-21 I issue the
commnnd to terminnte the µrocess.
Figure 10-21: Using the mysqladmin processlist and mysqladmin kill
commands to terminate a client process
Chapter 10 Databases And Data
3. IinnÌÌy, in Iigure 1O-22 I nttemµt to run the snme stntement ns in
Iigure 1O-2O. Notice the messnge µroduced by the CLI.
Figure 10-22: Issuing the same SELECT statement as in Figure 10-20
results in an error but the statement runs.
Information functions
The function informs the user whnt version of the server is running
nÌong with some other µertinent informntion nbout the server, incÌuding stn-
tus nnd uµtime informntion. An exnmµÌe is shown in Iigure 1O-28.
Figure 10-23: Cutput from the mysqladmin version command shows
the server version along with other useful information on server
Part II 5OL EssentiaIs
The function simµÌy teÌÌs the ndministrntor whether the server, ,
is nÌive. If the server is not nÌive, the commnnd returns nn error. In Iigure 1O-24
I run the commnnd on the server whiÌe it is running, then secretÌy stoµ the
server in nnother window (see Figure 10-26) nnd re-run the function
Figure 10-24: The mysqladmin ping command in action. The first
attempt is successful; the second fails because I shut the MySCL
server down in another window.
Changing passwords through mysqIadmin
The commnnd cnn nÌso be used to set or chnnge µnsswords for users
in the MySQL dntnbnse. In fnct, this is how you chnnged the initinÌ µnssword
for the server bnck when it wns instnÌÌed.
The syntnx for the µnssword function cnn sometimes cnuse confusion. The syntnx
is ns foÌÌows:
The switch is necessnry if you do not wnnt to chnnge the µnssword
for the current user. If you need to suµµÌy nn existing µnssword for the user
nccount sµecified with the usernnme switch (or for yourseÌf if you don`t use the
switch), then you must use the -µ switch to hnve µromµt
for n µnssword. Next the function nnme, µnssword, is required. IinnÌÌy, the new
µnssword is given ns the Ìnst nrgument. The new µnssword must be quoted.
I`ve µreµnred n couµÌe of exnmµÌes, shown in Iigure 1O-2b. The first exnmµÌe
chnnges the µnssword for the current user, which hnµµens to be . The
second exnmµÌe chnnges the µnssword for the root user. 8oth nre ÌocnÌhost
Chapter 10 Databases And Data
Figure 10-25: Examples of changing passwords with the mysqladmin
password command
5topping the My5OL server with mysqIadmin
The function stoµs the MySQL server through the com-
mnnd. As with nny shutdown, the commnnd hns to wnit untiÌ thrends nre through
with tnbÌes, this requirement µrotects the integrity of the dntn. The shutdown func-
tion µrovides no feedbnck to the user, see Iigure 1O-26.
Figure 10-26: The mysqladmin shutdown command provides no
feedback to the user upon success.
kepIication functions with mysqIadmin
There nre two mnin functions of for use with reµÌicntion. These nre the
nnd functions. These functions stnrt nnd stoµ n sÌnve
reµÌicntion µrocess.
Part II 5OL EssentiaIs
Replication takes updates to data from one server and automatically copies them
in real-time to another MySCL server. Chapter 18 covers replication. If you are not
using replication, these functions are of no use.
Exporting Data
Two mnin methods nre nvniÌnbÌe for exµorting dntn from n MySQL dntnbnse:
the stntement.
Whether you`re Ìooking to mnke n simµÌe bnckuµ of the server or exµort certnin
coÌumns from n tnbÌe into nnother µrogrnm such ns Microsoft Access, the exµorting
utiÌities nnd stntements incÌuded with MySQL wiÌÌ he̵.
You can also use a program called mysqlhotcopy to make a copy of a database. In
addition, through the use of the MySCL CLI in non-interactive mode or with the
option, results can be saved or redirected into a file.
The utiÌity is n µowerfuÌ µrogrnm for extrncting dntnbnse nnd tnbÌe
structure nÌong with the nctunÌ dntn. The utiÌity is sufficientÌy grnnuÌnr
so thnt you couÌd get the tnbÌe structure nnd dntn from |ust one tnbÌe or from nÌÌ
tnbÌes of nÌÌ dntnbnses. If you wouÌd |ust Ìike the tnbÌe structure with no dntn you
cnn do thnt ns weÌÌ. If you wnnt |ust the dntn with no tnbÌe structure,
nÌso µrovides thnt functionnÌity. The bnsic syntnx for mysqÌdumµ is ns foÌÌows:
When given no arguments, simply prints a syntax reference.
There are quite a few options with . Some of the options and switches
such as those for specifying the username and password have been discussed in
other chapters. If you are unsure how to specify a username or password with
MySCL utilities, please refer to Chapter 8 for more details.
There nre two vnrinbÌes thnt cnn nffect your nbiÌity to dumµ tnbÌes with Ìnrge
coÌumns: nnd . 8oth cnn be set using
the or switch on the commnnd Ìine or in the
MySQL configurntion fiÌe.
The utiÌity uses comments (escnµed with ) to seÌect oµtions thnt
mny onÌy be found in newer versions of MySQL. Ior exnmµÌe, when crenting n
Chapter 10 Databases And Data
dntnbnse the keywords were introduced in version 8.28.12 of
MySQL. The keywords wiÌÌ be encÌosed in nn escnµe sequence
nÌong with the version number. This nÌÌows the functionnÌity of to
be used by those versions thnt cnn hnndÌe it nnd snfeÌy ignored without error on
those versions thnt do not incÌude the function.
NormnÌ usnge of cnÌÌs for the commnnd nÌong with oµtions such ns user-
nnme nnd µnssword foÌÌowed by the nnme of the dntnbnse to dumµ nnd (oµtionnÌÌy)
sµecific tnbÌes nnd coÌumns to dumµ. In Iigure 1O-27 the commnnd is
issued to dumµ |ust the tnbÌe of the MySQL dntnbnse. The commnnd is
ns foÌÌows:
Figure 10-27: Using mysqldump to obtain the DDL and DML for one
table of one database
Ior most of its uses, redirects the outµut to n fiÌe instend of sending the
outµut to or to the screen (which is the defnuÌt). The chnrncters used to
redirect outµut cnn vnry by OS:
In Linux, you µerform redirect oµerntions with the grenter-thnn ( ) sign.
In Windows, use the or switch with , which
nssists the newÌine nnd cnrringe return.
Part II 5OL EssentiaIs
Iigure 1O-28 shows exnmµÌes of both redirect methods.
Figure 10-28: Examples of redirecting output via the greater-than
sign and the -r switch
5pecifying records to be dumped
You cnn even get more sµecific thnn n µnrticuÌnr tnbÌe with . The use of
the or switch ennbÌes you to ndd n stntement. Ior exnmµÌe, to
dumµ onÌy the contents of the user tnbÌe of the MySQL grnnts dntnbnse where the
user is , the commnnd in Iigure 1O-29 couÌd be issued:
The cÌnuse cnn be Ìonger thnn one nrgument. Ior exnmµÌe, the foÌÌowing
commnnd is vnÌid:
ControIIing the IN5EkI statement
Two oµtions controÌ how nny stntements nre done with . These
oµtions nre ( ), or ( ). The defnuÌt is
LxnmµÌes with both tyµes of insert oµtions nre shown in Iigure 1O-8O. The com-
mnnds to reµroduce these exnmµÌes nre ns foÌÌows:
Chapter 10 Databases And Data
Figure 10-29: Using the --where= switch to specify only certain
records to be dumped
5uppressing DDL
In the exnmµÌes in Iigure 1O-8O, you mny hnve noticed nn extrn oµtion: (nÌso
known ns , which suµµresses the DDL or the stntements thnt
wouÌd otherwise crente the tnbÌe.
The oµtion cnn be usefuÌ for mnking n quick bnckuµ of the dntn in n tnbÌe. Ior
exnmµÌe, if you hnve nnother server thnt contnins the snme tnbÌe structure nnd
onÌy wnnt to migrnte your dntn to the new server, you couÌd suµµress the DDL with
the oµtion. The resuÌt is the DML or stntements to insert the dntn into the tnbÌe
or tnbÌes.
5uppressing DML and data
1ust ns you might wnnt to suµµress the µrinting of tnbÌe crention stntements in the
outµut of n , you might nÌso wnnt to suµµress the nctunÌ DML or insert
stntements from the outµut ns weÌÌ. The switch for this oµtion is or .
Part II 5OL EssentiaIs
Figure 10-30: Examples of the types of INSERT statements that can
be produced by mysqldump
Using the switch, n wiÌÌ simµÌy outµut the tnbÌe (nnd µossibÌy
dntnbnse) crention stntements. This fenture cnn be usefuÌ for mnking n skeÌeton
coµy of the dntnbnse nnd tnbÌe structure on nnother server. Iigure 1O-81 is nn exnm-
µÌe of the switch in nction, µroducing the DDL for the dntnbnse. The
commnnd for this exnmµÌe is ns foÌÌows:
Adding drops and Iocks
cnn be configured to ndd stntements to Ìock nnd unÌock tnbÌes nround
INSLRT stntements. Doing so ensures thnt the wiÌÌ comµÌete without nn
unexµected chnnge in the dntn or contention for the tnbÌe. The switch to ennbÌe the
Ìocking function is .
You cnn nÌso Ìock the tnbÌes nround the rends thnt µroduce the outµut of .
The switch or turns this function on.
The switch teÌÌs to ndd n stntement
|ust before crenting the tnbÌe. Adding this switch cnn be he̵fuÌ if you nÌrendy hnve
tnbÌes of the snme nnme thnt do not contnin usefuÌ dntn.
Chapter 10 Databases And Data
Figure 10-31: The -d or --no-data switch causes mysqldump to
exclude the DML or INSERT statements from the output.
Using the switch will cause all data to be lost in any tables
that are removed.
nÌso incÌudes n switch thnt cnn sµecify n number of the µreviousÌy dis-
cussed oµtions ns weÌÌ ns others. The switch is the switch nnd incÌudes the
switches , , , ,
, nnd .
If you are going to use the , , ,
, , or switch, specifying the
switch is a timesaver.
5peciaI formatting functions with mysqIdump
With you cnn sµecify n number of oµtions thnt determine how the out-
µut wiÌÌ Ìook. These incÌude sµecinÌ quotntion of fieÌds in the outµut, escnµing or
encÌosing the fieÌds in n sµecinÌ mnnner, nnd terminnting Ìines nnd fieÌds with the
desired chnrncter. The switches or oµtions to sµecify on the commnnd
Ìine nre ns foÌÌows:
Part II 5OL EssentiaIs
The first switch, , µÌnces bnckquotes ( ) nround the nnmes of
tnbÌes nnd dntnbnses.
The second switch, , cnn nÌso be nbbrevinted ns . The switch
cnuses to crente two fiÌes, µÌncing outµut from ench tnbÌe in the nrgument
Ìist. One fiÌe is the normnÌ outµut of the DDL thnt you wouÌd
exµect from . The second fiÌe, , is n tnb-deÌimited fiÌe
contnining onÌy the dntn from the tnbÌe.
The switch can be useful for importing data into other applications such
as Microsoft Access.
The or switch exµects n directory or µnth ns nn nrgument, in effect,
using wiÌÌ cnuse the resuÌts to be µÌnced in n directory cnÌÌed
. It is imµortnnt thnt MySQL hnve µermission to write into thnt directory.
Ior this renson, the switch onÌy works when run from the server thnt
runs on. A few exnmµÌes of the switch nre shown in Iigure 1O-82.
The first nttemµt is unsuccessfuÌ becnuse the sµecified directory does not exist. In
the second nttemµt, the MySQL server does not hnve µermission to write into the
directory sµecified. The finnÌ nttemµt is successfuÌ.
Figure 10-32: Three examples of use of the --tab= switch, two
unsuccessful and one successful
Chapter 10 Databases And Data
The nnd oµtions require the use of the switch. Lnch
oµtion is sufficientÌy seÌf-exµÌnnntory. If you wnnt to terminnte or encÌose n fieÌd of
the outµut with n string you cnn do so with these functions. AÌso, things Ìike for
nnd for nre suµµorted, so you cnn seµnrnte fieÌds or Ìines by those
chnrncters ns weÌÌ. The keyword used with cnuses onÌy
nnd coÌumn tyµes to be encÌosed in the sµecified mnnner. LxnmµÌes
of vnrious commnnds thnt use these switches nre shown in Iigures 1O-88
through 1O-86.
Figure 10-33: Performing the command: mysqldump
-p ecommerce --fields-terminated-by=+ --tab=outputdir to produce
output with fields terminated by a plus sign (+)
Figure 10-34: Running the command mysqldump -p ecommerce --
fields-terminated-by="\n" --tab=outputdir to separate all fields by a
newline (\n)
Part II 5OL EssentiaIs
Figure 10-35: The mysqldump -p ecommerce --lines-terminated-
by="HELLC" --tab=outputdir command is run to terminate lines by
the word HELLC.
Figure 10-36: The mysqldump -p ecommerce --fields-enclosed-by="\\"
--tab=outputdir command to produce output with a backslash around
the fields. Note the use of two slashes in the actual command.
Ihe aII-databases function
There nre two mncro-ÌeveÌ functions to dumµ nÌÌ dntnbnses with . With
such functions it is µossibÌe to mnke n bnckuµ coµy of nn entire dntnbnse server ~
though MySQL A8 recommends thnt you use the utiÌity for this
The utility for making backups is covered in Chapter 14.
The first oµtion, or , dumµs nÌÌ dntnbnses, incÌuding dntnbnse
structure nnd dntn. The oµtion nÌso crentes the nctunÌ dntnbnses
ns weÌÌ.
In Iigure 1O-87 the mncro serves to dumµ nÌÌ dntnbnses con-
tnined on my exnmµÌe server. The commnnd to run is ns foÌÌows:
Chapter 10 Databases And Data
Figure 10-37: Using the -A or --all-databases macro to dump the
contents of all databases and data on the server.
As you cnn see by Iigure 1O-87, nÌÌ outµut wns sent to the screen. Ooµs! If there
were nny Ìnrge tnbÌes on the server, the outµut couÌd hnve tnken quite some time.
Using nvoids tying uµ the screen by redirecting the outµut to n fiÌe. As
stnted µreviousÌy, in Linux you use the grenter-thnn sign ( ) to nccomµÌish this redi-
rection. Ior exnmµÌe, to rerun the mncro from the exnmµÌe in
Iigure 1O-87, the commnnd wouÌd be
Performing thnt commnnd µroduces n fiÌe thnt couÌd be imµorted onto nnother
server or servers to crente n snnµshot of the dntnbnse server nt thnt µoint in time.
The fiÌe couÌd nÌso be used ns n bnckuµ ns weÌÌ. Iigure 1O-88 shows nnother run of
the commnnd, foÌÌowed by n Ìook nt the resuÌting dntn.
Ihe databases function
The second mncro-ÌeveÌ function with is the or func-
tion. This oµtion tnkes dntnbnses ns nrguments, µroducing the snme tyµe of outµut
ns the mncro. SµecificnÌÌy, the function incÌudes
nÌÌ DDL to crente the dntnbnse(s) nnd tnbÌe(s) ns weÌÌ ns the stntements to
connect to those new dntnbnses. The difference between the nnd
Part II 5OL EssentiaIs
the mncros is thnt you cnn use the oµtion to
sµecify onÌy the dntnbnses you`d Ìike to use, the oµtion incÌudes
nÌÌ dntnbnses.
Figure 10-38: Taking the mysqldump command and redirecting the
output to a file
The function exµects nt Ìenst one dntnbnse nnme to foÌÌow ns nn nrgu-
ment. If you wnnt to sµecify more thnn one dntnbnse, seµnrnte the dntnbnse nnmes
singÌe sµnces. In Iigure 1O-89 the function serves to µroduce n dumµ
of the MySQL grnnts dntnbnse nnd the ecommerce dntnbnse exnmµÌe. NormnÌÌy I
wouÌd redirect the outµut to n fiÌe (ns shown in Iigure 1O-88), the commnnd thnt
µroduces these resuÌts is ns foÌÌows:
Figure 10-39: Using the --databases function to produce a dump of
two databases
Chapter 10 Databases And Data
Another switch, the switch, is used with the function to
sµecify the tnbÌes in the dntnbnse to incÌude in the outµut.
5uppressing creation of databases
With the two mncro ÌeveÌ functions defined µreviousÌy, the dntnbnses switch
nnd the switch, you cnn µrevent from issuing the stnte-
ment to crente the dntnbnse or dntnbnses. The switch for this nction is or
Ior exnmµÌe, if you nre migrnting from one server to nnother nnd nÌrendy hnve the
dntnbnses crented there is no renson to incÌude stntements in the
resuÌts from . Using the switch, no stntements wiÌÌ
be incÌuded.
Another method for extrncting or exµorting dntn from MySQL is with the
stntement. This stntement is usunÌÌy run from inside the
MySQL CLI nnd cnn µroduce outµut much the snme ns .
The stntement is renÌÌy n stntement nt henrt, with
the modifier thrown onto the end to send the outµut of the query
into n fiÌe. Therefore, modifiers such ns grouµing nnd ordering ns weÌÌ ns the
cÌnuse nre nvniÌnbÌe for use with the stntement.
Chapter 9 and Appendix ß provide more information on the statement.
Chapter 9 shows examples of the SELECT statement in action while Appendix ß
provides the syntax of the SELECT statement in MySCL.
The outµut fiÌe when using the modifier is Ìocnted in the dntnbnse`s
directory on the server. Ior exnmµÌe, if your for MySQL is
undernenth which nµµenr the directories for the vnrious
dntnbnses, the wiÌÌ nµµenr inside the nctunÌ dntnbnse`s directory unÌess
sµecified otherwise.
As with the utiÌity, the stntement µro-
duces the dntn in n tnb-deÌimited formnt. This mnkes it ensy to imµort into n µro-
grnm such ns Microsoft Access.
Unlike the utility, the statement does not
support the selection of all tables from multiple databases. If you want to export
the data to another MySCL server, is the better choice.
Much the snme ns , suµµorts n number of
oµtions thnt controÌ how the dntn is exµorted. These oµtions incÌude
, , , nnd
. These oµtions work the snme ns with .
Part II 5OL EssentiaIs
The fiÌe sµecified in the stntement cnnnot nÌrendy
exist. If the fiÌe exists, the stntement wiÌÌ fniÌ.
Most of the bnttÌe with the stntement is getting the
stntement correct. Syntnx exnmµÌes for the
stntement foÌÌow, ns shown in Iigures 1O-4O nnd 1O-41.
Figure 10-40: An example of a basic SELECT statement coupled with
the INTC CUTFILE modifier and then a look at the results in the file
Figure 10-41: Another SELECT statement using an CRDER ßY
coupled with the INTC CUTFILE modifier and then a look at the
results in the file
The outµut from the stntement in Iigure 1O-4O (nnd mnny others exµorted through
MySQL) cnn be imµorted into other µrogrnms such ns Microsoft Access. Most µro-
grnms cnn recognize the Tnb chnrncter ns n deÌimiter. An exnmµÌe of imµorting the
outµut from Iigure 1O-41 is shown in Iigure 1O-42.
Chapter 10 Databases And Data
Figure 10-42: Importing the data into Microsoft
Access, produced from a SELECT INTC CUTFILE
Importing Data
Showing nn exnmµÌe of the imµort µrocess nt the end of the µreceding section Ìends
directÌy into this section, Imµorting Dntn Into MySQL Dntnbnses. This section exnm-
ines three methods for imµorting dntn into MySQL: Irom the CLI, with the
stntement, nnd with the utiÌity.
The MySQL CLI incÌudes the nbiÌity to imµort dntn. In renÌity, the CLI nÌÌows nny SQL
stntements in n fiÌe to be rend in vin the commnnd Ìine. The syntnx for this fenture is
ns foÌÌows:
The oµtions wouÌd incÌude things Ìike the user, host, nnd µnssword for the MySQL
CLI to nuthenticnte |ust ns with nny other use of the CLI. The fiÌe is exµected to con-
tnin vnÌid SQL stntements, mnny times or stntements µroduced with
Ior exnmµÌe, Iigure 1O-48 shows the contents of n fiÌe to imµort into the
dntnbnse. The contents of the fiÌe were µroduced with . Iigure 1O-48 nÌso
shows the commnnd thnt wiÌÌ insert these into the dntnbnse. It renÌÌy is thnt simµÌe.
Part II 5OL EssentiaIs
Figure 10-43: Importing the contents of a file into a database through
The comµÌement to the stntement is the
stntement. This stntement is normnÌÌy run from the MySQL CLI to imµort
dntn into n tnbÌe. The syntnx for this stntement is ns foÌÌows:
The keyword cnuses the stntement to wnit untiÌ no other
cÌients nre rending from the tnbÌe. The keyword nÌÌows other cÌients to
rend from the tnbÌe whiÌe the stntement is executing.
IiÌes nre normnÌÌy nssumed to be on the server mnchine. With the keyword,
however, the fiÌe is rend from the cÌient host thnt executes the commnnd. The fiÌe-
nnme sµecified must be nn nbsoÌute µnth, whether in the dntn directory of MySQL
or in the nctunÌ dntnbnse`s directory on the server.
Using the keyword blocks you from stopping the import process once
Chapter 10 Databases And Data
The stntement ennbÌes you to determine the nction when
n coÌÌision occurs for records being imµorted to n unique coÌumn. The stntement
cnn either reµÌnce the existing record with the new one or ignore the new
record entireÌy. The keywords to sµecify this behnvior nre nnd ,
Cther options (such as the , and
) work the same as in the
statement and . This chapter includes descriptions and syntax exam-
ples for these options.
One ndditionnÌ behnvior not found in the stntement
or utiÌity is . This modifier nµµenrs in the
cÌnuse. Using the modifier you cnn teÌÌ the
stntement to ignore or skiµ over n certnin number of Ìines nt
the beginning of the fiÌe to be imµorted. Ior exnmµÌe, if you hnve the coÌumn nnmes
ns the first Ìine of the fiÌe you cnn hnve the stntement ignore
thnt first Ìine with the nddition of to the
You cnn nÌso sµecify onÌy certnin coÌumns to imµort into. The coÌumn or coÌumn
Ìist comes nt the end of the stntement, if sµecifying more thnn one coÌumn, seµnrnte
them with n commn. Ior exnmµÌe, to imµort one of the fiÌes from n µrevious exnm-
µÌe nnd onÌy imµort the coÌumn, the foÌÌowing stntement is issued:
The resuÌts from the µreceding stntement nre shown in Iigure 1O-44.
Figure 10-44: An example of using the LCAD DATA INFILE statement
to import only one column
Part II 5OL EssentiaIs
The utiÌity is n commnnd-Ìine µrogrnm for imµorting dntn into n
MySQL dntnbnse. The utiÌity is simiÌnr in usnge to the
stntement. The bnsic syntnx for the utiÌity is ns foÌÌows:
As with most MySCL programs, you can obtain a syntax listing for
by typing the command with no switches or arguments, or by using the or
Much Ìike the MySQL CLI, uses the snme switches for sµecifying the
user, host, µort, µnssword, nnd so on.
Chapter 8 covers the basic switches.
As is renÌÌy n commnnd-Ìine version of , the func-
tionnÌity is nenrÌy the snme. One exceµtion not Ìocnted in nnother stntement or
commnnd is the or switch. Using , wiÌÌ deÌete
the contents of the tnbÌe µrior to imµorting.
With , if you sµecify n coÌumn or coÌumns to imµort into you do
so by ndding them onto the end of the stntement. With , this is ndded
with the or switch. The nnd functionnÌity is cnÌÌed
with the or nnd , resµectiveÌy.
Much Ìike the , , nnd
utiÌities the use of switches for formntting is suµµorted by . These nre
ns foÌÌows:
The or switch teÌÌs to Ìook on the ÌocnÌ cÌient for the fiÌe
to imµort. This is ns oµµosed to the normnÌ behnvior where MySQL wiÌÌ senrch for
the fiÌe on the server running . Notice thnt the switch is nn uµµercnse L. The
Ìowercnse switch is n synonym for the function thnt Ìocks
nÌÌ tnbÌes before µroceeding with the imµort.
Chapter 10 Databases And Data
MySQL incÌudes six tnbÌe tyµes. Three nre non-trnnsnctionnÌ, two nre trnnsnc-
tionnÌ, nnd one resides onÌy in voÌntiÌe memory.
The mnin tnbÌe tyµe in MySQL is . descends from the
tnbÌe tyµe thnt incÌudes fewer fentures. The tnbÌe tyµe is n coÌÌection of
MySQL tnbÌes for quicker oµerntion.
The two trnnsnctionnÌ tnbÌe tyµes in MySQL nre nnd .
These tnbÌe tyµes use more resources thnn reguÌnr non-trnnsnctionnÌ tnbÌes
but nre snfer in the event of error.
The tnbÌe tyµe is n temµornry tnbÌe thnt resides onÌy in voÌntiÌe memory.
The commnnd is n µowerfuÌ commnnd for mnnngement nnd
ndministrntion of n MySQL server.
With you cnn stoµ the server, troubÌeshoot µerformnnce µrobÌems,
nnd crente or deÌete dntnbnses.
There nre two mnin methods for exµorting dntn from MySQL, nnd
the stntement.
The utiÌity incÌudes the nbiÌity to exµort both DDL nnd DML.
Therefore, with you cnn crente n comµÌete snnµshot of n server
incÌuding dntnbnses, tnbÌes, nnd the nctunÌ dntn.
The stntement is normnÌÌy run from the MySQL
CLI. With you hnve the µower of n reguÌnr
stntement whiÌe exµorting dntn with mnny µowerfuÌ oµtions.
There nre three mnin methods for imµorting dntn into MySQL. Dntn cnn be
imµorted through the MySQL CLI, with the stntement,
or with .
The MySQL CLI ennbÌes you to execute SQL stntements by rending the
contents of n fiÌe from the commnnd Ìine.
With the stntement you cnn imµort through the CLI with n
number of oµtions such ns how to hnndÌe duµÌicnte vnÌues.
The utiÌity is n commnnd-Ìine version of
nnd incÌudes the snme oµtions. The utiÌity nÌso incÌudes nn
oµtion to deÌete the dntn from the tnbÌe µrior to imµort.
ln Ihis Porl
Chopler JJ
Server Conllgurollons
Chopler J2
Chopler J3
Debugglng ond
Repolrlng Doloboses
Chopler J4
Perlormonce lunlng
P A k I
s evidenced nenrÌy everywhere in this book, MySQL is
highÌy customiznbÌe. Irom customizntions during the
instnÌÌntion µrocess detniÌed in Chnµters 8, 4, nnd b to configu-
rntions for the CLI thnt I wrote nbout in Chnµter 8, MySQL is the
most customiznbÌe mn|or dntnbnse server nvniÌnbÌe. Of course
you wouÌd exµect so since you cnn downÌond the source code
for MySQL nnd write it to your exnct sµecificntions.
In this chnµter I`m going to exnmine server configurntions nnd
customizntions through the use of the my.cnf or my.ini config-
urntion fiÌes. These configurntions wiÌÌ mninÌy work with
server vnrinbÌes nnd switches for the mysqÌd server µrocess.
I`ÌÌ begin with n Ìook nt the vnrinbÌes nnd switches themseÌves
nnd then use some snmµÌes thnt come with the MySQL soft-
wnre for smnÌÌ, medium, nnd Ìnrge instnÌÌntions.
My5OL 5erver VariabIes
MySQL cnn nnd shouÌd be tuned to the µhysicnÌ server hnrd-
wnre thnt it is running on nnd for the mnin nµµÌicntion or
nµµÌicntions thnt it wiÌÌ be serving. A grent mnny vnrinbÌes cnn
be chnnged thnt nÌter the wny n server oµerntes. When set
correctÌy these vnrinbÌes cnn imµrove the µerformnnce of the
server nnd thus the nµµÌicntions using the dntnbnse. As you
wouÌd exµect, when set incorrectÌy these vnrinbÌes cnn
degrnde the µerformnnce of the server ns weÌÌ. In this section
I`ÌÌ exnmine the vnrinbÌes themseÌves.
Viewing current server variabIes
You cnn Ìook nt nÌÌ the vnrinbÌes nnd settings for the server
through the stntement from in the MySQL CLI
or with the mysqÌndmin vnrinbÌes commnnd. The stntement
nnd commnnd yieÌd the snme resuÌts, ns shown in Iigure 11-1.
The commnnd to reµroduce the outµut shown in Iigure 11-1 is
, the fuÌÌ outµut foÌÌows.
C H A P I E k
ln Ihis Chopler
Clossllylng MySCL
server vorlobles
Benchmorklng ond
lesllng MySCL
Exomlnlng somple
conllgurollon llles
Developlng your own
conllgurollon llle
Runnlng more lhon
one MySCL Server
on lhe some mochlne
Part III Administration
Figure 11-1: Partial output from the mysqladmin variables statement
TnbÌe 11-1 shows some MySQL server vnrinbÌes commnnd, nÌong with brief descriµ-
tions of their µurµoses. The ndditionnÌ vnrinbÌes µresented in the outµut of the
vnrinbÌes do not nffect server µerformnnce. Most of those vnrinbÌes
nnd settings nre discussed in other chnµters throughout the book.
Table 11-1
My5OL server variabIes
Vorioble Whot it does
Sets size of buffer for caching rows and indexes of ßDß
Sets size of buffer for the ßDß logs.
Sets maximum number of locks you can have on a ßDß
Sets size of cache for statements to be put into the
binary log.
Chapter 11 5erver Configurations
Vorioble Whot it does
Determines the length of time will wait for a
Determines when the key can be flushed (tables with
this option active cannot have the key flushed until the
table is closed).
Sets number of rows to be inserted before the delay is
Sets amount of time to wait for
Sets size of the queue for
statements in rows.
Sets time (in seconds) to free up resources by closing
all tables.
Enabled if ( ) tables are available.
Enabled if tables are available.
Enabled if tables are available.
Indicates whether tables are available.
Indicates whether RAID will be used.
Indicates whether SSL is available.
Sets amount of time waits for activity on
interactive clients.
Sets size of buffer used for full operations.
Sets size of buffer used for indexes shared among
Indicates whether this version of supports large
Indicates whether the logging of all queries is enabled.
Indicates whether the logging of updates is enabled.
Indicates whether a binary log file format is in use.
Indicates whether updates from the slave should be
Sets number of seconds before the
counter is enabled.
Sets maximum size of any one packet.
Part III Administration
Table 11-1 (cont/nµed)
Vorioble Whot it does
Sets maximum size of the cache for the binary log.
Sets maximum size of the binary log.
Sets maximum number of simultaneous connections.
Sets maximum number of errors from a given host.
Sets maximum number of threads to start for
Sets maximum size for a table.
Sets maximum size for joins.
Sets number of bytes to use for sorting and
Sets maximum number of simultaneous user
Sets maximum number of temporary tables to create.
Sets number of write locks that occur before a read lock
is enabled.
Sets maximum size before the key cache is used.
Sets maximum size of the temporary file used to create
an index with myisam table.
Sets size of buffer for myisam index functions.
Sets size of communications buffer.
Specifies time to wait between reads before closing a
Specifies number of times to retry a connection before
Specifies time to wait between writes before closing a
Specifies number of file descriptors to open.
Sets initial size of the query buffer.
Specifies buffer to use for threads that do sequential
Indicates whether internal or external locking is in use.
Chapter 11 5erver Configurations
Vorioble Whot it does
Increments a counter if a thread takes longer than this
interval to launch.
Allocates buffer for functions that sort.
Sets maximum number of open tables across all
Sets number of threads to keep in cache for reuse.
Sets size of stack for an individual thread.
Sets maximum size for a temp table before being
converted to .
Sets maximum time to wait for a connection until it is
timed out.
The server I`ve been using in mnny of the exnmµÌes in this book is n convenient
exnmµÌe of setting vnrinbÌes. It`s n Pentium 2OOMMX with 96M8 RAM, running
SÌnckwnre Linux. On this server, I hnd to chnnge n couµÌe of settings to nvoid using
uµ nÌÌ the memory. The defnuÌts for my server nre ns foÌÌows:
Part III Administration
Chapter 11 5erver Configurations
Part III Administration
Chapter 11 5erver Configurations
Part III Administration
Chapter 11 5erver Configurations
AÌthough the outµut given here does contnin even more vnri-
nbÌes, these nre beyond the scoµe of this chnµter.
5o many variabIes, so IittIe time
As you cnn see from TnbÌe 11-1 nnd the vnrinbÌe µrintout, I sµenk the truth nbout
the Ìnrge number of server vnrinbÌes nnd settings nvniÌnbÌe for nn ndministrntor to
work with. When you ndd cnµnbiÌities such ns reµÌicntion, even more vnrinbÌes nnd
settings must be considered.
At this µoint you mny be nsking, ¨Which vnrinbÌes nnd settings do I rcolly hnve to
chnnge nnd which ones cnn be Ìeft nt the defnuÌts"" I certninÌy cnn`t µrench thnt nÌÌ
vnrinbÌes must be set for ench server, in my view, thnt`s neither true nor µrncticnÌ.
Resµonding to testing nnd feedbnck from users of MySQL, MySQL A8 hns set
defnuÌts for most vnrinbÌes thnt wiÌÌ work weÌÌ.
Another renson not to set nÌÌ the vnrinbÌes is thnt the MySQL server itseÌf is quite
efficient for most uses of the dntnbnse ~nnywhere from |ust n few records to n few
hundred thousnnd or more. I`ve worked with Ìnrge dntnbnses (millions of rows) on
whnt I wouÌd consider normnÌ hnrdwnre ~Pentium-cÌnss comµuters with 128M8
RAM~nnd noticed no µerformnnce µrobÌems thnt wouÌd mnke me wnnt to chnnge
too mnny server vnrinbÌes.
However, working with sµecific nµµÌicntions or dntnbnses mny require thnt you set
or chnnge vnrinbÌes to imµrove µerformnnce of the MySQL server. Some rensons
you mny hnve to set vnrinbÌes incÌude the foÌÌowing:
A sµecific nµµÌicntion µerforms oµerntions on the dntnbnse sÌow or cnuse the
server to Ìng.
The use of Ìower-end hnrdwnre or smnÌÌ nmounts of resources.
Using MySQL on n server thnt runs mnny other nµµÌicntions nnd services.
Inefficient or µoorÌy written nµµÌicntions thnt cnuse µrobÌems for the server
or dntnbnse.
A desire to imµrove your server`s µerformnnce.
Coming bnck to the originnÌ question in this section, how do you know which vnri-
nbÌes to set if you wnnt oµtimnÌ µerformnnce from MySQL" LuckiÌy, MySQL A8 hns
done some of the homework for mnny imµÌementntions, two fentures of its instnÌÌn-
tion µrogrnm cnn he̵ you oµtimize MySQL:
A suite of applications helps you benchmark your server's performance.
MySQL nÌso incÌudes nnother set of tests known ns the Croshmc tests.
Together with the MySQL 8enchmnrk nµµÌicntions, the Crnsh-me tests he̵
you give your server n vigorous test. These nµµÌicntions nnd scriµts he̵
determine nnd test the Ìimits of your server by simuÌnting renÌ-worÌd scennr-
ios. The benchmnrking nµµÌicntions nre n series of tests contnined in the
directory within your MySQL instnÌÌntion. The Crnsh-me tests nre
Part III Administration
contnined within one µrogrnm nµtÌy titÌed , nnd nÌso in the sqÌ-bench
directory. In the next section I`ÌÌ Ìook nt some of the benchmnrking nµµÌicn-
tions incÌuded with MySQL.
Even with the tests and benchmarking, you still need a way to simulate a real-
world load on a database server. A program called Super-smack does that job; you
can use it to try out various values as you set parameters until you get the ones
that work best for your configuration. Super-smack is available for free from
MySCL Aß. To get Super-smack, go to the Contributed Software section of the
MySCL Web site .
Sample configuration files let you try out different-size implementations.
Look for these snmµÌe configs in the directory of your MySQL
instnÌÌntion. Iour snmµÌe configurntion fiÌes nre incÌuded:
The snmµÌe configurntion fiÌes nre covered in detniÌ Ìnter in this chnµter.
My5OL ßenchmarking and Iesting
IncÌuded with the MySQL softwnre nre nµµÌicntions nnd scriµts for testing the Ìimits
nnd vnrinbÌes of the MySQL server. These tests cnn he̵ to imµrove µerformnnce by
showing obvious bottÌenecks on the nctunÌ hnrdwnre with cÌose to renÌ-worÌd sce-
nnrios. Using sµecific tests you cnn simuÌnte how your server wiÌÌ be used nnd see
whnt imµrovements must be mnde. I`ve hnd times where running the tests snved
me from imµÌementing n server on hnrdwnre thnt couÌdn`t stnnd uµ to the Ìond for
the nµµÌicntion to be run.
kequirements for the appIications
The 8enchmnrk nnd Crnsh-me nµµÌicntions use n number of different tyµes of stnte-
ments nnd functions. The nµµÌicntions nre incÌuded with 8innry instnÌÌntions of
MySQL nnd MySQL-Mnx ns weÌÌ ns with the MySQL source code. To use the nµµÌicn-
tions from nn RPM-bnsed instnÌÌntion, mnke sure you instnÌÌ the RPM
(in nddition to the other MySQL RPMs). AdditionnÌ requirements for the bench-
mnrking nnd Crnsh-me nµµÌicntions nre ns foÌÌows:
Chapter 11 5erver Configurations
AÌÌ the Ìntest coµies of the PerÌ-D8I nnd the MsqÌ-MysqÌ-moduÌes cnn be found on
PerÌ is normnÌÌy incÌuded with Linux, though you mny not hnve instnÌÌed it when
you instnÌÌed the oµernting system. IoÌÌow the instructions incÌuded with the PerÌ-
D8I for instnÌÌntion of the softwnre. The MsqÌ-MysqÌ-moduÌes nsk some reÌevnnt
questions during the instnÌÌntion, see Iigure 11-2.
Figure 11-2: Running Makefile.PL for the Msql-Mysql-modules poses
some questions about how you would like to configure the modules.
How you nnswer the questions for instnÌÌntion ÌnrgeÌy deµends on how you intend
to use the moduÌes, nnd whether you hnve n µrevious version instnÌÌed. If you
intend to use through n PerÌ nµµÌicntion, you mny wnnt to consider instnÌÌing
the moduÌe for thnt in nddition to the MySQL moduÌe. In Iigure 11-2, I simµÌy seÌect
MySQL becnuse I don`t µÌnn to use , vin PerÌ or otherwise, for the exnmµÌes.
kunning the tests
Once you hnve the µrerequisites instnÌÌed you cnn run the 8enchmnrk nµµÌicntions
nnd Crnsh-me tests. The nµµÌicntions nre Ìocnted in the directory in
your MySQL server directory. The 8enchmnrking suite incÌudes vnrious tests for
different tyµes of nµµÌicntions to Ìook nt different nsµects of server µerformnnce ~
in µnrticuÌnr, how it hnndÌes some crucinÌ nsµects of dntnbnse oµerntion:
8ig tnbÌes
AÌterntion of tnbÌes
Crention of tnbÌes
Part III Administration
Query oµtimizntion nnd other nsµects of the server
The finnÌ test in the suite is cnÌÌed the Wisconsin test. (And no, this isn`t something
I`m |ust mnking uµ becnuse I`m from the stnte of Wisconsin.) The Wisconsin test is n
comµrehensive set of tests to Ìook nt query oµtimizntion nnd µerformnnce of other
nsµects of the server.
The directory contnins n number of scriµts, ns shown in Iigure 11-8.
Figure 11-3: A directory listing for the sql-bench directory in MySCL
You cnn run the tests individunÌÌy or nÌÌ nt once. RegnrdÌess of the whether you run
them one nt n time or nÌÌ nt once, you must sµecify nt Ìenst n µnssword to ennbÌe the
µrogrnms to run. Other commnnd-Ìine switches nre nvniÌnbÌe to sµecify user nnd
host. Ior exnmµÌe, to run the nµµÌicntion, the foÌÌowing commnnd Ìine
wouÌd be used:
As you cnn see, you hnve to sµecify the nctunÌ µnssword on the commnnd Ìine for
the nµµÌicntion to run. If you sµecify the user, do so with the
syntnx. To sµecify the host, use syntnx.
The scriµt thnt cnÌÌs nÌÌ the other testing nµµÌicntions (nnd runs them nÌÌ in
sequence) is cnÌÌed . This scriµt nÌso requires thnt the µnssword be
given ns nn nrgument. Running this scriµt on n sÌower server ~sny, n Pentium
2OOMMX with 96M8 RAM~cnn incrense the server Ìond (not to mention thnt the
tests themseÌves tnke hours). Therefore I wouÌd not recommend running these tests
in n µroduction environment.
Chapter 11 5erver Configurations
Running the testing suite can cause performance problems on the MySCL server. I
recommend against running the testing suite during peak usage or in a production
CurrentÌy the tests nre not muÌtithrended, they oµen one connection nt n time to
the MySQL server. This does Ìimit the nbiÌity of the tests to truÌy simuÌnte n renÌ-
worÌd environment where muÌtiµÌe users or thrends frequentÌy use the dntnbnse
simuÌtnneousÌy. In future versions, MySQL A8 wiÌÌ ndd to the testing suite to run
muÌtiµÌe thrends.
If the tests nre tnking nn incredibÌy Ìong time nnd you think something mny hnve
gone wrong, you cnn check the µrogress of the tests with n couµÌe commnnds on
the MySQL server. Running the stntement or
commnnd wiÌÌ n singÌe thrend running for the tests, ns shown in Iigure
11-4. Note the different vnÌues in the fieÌd ns the testing suite runs
Figure 11-4: The mysqladmin processlist shows the progress of the
testing suite, in this instance the INSERT tests.
8ecnuse the tests simuÌnte so mnny different nµµÌicntions nnd imµÌementntions, if
you know you`re going to hnve nn -henvy nµµÌicntion, you cnn Ìimit the test-
ing to |ust the test. Then, by twenking vnrinbÌes to imµrove µerfor-
mnnce nnd rerunning the test, you cnn see whether you get n noticenbÌe
µerformnnce imµrovement from the new settings.
Part III Administration
5ampIe Configuration FiIes
Iour snmµÌe configurntion fiÌes come with MySQL. These fiÌes µrovide defnuÌts
bnsed on the hnrdwnre thnt MySQL server wiÌÌ be run on. The snmµÌe configurntion
fiÌes cnn µrovide n good stnrting µoint for defnuÌts. Ior most nµµÌicntions, the
defnuÌt settings wiÌÌ work |ust fine.
Examination of the sampIe configuration fiIes
The snmµÌe configurntion fiÌes cnn be found in the directory of
your MySQL instnÌÌntion. The four fiÌes rnnge in recommended use from mnchines
with Ìess thnn 64M8 RAM to mnchines with 1G to 2G RAM. Ior ench of the fiÌes, I`m
going to exnmine the mnin server µortion undernenth the section, nnd
nÌso other chnnges thnt tnke µÌnce in the fiÌe to nffect other nµµÌicntions such ns
nnd so on.
The first fiÌe, for mnchines with Ìess thnn 64M8 RAM, is cnÌÌed .
MySQL A8 recommends this configurntion fiÌe for use where MySQL is not the µri-
mnry nµµÌicntion, nnd is onÌy used now nnd then for minor dntnbnse functions.
The reÌevnnt section from is shown in Iigure 11-b.
Figure 11-5: The [mysqld] section from the my-small.cnf example
defaults file for MySCL
Chapter 11 5erver Configurations
The second fiÌe, , is for mnchines with smnÌÌer nmounts of memory
(under 128M8). If MySQL is the soÌe nµµÌicntion (or one of n few µrimnry nµµÌicn-
tions) running on n mnchine Ìike this, then the configurntion fiÌe mny be for
you. In nddition, if you hnve 128M8 to 2b6M8 nnd MySQL wiÌÌ be working with other
nµµÌicntions (such ns Aµnche or other services), the medium configurntion wouÌd
be n good stnrting µoint for n configurntion fiÌe.
The exnmµÌe section of the configurntion fiÌe for is shown in Iigure 11-6.
The third configurntion fiÌe, , is mennt for systems thnt hnve more thnn
b12M8 RAM, though Ìess thnn 1G8 RAM. The server is mninÌy resµonsibÌe for dntnbnse
tnsks with MySQL~therefore it isn`t running mnny other services. Of course, running
n Web server for nn interfnce wouÌd µrobnbÌy be ncceµtnbÌe. However, n µroduction
Web server for µubÌic use wouÌd be better run on n seµnrnte server.
Figure 11-6: The [mysqld] section from the my-medium.cnf example
defaults file for MySCL
The section for nf is shown in Iigure 11-7.
IinnÌÌy, the exnmµÌe configurntion fiÌe for the Ìnrgest configurntions is
. This fiÌe is mennt ns nn exnmµÌe fiÌe for systems with 1G8 RAM or more,
where MySQL is the solc nµµÌicntion or service running on the server. If you intend
to run nny other nµµÌicntions or services, you shouÌd run them servers other thnn
the MySQL server ~nnd you cnn use this exnmµÌe fiÌe ns n good stnrting µoint. If
you nre running n MySQL server in such nn environment, you wiÌÌ µrobnbÌy hnve to
set other vnrinbÌes sµecificnÌÌy to mntch your nµµÌicntion.
Part III Administration
Figure 11-7: The [mysqld] section from the my-large.cnf example
configuration file for MySCL.
The section from the exnmµÌe configurntion fiÌe is shown in Iigure 11-8.
Notice how the configurntion fiÌe exnmµÌes differ from ench other. In the exnmµÌe
configurntion fiÌe for dntnbnse servers, the buffer sizes tnke ndvnntnge of the
Ìnrge nmounts of RAM memory nvniÌnbÌe for use. The configurntion-fiÌe exnmµÌe for
servers uses much Ìess RAM for buffers nnd other µnrnmeters.
DeveIoping your own configuration fiIe
The first recommendntion I hnve is to usc on cxomplc filc ihoi closcly moichcs your
confiµuroiion ÷not onÌy of your mnchine, but nÌso of your µÌnnned nµµÌicntion(s).
Ior exnmµÌe, I use the fiÌe for the exnmµÌe server thnt I`m using ~n
Pentium 2OOMMX with 96M8 RAM.
After stnrting the dntnbnse server, monitor the vnrinbÌes nnd µerformnnce through
the use of the commnnd. Of course, your users wiÌÌ
teÌÌ you if the dntnbnse is µerforming sÌowÌy.
Chapter 11 5erver Configurations
Figure 11-8: The [mysqld] section from the my-huge.cnf example
configuration file for MySCL.
When the µerformnnce of the MySQL server is degrnded, it is time to nnnÌyze why it
is hnµµening. One item thnt cnn nssist, though it does crente µerformnnce degrndn-
tion itseÌf, is the oµtion in the configurntion fiÌe. Using the function, you
cnn ensure thnt nÌÌ queries to the server nre Ìogged (see Iigure 11-9). Using this Ìog-
fiÌe, you cnn then determine whether queries cnn be oµtimized~or whether you
hnve to fine-tune n server vnrinbÌe. To ennbÌe the function, ndd the keyword
within the section of the MySQL configurntion fiÌe.
Other Ìogging oµtions, ns defined in TnbÌe 11-1, cnn nssist in dingnosing whnt
µnrnmeters nnd vnrinbÌes nre working nnd which ones might not be. With some
µntience whiÌe tuning the server, you cnn use these Ìogging oµtions to he̵ mnke
MySQL`s µerformnnce exceµtionnÌ.
ße sure to turn off logging when it's needed; it can degrade performance.
ße careful not to increase too many values at once or make memory-based values
too large. This can cause disk-swapping behavior as the server runs out of avail-
able RAM and has to use (slower) virtual memory.
Part III Administration
Figure 11-9: An example of the logfile for queries with the log option
enabled in the configuration file
Iigure 11-1O, for exnmµÌe, shows snmµÌe outµut from n run of the
Figure 11-10: Sample output of the test-select benchmarking
application running with the generic my-small.cnf configuration file
Chapter 11 5erver Configurations
After getting the resuÌts, I tnke n Ìook nt the vnÌues from
, ns shown in Iigure 11-11.
Figure 11-11: Examination of the values from the mysqladmin
extended-status command after running the test-select benchmark
Notice the vnÌues for nnd . This indicntes thnt
there were n Ìnrge number of requests for index use nnd thnt mnny of them couÌdn`t
be hnndÌed by the . Therefore, I incrense the in the
configurntion fiÌe nnd re-run the tests to see whether I cnn get nny imµroved resuÌts.
The resuÌts of the new test nre shown in Iigure 11-12.
The incrense in µerformnnce for the nµµÌicntion did not come with-
out cost. To get the µerformnnce imµrovement, I incrensed the
vnÌue to 16M from 16K! On n server with onÌy 96M8 RAM to begin with, this might
not be such n good iden ~disk swnµµing cnn incrense if other nµµÌicntions thnt nre
currentÌy running require much memory.
AÌso, notice thnt the incrense in does not show uµ on the snme
order ns the incrense in µerformnnce. In effect, I incrensed the vnÌue from 16K to
16M. Thnt`s nn incrense of 1,OOO times. If you comµnre the resuÌts from Iigure 11-1O
nnd Iigure 11-12 you`ÌÌ see thnt the times were cut by roughÌy bO/. Therefore
incrensing the vnÌue to 16M is (to µut it miÌdÌy) somewhnt
nggressive for this imµÌementntion.
Part III Administration
The exnmµÌe |ust given shows you how to dingnose the µerfor-
mnnce of your MySQL server. You shouÌd be nbÌe to use your knowÌedge of the com-
mnnds to work with the server nnd imµrove µerformnnce where necessnry.
Figure 11-12: An increase in the key_buffer_size value greatly
improved performance for the test-select benchmark.
Other vnrinbÌes thnt cnn nssist in imµroving µerformnnce deµend on the hnrdwnre
nnd nµµÌicntions. Ior exnmµÌe, if you hnve nn nµµÌicntion thnt oµens mnny thrends
nnd negÌects to cÌose them, you couÌd Ìower the vnrinbÌe. Of
course, the better soÌution wouÌd be to fix the fnuÌty nµµÌicntion nnd hnve n tnÌk
with the deveÌoµer who designed it.
Another exnmµÌe: The error messnge indicntes thnt you
might consider incrensing the size or chnnging the design of the
dntnbnses on the server. Other vnrinbÌes (some of them reÌntiveÌy seÌf-evident) cnn
be set with ÌittÌe troubÌe ~for exnmµÌe, the vnrinbÌe. If
you need to mnke more connections nvniÌnbÌe, you cnn incrense this vnÌue nnd
restnrt the server.
ßringing it aII together
AµµÌicntions chnnge, dntn chnnges, nnd other µnrnmeters on the server hnve to
chnnge ns weÌÌ. Therefore tuning nnd monitoring of server vnrinbÌes is not n one-
time tnsk. You shouÌd check nnd monitor µerformnnce reguÌnrÌy through the
tus nnd commnnds, ns weÌÌ ns by monitoring the Ìogs.
Chapter 11 5erver Configurations
If you notice n sÌowdown of MySQL during certnin oµerntions you mny hnve to
twenk n vnrinbÌe or two. Through µroµer dingnostics nnd testing, you cnn deter-
mine which vnrinbÌes to nÌter to imµrove µerformnnce. MySQL µrovides enough
feedbnck nnd tooÌs to he̵ you get this |ob done.
kunning More Ihan One My5OL 5erver
on the 5ame Machine
A server configurntion thnt some ndministrntors find the need to imµÌement is one
where muÌtiµÌe instnnces of MySQL nre running on the snme µhysicnÌ mnchine. The
MySQL server softwnre uses comµÌeteÌy seµnrnte dntnbnses thnt know nothing of
the other MySQL server or servers running on thnt mnchine. This section Ìooks nt
how to instnÌÌ muÌtiµÌe MySQL servers on the snme comµuter.
Configuration of muItipIe My5OL servers
Ior more thnn one MySQL server to run successfuÌÌy on the snme mnchine, the
servers must use different directories for the MySQL server fiÌes nnd dntnbnses. In
nddition, ench server must use n unique socket fiÌe nnd µort number. If you nre
instnÌÌing from source, you cnn sµecify these µnrnmeters nt comµiÌe time. This is
the method recommended by MySQL A8, it Ìooks Ìike this:
If you wnnt to use binnry versions of MySQL you cnn sµecify the µnth nnd fiÌe
oµtions on the commnnd-Ìine or in n MySQL configurntion fiÌe. Here`s the syntnx to
use when you sµecify them on the commnnd Ìine:
In older versions of MySCL, the command to start the server is .
Connecting to muItipIe My5OL servers
When connecting to n MySQL server thnt is not Ìistening on the defnuÌt µort of
88O6 or is nvniÌnbÌe through n non-defnuÌt socket fiÌe you must sµecify this on the
commnnd-Ìine. Ior exnmµÌe, to connect to n MySQL server running on µort 66O8
using the CLI, the ndditionnÌ switch or is necessnry:
Part III Administration
Other defnuÌts mny be rend from the defnuÌt MySQL configurntion fiÌe. However, this
fiÌe mny refer to the wrong MySQL server. Using the
, you cnn sµecify the fiÌe thnt is rend for defnuÌts.
If you don`t sµecify n hostnnme, MySQL wiÌÌ nssume thnt you nre connecting to the
server on ÌocnÌhost nnd wiÌÌ use the socket to connect to the server. In such nn
event you need to sµecify the Ìocntion of the socket fiÌe. Do so with the
or switch, the commnnd Ìooks Ìike
MySQL cnn be ~nnd shouÌd be ~tuned to the µhysicnÌ server hnrdwnre thnt it is
running on, nnd configured for the mnin nµµÌicntion or nµµÌicntions thnt it wiÌÌ be
serving. When set correctÌy, the MySQL server vnrinbÌes cnn imµrove the µerfor-
mnnce of the server nnd thus the nµµÌicntions using the dntnbnse.
You cnn Ìook nt nÌÌ the vnrinbÌes nnd settings for the server through the
stntement from within the MySQL CLI (or with the
vnrinbÌes commnnd).
Though mnny settings nre nvniÌnbÌe for n MySQL server, most of them do need
not be individunÌÌy configured.
MySQL comes with benchmnrking nnd testing utiÌities for dingnosing server
MySQL A8 hns incÌuded snmµÌe configurntion fiÌes for different sizes nnd
Among these configurntion fiÌes, you cnn choose from smnÌÌ, medium, Ìnrge,
nnd huge imµÌementntions.
Once nn exnmµÌe configurntion fiÌe hns been chosen, it shouÌd be customized
for the nµµÌicntion nnd instnÌÌntion thnt the MySQL server wiÌÌ be used for.
Customizing the server vnrinbÌes is n µrocess thnt tnkes time. The ndministrn-
tor cnn chnnge settings nnd then use one or nÌÌ of the benchmnrking utiÌities
to test the µerformnnce of the MySQL server.
8ecnuse dntn nnd nµµÌicntions chnnge, the server shouÌd be monitored for
µerformnnce issues. If you notice µerformnnce degrndntion, further testing
shouÌd revenÌ where bottÌenecks nre.
n oft-overÌooked nren of MySQL nnd comµuters in
genernÌ is security. How mnny µntches nnd security fixes
hnve to come out for n Web server before nn ndministrntor
uµdntes it" How often does n server hnve to be broken into
before nn ndministrntor turns off unnecessnry services nnd
chnnges unsecured defnuÌt settings" These questions nre not
rhetoricnÌ, sooner or Ìnter, every ndministrntor must fnce them.
This chnµter introduces some simµÌe security ruÌes nnd
suggestions to imµrove the security of your MySQL server
nnd the integrity of the dntn you keeµ there.
5ecurity of the My5OL Host 5erver
The lcosipricilcµc sysicm is n high-security nµµronch to the
nssigning of nccess µriviÌeges to users. It requires thnt no
unnecessnry services be ennbÌed on the server, thnt the server
softwnre gets reguÌnr uµdntes ns soon ns they nre nvniÌnbÌe,
nnd thnt users nre not given more µriviÌeges thnn their work
If everyone subscribed to the Ìenst-µriviÌege system, I beÌieve
there wouÌd be much Ìess business for security consuÌtnnts.
AÌthough I ndmit thnt it tnkes time to nµµÌy µntches nnd keeµ
uµ with security uµdntes, the snme nrguments stiÌÌ nµµÌy: How
much time does it tnke to reµnir n server dnmnged by unnu-
thorized use" How vnÌunbÌe is your dntn if you ¨cnn`t nfford"
to sµend the time securing your systems"
A good stnrting µoint in nny discussion of system security is
to define unouihorizcJ usc nnd oiioch in consistent, µrncticnÌ
terms. AÌthough the words themseÌves mny seem obvious,
nttncks nnd unnuthorized uses nctunÌÌy incorµornte severnÌ
distinct conceµts:
LxµÌoits, whether initinted from outside or inside, tnke
ndvnntnge of n security hoÌe for the nttncker`s own gnin.
C H A P I E k
ln Ihis Chopler
lmplemenllng securlly
lor lhe MySCL hosl
Selllng up MySCL
sollwore securlly
Conllgurlng MySCL
oulhenllcollon ond
Monoglng user
occounls ln MySCL
Coplng wllh common
securlly problems
Part III Administration
Attncks (ngnin, whether initinted from outside or inside) nre often more
nggressive nnd seek to disruµt, dnmnge, or even bring down the tnrget system.
Unnuthorized use is not Ìimited to µurµosefuÌ nttncks or exµÌoits on n server
or network, it cnn nÌso be unintended, ns in these exnmµÌes:
º A user with too mnny µriviÌeges mny not renÌize they nre innµµroµrinte,
use them inefficientÌy or incorrectÌy, nnd wnste system resources such
ns stornge sµnce nnd bnndwidth.
º A hnrried deveÌoµer who menns no hnrm cnn unÌensh fnuÌty code thnt
disruµts n server no Ìess thnn does n hncker nttnck.
º Sometimes nn ndministrntor`s test of system security goes nwry nnd
interferes too much with its oµerntion.
Knowing thnt your system is vuÌnernbÌe to disruµtion, whether mnÌicious or unin-
tentionnÌ, shouÌd shnµe your security µoÌicy. The Ìenst-µriviÌege conceµt µrovides
n good stnrting µoint, ns in these exnmµÌes:
Providing n weÌÌ-thought-out set of Ìimited µriviÌeges to n deveÌoµer he̵s
ensure thnt new nµµÌicntions for the server nre renÌisticnÌÌy tested, but nÌso
Ìimits the µossibÌe consequences of running fnuÌty code.
Limiting users to minimnÌ necessnry µriviÌeges cnn thwnrt some nttncks
before they even begin.
Although the usual assumption is that attacks always start outside and/or are
always intentional, it's far from true. When I refer to attacks, attackers, or unautho-
rized uses, I have in mind a wider definition that includes both intentional and
unintentional disruptions.
Locating security information
Mnny ndministrntors nnd wouÌd-be ndministrntors comµÌnin thnt they hnve troubÌe
keeµing uµ with uµdntes. No centrnÌ reµository of informntion for uµdntes nnd
reµorts of exµÌoits now exists (nÌthough thnt mny be nÌÌ to the good ~why give
hnckers nny more idens thnn they nÌrendy hnve"), in the worÌd of network security,
you`re ÌnrgeÌy on your own. To give you n usefuÌ stnrting µoint ns you grnµµÌe with
issues of network security, I`ve incÌuded some onÌine sites thnt cnn he̵, nnd inter-
sµersed this chnµter with some essentinÌ security conceµts to keeµ in mind, the
first of which is ns foÌÌows:
Maintain a proactive approach to keeping up with exploits and problems with soft-
ware you are running.
Security does require n µronctive nµµronch, keeµing servers nnd softwnre secure
is difficuÌt enough. Comµnnies thnt wnnt to mnintnin n vinbÌe reµutntion for their
Chapter 12 5ecurity
µroducts mny wnnt to suµµress nÌÌ knowÌedge of exµÌoits or try to keeµ them
secret, but by fnr the more ethicnÌ resµonse to security vuÌnernbiÌity is to µroduce,
document, nnd distribute nn effective µntch. The nvniÌnbiÌity of such µntches (nnd n
good trnck record for µroducing them in n timeÌy mnnner) is one teÌÌing criterion
thnt he̵s define nn nbove-nvernge vendor.
5ecurity focus
Lven though informntion on security is scnttered ncross the Internet nt diffuse Ìocn-
tions, one Web site stnnds out ns n consistent reµository for reÌinbÌe informntion:
Security Iocus, . Using this site nn ndministrn-
tor cnn keeµ uµ with exµÌoits nnd security µntches ns soon ns they nre nvniÌnbÌe.
The Security Iocus Web site is nÌso home to numerous mniÌing Ìists, security-reÌnted
nnd otherwise. Iigure 12-1 shows some of the mniÌing Ìists nvniÌnbÌe for subscriµ-
tion on the Security Iocus Web site. One of the most notnbÌe nnd fnmous is the
8ugtrnq mniÌing Ìist, wideÌy regnrded ns the most ndeµt nt keeµing uµ with security
issues ncross n wide vnriety of µÌntforms. Ior µeoµÌe worried nbout being inun-
dnted with yet more e-mniÌ, mnny high-voÌume Ìists nt Security Iocus offer digest-
mode subscriµtions ns weÌÌ.
Figure 12-1: Some mailing lists, security-related and otherwise, available from the
Security Focus Web site
Part III Administration
AppIy patches and fixes
1ust keeµing uµ with the exµÌoits nnd hoÌes thnt come to Ìight in servers nnd softwnre
isn`t enough. You must nµµÌy the µntches nnd fixes ns soon ns they nre reÌensed. This
brings me to the simµÌe second ruÌe:
Apply patches and fixes as soon as they are released.
If no µntch is nvniÌnbÌe, try to find n worknround thnt effectiveÌy thwnrts nttncks.
Ior exnmµÌe, I`ve mnintnined n system thnt rnn n µubÌic ITP server serving thou-
snnds of renÌ users. AÌong with the renÌ users, the ITP server nÌso nÌÌowed nnony-
mous nccess for non-µnying µeoµÌe from nÌÌ over the Internet to downÌond fiÌes.
A certnin exµÌoit ngninst thnt µnrticuÌnr ITP server couÌd onÌy be done by nnony-
mous nccess. No µntch wns immedinteÌy nvniÌnbÌe from the vendor, so I chose to
disnbÌe nnonymous nccess untiÌ n µntch couÌd be reÌensed. AÌthough this is not nn
oµtimnÌ soÌution, sometimes you hnve to disnbÌe nccess for n reÌntiveÌy short time
in order to nvoid n much worse nÌternntive ~n non-trusted user getting ndministrn-
tive rights. As soon ns n µntch wns nvniÌnbÌe for the ITP server, I nµµÌied it nnd re-
ennbÌed nnonymous nccess.
DisabIe unused programs and services
Lvery now nnd ngnin, |ust for fun, I nssist n friend with the security of his comµuter
systems by µerforming n µort scnn of his servers. I never cense to be nmnzed nt how
mnny µorts he Ìenves oµen for the worÌd to tnke ndvnntnge of. He runs n bnsic Web
server thnt nÌso serves ns nn e-mniÌ server. Such n server shouÌd hnve no more thnn
three µorts oµen: TCP µort 8O for the Web server, TCP µort 2b for the SMTP server
nnd TCP µort 11O for the POP8 server. UnfortunnteÌy, it doesn`t stoµ there. He wns
surµrised to Ìenrn thnt he nÌso hnd nn NNTP server nnd even nn IRC server running!
The Ìesson is summed uµ in nnother bnsic security µrinciµÌe:
Disable unused services and verify that only the services you specify are running.
Much of the µrobÌem with extrnneous services being ennbÌed stems from the defnuÌt
instnÌÌntions of mnny oµernting systems nnd softwnre. My friend`s µrobÌem nrose
becnuse he chose defnuÌt oµtions whiÌe instnÌÌing Microsoft`s Internet Informntion
Server. However, the µrobÌem isn`t Ìimited to Microsoft oµernting systems nnd soft-
wnre. Choosing whnt nµµenr to be the defnuÌt oµtions with Red Hnt Linux cnn nÌso
yieÌd mnny invisibÌy ennbÌed services thnt nre nÌso security µrobÌems.
With n µrogrnm such ns you cnn effectiveÌy scnn both TCP nnd UDP µorts of
nn Internet server to find unexµected µorts thnt mny be running. The µrogrnm
is nvniÌnbÌe for Linux nnd Windows but cnn scnn ngninst nny IP-bnsed host. In Iigure
12-2 I run n bnsic scnn ngninst one of my ÌocnÌ mnchines.
Chapter 12 5ecurity
Figure 12-2: The nmap program can assist in determining open
ports on one of your servers.
Never perform port scans against any IP or server that you are not responsible for.
Doing so can get you terminated by your ISP or worse!
Most versions of Linux nnd mnny other oµernting systems incÌude n µrogrnm cnÌÌed
thnt cnn he̵ you determine which µorts your sever is using to Ìisten to
onÌine trnffic. AÌthough is n µowerfuÌ µrogrnm thnt does much more thnn
|ust showing which µorts nre Ìistening, thnt Ìistening function is n source of µotentinÌ
security hendnches. In Iigure 12-8, for exnmµÌe, I run the commnnd
to µroduce bnsic outµut of the µorts thnt this server is Ìistening on. This server is
Ìistening for connections to TCP µort 22 for connections, UDP µorts 67 nnd 68
to tnÌk to n DHCP server, nnd TCP µort 88O6 for MySQL.
Figure 12-3: The netstat -an command shows the ports of this server
that are available for connection.
Part III Administration
After using n µrogrnm such ns or , you shouÌd hnve n cÌenrer µicture
of whnt services nre running on your server. The more services you hnve running,
the more vuÌnernbÌe the server is to nttnck. Thus turning off nÌÌ unnecessnry ser-
vices cnn snve you time nnd hendnches.
My5OL 5oftware 5ecurity
Uµ to this µoint, I`ve been Ìooking nt whnt you cnn do with the security of the host
thnt runs the MySQL server. The security of the MySQL host server is nn essentinÌ
first steµ in enhnncing the overnÌÌ security of the dntnbnse server (nnd thus the
dntn). Without first securing the host server, no nmount of MySQL security wiÌÌ
keeµ your dntn snfe.
In this section I`m going to exnmine whnt cnn be done with the MySQL server itseÌf.
This incÌudes keeµing the server uµ to dnte, securing communicntion chnnneÌs, nnd
monitoring the server stntus.
My5OL updates
Though onÌy one µiece of the security µuzzÌe the MySQL softwnre itseÌf is (Ìike nny
other softwnre) susceµtibÌe to µrobÌems nnd security exµÌoits. Though these hnve
been very few nnd fnr between for MySQL, the µrobÌems cnn hnµµen nonetheÌess.
DeveÌoµing n systemntic nµµronch for keeµing uµ to dnte with MySQL softwnre wiÌÌ
nssist in keeµing the dntnbnse snfe from nttnck.
The best method for monitoring when n new version of MySQL is reÌensed is by
subscribing to the MySQL Announce mniÌing Ìist. Offered for free by MySQL A8, this
mniÌing Ìist wiÌÌ give you uµdntes when new versions of MySQL nre reÌensed. Don`t
worry nbout it overcrowding your inbox, the MySQL Announce Ìist is Ìow-voÌume.
Another mniÌing Ìist nvniÌnbÌe for MySQL is the mnin MySQL mniÌing Ìist. This Ìist
is much higher voÌume ns it contnins questions from genernÌ users of MySQL nnd
discussion of mnny MySQL-reÌnted toµics. If you wouÌd Ìike to Ìenrn more nbout
the inner workings of MySQL, this mniÌing Ìist cnn he̵.
I've included a link to the mailing list section of the MySCL Web site on the Links
document on the CD-RCM with this book.
When nn uµdnte is reÌensed, you must mnke bnckuµs of your dntn µrior to µroceed-
ing with the uµgrnde. This is necessnry becnuse of the inherent unknown in
uµgrndes of nny nnture. I`ve usunÌÌy found thnt if I tnke the time to mnke bnckuµs
nothing wiÌÌ go wrong ~but if I forego thnt steµ, inevitnbÌy something wiÌÌ fniÌ.
üo the
Chapter 12 5ecurity
In Chapter 13 backup and recovery of MySCL databases is covered in detail.
Since the uµgrnde µrocess is quite customized (deµending on your instnÌÌntion),
exhnustive covernge is neither µossibÌe nor desirnbÌe here. Often the soÌution is ns
simµÌe ns recomµiÌing or overwriting nn existing MySQL instnÌÌntion.
kun the server as a non-priviIeged user
In Linux}Unix, you cnn set the user nccount thnt runs the MySQL server µrocess,
. (This is ns oµµosed to running the server µrocess ns the suµeruser
on the system.) Iigure 12-4 shows n µrocess Ìisting from Linux, with the server
running ns n non-µriviÌeged reguÌnr user cnÌÌed .
Figure 12-4: Running the MySCL server as a non-privileged user can
prevent unauthorized access in the event of an exploit performed on
the server.
8y running the server ns n normnÌ user in Linux}Unix, the server onÌy hns the snme
µriviÌeges ns thnt user. In other words, if the server is exµÌoited the nttncker cnnnot
gnin further nccess or µerform other µriviÌeged µrocesses on the server.
To ennbÌe MySQL to run ns nnother user on the system, foÌÌow these steµs:
1. Add the user, nnd if desired n grouµ, to the server. This is normnÌÌy nccom-
µÌished vin the nnd commnnds.
2. Mnke sure the user hns nccess to the dntn nnd server fiÌes for MySQL. This
steµ is nccomµÌished with n combinntion of nnd in Linux.
3. Add the oµtion to the commnnd Ìine, or ndd the
Ìine to the fiÌe under the section.
Part III Administration
Full details of installation of the MySCL server, including details on configuring the
server to run as a non-privileged user, are located in Chapter 3.
FirewaIIing the My5OL server
The most effective security to µrotect the MySQL server from outside nttnck is to
µrevent µeoµÌe from the outside from gnining nccess to the server. InstnÌÌing n fire-
wnÌÌ to µrotect the server wiÌÌ he̵ to µrevent nccess from non-trusted hosts.
Using n µnssive firewnÌÌing soÌution to simµÌy µrevent nttncks is n good soÌution.
The use of n firewnÌÌ stoµs outside or non-trusted Ìocntions from even knowing thnt
n MySQL server is nvniÌnbÌe nt your Ìocntion. An nttncker cnn`t gnin nccess to your
dntn if they cnn`t find it.
Another oµtion is to use nn ociicc fircuoll thnt Ìistens on common (nnd even uncom-
mon) µorts for n non-trusted user sending n µort-scnn or µrobe to your mnchines.
The nctive firewnÌÌ then comµÌeteÌy bÌocks nccess from thnt IP nddress to nÌÌ µorts.
If you must nÌÌow nccess to the MySQL server from outside the firewnÌÌ, you need
onÌy nÌÌow nccess to the µort on which MySQL Ìistens for TCP connections. 8y
defnuÌt, this is µort 88O6. Iurther, you shouÌd onÌy nÌÌow nccess to the MySQL µort
from sµecific trusted IP nddresses. You couÌd nÌso crente nn SSH tunneÌ through n
trusted host without hnving to oµen uµ nny µorts for MySQL on the firewnÌÌ.
Lven with n firewnÌÌ in µÌnce, you must mnke sure thnt trusted hosts don`t serve ns
n Ìnunching µoint for nttnckers. Monitor these mnchines to mnke sure they nre uµ to
dnte nnd hnve the Ìntest security µntches. Using the nctive firewnÌÌing soÌution, you
cnn monitor these servers to mnke sure they nren`t originnting µort scnns or other
common µrobes ngninst the servers in your network or within your trusted domnin.
Communicating secureIy with the My5OL server
As of version 4 of MySQL, communicntion over TCP vin the Secure Sockets Lnyer
(SSL) is µossibÌe. Prior to this nÌÌ communicntion between server nnd cÌient µnssed
unencryµted. The nmbitious nttncker couÌd therefore wntch trnffic ns it µnssed nnd
gnther informntion on dntn ns weÌÌ ns user nnd µnssword informntion.
With SSL suµµort ennbÌed, the trnffic between the MySQL server nnd the cÌient is
encryµted. Lven if nn nttncker gnins enough nccess to envesdroµ on nn eÌectronic
conversntion, he or she cnn`t mnke sense of the resuÌting dntn.
The SSL option is not enabled on a connection by default. However, you can
enable it and even require it through the use of the additional user privilege sys-
tem when SSL is compiled into MySCL.
Chapter 12 5ecurity
Using socket-based connections
8y defnuÌt, MySQL Ìistens for connections both through sockets for ÌocnÌ connec-
tions nnd vin TCP}IP for remote connections. If you wiÌÌ not be connecting to MySQL
from nny hosts other thnn the MySQL server itseÌf, you shouÌd disnbÌe the TCP}IP
oµtion in MySQL.
DisnbÌing networking µrevents you from using the or oµtion, whether from
the ÌocnÌ mnchine or from other hosts on the network. Attemµting to connect to n
MySQL server thnt is not nvniÌnbÌe (or not Ìistening for connections) vin TCP}IP wiÌÌ
resuÌt in nn error, ns shown in Iigure 12-b.
Figure 12-5: Attempting to connect to a MySCL server that is not
listening for connections, using TCP/IP
You cnn disnbÌe TCP}IP-bnsed connections by ndding the
oµtion to the commnnd Ìine when stnrting the server. Another wny to disnbÌe
TCP}IP nccess is to ndd the oµtion to the section
of the MySQL configurntion fiÌe.
In the future, MySCL Aß may alter the connection sequence, thus altering the fin-
gerprint for MySCL. For older servers the fingerprint will remain the same.
Changing the My5OL defauIt port
WhiÌe certninÌy not n substitute for n firewnÌÌ or for disnbÌing TCP}IP networking,
nnother method for sÌowing nn nttnck is to chnnge the µort thnt MySQL Ìistens on
for connections. 8y defnuÌt, MySQL Ìistens on TCP µort 88O6 for connections. If you
chnnge the defnuÌt µort, n curious µerson who scnns for µort 88O6 won`t discover
Part III Administration
thnt you hnve n MySQL server unÌess he or she uses other methods for fingerµrint-
ing the server on nnother µort.
Iingerµrinting n MySQL server is µossibÌe. A curious µerson couÌd oµen connec-
tions on rnndom or sequentinÌ µorts nnd see n fnmiÌinr signnture or fingerµrint thus
discovering your MySQL server. In Iigure 12-6, I hnve the MySQL server set to Ìisten
on µort b1bO. Then, by simµÌy teÌnetting to thnt µort, I cnn see n reµentnbÌe µnttern.
Figure 12-6: Telnetting to a port that MySCL listens on shows a
definite fingerprint indicating that it is indeed a MySCL server.
Notice, in Iigure 12-6, thnt the µnttern is nÌwnys the snme. The beginning of the
session oµens with n Ìeft µnrentheses foÌÌowed by n Ìine-feed. Then n µnttern of
digits is shown foÌÌowed by eight chnrncters. Lnch time I teÌnet to the server, the
µnttern reµents. Now I know not onÌy thnt there is n MySQL server on this host but
nÌso whnt version of the server is running, ns indicnted by the digits.
As you cnn see, simµÌy chnnging the µort wiÌÌ not stoµ nn nmbitious nttncker. The
sµeed nnd trivinÌity with which nn nttncker couÌd scnn 6b,OOO µorts for n MySQL
server mnkes chnnging the defnuÌt µort somewhnt of n moot µoint. However, I stiÌÌ
beÌieve thnt chnnging the defnuÌt µort cnn serve n µurµose to discournge the cnsunÌ
onÌooker or curious µerson.
To chnnge the defnuÌt µort thnt MySQL Ìistens for TCP}IP connections on, ndd the
Ìine to the section of the MySQL configurntion fiÌe. Ior exnmµÌe, in
Iigure 12-7 the section is shown from nn exnmµÌe server configurntion fiÌe. (Note
thnt the µort number hns been chnnged for the server.)
For the sake of security, you must change any applications -including the MySCL
CLI -so they connect via the alternative port number.
Chapter 12 5ecurity
Figure 12-7: Changing the port that the MySCL server listens on can
help to hide the server from a curious person.
Monitoring data sent to My5OL
When dntn is entered into n dntnbnse from nµµÌicntions, esµecinÌÌy those thnt nÌÌow
users to tyµe in their own vnÌues, you must check the dntn for errors nnd other
nnomnÌies. It is the resµonsibiÌity of the deveÌoµer to ensure thnt dntn sent to the
MySQL server is cÌenn nnd free from error. The errors occur from two sources:
A malicious attack: With intentionnÌ nttncks on the nµµÌicntion nnd dntnbnse,
the nttncker mny nttemµt to escnµe DDL stntements into the nµµÌicntion.
There nre simµÌe methods for µreventing this tyµe of nttnck incÌuding n Ìenst-
µriviÌeged user nnd dntn cÌennsing.
Normal users: Sometimes normnÌ users of nn nµµÌicntion nre more dnngerous
thnn n wouÌd-be nttncker. RegnrdÌess of how mnny notes nnd documents you
crente for use of the nµµÌicntion, inevitnbÌy someone wiÌÌ innocentÌy enter nn
iÌÌegnÌ vnÌue. The deveÌoµer must nccount for these errors nnd µrovide some
feedbnck to the user vin error messnges or reguÌnr bentings.
As nn ndministrntor, you shouÌd nttemµt to mnke sure thnt the deveÌoµer under-
stnnds whnt is needed from n dntnbnse side to mnke sure the dntn is snfe. This
incÌudes working with the deveÌoµer on the design of the dntnbnse nnd tnbÌes
within the dntnbnse so thnt the incoming dntn is of the µroµer Ìength nnd tyµe
for the coÌumn.
1ust ns imµortnnt is mnking sure the deveÌoµer µerforms necessnry cÌennsing of
inµutted dntn. These steµs cnn be enumernted for items thnt the ndministrntor nnd
deveÌoµer must work on together:
Use n Ìenst-µriviÌeged user for connections from the nµµÌicntion to the dntnbnse
or use more thnn one user, one user for inserts nnd uµdntes, one for seÌects.
Check nÌÌ vnÌues to ensure thnt they nre the exµected formnt, string or number.
Part III Administration
Check nÌÌ vnÌues for Ìength.
Check nÌÌ vnÌues to mnke sure they contnin no unexµected chnrncters.
These tiµs mny seem Ìike common sense, but you might be surµrised nt how mnny
nµµÌicntions don`t check for errors in the dntn, or give incoming dntn onÌy n gÌnnce.
Later in this chapter, I show how to add users to the database. Armed with this
information, you can then add a least-privileged user account that you can use to
connect to the database from applications. Thus, even if you miss a step in error
checking (or someone finds a way around error checking), the damage is minimal.
DisabIing DN5
One method of nttncking n server or mnniµuÌnting dntn is to mnsquernde ns n
trusted server or cÌient in n MySQL cÌient-server exchnnge. This tyµe of nttnck is
µossibÌe ngninst nÌÌ nµµÌicntions thnt utiÌize Domnin Nnme System (DNS) dntn, not
|ust MySQL. 8y µosing ns n trusted or known host, the nttncker cnn µotentinÌÌy gnin
nn innµµroµrinte ÌeveÌ of µriviÌeges.
Ior n DNS nttnck to occur, the nttncker must be nbÌe to nÌter the DNS dntn on one
of the resoÌvers for your MySQL server. Ior exnmµÌe, if you hnve set
ns n DNS server for your MySQL server, the nttncker must nÌter the DNS dntn on nnd send bnck fnÌse informntion nbout hosts in your MySQL communicn-
tion. An nttncker couÌd nÌso sµoof µnckets within the communicntion nnd µretend
to be If DNS dntn is nÌtered or untrusted nn nttncker couÌd nÌso µretend
to be n trusted host becnuse the host is µnrt of the MySQL nuthenticntion scheme.
DNS nttncks nre not Ìimited soÌeÌy to the server. A DNS nttnck couÌd be µerformed
ngninst n cÌient ns weÌÌ. In n cÌient nttnck, fnÌse informntion is µnssed to the cÌient
nnd n fnke MySQL server µoses ns the renÌ server (thus getting nuthenticntion
informntion ns weÌÌ ns the dntn being µnssed from cÌient to server).
To prevent a DNS attack from being successful, you can turn off hostname lookups
in MySCL. All connections will be based on IP address, with the exception of local-
host connections. To disable DNS use from MySCL, start with the
command-line switch . You can also add
to the MySCL configuration file.
Dynamic My5OL monitoring of Web pages
Using the HTML function of the MySQL CLI you cnn crente n Web µnge with server
informntion. With n scheduÌer such ns cron you couÌd then crente the Web µnge in
reguÌnr intervnÌs to monitor the µerformnnce of the MySQL server. The resuÌting
Web µnges won`t win nwnrds for design, but they wiÌÌ µroduce usefuÌ informntion
for ndministrntion of the MySQL server.
Chapter 12 5ecurity
Using these µnges, the ndministrntor cnn monitor the MySQL server`s µerformnnce.
This cnn snve time nnd mnke it so other ndministrntors cnn monitor the MySQL
server without hnving to know the bnckend commnnds for MySQL ndministrntion.
You should protect these Web pages via effective passwords; unauthorized access
to them is especially dangerous.
A requirement for viewing dynnmic monitoring Web µnge on n network is to get n
Web server running. This does not hnve to be the snme µhysicnÌ mnchine ns the
one thnt houses the MySQL server. If the mnchines nre seµnrnte you wiÌÌ need to
nutomnticnÌÌy trnnsfer the resuÌting outµut from the MySQL commnnds to the Web
The foÌÌowing exnmµÌe µrocesses nre µerformed in Linux, running nn Aµnche Web
server. (Your version of Linux mny vnry sÌightÌy from the one shown here.)
Creating the fake database
The steµs invoÌved to µroduce n MySQL monitoring Web µnge nre ns foÌÌows:
1. Mnke n µubÌicÌy nvniÌnbÌe directory to hoÌd HTML outµut, using this commnnd:
2. Crente n µnssword method to µrevent unnuthorized nccess to the directory, the
fiÌe is n usefuÌ exnmµÌe, nnd Iigure 12-8 shows how to crente one.
Figure 12-8: Creating a .htaccess file within the mysqlmonitor directory
to prevent unauthorized access to the MySCL monitoring Web pages.
3. With the fiÌe in µÌnce, you must crente n µnssword fiÌe to nccom-
µnny the fiÌe. The nnme of the fiÌe is sµecified in the fiÌe.
Part III Administration
The user thnt you ndd for does not need to be n system user or exist
on the system in nny wny exceµt in the µnssword fiÌe for . The foÌÌow-
ing commnnd crentes the µnssword fiÌe (ns sµecified in the fiÌe) nnd
ndds n user cnÌÌed to the nccess fiÌe (ns shown in Iigure 12-9):
Figure 12-9: Using the htpasswd command to create the password
file specified in the .htaccess file and adding a user called suehring
to the password file
The password file for should not be in a publicly available directory. In
addition, adding a user to the password file for does not affect the
user's rights on the system, if any.
4. Now ndd n user to the MySQL dntnbnse to retrieve the informntion for the
Web µnges. To nccomµÌish this, crente n fnke dntnbnse nnd give the user
nccess to the dntnbnse.
Crenting n fnke dntnbnse ennbÌes you to hnve n user on the dntnbnse server
with onÌy n bnre minimum of µriviÌeges ~nnd then onÌy on n dntnbnse thnt
hoÌds no tnbÌes or dntn. You cnn use the commnnd to crente the
fnke dntnbnse, do so from inside the CLI, or however you`d Ìike. The commnnd
Ìooks Ìike this:
5. With the fnke dntnbnse in µÌnce, you cnn ndd the user to the dntnbnse server
(normnÌÌy done vin the MySQL CLI, ns shown in Iigure 12-1O).
Chapter 12 5ecurity
Figure 12-10: Adding a user to the MySCL database server
6. Since you`re crenting Web µnges with stntus informntion, the user doesn`t
need nny extrn µriviÌeges. The foÌÌowing commnnd simµÌy crentes the user on
the dntnbnse server (but does not give the user µriviÌeges such ns ,
, , or the Ìike):
The statement is not necessary when you're using the
Creating the script that makes the Web pages
With the Web server nnd nccess method rendy, you cnn crente n scriµt for µroduc-
ing the nctunÌ Web µnges. The scriµt itseÌf cnn be n simµÌe sheÌÌ scriµt (which
Windows users know ns n Windows scriµt), or it cnn be done in nnother Ìnngunge
such ns PerÌ. The conceµt for the scriµt is simµÌe: Run the MySQL CLI commnnd
in bntch mode, use the switch to µroduce HTML outµut, nnd redirect thnt
outµut to n fiÌe.
Iigures 12-11 nnd 12-12 show exnmµÌes of simµÌe scriµts to check the stntus of the
server vin the stntement ~nnd nÌso to Ìook nt the µrocesses running
on the server vin the stntement. Iigure 12-11 is n simµÌe sheÌÌ
scriµt, Iigure 12-12 is n scriµt written in PerÌ.
You will probably need to change the paths to both the MySCL CLI and the direc-
tory in which you want to produce the HTML output from the script.
Part III Administration
Figure 12-11: A shell script for creating two Web pages to monitor
MySCL server information
Figure 12-12: A Perl script for creating two Web pages to monitor
MySCL server information. This script can be run on any system that
has Perl, including Windows and Mac CS X systems, by changing the
location of Perl at the top of the script.
ßoth these scripts are included on the CD-RCM.
üo the
Chapter 12 5ecurity
ße sure to control access to the script. It contains the password for one of the
users on your MySCL server.
You couÌd get fnncy nnd use n concntennte redirect of the outµut to µÌnce both
commnnds in one fiÌe. Adding the outµut into one fiÌe gives you one µÌnce to moni-
tor. You couÌd nÌso crente nnother scriµt to µroduce outµut nt oµµosite intervnÌs,
thus you couÌd monitor chnnges in the vnrinbÌes over time.
The outµut from either scriµt is shown (ns viewed through n Web browser) in
Iigures 12-18 nnd 12-14.
Figure 12-13: The output from the SHCW STATUS statement, as produced by the
Part III Administration
Figure 12-14: The remaining output from the SHCW PRCCESSLIST statement as
produced by the MySCL CLI HTML switch
The finnÌ steµ, though oµtionnÌ, is to scheduÌe the scriµt to run nutomnticnÌÌy. How
often you wouÌd Ìike to scheduÌe the scriµt deµends on how busy your server is,
nnd how often you wnnt to scheduÌe it. Using in Linux, I scheduÌe the scriµt to
run every 1b minutes, ns shown in Iigure 12-1b.
Figure 12-15: Scheduling the monitoring script to run every
15 minutes by using the cron command in Linux
Chapter 12 5ecurity
My5OL Authentication and PriviIeges
Prior to getting down to the dirty business of working with users, I beÌieve it is nec-
essnry to give nn overview of the MySQL nuthenticntion system. This incÌudes the
stnges of nuthenticntion ns weÌÌ ns the µriviÌeges thnt cnn be grnnted nnd revoked.
(This nÌso gives me nnother chnnce to get on n sonµbox nbout µnsswords.)
Overview of My5OL authentication
The MySQL µriviÌege system works on n number of ÌeveÌs µrior to nÌÌowing nccess
to the server. UnÌike systems where simµÌy n usernnme nnd µnssword nre exnmined
to determine nccess, MySQL uses the usernnme, µnssword, nnd host to determine
nccess ÌeveÌ for the dntnbnse.
MySQL uses n two-stnge µrocess for determinntion of your nccess ÌeveÌ, the connec-
tion ÌeveÌ nnd µrocess ÌeveÌ. Using these two ÌeveÌs, in two sequentinÌ steµs, the
MySQL server determines
Whether you nre nÌÌowed to connect nt nÌÌ.
Whether you hnve µriviÌeges to µerform the requested oµerntion or stntement.
During the first stnge, which I wiÌÌ refer to ns the Connection Stnge, the MySQL
server combines the user nnd host µrovided ns credentinÌs nnd determines if the
given combinntion is nÌÌowed to connect with the given µnssword.
1. The first µhnse of the Connection Stnge combines the , , nnd
coÌumns from the tnbÌe of the MySQL dntnbnse.
º If no dntnbnse is incÌuded in the connection request, nccess is grnnted or
denied nt this µoint. The host coÌumn within the grnnts dntnbnse cnn
contnin nny vnÌid hostnnme, IP nddress, or ÌocnÌhost. In nddition, the
wiÌdcnrds nnd nre vnÌid ns nre netmnsk vnÌues. Ior nÌÌ hosts, the
wiÌdcnrd cnn be used. Ior exnmµÌe, wouÌd
grnnt nccess to usernnme from nny nddress within the 192.168.1.O}24
rnnge. This is the snme ns usernnme'192.168.1.O}2bb.2bb.2bb.O`. If given
usernnme'/` then usernnme nt nny host wouÌd be nÌÌowed.
º If n dntnbnse is incÌuded within the connection request, the second
µhnse begins.
2. The second µhnse of the Connection Stnge of nuthenticntion is to verify
credentinÌs for the dntnbnse.
This µhnse is µerformed ngninst the tnbÌe of the MySQL dntnbnse.
The tnbÌe is exnmined for host, dntnbnse, nnd user. If nccess to nÌÌ dntnbnses
is grnnted to the user, this stnge nutomnticnÌÌy µnsses, otherwise nccess is
grnnted or denied, deµending on the informntion in the tnbÌe.
Part III Administration
3. The third µhnse of the Connection Stnge is µerformed ngninst the tnbÌe
of the MySQL dntnbnse. The nnd coÌumns from the host tnbÌe
nre incÌuded in this µhnse.
If connections from n host nre restricted in some wny, this tnbÌe determines
nµµroµrinte nccess.
During the next (second) stnge of MySQL nuthenticntion, the requested µrocess is
exnmined for sµecific µriviÌeges to determine nccess. Ior exnmµÌe, if the user nttemµts
to issue n stntement, the nuthenticntion µrocess Ìooks ngnin nt the tnbÌe
of the MySQL dntnbnse. If nuthenticntion µnsses the tnbÌe, it is ngnin
µnssed on to the tnbÌe nnd then to the tnbÌe. If the stntement is run ngninst n
tnbÌe, the tnbÌe is nÌso consuÌted for nuthenticntion, if the stntement
runs ngninst n coÌumn or coÌumns, then the tnbÌe is consuÌted.
My5OL priviIeges
Lnch tnbÌe of the MySQL dntnbnse µrovides the µriviÌeges shown in TnbÌe
12-1 (with the exceµtion of the , , , nnd µriviÌeges,
which nre Ìimited to the tnbÌe becnuse they hnve no menning in other contexts).
Table 12-1
My5OL PriviIeges and their functions
Privilege Function
Table-level privilege for selecting data or performing queries.
Table-level privilege for adding data.
Table-level privilege for updating or changing data.
Table-level privilege for deleting data from tables.
Table-level privilege for creating and deleting indexes.
Table-level privilege for changing table layout.
Database-, table-, and index-level privilege for creation of databases,
tables and indexes.
Database- and table-level privilege for deleting databases and tables.
Database- and table-level privilege for enabling a user to alter privileges
for other users including adding and deleting users.
Database- and table-level privilege for using references.
Server-level privilege for reloading and flushing server parameters.
Server-level privilege for stopping the MySCL database server.
Server- level privilege to enable process listing and killing.
Server- level privilege to work with files such as selecting into outfiles.
Chapter 12 5ecurity
If the privilege is given to a user, that user will be able to read the contents
of all other databases on the server.
The µriviÌeges nre simµÌe insofnr ns they menn whnt they nre nnmed. To issue n
stntement, you need the µriviÌege, to insert dntn you need the
µriviÌege, nnd so on.
5ecurity of passwords
Working with nn Internet service µrovider, I cnn`t count the number of times I`ve
seen µeoµÌe choose bnd µnsswords. I`ve seen nÌÌ the mistnkes in the book, from
choosing the usernnme ns the µnssword to using the worst oÌd fnvorite µossibÌe
(the word possuorJ). I beÌieve these tyµes of mistnkes nre, in the words of 1nmes R.
Leu, ¨comµÌeteÌy unncceµtnbÌe." ReguÌnr users mny hnve nn excuse for choosing
µoor µnsswords, but System nnd Dntnbnse Administrntors don`t. As the µerson who
is in chnrge of n server or servers, it is your |ob to use µnsswords thnt cnnnot be
ensiÌy guessed or crncked.
Password guideIines
I`ve µut together some guideÌines thnt shouÌd he̵ you choose effective µnsswords,
come uµ with stronger ones, nnd keeµing the ones you hnve secure.
Pnsswords shouÌd be six chnrncters nt nn nbsoÌute minimum.
Pnsswords shouÌd incÌude n mix of n̵hnnumeric chnrncters such ns Ìetters
nnd numbers nnd non-n̵hnnumeric chnrncters, such ns ¨©#$´&*".
When you crente n µnssword, never use words thnt you cnn find in n dictio-
nnry (or those snme words sµeÌÌed bnckwnrds).
Pnsswords shouÌd incÌude the use of both sides of the keybonrd or both
hnnds whiÌe tyµing. In other words, don`t use µnsswords thnt require you to
use onÌy your Ìeft hnnd or the Ìeft side of the keybonrd onÌy.
Pnsswords shouÌd be different ncross servers. Don`t use the snme µnssword
for nÌÌ of your servers, routers, nnd other genr. Thus, if one mnchine is com-
µromised, the nttncker cnnnot nutomnticnÌÌy gnin nccess to your other
Don`t write your µnsswords down. If you feeÌ you cnn`t remember n µnssword
nnd must write something down, write down n word or µhrnse thnt wiÌÌ
remind you of the µnssword.
Part III Administration
My5OL passwords
There is genernÌ confusion over whether the Unix encryµtion structure is comµnti-
bÌe with MySQL becnuse n UNIX encryµtion does Ìook somewhnt simiÌnr to n MySQL
encryµtion. Lven so, MySQL µnsswords nre stored with nn encryµtion nÌgorithm
different from thnt of the stnndnrd Unix encryµtion method. Ior this renson, you
cnnnot simµÌy trnnsfer your µnssword nnd its encryµtion key from n µnssword fiÌe
to the MySQL dntnbnse.
MySQL incÌudes n function to crente n vnÌid MySQL encryµtion: . Using
the function, n user with nccess to n MySQL CLI couÌd crente n vnÌid
encryµtion for use in MySQL. The user couÌd then tnke the encryµtion nnd trnnsfer
it to the server ndministrntor for nddition to the MySQL dntnbnse.
As stnted µreviousÌy there is some confusion over the use of cryµts within the user
tnbÌe of the MySQL grnnts dntnbnse. Pnrt of this confusion comes becnuse of the
function. The function crentes n Unix styÌe encryµtion but
it is not vnÌid in the MySQL grnnts dntnbnse. In Iigure 12-16, for exnmµÌe, I use the
function to crente n vnÌid MySQL µnssword. The resuÌting µnssword
couÌd be trnnsferred to the ndministrntor for the server nnd he or she wouÌd never
be nbÌe to see my unencryµted µnssword. I nÌso use the function ns n
reference to show the difference, given the snme µÌnintext µnssword.
Figure 12-16: The PASSWCRD( ) function creates a valid MySCL
encryption while the ENCRYPT( ) function does not.
My5OL User Management
Ior mnximum security, I recommend imµÌementing the Ìenst-µriviÌege conceµt of
µermissions. When issuing grnnts nnd µriviÌeges to users of n dntnbnse, you shouÌd
give them onÌy the µriviÌeges they need to µerform their |obs.
Chapter 12 5ecurity
You cnn crente user nccounts in MySQL by one of two methods: Using the
stntement or using the stntement. Ior the µurµoses of this chnµter I wiÌÌ be
concentrnting soÌeÌy on the stntement nnd its oµµosite stntement, .
If you choose to use nn or stntement for working with the grnnts
dntnbnse, you must use the stntement ns weÌÌ. If you use n
or stntement, the dntnbnse server sees the chnnges immedinteÌy.
If you chnnge n user`s nccess to n dntnbnse whiÌe they nre connected to thnt
dntnbnse, the chnnge wiÌÌ not tnke effect immedinteÌy for thnt user. In nddition, if
you chnnge n user`s gÌobnÌ µriviÌeges or chnnge their µnssword it wiÌÌ not tnke effect
untiÌ the next time they connect. Therefore, you shouÌd kiÌÌ the user`s µrocess in
order for the chnnges to tnke effect for these instnnces.
Two mncro-ÌeveÌ grnnts nre not Ìisted in TnbÌe 12-1: the nnd
mncros. The mncro cnn be substituted in n or
stntement instend of hnving to enumernte ench of the µriviÌeges. The mncro
simµÌy crentes the user nccount with no µriviÌeges. In other words, think of the
mncro ns n µÌncehoÌder. It nÌÌows the ndministrntor to crente the user
nccount nnd come bnck to it Ìnter to set µriviÌeges.
The macro does not include (and so does not grant) the
administrative privilege of granting and revoking privileges.
Adding users and granting priviIeges
In MySQL, ndding n user nnd grnnting µriviÌeges cnn occur simuÌtnneousÌy. You cnn
nÌso ndd muÌtiµÌe users ~with the snme µriviÌeges ~simuÌtnneousÌy. The bnsic
stntement for ndding n user nnd setting µriviÌeges is the stntement.
The syntnx for the stntement is ns foÌÌows:
To use the statement, you must have the privilege. Note
Part III Administration
In my time ns n dntnbnse ndministrntor, I`ve most frequentÌy used the mncro
to initinÌÌy crente the user nnd then gone bnck nnd grnnted individunÌ µriviÌeges for
the user nt n Ìnter time. With the mncro the user wiÌÌ be ndded to the grnnts
dntnbnse ns normnÌ exceµt no µriviÌeges wiÌÌ be given to the user. The mncro
cnn be he̵fuÌ if the nctunÌ dntnbnse hnsn`t been crented yet (or tnbÌes hnven`t been
crented within the dntnbnse).
As you cnn see by the syntnx Ìisting, the stntement ncceµts wiÌdcnrds for the
dntnbnse nnd nÌso wiÌdcnrds within the dntnbnse context to indicnte nÌÌ tnbÌes. Ior
exnmµÌe, to grnnt µriviÌeges on n sµecific tnbÌe within n dntnbnse, you cnn use
(or simµÌy if you nre in the dntnbnse nt the
time). Contrnst this with grnnting µriviÌeges on nÌÌ tnbÌes within n dntnbnse (which
you cnÌÌ with the syntnx, or simµÌy with from within the
dntnbnse). AÌso, grnnting µriviÌeges to nÌÌ dntnbnses nnd tnbÌes is µossibÌe with the
use of the wiÌdcnrd syntnx. LxnmµÌes of these grnnts nre shown in Iigure 12-17.
Figure 12-17: Examples of CRANT statements in differing scenarios
With the stntement you cnn sµecify thnt the µriviÌege wiÌÌ onÌy nµµÌy to cer-
tnin coÌumns within n given tnbÌe. You cnn nÌso sµecify more thnn one µriviÌege
within n stntement nnd nµµÌy thnt to the snme or different coÌumns within the snme
tnbÌe or structure. In nddition, you cnn give the snme µriviÌeges to
muÌtiµÌe users nt the snme time if you seµnrnte the µortions
with commns. LxnmµÌes of these grnnts nre shown in Iigure 12-18.
Chapter 12 5ecurity
Figure 12-18: Some variations of the CRANT statement as useful
syntax examples
The vnÌue for cnn contnin nny vnÌid hostnnme, IP nddress, or ÌocnÌhost. In
nddition, the wiÌdcnrds nnd nre vnÌid ns nre netmnsk vnÌues. Ior nÌÌ hosts, the
wiÌdcnrd cnn be used. When using n wiÌdcnrd or netmnsk vnÌue, the µortion
must be quoted. Ior exnmµÌe, wouÌd grnnt nccess to
usernnme from nny nddress within the 192.168.1.O}24 rnnge. This is the snme ns
. If given usernnme`/` then usernnme
nt nny host wouÌd be nÌÌowed.
You cnn require the user connect onÌy vin n secure connection such ns Secure
Sockets Lnyer (SSL) or with XbO9. This functionnÌity is nchieved by ndding the
modifier to the stntement.
If you wish for the user to hnve the nbiÌity to ndd, deÌete, nnd nÌter µriviÌeges within
the dntnbnse you must ndd the modifier to the end of the
stntement. This is true even if you use the mncro to ennbÌe nÌÌ µrivi-
Ìeges for the user. The µriviÌege is not incÌuded with the
Use care when issuing statements so as not to give too many privileges or
give them to unintended users.
As with nÌÌ dntnbnse ndministrntion, you shouÌd be cnrefuÌ when issuing GRANT
stntements. Since MySQL uses n user}host combinntion for nuthenticntion, there
cnn be muÌtiµÌe users in the dntnbnse with the snme usernnme. Lnsuring thnt you
nre grnnting nccess to the correct user or users is very imµortnnt.
Part III Administration
If you nre unsure of the grnnts thnt n given user hns, you cnn issue the
stntement. Ior exnmµÌe, to find out the grnnts nnd µriviÌeges given to
(from n µrevious exnmµÌe in this chnµter), issue the foÌÌowing stntement:
DeIeting users and revoking priviIeges
The stntement is used to remove µriviÌeges from n user. The syntnx for the
stntement is ns foÌÌows:
The syntnx is quite simiÌnr to thnt of the stntement. The stntement
cnn nµµÌy to n coÌumn or coÌumns, dntnbnses nnd tnbÌes cnn be sµecified nnd wiÌd-
cnrded nnd muÌtiµÌe users cnn be revoked simuÌtnneousÌy.
The mncro works with the stntement the snme ns with
the stntement. This is imµortnnt to know becnuse if you hnve grnnted the
µriviÌege to the user nnd use n stntement, the
oµtion wiÌÌ stiÌÌ be there! Therefore, you must µerform n seµnrnte stntement
of for this occnsion.
Issuing n stntement does not deÌete the user from the MySQL grnnts
dntnbnse. To deÌete n user from the grnnts dntnbnse you must sµecificnÌÌy issue n
stntement to remove them from the dntnbnse.
Use caution when issuing any or statements as you can easily
revoke all privileges from all users or even delete all users from the database,
including the root user!
The syntnx for the stntement is the snme to remove user nccounts ns it is to
deÌete rows from the tnbÌes of other dntnbnses. Remember thnt MySQL uses the
user nnd host combined to identify n user. Therefore you cnn hnve ns mnny users
with the usernnme in the dntnbnse, but onÌy one thnt connects from
o spccific hosi. Therefore you must be extremeÌy cnrefuÌ when issuing the
stntement so ns to not deÌete nÌÌ those other 8obs from the dntnbnse server! A mis-
guided or cnreÌess stntement cnn resuÌt in removnÌ of nÌÌ µriviÌeges for nÌÌ
users, not |ust for . After issuing the correct stntement, don`t forget
to run the stntement so the deÌetion tnkes effect on the server.
Iigure 12-19 shows nÌÌ µriviÌeges being revoked from nn exnmµÌe user, nfter which n
deÌetion removes the user nccount entireÌy from the dntnbnse.
Chapter 12 5ecurity
Figure 12-19: An example REvCKE statement, followed by an example
DELETE statement. The FLUSH PRIvILECES statement causes the delete
to take effect immediately, preventing the (now-former) user from
making a new connection.
Revoking nÌÌ µriviÌeges from n user won`t necessnriÌy truÌy remove nÌÌ of their µrivi-
Ìeges. Sµecific µriviÌeges need to be sµecificnÌÌy revoked. The
stntement cnn be quite usefuÌ in this situntion to determine whnt sµecific µriviÌeges
n user hns ~for exnmµÌe, .
Changing passwords and other parameters
Sooner or Ìnter, you wiÌÌ hnve to chnnge n user`s µnssword ns you ndminister n
dntnbnse server. You mny nÌso hnve to chnnge n usernnme or nÌter the host µnrnme-
ters for n dntnbnse user. MySQL µrovides n function sµecificnÌÌy for chnnging µnss-
words, for other chnnges, normnÌ SQL stntements nre required.
There nre two methods for chnnging n µnssword in MySQL. The first is with the
stntement, the second is the stntement. 8oth stntements mnke
use of the function to encryµt the µnssword. LxnmµÌes of both meth-
ods for chnnging n µnssword nre in Iigure 12-2O.
Use the stntement to chnnge other µnrnmeters such ns usernnmes nnd
hosts. The syntnx for the stntement is the snme in this context ns it is in
other DML stntements. In Iigure 12-21, I issue vnrious UPDATL stntements to
chnnge usernnmes nnd hosts. IoÌÌowing the , I issue the
stntement to mnke the chnnges tnke effect immedinteÌy.
Part III Administration
Figure 12-20: Using SET PASSWCRD and UPDATE to change
passwords for users in MySCL
The statement is discussed In Chapter 9 and in Appendix A.
Figure 12-21: Examples of UPDATE statements to change usernames
and hosts in the MySCL grants database
Chapter 12 5ecurity
When using the stntement, MySQL sees the chnnge immedinteÌy.
However, when using nn stntement, whether for uµdnting n µnssword or
chnnging nnother µnrnmeter, you must issue the stntement for
the chnnge to tnke effect.
Common ProbIems
Though there nre mnny µrobÌems thnt on their fnce nµµenr to be nuthenticntion
µrobÌems, they nre renÌÌy reÌnted to server or other oµernting system issues. Those
tyµes of errors nre hoµefuÌÌy covered eÌsewhere in this book. This section sµecifi-
cnÌÌy exnmines some common error messnges reÌnted to nuthenticntion. In nddition,
n recurring issue surfnces: Too often, µeoµÌe forget the µnssword for MySQL.
I`d Ìike to think thnt they forget becnuse MySQL is so stnbÌe thnt they don`t need to
connect to it for ndministrntion tnsks. RegnrdÌess, I`ÌÌ Ìook nt how to chnnge the
µnssword if you do forget it.
Access denied
There nre numerous rensons why you might receive nn error
messnge when nttemµting to µerform nn oµerntion. Ior thnt mntter, you might get
one simµÌy by trying to connect to n MySQL server. This section exnmines the most
common of these messnges, which incÌude the foÌÌowing:
Password: PersonnÌÌy sµenking, my most common cnuse of nn
error is becnuse I cnn`t tyµe my µnssword strnight. Therefore, this is
the first thing thnt comes to mind when thinking of items to check when you
receive nn Access Denied error.
Username: Is it nÌÌowed to connect"
Hostname or host: MySQL might not be nbÌe to µroµerÌy identify the
user}host combinntion, in which cnse it refuses nccess.
The MySQL CLI is very good nt remembering nnd teÌÌing you whnt wns µrovided to
it for credentinÌs. I`ve µrovided some exnmµÌes of error messnges in Iigure 12-22:
Part III Administration
Figure 12-22: various Access Denied errors
In the first exnmµÌe, I simµÌy forget to sµecify the switch to hnve MySQL
µromµt me for n µnssword.
In the second exnmµÌe, I remember the switch but onÌy µress Lnter nt
the µromµt.
The third exnmµÌe is fnmiÌinr to me (nnd to too mnny of us): n mistyµed
The finnÌ exnmµÌe is denied simµÌy becnuse the user does not hnve nny µrivi-
Ìege thnt nÌÌows connection to the dntnbnse.
The third exnmµÌe in Iigure 12-22 is interesting becnuse thnt snme error cnn occur
if the user exists but the µnssword is different for thnt user}host combinntion. Ior
exnmµÌe, if n dntnbnse hns two users cnÌÌed , one user}host combinntion
couÌd be nnd nnother couÌd be . If
the µnsswords nre different for ench user}host combinntion nnd I tyµed the wrong
µnssword for either one, the snme error wouÌd occur.
MySCL uses the user/host combination for authentication against a password.
Oops, I forgot the root password
Though you somedny mny be in n situntion thnt requires you to µerform these
steµs on your MySQL server, I sincereÌy hoµe you never hnve to. If you hnve forgot-
ten the µnssword for MySQL nnd don`t hnve nny other users with µrivi-
Ìeges on the dntnbnse server, you wiÌÌ need to reset the µnssword in order to be
nbÌe to µerform nnd µossibÌy other functions. Here nre the steµs, nnd mny
you never need them:
1. Stoµ the dntnbnse.
Chapter 12 5ecurity
º If you hnve n user nccount in the dntnbnse with the µriviÌege,
now wouÌd be the time to use thnt nccount. The first steµ in the µrocess
for emergency µnssword recovery is to stoµ the MySQL server. In n µer-
fect worÌd, you couÌd issue n commnnd to the MySQL server.
º If you don`t hnve n user with the µriviÌege, you hnve to kiÌÌ the
server with nn oµernting-system commnnd (in Linux, this is the
commnnd, in Windows, it`s the Lnd Tnsk box thnt nµµenrs nfter you use
MySCL Aß specifically recommends that you don´t use the signal when you
issue the operating system's command.
2. Restnrt the server with the commnnd-Ìine switch.
3. Set the µnssword, using one of the foÌÌowing methods:
º Set the µnssword ns you wouÌd for n new instnÌÌntion:
The new password must be in single quotes. Substitute your host for
and the new password for .
º AÌternntiveÌy, you cnn enter the MySQL CLI nnd chnnge the µnssword.
4. Issue the stntement so thnt MySQL rends the other grnnts
nnd µriviÌeges nnd the new µnssword tnkes effect.
MySQL security is n toµic of mnny fncets, but with three mnin nrens of concern: the
host server, the MySQL softwnre, nnd the user nccounts. No one fncet is more
imµortnnt thnn nnother, securing nÌÌ is necessnry to µrotect the dntnbnse. In µur-
suit of thnt gonÌ, the Ìenst-µriviÌege system is n security nµµronch thnt gives users
onÌy the nbsoÌute minimum of nccess needed to µerform their |obs.
ImµÌementing nnd µreserving the security of the host server invoÌves three
bnsic ruÌes:
º Mnintnin n µronctive nµµronch to keeµing uµ with exµÌoits nnd µrobÌems
with softwnre you nre running.
º AµµÌy µntches nnd fixes ns soon ns they nre reÌensed.
º DisnbÌe unused services nnd verify thnt onÌy the services you sµecify nre
Part III Administration
With MySQL softwnre security there nre n number of items you cnn do to
imµrove security. These incÌude keeµing the softwnre uµdnted, firewnÌÌing the
server, running the server ns n non-µriviÌeged user, nnd ndditionnÌ steµs to
nssist in security of the MySQL softwnre.
MySQL nuthenticntion nnd µriviÌeges determine whnt nccess n user wiÌÌ hnve
for n dntnbnse. Authenticntion is done with n user}host combinntion.
There nre mnny µriviÌeges thnt cnn be grnnted to n user. The µriviÌeges cnn be
grnnted with grnnuÌnrity to the coÌumn ÌeveÌ with n tnbÌe.
PriviÌeges nre normnÌÌy given to n user through the use of the stntement
nnd tnken nwny from n user with n stntement. The stntement
is necessnry to remove n user comµÌeteÌy from the dntnbnse.
It is common to receive error messnges when nttemµting to
connect to n dntnbnse. These errors cnn occur for n number of rensons, some
ns simµÌe ns tyµing the µnssword incorrectÌy.
and kepairing
n n µerfect worÌd, comµuters nnd comµuter softwnre
wouÌd work correctÌy the first time. In n µerfect worÌd,
hnrd disks wouÌd never fniÌ. In n µerfect worÌd, I wouÌd hnve n
much better introduction for this chnµter thnn n cÌiche nbout
comµuter fniÌures.
Pnrt of ndministrntion of nny comµuter system is n good rou-
tine of bnckuµs. In this chnµter I`ÌÌ Ìook nt methods for bnck-
ing uµ the dntn in the MySQL server. MySQL A8 incÌudes
severnÌ methods for µroducing bnckuµs of the dntn nnd
Hnving bnckuµs is |ust one of the fncets of mnnnging n
dntnbnse server. If something goes nwry with the dntn, know
whnt cnn be done to correct the µrobÌems. I`ÌÌ exnmine some
tooÌs incÌuded with MySQL for troubÌeshooting nnd reµniring
tnbÌe µrobÌems.
If reµniring cnn`t fix n µrobÌem, you`ÌÌ need to restore from
n bnckuµ. The restore µrocess nnd reÌnted commnnds nre
covered in this chnµter ns weÌÌ.
After rending this chnµter you shouÌd be nbÌe to successfuÌÌy
µerform bnckuµs, restores, nnd troubÌeshooting for tnbÌe
µrobÌems. I recommend mnking n bnckuµ or two ns soon
ns µossibÌe.
C H A P I E k
ln Ihis Chopler
Perlormlng dolobose
lroubleshoollng ond
repolrlng dolobose
Reslorlng o dolobose
Devlslng o plon lor
regulor bockups
Part III Administration
Performing Database ßackups
As µnrt of my consuÌting for business dntnbnse systems, I once received nn emer-
gency cnÌÌ from n new cÌient who hnd the unfortunnte incident thnt everyone fenrs:
A hnrd drive fniÌure. The cÌient nnd I tried desµernteÌy to recover the drive, even
working with the mnnufncturer. It becnme evident thnt no nmount of effort to
recover the drive wns going to bring it bnck to Ìife. The obvious next steµ to get
their business bnck onÌine wns to restore from bnckuµ. I`ÌÌ never forget the µnuse
when I snid, ¨It nµµenrs we`ÌÌ need to restore from bnckuµ." The cÌient hnd no
bnckuµ of the drive ~thus no bnckuµ of the dntnbnse.
The µrevious scennrio is nÌÌ too common. No bnckuµs nre done to criticnÌ dntn nnd
no extrn coµies nre stored, even on the snme disk. When something cntnstroµhic
hnµµens, the hnrd drive nnd nÌÌ the dntn on it cnn be Ìost. With the cÌient, we even-
tunÌÌy sent the hnrd drive bnck to the mnnufncturer nnd they were nbÌe to µerform
exµensive dntn recovery. The cÌient ended uµ with n week`s worth of downtime nnd
n Ìnrge biÌÌ from the hnrd drive mnnufncturer for dntn recovery.
This section exnmines some tooÌs for mnking bnckuµs of the dntn within MySQL.
These tooÌs incÌude , , nnd the stntement.
The µrogrnm is the MySQL A8 recommended method for bncking uµ
n dntnbnse. With you cnn mnke n bnckuµ of n Ìive dntnbnse nnd hnve
the resuÌts coµied to nnother directory. The µrogrnm is nctunÌÌy
written in PerÌ ~so be sure to hnve PerÌ nnd its reÌnted MySQL-PerÌ Ìibrnries
As with nÌÌ µrogrnms, hns its Ìimitntions:
lt presently supports only . Therefore doesn`t coµy the
resuÌting fiÌe to nnother server. However, this function cnn be ndded (nÌong
with other methods) for ensuring the stornge of the bnckuµ in n different
lt can run only on the actual database server. An ndministrntor must connect
to the dntnbnse server to run the commnnd, or scheduÌe it with n scheduÌing
µrogrnm such ns .
ßecause uses the command, it cannot run on Microsoft
Windows platforms such as Windows 2000.
ShouÌd you wnnt more informntion on the commnnd (nnd you don`t
hnve this book nvniÌnbÌe), you cnn run the foÌÌowing commnnd:
Chapter 13 Debugging and kepairing Databases
The resuÌt is n summnry of the commnnd. As with mnny other
MySQL commnnds nnd scriµts, you cnn obtnin n syntnx descriµtion by simµÌy
tyµing the commnnd, ns shown in Iigure 18-1.
Figure 13-1: The syntax of the mysqlhotcopy command can be
obtained by typing the command with no arguments.
As Iigure 18-1 shows, the bnsic syntnx for the commnnd is
Iigure 18-1 nÌso shows these other oµtions nnd switches thnt you cnn use with the
commnnd (note the cnse sensitivity):
Chapter 8 contains detailed discussion of switches (such as those for specifying
username, port, and socket) to use with the command.
Part III Administration
One notnbÌe exceµtion in the behnvior of the switches is the or
switch. NormnÌÌy, µrogrnms such ns the MySQL CLI nnd µromµt for n
µnssword when you use the switch (ns shown in Iigure 18-2). You couÌd nÌso
sµecify the µnssword on the nctunÌ commnnd Ìine, nÌso iÌÌustrnted in Iigure 18-2.
Figure 13-2: The variations of the types of password entry methods
for most MySCL commands
UnÌike most µrogrnms thnt come with MySQL, doesn`t µromµt for n
µnssword. Rnther, the µnssword must be sµecified on the commnnd Ìine. In nddition,
if you use the -µ switch exµects n sµnce nfter the . Iigure 18-8
shows nn exnmµÌe of this behnvior. If the sµnce isn`t given nfter the switch, nn
error messnge resuÌts.
Figure 13-3: Attempting to give the password without a space after
the -p switch results in an error.
Chapter 13 Debugging and kepairing Databases
At its most bnsic ÌeveÌ, the scriµt µerforms the foÌÌowing three steµs:
1. Locks the tnbÌe or tnbÌes sµecified.
2. IÌushes the tnbÌes to cÌose nny oµen tnbÌes.
3. Performs the nctunÌ coµying of the dntn fiÌes.
8ecnuse µerforms n Ìock tnbÌes ns the first steµ, no other
cÌients cnn use the tnbÌes whiÌe runs.
The Ìocking cnn tnke quite some time on Ìnrge tnbÌes.
The fÌushing of the tnbÌes wiÌÌ cnuse nÌÌ oµen tnbÌes to cÌose.
The nctunÌ coµy cnn be time-consuming if the tnbÌes nre Ìnrge ns weÌÌ.
The scriµt mnkes nn nctunÌ eÌectronic coµy of the dntnfiÌes for the
dntnbnse. Therefore nny user nccount thnt runs must hnve sufficient
µriviÌeges to rend the directory in which the dntnfiÌes reside. Ior exnmµÌe, Iigure 18-4
shows nn nttemµt to run ns n normnÌ user in Linux. NormnÌ users
don`t hnve the requisite µriviÌeges on the dntnbnse directory, the commnnd fniÌs.
Figure 13-4: mysqlhotcopy requires that the user running the script
have sufficient privileges to read the database directory.
A simµÌe summnry (n common usnge of the µrogrnm) is shown in
Iigure 18-b. In the figure, the MySQL dntnbnse is coµied or bncked
uµ to n new dntnbnse cnÌÌed .
Figure 13-5: A common usage of the mysqlhotcopy program to make
a copy of the MySCL grants database
Part III Administration
nÌso coµies nny other fiÌes within the directory housing the
dntnbnse ns weÌÌ. Ior exnmµÌe, if you hnve fiÌes such ns those µroduced with
µerforming n of the dntnbnse coµies those to the new
Ìocntion. Iigure 18-6 shows nn exnmµÌe of this behnvior. A Ìisting of the
dntnbnse directory is done, then n to mnke n bnckuµ of the dntnbnse
into , foÌÌowed by n Ìisting of the new directory.
Figure 13-6: The mysqlhotcopy script copies all files located in the
database's directory on the server.
RecnÌÌ the bnsic syntnx for the µrogrnm:
You hnve two µossibÌe destinntions for the bnckuµ:
A new dntnbnse
A directory in n different Ìocntion
The exnmµÌes in Iigures 18-b nnd 18-6 ench mnde new dntnbnses. However, nttemµt-
ing to use either dntnbnse cnn resuÌt in nn error messnge, ns shown in Iigure 18-7.
Chapter 13 Debugging and kepairing Databases
Figure 13-7: The MySCL server does not have sufficient privileges to
read the database of a recently backed up database with mysqlhotcopy.
The error in Iigure 18-7 occurs becnuse the scriµt wns run ns the
or suµeruser. Therefore the new dntnbnse directory wns crented by nnd is
owned by . 8ecnuse the dntnbnse server fiÌes nre owned by the usernnme
~nnd the server runs ns thnt user ~it cnnnot rend the contents of the new
dntnbnse directory. You cnn fix this with n commnnd such ns . Ior exnmµÌe,
Iigure 18-8 shows the directory ownershiµ nnd µermissions before nnd nfter the
commnnd in Linux. Iigure 18-8 nÌso shows n successfuÌ connection to the
bnckuµ coµy crented by .
Figure 13-8: Changing ownership of the new database created by
The other method for bncking uµ n dntnbnse is to nnother directory. Ior ndded µre-
cnution, the directory couÌd be on n seµnrnte µhysicnÌ disk. Instend of µroviding n
dntnbnse nnme for to bnck uµ to, you sµecify n directory nnme. You
must mnke sure thnt the directory exists. Iigure 18-9 shows nn exnmµÌe of using
to mnke n bnckuµ of n dntnbnse to n directory. In the first nttemµt,
the directory does not exist. The second nttemµt is successfuÌ. A directory Ìisting is
µrovided for convenience.
Part III Administration
Figure 13-9: Using mysqlhotcopy to make a backup of a MySCL
database to a directory
isn`t Ìimited to simµÌy mnking bnckuµs of the entire dntnbnse ~or
even to one dntnbnse. I`ÌÌ Ìook nt how to bnck uµ more thnn one dntnbnse within
this section ns weÌÌ. Ior now, I`m going to exnmine how to mnke n bnckuµ of onÌy
certnin tnbÌes within n dntnbnse.
Agnin, recnÌÌing the syntnx of the µrogrnm, you cnn sµecify tnbÌes
within the formnt of n reguÌnr exµression. In effect, you sµecify the tnbÌes thnt
mntch n certnin poiicrn thnt you wnnt to bnck uµ. Ior exnmµÌe, to bnck uµ nÌÌ tnbÌes
in the dntnbnse thnt contnin the word proJuci, the commnnd in Iigure
18-1O is issued.
Figure 13-10: ßacking up only certain tables with the
mysqlhotcopy command
Chapter 13 Debugging and kepairing Databases
At first, you might not think this method convenient or µowerfuÌ enough for bnck-
ing uµ tnbÌes (more thnn one tnbÌe cnnnot be sµecified). However, by using the reg-
uÌnr exµression chnrncter for ÌogicnÌ , you cnn bnck uµ more thnn one tnbÌe
nnme with . In Iigure 18-11, I re-run the commnnd from Iigure 18-1O
nnd ndd the ÌogicnÌ (or the µiµe chnrncter) to the commnnd becnuse I wnnt to
bnck uµ the tnbÌes thnt contnin the word . Notice thnt the µiµe chnrncter must
be nÌÌowed to ¨escnµe" by using n bncksÌnsh.
Figure 13-11: Using the regular expression syntax for a logical CR
you can back up more than one table with mysqlhotcopy.
Uµ to this µoint I`ve onÌy been Ìooking nt the bnsic syntnx of .
incÌudes n number of switches thnt directÌy nffect the oµerntion of
the µrogrnm. These switches cnn chnnge which dntnbnses nre coµied, how they nre
coµied, nnd nny extrn functions thnt shouÌd µerform.
When mnkes n bnckuµ coµy of n dntnbnse the µrocess fniÌs if there
is nÌrendy n dntnbnse of the snme nnme. This hns the obvious ndvnntnge of µrevent-
ing nn nccidentnÌ overwrite of n vitnÌ dntnbnse. Iigure 18-12 shows nn exnmµÌe of
the error messnge when the destinntion dntnbnse nÌrendy exists.
indicates an error if the destination exists regardless of whether
the destination is a database or a directory.
Figure 13-12: If the destination exists, whether it is a database or
directory, the mysqlhotcopy script fails and generates the error
message shown.
Part III Administration
To nÌÌow to overwrite the destinntion dntnbnse or directory, you use
the switch. The switch chnnges the existing destinntion
nnd nµµends to the nnme of the existing destinntion. When the coµy is
successfuÌÌy comµÌeted, the oÌd directory nnd fiÌes therein nre deÌeted. Iigure 18-18
shows nn exnmµÌe of this behnvior.
Figure 13-13: The --allowold switch moves the existing destination
and appends the extension _old to the name. After the copy is
complete, the old directory is deleted.
AÌthough the switch ennbÌes you to µerform n bnckuµ even if the stnted
destinntion nÌrendy exists, deÌetes the oÌd coµy ns its finnÌ steµ in the
bnckuµ µrocess. If you wnnt to keeµ the oÌd coµy nfter the commnnd is comµÌete,
use the switch. Iigure 18-14 shows with the
switch ndded ns weÌÌ ns n Ìisting of the MySQL dntn directory nfter the
commnnd runs to keeµ the oÌd coµy of the dntn using the switch.
Figure 13-14: Adding the --keepold switch tells mysqlhotcopy to keep the
old destination after performing a copy where the destination already exists.
Chapter 13 Debugging and kepairing Databases
To coµy more thnn one dntnbnse nt n time, you cnn use the switch to cre-
nte n reguÌnr exµression of mntching dntnbnses. This switch uses n syntnx simiÌnr to
the one thnt teÌÌs which tnbÌes to coµy. Iigure 18-1b shows nn exnm-
µÌe of the switch in nction.
The option does not run well currently; it may be fixed in a future
version of .
Figure 13-15: The --regexp switch serves to copy more than one
database at a time but is currently quite buggy.
You cnn nÌso sµecify n suffix for coµied dntnbnses with the switch. Doing
so cnn he̵ to keeµ n stnndnrd suffix for nÌÌ bncked-uµ dntnbnses. In Iigure 18-16,
for exnmµÌe, I use the switch to crente n bnckuµ with nn extension
of .
Figure 13-16: Using the --suffix switch to create a backup with a
special extension
To see nn exnmµÌe of whnt wouÌd do given n set of nrguments, use the
or switch. The or switch µrovides n Ìisting of whnt wouÌd
hnµµen without nctunÌÌy µerforming the oµerntion. An exnmµÌe of the
switch is shown in Iigure 18-17.
Part III Administration
Figure 13-17: Using the --dryrun or -n switch you can see what would
happen with mysqlhotcopy without actually performing the backup.
Other oµtions for incÌude the foÌÌowing:
Dµtion 0escriµtion
Excludes any index files from the backup.
Performs the same functions as the function with
to reset any logging. Related to replication,
Restarts the replication process.
Restarts the replication process.
Changes the location of the temporary directory used by
(which is by default).
Lnter this chnµter µrovides nn exnmµÌe of n scriµt thnt nutomntes the µrocess of
mnking bnckuµs with .
The script for automating backups with is also located on the CD
RCM included with this book.
With , you cnn obtnin n coµy of the dntnbnse structure, ns weÌÌ ns the
nctunÌ dntn for nÌÌ dntnbnses on the server. The commnnd is fÌexibÌe
enough thnt you cnn sµecify structurnÌ units ns smnÌÌ ns tnbÌes nnd exµort them.
Tnking the outµut from nnd imµorting it bnck into MySQL, you cnn
quickÌy reµroduce nn entire dntnbnse server, nÌong with nÌÌ its dntn.
üo the
Chapter 13 Debugging and kepairing Databases
For further details of the program, see Chapter 10.
Ior exnmµÌe, in Iigure 18-18 the commnnd runs to crente n bnckuµ of nÌÌ
dntnbnses on the server nnd µÌnce the contents in n fiÌe cnÌÌed .
The contents of the fiÌe incÌude the DDL to crente the dntnbnses nnd internnÌ struc-
ture for the dntnbnses. The fiÌe nÌso incÌudes the DML nnd dntn contnined in the
Figure 13-18: Using mysqldump to export the entire contents of a
database server including DDL and DML
The fiÌe crented by couÌd then be snved or nrchived to n remote Ìocn-
tion or tnµe drive. 8ecnuse cnn be run from n remote mnchine, the fiÌe
wouÌd nutomnticnÌÌy be n redundnnt bnckuµ in cnse of hnrdwnre fniÌure on the
MySQL server. If the hnrd drive fniÌs on the MySQL server, the fiÌe µroduced by
on the remote mnchine wouÌd stiÌÌ be intnct.
The fiÌe µroduced by cnn then be imµorted into n new MySQL server by
simµÌy rending it in through the CLI. Iigure 18-19 shows nn exnmµÌe of rending the
outµut of n into the CLI. No outµut or success messnge µrints to the
screen uµon comµÌetion.
Figure 13-19: Importing the output of a mysqldump file is as easy as
reading it into the CLI.
Part III Administration
Another method for bncking uµ nn individunÌ tnbÌe is vin the stnte-
ment. This stntement runs from within (or using) the MySQL CLI. The syntnx is ns
The stntement exµects n µnth nnd directory ns the nrgument for
bnckuµ Ìocntion. The stntement currentÌy onÌy works with tnbÌes ns weÌÌ. The
stntement mnkes n coµy of the nnd fiÌes for the given tnbÌe.
If you`re bncking uµ more thnn one tnbÌe nt n time, you shouÌd issue n LOCK TA8LLS
stntement before the stntement to ensure consistency nmongst the
tnbÌes. Don`t forget to issue n stntement uµon comµÌetion.
Uµon comµÌetion, the stntement µrints n stntus messnge. If nn error
occurs, its messnge is nÌso µrinted ns µnrt of the outµut. Ior exnm-
µÌe, if the tnrget directory does not exist, you receive n messnge simiÌnr to thnt in
Iigure 18-2O.
Figure 13-20: The ßACKUP TAßLE statement produces a status
message upon completion, as well as an error message if needed.
In Iigure 18-21, n successfuÌ exnmµÌe of the stntement is shown ~
nÌong with the resuÌting stntus messnge.
Chapter 13 Debugging and kepairing Databases
Figure 13-21: A successful run of the ßACKUP TAßLE statement
IroubIeshooting and kepairing
IabIe ProbIems
I once hnd n cÌient who, instend of Ìogging in to n mnchine nnd tyµing rcbooi, wouÌd
simµÌy turn the mnchine off nnd then bnck on. He couÌdn`t figure out why the fiÌes
on the system were corruµt nnd some tnbÌes in the dntnbnse wouÌd often give
errors nnd need reµnir. He bÌnmed the corruµtion nnd errors on |ust nbout every-
thing eÌse, nnd didn`t even think thnt turning the mnchine off uiihoui shuiiinµ Joun
ihc opplicoiions couÌd nffect the integrity of nnything on the comµuter. MySQL is n
stnbÌe nnd robust dntnbnse server, but even MySQL wouÌd hnve n hnrd time mnin-
tnining dntn integrity in such n situntion.
AÌthough I cnn`t sny thnt tnbÌe corruµtion never resuÌts from nn error in the
dntnbnse itseÌf, normnÌÌy the server mnintnins the integrity of its dntn nt nÌÌ times.
Instnnces of tnbÌe errors nnd corruµtion usunÌÌy µoint to n dirty shutdown of
MySQL or the server, n hnrdwnre fniÌure, or some other cntnstroµhe not directÌy
reÌnted to the MySQL server.
When n fniÌure does occur, mnke sure you hnve bnckuµs of both the dntn onJ the
tnbÌe structure thnt keeµs your dntn orgnnized. Hnving current nnd qunÌity bnckuµs
is the first Ìine of defense in ndministrntion of the MySQL server. Aside from cntns-
troµhe, tnbÌes cnn sometimes suffer from frngmentntion. This cnn occur becnuse of
deÌetes nnd uµdntes to n tnbÌe. Knowing how to oµtimize tnbÌes is nnother nsµect of
ndministrntion of n MySQL server.
This section exnmines the commnnds nnd stntements you use for troubÌeshooting
nnd reµniring tnbÌes in MySQL. Most of the section concentrntes on the
tnbÌe tyµe (the defnuÌt in MySQL), nÌthough some tooÌs cnn be used with the
(8D8) trnnsnctionnÌ tnbÌe tyµe.
Part III Administration
is n reÌntiveÌy new commnnd for working with tnbÌes.
The program requires you to stop the server before running checks or
repairs. However, the command allows the server to be running
while performing the checks and repairs.
If a client is working with the table at the same time that attempts
the requested operation, the operation fails.
The commnnd serves ns the bnsis for most other troubÌeshooting
functions with MySQL.
Like other commands with MySCL, has many command-line
switches and options the same. Refer to Chapter 8 on the MySCL CLI for full expla-
nation of the common options, such as or ,
, , , or , or ,
or , or -- , or , or , and or
As with many other commands with MySCL, you can obtain a syntax reference
simply by typing the command, as shown in Figure 13-22.
Figure 13-22: Typing mysqlcheck with no options yields a syntax and
options reference for the command.
Chapter 13 Debugging and kepairing Databases
The bnsic syntnx for the commnnd is ns foÌÌows:
When cnÌÌed with no oµtions, exnmines the tnbÌes within the given
dntnbnse for errors. If no errors nre found, n stntus messnge of is µrinted for
ench tnbÌe, ns shown in Iigure 18-28.
Figure 13-23: Mysqlcheck prints an CK status message for each table
free from errors during the default check operation.
MysqÌcheck nÌso incÌudes n function to nnnÌyze the key distribution for n tnbÌe. This
function is cnÌÌed with the or switch on the commnnd Ìine. The out-
µut when using this function is the snme ns with the defnuÌt use of mysqÌcheck
when cnÌÌed with no oµtions, the commnnd outµuts nn stntus messnge. If the
tnbÌe does not need further nnnÌysis the stntus messnge is
. Ior exnmµÌe, if no chnnges hnve tnken µÌnce, recognizes this
fnct nnd does not µerform ndditionnÌ nnnÌysis, ns shown in Iigure 18-24.
Figure 13-24: Mysqlcheck -a outputs a different status message if the
table does not need analysis.
If you µerform n Ìnrge number of deÌetes or other chnnges to n tnbÌe, you cnn
imµrove µerformnnce by using the or switch with mysqÌcheck.
Oµtimizing the tnbÌe wiÌÌ defrngment the tnbÌe. Like the µrocess for nnnÌyzing n
tnbÌe, the oµtimizntion µrocess wiÌÌ µrovide n stntus messnge for tnbÌes within the
Part III Administration
The finnÌ mnin function with mysqÌcheck is to reµnir the tnbÌe. This function is
cnÌÌed with the or oµtion. The reµnir function cnn fix most nny µrob-
Ìem with n tnbÌe. However, the reµnir function cnn sometimes Ìose dntn, therefore
I`ÌÌ stress ngnin to mnke sure you hnve bnckuµs. If reµorts nn error nnd
you`re going to reµnir it, it is nÌwnys n good iden to check the integrity of your bnck-
uµs before µroceeding. Iigure 18-2b shows nn exnmµÌe of reµniring n
tnbÌe. (Note thnt I µurµoseÌy corruµted the tnbÌe for this exnmµÌe.)
Figure 13-25: Using mysqlcheck to repair a corrupt table
When you use the mnin (defnuÌt) oµtion to check dntnbnses nnd tnbÌes with which
, you hnve severnÌ ÌeveÌs or degrees nt which to exnmine the tnbÌe(s)
for errors:
Commond Function
or The default option; checks all tables.
or Checks only tables that have changed since the last
or Looks for and examines tables that weren't closed
or Does not check row-level objects.
If you wnnt for to nutomnticnÌÌy reµnir nny errors it finds, ndd the
switch. Iigure 18-26 shows nn exnmµÌe of using the nir
switch with to reµnir n broken tnbÌe.
Chapter 13 Debugging and kepairing Databases
Figure 13-26: Use the --auto-repair switch to automatically repair a
table when a problem is found.
Two functions defined with exnmine nÌÌ dntnbnses or more thnn one
sµecified dntnbnse.
Commond Function
Runs the specified operation on all databases within the MySCL
or Checks more than one, but not all, databases; used with the
names of the databases separated by whitespace. Figure 13-27
shows an example of the switch in use,
examining three databases on the server.
Figure 13-27: The --databases switch examines one or more databases
with mysqlcheck.
Part III Administration
If you wnnt to onÌy exnmine certnin tnbÌes within n dntnbnse, use the
switch. 8ecnuse deÌete oµerntions cnn cnuse frngmentntion, you cnn sµeed uµ your
exnminntion by ndding n cÌnuse so the com-
mnnd exnmines onÌy the sµecified tnbÌe(s). To sµecify more thnn one tnbÌe, seµn-
rnte the tnbÌennmes with whitesµnce. Iigure 18-28 shows nn exnmµÌe of
exnmining certnin tnbÌes with the switch.
The --tables switch cannot be used with the --databases or -ß switch.
Figure 13-28: The --tables switch causes mysqlcheck to examine
only the specified table or tables.
To chnnge the µerformnnce of the or switch cnn be
used. This switch cnuses to use n singÌe query for nÌÌ oµerntions within
n given dntnbnse. This is ns oµµosed to the normnÌ behnvior of one query µer tnbÌe.
The or oµtion cnuses to continue its oµerntion even if nn
error is encountered. Using this oµtion cnn sometimes cnuse corruµtion or other
The utiÌity serves to check nnd reµnir tnbÌes whiÌe the MySQL
server is offÌine. Much of the syntnx nnd mnny of the switches for nre
the snme ns those for .
The switches thnt shnres in common with other MySQL utiÌities
incÌude those for obtnining he̵ nnd setting defnuÌt chnrncter sets. As with the
other utiÌities, I`ÌÌ forego covernge of the foÌÌowing bnsic switches in this section:
or --debug
Chapter 13 Debugging and kepairing Databases
The bnsic syntnx for is ns foÌÌows:
hns gÌobnÌ oµtions nside from those µreviousÌy described. The
switch informs to µnuse if the tnbÌe is nÌrendy Ìocked. Using the
switch cnuses to be quieter ns it goes nbout its business. MuÌtiµÌe
switches cnn mnke the commnnd even more siÌent. The switch cnuses
to µrint more informntion ns it works. As with the switch, you cnn
use more thnn one switch to incrense the verbosity of .
hns two bnsic modes of oµerntion: Check nnd Reµnir. The defnuÌt nction
for is to check the tnbÌes sµecified. Iigure 18-29 shows n bnsic usnge of
Figure 13-29: An example of basic usage of myisamchk
Options for checking tabIes with myisamchk
The oµtions reÌnting to checking tnbÌes with nre ns foÌÌows:
e or
Part III Administration
The switch (which instructs the utiÌity to check) is the defnuÌt with .
The , , , , nnd
oµtions were discussed in the µreceding section on .
The switch µrints more informntion on the tnbÌe(s) exnmined.
Iigure 18-8O shows nn exnmµÌe of the commnnd run with the switch.
Comµnre the resuÌts to Iigure 18-29 to see the extrn informntion µrinted.
Figure 13-30: Using the -i or --information switch tells myisamchk to
print more information about the table or tables that it examines.
The or switch teÌÌs not to uµdnte the
tnbÌe vnrinbÌe. (Informntion nbout tnbÌes cnn be obtnined with the
stntement using the CLI.) NormnÌÌy, when oµerntes on n tnbÌe,
it uµdntes the vnrinbÌe. LxnmµÌes of the or switch
nµµenr in Iigures 18-81 through 18-88.
Iigure 18-81, the stntement disµÌnys n tnbÌe thnt hnsn`t been
checked recentÌy. Iigure 18-82 shows n run of the commnnd with the
switch. (Notice thnt the commnnd oµerntes the snme ns it wouÌd without the
switch.) Iigure 18-88 shows the commnnd run ngnin, notice
thnt stiÌÌ hnsn`t chnnged.
Chapter 13 Debugging and kepairing Databases
Figure 13-31: The SHCW TAßLE STATUS statement shows that the
table hasn't been checked recently.
Figure 13-32: Performing a myisamchk with the -T switch that causes
the Check_time to not be updated.
Figure 13-33: Looking at the output from SHCW TAßLE STATUS again,
the value for Check_time has indeed remained the same even though
I checked the table with myisamchk.
Part III Administration
If you susµect n tnbÌe contnins errors or corruµtion nnd wnnt to µrevent further use
of the tnbÌe, the or switch with mnrks nny tnbÌe
where nn error is found ns n croshcJ ioblc ~which effectiveÌy µrevents nny further
use of the tnbÌe, even with n stntement, untiÌ the tnbÌe is reµnired. CÌients
nttemµting to work with the tnbÌe receive nn error messnge. Iigure 18-84 shows nn
exnmµÌe of n simµÌe stntement µerformed on n tnbÌe, using the MySQL CLI.
Figure 13-34: A simple SELECT statement, performed through the
CLI on a table that I suspect to be corrupt
AÌthough there`s no wny to teÌÌ from the stntement, I susµect thnt this
tnbÌe might be corruµt. Therefore I µerform n on the tnbÌe nnd use
the switch, ns shown in Iigure 18-8b.
Figure 13-35: Running myisamchk with the -U switch to mark the
table as crashed and prevent further use
Iigure 18-86 shows whnt hnµµens when I nttemµt to run the µreviousÌy successfuÌ
stntement on the tnbÌe ngnin. The stntement fniÌs becnuse the tnbÌe
is mnrked ns crnshed~which (even if it seems inconvenient nt the moment) nctu-
nÌÌy he̵s by µreventing further corruµtion or invnÌid resuÌts.
Chapter 13 Debugging and kepairing Databases
Figure 13-36: The same SELECT statement that was previously
successful now fails because the table is marked as crashed.
Options for repairing tabIes with myisamchk
8ecnuse checking is the defnuÌt oµtion with , you cnn onÌy use the reµnir
or recover function by sµecifying the or switch on the
commnnd Ìine.
If the normal switch fails, the options that repair or recover tables with
can also be used with the or switch
The reµnir or recover switches nre ns foÌÌows:
A bnsic reµnir or recovery with cnn be run with the foÌÌowing commnnd
Part III Administration
Iigure 18-87 shows the resuÌts of this commnnd.
Figure 13-37: A basic quick repair with myisamchk
does not necessnriÌy use memory efficientÌy for reµnirs. Therefore you
shouÌd set vnrinbÌes on the myisnmchk commnnd Ìine using the or
switch. Doing so wiÌÌ mnke the reµnir µrocess fnster. IdenÌÌy, the key_buffer
nnd sort_buffer vnÌues wouÌd be nbout n qunrter of the totnÌ system memory to
mnximize efficiency of the myisnmchk reµnir.
The foÌÌowing vnrinbÌes nffect the µerformnnce of :
To determine the current setting for the vnrinbÌes, simµÌy tyµe the com-
mnnd with no nrguments (ns shown in Iigure 18-88).
You can type the command shown in Figure 13-38 safely while the server runs.
As stnted µreviousÌy, the vnrinbÌes cnn be set on the commnnd Ìine using the or
switch (ns shown in Iigure 18-89). The vnrinbÌes cnn nÌso be set
inside the configurntion fiÌe such ns in Linux. To set the vnrinbÌes in the
configurntion fiÌe, µÌnce them undernenth the section.
Chapter 13 Debugging and kepairing Databases
Figure 13-38: Determining the current values for myisamchk variables
is done by simply typing the myisamchk command without switches
or arguments.
Figure 13-39: Setting variables on the myisamchk command line by
using the -C switch.
Part III Administration
One of the more imµortnnt oµtions to use when reµniring n tnbÌe is the or
switch. Using the switch wiÌÌ cnuse to mnke n bnckuµ
coµy of the dntn fiÌe before you nttemµt to reµnir or oµtimize it. Doing so cnn be
extremeÌy he̵fuÌ if you wnnt to snfegunrd the tnbÌe contents where n reµnir or oµti-
mize function might cnuse n µrobÌem.
If you hnve n µrobÌem with n tnbÌe thnt the normnÌ reµnir µrocess cnnnot fix, you
mny wnnt to nttemµt the or oµtion. This switch tries to
recover every row from n tnbÌe. If you`d Ìike to get n fnster reµnir, the or
oµtion µerforms the recovery without modifying the dntn fiÌe. The
use of two switches on the commnnd Ìine fixes duµÌicnte index vnÌues.
Three fiÌe-system oµtions thnt nffect the µerformnnce of nre
Commond Function
or Changes the location that uses for the temporary
or Tells not to follow symbolic links in the file system
when examining tables.
or Causes to unarchive a file packed with .
The 8LL stntement runs through (or using) the MySQL CLI. It is the
equivnÌent of running with the switch.
For more information on optimizing tables, see the section on in this
The stntement runs through (or using) the MySQL CLI. It is the
equivnÌent of running with the switch. Oµtimizing n tnbÌe
is usefuÌ if you hnve chnnged vnrinbÌe Ìength rows or deÌeted mnny rows from n
tnbÌe. It reduces frngmentntion within the tnbÌes thnt it checks. The syntnx for the
stntement is ns foÌÌows:
For more information on optimizing tables, see the section on in this
Chapter 13 Debugging and kepairing Databases
The CHLCK TA8LL stntement runs through (or using) the MySQL CLI. It is the equiv-
nÌent of running with the switch or with no nrguments nt nÌÌ,
ns it is the defnuÌt for .
For more information on optimizing tables, see the section on in this
The stntement runs through (or using) the MySQL CLI. It is the
equivnÌent of running with the switch.
For more information on optimizing tables, see the section on in this
kestoring a My5OL Database
Restoring n dntnbnse cnn be n stressfuÌ µrocess ~the dntnbnse or server mny hnve
crnshed, cnusing µrobÌems thnt need to be corrected, the reµnir µrocess mny not
hnve worked on n corruµt tnbÌe, n user mny hnve inndvertentÌy deÌeted nÌÌ the dntn.
Whntever the renson, n good bnckuµ cnn snve the dny. A µrevious section in this
chnµter discussed the µrocess of crenting the bnckuµs. This section Ìooks nt how to
restore them.
There is no universnÌÌy right or wrong wny to restore from n bnckuµ, but there is n
universnÌÌy µrncticnÌ µrinciµÌe to use: Hou you rcsiorc from o bochup is JcicrmincJ
by hou ihc bochup uos crcoicJ. Consider these exnmµÌes:
If you used to mnke the bnckuµ, you cnn use to
restore the dntnbnse ~or simµÌy coµy the dntnbnse directory to the µroµer
Ìocntion nnd recrente the µriviÌeges for the individunÌ nccounts.
If you crented the bnckuµ by using the stntement, the
stntement wouÌd be the nnturnÌ comµÌement.
If you crented the bnckuµ by using the utiÌity, then you cnn restore
using the MySQL CLI.
Part III Administration
The µrogrnm is for mnking bnckuµs of entire dntnbnse directories.
However, you cnn nÌso use to restore from n µreviousÌy bncked-uµ
coµy of n dntnbnse directory. Ior exnmµÌe, suµµose you`ve used to
crente n bnckuµ of the dntnbnse cnÌÌed . If something
hnµµens to the dntnbnse nnd you hnve to restore it, the
µrogrnm cnn do so.
The foÌÌowing commnnd wouÌd restore the dntnbnse to the
directory nnd mnke n bnckuµ of the broken dntnbnse nt
the snme time:
Cften, when creates a backup, it doesn't update the permissions
properly for your database server. Therefore using this utility to restore from a
backup may generate a error. If you receive this error mes-
sage, check the ownership of the directory holding the backup.
The resuÌts of this commnnd nre shown in Iigure 18-4O.
Figure 13-40: Restoring a previously backed-up database with the
mysqlhotcopy program
The stntement is the comµÌement to the stntement.
If you used the stntement to bnck uµ your tnbÌes, you cnn ensiÌy
restore them to your MySQL server by using the stntement with
the MySQL CLI. The syntnx for the stntement is ns foÌÌows:
Chapter 13 Debugging and kepairing Databases
Like the stntement, the stntement µroduces n stn-
tus messnge ns the outµut for the commnnd. Lven nn error messnge cnn serve ns n
kind of stntus messnge in this context. Ior exnmµÌe, enrÌier in the chnµter (refer to
Iigure 18-21), I crented n bnckuµ of the tnbÌe nnd µut it in the direc-
tory . Suµµose I try to restore thnt tnbÌe through
the CLI, using the foÌÌowing commnnd:
The tnbÌe nÌrendy exists ~so MySQL doesn`t restore the tnbÌe, µroducing (instend)
the error messnge shown in Iigure 18-41.
Figure 13-41: Attempting to overwrite an existing table causes a failure.
8efore restoring from n bnckuµ with the stntement, you must droµ
the tnbÌe. Iigure 18-42 shows the stntement nÌong with the successfuÌ
resuÌts from the stntement.
Figure 13-42: Using the RESTCRE TAßLE statement to restore a table
backed up earlier with the ßACKUP TAßLE statement.
Part III Administration
ße extremely careful running the statement; it deletes the entire
contents -every last shred of data -in the directory!
Ior bnckuµs or dumµs crented with the utiÌity, you cnn imµort or
restore those into MySQL through the MySQL CLI. 8ecnuse the utiÌity
crentes outµut ns SQL stntements, the fiÌes contnining the outµut cnn then be
imµorted or reµÌnyed simµÌy by executing the stntements.
ObviousÌy for nnything more thnn n few stntements it becomes burdensome to coµy
nnd µnste these into the CLI by hnnd. The use of the Ìess-thnn sign ( ) for redirect-
ing the contents of n fiÌe into the CLI cnn nÌÌevinte the work of coµying nnd µnsting
SQL into the CLI. Tnking the contents of n fiÌe µroduced with nnd redi-
recting it into MySQL is n simµÌe µrocess.
RecnÌÌ thnt µroduces outµut (ns shown in Iigure 18-48).
Figure 13-43: Example output from mysqldump
Chapter 13 Debugging and kepairing Databases
If you`ve mnde n comµÌete bnckuµ of n dntnbnse with nnd need to recre-
nte the dntnbnse nnd dntn, you cnn imµort it through the MySQL CLI with n commnnd
Ìine thnt Ìooks Ìike this:
As you cnn see from this commnnd, imµorting into MySQL through the CLI is ensy.
The section cnn incÌude things Ìike usernnme, µnssword, host, nnd so
forth. Another oµtion thnt you mny need to incÌude is the nnme of the dntnbnse.
The outµut from cnn incÌude the DDL to crente the dntnbnse. If you do
not hnve DDL to crente the dntnbnse incÌuded with the outµut, then you
wiÌÌ need to incÌude the nnme of the dntnbnse in your MySQL CLI commnnd Ìine. Ior
exnmµÌe, the foÌÌowing commnnd imµorts the contents of the fiÌe from Iigure 18-48:
The execution of this commnnd is shown in Iigure 18-44.
Figure 13-44: Importing an actual file produced with mysqldump
into the CLI with the use of the redirect character
Devising a PIan for Database ßackups
The µrogrnms nnd tooÌs discussed in this chnµter nre onÌy usefuÌ if you nctunÌÌy
tnke the time to nctunÌÌy use them. Mnking bnckuµs nnd oµtimizing tnbÌes is nn
imµortnnt µnrt of dntnbnse ndministrntion. In this section I`ÌÌ give nn exnmµÌe of n
simµÌe scriµt nnd method for reguÌnrÌy bncking uµ the dntn in your MySQL server.
Chapter 14 discusses methods for optimizing tables and suggests a regimen of
table maintenance.
Part III Administration
I`ÌÌ be using the commnnd to crente bnckuµs of the dntnbnse server. The
resuÌting outµut cnn be huge if you`re bncking uµ n Ìnrge dntnbnse or dntnbnses.
However the ndvnntnge of is thnt the outµut is in µÌnintext ~you cnn
edit the fiÌe so it onÌy imµorts the dntn you wnnt restored. The resuÌting outµut fiÌe
cnn nÌso be comµressed, which snves sµnce.
The commnnd to bnck uµ nÌÌ dntnbnses with is ns foÌÌows:
Ior exnmµÌe, to crente n bnckuµ of nÌÌ dntnbnses on my exnmµÌe server, I run this
IdenÌÌy, I wouÌdn`t need to be µresent to wntch the commnnd run ~so I mnke n
simµÌe scriµt to µroduce ~nnd then comµress ~n bnckuµ. The scriµt is shown in
Iigure 18-4b.
Figure 13-45: A simple shell script to make a backup of all databases
using mysqldump
The scriµt first gets the dnte so I cnn keeµ more thnn one dny`s worth of bnckuµ
fiÌes. Next the scriµt runs nnd sends the outµut to n fiÌe contnining the
dnte vnrinbÌe set enrÌier. IinnÌÌy, the scriµt comµresses the resuÌting fiÌe with the
Using n scheduÌer such ns , you cnn scheduÌe this scriµt to run ns often ns
you`d Ìike.
Store this file in a secure location and make sure that it is archived to another
medium (such as tape) or otherwise copied to another physical medium regularly.
Another method for crenting n bnckuµ is with . The snme methods
used for crenting n scriµt with cnn nÌso be used with .
The limitations and methods of are covered earlier in this chapter.
Chapter 13 Debugging and kepairing Databases
MySQL hns three bnsic methods for mnking bnckuµs: , ,
nnd . Lnch hns its own wny of µerforming bnckuµs, nn oµerntion
indisµensnbÌe to dntn integrity nnd dntnbnse security.
The utiÌity works by mnking n coµy of the nctunÌ directory
contnining the dntnbnse fiÌes. It must be run from the nctunÌ dntnbnse server.
The utiÌity µroduces the DDL nnd DML to recrente the dntnbnses
nnd tnbÌes ns new. If cnn be run from n mnchine other thnn the dntnbnse
server nnd cnn bnck uµ one, more thnn one, or nÌÌ dntnbnses nt once.
The stntement runs with the MySQL CLI. It cnn crente bnckuµs
of one or more thnn one tnbÌe within n dntnbnse.
The two commnnds for checking most tnbÌe tyµes in MySQL nre
nnd .
Iour stntements nre used with the MySQL CLI for working with tnbÌes:
, , , nnd . The stntements
nre simiÌnr in function to their counterµnrts.
The utiÌity cnn work with dntnbnses whiÌe the server is onÌine
wherens shouÌd not be used in this mnnner.
The utiÌity cnn reµnir most µrobÌems with tnbÌes nnd cnn crente
bnckuµs of tnbÌes before working with them for ndditionnÌ dntn snfety.
To restore dntnbnses nnd tnbÌes the commnnd cnn be used
nÌong with the MySQL CLI nnd the stntement.
The MySQL CLI cnn be used to imµort fiÌes crented with such ns n
bnckuµ fiÌe of n dntnbnse or tnbÌe.
Crente n reguÌnr routine for bncking uµ the dntnbnse on your server. Without
bnckuµs, you cnn Ìose nÌÌ the dntn on your server in the event of n cntnstroµhic
ySQL A8 hns gone to grent Ìengths to see thnt MySQL
µerforms weÌÌ. However, the deveÌoµers cnn`t foresee
every imµÌementntion of MySQL. It`s imµossibÌe to set every
vnrinbÌe nµµroµrinteÌy by defnuÌt. Ior this renson, mnny vnri-
nbÌes cnn be set by the dntnbnse ndministrntor to imµrove
µerformnnce for the sµecific nµµÌicntion.
Though tiµs nnd hints for enhnncing nnd imµroving the µer-
formnnce of the MySQL server nre disµersed throughout the
book, this chnµter µrovides ndditionnÌ informntion for setting
vnrinbÌes nnd imµroving MySQL µerformnnce
IroubIeshooting 5ervers
As with the first µortion of Chnµter 11 (which trents enhnncing
the µerformnnce of the MySQL server), this first µnrt of
Chnµter 14 exnmines troubÌeshooting nnd imµroving the server
itseÌf. One of the most imµortnnt methods for troubÌeshooting
server µrobÌems is to exnmine ÌogfiÌes. I`ÌÌ Ìook nt the different
ÌogfiÌes thnt nre nvniÌnbÌe with MySQL ns the first µortion of this
Knowing how to determine whnt needs imµrovement is indis-
µensnbÌe to imµroving server µerformnnce. Therefore I`ÌÌ
begin with bnsic troubÌeshooting techniques nnd commnnds,
nnd then recnµ some server vnrinbÌes nnd µerformnnce-
reÌnted oµtions.
MySQL A8 hns incÌuded some good suggestions for µerfor-
mnnce-reÌnted vnrinbÌes within their snmµÌe configurntion
fiÌes. I recommend using those fiÌes for exnmµÌes to mntch
your server configurntion nnd resource nvniÌnbiÌity.
C H A P I E k
ln Ihis Chopler
lroubleshoollng lhe
Doloboses ond
Cpllmlzlng Cuerles
Part III Administration
Chapter 11 examines the MySCL configuration files in detail.
My5OL IogfiIes
A fenture I use frequentÌy for troubÌeshooting is the MySQL ÌogfiÌes. The four common
ÌogfiÌe tyµes nre Ìisted in TnbÌe 14-1.
Table 14-1
Iypes of LogfiIes with My5OL
Log Iyµe 0se
ßinary log Stores all updates or changes to data, used in replication
Error log Records errors encountered by the server.
Cuery log Stores all connections and queries.
Slow query log Stores queries that take longer than or don't use
Two logfile types, the isam and the update logs, are outside the scope of this book.
One ÌogfiÌe of µnrticuÌnr imµortnnce is the MySQL error Ìog. If the server won`t
stnrt, mnny oµernting systems wiÌÌ record n trnce thnt cnn indicnte why the server
won`t stnrt or why it crnshed. Stnrts nnd stoµs of the server nre recorded in the
error ÌogfiÌe. An exnmµÌe error Ìog is shown in Iigure 14-1.
8y defnuÌt, the crror loµ is stored in the dntn directory for MySQL with n nnme of
is the hostnnme of the server). To chnnge the Ìocn-
tion of the error Ìog, set it with the oµtion undernenth the
section of the MySQL configurntion fiÌe.
To store nÌÌ inserts nnd uµdntes to dntn, use the binory loµ. The oµtion
under the section of the configurntion fiÌe ennbÌes the binnry Ìog, which
is stored in the dntn directory. The binnry Ìog is nÌso usefuÌ during reµÌicntion on
the reµÌicntion mnster, ns the ÌogfiÌe thnt records uµdntes for the sÌnves. This fiÌe
contnins binnry dntn, the contents of n binnry uµdnte Ìog nre shown in Iigure 14-2.
Chapter 14 Performance Iuning
Figure 14-1: A sample error log where the server crashed
Figure 14-2: An example of the binary log recorded with MySCL
Part III Administration
The oucry loµ records connections nnd queries mnde to the MySQL server. Using
the query Ìog, you cnn debug connection µrobÌems or query issues with the server.
The query Ìog is ennbÌed by ndding the oµtion beÌow the section in
the MySQL configurntion fiÌe. 8y defnuÌt, the query Ìog is recorded in the dntn direc-
tory of your MySQL server nnd is nnmed . This cnn be chnnged by
ndding to the oµtion in the configurntion fiÌe, Ìike this:
An exnmµÌe of the dntn stored in the query Ìog is shown in Iigure 14-8.
Figure 14-3: An example of the query log in MySCL
I`ve used the query Ìog to wntch µoorÌy written nµµÌicntions µerform µoorÌy written
queries nnd then Ìenve their connections oµen. Another Ìog thnt cnn be used for
this µurµose is the slou oucry loµ, which records two tyµes of sÌow queries:
Queries thnt tnke Ìonger thnn the vnÌue of the vnrinbÌe
Queries thnt don`t use nn index with the oµtion
To ennbÌe the sÌow query Ìog, ndd the oµtion undernenth the
section of the MySQL configurntion fiÌe. You cnn nÌso chnnge the tnrget
for the ÌogfiÌe from the defnuÌt of to nnother nnme by
ndding when using the oµtion, ns in the foÌÌowing
Chapter 14 Performance Iuning
To determine the vnÌue of the vnrinbÌe, use the
vnrinbÌes commnnd. The resuÌts nre shown in Iigure 14-4.
Figure 14-4: The long_query_time variable controls how long a query
has to take before it is recorded in the Slow Cuery Log.
You cnn chnnge the vnÌue for by ndding the foÌÌowing to the
MySQL configurntion fiÌe under the section:
The vnÌue is given in seconds. Ior exnmµÌe, to shorten the vnÌue
to 8 seconds, you wouÌd ndd the foÌÌowing Ìine to the section to the
MySQL configurntion fiÌe, Ìike this:
IroubIeshooting and performance
functions with mysqIadmin
The commnnd hns numerous functions thnt nssist with server
Chapter 10 covers these functions in detail.
Part III Administration
Functions to cIear IogfiIes
LogfiÌes cnn be reset or rotnted to the next ÌogfiÌe through the func-
tion. Ior exnmµÌe, Iigure 14-b shows n directory Ìisting of the numerous ÌogfiÌes run-
ning on this server. Iigure 14-6 shows the function being
run, foÌÌowed by nnother directory Ìisting. In thnt cnse, the binnry Ìog hns been
rotnted to number in the sequence nnd the server hns nÌso nccessed other Ìogs.
Figure 14-5: A directory listing showing the logfiles and timestamps
before the flush-logs function is run
Figure 14-6: The mysqladmin flush-logs function is run along with
another directory listing.
Chapter 14 Performance Iuning
Other fIush functions with mysqIadmin
hns five other functions for fÌushing ob|ects. These nre shown in
TnbÌe 14-2.
Table 14-2
FIush functions with mysqIadmin
Function nome Purµose
Clears the DNS cache of MySCL. Can assist if a host gets blocked
due to errors.
Clears and cycles MySCL logfiles.
Reloads the MySCL grants database so privilege changes take effect.
Clears server counters found with the and
Closes all open tables.
Closes all open threads.
The functions are discussed in detail in Chapter 10.
Two functions hnve synonyms or olioscs.
The function is nn nÌins for the function. 8oth
reÌond the grnnt tnbÌes.
The function is nn nÌins thnt µerforms both the duties of the
function nnd the function. Running n
wiÌÌ cÌose nÌÌ oµen tnbÌes nnd restnrt Ìogging (or cycÌe the ÌogfiÌes).
5tatus and variabIe functions
In nddition to the functions thnt fÌush or reset vnÌues nnd ob|ects with ,
other functions exnmine server stntus nnd vnrinbÌes.
The flush functions are discussed in detail in Chapter 10.
The functions nnd their µurµoses nre shown in TnbÌe 14-8.
Part III Administration
Table 14-3
5tatus and VariabIe functions with mysqIadmin
Function Purµose
Prints the current value for many server counters and status-related
Checks to see if the mysqld process is still alive.
Lists the currently open processes, along with their status and action.
Prints a short status message on the server with some status-related
Cutputs the current values for the variables set for the MySCL server.
The stntus nnd functions nre reÌnted becnuse they both outµut
the current stntus of vnrious counters within the server. The messnge
shows reÌntiveÌy few imµortnnt ob|ects, the outµut of shows
mnny ob|ects.
Unless you have an insanely small resolution on a huge monitor, you'll probably
need to pipe or redirect the output from the function so it
doesn't scroll by too fast on-screen.
Iigure 14-7 shows nn exnmµÌe of the stntus function. The fuÌÌ outµut from the
function foÌÌows ns weÌÌ.
Figure 14-7: Cutput from the mysqladmin status function shows the
current values for important counters.
Comµnre the outµut from the function in Iigure 14-7 to the foÌÌowing outµut
from the function.
Chapter 14 Performance Iuning
Part III Administration
Some of the snme counters nre incÌuded in the nnd
forms. (Chnµter 1O hns more informntion on the sµecific vnÌues.)
My5OL CLI troubIeshooting and
performance functions
The MySQL CLI incÌudes mnny of the snme functions ns the commnnd
. Ior exnmµÌe, the function is reµÌnced with the
stntement when executed with the CLI. The commnnd is
reµÌnced with the stntement when used with the CLI. TnbÌe 14-4
shows functions with their CLI equivnÌents.
Table 14-4
Functions with mysqIadmin and the My5OL CLI
Mysqlodmin lunction My5DL CLI equivolent
When run from within the CLI, the stntement hns three vnrintions.
The first is the normnÌ stntement thnt cÌoses nÌÌ oµen tnbÌes. The
second vnrintion cÌoses onÌy sµecified tnbÌes nnd cnn be cnÌÌed in singuÌnr or
µÌurnÌ form:
Two exnmµÌes of the stntement with sµecific tnbÌes nre shown in
Iigure 14-8.
Chapter 14 Performance Iuning
Figure 14-8: The FLUSH TAßLES statement using specific tables
The third vnrintion of the stntement is ns foÌÌows:
The stntement cÌoses nÌÌ oµen or in-use tnbÌes,
|ust Ìike the stntement. However, the
stntement nÌso µÌnces n Ìock on the tnbÌes thnt must be mnnunÌÌy unÌocked
with the stntement.
Iigure 14-9 shows nn exnmµÌe of the stntement,
nn nttemµt to rend from one of the Ìocked tnbÌes, nnd then the
stntement to nÌÌow nccess ngnin.
Figure 14-9: An example of the FLUSH TAßLES WITH READ LCCK
Part III Administration
Though comµÌemented by stntements in the CLI, the commnnd
cnn find the structure of dntnbnses, tnbÌes, nnd coÌumns. The stntement
is unÌike other commnnds in MySQL. You cnn`t simµÌy tyµe the commnnd to get n
syntnx µrinting. To see n syntnx reference for the commnnd, you shouÌd
ndd the switch, ns shown in Iigure 14-1O.
The switch is listed as a synonym for the switch, but it doesn't work.
Figure 14-10: A syntax reference for the mysqlshow command is
obtained by adding the --help switch.
Using the commnnd is quite simiÌnr to using other commnnds with
MySQL: The switch defines the user, the switch cnn define the µnssword, the
switch defines the host, nnd so on. The outµut from the commnnd is
simiÌnr to the outµut from the equivnÌent CLI commnnd (such ns or
). LxnmµÌes of the outµut from the commnnd nµµenr in
Iigures 14-11 nnd 14-12.
Chapter 14 Performance Iuning
Figure 14-11: Using the mysqlshow command to show the tables
within a database
Figure 14-12: Using the mysqlshow command to list the columns
within a table of the ecommerce database
Part III Administration
Optimizing Databases and IabIes
Certnin oµtimizing techniques cnn chnnge the structure of dntnbnses nnd tnbÌes to
mnke them oµernte more efficientÌy. In nddition, certnin stntements cnn oµtimize
tnbÌes with µerformnnce enhnncements such ns defrngmentntion.
The use of indexes wiÌÌ he̵ µerformnnce immenseÌy on Ìnrge dntnsets. MySQL
stores indexes nnd dntn in seµnrnte fiÌes to mnximize efficiency. Adding nn index (or
crenting one with n tnbÌe) wiÌÌ he̵ when µerforming oµerntions on the dntn, thnt
wny MySQL need onÌy Ìook nt n subset of the dntn for the correct resuÌt.
If there is n index on the tnbÌe, it shouÌd be n short tnsk to mnximize
sµeed. If you frequentÌy senrch on muÌtiµÌe coÌumns, index the coÌumns with the
most used coÌumn being the first in the Ìist. However, don`t mnke unnecessnry
The stntement cnn nssist in determining when nn index might be usefuÌ.
The stntement is used with n stntement. Ior exnmµÌe, Iigure 14-18
uses the stntement to show indexes used by n stntement.
Figure 14-13: A description of two tables in the ecommerce database
along with an EXPLAIN statement to examine the SELECT statement
being used to find the first and last names of customers
Chapter 14 Performance Iuning
The nnd coÌumns in the outµut of the stntement
show µossibÌe keys thnt MySQL couÌd use for the nnd the nctunÌ key (if
nny) thnt MySQL used for the query.
AÌÌ index tyµes in MySQL nre stored in 8-Tree formnt. They cnn imµrove µerfor-
mnnce with n cÌnuse. Since most stntements wiÌÌ use n cÌnuse,
nn index cnn be the singÌe most imµortnnt imµrovement you mnke for better µerfor-
mnnce. Indexes cnn nÌso quickÌy sort, Ìocnte the mnximum nnd minimum vnÌues for
n coÌumn, nnd nssist with n |oin of two or more tnbÌes.
The syntnx for crenting nn index during n stntement is
Creating a column as a also enables MySCL to optimize queries.
You cnn nÌso crente nn index nfter the tnbÌe hns been crented through the crente
index or nÌter tnbÌe commnnds. The crente index commnnd is nctunÌÌy nn nÌins for
nn nÌter tnbÌe stntement. The syntnx for n crente index stntement is ns foÌÌows:
Snve disk sµnce by choosing the correct coÌumn tyµes nnd mnking the dntn ns smnÌÌ
ns µossibÌe. Choosing the smollcsi or mosi opproprioic coÌumn tyµe he̵s MySQL
work efficientÌy with the dntn. Choosing fixed-Ìength coÌumns cnn nÌso incrense
Fixed length columns may end up wasting space since MySCL will always allocate
the defined amount of bytes for the column regardless of the actual data length.
The stntement run with the MySQL CLI is used to defrngment n
tnbÌe or tnbÌes. The stntement onÌy works with nnd tnbÌes.
reµnirs nny deÌeted or sµÌit rows nnd nÌso sorts indexes. Two exnmµÌes of the
stntement nre shown in Iigure 14-14.
While the statement is running, the table is locked. ße aware
that this can take a fair amount of time, depending on the size of the table.
Part III Administration
Figure 14-14: The CPTIMIZE TAßLE statement in action
Optimizing Oueries
MySQL µerforms mnny oµtimizntions for queries nnd stntements without the user
hnving to be invoÌved. These incÌude µrocesses Ìike exnminntion of cÌnuses nnd
stntements to determine how they couÌd be µhrnsed in n more efficient mnnner, nnd
re|ection of some stntements without running them if they nre invnÌid. MySQL nÌso
µerforms bnckground oµtimizntion of stntements nnd stntements.
If this µrocess is nutomnted, whnt`s your roÌe" In the µrevious section I exnmined
the stntement. The stntement cnn he̵ you determine the
indexes to use with n stntement. UsefuÌ indexes nre the key to imµroving
server µerformnnce when your dntnbnse nµµÌicntions µerform mnny rends.
After the dntnbnse hns been µoµuÌnted, sorting the indexes within the dntnbnse
mny be he̵fuÌ. You cnn do this with the stntement. Ior exnmµÌe, to sort
on the first index, issue the foÌÌowing commnnd:
Iigure 14-1b shows the µrevious commnnd when run ngninst n few tnbÌes within the
dntnbnse. The second nttemµt in the exnmµÌe fniÌs becnuse no indexes
exist in the tnbÌe.
Chapter 14 Performance Iuning
Figure 14-15: Examples of the myisamchk command to sort indexes
on tables within the ecommerce database
The use of vnrious MySQL ÌogfiÌes is n mn|or nsset when troubÌeshooting the server
or denÌing with other dntnbnse µrobÌems.
The error Ìog is nn imµortnnt tooÌ for he̵ing to determine why the server
crnshes or won`t stnrt.
The binnry uµdnte Ìog nnd the query Ìog cnn he̵ you wntch for uµdntes thnt
cnuse µrobÌems, they cnn nÌso he̵ you Ìook for nny stntements thnt
crente µerformnnce µrobÌems.
The sÌow query Ìog shows queries thnt tnke Ìonger thnn the sµecified time or
don`t use nn index.
The commnnd contnins usefuÌ functions for troubÌeshooting the
server incÌuding fÌush functions nnd stntus nnd vnrinbÌe functions.
The fÌush functions with reset or cÌenr counters, ÌogfiÌes, nnd
even the MySQL µriviÌege system.
The MySQL CLI nÌso incÌudes functions nÌong with functions to show
vnrinbÌes nnd monitor server µerformnnce.
Part III Administration
Indexes cnn he̵ sµeed uµ oµerntions with dntnbnses.
The stntement is used to Ìook nt the indexes thnt n stnte-
ment cnn use or might benefit from.
You cnn crente indexes during the tnbÌe crention stntement or through the use
of n seµnrnte stntement.
The stntement is used to reµnir nnd defrngment nnd
MySQL µerforms mnny oµtimizntions in the bnckground without nny user
intervention. Stntements nre nnnÌyzed before they nre run to determine vnÌid-
ity nnd how to µhrnse them better for imµroved µerformnnce.
ln Ihis Porl
Chopler J5
Perl Developmenl
Chopler J6
PHP Developmenl
Chopler J7
P A k I

`ve been using PerÌ for mnny yenrs. I`ve found the Ìnngunge
extremeÌy usefuÌ in server nnd network ndministrntion.
Without PerÌ, my |ob wouÌd`ve been imµossibÌe to do.
MySQL hns nn nµµÌicntion-µrogrnmming interfnce (API) for
PerÌ. It`s cnÌÌed the PerÌ Dntnbnse Interfnce (D8I), nnd µro-
grnmmers cnn use it to crente µowerfuÌ nµµÌicntions thnt µer-
form every function imnginnbÌe ~from ndministrntion tnsks
to reµorting to Web nµµÌicntions ~with n MySQL server. The
PerÌ-D8I combines fuÌÌ nccess to the µower of MySQL with the
ense of PerÌ.
The DßI allows access to many different database types.
To enable access to MySCL, however, a MySCL-specific
database driver (DßD) must be used. This chapter refers to
the combination of DßI-and-DßD as either "the DßI" or
This chnµter buiÌds n few nµµÌicntions thnt tnke ndvnntnge of
the PerÌ-D8I. 8efore buiÌding the nµµÌicntions, I show you the
PerÌ API itseÌf ~nnd the mnny functions incÌuded with it.
The exnmµÌe nµµÌicntions stick to the fundnmentnÌs of using
the PerÌ D8I nnd the MySQL D8D. Ior the time being, you cnn
forego buiÌding n guestbook nµµÌicntion (n common exercise
in books devoted to PerÌ). If you wnnt to buiÌd n guestbook
Ìnter, the exnmµÌes in this chnµter µrovide n good foundntion
for doing so.
C H A P I E k
ln Ihis Chopler
lnslolllng lhe Perl DBl
ond lhe MySCL DBD
lnlroduclng lhe DBl
Üslng luncllons
wllh lhe DBl
Bulldlng boslc
Bulldlng Veb
Produclng o Veb slle
lor ecommerce
Part Iv DeveIopment
InstaIIing the PerI DßI And My5OL DßD
A µrerequisite for instnÌÌing the D8I nnd the MySQL D8D is hnving PerÌ itseÌf
instnÌÌed. InstnÌÌntion of PerÌ is beyond the scoµe of this book, this section
nssumes thnt you nÌrendy hnve PerÌ instnÌÌed. The steµs given here simµÌy
instnÌÌ the PerÌ-D8I nnd the MySQL D8D on n Linux system.
Where to get the DßI and DßD
The Ìntest coµies of the PerÌ D8I nnd MySQL D8D cnn be obtnined nt your ÌocnÌ
CPAN mirror, . The MySQL D8D is nctunÌÌy n combinntion of
the D8D for the dntnbnse ns weÌÌ ns the D8D for MySQL.
InstaIIing the DßI
Once you`ve obtnined the D8I nnd D8D for MySQL, you unµnck the nrchive by using
the commnnd in Linux. The commnnd syntnx is
nnd here`s nn exnmµÌe:
Unµncking the D8I resuÌts in n directory thnt contnins the fiÌes
necessnry to crente the D8I, ns shown in Iigure 1b-1.
8efore unµncking nnd instnÌÌing the D8D, you need to comµiÌe the D8I softwnre.
Chnnge into the newÌy crented D8I directory, the commnnd syntnx is
nnd here`s nn exnmµÌe:
The first steµ townrds instnÌÌntion is executing the MnkefiÌe for the softwnre. This is
nccomµÌished with the commnnd:
Chapter 15 PerI DeveIopment
Figure 15-1: Unpacking the DßI results in a directory containing the
files necessary to create the actual DßI software
ßecause the filename is case-sensitive, entering
doesn't work.
Lxecuting the commnnd |ust described yieÌds resuÌts simiÌnr to Iigure 1b-2.
Figure 15-2: Executing the Makefile for the DßI
Part Iv DeveIopment
The next steµ for instnÌÌntion of the D8I is to comµiÌe the softwnre. This is nccom-
µÌished with the commnnd. Lxecuting the commnnd resuÌts in n fnir
nmount of outµut scroÌÌing on the screen, this is normnÌ (see Iigure 1b-8).
Figure 15-3: Compiling the DßI
There nre two steµs remnining for instnÌÌntion of the D8I. The next µortion of the
instnÌÌntion is to test the softwnre before nctunÌÌy instnÌÌing it on the system. This is
nccomµÌished with the commnnd. The commnnd tests the
D8I to mnke sure thnt the uµcoming instnÌÌntion works ns µÌnnned. The outµut from
the commnnd for instnÌÌntion of the D8I shouÌd Ìook much Ìike Iigure 1b-4.
The finnÌ stnge of the D8I instnÌÌntion is to run the commnnd to
nctunÌÌy instnÌÌ the softwnre, ns shown in Iigure 1b-b.
Systems and configurations differ; your output may look slightly different. Note
Chapter 15 PerI DeveIopment
Figure 15-4: Cutput from your command (to test the DßI
software before installation) is similar to that shown here.
Figure 15-5: The final stage to actually install the DßI is accomplished
with the command.
Part Iv DeveIopment
InstaIIing the My5OL DßD
The MySQL Dntnbnse Driver or D8D is n combined with the driver for the
dntnbnse system. As stnted µreviousÌy, the D8D cnn be obtnined nt your ÌocnÌ CPAN
mirror or nt . The instnÌÌntion µrocess for the D8D is some-
whnt simiÌnr to the D8I however there nre some questions thnt must be nnswered
during the instnÌÌntion.
Use the commnnd to unµnck the MySQL D8D nrchive, tyµicnÌÌy cnÌÌed
. Ior exnmµÌe:
Chnnge into the newÌy crented directory with the com-
mnnd nnd tyµe perl Makefile.PL to begin the instnÌÌntion µrocess for the MySQL
D8D. You`ÌÌ be nsked n series of questions, the first of which determines whether
you`d Ìike to instnÌÌ the driver for MySQL, versions 1 nnd 2, or nÌÌ drivers, ns
shown in Iigure 1b-6.
Figure 15-6: The first question for the command used to
build the database drivers
Ior the µurµoses of this instnÌÌntion, I choose onÌy the MySQL oµtion, number 1.
The second question during the instnÌÌntion of the D8D is whether to instnÌÌ
emuÌntion. ( is the oÌd version of the D8D for MySQL nnd
PerÌ.) If you hnve oÌd nµµÌicntions thnt mny hnve been crented using the syntnx of
the driver, then you shouÌd sny yes to this oµtion. Ior this instnÌÌntion, I
don`t need emuÌntion, so I nnswer for no.
The third question nsks for the Ìocntion of the MySQL server fiÌes. Ior my test server,
the defnuÌt of is correct. However, your instnÌÌntion of MySQL mny be
Chapter 15 PerI DeveIopment
(nnd µrobnbÌy is) in n different Ìocntion. As stnted in the µromµt in Iigure 1b-7, the
Ìocntion shouÌd be where the cnn find the directory of the
MySQL instnÌÌntion.
Figure 15-7: The location of the MySCL server files is necessary. The
default (/usr/local) is correct for my example server.
The next series of questions sets the µnrnmeters for testing of the driver. The first
question is the nnme of the dntnbnse thnt the instnÌÌntion µrocess shouÌd use for test-
ing. The MySQL server usunÌÌy incÌudes n dntnbnse cnÌÌed , therefore this is nn
ensy choice to Ìenve nt the defnuÌt of nt the µromµt. The second question in
this series nsks for the nnme of the server to use for testing. (The test server shown
in Iigure 1b-8 runs on the ÌocnÌ mnchine, the defnuÌt of is ncceµtnbÌe.)
Figure 15-8: Using the test database for testing, with the server
running on the local machine. ßoth defaults are accepted if you
press Return or Enter.
Part Iv DeveIopment
The next two questions hnve no defnuÌts. The first nsks for the usernnme to use for
testing the driver, the second nsks for the µnssword for thnt user. I`ÌÌ be using the
user nccount for testing nnd giving thnt µnssword ns weÌÌ, ns in Iigure 1b-9.
Figure 15-9: Using the root user account for testing of the MySCL DßD
The questions you |ust nnswered crente fiÌes thnt serve ns the bnsis for the next
steµ in the µrocess: the nctunÌ crention of the D8D. Wnrnings nbout n missing
Ìibrnry nnd cnn be ignored. 8egin this next µhnse by tyµing make.
You begin the testing µhnse by tyµing the foÌÌowing commnnd:
If you hnµµen to mistyµe (or sµecify n user, µnssword, or test dntnbnse thnt doesn`t
exist) during the initinÌ stnge of the instnÌÌntion, this testing µhnse fniÌs misernbÌy
nnd shows errors thnt resembÌe Iigure 1b-1O.
However, if you µrovided correct informntion for the testing µortion of the initinÌ
µhnse the tests shouÌd comµÌete successfuÌÌy, ns shown in Iigure 1b-11.
Chapter 15 PerI DeveIopment
Figure 15-10: The testing phase of the DßD installation fails if you
provided incorrect information during the initial stage of the installation.
Figure 15-11: Successful testing of the DßD
Part Iv DeveIopment
IinnÌÌy, instnÌÌ the MySQL PerÌ D8D by tyµing the foÌÌowing commnnd:
The NormnÌ instnÌÌntion dinÌog box shouÌd nµµenr whiÌe the D8D is instnÌÌed in the
µroµer Ìocntions (see Iigure 1b-12).
Figure 15-12: Normal installation output when you run the make
install command to install the MySCL DßD
Other sµecific drivers nnd tooÌs cnn be instnÌÌed to work with MySQL nnd PerÌ, their
instnÌÌntion µrocess Ìooks much the snme ns this one.
Introducing the DßI
The PerÌ D8I is the nnme for n dntnbnse-indeµendent set of softwnre µrogrnms thnt
n µrogrnmmer cnn use with mnny different dntnbnses ~using the snme functions in
every cnse. The D8I snves hnving to nccount for the muÌtitude of nccess methods
used for different dntnbnses. Ior exnmµÌe, the D8I ennbÌes the µrogrnmmer to use
different dntnbnse drivers (D8Ds) for dntnbnses such ns OrncÌe, mSQL, Sybnse, nnd
others ~without hnving to Ìenrn nn entireÌy new syntnx to µrogrnm ench one.
The uµcoming µortion of the chnµter introduces the D8I itseÌf ~in µnrticuÌnr, the
bnsics of D8I use (such ns connecting to n dntnbnse nnd disconnecting), ns weÌÌ ns
the D8I`s error-hnndÌing cnµnbiÌity.
ßasic DßI Usage
The D8I is buiÌt nround nn ob|ect-oriented µrogrnmming styÌe. Within thnt context,
the dntnbnse driver is initinÌized, connections to the dntnbnse nre crented, commnnds
Chapter 15 PerI DeveIopment
nnd stntements nre run, nnd the connections nre destroyed. Whenever you crente nn
ob|ect, the D8I identifies it ~ns n driver, n dntnbnse, or n stntement ~by nssocinting
it with one of three ÌogicnÌ mnrkers (known ns honJlcs) thnt corresµond to those
three tyµes of ob|ects: (drivers, dntnbnses, or stntements). The hnndÌes nre nctunÌÌy
µointers to sµecific insionccs of ob|ects.
Irom n µrogrnmming stnndµoint, you decÌnre thnt you`d Ìike to use the D8I in your
µrogrnm by ndding the foÌÌowing Ìine nenr the beginning of your µrogrnm:
Driver handIes
D8I driver hnndÌes nre nvniÌnbÌe for mnny dntnbnse tyµes. Ior the µurµoses of this
book, you need be concerned onÌy with the MySQL driver hnndÌe.
You can use more than one driver handle within the same program to connect to
different database types. You can only use one driver handle per database. (Then
again, why would you need more than one handle to the same driver!)
You initinÌize the driver hnndÌe (or more µroµerÌy, the D8I does so) behind the
scenes. Ior exnmµÌe, the driver hnndÌe for MySQL is crented when you cnÌÌ the
method for the D8I.
Database handIes
Dntnbnse hnndÌes nre the controÌs you use to mnniµuÌnte dntnbnse-reÌnted µrogrnms.
When n dntnbnse hnndÌe is crented, you connect to the MySQL dntnbnse nnd µrovide
credentinÌs such ns usernnme, µnssword, nnd dntnbnse nnme. These credentinÌs
nre the snme ns those you wouÌd suµµÌy to connect with the MySQL CLI (or the
commnnd nnd so forth).
The stnndnrd nnming scheme for n dntnbnse hnndÌe is the vnrinbÌe (which I
use throughout this chnµter). A dntnbnse hnndÌe is crented nutomnticnÌÌy whenever
you cnÌÌ the method, the syntnx Ìooks Ìike this:
The µnrent driver hnndÌe is nÌso crented ~nutomnticnÌÌy ~when the dntnbnse
hnndÌe is crented. (Connection nnd disconnection get n cÌoser Ìook in nn uµcoming
section of this chnµter.)
MySQL nÌÌows muÌtiµÌe simuÌtnneous connections when using methods such ns
the CLI, connections using the D8I hnve the snme cnµnbiÌity. Therefore, muÌtiµÌe
dntnbnse hnndÌes cnn be crented thnt nttnch to the snme dntnbnse. Iurther, ench
dntnbnse hnndÌe is n comµÌeteÌy seµnrnte ob|ect, you need not worry nbout
commnnds or resuÌts coÌÌiding with ench other.
Part Iv DeveIopment
5tatement handIes
Sioicmcni honJlcs nre the menns by which nctunÌ SQL nnd reÌnted stntements
nre executed ngninst the MySQL server. The stntement hnndÌe is the chiÌd of the
dntnbnse hnndÌe, cnn issue muÌtiµÌe stntements using the snme dntnbnse hnndÌe.
Lnch stntement you issue gets its own stntement hnndÌe, usunÌÌy referred to by the
vnrinbÌe nnme. Think of this µrocess ns issuing muÌtiµÌe stntements from
within the CLI. You don`t hnve to reconnect to the CLI for ench stntement
(for exnmµÌe), you cnn issue muÌtiµÌe stntements.
Connecting to and disconnecting
from the database with the DßI
Internction with the dntnbnse cnn onÌy be done nfter n connection is mnde. The
connection is known ns n dntnbnse hnndÌe nnd usunÌÌy referred to by the h
vnrinbÌe nnme. The driver hnndÌe is crented in the bnckground when n connection
is mnde.
Use the method to crente n dntnbnse hnndÌe nnd connect to the dntnbnse.
When using the method, you must suµµÌy credentinÌs ns you wouÌd if you
were connecting through the CLI. Ior exnmµÌe, if you hnve to sµecify n µnssword
(nnd you shouÌd), then connecting through the CLI menns you hnve to sµecify thnt
snme µnssword when you connect through the D8I. Iigure 1b-18 shows some fniÌed
connections nttemµted with n D8I-bnsed PerÌ µrogrnm, they fniÌ when µroµer
credentinÌs nren`t suµµÌied.
Figure 15-13: Errors when a DßI-based application doesn't have
proper credentials to connect to the database requested
Chapter 15 PerI DeveIopment
The nuthenticntion scheme is the snme for n D8I-bnsed PerÌ nµµÌicntion ns it is for
nny other connection to the dntnbnse. The usernnme suµµÌied must be nÌÌowed
nccess from the host where the µrogrnm is running, the usernnme must be nÌÌowed
to nccess the dntnbnse, the µnssword suµµÌied with the usernnme must mntch, nnd
other credentinÌs must be correctÌy suµµÌied, ns is the cnse with nny other connec-
tion to the dntnbnse server.
RecnÌÌ thnt the bnsic syntnx for n connection is
The for MySQL contnins n reference to the MySQL D8D foÌÌowed by
the oµtionnÌ nnme of the dntnbnse you wnnt to connect to, foÌÌowed by the oµtionnÌ
hostnnme of the dntnbnse server thnt houses the dntnbnse. Here`s nn exnmµÌe:
wouÌd connect to the dntnbnse on the ÌocnÌ host nnd crente n dntnbnse
hnndÌe ( ), nssuming the credentinÌs suµµÌied in nre correct.
Ior exnmµÌe, Iigure 1b-14 shows n smnÌÌ exnmµÌe nµµÌicntion thnt, when executed,
issues n simµÌe outµut messnge.
Figure 15-14: A small application for connecting to the ecommerce
As stnted µreviousÌy, the dntnbnse itseÌf is oµtionnÌ within the µortion
of the D8I oµerntion thnt crentes the ob|ect. The foÌÌowing commnnd
(which crentes n dntnbnse hnndÌe) is vnÌid ns weÌÌ:
Part Iv DeveIopment
Other µortions of the incÌude the oµtionnÌ host nnd µort. If no host or
µort is suµµÌied, the host is nssumed to be nnd the µort is nssumed to
be the defnuÌt µort, 88O6. Ior exnmµÌe, Iigure 1b-1b shows different methods for
suµµÌying the host nnd}or µort for connecting to the dntnbnse.
Figure 15-15: Methods for specifying host and port for the
portion of the database handle
Notice the word within the µrogrnm in Iigure 1b-14. The is n µÌnce-
hoÌder where the usernnme wouÌd normnÌÌy go. In this instnnce, is there, the
D8I tnkes the vnÌue of the environment vnrinbÌe nnd µuts it in the µÌnce of the
If you wnnt to suµµÌy the usernnme, you shouÌd encÌose the usernnme in singÌe or
doubÌe quotntion mnrks. However, if you suµµÌy the usernnme ns n vnrinbÌe, the D8I
interµoÌntes the vnrinbÌe without requiring you to use quotes. Iigure 1b-16 shows n
few exnmµÌes of correct methods for sµecifying the credentinÌ ns µnrt of
the crention.
If you suµµÌy ns the µnssword or don`t use n µnssword nt nÌÌ, it is nssumed
thnt no µnssword is used. This is ns oµµosed to sµecifying n bÌnnk µnssword.
Iigure 1b-17 shows exnmµÌes of two scriµts nnd the errors thnt resuÌt from running
them with the different µnssword methods. Notice the error from the first scriµt
(where MySQL beÌieves no µnssword is sµecified) nnd from the second scriµt
(where n bÌnnk µnssword is sµecified).
Chapter 15 PerI DeveIopment
Figure 15-16: various methods for specifying the username portion
of the credentials when creating a connection
Figure 15-17: Different methods for specifying a password, one
using the placeholder and one specifying a blank password
Part Iv DeveIopment
Of course, you couÌd suµµÌy the credentinÌs inside one vnrinbÌe ns weÌÌ (see
Iigure 1b-18).
Figure 15-18: Creating the proper credentials inside a variable.
is also a valid way to connect.
AÌso ns the credentinÌs µortion of the connection cnn be suµµÌied in n vnrinbÌe, the
couÌd nÌso be suµµÌied in whoÌe or in µnrt by vnrinbÌe interµoÌntion.
Ior exnmµÌe, you couÌd define the host ns , the dntnbnse nnme ns ,
nnd so forth: You couÌd even suµµÌy the entire ns n vnrinbÌe,
(or the nnme of your choosing.) Iigure 1b-19 iÌÌustrntes some of these
Figure 15-19: Specifying portions of the through the use
of variables can help to make the program more readable.
Lxnmining whnt I hnve defined so fnr:
Chapter 15 PerI DeveIopment
I`d Ìike to introduce the finnÌ µortion of dntnbnse hnndÌe crention with the D8I nnd
MySQL D8D. The finnÌ µortion is oµtionnÌ nnd consists of nttributes or eÌements
thnt nffect the behnvior of the hnndÌe itseÌf. Therefore, ndding this onto the
definition I`ve been using:
A number of eÌements nre nvniÌnbÌe here, most notnbÌy those thnt define how errors
nre hnndÌed nnd whnt to do with extrn bÌnnk sµnces for coÌumn tyµes. I`ÌÌ
exnmine error hnndÌing in the next section, therefore I`ÌÌ snve further discussion of
the oµtionnÌ eÌements untiÌ then.
Uµ untiÌ now, I`ve Ìooked nt methods for connecting to the dntnbnse. 8y now, you
hnve more thnn enough informntion to connect to n dntnbnse. However, disconnect-
ing from n dntnbnse is imµortnnt ns weÌÌ.
NormnÌÌy, when your µrogrnm exits, the disconnection is nutomntic thus snving the
µrogrnmmer the work of hnving to exµÌicitÌy issue n commnnd. In µrnc-
tice, however, nÌwnys exµÌicitÌy disconnect your dntnbnse hnndÌes. This is becnuse
there nre times when using muÌtiµÌe hnndÌes in n µrogrnm thnt you mny need to dis-
connect oÌd hnndÌes to µreserve resources.
If you do not issue nn exµÌicit disconnect, PerÌ disconnects the hnndÌe ns µnrt of the
µrocess when n µrogrnm terminntes. You mny see nn error or wnrning Ìike:
This shouÌd remind you to go bnck nnd issue n stntement within your
µrogrnm. The syntnx for the method is:
Therefore, you cnn see thnt it is µossibÌe to disconnect onÌy certnin dntnbnse
hnndÌes. Ior exnmµÌe, if your µrogrnm hns three dntnbnse hnndÌes, , ,
, you couÌd simµÌy issue n to the sµecific hnndÌe or hnndÌes
thnt you no Ìonger need.
You mny wnnt to check the return stntus of the disconnection to mnke sure thnt it
wns successfuÌ. You cnn do this by checking the return vnÌue from the
cnÌÌ, using the foÌÌowing commnnd:
If the vnÌue of evnÌuntes , then the disconnection wns successfuÌ, other-
wise the disconnection fniÌed.
Part Iv DeveIopment
HandIing errors with the DßI
In most instnnces, error hnndÌing is nutomntic with the D8I. This wns evidenced by
enrÌier Iigures nnd exnmµÌes in this chnµter. The error messnges Ìook quite simiÌnr
to those you wouÌd see with other MySQL tooÌs such ns the CLI or .
Sometimes you mny wnnt to disnbÌe this nutomntic error-checking in fnvor of mnn-
unÌ error checking (or n combinntion of nutomntic nnd mnnunÌ).
Lrror hnndÌing is configured using the nttributes or eÌements discussed in n µrevi-
ous section. There nre two nttributes of D8I error-checking: nnd
. 8y defnuÌt, is ennbÌed. simµÌy µrints the
error messnge to the screen nnd continues execution of the µrogrnm ns if nothing
hnd hnµµened. This is bnd if your µrogrnm is reÌying on informntion from the
dntnbnse nnd n stntement or commnnd fniÌs to execute.
To iÌÌustrnte this behnvior, tnke n Ìook nt the µrogrnm in Iigure 1b-2O. In this
µrogrnm, I query n dntnbnse for n number nnd then µerform n comµutntion bnsed
on thnt number. I nÌÌow to µerform the error checking in the µrogrnm,
but do no further error hnndÌing myseÌf. You cnn see the resuÌts of the µrogrnm in
nction in Iigure 1b-2O ns weÌÌ. The µrogrnm hnµµiÌy continues, even though the
query execution fniÌed. If these resuÌts were to be nutomnticnÌÌy e-mniÌed to me
using n scheduÌing µrogrnm such ns , I wouÌdn`t see these error messnges.
Figure 15-20: A program continues execution in the event of an
error when using the default for error-checking.
Chapter 15 PerI DeveIopment
Though disnbÌed by defnuÌt, the nttribute cnuses the µrogrnm to termi-
nnte immedinteÌy uµon encountering nn error with the D8I. 8y crenting nn nttribute
hnsh, , nnd setting to 1, the nttribute becomes
oµerntionnÌ nnd thus terminntes the µrogrnm if nn error is encountered. Iigure
1b-21 shows nn exnmµÌe of the snme µrogrnm from Iigure 1b-2O with the
hnsh crented nnd then nµµended to the dntnbnse hnndÌe initinÌizntion.
Note the use of the backslash to escape the in the database handle creation.
Figure 15-21: Using RaiseError to terminate a program immediately
if an error occurs
Notice in Iigure 1b-21 thnt the snme error messnge is µrinted twice. This is exµected
behnvior. Remember thnt is ennbÌed by defnuÌt. Therefore, when nn
error occurs, sees it nnd µrints the error. OnÌy when
hnndÌes the error does the µrogrnm terminnte. If you wnnt to disnbÌe ,
set its vnÌue to O, ns shown in Iigure 1b-22.
Part Iv DeveIopment
Figure 15-22: Setting PrintError to 0 in the %attr attribute hash to
prevent duplicate printing of the error message
You cnn nÌso toggÌe the behnvior of the nnd nttributes
within the µrogrnm. Ior exnmµÌe, if you wnnt to disnbÌe nÌÌ error checking for n
certnin stntement you cnn set the vnÌues of nnd to O
nnd then re-ennbÌe one or both nfter the stntement executes. Iigure 1b-28 shows
nn exnmµÌe thnt disnbÌes nÌÌ error checking by the D8I, µerforms n stntement,
nnd then re-ennbÌes the defnuÌt error-checking method.
Figure 15-23: Selective error checking within the same program
Chapter 15 PerI DeveIopment
If you choose to disnbÌe the error-checking fenture, you must µerform error check-
ing nnd hnndÌing mnnunÌÌy. This cnn be nchieved in numerous wnys incÌuding the
die or wnrn functions. Another method for mnnunÌ error checking is the use of nn
test. 8ecnuse most oµerntions with the D8I return n vnÌue of for n fniÌure,
if the vnÌue from the oµerntion does not exist, then you cnn nssume thnt the execu-
tion fniÌed. If it evnÌuntes , then you cnn be nssured thnt the dntnbnse hnndÌe
wns crented. Iigure 1b-24 shows some exnmµÌes of mnnunÌ error checking.
I've been using an test in the examples throughout this chapter to test whether
the database-handle variable evaluated to or .
Figure 15-24: Using manual error-checking methods
ßuiIt-in error status methods
There nre buiÌt-in methods for working with error stntus messnges. The exnmµÌe
µrogrnm in Iigure 1b-24 showed one of these, . Another method thnt I`ÌÌ
highÌight is the method. The method contnins the string text
messnge of the error. The method contnins the error number corresµonding
to the error.
The nnd methods exist both nt the D8I ÌeveÌ nnd nt the hnndÌe
ÌeveÌ. At the D8I ÌeveÌ, ns used in Iigure 1b-24, the methods contnin the informntion
for the Ìnst-used hnndÌe. The hnndÌe-ÌeveÌ methods nre cnÌÌed ns shown:
Modifying the µrogrnm from Iigure 1b-24 to use the hnndÌe methods is quite simµÌe,
ns shown in Iigure 1b-2b.
Part Iv DeveIopment
Figure 15-25: Using manual error checking and the handle-level
error methods
Using hnndÌe-ÌeveÌ error methods you couÌd nssign the resuÌts to vnrinbÌes for
Ìnter testing. An exnmµÌe of n µrogrnm using this tyµe of test is shown in Iigure 1b-26.
Figure 15-26: Using handle-level error methods and assigning one to
a variable for later use
Chapter 15 PerI DeveIopment
Functions with the DßI
So fnr, I`ve discussed four functions ns nn introduction to the D8I:
I`ve used some other functions in exnmµÌes. This section exnmines those functions,
nÌong with others for use with the D8I nnd MySQL D8D.
Going bnck to exnmµÌes shown in µrevious figures in this chnµter you`ÌÌ see the cre-
ntion of n stntement hnndÌe, , nnd the use of the method nÌong with
the method. The method tnkes nn SQL stntement nnd stores
or µnrses it for Ìnter execution by the D8I. The method then tnkes thnt
µreµnred stntement nnd runs it ngninst the dntnbnse engine. The
method returns the number of rows nffected for non- stntements. With n
stntement n vnÌue is returned uµon successfuÌ execution.
The exnmµÌes of the nnd methods shown µreviousÌy were
done in such n mnnner ns to µroduce nn error. Therefore, I`ÌÌ Ìenve those exnmµÌes
nÌone nnd show n new exnmµÌe µrogrnm with n successfuÌ nnd
method cnÌÌ, ns shown in Iigure 1b-27.
Figure 15-27: A successful execution of a MySCL statement using the
Perl DßI
The nnd methods both tnke oµtionnÌ nrguments or µÌnce-
hoÌders thnt nre substituted into the nctunÌ stntement nt execution time, much Ìike
n vnrinbÌe wouÌd be. The µÌncehoÌder is the question mnrk ( ). The
method substitutes the nctunÌ vnÌues for the question-mnrk µÌncehoÌder when using
Part Iv DeveIopment
. AÌternntiveÌy, the substitution cnn tnke µÌnce nt execution time by
suµµÌying nn nrgument to the cnÌÌ. Iigure 1b-28 shows nn exnmµÌe of
this behnvior.
Figure 15-28: Using a placeholder to substitute a value at execution
time for a SELECT statement
An exnmµÌe of the function is shown in Iigure 1b-29.
Figure 15-29: Using the bind_param function to substitute values in
a call
NnturnÌÌy, you couÌd substitute vnrinbÌes for the vnÌues in the nrgu-
ment Ìist. The nrgument Ìist nÌso tnkes nn oµtionnÌ third nrgument for
the tyµe of dntn (such ns , , nnd so on).
Chapter 15 PerI DeveIopment
Another function in Iigures 1b-27 through 1b-29 is of µnrticuÌnr interest: .
This nnd severnÌ reÌnted functions retrieve resuÌts from executed MySQL stntements
by using the D8I. The functions nre Ìisted in TnbÌe 1b-1.
Table 15-1
Fetch functions to retrieve statement resuIts
Function nome 0escriµtion
Retrieves all data as a reference to an array.
Retrieves one value. Useful where one value is selected
as a result.
Retrieves results and places them in an array.
Retrieves data as a referenced array.
Retrieves data as a hash. Cperates similarly to
I beÌieve thnt exnmµÌes of the different functions serve better thnn n written
exµÌnnntion. Ior the exnmµÌes in Iigures 1b-27 through 1b-29, I retrieved onÌy the
first row of resuÌts. If you wnnt to retrieve more thnn one row using the
method, you hnve to Ìooµ through the resuÌts with n function such ns , ns
shown in Iigure 1b-8O.
Figure 15-30: Retrieving all the results for the query, using a
loop and
Part Iv DeveIopment
Iigure 1b-8O is n smnÌÌ usefuÌ µrogrnm for determining the hosts thnt n user is
nÌÌowed to connect from. The µrogrnm tnkes the usernnme to senrch for ns nn
nrgument nnd returns the nnmes of the hosts for which the user hns nn entry
in the tnbÌe of the MySQL dntnbnse.
If the field of the table is blank, the program from Figure 15-30 may
return incomplete or incorrect results.
Iigure 1b-81 shows nn exnmµÌe of the method for retrieving
query resuÌts. The method gets nÌÌ the resuÌts nt once nnd µÌnces them in nn nrrny
with ench row contnined ns µnrt of the nrrny. As this is n muÌti-dimensionnÌ nrrny,
the resuÌts need to be nccessed ns such.
Figure 15-31: The method in action
Iigure 1b-82 modifies the snme µrogrnm from the µrevious two figure iÌÌustrntions
to use the method. This method is frequentÌy used for retriev-
ing resuÌts where the stntement queries for more thnn one coÌumn.
The finnÌ two methods, nnd ,
both retrieve resuÌts ns references to nrrnys or hnshes, resµectiveÌy. With
the first row of resuÌts contnin the fieÌd nnmes for
the vnÌues with the nctunÌ vnÌues being stored therenfter. An exnmµÌe of
the method is shown in Iigure 1b-88.
Chapter 15 PerI DeveIopment
Figure 15-32: The method is frequently used as a
means to retrieve results from a query.
Figure 15-33: An example of the method for
retrieving results from a query
Part Iv DeveIopment
Iigure 1b-88 iÌÌustrntes the method. Notice thnt the first
cnÌÌ retrieves the host from the query, nnd the second cnÌÌ nctunÌÌy retrieves the
µnssword corresµonding to the second entry or second row of resuÌts. The third
method cnÌÌ retrieves nn entire row of resuÌts from the query nt once.
Not nÌÌ internctions with the dntnbnse require both n nnd
method cnÌÌ. The method ennbÌes you to execute stntements without hnving
to mnke two seµnrnte cnÌÌs ns with nnd . Like the
nnd methods, cnn ncceµt µÌncehoÌders. The µÌncehoÌders nre
question mnrks nnd shouÌd be incÌuded ns the Ìnst nrgument of the method
cnÌÌ. Iigure 1b-84 shows nn exnmµÌe of .
You cannot retrieve results using a method call, so it is not appropriate for
statements. The method does return the number of rows affected
by the statement. Therefore, it can be helpful to store this value for sanity check-
ing. In other words, you can compare the number of returned rows to ensure that
the value makes sense for the given query.
Figure 15-34: Using the method call to execute a statement
without having to prepare it in a separate statement
Another method, , cnn nssist to µrint resuÌts for testing
µurµoses whiÌe you nre µrogrnmming. cnÌÌs nnother method,
, to formnt the resuÌts nnd mnke them Ìook nicer ns outµut. The
method cnn tnke uµ to five nrguments. The syntnx is ns foÌÌows:
Chapter 15 PerI DeveIopment
The first nrgument, or the stntement hnndÌe, is required. The second nrgu-
ment, reµresented by in the exnmµÌe, is the mnximum Ìength for the
resuÌts to µrint. The third nnd fourth nrguments sµecify how you wnnt to seµnrnte
the Ìines nnd fieÌds resµectiveÌy. The defnuÌt for n Ìine brenk is the newÌine ( ),
nnd the defnuÌt for n fieÌd seµnrntor is n commn. The finnÌ nrgument, reµresented
by , is n µointer to n fiÌe hnndÌe to indicnte n fiÌe to which the resuÌts
shouÌd be dumµed (instend of to the screen) on . You don`t snve the
resuÌts of the method, rnther, you use PerÌ`s function
to µrint them.
More thnn one figure is necessnry to fuÌÌy iÌÌustrnte the syntnx nnd use of the
method. Iigure 1b-8b shows n bnsic instnnce, Iigure 1b-86
shows n bnsic usnge. Iigure 1b-86 demonstrntes setting n mnximum Ìength for
the second nrgument.
Figure 15-35: A basic use of the method
Iigure 1b-87 shows n usnge of fieÌd seµnrntors nnd the mnnunÌ setting of Ìine brenks,
Iigure 1b-88 demonstrntes the use of n fiÌe hnndÌe to dumµ resuÌts into n fiÌe instend
of to the screen.
Part Iv DeveIopment
Figure 15-36: Setting the maximum length to 8 with the second
argument of the method
Figure 15-37: Using an odd combination of characters as a field
separator and manually setting the line break to a newline
Chapter 15 PerI DeveIopment
Figure 15-38: Using a file handle to dump the results to a file instead
of to
Though not technicnÌÌy necessnry for the MySQL D8D, the method cnn
be used to recycÌe stntement hnndÌes nnd imµrove the rendnbiÌity of your code. The
method reÌenses the remnining resuÌts from n stntement hnndÌe nnd frees
it for nnother use. The MySQL D8D does not require you to finish before issuing
nnother µreµnre stntement, but doing so cnn grentÌy nssist in trncing code if you
need to go bnck nnd exnmine the code nt n Ìnter dnte.
IinnÌÌy, if you hnve to cÌenn uµ inµut received from n user or through n Web form,
you shouÌd know nbout the method thnt mnkes strings snfe for use inside
nn SQL stntement. It tnkes n soÌe nrgument ~the string to work with~nnd resuÌts
in nn SQL-snfe string. Iigure 1b-89 shows nn exnmµÌe of the method.
When using the method, you do not need to include quotes around the
strings inside queries. Notice, for example, the change in the way the variable
is called in Figure 15-39.
Part Iv DeveIopment
Figure 15-39: The method serves to make strings SCL safe.
ßuiIding ßasic AppIications
I`ve been mnking bnsic nµµÌicntions throughout this chnµter ~inside exnmµÌes of
error messnges, queries, nnd uµdntes. This section exµnnds on some of those exnm-
µÌes to show n bnsic PerÌ-bnsed D8I nµµÌicntion thnt uses functions nnd methods
discussed in the µrevious section. The gonÌ is to µreµnre you for buiÌding the nµµÌi-
cntions needed to mnnnge nn e-commerce Web site in n Ìnter section.
My5OL User Manager
An enrÌier exnmµÌe crented n smnÌÌ nµµÌicntion to Ìook nt the hosts from which n
given user is nÌÌowed to connect. I`ÌÌ exµnnd on thnt exnmµÌe here, mnking n more
µowerfuÌ user mnnnger to exnmine the µriviÌeges thnt n given user}host combinn-
tion hns. As n stnrting µoint, Iigure 1b-4O iÌÌustrntes the enrÌier µrogrnm.
This µrogrnm, though fine for the exnmµÌes, is woefuÌÌy inndequnte when it comes
to error checking. Ior exnmµÌe, if the fieÌd is bÌnnk, the µrogrnm evnÌuntes the
Ìooµ ns nnd stoµs iternting through it. Iurther, no inµut vnÌidntion is
done. I`ve mnde chnnges to the µrogrnm to mnke it check for errors nnd continue
through the Ìooµ even if the is bÌnnk. I`m doing some shennnignns
on the nctunÌ query to mnke sure thnt it nÌwnys returns something regnrdÌess of
whether the is bÌnnk. I ndded the user to the query resuÌts so ns to mnke it
nÌwnys evnÌunte for the Ìooµ. The µrogrnm is shown in Iigure 1b-41.
Chapter 15 PerI DeveIopment
Figure 15-40: A small program to query the hosts for a given user in
the MySCL grants database
Figure 15-41: Adding error checking and other improvements to a
small user management program with the Perl DßI
Part Iv DeveIopment
To mnke the µrogrnm even more usefuÌ I`ve ndded the nbiÌity to Ìook uµ the µrivi-
Ìeges thnt n given user}host µnir hns. This shows nn exnmµÌe of nnother tyµe of
stntement being µerformed on the MySQL dntnbnse other thnn n . The µro-
grnm is too Ìnrge to fit into n figure iÌÌustrntion but I`ve incÌuded the µrogrnm here
nnd nÌso some snmµÌe outµut in Iigure 1b-42.
Chapter 15 PerI DeveIopment
Figure 15-42: Usage examples of the MySCL User Management
program I've built with the DßI
Part Iv DeveIopment
Other ndditions nnd modificntions cnn be mnde to the simµÌe user mnnnger µro-
grnm thnt I`ve stnrted. I`d stiÌÌ Ìike to see better error checking in it ns weÌÌ ns more
fentures. Another modificntion thnt wouÌd be usefuÌ wouÌd be ennbÌing the µrogrnm
to ndd users to MySQL. If n user isn`t found, the µrogrnm couÌd nsk whether to ndd
the user nnd then nsk for the µnssword.
Chapter 19 examines the integration of Linux and MySCL and offers some addi-
tional programs for management and administration.
The user-management program given in this section is included on the CD-RCM
with this book.
ßuiIding Web Pages with the DßI
The e-commerce Web site thnt I`m buiÌding is mninÌy mnnnged with Web-bnsed
tooÌs. This offers the ndvnntnge of ennbÌing emµÌoyees to uµdnte the Web site from
nnywhere nnd with minimnÌ trnining. Iurther, the use of Web-bnsed tooÌs for mnn-
ngement Ìessens the risk of n user error nccidentnÌÌy ruining the dntn. This section
exnmines how to buiÌd Web µnges with dntn from n MySQL dntnbnse. This is in
µreµnrntion for the finnÌ section of this chnµter, which entniÌs the buiÌding of the
e-commerce Web site.
Progrnms written to internct with n Web server nre sometimes referred to ns
Common Gntewny Interfnce or CGI µrogrnms, sometimes even ns CGI scriµts. PerÌ
µrogrnms written for the Web nre nÌso sometimes cnÌÌed CGIs nnd nre tyµicnÌÌy exe-
cuted by the Web server. A better term wouÌd µrobnbÌy be Web nµµÌicntions. Ior
this section I`ÌÌ be referring to CGI µrogrnms or CGI scriµts interchnngenbÌy with
Web nµµÌicntions.
This section nssumes thnt you hnve n Web server running nnd the nbiÌity to execute
CGI µrogrnms with the PerÌ moduÌe . In the bnckground, µrogrnms written
for the Web oµernte the snme ns non-Web bnsed µrogrnms, the snme PerÌ routines
thnt work in other µrogrnms work with n CGI scriµt. It shouÌd be noted thnt becnuse
CGIs tyµicnÌÌy nre executed by non-µriviÌeged Web servers thnt not nÌÌ routines mny
work the snme.
Ior the µurµoses of this book, n sioiic poµc is one contnined entireÌy in n fiÌe, tyµi-
cnÌÌy with n or extension. The µnge rnreÌy chnnges, when it does, it is
edited by hnnd. A Jynomic poµc is n µnge buiÌt nutomnticnÌÌy (or by n µrocess other
thnn writing the HTML ench time), nnd it contnins dntn thnt chnnges often.
üo the
Chapter 15 PerI DeveIopment
A simpIe Web appIication to query My5OL
One of the bnsic buiÌding bÌocks of n CGI µrogrnm is the Web form cnÌÌed with the
HTML tng. The Web form cnÌÌs nn nction or µrogrnm to execute. This µro-
grnm is the CGI. As n simµÌe exnmµÌe, consider the Web µnge in Iigure 1b-48 ~n
simµÌe button crented on n stntic Web µnge, using the HTML shown Ìnter. When
cÌicked, thnt button cnÌÌs n CGI (contnined in Iigure 1b-44) nnd outµuts the resuÌts
to nnother Web µnge (ns shown in Iigure 1b-4b).
Figure 15-43: A static Web page with a form
button to call a CCI
The HTML to µroduce the stntic Web µnge from Iigure 1b-48:
Part Iv DeveIopment
Figure 15-44: The CCI that is executed when the form button is selected
Figure 15-45: The results from the CCI automatically build a
dynamic Web page.
Looking nt the code in Iigure 1b-44, notice the nddition of the directive.
This nddition tnkes ndvnntnge of the moduÌe nnd nÌÌ its fentures to ense the
burden on CGI µrogrnmmers. AÌso note the nddition of the foÌÌowing Ìine:
Chapter 15 PerI DeveIopment
The µrevious Ìine of code µrints nn HTML hender to the Web browser so it knows to
rend the outµut ns n Web µnge. IinnÌÌy, notice thnt the newÌine chnrncters ( ) in
the stntements hnve been reµÌnced with the HTML tng for n µnrngrnµh, .
Accepting input from a form
The µrogrnm shown in the µrevious section isn`t µowerfuÌ. I cnn enhnnce the µro-
grnm by nÌÌowing for user inµut, much Ìike the User Mnnngement µrogrnm shown in
µrevious exnmµÌes in this chnµter. I`ÌÌ ndd n text inµut box to ennbÌe the user to
inµut n usernnme to query ngninst the MySQL dntnbnse.
Much of the error checking thnt I ndded in the µrevious section is stiÌÌ nµµÌicnbÌe.
The HTML for the new version of the Web µnge is shown with the resuÌting µnge in
Iigure 1b-46.
Figure 15-46: An input form for a Web-based version of the
user manager program
The code for the Web version of the user mnnnger is ns foÌÌows:
Part Iv DeveIopment
Chapter 15 PerI DeveIopment
The code is bnsicnÌÌy the snme ns the code used to µroduce Iigure 1b-42. The
notnbÌe nddition or chnnge is the foÌÌowing Ìine:
Instend of getting the user for inµut from the commnnd Ìine in , the inµut
comes from the Web form. The function is contnined the moduÌe.
Some outµut exnmµÌes from this µrogrnm nre shown in Iigures 1b-47 nnd 1b-48.
Part Iv DeveIopment
Figure 15-47: The Web version of the MySCL user-manager
Figure 15-48: Another example of the Web version of the user-
manager program, calling the program with the © syntax
The exnmµÌes in this section show how ensy it is to write MySQL ennbÌed nµµÌicn-
tions for the Web in PerÌ. KnowÌedge of PerÌ is the key nnd beyond thnt imµÌement-
ing nnd modifying the µrogrnms for MySQL is n simµÌe tnsk.
Producing an E-Commerce Web site
The gonÌ of this section is to µroduce n successfuÌ e-commerce Web site (buiÌt using
the PerÌ D8I) thnt incÌudes behind-the-scenes tooÌs thnt nren`t on the Web, ns weÌÌ
ns the engine thnt runs the Web site itseÌf. The µrevious two sections hnve shown
Chapter 15 PerI DeveIopment
exnmµÌes of buiÌding bnsic nµµÌicntions using the PerÌ D8I, ns weÌÌ ns how to use
the PerÌ D8I to buiÌd dynnmic Web µnges bnsed on dntn in the MySQL dntnbnse.
This section combines those two comµonents to µroduce n fuÌÌy functionnÌ, nÌbeit
simµÌe, e-commerce Web site.
Database Iayout
The initinÌ dntnbnse design nnd Ìnyout hns nÌrendy been done in µrevious chnµters.
I`ve modified it somewhnt, nÌtering it ns I deveÌoµ the Web site. The dntnbnse Ìnyout
now is ns foÌÌows:
Part Iv DeveIopment
If you have the database on your server now, it would be a good time
to drop the database and start over with a fresh version, using the layout listed in
this section.
One tnbÌe, , needs to hnve n couµÌe of credit cnrd tyµes entered into it. I
couÌd buiÌd n Web µnge nnd CGI for this µurµose, but this dntn doesn`t chnnge fre-
quentÌy. MnnunÌ entry is quicker if nÌÌ you need µut in the dntnbnse is the two cnrd
tyµes thnt the site ncceµts.
ReÌnted to the inµut, the tnbÌe nÌso needs to be µoµuÌnted
with some initinÌ dntn. I`ÌÌ be seÌÌing music, movies, books, nnd video gnmes nt the
site so I`ÌÌ use three µroduct tyµes or cntegories.
ßuiIding an inventory-input program
The first steµ to getting the site onÌine is to get µroducts Ìisted in the dntnbnse so
µeoµÌe cnn Ìocnte them nnd buy them. To nccomµÌish this tnsk, I buiÌd n CGI thnt
ennbÌes ensy inµut of inventory items.
A stntic Web µnge cnn be used ns the initinÌ form for inµut. To inµut nny of the four
µroduct tyµes I`ÌÌ need to enter the nnme of the µroduct, the nrtist or nuthor, the
µrice, qunntity on hnnd, the mnnufncturer if nµµÌicnbÌe, nnd n short descriµtion of
the µroduct. The simµÌe stntic µnge is shown in Iigure 1b-49, the HTML to µroduce
thnt µnge is ns foÌÌows:
Chapter 15 PerI DeveIopment
Figure 15-49: A static page for entering inventory
The CGI to ndd the µroducts to the dntnbnse is ns foÌÌows:
Part Iv DeveIopment
Chapter 15 PerI DeveIopment
Part Iv DeveIopment
The µrogrnm doesn`t introduce nny new conceµts, so I`ÌÌ |ust highÌight some of its
inner workings. The µrogrnm mnkes use of the µercent sign (/) ns n wiÌdcnrd in the
SQL queries. The µrogrnm ncceµts inµut from n form nnd does some simµÌe error
checking on the incoming dntn. If the first Submit button wns cÌicked, the µrogrnm
then queries the µroduct dntnbnse for n simiÌnr µroduct. If n simiÌnr µroduct is
found, n µnge is sent to the user, with informntion nbout the existing µroduct
(see Iigure 1b-bO).
Figure 15-50: A similar product was found in the database, therefore
this page is produced with results from the database query.
If no simiÌnr µroduct is found, n confirmntion µnge is µroduced ns shown in
Iigure 1b-b1. Notice on thnt µnge thnt the existing vnÌues nre incÌuded ns hidden
tngs, you don`t see them in Iigure 1b-b1 but, they exist if you view the µnge
source. When the confirm button is cÌicked, those hidden tngs nre µnssed
bnck to the server the snme ns with nny other form.
IinnÌÌy, if the Confirmed button were cÌicked, the µrogrnm ndds the µroduct to the
To deveÌoµ this further, idenÌÌy you wouÌd ndd n method by which more thnn one
item couÌd be ndded nt once. In nddition, n method to senrch for
or is needed. Mnny ndditionnÌ dntnbnse tnbÌes nnd coÌumns couÌd
be ndded with items such ns wnrehousing, dnte of reÌense, other formnts, muÌtiµÌe
Chapter 15 PerI DeveIopment
cntegories, nnd so on. Look bnck nt the exnmµÌe in the µrevious section for n simµÌe
senrch function with the D8I. The next section deveÌoµs n µroduct senrch engine.
Figure 15-51: The confirm page produced by the inventory program
Please add some inventory to your sample database, using the inventory program
or any other method. You'll need it for the next section.
ßuiIding a simpIe product search engine
To get the fuÌÌ benefit of this section, mnke sure you`ve ndded n few (or more) µrod-
ucts to your dntnbnse. This section buiÌds n senrch engine to Ìook for µroducts in
the dntnbnse. The bnsis for the senrch engine is (ngnin) n stntic µnge, which then
Ìinks to n CGI to µroduce dynnmic µnges with the resuÌts.
I`ÌÌ be mnking n simµÌe senrch box thnt wouÌd µrobnbÌy go on the mnin µnge of the
site ~nnd n more comµÌicnted senrch µnge with more oµtions (µrobnbÌy n seµnrnte
µnge). Here is the HTML thnt µroduces the simµÌe senrch µnge or box:
Part Iv DeveIopment
The simµÌe senrch µnge is shown in Iigure 1b-b2.
Figure 15-52: The simple search page
The HTML for µroducing the fuÌÌ senrch µnge Ìooks Ìike this:
The fuÌÌ senrch µnge is shown in Iigure 1b-b8.
Chapter 15 PerI DeveIopment
Figure 15-53: The full search page
The code to mnke the senrch functions work is ns foÌÌows:
Part Iv DeveIopment
Chapter 15 PerI DeveIopment
Part Iv DeveIopment
As with other µrogrnms shown ns exnmµÌes, this one couÌd nÌwnys be imµroved ~
sny, with better error checking nnd hnndÌing, ns weÌÌ ns with more robust senrching
cnµnbiÌities. 8ut you get the iden.
The µrogrnm works in much the snme wny ns the inventory µrogrnm, it gets µnrnm-
eters from the incoming form nnd µÌnces them into vnrinbÌes. Irom there, it mnkes n
decision bnsed on which button wns seÌected (simµÌe senrch or more comµÌicnted
senrch). Notice thnt during the Ìooµ to retrieve resuÌts n decision is mnde
bnsed uµon the qunntity on hnnd of the given µroduct. Aside from thnt (nnd n bit
of PerÌ here nnd there to mnke things work correctÌy), you hnve n fuÌÌy functionnÌ
senrch engine. An exnmµÌe of the simµÌe senrch resuÌt is shown in Iigure 1b-b4.
Figure 15-54: Results from the simple search
The more comµÌicnted senrch uses nn if both the µroduct nnme nnd nrtist nre
fiÌÌed in. A snmµÌe resuÌt is shown in Iigure 1b-bb.
Chapter 15 PerI DeveIopment
Figure 15-55: The full search page in action
IinnÌÌy, if no resuÌts nre found, thnt notificntion is sent to the visitor ns weÌÌ, ns
shown in Iigure 1b-b6.
Figure 15-56: The page when no results are found
Part Iv DeveIopment
The programs contained in this section are available on the CD-RCM.
Present and future expansion
The site hns n stnrt. It`s nowhere nenr rendy to go onÌine nnd tnke orders.
A shoµµing-cnrt CGI must be buiÌt, ns weÌÌ ns more robust inventory cnµnbiÌities.
Using n combinntion of cookies, knowÌedge of PerÌ, nnd the idens in this chnµter, it
shouÌdn`t be too much of n stretch to tnke the site to the next steµ.
The PerÌ D8I is n generic interfnce used by mnny tyµes of RD8MS to ennbÌe PerÌ
µrogrnms to work with dntnbnses. MySQL hns n dntnbnse driver (D8D) to work
with the D8I nnd ennbÌe the µrogrnmmer to write µowerfuÌ MySQL-ennbÌed PerÌ
8oth the D8I nnd the D8D for MySQL cnn be obtnined nt your nenrest CPAN
mirror or nt .
The D8I tnkes ndvnntnge of hnndÌes to ennbÌe the deveÌoµer to communicnte
with n dntnbnse server. There nre driver hnndÌes such ns MySQL, dntnbnse
hnndÌes for connecting to the dntnbnse server, nnd stntement hnndÌes for
working with SQL stntements.
The deveÌoµer using the D8I communicntes with the dntnbnse using nn
ob|ect-oriented nµµronch. Dntnbnse hnndÌes nre crented mnnunÌÌy by the
user nnd cnn be destroyed by the user or nutomnticnÌÌy by PerÌ.
The D8I nÌso incÌudes configurnbÌe error checking. 8y defnuÌt, error checking
is nutomntic. The µrogrnmmer cnn controÌ whether error checking is mnnunÌ,
nutomntic, or n combinntion of both even within the snme µrogrnm.
The D8I incÌudes mnny functions for working with dntnbnses, not |ust MySQL.
These incÌude functions to retrieve dntn such ns , ,
nnd others.
The D8I ennbÌes the PerÌ µrogrnmmer to combine the µower of PerÌ with the
fentures of MySQL to mnke nµµÌicntions thnt run from the commnnd Ìine or in
n CGI for the Web.
üo the
few yenrs bnck, I devoted weeks to Ìenrning the PerÌ-
D8I interfnce to MySQL so I couÌd crente MySQL-PerÌ
nµµÌicntions for use in µÌnces other thnn the Web. When I did
stnrt writing Web-bnsed nµµÌicntions, I wns so immersed in
the D8I thnt I negÌected to Ìook nt other MySQL deveÌoµment
Ìnngunges for the Web, I hnd confidence in PerÌ ns n µowerfuÌ,
stnbÌe deveÌoµment Ìnngunge.
Then one of my good friends toÌd me I shouÌd be using yet
nnother Ìnngunge ~PHP. Lven though I hnd sµent n Ìong time
Ìenrning the D8I, I dove into PHP~nn ensy nnd µowerfuÌ
deveÌoµment Ìnngunge in its own right.
Why Ìenrn PHP" This is n vnÌid question. If you don`t need to
write Web-bnsed nµµÌicntions for MySQL, then PHP mny be of
Ìimited usefuÌness for you. If, however, you do write Web-
bnsed nµµÌicntions nnd need them to internct with MySQL,
PHP couÌd be |ust whnt you`re Ìooking for. PHP is extremeÌy
usefuÌ for interncting with n MySQL dntnbnse, is somewhnt
simiÌnr to PerÌ, nnd (dnre I sny) is somewhnt intuitive.
This chnµter exnmines how to instnÌÌ PHP nnd mnke it work
with MySQL. I nÌso cover some bnsic PHP conceµts, ns weÌÌ ns
PHP-MySQL functions. The chnµter concÌudes with n few
exnmµÌe nµµÌicntions. (They`re n ÌittÌe off the benten trnck ~
no Guestbook nµµÌicntion exnmµÌes!)
PHP InstaIIation
UnfortunnteÌy, instnÌÌing PHP is not nenrÌy ns ensy ns instnÌÌing
the PerÌ D8I nnd MySQL D8D. However, the deveÌoµers of PHP
hnve tnken grent µnins with their documentntion, it`s some of
the best I`ve ever seen. This incÌudes documentntion of the
instnÌÌntion softwnre, ns weÌÌ ns further covernge on their Web
site, .
C H A P I E k
ln Ihis Chopler
lnslolllng PHP
Gelllng down lo
bross locks wllh PHP
Conllgurlng PHP
Llsllng PHP MySCL
Bulldlng MySCL
enobled oppllcollons
wllh PHP
Part Iv DeveIopment
This section concentrntes on instnÌÌing PHP on n Linux system, using the stnndnrd
µrocess bnsed on nnd commnnds. Your distribution of Linux mny
hnve n µncknge-mnnngement tooÌ, in which cnse you mny nÌrendy hnve n comµiÌed
version of PHP nnd Aµnche to work with. In nddition, you mny nÌrendy hnve PHP
instnÌÌed, but it mny not be MySQL-ennbÌed. If such is the cnse, you`ÌÌ need to rein-
stnÌÌ n MySQL-ennbÌed version of PHP. IinnÌÌy, you`ÌÌ µrobnbÌy hnve to reconfigure
your Web server to work with PHP, so the chnµter covers configuring Aµnche (the
stnndnrd Linux Web-server softwnre) with PHP.
What you need for instaIIation
To instnÌÌ n MySQL-ennbÌed version of PHP, you need three essentinÌ ingredients
on hnnd:
the PHP softwnre itseÌf
the source code for Aµnche (or whntever Web server you`re running)
the MySQL cÌient Ìibrnries
Iirst, find out whether you nÌrendy hnve PHP instnÌÌed for use with Aµnche (nnd
whether it`s ennbÌed for MySQL). On the Web server, tyµe the foÌÌowing commnnd:
Look for n Ìine simiÌnr to this one:
If you see thnt Ìine, congrntuÌntions ~PHP is µrobnbÌy nÌrendy instnÌÌed nnd
ennbÌed on your Web server. AÌternntiveÌy, Ìook for Ìines Ìike these:
If you see those Ìines, then your server is configured to Ìond dynnmic moduÌes ~
nnd you mny hnve PHP suµµort nvniÌnbÌe.
Lven if you hnve PHP instnÌÌed, it mny not be MySQL-ennbÌed. To test nn existing
instnÌÌntion of PHP~nnd simuÌtnneousÌy check it for MySQL suµµort ~you shouÌd
buiÌd n test PHP µnge. SimµÌy crente n reguÌnr fiÌe, snve it with the fiÌennme
, nnd µÌnce it in the µubÌic or foÌder, |ust ns you wouÌd nny
µnge. The fiÌe itseÌf needs no more thnn the foÌÌowing contents:
If everything is configured correctÌy, you shouÌd see n µnge simiÌnr to the one in
Iigure 16-1.
Chapter 16 PHP DeveIopment
Figure 16-1: A server with PHP enabled and configured correctly
If, for whntever renson, the µnge does not come uµ, there is µrobnbÌy something
wrong with your PHP configurntion. Don`t worry! I wnÌk through the instnÌÌntion
of PHP in this chnµter, you cnn reconfigure ns µnrt of the instnÌÌntion µrocess.
ScroÌÌ down in the PHP informntion µnge nnd Ìook for the section on MySQL,
ns shown in Iigure 16-2.
In the exnmµÌe in Iigure 16-2, MySQL is ennbÌed with PHP. If your µnge Ìooks simiÌnr,
you cnn skiµ the sections of this chnµter concerned with instnÌÌing nnd configuring
PHP for use with MySQL.
If PHP is instnÌÌed on your system but MySQL is not ennbÌed, you`ÌÌ wnnt to reinstnÌÌ
PHP to ennbÌe MySQL.
Where to get the software
The mnin distribution site for PHP is . I`ve nÌso incÌuded PHP
on the CD-ROM with this book (the PHP Web site µrobnbÌy hns n newer version).
The CD-RCM with this book includes the latest version of PHP available as of press
time. This version works with the examples given in the book.
üo the
Part Iv DeveIopment
Figure 16-2: The MySCL section of the PHP information page
InstaIIing PHP on a Linux system
Whether this is your first time instnÌÌing PHP or n reinstnÌÌntion (to ennbÌe MySQL
on n system thnt nÌrendy hns PHP instnÌÌed), this section cnn he̵. As n µrerequisite,
you shouÌd nÌrendy hnve MySQL instnÌÌed ~incÌuding the Ìibrnries for MySQL.
In nddition, you shouÌd hnve n Web server running.
This section examines the installation of PHP with Apache as the Web server soft-
ware. If your Web server is not Apache, refer to the documentation included with
your Web server -and with PHP itself -for help with installation.
InstaIIing and configuring PHP
The steµs for instnÌÌing nnd configuring PHP on n Linux system (with Aµnche ns
the Web server) nre ns foÌÌows:
1. Unµnck the PHP nrchive by issuing the foÌÌowing commnnd:
Ior exnmµÌe, Iigure 16-8 shows PHP unµncked to its defnuÌt directory.
Chapter 16 PHP DeveIopment
Figure 16-3: Unpacking the PHP archive
2. Chnnge into the newÌy crented PHP directory.
If you have an existing PHP source directory that you've previously configured
from, be sure to either remove the directory or at remove the file
contained therein.
It is nt this µoint where decisions must be mnde regnrding your existing
Aµnche instnÌÌntion ns weÌÌ ns other oµtions, you mny wnnt to ennbÌe with
PHP. I`ÌÌ show nn exnmµÌe configurntion thnt ennbÌes MySQL on nn Aµnche
server thnt uses Dynnmic Shnred Ob|ects.
3. To configure PHP in the environment described in Steµ 2, tyµe
You mny receive nn error messnge simiÌnr to thnt in Iigure 16-4.
4. If you receive the error messnge shown in Iigure 16-4, note whnt the messnge
µoints out nnd resµond nccordingÌy. In this instnÌÌntion, I needed to ndd the
µnth to the moduÌe for Aµnche. Iirst I needed to find it:
Ior the exnmµÌe, is Ìocnted in n couµÌe of µÌnces, I chose the one in
(your Ìocntion mny be different).
Part Iv DeveIopment
Figure 16-4: An error that occurs during PHP configuration
5. To teÌÌ the PHP scriµt where it cnn find , be sure to remove
the existing fiÌe with the foÌÌowing code:
An error simiÌnr to the µrevious one cnn occur if the scriµt cnn`t
find the necessnry MySQL Ìibrnries. If thnt hnµµens, you hnve two µossibÌe
* Add the µnth ns µnrt of the oµtion.
* Add the µnth to nnd run . (I`ve hnd better
success with this oµtion.)
If the scriµt runs successfuÌÌy, congrntuÌntions! AÌthough there`s
more to come, you now hnve n bnsic configurntion in µÌnce to nccommodnte
PHP. You mny, however, receive one or more wnrnings when the
scriµt comµÌetes its run, n couµÌe of these nre shown in Iigure 16-b.
6. Continue the instnÌÌntion µrocess by buiÌding the softwnre, tyµe the foÌÌowing
Chapter 16 PHP DeveIopment
Figure 16-5: Some warnings produced by the PHP configure script
When you µress Lnter, the µrocess begins. How Ìong it tnkes deµends on
the sµeed nnd resources nvniÌnbÌe on your mnchine.
If the process fails this time, don't worry. PHP installation can sometimes be
difficult; often the build fails because a library is not found. Normally you can get
good clues to what went wrong by closely examining the last few lines of code just
before the point at which the build process died. For additional help, try the PHP
Web site's section of search functions and FACs. If you're getting error messages
like those in Figure 16-5, chances are someone else has too-and there could be
a simple fix.
If the µrocess is successfuÌ, congrntuÌntions!
7. InstnÌÌ the softwnre, using the foÌÌowing commnnd:
NormnÌÌy this is the finnÌ bnsic steµ in the buiÌd µrocess. You`re not done yet
though. In µnrticuÌnr, check inside your Aµnche Web server configurntion fiÌe
(usunÌÌy cnÌÌed ) for some Ìines Ìike those shown in Iigure 16-6.
Part Iv DeveIopment
Figure 16-6: Lines relating to PHP 4.x, as they appear in the Apache
Web server configuration file (httpd.conf)
8. Uncomment the Ìines thnt reÌnte to PHP 4.x by removing the µound sign ( )
from in front of those Ìines.
9. Snve the uncommented configurntion fiÌe nnd then restnrt the Web server
Truthfully, you could get by with just uncommenting the first line that mentions the
The newÌy uncommented Ìines (which ennbÌe PHP when the Web server
restnrts) nre shown in Iigure 16-7.
Don't forget to save the file and then restart the Web server for the changes to take
effect. Simply restarting Apache will work, no need to reboot the entire machine;
this is Linux!
10. Preµnre to test your new configurntion by crenting n PHP fiÌe within the
(or within n µubÌicÌy nvniÌnbÌe HTML directory) on your Web server.
Figure 16-7: Uncommenting the PHP-related lines in httpd.conf
enables PHP in the Apache Web server.
Chapter 16 PHP DeveIopment
Ior exnmµÌe, you couÌd crente n fiÌe cnÌÌed with the foÌÌowing
11. Point your Web browser to your test µnge (which shouÌd resembÌe Iigure 16-8)
nnd scroÌÌ down to the MySQL section to verify thnt MySQL is ennbÌed.
If the MySQL section in your test µnge indicntes n successfuÌ PHP instnÌÌntion,
congrntuÌntions! You cnn now skiµ nhend nnd stnrt buiÌding MySQL-ennbÌed
PHP nµµÌicntions.
Lven nfter n hnssÌe-free instnÌÌntion µrocess, however, two common errors cnn
croµ uµ:
º The µnge shows uµ on-screen ns source code (ns shown in Iigure 16-9).
º The browser µromµts you to Snve or Oµen the fiÌe (it shouÌdn`t).
If either of these errors hnµµens to you, foÌÌow the troubÌeshooting steµs
given here (which use Iigure 16-9 ns nn exnmµÌe).
Figure 16-8: A successful PHP installation as shown by the MySCL section of the
phpinfo( ) function
Part Iv DeveIopment
Figure 16-9: A common error that can occur after
the installation process itself went smoothly
IroubIeshooting a page that shows up as source code
IoÌÌow these steµs to correct the error deµicted in Iigure 16-9:
1. Check thnt you nctunÌÌy ennbÌed PHP in the configurntion fiÌe for
Aµnche (by uncommenting the PHP-reÌnted Ìines in the configurntion fiÌe).
2. Check the Ìine thnt normnÌÌy ennbÌes PHP to determine whether it`s encÌosed
in n directive. If it is, then it`s effectiveÌy hidden from the mnin
configurntion. If it is inside of n virtunÌ directive, you shouÌd move the Ìine out-
side of the directive so thnt it is nµµÌied nt the mnin server ÌeveÌ.
3. Mnke sure you restnrted the Web server softwnre, exnmine nny ÌogfiÌes cre-
nted when it restnrted.
4. Another µossibiÌity is thnt the configurntion fiÌe isn`t the one being rend.
Senrch the comµuter for other configurntion fiÌes (
). One those fiÌes mny be the nctunÌ configurntion fiÌe for
Aµnche on your server nnd you`ÌÌ need to edit thnt fiÌe.
5. Check the Web server softwnre itseÌf to determine whether it hns PHP
I buiÌt the exnmµÌe ns n dynnmic moduÌe, if you nre working with n dynnmic
moduÌe, mnke sure thnt when you run
you see Ìines simiÌnr to these:
Chapter 16 PHP DeveIopment
If a number of other modules are compiled in the dynamic module, chances are
you'll have recompile Apache. Although Apache installation is outside the scope of
this book, Apache does include a document with its installation files that can help:
. This document contains detailed instructions for PHP
installation. Also, don't forget to check the PHP and Apache Web sites; if you've
encountered a problem, someone may have already tackled it.
6. Coµy the fiÌe to the PHP instnÌÌ directory
nnd nnme it .
The function teÌÌs you where to µut the configurntion fiÌe within
your server`s fiÌe system. UsunÌÌy is the correct µÌnce, but
your instnÌÌntion mny demnnd n different Ìocntion (such ns the directory).
7. If you nÌrendy hnve n instnÌÌed, nvoid overwriting it, use the
oµtion with the commnnd, ns foÌÌows:
The configurntion of this fiÌe is now comµÌete, your PHP cnµnbiÌity shouÌd be
rendy to use.
ßrass Iacks: PHP EssentiaIs
On the nssumµtion thnt it`s wise to Ìenrn to wnÌk before running or |umµing (nt Ìenst
where the use of PHP with MySQL is concerned) this section µresents some bnsics
of PHP. Though µowerfuÌ, PHP is reÌntiveÌy simµÌe to Ìenrn, regnrdÌess of µrevious
µrogrnmming exµerience. (NnturnÌÌy such exµerience is he̵fuÌ, esµecinÌÌy if you`ve
µrogrnmmed with n Ìnngunge such ns PerÌ).
This section demonstrntes essentinÌ PHP conceµts by crenting n simµÌe Web µnge
or two. Though by no menns mennt ns n comµÌete exnminntion of PHP (or nn
exhnustive cntnÌog of its bnsics), the section Ìnys the groundwork for working with
the Ìnngunge.
For quick access to more detailed information on PHP, refer to
A PHP Web page
PHP cnn be used to buiÌd comµÌicnted nµµÌicntions thnt do comµÌex cnÌcuÌntions,
work with the fiÌe system, obtnin nnd work with dntn from forms, nnd mnniµuÌnte
dntn inside mnny dntnbnse systems. PHP cnn nÌso be nn esµecinÌÌy µowerfuÌ tooÌ for
crenting nnd oµernting Web µnges, n PHP-ennbÌed Web µnge cnn µerform functions
nnd cnÌcuÌntions disµersed throughout the HTML code thnt mnkes uµ the µnge.
Part Iv DeveIopment
PHP code cnn be encÌosed within nn HTML µnge, or PHP cnn µroduce the HTML
itseÌf. RegnrdÌess of the method, PHP sections within n fiÌe nre encÌosed Ìike this:
These tngs, nÌong with the code between them, indicnte to the Web server thnt it
must µnrse the indicnted stntements sµecificnÌÌy ns PHP. Ior exnmµÌe, the foÌÌowing
code sniµµet crentes n bnsic µnge (Iigure 16-1O shows the resuÌt):
In Iigure 16-11, you cnn see nn exnmµÌe of interwoven PHP nnd HTML. The foÌÌow-
ing code sniµµet µroduces the resuÌts deµicted in the figure:
Here n PHP section begins the code, concÌudes its own oµerntion, nnd mnkes
wny for reguÌnr HTML. The entire code sniµµet ends with nnother section of PHP.
Iigure 16-11 shows the resuÌt.
Chapter 16 PHP DeveIopment
Figure 16-10: The results of the code shown to
create HTML within PHP code
Figure 16-11: An example of PHP and HTML interwoven
Part Iv DeveIopment
PHP and forms
As stnted µreviousÌy, PHP is grent for working with dntn gnthered from Web forms.
8ecnuse you cnn combine HTML nnd PHP ensiÌy, the form dntn cnn be mnniµuÌnted
nnd then n resuÌt µnge served without ever Ìenving the snme PHP µrogrnm.
VnrinbÌes in PHP do not hnve to be exµÌicitÌy decÌnred nnd nre cnÌÌed for the most
µnrt with the doÌÌnr sign ( ). This incÌudes nrrnys nnd mnrks n noticenbÌe difference
from PerÌ where nrrnys nre indicnted with the oi symboÌ ( ).
Web forms nre ensiÌy hnndÌed with PHP. SimµÌy crente the form ns you wouÌd nny
HTML Web form, cnÌÌing n PHP µnge ns the nction. Often the snme µnge thnt µroduces
the form is nÌso the nction of the form. Ior exnmµÌe, consider the foÌÌowing code:
The form nnd the resuÌts nre shown in Iigures 16-12 nnd 16-18.
Figure 16-12: The simple form created with the code example in PHP
Chapter 16 PHP DeveIopment
Figure 16-13: The results when a name is entered into the form
If no nnme is entered into the form, the code simµÌy regenerntes the form.
The simµÌicity with which this scennrio is hnndÌed is |ust the tiµ of the iceberg
when it comes to buiÌding dynnmic µnges with PHP. I nm n PerÌ diehnrd, but µroduc-
ing the snme resuÌt in PerÌ simµÌy wouÌd not be ns ensy or eÌegnnt.
The rest of this chnµter Ìooks nt functions nnd exnmµÌes in PHP thnt nre esµecinÌÌy
reÌevnnt to MySQL ~stnrting with PHP configurntion.
PHP My5OL Configuration
PHP doesn`t require much configurntion for it to work grent with MySQL. The reÌe-
vnnt configurntion is contnined in the fiÌe usunÌÌy Ìocnted in
or . This section exnmines those configurntion oµtions.
Configuration settings
The configurntion fiÌe for PHP ( ) is usunÌÌy Ìocnted in the
directory, but it mny be in or nnother Ìocntion on your fiÌe system. The
function wiÌÌ teÌÌ you where the fiÌe is Ìocnted. See the µrevious section
for informntion on how to use the function in n simµÌe µnge.
The PHP configurntion fiÌe hns n section devoted to MySQL, ns Iigure 16-14
Part Iv DeveIopment
Figure 16-14: The MySCL section of the php.ini configuration file
The functions nnd their definitions nre Ìisted in TnbÌe 16-1.
Table 16-1
My5OL Configuration Options for PHP
Dµtion 0elinition
Enables connections to stay active. Default
Maximum number of default connections. Default
Maximum number of total connections. Default
Port to connect to the server on. Default blank, read from
Socket to connect to server on. Default blank, read from
Sets the host to connect to. Default blank.
mysql.default_user Sets the user to connect as. Default blank.
Set a global password to authenticate as. Default blank.
Chapter 16 PHP DeveIopment
The settings contnined in the do not need to be set for PHP to work with
For security reasons, I strongly recommend against setting the user or password
/ns/de the . Anyone with read access to the file (or who can write a PHP
script and get at the server variables) can determine the settings.
PHP My5OL Functions
PHP incÌudes n Ìnrge number of buiÌt-in functions ~some of which cnn tnke the
µÌnce of existing MySQL functions or stntements to enhnnce or strenmÌine oµern-
tions. This section exnmines some functions thnt nccomµÌish these gonÌs with
MySQL nnd PHP, nnd µrovides exnmµÌes.
Ihe functions
The best wny to hnndÌe this nbundnnce of MySQL-reÌnted functions in PHP is to Ìist
them in n tnbÌe. TnbÌe 16-2 does so.
Table 16-2
PHP My5OL Functions
Function 0elinition
Returns number of rows affected by a non-
Changes the user currently logged in to the program.
Closes the connection to the MySCL server.
Connects to the MySCL server.
Creates a MySCL database.
Moves the internal pointer one row.
Returns the name of the current database.
Issues a query to the database.
Drops or deletes a database.
Returns the error number of the current error message.
Returns the text for the current error message.
Takes a string and returns a MySCL-safe quoted string.
Part Iv DeveIopment
Table 16-2 (Cont/nµed)
Function 0elinition
Returns an array that can be numerical and/or associative.
Returns an associative array (similar to the fetchrow_array
command in Perl).
Returns an object associated with a column.
Returns the length of the result set.
Returns an entire row as an object.
Returns a row of the result set.
Returns the flags from a result set.
Returns the field name of a result set.
Returns length of the field.
Moves the pointer of the result set.
Returns the name of the table associated with the field.
Returns column type.
Clears the results, empties the memory associated with them.
Returns information on the client connection.
Returns information on the MySCL host.
Returns information on the MySCL protocol version.
Returns information on the MySCL server itself.
Returns the ID of a column associated with the last INSERT
Returns a list of available databases.
Returns a list of available fields.
Returns a list of tables available within a database.
Returns the number of fields in a given table.
Returns the number of rows in a result set.
Creates a persistent connection to the server.
Issues a query.
Returns the result set.
Connects to a given database within a server.
Returns the table name.
Sends a query without regard for return values.
Chapter 16 PHP DeveIopment
As I stnted, quite n few of the numerous functions nre substitutes for MySQL
stntements ~for exnmµÌe, reµÌnces . I`ÌÌ use
mnny of these functions in the code exnmµÌes in uµcoming sections.
Connecting to My5OL with PHP
It`s finnÌÌy time to buiÌd the first PHP MySQL µrogrnm of the chnµter ~though I suµ-
µose the smnÌÌ exnmµÌe µnge you buiÌt with the function counts n ÌittÌe.
So this wiÌÌ be the second PHP MySQL µrogrnm but the first one where you wiÌÌ
nctiveÌy connect to MySQL.
You cnn connect to MySQL by using the function, you terminnte
the connection with the function. Like the PerÌ D8I, the
function requires some µnrnmeters for connecting.
You can specify some connection parameters within the configuration
The syntnx for the function is ns foÌÌows:
Consider this exnmµÌe:
As you wouÌd exµect, you cnn set the vnÌues of , , nnd to
Once the connection is mnde, stntements nre issued or nnother function is used.
UnÌike PerÌ, PHP does not use the conceµt of hnndÌes for working with MySQL.
Therefore, stntements cnn be sent simµÌy through the function nnd
retrieved through one of the functions.
Protecting PHP authentication information
A significnnt security issue with PHP is stornge of the nuthenticntion informntion for
MySQL. PHP µuts nuthenticntion informntion in the PHP fiÌe ~where it`s rendnbÌe
by nnyone on the Web server. One wny nround this µotentinÌ security hoÌe is to
µÌnce nuthenticntion informntion inside n funciion. in n fiÌe seµnrnte from the PHP
µrogrnm being cnÌÌed by the Web server. The fiÌe contnining the function must be
rendnbÌe by the user running the Web server, but shouÌd not be worÌd-rendnbÌe.
Part Iv DeveIopment
Ior exnmµÌe, suµµose I crente n simµÌe PHP fiÌe cnÌÌed µ, µÌnce it in n
directory thnt the Web server cnn nccess, nnd use it for executing PHP fiÌes. The
fiÌe`s entire contents Ìook Ìike this:
The fiÌe is owned by the user nccount thnt the Web server runs ns (usernnme
), nnd onÌy thnt user hns rend-write ( ) nccess. The Web server cnn rend the
contents of the fiÌe but no other users cnn (not even if they`re on the snme server).
AÌtering the smnÌÌ connection commnnds I hnve given here, I use the PHP
function. The contents of the fiÌe incÌuded wiÌÌ be nvniÌnbÌe for the PHP
scriµt to execute. The code thnt uses the function Ìooks Ìike this:
Lxnminntion of the code revenÌs the function foÌÌowed by the
function. I`ve nÌso used the function to ndd some error
checking. If the connection cnnnot be mnde, nn error messnge is returned nnd exe-
cution of the scriµt terminntes. The function is reÌnted to two
other functions with comµÌementnry cnµnbiÌities:
is the oµµosite of . You cnn use
to cÌose or terminnte n connection to n MySQL server. When
n scriµt comµÌetes its execution, however, its session terminntes nutomnti-
cnÌÌy, normnÌÌy you don`t hnve to use .
oµens n µersistent connection to n MySQL server. This
tyµe of connection remnins nctive even nfter the PHP scriµt terminntes.
5eIecting data from a My5OL database
The functions in TnbÌe 16-2 incÌude n number of functions for issuing stntements or
µerforming vnrious tnsks on the MySQL server. Some of the functions reµÌnce MySQL
functions such ns those for crention of n dntnbnse nnd Ìisting dntnbnses nnd tnbÌes.
mysqI_seIect_db and mysqI_query_db
Once n connection is mnde to the MySQL server, you cnn internct with n sµecific
dntnbnse by using the function, which tnkes the nnme of thnt
Chapter 16 PHP DeveIopment
dntnbnse ns nn nrgument. The function is n bit more direct,
it sends n query to n sµecified dntnbnse without using the
function. The syntnx for both stntements is ns foÌÌows:
The function sends queries nnd other stntements to the MySQL
server. To retrieve the resuÌts of such n query or stntement, use n function
such ns or . The resuÌting vnÌue(s) cnn then
be µnrsed nnd worked with, Ìike nny other vnrinbÌes. LxnmµÌes of nre
shown throughout the rest of the chnµter.
The function is one method for retrieving the resuÌts of n
MySQL query. Lxnmine the foÌÌowing code:
This code exnmµÌe connects to the MySQL server, seÌects the MySQL grnnts
dntnbnse, nnd then issues n stntement. The resuÌts from the
stntement nre µrinted in tnbÌe form, Iigure 16-1b shows the resuÌting outµut.
Part Iv DeveIopment
Figure 16-15: Results from the PHP code example
The code snmµÌe shown in this section uses to get the resuÌts
from the query in nn nssocintive nrrny. Then, by using the PHP functions
nnd , I cnn wnÌk through the resuÌts row by row~nnd µÌnce them in n
simµÌe HTML tnbÌe.
Using is the same as using with
as the second argument.
I couÌd use the function for this query, but the resuÌts wouÌdn`t
go ns niceÌy into n tnbÌe formnt. The foÌÌowing code shows the µrogrnm using
, Iigure 16-16 shows the resuÌts.
Chapter 16 PHP DeveIopment
Figure 16-16: Using mysql_fetch_row to retrieve the results from a query
Part Iv DeveIopment
It is sometimes usefuÌ to find out the number of rows returned by n MySQL query.
The function is simµÌy cnÌÌed with the resuÌt set ns the nrgument.
onÌy works with stntements. The function doesn`t work
with other SQL stntements such ns , , nnd so forth, ns in the
foÌÌowing exnmµÌe:
The argument for is the database connection identifier. In
the examples I've shown, I've used the variable name for the function
call for .
Inserting and updating data in My5OL
Inserts nnd other stntements nre µerformed |ust Ìike stntements, using the
function. Ior exnmµÌe, to ndd n row, the syntnx is simµÌe:
The function serves to determine the number of rows
nffected by n non- oµerntion such ns nn or n . Adding
to the µrevious nµµÌicntion yieÌds the foÌÌowing code
Chapter 16 PHP DeveIopment
The resuÌts from this modified code nre shown in Iigure 16-17.
You run the function with the database connection
name from -instead of the result set -serving as the argu-
ment. This necessary substitution is a common source of confusion among first-
time PHP programmers.
Figure 16-17: Using mysql_affected_rows to see how
many rows were affected by the operation
Part Iv DeveIopment
ßuiIding My5OL-EnabIed AppIications
With PHP
The µrevious sections of this chnµter µrovided exnmµÌes of connecting to MySQL
through PHP, nÌong with some functions used to work with dntn nnd dntnbnses. This
section buiÌds on those exnmµÌes to µroduce some PHP nµµÌicntions.
A PHP version of the user manager
Chnµter 1b buiÌds n simµÌe user-mnnnger µrogrnm in PerÌ, it queries the tnbÌe
of the MySQL grnnts dntnbnse. This section µorts thnt snme PerÌ nµµÌicntion over to
PHP. (I incÌude the PerÌ code for reference here so you cnn ensiÌy see the chnnges
needed to µort it to PHP.) The PerÌ version of the code Ìooks Ìike this:
Chapter 16 PHP DeveIopment
Part Iv DeveIopment
Porting the code to PHP is reÌntiveÌy ensy becnuse of some key simiÌnrities between
PerÌ nnd PHP. The PHP version of the user-mnnnger µrogrnm code Ìooks Ìike this:
Chapter 16 PHP DeveIopment
Iigures 16-18 through 16-21 show sniµµets of the PHP version, nÌong with exnmµÌe
runs of the µrogrnm.
Figure 16-18: The form built by the PHP version
of the user manager
Part Iv DeveIopment
Figure 16-19: The results with the PHP version of the
user manager look the same as those from the Perl
CCI version.
Figure 16-20: The privilege lookup with the PHP
version of the user manager
Chapter 16 PHP DeveIopment
Figure 16-21: Cuerying for privileges works the same
with the PHP version as with the Perl CCI version.
Examination of the PHP version of the user manager
Mnny of the user mnnnger`s bnsic functions nre the snme in both the PerÌ nnd PHP
versions ~in µnrticuÌnr, functions such ns nnd . Looking nt the first bits of
the PHP code, notice thnt the µrogrnm no Ìonger stnrts with
(which mnkes sense, since this PHP version isn`t n PerÌ µrogrnm). An
stntement in the PHP code incÌudes the dntnbnse credentinÌs, it`s the Ìnst Ìine of the
foÌÌowing code sniµµet:
The next µortion is n new nddition to the PHP version thnt`s unnecessnry in the PerÌ
CGI version. 8ecnuse the initinÌ µnge in the PerÌ version is n stntic HTML µnge, the
CGI doesn`t crente nny HTML. AÌthough the snme couÌd be done with the PHP ver-
sion (nnd technicnÌÌy with the PerÌ version ns weÌÌ), it`s ensier to hnndÌe crenting the
Part Iv DeveIopment
HTML directÌy in the PHP µrogrnm. In this instnnce, if the Submit button isn`t
cÌicked (ns it wouÌd be when you initinÌÌy visit the µnge, or if the fieÌd were
bÌnnk), the µnge is simµÌy served ngnin.
The PHP method for connecting to the dntnbnse server nnd dntnbnse is next in the
The next bit of code exnmines the vnÌue thnt wns inµut, Ìooking for nn symboÌ
(which wouÌd indicnte thnt the query is Ìooking for the grnnts ~µriviÌeges ~
nfforded n given user). Notice the use of the PHP function to exnmine the
string vnrinbÌe. A PHP MySQL function introduced in this section ~
~works somewhnt Ìike the function
in PerÌ.
The function tnkes n string thnt wns nÌrendy inµut
nnd mnkes it snfe for use in n MySQL stntement. The function
in PerÌ does the snme thing, but it µuts quotntion mnrks nround the string ~
which the function in PHP does not. Therefore, to use
, µut quotes nround the string in your PHP MySQL
stntements. The foÌÌowing sniµµet is nn exnmµÌe:
The next section is executed when no symboÌ is incÌuded from the form (hence, in
effect, no grnnts nre sought). The µrogrnm queries for the nÌrendy-inµut usernnme
nnd returns the resuÌt.
Chapter 16 PHP DeveIopment
In nddition to the functions used in this section, nnother method is µossibÌe for µro-
cessing the returned resuÌts. It Ìooks Ìike this:
The finnÌ section of the µrogrnm is cnÌÌed when nn symboÌ is incÌuded in the inµut
thnt comes from the form:
In the code sniµµet |ust given, notice thnt PHP cnÌÌs the function with the nnme
(wherens PerÌ uses to designnte n user-defined function). The func-
tion nÌso uses n different method for receiving the vnrinbÌes thnt nre cnÌÌed with it.
Part Iv DeveIopment
Throughout the µrogrnm, the µersistent chnÌÌenge is to keeµ trnck of both the simiÌnri-
ties nnd the significnnt differences between PerÌ nnd PHP to nvoid Ìosing functionnÌity.
Cookies with no miIk
Coohics nre vnÌue-µÌus-µnrnmeter µnirs stored in the HTTP hender nnd sent to n
Web ngent (such ns n browser) when retrieving nn ob|ect ~usunÌÌy n Web µnge~
from the Internet. They nre commonÌy used to store user-reÌnted dntn (such ns ses-
sion identifiers) nnd cnn be set to exµire nt n µoint in the future determined by the
site thnt sets nnd uses the cookie.
AÌthough PHP incÌudes functions for setting nnd ensiÌy retrieving cookies, it nÌso
incÌudes other functions for setting nnd retrieving session identifiers, some of these
don`t use cookies. A deveÌoµer cnn use either n cookie function or n session func-
tion in PHP to mnintnin stnte or nuthenticnte users for Web µnges.
There nre µrobnbÌy endÌess methods for crenting nuthenticntion mechnnisms for
Web sites nnd Web µnges. This section exnmines one method for nuthenticnting
users thnt nÌso sets n cookie with n session identifier. The nµµronch thnt is sµecifi-
cnÌÌy reÌevnnt to this book is to integrnte the nuthenticntion mechnnism with n
MySQL dntnbnse.
Once thnt integrntion is comµÌete, visitors cnn enter n usernnme nnd µnssword. The
credentinÌs wiÌÌ be nuthenticnted ngninst dntn in n MySQL dntnbnse. If the Ìogin is
successfuÌ, n session ID nnd timestnmµ nre recorded in the MySQL dntnbnse. A
cookie is sent to the user uµon success, contnining thnt snme session ID nnd user-
nnme (in encryµted form). When the user nttemµts to nccess nnother resource
within the site, the user`s cookie is exnmined nnd comµnred to the one in the
dntnbnse. If it`s vnÌid, the user is nÌÌowed to nccess the resource. In nddition, the
dntnbnse incÌudes n function so resources cnn be Ìimited by grouµ (shouÌd
the need nrise).
No need to undertake full normalization of the database for this site. Since the site
is intended for low usage, normalization would have little or no effect on perfor-
The first steµ townrd the nuthenticntion system is to crente the dntnbnse ~in
effect, n big tnbÌe with some sµecinÌ fentures. The tnbÌe for the nuthenticntion sys-
tem hns the foÌÌowing structure:
Chapter 16 PHP DeveIopment
Two mnin PHP scriµts mnke uµ the nuthenticntion system: n sign-in µrogrnm nnd n
cookie-vnÌidntion µrogrnm. The sign-in µrogrnm µrints n form for usernnme nnd
µnssword, nnd then sets the cookie. It Ìooks Ìike this:
Part Iv DeveIopment
Lxnminntion of the code revenÌs thnt mnny of the functions (nnd some of the Ìogic)
µreviousÌy discussed in this chnµter nre incorµornted into the µrogrnm. A couµÌe of
sniµµets cnÌÌ for n cÌoser Ìook: One encryµts nn otherwise-µÌnintext usernnme before
returning it to the browser, the other cÌenrs the memory nssocinted with n resuÌt.
Chapter 16 PHP DeveIopment
Encrypting a username before returning it
In this section, nfter the usernnme nnd µnssword hnve been vnÌidnted, I crente n cou-
µÌe of seemingÌy rnndom strings for vnÌues to store in cookies Ìnter. The PHP function
is used twice. 8ecnuse both the session ID nnd the usernnme shouÌd be vnÌi-
dnted (I`ÌÌ teÌÌ you why Ìnter), I`d Ìike to send n usernnme. However, sending n µÌnintext
usernnme bnck to the browser is not such n good iden (from the stnndµoint of security
nnd µrivncy). The function to the rescue! The reÌevnnt code Ìooks Ìike this:
CIearing the memory associated with a resuIt
The next PHP MySQL function hnsn`t been used before in this chnµter`s exnmµÌes:
, which cÌenrs the memory nssocinted with n resuÌt.
AÌthough technicnÌÌy it doesn`t hocc to be used here, it does ensure thnt the vnÌue
in wiÌÌ be cÌenn nnd fresh~nnd thnt`s one Ìess source of µotentinÌ error.
ßecause the use of wipes the old result set out of mem-
ory, you can't glean any further information from the old result set! Make sure you
have the information you need before you trash the old result set.
Using cnn be n Ìifesnver if your system is oµernting nenr the
Ìimit of its resources nnd you hnve n huge resuÌt set thnt tnkes uµ too much mem-
ory. Here`s whnt the code Ìooks Ìike:
Note the comment thnt Ìets the µrogrnmmer know whnt`s intended here (nnd con-
sider it n reminder to cuÌtivnte good documentntion hnbits). Next, n cnÌÌ to the PHP
function gives me n current Unix}Linux vnÌue (given ns the num-
ber of seconds since the Lµoch), nnd running the stntement sets the ses-
sion ID in the nÌong with the . Here`s the code:
Using n together with the session ID he̵s ensure thnt the session is reÌ-
ntiveÌy recent (which is imµortnnt to estnbÌish, ns I`ÌÌ show you in the µrogrnm to
vnÌidnte cookies).
Part Iv DeveIopment
5etting and vaIidating the cookie
The foÌÌowing code contnins two exnmµÌes of the function:
The stntement nt the end of this code sniµµet wouÌd be n good µÌnce to send
n redirect to the cÌient, sending it to nnother µnge or cnÌÌing nnother function.
In the first code snippet just given, normally you'd put the valid URL for the cookie
between the final double quotes to the left of the -in both instances. As it hap-
pens, some crazy redirection on my network prevents me from placing that value
correctly (within that final set of quotes) for the example.
The µrogrnm to vnÌidnte cookies is ns foÌÌows:
Chapter 16 PHP DeveIopment
The function wouÌd normnÌÌy be cnÌÌed from within nnother µnge. Ior
exnmµÌe, I hnve n µnge cnÌÌed thnt I do not wnnt nnyone to gnin nccess
to unÌess they nre vnÌid. IncÌuding n cnÌÌ to this function nt the beginning of thnt µnge
he̵s me ensure thnt the user hns n vnÌid cookie nnd is nuthorized to view the µnge.
VaIidating the user and the cookie
The query in the uµcoming code sniµµet is the snme one sent to nctunÌÌy vnÌidnte
the user nnd the cookie.
Here I`m using the cÌnuse to Ìook for three mntches:
The session ID shouÌd mntch the one sent in the user cookie.
The in the is comµnred to the current time. If the
is Ìess thnn 1O minutes ngo (6OO seconds), then it`s vnÌid.
The user in the tnbÌe (sent through ) shouÌd mntch the ed user from
the cookie.
If nÌÌ three of these vnÌues mntch nµµroµrinteÌy, the cookie is vnÌid.
Using three vnÌues in the dntnbnse to vnÌidnte cookies mnkes it more difficuÌt for
n mnÌicious user to fnke n session ID to try to gnin nccess to µrotected resources.
Lven if n user cnn fnke n session ID, he or she must tie in thnt session ID with
the encryµted usernnme within the time sµecified in the query (in this cnse,
1O minutes).
The function ends with n cnÌÌ to the PHP function. The function sends the
vnÌue bnck to the cnÌÌing µrogrnm.
As nn exnmµÌe, here`s the code thnt crentes n µnge cnÌÌed . Thnt µnge
cnÌÌs the function to vnÌidnte the user before continuing. The code
for the µnge is ns foÌÌows:
Part Iv