MYSQL 8 Administrator's Guide My SQL Effective To Administering High Performance Solutions
User Manual:
Open the PDF directly: View PDF .
Page Count: 1116 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Preface
- An Introduction to MYSQL 8
- Installing and Upgrading MySQL 8
- The MySQL 8 installation process
- Post-installation setup for MySQL 8
- Upgrading MySQL 8
- MySQL 8 downgrading
- Summary
- MySQL 8 – Using Programs and Utilities
- Overview of MySQL 8 programs
- MySQL 8 command-line programs
- Executing programs from the command line
- Server and server-startup programs
- Installation programs
- MySQL 8 client programs
- mysql - the command-line tool
- mysql options
- mysql commands
- mysql logging
- mysql server-side help
- Executing sql from text files
- mysqladmin - client for administering a MySQL server
- mysqlcheck - a table maintenance program
- mysqldump - a database backup program
- mysqlimport - a data import program
- mysqlpump - a database backup program
- mysqlsh - the MySQL Shell
- mysqlshow - showing database, table, and column information
- mysqlslap - load emulation client
- mysql - the command-line tool
- MySQL 8 administrative programs
- ibdsdi - InnoDB tablespace SDI extraction utility
- innochecksum - offline InnoDB file checksum utility
- myisam_ftdump - displaying full-text index utility
- myisamchk - MyISAM table-maintenance utility
- myisamlog - displaying MyISAM log file content
- myisampack - generating compressed, read-only MyISAM tables
- mysql_config_editor - MySQL configuration utility
- mysqlbinlog - utility for processing binary log files
- mysqldumpslow - summarizing slow query log files.
- MySQL 8 environment variables
- MySQL GUI tools
- Summary
- MySQL 8 Data Types
- MySQL 8 Database Management
- MySQL 8 Storage Engines
- Indexing in MySQL 8
- Replication in MySQL 8
- Partitioning in MySQL 8
- MySQL 8 – Scalability and High Availability
- MySQL 8 – Security
- Optimizing MySQL 8
- Extending MySQL 8
- MySQL 8 Best Practices and Benchmarking
- Troubleshooting MySQL 8
- Other Books You May Enjoy
MySQL8Administrator'sGuide
Effectiveguidetoadministeringhigh-performance
MySQL8solutions
ChintanMehta
AnkitBhavsar
HetalOza
SubhashShah
BIRMINGHAM-MUMBAI
MySQL8Administrator'sGuide
Copyright©2018PacktPublishingAllrightsreserved.Nopartofthisbookmaybereproduced,storedina
retrievalsystem,ortransmittedinanyformorbyany means,withoutthe priorwrittenpermissionof the
publisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express or
implied.Neithertheauthors,norPacktPublishingoritsdealersanddistributors,willbeheldliableforany
damagescausedorallegedtohavebeencauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproducts
mentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteethe
accuracyofthisinformation.
CommissioningEditor:AmeyVarangaonkar
AcquisitionEditor:AmanSingh
ContentDevelopmentEditor:Aaryamansingh
TechnicalEditor:DharmendraYadav
CopyEditors:SafisEditing
ProjectCoordinator:ManthanPatel
Proofreader:SafisEditing
Indexer:TejalDaruwaleSoni
Graphics:TaniaDutta
ProductionCoordinator:AparnaBhagatFirstpublished:February2018
Productionreference:1140218
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
Birmingham
B32PB,UK.
ISBN978-1-78839-519-9
www.packtpub.com
Whysubscribe?
SpendlesstimelearningandmoretimecodingwithpracticaleBooksand
Videosfromover4,000industryprofessionals
ImproveyourlearningwithSkillPlansbuiltespeciallyforyou
GetafreeeBookorvideoeverymonth
Maptisfullysearchable
Copyandpaste,print,andbookmarkcontent
PacktPub.com
Didyou knowthat PacktofferseBook versionsof everybook published,with
PDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktP
ub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBook
copy.Getintouchwithusatservice@packtpub.comformoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,sign
upforarangeoffreenewsletters,andreceiveexclusivediscountsandofferson
PacktbooksandeBooks.
Contributors
Abouttheauthors
Chintan Mehta is a cofounder of KNOWARTH Technologies
(www.knowarth.com)andheadscloud/RIMS/DevOps.Hehasrich,progressive
experienceinserveradministrationofLinux,AWScloud,DevOps,RIMS,and
opensourcetechnologies.HeisanAWSCertifiedSolutionsArchitect.
He has authored MySQL 8 for Big Data and Hadoop Backup and Recovery
Solutions, and has reviewed Liferay Portal Performance Best Practices and
BuildingServerlessWebApplications.
I would like to thank my coauthors. I would especially like to thank my
wonderfulwife,Mittal,andmysweetson,Devam,forputtingupwiththelong
days,nights,andweekendswhenIwascampinginfrontofmylaptop.Lastbut
not least, I want to thank my mom, dad, friends, family, and colleagues for
supportingmethroughout.
AnkitBhavsarisaseniorconsultantleadingateamworkingonERPsolutions
at KNOWARTH Technologies. He received an MCA from North Gujarat
university. He has had dynamic roles in the development and maintenance of
ERP solutions and astrology portals Content Management that including OOP,
technicalarchitectureanalysis,design,developmentaswellasdatabasedesign,
development and enhancement process, data and object modeling, in order to
providetechnicalandbusinesssolutionstoclients.
First, I would like to thank the coauthors, reviewers, the wonderful team at
PacktPub, and Aaryaman for this effort. I would especially like to thank my
wonderfulwife,Avani,forputtingupwiththelongdays,nights,andweekends.
Last,butnotleast,Iwanttothankmymom,dad,friends,family,andcolleagues
forsupportingmethroughoutthewritingofthisbook.
Hetal Oza an MCA from a reputable institute of India, is working as a lead
consultantatKNOWARTHTechnologies.ShehasrichexperienceinJava-based
systemswithvariousdatabases.Her10yearsofexperiencecoversallstagesof
softwaredevelopment.Shehasworkedondevelopmentofweb-basedsoftware
solutions on various platforms. She has good exposure to integration projects
with web-service-based and thread-based architecture. Her knowledge is not
boundtoanysinglefieldbecauseshehasworkedonwiderangeoftechnologies
andtools.
Itgavemeimmensepleasuretobeanauthorofthisbook.First,Iwouldliketo
thankmyhusband,Suhag,andmysweetson,Om,forputtingupwithmeduring
thelongdays,nights,andweekendswhenIwascampinginfrontofmylaptop.
Second, I would like to thank Chintan Mehta, who showed trust in me and
providedthisopportunity,andKrupalKhatriforhissupport.Iwouldalsoliketo
thanktheteamatPacktPubfortheirgreathelp.
SubhashShah works as a principal consultant at KNOWARTH Technologies.
HeholdsadegreeininformationtechnologyfromaHNGU.Heisexperienced
in developing web-based solutions using various software platforms. He is a
strongadvocateofopensourcesoftwaredevelopmentanditsusebybusinesses
to reduce risks and costs. His interests include designing sustainable software
solutions.Histechnicalskillsincluderequirementanalysis,architecturedesign,
projectdelivery,applicationsetup,andexecutionprocesses.Heisanadmirerof
qualitycodeandtest-drivendevelopment.
Iwouldliketothankmyfamilyforsupportingmethroughoutthecourseofthis
book.It would have been difficult without them being a source of inspiration.
ThankstoPacktPublishing,especiallyAaryaman,fortheirsmoothcoordination
and support. Thanks to fellow authors for being around all the time, for their
dedicationandcommitment.Lastbutnot least,thankstomycolleaguesfor all
thesupporttheyhaveprovided.
Aboutthereviewers
Sahaj Pathak has been involved with backend technologies such as Java,
Spring,Hibernate,anddatabases(MySQL,PostgreSQL,Oracle,andothers).His
experience also spans frontend technologies (HTML4/5, jQuery, AngularJS,
Node.Js,JavaScript,andCSS2/3).Hehasspeedyversatilitywithanytechnology
andasharpdesireforconsistentchange.
HeworksatKNOWARTHTechnologiesasasoftwareconsultantwherehedeals
withbigenterprise-product-basedprojects.
Ravi Shah is a highly versatile IT professional with more than 5 years of
experience of handling high-end IT projects, with competencies in
conceptualizingandsupportingcriticalITframeworksandapplications.Heisa
team player, a software engineer with a can-do attitude, and possesses
phenomenal time management skills, and strong user focus. He has developed
severalwebapplicationsandmainlyspecializesinhealthcareandinsurance.
He is skilled in all phases of software development, an expert in translating
businessrequirementsintotechnicalsolutions,anddevotedtoquality,usability,
security and scalability. His expertise mainly includes Liferay, Java, Spring,
Struts,Hibernate,MySQL,Lucene,Angular,andAgile.
He is a good trainer delivering training on J2EE and the Liferay portal in his
organization.
IwouldliketotakethisopportunitytoexpressheartfeltthankstoKNOWARTH
Technologies and Packt Publishing for giving me this opportunity. Also, I am
verythankfultomyparentsforalwayssupportingmeinallpossibleways.
Packt is searching for authors
likeyou
Ifyou'reinterestedinbecominganauthorforPackt,pleasevisitauthors.packtpub.c
om and apply today. We have worked with thousands of developers and tech
professionals,justlikeyou,tohelpthemsharetheirinsightwiththeglobaltech
community.Youcan makeageneralapplication,applyforaspecifichottopic
thatwearerecruitinganauthorfor,orsubmityourownidea.
LicenserequirementsofMySQL8
Reliabilityandscalability
Platformcompatibility
Releases
CorefeaturesinMySQL
Structureddatabase
Databasestorageenginesandtypes
OverviewofInnoDB
OverviewofMyISAM
Overviewofmemory
Overviewofarchive
OverviewofBLACKHOLEasastorageengine
OverviewofCSV
2. InstallingandUpgradingMySQL8
TheMySQL8installationprocess
Generalinstallationguide
DownloadingMySQL8
Verifyingthepackageintegrity
UsingMD5checksums
Usingcryptographicsignatures
InstallingMySQL8onMicrosoftWindows
Windows-specificconsiderations
MySQL8installationlayout
Choosingtherightinstallationpackage
TheMySQL8installer
Initialsetupinformation
Installationworkflow
InnoDBclustersandboxtestsetup
Serverconfiguration
MySQLinstallerproductcataloganddashboard
MySQLinstallerconsole
MySQL8installationusingaZIPfile
InstallingMySQL8onLinux
InstallationusingtheYumrepository
InstallationusingtheRPMpackage
InstallationusingtheDebianpackage
Post-installationsetupforMySQL8
Datadirectoryinitialization
SecuringtheinitialMySQLaccount
StartingandtroubleshootingMySQL8services
Executingcommandstotesttheserver
UpgradingMySQL8
Upgradingmethods
In-placeupgradeofMySQL
LogicalupgradeforMySQL8
UpgradingprerequisitesforMySQL5.7
MySQL8downgrading
Downgradingmethods
Logicaldowngrade
Manualchangesrequiredbeforedowngrading
Summary
3. MySQL8–UsingProgramsandUtilities
OverviewofMySQL8programs
MySQLprogramsinbrief
Startupprograms
Installation/upgradationprograms
Clientprograms
Administrativeandutilitiesprograms
Environmentvariables
MySQLGUItool
MySQL8command-lineprograms
Executingprogramsfromthecommandline
ExecutingMySQLprograms
ConnectingtotheMySQLserver
Specifyingoptionsforprograms
Optionsonthecommandline
Modifyingprogramoptions
Modifyingoptionswithfiles
group
opt_name
opt_name=value
Includedirectives
Command-lineoptionsaffectingoptionfilehandling
Settingprogramvariableswithoptions
Settingenvironmentvariables
Serverandserver-startupprograms
mysqld-theMySQLserverprogram
Options
mysqld_safe-MySQLserverstartupscript
mysql.server-MySQLServerstartupscript
mysqld_multi-managingmultipleMySQLservers
Installationprograms
comp_err-compilingtheMySQLerrormsgfile
mysql_secure_installation-improvingMySQLinstallationsecurity
mysql_ssl_rsa_setup-creatingSSL/RSAfiles
mysql_tzinfo_to_sql-loadingthetimezonetables
mysql_upgrade-checkingandupgradingMySQLtables
MySQL8clientprograms
mysql-thecommand-linetool
mysqloptions
mysqlcommands
help[arg],\h[arg],\?[arg],?[arg]
charsetcharset_name,\Ccharset_name
clear,\c
connect[db_namehost_name],\r[db_namehost_name]
edit,\e
exit,\q
prompt[str],\R[str]
quit,\q
status,\s
usedb_name,\udb_name
mysqllogging
mysqlserver-sidehelp
Executingsqlfromtextfiles
mysqladmin-clientforadministeringaMySQLserver
mysqlcheck-atablemaintenanceprogram
mysqldump-adatabasebackupprogram
Performanceandscalability
mysqlimport-adataimportprogram
mysqlpump-adatabasebackupprogram
mysqlsh-theMySQLShell
mysqlshow-showingdatabase,table,andcolumninformation
mysqlslap-loademulationclient
MySQL8administrativeprograms
ibdsdi-InnoDBtablespaceSDIextractionutility
innochecksum-offlineInnoDBfilechecksumutility
myisam_ftdump-displayingfull-textindexutility
myisamchk-MyISAMtable-maintenanceutility
myisamlog-displayingMyISAMlogfilecontent
myisampack-generatingcompressed,read-onlyMyISAMtables
mysql_config_editor-MySQLconfigurationutility
mysqlbinlog-utilityforprocessingbinarylogfiles
mysqldumpslow-summarizingslowquerylogfiles.
MySQL8environmentvariables
MySQLGUItools
MySQLWorkbench
MySQLNotifier
MySQLNotifierusage
Summary
4. MySQL8DataTypes
OverviewofMySQL8datatypes
Numericdatatypes
Integertypes
Fixedpointtypes
Floatingpointtypes
Problemswithfloatingpointvalues
Bitvaluetype
Bitvalueliterals
PracticalusesofBIT
Typeattributes
Overflowhandling
Dateandtimedatatypes
DATE,DATETIME,andTIMESTAMPtypes
MySQLDATETIMEfunctions
TIMEtype
Timefunctions
YEARtype
MigratingYEAR(2)toYEAR(4)
Stringdatatypes
CHARandVARCHARdatatypes
BINARYandVARBINARYdatatypes
BLOBandTEXTdatatypes
ENUMdatatype
SETdatatype
JSONdatatype
PartialupdatesofJSONvalues
Storagerequirementsfordatatypes
Choosingtherightdatatypeforcolumn
Summary
5. MySQL8DatabaseManagement
MySQL8serveradministration
Serveroptionsanddifferenttypesofvariables
Grantsystemtables
Objectinformationsystemtables
Logsystemtables
Theserver-sidehelpsystemtables
Timezonesystemtables
Replicationsystemtables
Optimizersystemtables
Othermiscellaneoussystemtables
Runningmultipleinstancesonasinglemachine
Settingupmultipledatadirectories
RunningmultipleMySQLinstancesonWindows
Componentsandpluginmanagement
MySQL8serverplugins
Installingtheplugins
Localesupport
MySQL8serverlogs
Theerrorlog
Componentconfiguration
Defaulterrorlogdestinationconfiguration
DefaulterrorlogdestinationonWindows
DefaulterrorlogdestinationonUnixandUnix-Likesystems
Thegeneralquerylog
Thebinarylog
Theslowquerylog
TheDDLlog
Serverlogmaintenance
Summary
6. MySQL8StorageEngines
Overviewofstorageengines
MySQLstorageenginearchitecture
Severaltypesofstorageengine
OverviewoftheInnoDBstorageengine
Customstorageengine
Severaltypesofstorageengines
Pluggablestorageenginearchitecture
Thecommondatabaseserverlayer
Settingthestorageengine
TheMyISAMstorageengine
TheMEMORYstorageengine
TheCSVstorageengine
Tablesandindexes
INFORMATION_SCHEMAtables
Memcachedplugin
Creatingacustomstorageengine
Creatingstorageenginesourcefiles
Addingengine-specificvariablesandparameters
Creatingthehandlerton
Handlinghandlerinstallation
Definingfilenameextensions
Creatingtables
Openingatable
Implementingbasictablescanning
Closingatable
Referenceforadvancedcustomstorageengine
Summary
7. IndexinginMySQL8
Anoverviewonindexing
UsesofindexesinMySQL8
SQLcommandsrelatedtoindexes
CreatinganINDEXcommand
Spatialindexcharacteristics
Non-spatialindexcharacteristics
Dropindexcommand
SPATIALindexcreationandoptimization
InnoDBandMyISAMindexstatisticscollection
Column-levelindexing
Columnindexes
Summary
8. ReplicationinMySQL8
Overviewofreplication
WhatisMySQLreplication?
AdvantagesofMySQLreplication
Configuringreplication
Binarylogfilebasedreplication
Replicationmasterconfiguration
REPLICATIONSLAVEconfiguration
Addingslavestoreplication
Globaltransactionidentifiersbasedreplication
MySQLmulti-sourcereplication
Replicationadministrationtasks
Implementingreplication
Replicationformats
Statement-basedversusrow-basedreplication
Replicationimplementationdetails
Replicationchannels
Replicationrelayandstatuslogs
Evaluatingreplicationfilteringrules
Groupreplication
Primary-secondaryreplicationversusgroupreplication
Groupreplicationconfiguration
Groupreplicationusecases
Replicationsolutions
Summary
9. PartitioninginMySQL8
Overviewofpartitioning
Typesofpartitioning
Partitioningmanagement
Partitionselectionandpruning
Restrictionsandlimitationsinpartitioning
Typesofpartitioning
RANGEpartitioning
LISTpartitioning
COLUMNSpartitioning
RANGECOLUMNpartitioning
LISTCOLUMNpartitioning
HASHpartitioning
LINEARHASHpartitioning
KEYpartitioning
Subpartitioning
HandlingNULLinpartitioning
Partitionmanagement
RANGEandLISTpartitionmanagement
HASHandKEYpartitionmanagement
Partitionmaintenance
Obtainpartitioninformation
Partitionselectionandpruning
Partitionpruning
Partitionselection
Restrictionsandlimitationsinpartitioning
Partitioningkeys,primarykeys,anduniquekeys
Partitioninglimitationsrelatingtostorageengines
Partitioninglimitationsrelatingtofunctions
Summary
10. MySQL8–ScalabilityandHighAvailability
OverviewofscalabilityandhighavailabilityinMySQL8
MySQLreplication
MySQLcluster
OracleMySQLcloudservice
MySQLwiththeSolariscluster
ScalingMySQL8
Scalingusingcluster
Clientnode
Applicationnode
Managementnode
Datanode
Datastorageandmanagementofdisk-basedandin-memorydata
Automaticanduser-definedpartitioningoftablesorsharding
oftables
Synchronousdatareplicationbetweendatanodes
Dataretrievalandtransactions
Automaticfailover
Automaticre-synchronizationforself-healingafterfailure
ScalingusingmemcachedinMySQL8
NoSQLAPIs
Scalingusingreplication
Singleserverdependancy
Performance
Backupandrecovery
Loaddistribution
Updatesinthesystem
Choosingthesolution
Advantagesofhighavailability
Summary
11. MySQL8–Security
OverviewofsecurityforMySQL8
Commonsecurityissues
Generalguidelines
Guidelinesforasecurepassword
Guidelinesforendusers
Guidelinesforadministrators
Passwordandlogging
SecureMYSQL8againstattackers
SecurityoptionsandvariablesprovidedbyMySQL8
Securityguidelinesforclientprogramming
AccesscontrolinMySQL8
PrivilegesprovidedbyMySQL8
Granttables
Verificationofaccesscontrolstages
Stage1-Connectionverification
Stage2-Requestverification
AccountmanagementinMySQL8
Addandremoveuseraccounts
Securityusingroles
SETROLE
CREATEROLE
DROPROLE
GRANT
REVOKE
SETDEFAULTROLE
SHOWGRANTS
Passwordmanagement
EncryptioninMySQL8
ConfiguringMySQL8touseencryptedconnections
Server-sideconfigurationforencryptedconnections
Client-sideconfigurationforencryptedconnections
Commandoptionsforencryptedconnections
ConnectwithMySQL8remotelyfromWindowswithSSH
Securityplugins
Authenticationplugins
SHA-2pluggableauthentication
Client-sidecleartextpluggableauthentication
No-loginpluggableauthentication
Socketpeer-credentialpluggableauthentication
Testpluggableauthentication
Theconnection-controlplugins
CONNECTION_CONTROL
Plugininstallation
VariablesrelatedtoCONNECTION-CONTROL
Thepasswordvalidationplugin
Installpasswordvalidationplugin
Variablesandoptionsrelatedtothepasswordvalidationplugin
MySQL8keyring
Installkeyringplugin
Systemvariablesrelatedtokeyringplugin
Summary
12. OptimizingMySQL8
OverviewofMySQL8optimization
Optimizingthedatabase
Optimizingthehardware
OptimizingMySQL8serversandclients
OptimizingdiskI/O
UsingNFSwithMySQL
Optimizingtheuseofmemory
Optimizinguseofthenetwork
Optimizinglockingoperations
Performancebenchmarking
Examiningthreadinformation
Optimizingtables
OptimizationforInnoDBtables
OptimizationforMyISAMtables
OptimizationforMEMORYtables
Leveragingbufferingandcaching
InnoDBbufferpooloptimization
MyISAMkeycache
Summary
13. ExtendingMySQL8
AnoverviewofextendingMySQL8
MySQL8internals
MySQL8pluginAPI
MySQL8servicesforcomponentsandplugins
AddingnewfunctionstoMySQL8
DebuggingandportingMySQL8
Extendingpluginsandusingservicestocallthem
Writingplugins
Componentandpluginservices
Thelockingservice
Thekeyringservice
Addingnewfunctions
Featuresofauser-definedfunctioninterface
Addinganewuser-definedfunction
Addinganewnativefunction
Debuggingandporting
DebuggingMySQLserver
DebuggingMySQLclient
Namespaces
Cachingmechanism
Memcachedgeneralstatistics
Bestpracticesforreplication
Throughputingroupreplication
Infrastructuresizing
Constantthroughput
Contradictoryworkloads
Writescalability
Bestpracticesfordatapartitioning
Horizontalpartitioning
Verticalpartitioning
PruningpartitionsinMySQL
Limitingyourself
Analyzingslowqueries
Querycost
Summary
15. TroubleshootingMySQL8
MySQL8commonproblems
MostcommonMySQLerrors
Accessdenied
Can'tconnectto[local]MySQLserver
LostconnectiontoMySQLserver
Passwordfailswhenenteredincorrectly
Hosthost_nameisblocked
Toomanyconnections
MySQLtemporaryfilesstorage
MySQLUnixsocketfile
Timezoneproblems
MySQL8clienterrors
Casesensitivityinstringsearches
ProblemswithDATEcolumns
ProblemswithNULLvalues
MySQL8troubleshootingapproach
Analyzingqueries
Real-worldscenario
Summary
OtherBooksYouMayEnjoy
Leaveareview-letotherreadersknowwhatyouthink
Preface
Foranysystem, it ismustto manage datainan organizedmanner.Ina large-
scale system, it is necessary to handle various configurations for security
purposes.MySQL
is one of the popular solutions used to handle enterprise-level applications. In
thisbook,wewillexplainhowtoconfigureusers,theirroles,multipleinstances,
andmuchmore.
ManyorganizationsuseMySQLfortheirwebsitesorcommercialproducts,and
it's very challenging for them to manage data storage and analyze data in
accordance with the business requirements. This book will show you how to
implementindexingandqueryoptimizationforbetterperformance.Alongwith
this,we'llcoverhowscalabilityandhighavailabilityoftheMySQLservercan
helptomanagefailurescenarios.Inadditiontothat,replicationandpartitioning
conceptsareexplainedindetailwithexamples.
ThebookdescribesvariousfeaturesofMySQL8bytargetingdifferentlevelsof
users, from beginners to database administrators. This book starts from the
installationwithabasicunderstandingofMySQL8'sconcepts.Theweproceed
toadministrative-levelfeatureswithconfiguration.Attheendofthebook,you
will have learned about very interesting functionalities, such as optimization,
extension,andtroubleshooting.
Whothisbookisfor
Thisbookis intended forMySQLadministratorswho are lookingfora handy
guide covering all the MySQL administration-related tasks. If you are a DBA
lookingtogetstartedwithMySQLadministration,thisbookwillalsohelpyou.
Knowledgeofbasicdatabaseconceptsisrequiredtogetstartedwiththisbook.
Whatthisbookcovers
Chapter 1, An Introduction to MySQL 8, serves as an introductory guide to
MySQL 8. It briefly defines the core features available in MySQL and newly
introducedorenhancedfeaturesofMySQL8.Inthelaterpartofthechapter,we
highlightthebenefitsofMySQL8alongwithreal-worldapplications.
Chapter 2, Installing and Upgrading MySQL 8, describes detailed steps for
installingMySQL8ondifferentplatforms.Italsoexplainshowtoupgradetoor
downgradefromMySQL8.
Chapter 3, MySQL 8 – Using Programs and Utilities, introduces command-line
programsfortheMySQL8serverandclient.Italsoprovidesinformationonthe
availableGUItoolswithitsconfiguration.
Chapter4,MySQL8DataTypes,focusesonadetailedexplanationofMySQL8
data types. It also explains data type categorization based on the types of
content. We cover data types along with their properties in each category. We
alsocoverstoragerequirementsfordatatypes.
Chapter 5,MySQL 8 Database Management,mainlyexploresthe administration
part of MySQL 8. This chapter covers components and plugin management,
along with user and role management. In addition, it explains globalization
configuration, caching techniques, and different types of logs available in
MySQL8.
Chapter 6,MySQL 8 Storage Engines,explains several types of storage engines
anddetailsoftheInnoDBstorageengine.Thischapterprovidesinformationon
custom storage engine creation, along with steps to make it pluggable in
installedMySQL8.
Chapter7,IndexinginMySQL8,explainsindexing,alongwiththepossibleways
ofimplementingit.Itcomparestypesofindexing.
Chapter8,ReplicationinMySQL8,explainsreplicationandthedifferenttypesof
replication available in MySQL 8. It also describes the configuration and
implementationofreplicationalongwithdifferentapproaches.
Chapter 9, Partitioning in MySQL 8, explains the setting of several types of
partitioning,selection,andpruningofpartitioning.Italsoexplainshowtocope
upwithrestrictionsandlimitationswhilepartitioning.
Chapter 10, MySQL 8 – Scalability and High Availability, explains how to do
scaling and how to handle different challenges during implementation. The
reader gets an understanding of diverse ways to achieve high availability in
MySQL8.
Chapter 11, MySQL 8 – Security, focuses on MySQL 8 database security. This
chaptercoversgeneralfactorsthataffectsecurity,thesecurityofcoreMySQL8
files, accesscontrol, and securingthe database system itself. This chapter also
includesdetailsofsecurityplugins.
Chapter12,OptimizingMySQL8,explainshowtoconfigureMySQL8forbetter
performance. This chapter also describes use cases with a few performance
resultstovalidate.Thiswillhelpyouknowvarioustouchpointstolookoutfor
whendealingwithoptimizingMySQL8.
Chapter 13,Extending MySQL 8, shows how to extend MySQL 8 and add new
functions,alongwithdebuggingandportingtoMySQL8.
Chapter 14, MySQL 8 Best Practices and Benchmarking, explains the best
practices of using MySQL. It also explains various benchmarkings done for
MySQL8.
Chapter 15, Troubleshooting MySQL 8, explains many common and real-world
scenariosoftroubleshootingforMySQL8.
Togetthemostoutofthisbook
WerecommendthatyougetsomebasicknowledgeofMySQL(anyversion)and
SQLcommandsbeforeyoustartreadingthisbook.
Thisbookalsocoverspracticalscenariosandcommandexecution,soifpossible,
installatoolforeasyexecutionofMySQLcommands.
Downloadtheexamplecodefiles
Youcandownloadtheexamplecodefilesforthisbookfromyouraccountatwww.
packtpub.com.Ifyoupurchasedthisbookelsewhere,youcanvisitwww.packtpub.com/su
pportandregistertohavethefilesemaileddirectlytoyou.
Youcandownloadthecodefilesbyfollowingthesesteps:
1. Loginorregisteratwww.packtpub.com.
2. SelecttheSUPPORTtab.
3. ClickonCodeDownloads&Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.
Once the file is downloaded, please make sure that you unzip or extract the
folderusingthelatestversionof:
WinRAR/7-ZipforWindows
Zipeg/iZip/UnRarXforMac
7-Zip/PeaZipforLinux
ThecodebundleforthebookisalsohostedonGitHubathttps://github.com/PacktPu
blishing/MySQL-8-Administrators-Guide.Wealsohaveothercodebundlesfromourrich
catalogofbooksandvideosavailableathttps://github.com/PacktPublishing/.Check
themout!
Conventionsused
Thereareanumberoftextconventionsusedthroughoutthisbook.
CodeInText: Indicates code words in text, database table names, folder names,
filenames, file extensions, pathnames, dummy URLs, user input, and Twitter
handles.Hereisanexample:"ItwilldownloadwinMD5Sum.exeontoyourcomputer."
Anycommand-lineinputoroutputiswrittenasfollows:
CREATETABLEworking_days(
yearINT,
weekINT,
daysBIT(7),
PRIMARYKEY(year,week));
Bold:Indicatesanewterm,animportantword,orwordsthatyouseeonscreen.
Forexample,wordsinmenusordialogboxesappearinthetextlikethis.Hereis
anexample:"ClickontheDownloadWinMD5Sumoptiononthepage."
Warningsorimportantnotesappearlikethis.
Tipsandtricksappearlikethis.
Getintouch
Feedbackfromourreadersisalwayswelcome.
Generalfeedback:Emailfeedback@packtpub.comandmentionthebooktitleinthe
subjectofyourmessage.Ifyouhavequestions
aboutanyaspectofthisbook,pleaseemailusatquestions@packtpub.com.
Errata: Although we have taken every care to ensure the accuracy of our
content,mistakes
dohappen.Ifyouhavefoundamistakeinthisbook,wewouldbegratefulifyou
would
report this to us. Please visit www.packtpub.com/submit-errata, selecting your book,
clickingontheErrataSubmissionFormlink,andenteringthe
details.
Piracy:Ifyoucomeacrossanyillegalcopiesofourworksinanyformonthe
Internet,
we would be grateful if you would provide us with the location address or
website
name.Pleasecontactusatcopyright@packtpub.comwithalinktothematerial.
Ifyouareinterestedinbecominganauthor:Ifthereisatopicthatyouhave
expertiseinandyouareinterestedineither
writingorcontributingtoabook,pleasevisitauthors.packtpub.com.
Reviews
Pleaseleaveareview.Onceyouhavereadandusedthisbook,whynotleavea
reviewonthesitethatyoupurchaseditfrom?Potentialreaderscanthenseeand
use your unbiased opinion to make purchase decisions, we at Packt can
understand what you think about our products, and our authors can see your
feedbackontheirbook.Thankyou!
FormoreinformationaboutPackt,pleasevisitpacktpub.com.
AnIntroductiontoMYSQL8
MySQL is a well-known open source structured database because of its
performance,easinesstouse,andreliability.Thisisthemostcommonchoiceof
web applications for a relational database. In the current market, thousands of
web-based applications rely on MySQL including giant industries such as
Facebook,Twitter,andWikipedia.
IthasalsoproventobethedatabasechoiceforSoftwareasaService(SaaS)
based applications such as Twitter, YouTube, SugarCRM, Supply Dynamics,
Workday,RightNow,Omniture,Zimbra,andmanymore.Wewilldiscussthisin
detail in the use cases of MySQL section later in the chapter. MySQL was
developed by MySQL AB, a Swedish company, and now it is distributed and
supportedbyOracleCorporation.MySQLcarriesavaluablehistorywithit.
MySQL has continued to improve in order to become an enterprise-level
database management system. MySQL 8 is expected to be a game-changer as
todayweareintheageofdigitization.
MySQL8isalltunedtoservemanynewusecasesthatinpriorversionswere
difficult to achieve. Some of the use cases an enormous amount of data is
produced are social networking, e-commerce, bank/credit card transactions,
emails, data stored on the cloud, and so on. Analysis of all such structured,
unstructured, or semi-structured ubiquitous data helps to discover hidden
patterns,markettrends,correlations,personalpreferences.
"Thereissomuchforeachofus"
- James Truslow Adams Let's take an in-depth look at MySQL 8 new features,
benefits, use cases along with a few limitations of MySQL 8 after we have an
overviewofMySQL.Thisisgoingtobeexciting,let'sgetprepared.
OverviewofMySQL
Structured Query Language (SQL) is used to manipulate, retrieve, insert,
update,anddeletedatainrelationaldatabasemanagementsystem(RDBMS).
Tomakeitsimpler,SQLtellsthedatabasewhattodoandexactlywhatitneeds.
SQL is a standard language that all RDBMS systems such as MySQL, MS
Access,MSSQL,Oracle,Postgres,andothersuse.
RDBMSisthebasisforSQLandforallmoderndatabasesystems
suchasMSSQLServer,IBMDB2,Oracle,MySQL,andMicrosoft
Access.
SQL allows users to access data from MySQL and define and manipulate the
data. To embed within other languages, you can leverage SQL modules,
libraries,andprecompilers,whichcanhelpyoucreate/dropdatabasesandtables,
allowuserstocreatetheview,andstoredprocedures,functions,andsoon,ina
database. It can do various other operations such as allowing users to set
permissionsontables,procedures,andviews.
MySQL as a relational database
managementsystem
Datainarelationaldatabaseisstoredinanorganizedformatsothatinformation
canberetrievedeasily.Datawillbestoredindifferenttablesmadeupofrows
and columns. However, the relationship can also be built between different
tablesthatefficientlystorehugedataand effectivelyretrievetheselecteddata.
Thisprovidesdatabaseoperationswithtremendousspeedandflexibility.
Asarelationaldatabase,MySQLhascapabilitiestoestablishrelationshipswith
differenttablessuchasonetomany,manytoone,andonetoonebyproviding
primarykeys,foreignkeys,andindexes.Itcanalsoperformjoinsbetweentables
toretrieveexactinformationsuchasinnerjoinsandouterjoins.
SQLisusedasaninterfacetointeractwiththerelationaldatainMySQL.SQLis
anAmericanNationalStandardInstitute(ANSI)standardlanguagewhichwe
canoperatewithdatasuchascreation,deletion,updating,andretrieval.
LicenserequirementsofMySQL8
Many industries prefer open source technology because of the technology's
flexibility and cost-saving features, while MySQL has put its footprint in the
marketbybecomingthemostpopularrelationaldatabaseforwebapplications.
Open source means that you can view the source of MySQL and customize it
basedonyourneedswithoutanycost.Youcandownloadthesourceorbinary
filesfromitssiteandusethemaccordingly.
TheMySQLserveriscoveredundertheGeneralPublicLicense(GNU),which
meansthatwecanfreelyuseitforwebapplications,studyitssourcecode,and
modify it to suit our needs. It also has the Enterprise Edition as well with
advancedfeaturesincluded.Manyenterprisesstillpurchasethesupportcontract
fromMySQL
togetassistanceonvariousissues.
Reliabilityandscalability
MySQL has great reliability to perform well without requiring extensive
troubleshooting due to bottlenecks or other slowdowns. It also incorporates a
number of performance enhanced mechanisms such as index support, load
utilities,andmemorycaches.MySQL
uses InnoDB as a storage engine, which provides highly efficient ACID
complianttransactionalcapabilitiesthatassurehighperformanceandscalability.
To handle the rapidly growing database, MySQL Replication and cluster help
scaleoutthedatabase.
Platformcompatibility
MySQL has great cross-platform availability that makes it more popular. It is
flexible to run on major platforms such as RedHat, Fedora, Ubuntu, Debian,
Solaris, Microsoft Windows, and Apple macOS. It also provides Application
Programming Interface (APIs) to interconnect with various programming
languagessuchasC,C++,C#,PHP,Java,Ruby,Python,andPerl.
Releases
HereisalistofmajorreleasesofMySQLsofar:
Version5.0GAwasreleasedon19thOctober,2005
Version5.1GAwasreleasedon14thNovember,2008
Version5.5GAwasreleasedon3rdDecember,2010
Version5.6GAwasreleasedon5thFebruary,2013
Version5.7GAwasreleasedon21stOctober,2015
Nowit'stimeforthemajorversionrelease--MySQL8--whichwasannouncedon
12thSeptember,2016andisstillinthedevelopmentmilestonemode.
CorefeaturesinMySQL
Let'slookbackandquicklyglancethroughsomeofthecorefeaturesinMySQL.
We will be discussing various features throughout the book in detail as we
progress.
Structureddatabase
Structured databases are traditional databases that have been used by many
enterprisesformorethan40years.However,inthemodernworld,datavolume
is becoming bigger and bigger and a common need has taken its place--data
analytics. Analytics is becoming difficult with structured databases as the
volumeandvelocityofdigitaldatagrowfasterbytheday;weneedtofindaway
to achieve such needs in an effective and efficient way. The most common
database that is used as a structured database in the open source world is
MySQL.
Manyorganizationsuseastructureddatabasetostoretheirdatainanorganized
waywiththeformattedrepository.Basically,datainastructureddatabasehasa
fixedfield,apredefineddatalength,anddefineswhatkindofdataistobestored
such as numbers, dates, time, addresses, currencies, and so on. In short, the
structureisalreadydefinedbeforedatagetsinserted,whichgivesacleareridea
ofwhatdatacanresidethere.Thekeyadvantageofusingastructureddatabase
isthatdatabeingeasilystored,queried,andanalyzed.
An unstructured database is the opposite of this; it has no identifiable internal
structure. It can have a massive unorganized agglomerate or various objects.
Mainly, the source of structured data is machine-generated, which means
information is generated from the machine and without human intervention,
whereasunstructureddataishuman-generateddata.Organizationsusestructured
databases for data such as ATM transactions, airline reservations, inventory
systems,andsoon.Inthesameway,someorganizationsuseunstructureddata
such as emails, multimedia content, word processing documents, web pages,
businessdocuments,andsoon.
<strong>mysql>SHOWTABLESTATUSLIKE'admin_user'\G;
</strong><br/><strong>***************************1.row
***************************</strong><br/><strong>Name:
admin_user</strong><br/><strong>Engine:InnoDB</strong><br/>
<strong>Version:10</strong><br/><strong>Row_format:
Dynamic</strong><br/><strong>Rows:2</strong><br/><strong>
Avg_row_length:8192</strong><br/><strong>Data_length:
16384</strong><br/><strong>Max_data_length:0</strong><br/>
<strong>Index_length:16384</strong><br/><strong>Data_free:
0</strong><br/><strong>Auto_increment:3</strong><br/>
<strong>Create_time:2017-06-1914:46:49</strong><br/><strong>
Update_time:2017-06-1915:15:08</strong><br/><strong>
Check_time:NULL</strong><br/><strong>Collation:
utf8_general_ci</strong><br/><strong>Checksum:NULL</strong>
<br/><strong>Create_options:</strong><br/><strong>Comment:
AdminUserTable</strong><br/><strong>1rowinset(0.00sec)
</strong>
<strong>mysql>SHOWENGINES\G;</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>Engine:
InnoDB</strong><br/><strong>Support:YES</strong><br/>
<strong>Comment:Supportstransactions,row-levellocking,and
foreignkeys</strong><br/><strong>Transactions:YES</strong><br
/><strong>XA:YES</strong><br/><strong>Savepoints:
YES</strong><br/><strong>***************************2.row
***************************</strong><br/><strong>Engine:
MRG_MYISAM</strong><br/><strong>Support:YES</strong><br
/><strong>Comment:CollectionofidenticalMyISAM
tables</strong><br/><strong>Transactions:NO</strong><br/>
<strong>XA:NO</strong><br/><strong>Savepoints:NO</strong>
<br/><strong>***************************3.row
***************************</strong><br/><strong>Engine:
MEMORY</strong><br/><strong>Support:YES</strong><br/>
<strong>Comment:Hashbased,storedinmemory,usefulfor
temporarytables</strong><br/><strong>Transactions:NO</strong>
<br/><strong>XA:NO</strong><br/><strong>Savepoints:
NO</strong><br/><strong>***************************4.row
***************************</strong><br/><strong>Engine:
BLACKHOLE</strong><br/><strong>Support:YES</strong><br
/><strong>Comment:/dev/nullstorageengine(anythingyouwriteto
itdisappears)</strong><br/><strong>Transactions:NO</strong><br
/><strong>XA:NO</strong><br/><strong>Savepoints:
NO</strong><br/><strong>***************************5.row
***************************</strong><br/><strong>Engine:
MyISAM</strong><br/><strong>Support:DEFAULT</strong><br
/><strong>Comment:MyISAMstorageengine</strong><br/>
<strong>Transactions:NO</strong><br/><strong>XA:NO</strong>
<br/><strong>Savepoints:NO</strong><br/>
<strong>***************************6.row
***************************</strong><br/><strong>Engine:
CSV</strong><br/><strong>Support:YES</strong><br/><strong>
Comment:CSVstorageengine</strong><br/><strong>Transactions:
NO</strong><br/><strong>XA:NO</strong><br/><strong>
Savepoints:NO</strong><br/>
<strong>***************************7.row
***************************</strong><br/><strong>Engine:
ARCHIVE</strong><br/><strong>Support:YES</strong><br/>
<strong>Comment:Archivestorageengine</strong><br/>
<strong>Transactions:NO</strong><br/><strong>XA:NO</strong>
<br/><strong>Savepoints:NO</strong><br/>
<strong>***************************8.row
***************************</strong><br/><strong>Engine:
PERFORMANCE_SCHEMA</strong><br/><strong>Support:
YES</strong><br/><strong>Comment:Performance
Schema</strong><br/><strong>Transactions:NO</strong><br/>
<strong>XA:NO</strong><br/><strong>Savepoints:NO</strong>
<br/><strong>***************************9.row
***************************</strong><br/><strong>Engine:
FEDERATED</strong><br/><strong>Support:NO</strong><br/>
<strong>Comment:FederatedMySQLstorageengine</strong><br/>
<strong>Transactions:NULL</strong><br/><strong>XA:
NULL</strong><br/><strong>Savepoints:NULL</strong><br/>
<strong>9rowsinset(0.00sec)</strong>
OverviewofInnoDB
InnoDBisthedefaultstorageenginebroadlyusedoutofallotheravailablestorage
engines.ItwasreleasedwithMySQL5.1asapluginin2008.MySQL5.5and
later has InnoDB as a default storage engine. It has been taken over by Oracle
CorporationinOctober
2005,fromtheInnobaseOy,whichisaFinland-basedcompany.
InnoDBtablessupport ACID-compliant commits,rollback, and crashrecovery
capabilitiestoprotect
user data. It also supports row-level locking, which helps with better
concurrency
andperformance.ItstoresdatainclusteredindexestoreduceI/Ooperationsfor
all SQL select queries based on the primary key. It also supports FOREIGN KEY
constraintsthatallowbetterdataintegrityforthedatabase.Themaximumsizeof
anInnoDBtablecanscaleupto64TB,whichshouldbegoodenough
toservemanyreal-worldusecases.
OverviewofMyISAM
MyISAM was the default storage engine for MySQLprior to 5.5 1. MyISAM storage
enginetablesdonotsupportACID-compliantasopposedtoInnoDB.MyISAMtables
support table-level locking only, so MyISAM tables are not transaction-safe;
however, they are optimized for compression and speed. It is generally used
whenyouneedtohaveprimarilyreadoperationswithminimaltransactiondata.
ThemaximumsizeofaMyISAMtablecangrowupto256TB,whichhelpsinuse
casessuchasdataanalytics.MyISAMsupportsfull-textindexing,whichcanhelpin
complexsearchoperations.Usingfull-textindexes,wecanindexdatastoredin
BLOBandTEXTdatatypes.
Overviewofmemory
Amemorystorageengineisgenerallyknownasaheapstorageengine.Itisused
toaccessdataextremelyquickly.ThisstorageenginestoresdataintheRAMso
itwouldn'tneedI/Ooperation.AsitstoresdataintheRAM,alldataislostupon
serverrestart.
Thistableisbasicallyusedfortemporarytablesorthelookuptable.Thisengine
supportstable-levellocking,whichlimitshighwriteconcurrency.
Importantnotesaboutmemorytablesareasfollows:
Because memory table stores data in the RAM, which has a very limited
storagecapacity;ifyoutrytowritetoomuchdataintothememorytable,it
willstartswappingdataintothediskandthenyoulosethebenefitsofthe
memorystorageengine
These tables don't support TEXT and BLOB data types, and it is not even
requiredasithaslimitedstoragecapacity
This storage engine can be used to cache the results; lookup tables, for
example,orpostalcodesandthenamesofstates
MemorytablessupportB-treeindexesandHashindexes
Overviewofarchive
Thisstorageengineisusedtostorelargeamountsofhistoricaldatawithoutany
indexes.Archivetablesdonothaveanystoragelimitations.Thearchivestorage
engine
is optimized for high insert operations and also supports row-level locking.
Thesetablesstoredata
inacompressedandsmallformat.ThearchiveenginedoesnotsupportDELETEor
UPDATEoperations;itonlyallowsINSERT,REPLACE,andSELECToperations.
Overview of BLACKHOLE as a
storageengine
Thisstorageengineacceptsdatabutdoesnotstoreit.Itdiscardsdataafterevery
INSERTinsteadofstoringit.
Now, what is the use of this storage engine; why would anybody use it? Why
wouldwerunanINSERTquerythatdoesn'tinsertanythingintothetable?
This engine is useful for replication with large number of servers. A BLACKHOLE
storageengineactsasafilterserverbetweenthemasterandslaveserver,which
donotstoreanydata,butonlyapplyreplicate-do-*andreplicate-ignore-*rulesand
writeabinlogs.Thesebinlogsareusedtoperformreplicationinslaveservers.We
willdiscussthisindetailinChapter8,ReplicationinMySQL8.
OverviewofCSV
The comma separated values (CSV) engine stores data in the .csv file type
using the comma-separated values format. This engine extracts data from the
databaseandcopiesitto.csvoutofthedatabase.IfyoucreateaCSVfilefrom
thespreadsheetandcopyitinto
the MYSQL data folder server, it can read the data using the select query.
Similarly,
ifyouwritedatainthetable,anexternalprogramcanreaditfromtheCSVfile.
This storage engine is used for the exchange of data between software or
applications.
ACSVtabledoesnotsupportindexingandpartitioning.AllcolumnsintheCSV
storage
engineneedtobedefinedwiththeNOTNULLattributetoavoiderrorsduringtable
creation.
Overviewofmerge
Thisstorage engineisalsoknownasanMRG_MyISAM storageengine. Thisstorage
enginemergesaMyISAMtableandcreatesittobereferredtoasingleview.Fora
mergetable,allcolumns
are listed in the same order. These tables are good for data warehousing
environments.
The table is used to manage log-related tables, generally. You can create
different
monthsoflogsinseparateMyISAMtablesandmergethesetablesusingthemerge
storageengine.
MyISAMtableshavestoragelimitfortheoperatingsystem,butacollectionofMyISAM
(merge)tablesdonothave storagelimits.So usingamergetablewouldallow
you
to split data into multiple MyISAM tables, which can help in overcoming storage
limits.
Merge tables do not support partitioning. Also, you cannot partition a merge
table
oranyofamergetable'sunderlyingMyISAMtablesinadifferentpartition.
Overviewoffederated
Thisstorageengineallowsyoutocreateasingledatabaseonamultiplephysical
server.Itopensaclientconnectiontoanotherserverandexecutesqueriesagainst
atablethere,retrievingandsendingrowsasneeded.Itwasoriginallymarketed
as a competitive feature that supported many enterprise-grade proprietary
databaseservers,suchasMicrosoftSQLServerandOracle,butthatwasalways
astretch,tosaytheleast.Althoughitseemedtoenablealotofflexibilityand
neat tricks, it has proven to be a source of many problems and is disabled by
default.ThisstorageengineisdisabledbydefaultinMySQL;toenableit,you
needtostarttheMySQLserverbinaryusingthefederatedoption.
OverviewoftheNDBcluster
NDBcluster(alsoknownasNDB)isanin-memorystorageengineofferinghigh
availabilityanddatapersistencefeatures.
TheNDBclusterstorageenginecanbeconfiguredwitharangeoffailoverand
loadbalancing options, but it is easiest to start with the storage engine at the
clusterlevel.NDBclusterusestheNDBstorageenginethatcontainsacomplete
set of data, which is dependent only on other datasets available within the
cluster.
The cluster portion of the NDB cluster is configured independently of the
MySQLservers.InanNDBcluster,eachpartoftheclusterisconsideredtobea
node.
Eachstorageenginehasitsownadvantageandusability,asfollows:
SearchEngine:NDBCluster
Transactionsdata:InnoDB
Sessiondata:MyISAMorNDBCluster
Localizedcalculations:Memory
Dictionary:MyISAM
Thefollowingdiagramwillhelpyouunderstandwhichstoreengineyouneedto
useforyourrequirement:
Nowyouhaveabetter ideaaboutvariousstorageenginesalongwithdifferent
usecases,whichwillhelpyoutomakeadecisionbasedonyourneeds.
It's time to move on to our next topic where we will look at delightful new
featuresavailableinMySQL8.
ImprovedfeaturesinMySQL8
The MySQL database development team has recently announced its major
releaseasMySQL
8DevelopmentMilestoneRelease(DMR).Itcontainssignificantupdatesand
fixesforproblemsthatweremuchneeded.
You might be wondering why it's 8 after 5.7! Were the intermediate versions,
thatis,6and7,missout?Ofcoursenot!Actually,6.0waspreservedaspartof
the changeover to a more frequent and timely release, while 7.0 for the
clusteringversionofMySQL.
Let'sseesomeexcitingfeaturesthathavebeenintroducedinthislatestversion,
as depicted in the following diagram:
It's time to look at MySQL 8 features in detail, which makes us excited and
convincedaboutthereasonsforamajorversionupgradeofMySQL.
Transactionaldatadictionary
Upuntilthepreviousversion,theMySQLdatadictionarywasstoredindifferent
metadatafilesandnon-transactionaltables,butfromthisversiononwards,itwill
haveatransactionaldatadictionarytostoretheinformationaboutthedatabase.
Nomore.frm,.trg,or.parfiles.All informationwillbestoredin thedatabase,
which removes the cost of performing heavy file operations. There were
numerous issues with filesystem metadata storage such as the vulnerability of
the filesystem, exorbitant file operations, difficult to handle crash recovery
failures,orreplication;itwasalsodifficulttoaddnewfeature-relatedmetadata.
Now this upgrade has made it simple by storing information in a centralized
manner,andwillhaveimprovedperformanceasthisdatadictionaryobjectcan
becachedinmemory,similartootherdatabaseobjects.
ThisdatadictionarywillhavedatathatisneededforSQLqueryexecutionsuch
as catalog information, character sets, collations, column types, indexes,
database information, tables, stored procedures, functions and triggers, and so
on.
Roles
In MySQL 8, the privileges module has been improved by introducing roles,
which means a collection of permissions. Now we can create roles with a
numberofprivilegesandassignthemtomultipleusers.
The problem with the previous version was that we were not able to define
genericpermissionsforagroupofusersandeachuserhasindividualprivileges.
Supposeifthereare1,000usersalreadyexistingthathavecommonprivileges,
andyouwanttoremovethewritepermissionsforthese1,000users,whatwould
youhavedone intheprevious version?You wouldhavehad totakethe time-
consuming approach of updating each user, right? Arrgh! That's a long, long
task.
Now with MySQL 8, it is easy to update any change in privileges. Roles will
define all the required privileges and this role will be assigned to those 1,000
users.Wejustneedtomakeanyprivilegechangesintheroleandalluserswill
automaticallyinherittherespectiveprivileges.
Rolescanbecreated,deleted,grantorrevokepermission,grantorrevokefrom
theuseraccount,andcanspecifythedefaultrolewithinthecurrentsession.
InnoDBautoincrement
MySQL 8 has changed the auto-increment counter value store mechanism.
Previously, it was stored in the memory, which was quite difficult to manage
during server restarts or server crashes. However, now the auto-increment
countervalueiswrittenintotheredologwheneverthevaluegetschangedand,
on each checkpoint, it will be saved in the system table, which makes it
persistentacrosstheserverrestart.
Withthepreviousversion,updateoftheauto-incrementvaluemayhavecaused
duplicateentryerrors.Supposeifyouupdatedthevalueofauto-incrementinthe
middleofthesequencewithalargerthanthecurrentmaximumvalue,butthen
subsequentinsertoperationscouldnotidentifytheunusedvalues,whichcould
cause a duplicate entry issue. This has been prevented by persisting the auto-
incrementvalue,hencesubsequentinsertoperationscangetthenewvalueand
allocateitproperly.
Ifserverrestarthappened,the auto-incrementvaluewas lostwiththeprevious
versionasitwasstoredinmemoryandInnoDBneededtoexecuteaquerytofind
outthemaximumusedvalue.Thishasbeenchanged,asthenewerversionhas
thecapabilitytopersistitsvalueacrosstheserverrestart.
Duringtheserverrestart,InnoDBinitializesthecountervalueinmemoryusingthe
maximum value stored in the data dictionary table. In case of server crashes,
InnoDB initializes the auto-increment counter value that is bigger than the data
dictionarytableandtheredolog.
<strong>ALTERTABLEtable1ALTERINDEXix_table1_col1
INVISIBLE;</strong><br/><strong>ALTERTABLEtable1ALTER
INDEXix_table1_col1VISIBLE;</strong>
Improvingdescendingindexes
Descendingindexesexistedinversion5.7too,buttheywerescannedinreverse
order,whichcaused performancebarriers. Toimprove performance,MySQL8
hasoptimizedthisandscanneddescendingindexesinforwardorder,whichhas
drasticallyimprovedperformance.
Italsobringsmultiplecolumnindexesfortheoptimizerwhenthemostefficient
scan order has ascending order for some columns, and descending order for
othercolumns.
<strong>SETGLOBALmax_connections=1000;</strong>
<strong>SETPERSISTmax_connections=1000;</strong>
ExpandedGISsupport
Until the previous version, it supported only one coordinate system, a unitless
2D
placethatwasnotreferencedtoapositiononearth.NowMySQL8hasadded
support for a Spatial Reference System(SRS) with geo-referenced ellipsoids
and2Dprojections.SRShelps assigncoordinatestoalocationandestablishes
relationshipsbetweensetsofsuchcoordinates.Thisspatialdatacanbemanaged
indatadictionarystorageastheST_SPATIAL_REFERENCE_SYSTEMStable.
Defaultcharacterset
The default character set has been changed from latin1 to UTF8. UTF8 is the
dominatingcharacterset,thoughithadn'tbeenadefaultoneinpreviousversions
of MySQL. Along with the character set default, collation has been changed
fromlatin1_swedish_ci to utf8mb4_800_ci_ai. With these changes globally accepted,
charactersetsandcollationsarenowbasedonUTF8;oneofthecommonreasons
is because there are around 21 different languages supported by UTF8, which
makessystemsprovidemultilingualsupport.
Extendedbit-wiseoperations
InMySQL5.7,bit-wiseoperationsandfunctionswereworkingforBIGINT(64-bit
integer)datatypesonly.WeneededtopassBIGINTasanargumentanditwould
return the result as BIGINT. In short, it had maximum range up to 64 bits to
performoperations.AuserneedstodoconversiontotheBIGINTdatatypeincase
theywanttoperformitonotherdatatypes.Thistypecastingwasnotfeasiblefor
datatypeslargerthan64bitsasitwouldtruncatetheactualvalue,whichresulted
ininaccuracy.
MySQL8hasimprovedbit-wiseoperationsbyenablingsupportforotherbinary
data types such as Binary,VarBinary, and BLOB. This makes it possible to perform
bit-wiseoperationsonlargerthan64-bitdata.
Nomoretypecastingneeded!Thisallowsthetakingofargumentsandreturning
resultslargerthan64bits.
InnoDBMemcached
Multiple get operations are now possible with the InnoDB memcached plugin,
which will really help in improving the read performance. Now, multiple key
value pairs can be fetched in a single memcached query. Frequent
communicationtraffichasalsobeenminimizedaswecangetmultipledataina
singleshot.
RangequeriesarealsosupportedbytheInnoDBMemcachedplugin.Itsimplifies
rangesearchesbyspecifyingaparticularrangeandretrievesvalueswithinthis
range.
<strong>SELECT*FROMtable1WHEREid=5FORUPDATE
NOWAIT;</strong><br/><strong>SELECT*FROMtable1FOR
UPDATESKIPLOCKED;</strong>
JSON
JSONsupporthadbeenimplementedinMySQL5.7;itwaswell-acknowledged
feature.
InMySQL 8 ithasadded variousfunctionsthat wouldallowus togetdataset
resultsinJSONdataformat,virtualcolumns,andtentatively15SQLfunctions
thatallowyoutosearchanduseJSONdataonserverside.InMySQL8thereare
additionalaggregationfunctionsaddedthatcanbeusedinJSONobjects/arrays
torepresentloadeddatainafurtheroptimizedway.Thefollowingarethetwo
JSONaggregationfunctionsthatwereintroducedinMySQL8:
JSON_OBJECTAGG()
JSON_ARRAYAGG()
Cloud
InMySQL8 anewoptionisintroducedinnodb_dedicated_server,whichwouldbe
helpfulforverticalscalingoftheservers.Itactuallyautomatically
detectsthememoryallocatedtothevirtualserverandappropriatelysetMySQL
8without
any need to change configuration files. These would be very handy features
considering
theadoptionofvirtualizationandcloudisthere.Infactwiththisconfiguration,
youmight noteven needtogetshellaccessofservertoedit theconfiguration
files.
You can do this with the new SET PERSIST feature that can set relevant
configurationfromtheMySQLcommandlineitself,which
can enhance security further as you almost wouldn't need shell access of the
server.
Resourcemanagement
MySQL8hascomeupwithawonderfulresourcemanagementfeaturethatwill
allowyouto allocateresourceto threads runningona server, whichwouldbe
executedbasedontheresourcesconfiguredforthegroup.Currently,CPUtime
isaresourcethatcanbeconfiguredforagroup.Withthis,youcantweakyour
workloadswithvirtualresourcemanagementwithinMySQLitself.MySQLwill
identifyonstartupnumbersofvirtualCPUsavailableandafterthatuserswith
appropriateprivilegescanmapthevirtualCPUswithresourcegroupandalign
threadmanagementtothesegroups.
We expect to see more features by the time MySQL 8 is available for general
use.LetusnowlookatbenefitsofusingMySQL8.
BenefitsofusingMySQL8
Whetheryouareadeveloperoranenterprise,youwouldobviouslychooseone
thatprovidesgoodbenefitsandresultswhencomparedtootherrelatedproducts.
MySQL
providesnumerousadvantagesasthefirstchoiceinthiscompetitivemarket.It
has various powerful features available that make it a more comprehensive
database.Let'snowgothroughsomebenefitsofusingMySQL.
Security
Thefirstthingthatcomestomindissecuringdatabecausenowadaysdatahas
becomepreciousandcanimpactbusinesscontinuityiflegalobligationsarenot
met;infact, itcanbe sobadthat it canclose down yourbusinessin notime.
MySQL is the most secure and reliable database management system used by
manywell-knownenterprisessuchasFacebook,Twitter,andWikipedia.Itreally
providesagoodsecuritylayerthatprotectssensitiveinformationfromintruders.
MySQLgivesaccesscontrolmanagementsothatgrantingandrevokingrequired
accessfromtheuseriseasy.Rolescanalsobedefinedwithalistofpermissions
thatcanbegrantedorrevokedfortheuser.
All user passwords are stored in an encrypted format using plugin-specific
algorithms.
Scalability
Day by day, the mountain of data is growing because of extensive use of
technologyinnumerousways.Becauseofthis,loadaverageisgoingthroughthe
roof.Insomecases,itisunpredictablethatdatacannotexceeduptosomelimit
or number of users will not go out of bounds. Scalable databases would be a
preferable solution so that, at any point, we can meet unexpected demands to
scale.MySQLisarewardingdatabasesystemforitsscalability,whichcanscale
horizontally and vertically; in terms of data, spreading database and load of
applicationqueriesacrossmultipleMySQL
servers is quite feasible. It is pretty easy to add horsepower to the MySQL
clustertohandletheload.
An open source relational
databasemanagementsystem
MySQLisanopensourcedatabasemanagementsystemthatmakesdebugging,
upgrading, and enhancing the functionality fast and easy. You can view the
sourceandmakethechangesaccordinglyanduseitinyourownway.Youcan
also distribute an extended version of MySQL, but you will need to have a
licenseforthis.
Highperformance
MySQL gives high-speed transaction processing with optimal speed. It can
cache the results, which boosts read performance. Replication and clustering
make the system scalable for more concurrency and manages the heavy
workload. Database indexes also accelerate the performance of SELECT query
statementsforsubstantialamountofdata.Toenhanceperformance,MySQL8
hasincludedindexesinperformanceschematospeedupdataretrieval.
Highavailability
Today,intheworldofcompetitivemarketing,anorganization'skeypointisto
have their system up and running. Any failure or downtime directly impacts
business and revenue; hence, high availability is a factor that cannot be
overlooked.MySQLisquitereliableandhasconstantavailabilityusingcluster
andreplicationconfigurations.
Cluster servers instantly handle failures and manage the failover part to keep
yoursystemavailablealmostallthetime.Ifoneservergetsdown,itwillredirect
theuser'srequesttoanothernodeandperformtherequestedoperation.
Cross-platformcapabilities
MySQL provides cross-platform flexibility that can run on various platforms
suchasWindows,Linux,Solaris,OS2,andsoon.IthasgreatAPIsupportfor
the all major languages, which makes it very easy to integrate with languages
such as PHP, C++, Perl, Python, Java, and so on. It is also part of the Linux
Apache MySQL PHP (LAMP) server that is used worldwide for web
applications.
It's now time to get our hands dirty and look at MySQL 8; let's start with the
installationofMySQL8onaLinuxplatforminourcase.WepreferMySQL8
onaLinuxoperatingsystemasthathasbeenacommonusecaseacrossmany
organizations.WewillbediscussingmoreinstallationinChapter2,Installingand
UpgradingMySQL8.YoucanuseitonotherplatformsthatMySQLsupports,
suchasWindows,Solaris,HP-UNIX,andsoon.Linuxprovidesvariouswaysto
installtheMySQLserver,asfollows:
RPMpackage
YUMrepository
APTrepository
SLESrepository
Debianpackage
TARpackage
Compilingandinstallingfromthesourcecode
LimitationsofMySQL8
A coin has two sides; similarly, benefits of also using MySQL 8 would come
alongwithafewlimitations.LetuswalkthroughafewareasofMySQL8now.
Numberoftablesordatabases
ThenumberofdatabasesortablesarenotalimitationforMySQL8;however,
theoperatingsystemfilelimitcanbealimitationforMySQL8.StorageEngine
InnoDBisallowedtoscaleuptofourbilliontablesasitspeaknumber.
Tablesize
Youmayhitmaximumtablesizelimit,whichisnotrestrictedfromMySQL8;
however,itmaybebecauseofoperatingsystemfilesystemlimits.
Joins
Inasinglejoin,onecanuse61tables,whichcanbereferred.Itisalsoapplicable
to the tables that are referenced in view definition. Joins that are part of
subqueriesandviewsarealsoconsideredtobepartofthelimitation.
Windowsplatform
There are few limitations when you have MySQL 8 used on the Windows
platform:
Memory:32-bitarchitecturehaslimitationtouseonly2GBofRAMfora
process.
Ports: In case you have a high number of concurrency you might come
across Windows platform limitation of having 4000 ports available for
clientconnectionsintotal.
Case-insensitivity: The Windows platform doesn't have case sensitivity,
which is why tables and databases need to be deliberately managed for
case-insensitivity.
Pipes:|, generally referred as pipe signs, they are not fully supported in
Windows. You might come across them in a few scenarios while doing
databaseadministrationactivities.
Pathname separator: MySQL 8 escape character is \, which is the
pathnameseparatorforWindows.Hencewhileusingpathseparatoryoucan
doubleslashas"\\"asanalternativeforapathnameseparator.
Tablecolumncount
The table column for each table in MySQL 8 has a limit of 4096 columns. It
mightvarybasedonafewotherfactorsforcolumnscountlimit,asstatedinthe
followingsection.
Rowsize
MySQLtableshavealimitof65,535bytesforarow,althoughstorageengines
suchasInnoDBarecapableofsupportinglargerchunks.
InnoDBstorageengine
Limitations on InnoDB storage engine are what we will talk about a bit more
specificallyasInnoDBnowwithMySQL8willplayaprominentrole.
Limitations of InnoDB storage
engine
WewillhaveaquickglanceatafewofthelimitationsofInnoDBstorageengine:
Thenumberofindexessupportedcanbemaximum64foratable
Fortablesthat usecompressed ordynamicrow format;3072 istheindex
keyprefixlengthlimit
Fortablesthatusecompactorredundantrowformat;767istheindexkey
prefixlengthlimit
Total columns in a table, which includes virtual generated columns, are
limitedtoamaximumof1,017
16columnsisthemaximumpermittedformulti-columnindexes
ThecombinedInnoDBlogfilesizecannotexceed512GB
MaximumtablesizesupportedbyInnoDBis256TB
AdminAPIisnotsupportedwhileusingunixsocketconnections
Multi-byte characters might give you unreliable aligned columns while
formattingofresultsinInnoDBclusters
Restrictions
WewillnowhaveaquickglanceatafewoftherestrictionsoftheInnoDBstorage
engine:
Delete from tablename:Itdoesn'tactuallydeletethecompletetable,insteadit
deleteseachrowofthetableoneafteranother.
Show table status: It wouldn't provide you accurate data all the time; it
providesestimates.
When counting rows, the number of rows provided by count(*) is not
accuratebecauseofconcurrency;itwouldcountonlythosecountsvisible
totransactionscurrentlyavailable.
Ifthereismultipleanalyzetablequeriesexecuted,lateronewillbeblocked
untilthefirstonegetscompleted.
InnoDBkeeps anexclusivelockontheindexattheendassociatedwiththe
auto_incrementcolumn.
Inacasetheauto_incrementintegerrunsoutofthevalue;thefollowinginsert
operationswouldshowusduplicate-keyerrors.
Foreignkeysthatarecascadedcannotactivatetriggers.
There are a few column names reserved by MySQL that InnoDB uses for
internalpurposes.Thefollowingareafewsuchcolumnnames:
DB_ROW_ID
DB_TRX_ID
DB_ROLL_PTR
DB_MIX_ID
Wemightcomeacrossoutputshowninthefollowingexampleincaseof
suchreservedcolumnnamesused:
mysql>CREATETABLEchintan(c1INT,db_row_idINT)
ENGINE=INNODB;ERROR1166(42000):Incorrectcolumnname'db_row_id'
InnoDB locks are released immediately after the transaction is aborted or
committed,whichisheldbyatransaction.
Theadditionoftablelocksarenotsupported,aslocksareimplicittocommit
andunlocktables
Datadictionary
Letushavealookatafewknownlimitationsofdatadictionary:
IndividualMyISAMtablesforbackupandrestorearenotsupportedbymerely
copyingthefiles.
ManuallycreateddirectoriesfordatabasesarenotsupportedbyMySQL8.
For instance, using mkdir would have no impact on MySQL server data
dictionary.
DDLoperationswouldtakemoretimethanexpectedbecausesuchoperations
arewrittentostorage,undologsandredoinsteadof.frmfilesaswhatwe
wouldhaveseeninpriorversionsofMySQL.
Limitationsofgroupreplicationin
MySQL8
It'snowtimetodiscussafewlimitationsofgroupreplicationinMySQL8:
Largetransactions: Transactions that result to GTID contents cannot be
replicatedbetweentherestofthemembersofthegroupifthey'retoolarge.
It is suggested to use smaller chunks of data that cannot be replicated in
aroundfivesecondstogroupmemberstoavoidfailures.
Clusterfromagroup:Ifyoutrytocreateclustersfromanexistinggroup
replicationsetupitwillresultinanerrorastheinstancewouldalreadybe
part of a replication group. This is noticed currently only in MySQL's
wizardmodeonly;analternativesolutionfortheissueistodisablewizard
mode.
Serializable isolation level: Serializable isolation level is not supported
whenmulti-primarygroupsareused,whichisthedefaultconfiguration.
DDL and DML operations: If there is concurrent DDL and DML
operationsexecutedagainstthesamedataobjectbutondifferentserversis
notsupportedwhenmulti-primarygroupmodeisused.
Replication checksum: Currently MySQL design limitations create
restrictionsofhavingreplicationeventchecksums.
Limitationsofpartitioning
Wewillbediscussinglimitationsofpartitioninginthissection.
Constructsprohibition
Thefollowingaretheconstructsthatarenotallowedinexpressionsofpartitions:
Declaredvariables
Uservariables
Storedprocedures
Storedfunctions
UDFs
Plugins
Operators
There are a few operators that are not permitted in partition expressions such
as<<,>>,|,&,~and^.Resultsforarithmeticoperatorssuchas+,-,and*must
haveanintegervalueorNULL.
Tables
Thefollowingareafewspecificareasthatshowuslimitationsofpartitioningon
tables:
Themaximum numberof partitionssupported byMySQL 8fora tableis
8192.Thislimitalsoconsiderssub-partitions.
Fulltextindexandsearchisnotsupportedonpartitionedtables.
Tablesthataretemporarycannotbepartitioned.
Logtablescan'tbepartitioned.
ForeignkeysarenotsupportedonpartitionedInnoDBstorageengine.
Thedatatypeofpartitionkeysshould bean integercolumnorcanbe an
expression to an integer. Expression or column values may be NULL;
however,expressionsthatincludeENUMarenotsupported.
UpgradingpartitionedtablesthathavebeenpartitionedbyKEYwouldhave
tobereloaded,whichstandstrueotherthantheInnoDBstorageengine.
Wehavesofardiscussedoverview,features,benefits,andafewlimitationsof
MySQL.
LetusnowwalkthroughthewonderfulusecasesofMySQL.
UsecasesofMySQL
MySQL has many advantages because it has its foot in many industries and
various usecases across theglobe. The importance of MySQL doesn't depend
onlyonhowmuchdatayouhave,it'sratherwhatyouaregoingtodowiththe
data.Datacanbesourcedandanalyzedfromunpredictablesourcesandcanbe
usedtoaddressmanythings.
Let's now look at use cases with real-life importance made on renowned
scenarioswiththehelpofMySQL:
The preceding figure helps us understand where MySQL is serving various
industries.
Thoughit'snotanextensivelistofindustrieswhereMySQLhasbeenplayinga
prominentroleinbusinessdecisions,let'snowdiscussafewoftheindustries.
Socialmedia
Social media content is information, and so are engagements such as views,
likes,demographics,shares,follows,uniquevisitors,comments,anddownloads.
At the end of the day, what matters is how your social media-related efforts
contributetothebusiness.
OnenotableexampleisFacebook,whereMySQLhadbeenusedextensively.On
top of MySQL where petabytes of data was used to serve likes, shares, and
comments. Facebook has developed the RocksDB storage engine on top of the
MySQL InnoDB storage engine, which leverages many advantages of InnoDB
storageengineasFacebookwantedtoprimarilyfocusonstorageoptimization.
ThoughcurrentlyMySQLisstillusedlargelyforothercommonapplications.
Government
The era of MySQL has been playing a significant role in government too;
government bodies have been using MySQL extensively because of splendid
returnoninvestmentsandpromotingopensource.Infact,thegovernmentsector
iscarryingoutahugenumberofimplementationsofMySQLworldwide.
Thismaycomeasasurprisetoyou;USNavyusesMySQLforitscriticalflight
planningactivities.Therearevariousactivitiessuchasweatherconditions,flight
plans, fuel efficiency, maintenance of flights, and many more that are being
trackedwiththehelpofMySQLasthedatabase.It'sano-brainerthatitneedsto
run 24x7 with full redundancy; MySQL was able to achieve this serving US
Navyaircraftacrosstheglobe.
Mediaandentertainment
YouTubeisalso oneof theprominentusers ofMySQL. Anytimeyou watcha
videoon YouTubeit getsdata fromarelationaldatabaseorablob storeusing
MySQL.YouTube alsouses Vitess;aprojectthatwasreleased byYouTube to
frontendMySQL.Vitesshelpstodolotsofoptimizationandactsasaproxyto
serveeachdatabaserequestusingMySQL.MySQLreplicasareheavilyusedin
YouTube's implementation; leveraging MySQL caching was one of the other
prominentfactorsforYouTube.
Frauddetection
Whenitcomestosecurity,frauddetection,orcompliance,andpreciselyifyour
solutionhelpsyouinidentifyingandpreventingissuesbeforetheystrike,thenit
becomesasweetspotforbusiness.Mostofthetime,frauddetectiontakesplace
alongtimeafterthefraudhasoccurred,whenyoumighthavealreadysuffered
loss. The next steps would be obviously to minimize the impact of fraud and
improveareasthatcouldhelpyoupreventthisfrombeingrepeated.
Manycompanieswhoareintoanytypeoftransactionprocessingorclaimsuse
fraud detection techniques extensively. MySQL helps to analyze transactions,
claims, and so on in real time, along with trends or anomalous behavior to
preventfraudulentactivities.
PayPal is one of such use cases that has built fraud detection system using
MySQL.
PayPal has more than 100 million active users, which is distributed to US,
Japanese, and European data centers. High-availability for such use cases is a
keycriteriaalongwithperformance,whichMySQLhasbeenabletodeliveras
expected.
Businessmapping
Netflix has millions of subscribers; it uses MySQL for running its billing
systems.
ThecorebillingsystemofNetflixonMySQLisaprominentbackboneforany
business.
Netflixhasbillionsofrowsofdataconcurrentlyupdatedandofconsistingdata
since
itsinceptiontwodecadesago.Compliancewasoneofthekeyfactorsalongwith
migration
fromOraclewithminimaldowntime;bothofthesewereachievedwithMySQL
andhas
beenexpandingtremendouslyeveryotherday.
E-commerce
Uber is one of the other well-known customers of MySQL. Uber had been
growingenormouslyworldwide,andscalability,high-availability,andreturnon
investmentswereafewoftheimportantcriteriatobeworkedupon.Uberuses
MySQLasitsprimarydatabaseforitsknownprivatecartransportationservice.
Uberheavilyusesschemalessdatabasearchitectureasitsbackendasalayeron
MySQL.
There are many real-world MySQL use cases that have changed humanity,
technology, predictions, health, science and research, law and order, sports, e-
commerce, power and energy, financial trading, robotics, and many more.
MySQLisanintegralpartofourdailyroutine,whichisnotevidentallthetime,
butyes,itplaysasignificantroleinwhatwedoinmanyways.
Summary
In this chapter, we started with an overview of MySQL along with major
features of the MySQL database and explored the newly added features in
MySQL8.Afterthis,wetookadeepdiveintoexcitingnewfeaturesofMySQL
8alongwith
benefitsofusingMySQLforyourbusinessapplications.WeunderstoodMySQL
8'scurrent
limitations and restrictions, which is important for us when performing the
implementations.
Finally,weglancedthroughafewimpressiveusecasesfromtherealworldthat
play
prominentrolesinourdailyroutine,andtheyalluseMySQLastheirdatabase.
In the next chapter, we will learn detailed steps for installing MySQL 8 on
different
platforms. The chapter also covers methods to upgrade or downgrade from
MySQL8,and
theywillallbediscussedindetail.
Installing and Upgrading MySQL
8
Inthepreviouschapter,weprovidedanoverviewofMySQLalongwithMySQL
8'snewfeatures,usecases,andlimitations.MySQLisveryflexibleintermsof
platforms, such as RedHat, Fedora, Ubuntu, Debian, Solaris, Microsoft
Windows, and so on. It has the support of an API to connect with different
languages, such as C, C++, C#, PHP, Java, Ruby, and many more. For any
programmingplatform,themostimportantandmonotonoustaskistosetupthe
environment with the necessary software tools. That won't be the case for
MySQL
8,asthischapterisfocusedonsettinguptheenvironmentwithMySQL8.
ThischapterexplainsMySQL8'sinstallationstepsindetailwiththenecessary
prerequisites.
SeparateinstallationstepsareprovidedtosetupMySQL8onvariousplatforms.
ThechapteralsocoversmethodstoupgradetoordowngradefromMySQL8.
Wewillcoverthefollowingtopicsinthischapter:
TheMySQL8installationprocess
Post-installationsetupforMySQL8
MySQL8upgrading
MySQL8downgrading
TheMySQL8installationprocess
This section will guide readers in MySQL 8 version selection, where to get
MySQL 8 from, and how to install MySQL 8. It also explains the post-
installationstepsrequiredforsetup.Thischapterprovidesinformationonhowto
upgradeordowngradefromMySQL8.
Generalinstallationguide
MySQL8isavailableonmanyoperatingsystemswithdifferent versions.The
MySQL
8releaseismanagedintwoways:
Developmentrelease:Thishasthenewestfeaturebutisnotrecommended
foruseinproduction
Generalrelease:Thisisastablereleaseanduserscanuseitforreleasein
productionalso
NamingconventionsarefollowedineachreleaseofMySQL8,whichindicates
itsstatus.
Eachreleasenameconsistsofthreedigitsandanoptionalsuffix.Forexample,
mysql.8.1.2-rc.Thenumbersareinterpretedasfollow:
Thefirstnumber(8)indicatesamajorversionoftherelease.
The second number (1) indicates a minor version of the release. A
combinationofmajorandminornumbersdescribestheseriesoftherelease.
The third number (2) indicates the version within the release series. It is
incrementedoneachbugfixrelease.
Themostrecentversionofthereleaseisthemostpreferableforuse.Thesuffix
givenintheexampleindicatesthestabilityoftheMySQL8release.TheMySQL
8
releasefollowsthreesuffixes:
DevelopmentMilestoneRelease(dmr):MySQL 8follows themilestone
model,whereeachmilestoneindicatesthoroughlytestedfeatures.
ReleaseCandidate(rc):Anewfeaturemightget releasedinthisversion
buttheaimistofixbugswithinthepreviouslyreleasedfeatures.
Absence of a suffix: This indicates General Availability (GA) or
productionrelease.Thisreleaseisstableandpassedthroughearlierstages.
Itisreliableandsuitableforuseinproduction.
As described, preceding each release is the DMR, followed by the RC, and
finallytheGAreleasestatus.Now,afterdecidingtheMySQL8versionforthe
installation,it'stimetoselectthedistributionformat.
Thebinarydistributionisrecommendedforgeneral-purposeuse.Itisavailable
innativeformatsformanyplatforms.Forexample,theRPMpackageforLinux
andDMG
packageforOSX.
DownloadingMySQL8
TogetMySQL8fromtheofficialsite,refertothefollowingURL:http://dev.mysq
l.com/downloads/.MySQLalsoprovidesamirrorsite:http://dev.mysql.com/downloads/m
irrors.html.Whenyoureachthedownloadpage,youcanseetheversionselection
tabatthebottomsideofthepage,wheretwotabsaredisplayed:
GenerallyAvailable(GA)release
Developmentrelease
Basedontheprevioussection,selectthesuitableversionfromthelistandclick
ontheDownloadbutton.
Verifyingthepackageintegrity
This is a stage where the downloaded package is available and ready for the
installation.
It'sanoptionalstep,butwerecommendittoavoiderrorsduringtheinstallation
process.Therearethreedifferentwaysavailabletocheckintegrity:
UsingMD5checksums
Usingcryptographicsignatures
UsingtheRPMintegrityverificationmechanism
<strong>E:\Softwares\md5>md5.exe<br/>E:\Softwares\mysql-
installer-community-5.7.19.0.msi</strong><br/><strong>
2578BFC3C30273CEE42D77583B8596B5<br/>
E:\Softwares\mysql-installer-community-5.7.19.0.msi</strong>
Performthefollowingstepsforthegraphicaltoolexecution:
1. Openthelink:
http://www.nullriver.com/index/products/winmd5sum.
2. ClickontheDownloadWinMD5Sumoptiononthepage.Itwill
downloadwinMD5Sum.exeontoyourcomputer.
3. RunthedownloadedInstall-winMD5Sum.exeandinstalliton
yourlocalmachine.
4. Aftersuccessfulinstallation,openthewinMD5Sumtool.This
opensonedialogboxwhereyouhavetoselectthedownloaded
MySQL.msifile.
5. Clickonthecalculatebutton.ThiswillcalculatetheMD5
checksumofthedownloadedfile.
6. EntertheMD5checksumavailableontheMySQLdownload
pageinthecomparetextboxandpressthecomparebutton.
<strong>cmd>gpg--verifypackage_name.asc</strong>
<strong>cmd>rpm--checksigpackage_name.rpm</strong>
ThistechniqueofverificationismorereliablethantheMD5
checksumbutitisverycomplexandrequiresmoreeffortforintegrity
checks.
Installing MySQL 8 on Microsoft
Windows
MySQLisavailableforboth32-bitand64-bitversions.Therearedifferentways
available to install MySQL 8 on Microsoft Windows. The most common
approachistouseaninstaller,whichinstallsandconfiguresMySQL8onyour
localsystem.
BeforeinstallingMySQLCommunity8.0Server,makesurethatthe
Microsoft Visual C++ 2015 redistributable package has been
installedonthesystem.
MySQL 8 either runs as a standard application or runs as a Windows service.
Useit,astheserviceenablesuserstocontrolandmeasureoperationsusingthe
Windows service management tool. Three major distribution formats are
availableforeachplatform:
Installerdistribution:ThisincludestheMySQL8serveralongwithother
productssuchasMySQLWorkbench,MySQL
for Excel, and MySQL Notifier. An installer is also useful for upgrading
productsintootherversions.
Sourcedistribution:Asthenameimplies,thiscontainsallthesourcecode
alongwithallthesupportedfiles.TheVisualStudiocompilerisrequiredto
makeitexecutable.
Binary distribution: This distribution is available in ZIP file format. It
containsallthe required filesexceptthe installer. The userhasto unpack
thefileintoaselecteddirectory.
Windows-specificconsiderations
BeforeinstallingMySQL8onMicrosoftWindowsconsiderfollowingpoints:
Antivirussoftware:Asweknow,antivirussoftwareusesthefingerprinting
technique,whichwillconsiderrapidlychangedfilesasapotentialsecurity
risk.InMySQL8,therearesomedirectoriesthatcontainMySQL8related
dataandtemporarytablesinformationandareupdatedfrequently.So,there
isapossibilitythatantivirussoftwarewillconsiderthosefilesasspam.This
willalsoimpactperformance.
Antivirus software provides configurations to exclude some of the
directories,soitisrecommendedtoexcludetheMySQL8datadirectory
andtempdirectory.MySQL
8, by default, stores temporary data into a Microsoft Windows temporary
directory.
To change this default configuration in MySQL 8, refer to my.ini file's tempdir
parameter.
Large table support: Use MySQL 8 on NTFS or any new filesystem to
supportlargetableswhosesizeismorethan4GB.Fortheselargertables,
theuserhastodefinetheMAX_ROWSandAVG_ROW_LENGTHpropertiesatthetimeof
tablecreation.
MySQL8installationlayout
Microsoft Windows, by default, considers the C:\Program Files directory for the
MySQL8installation.However,wehaveachoiceforthedirectoryselectionat
the time of installation. Whatever the location of the installation, the
subdirectorystructureafterinstallationremainssame.FortheMicrosoftWindow
layout,refertothefollowingtable:
Directory ContentsofDirectory Notes
bin mysqldserver,clientandutility
programs
%PROGRAMDATA%\MySQL\MySQL
Server8.0\ Logfiles,databases
TheWindows
systemvariable
%PROGRAMDATA%
defaultsto
C:\ProgramData
examples Exampleprogramsandscripts
include Include(header)files
Choosing the right installation
package
There are multiple options available for package formats while installing
MySQL 8 on Windows. MySQL provides a facility to debug the installation
processusingprogramdatabase(pdb)files.ThesefilesareavailableinaZIP
distribution:
Theinstallerpackage:Thisisawizard-basedprocessandiseasytouse.
Theinstallerpackageisavailable
for32-bitsonlybutcaninstallMySQL8onthe64-bitconfigurationalso.It
does
notcontainthedebuggingcomponentofMYSQL;wehavetodownloadit
separatelyin
the form of a ZIP file. The installer package is available in two different
formats:
Web Community: As the name implies, this is available for web
installation.ItmeanstheInternet
is required for the installation using the web community. Its size is
approx19MB.
ItsnameisdefinedasMySQL-installer-communitybytheappending
version.
Community: This package format is used for offline installation. Its
sizeisapprox301MB.
Its name is defined as MySQL-installer-web-community by the
appendingversion.
An installer is the most common way for MySQL product installation
andupgrade.
TheNoinstallArchives:Thisisamanualinstallationprocessthatcontains
filesfortheincompleteinstallation
package. As it is a manual process, no GUI is available. The user has to
manually
installand configureMySQL8 andotherproductsifrequired.Unlikethe
installer,
itprovidestwo differentfiles for32-bitand 64-bitconfigurationinaZIP
format.
TheMySQL8installer
The MySQL 8 installer is mainly used to reduce the complexity of the
installationprocessalongwiththemanagementofMySQLproductsrunningon
theWindowsplatform.
Intheproductlist,wecanconsider:
MySQLservers
MySQLapplications
MySQLconnectors
Documentationandsamples
TheMySQL8installerhastwoeditions:
CommunityEdition:Thiscanbedownloadedathttp://dev.mysql.com/download
s/installer/. As described in previous section, both Web Community and
Communitypackageformatsareavailablefortheinstaller.
CommercialEdition:Refertohttps://edelivery.oracle.com/todownloadthe
CommercialEdition.TheCommercialEditioncontainsalltheproductsthat
areavailableintheCommunityEditionalongwiththefollowingproducts:
WorkbenchSE/EE
MySQLEnterprisebackup
MySQLEnterprisefirewall
Initialsetupinformation
Asmentionedpreviously,theinstallerwillguideauserthroughthewizard.Once
westarttheinstallerinourhostmachineitwilldetectalreadyinstalledMySQL
productsandconsidertheminalistofproductstobemanaged.Thefollowing
arethestepsthatarerequiredintheinitialsetupoftheinstaller:
1. MySQL installer licensingand supportauthentication:Thisis thestep
where the user must accept the license agreement before starting the
MySQL8installation.Afteracceptingtheterms,theuserisallowedtoadd,
update,orremoveMySQLproducts.IntheCommercialEdition,credentials
are required to unbundle products and must match with the user's Oracle
accountinthesupportsite.
2. Choosingasetuptype:ThisisthestepwheretheusermustselectMySQL
products for installation. The installer also provides the option of a
predefined setup, which contains a set of MySQL products. So, you have
the flexibility of selecting one setup type as per your requirements. The
followingaresomesetupsavailableintheinstaller.
3. Developerdefault: This installs the version of MySQL 8 server that was
selectedatthetimeofdownload:
MySQLserver
MySQLshell
MySQLrouter
MySQLWorkbench
MySQLforVisualStudio
MySQLforExcel
MySQLnotifier
MySQLconnectors
MySQLutilities
MySQLdocumentation
MySQLsamplesandexamples
4. Serveronly:ThisinstallsonlytheMySQLserver.
5. Clientonly:Thisisthesameasthedeveloperdefaultsetuptype,exceptit
doesnotcontaintheMySQL8serveroranyclient-specificpackageadded
toit.
6. Full:ThisinstallsalltheavailableproductsofMySQL,suchasmysql-server,
mysql-client,mysqladmin,andafewmore.
7. Custom: This option installs only those products that are selected by the
user from the catalog. Here, the user has the freedom to choose only the
requiredproducts,ratherthaninstallingthecompletebundleofproducts.
8. Path conflicts: When the hosting system already contains a MySQL
productandtheuseristryingtoinstalladifferentversionofthatMySQL
productonthesamepath,thentheinstallerwillshowapathconflicterror
in the wizard. The installer enables the user to take action on the path
conflictinthefollowingways:
ChooseadifferentlocationusingtheBrowsebuttonfromthewizard
Chooseadifferentsetuptypeorversionbycustomselection
Overwritetheexistingfolderbymovingontothenextstep
Cancelthewizardsteps,deleteexistingproducts,andstarttheinstaller
again
9. Check requirements: Each MySQL product has a package-rules.xml file
attachedtoit,whichcontainsalltheprerequisitesoftwarelists.Duringthe
initialsetup,theinstallerwillchecktheavailabilityoftherequiredsoftware
andprompttheusertoupdatethehostincaseofmissingrequirements.
10. MySQLinstallerconfigurationfiles:Theinstallerconfigurationfilesare
locatedatC:\ProgramFiles.Thefollowingaretheconfigurationfiledetails:
Fileor
Folder
Description
FolderHierarchy
MySQL
installer
for
Windows
This folder contains all of the files
neededtorunMySQLinstallerandMySQ
LinstallerConsole.exe, a command-line
programwithsimilarfunctionality.
C:\ProgramFiles(x86)
Templates
TheTemplatesfolderhasonefilefor
eachversionofMySQLserver.
Templatesfilescontainkeysand
formulastocalculatesomevalues
C:\ProgramData\MySQL\MySQL
installerfor
Windows\Manifest
dynamically.
package-
rules.xml
This file contains the prerequisites for
everyproducttobeinstalled.
C:\ProgramData\MySQL\MySQL
installerfor
Windows\Manifest
produts.xml
The products file (or product catalog)
containsalistofallproductsavailable
fordownload.
C:\ProgramData\MySQL\MySQL
installerfor
Windows\Manifest
Product
Cache
The Product Cache folder contains all
standalone MSI files bundled with the
fullpackageordownloadedafterward.
C:\ProgramData\MySQL\MySQL
installerforWindows
Reference:https://dev.mysql.com/doc/refman/8.0/en/mysql-installer-setup.html
Installationworkflow
TheMySQLinstallerfollowsaworkflowforeachproduct:
1. Product download: The installer will download all the required product
MSIfilesintotheProductCachefolder.
2. Productinstallation:Theinstallermanagesthestatusofeachproductby
Ready|Install|Installing|Complete.
3. Product configuration: This phase uses a step-by-step configuration
process for products. The installer will change the status from Ready |
Configure.
4. Installationcomplete:Thisfinalizestheinstallationandtheusercanstart
usingtheapplicationaftertheinstallation.
InnoDB cluster sandbox test
setup
Therearetwooptionsavailableforhigh-availabilityimplementationinMySQL
8,usingtheinstaller:
StandaloneMySQLserver/ClassicMySQLreplication(default):This
option configures multiple servers manually or uses the latest version of
MySQLShelltoconfiguretheInnoDBcluster.
InnoDBclustersandboxtestsetup(fortestingonly):Thisisalsoknown
asthesandboxcluster.ThisoptionallowsyoutocreateanInnoDBclusteron
the local system for testing only. The MySQL installer toolbar provides
configurationsforanumberofinstancesinInnoDBclustering.
Clusternodesrunondifferentports.Afterconfiguration,clickontheSummary
tabtogettheportdetailsofeachcluster.
Serverconfiguration
The MySQL installer performs some basic configurations for the MySQL 8
server,including:
Theinstallerwillcreateamy.iniconfigurationfilefortheMySQL8server.
Filecontentswillbedecidedaspertheselectedoptionsoftheinstallation
process.
By default, the installer will add the Windows service for the MySQL 8
server.
TherequireddefaultinstallationanddatapathsoftheMySQL8serverwill
beprovidedbytheinstaller.
Theinstallerwillcreatesomeuseraccountswithrolesandpermissionsfor
MySQL
8server.ItcancreateaWindowsuserwithlimitedprivilegestotheMySQL
8server.
Using Show Advanced Options, MySQL installer allows for defining
custom paths for logging options. For example, you can configure the
separatepathforanerrorlog,showaquerylog,andmuchmore.
ThefollowingserverconfigurationisrequiredforMySQL8:
Serverconfigurationtype:Basedontheserverconfigurationtype,system
resourceswillbeassignedtotheMySQL8server.
Development: By considering the host as a personal workstation, it
configuresMySQL8tousetheminimumamountofmemory.
Server: As servers, some other applications are also running on the
machine,soitwillconfigureamediumamountofmemory.
Dedicated: In case of a dedicated machine for the MySQL 8 server, this
optionconfiguresthemaximumuseofavailablememoryfortheMySQL8
server.
Connectivity:ThisoptionindicatestheconnectionfortheMySQL8server.
Thefollowingoptionsareavailable:
TCP/IP: This option enables TCP/IP connection with MySQL 8.
Users are allowed to define the port number along with the firewall
settingfortheportonthenetworkaccess.
Namedpipe:Thisoptionallowsyoutodefinethepipelinenamefor
theconnection.
Sharedmemory:Thisallowsyoutodefinethememorynameforthe
MySQL8server.
Advanced configuration: This configuration enables additional logging
features which will manage logs in individual files. Users are allowed to
configurepathsforindividualfiles.Forexample,configuringacustompath
forabinarylog.
MySQL Enterprise Firewall: This option is used for the Commercial
Editiononly.ChecktheEnableEnterpriseFirewalloption toenable the
firewall.
Accountsandroles:Accountsandrolesareusedtomanageaccessrights
for the users. During the installation process, the MySQL installer allows
youtosetrootaccountpasswordsanduseraccounts.
Rootaccountpassword:Itisrequiredtoenterrootpasswordduring
theinstallationprocess.Theinstallerwillcheckthepasswordstrength
andgiveawarningifthereisaviolationofapredefinedpolicy.
MySQLuseraccounts:ThisisanoptionalstepwhereanewMySQL
user account defines with existing user roles. Predefined roles have
theirownprivileges.
Windows service: The MySQL 8 service can be configured in the
followingtwoways:
Configure as a Window service: This is the default option selected
duringtheinstallationprocess.Itfurtherprovidestwooptions:
Start service on system startup: This option is selected by
default and will start the MySQL 8 service automatically at
systemstartup.
Run Window service as: This option allows attaching the user
account with the MySQL 8 service. By default, the system
account is selected where the service is considered as network
service.
Withacustomuser,itfirstsetsprivilegesfortheuserbyusingthe
“localsecuritypolicy”inMicrosoftWindows.
Configure as an executable program: This deselects the Windows
Serviceoptionduringtheinstallationprocess.
Pluginsandextensions:Thisstepisavailableforanewinstallation.Ifthe
userwantstoupgradefromanolderMySQLversion,thentheuserneedsto
choosetheReconfigureoptionintheMySQLinstaller.
Advance options: To enable this option, select the Show advance
configuration check box in the Type and Networking step. This option
enablestheusertodefineaspecificpathforlogfiles,suchasanerrorlog,a
generallog,aslowquerylog,andbinlog.
Applyserverconfiguration:Oncealltheconfigurationhasbeendoneby
the user in the MySQL installer, click on the Execute button to make it
available.WhentheinstallationhasbeencompletedbypressingtheFinish
button, the MySQL installer and all the MySQL installed products are
availableintheWindowsStartmenu.
MySQL installer product catalog
anddashboard
This section contains details on how the MySQL installer handles product
catalogsandmanagesdashboards.
The product catalog is a component where a list of all the released MySQL
productsisavailable,whichsupportMicrosoftWindows.TheMySQLinstaller
updates the catalog on a daily basis and the option is also available for the
manual update of the catalog. The product catalog performs the following
actionstomanagethelist:
Populatetheavailableproductslistonaregularbasis
Checkfortheproduct'supdateasinstalledinthehost
Theproductcataloglistsalltheproductsthatareavailableinthedevelopment,
general,oranyminorrelease.
The MySQL installer dashboard provides the facility to manage MySQL
productsinstallationinthehostworkstation.
Thefollowingarethewaystomanageproductsusingthedashboard:
The MySQL installer provides a configuration to update the catalog at
specifictimeintervals.Theusercanenableordisableautomaticupdatesby
theconfiguration.
The dashboard shows a special icon at the product level when its new
versionisavailable.
Theusercanmanageproductswiththefollowingactions:
Add:Usetodownloadandinstalloneormoreproducts.
Modify:Usetoaddorremovefeaturesininstalledproducts.
Upgrade: Use to upgrade products. Make sure the checkbox is
selected at the product level for upgrading in the upgradeable
productspane.
Remove:Usetouninstallproductsfromthepopulatedlist.
The dashboard provides the reconfiguration feature, where the user can
changealreadyconfiguredoptionsandvalues.Afterapplyingchanges,the
MySQLinstallerwillstoptheMySQL8serverandrestartitagaintomake
themavailable.
The dashboard provides the facility to download the products catalog
withoutupgradingit.TheDonotupdateatthistimecheckboxisavailable
tocheckcurrentchangesrelatedtoproductswithoutdownloading.
Toperformthisfunctionality,selectthecheckboxandclickonthecatalog
link.
MySQLinstallerconsole
TheMySQLinstallerincludestheMySQLinstallerConsole.exefile,whichprovidesthe
functionalitytoexecutecommandsusingCommandPrompt.
This functionality is installed by default during the initial installation of the
MySQL installer. There are some commands available to manage MySQL
products.Toseethedetailsofthesecommands,executethehelpcommand.
<strong>[mysqld]</strong><br/><strong>#setbasedirtoyour
installationpath</strong><br/><strong>basedir=E:\\mysql</strong>
<br/><strong>#setdatadirtothelocationofyourdata
directory</strong><br/><strong>datadir=E:\\mydata\\data</strong>
<strong>E:\>“E:\MySQL\MySQLServer8\bin\mysqld”</strong>
<strong>mysqld:readyforconnections</strong><br/><strong>
Version:'8.0.4'socket:''port:3306</strong>
<strong>E:\>“E:\MySQL\MySQLServer8\bin\mysqld”--
install</strong>
<strong>E:\>“E:\MySQL\MySQLServer8\bin\mysqld”--install
MySQL--defaults-file=E:\my-opts.cnf</strong>
<strong>E:\>“E:\MySQL\MySQLServer8\bin\mysqld”--install-
manual</strong><br/><strong>E:\>"E:\MySQL\MySQLServer
8\bin\mysqld"--remove</strong>
InstallingMySQL8onLinux
ForMySQL8installationonLinux,varioussolutionsareavailable.Theusercan
choose any of the distributions for his requirement. Th following are the
differentdistributionsandamongthem,threeofwhicharedescribedindetail:
InstallationusingtheYumrepository
InstallationusingtheAPTrepository
InstallationusingtheSLESrepository
InstallationusingtheRPMpackage
InstallationusingtheDebianpackage
InstallationusingDocker
InstallationusingtheNativeSoftwarerepository
InstallationusingJuju
<strong>shell>sudoyumlocalinstallpackage_name.rpm</strong>
<br/><strong>shell>yumrepolistenabled|grep"mysql.*-
community.*"</strong>
<strong>shell>yumrepolistall|grepmysql</strong>
<strong>shell>sudoyum-config-manager--disablemysql57-
community</strong><br/><strong>shell>sudoyum-config-manager
--enablemysql80-community</strong>
<strong>mysql80-community]</strong><br/><strong>
name=MySQL8.0CommunityServer</strong><br/><strong>
baseurl=http://repo.mysql.com/yum/mysql-8.0-
community/el/6/$basearch/</strong><br/><strong>
enabled=1</strong>
<strong>shell>yumrepolistenabled|grepmysql</strong>
<strong>shell>sudoyuminstallmysql-community-server</strong>
<strong>shell>sudoservicemysqldstart</strong><br/><strong>
shell>sudoservicemysqldstatus</strong>
Duringtheinitialstartup,thefollowingtasksareperformed:
Theserverisinitialized
TheSSLcertificateandkeyfilesaregeneratedinthedata
directory
Thepluginsnamevalidate_password_pluginisinstalledand
enabled
Asuperaccountiscreated
<strong>shell>sudoservicemysqldstart</strong>
Aswithotherinstallations,theRPMpackageinstallationalsocreates
filesanddirectoriesinthesystemonfollowingpath:
FilesorResources Location
Clientprogramsandscripts /usr/bin
mysqldserver /usr/sbin
Configurationfile /etc/my.cnf
Datadirectory /var/lib/mysql
Errorlogfile
ForRHEL,OracleLinux,CentOS,orFedora
platforms:/var/log/mysqld.logForSLES:
/var/log/mysql/mysqld.log
Valueofsecure_file_priv /var/lib/mysql-files
SystemVinitscript
ForRHEL,OracleLinux,CentOS,orFedora
platforms:/etc/init.d/mysqldForSLES:
/etc/init.d/mysql
Systemdservice ForRHEL,OracleLinux,CentOS,orFedora
platforms:mysqldForSLES:mysql
Pidfile /var/run/mysql/mysqld.pid
Socket /var/lib/mysql/mysql.sock
Keyringdirectory /var/lib/mysql-keyring
Unixmanualpages /usr/share/man
Include(header)files /usr/include/mysql
Libraries /usr/lib/mysql
Miscellaneoussupportfiles(for
example,errormessages,and
charactersetfiles)
/usr/share/mysql
<strong>shell>tar-xvfmysql-server_MVER-DVER_CPU.deb-
bundle.tar</strong>
<strong>shell>sudoapt-getinstalllibaio1</strong>
<strong>shell>sudodpkg-preconfiguremysql-community-
server_*.deb</strong>
<strong>shell>sudoapt-get-finstall</strong>
TheMySQL8configurationfilesareavailableunderthefollowing
pathintheDebianpackage:
Configurationfilesarestoredunder/etc/mysql
Thedatadirectoryisstoredunder/var/lib/mysql
Binaries,libraries,andheadersarestoredunder/user/binand
underuser/sbin
Post-installationsetupforMySQL
8
Post-installationisaprocessthatdescribesthebasicstepsorconfigurationthat
theuserhastoperformafterMySQL8installation.
<strong>E:\>bin\mysqld–-initialize</strong><br/><strong>E:\>
bin\mysqld--initialize-insecure</strong>
<strong>E:\>bin\mysqld--initialize--basedirE:\mysql--datadir
:\mydata\data</strong>
Theusercanalsospecifythesedirectoriesinaseparatefile,knownas
theOptionfile,underthemysqldparameter.Thisconfigurationis
describedindetailundertheOptionfilesectioninthischapter.When
theuserexecuteseitherofthecommands,mysqldperformsthe
followingstepsintheexecution:
1. Itcheckstheexistenceofthedatadirectory
2. TheMySQL8servercreatesasystemdatabaseanditstable,
granttables,helptables,andtimezonetables
3. ItinitializesasystemtablespacewithdatastructureforInnoDB
tables
4. Theroot@localhostsuperuseraccountandotherreserved
accountswillbecreated
<strong>shell>mysql-uroot-p</strong><br/><strong>Enter
password:(entertherandomrootpasswordhere)<br/></strong>
<strong>mysql>ALTERUSER'root'@'localhost'IDENTIFIEDBY
'newPassword';</strong>
<strong>mysql-uroot</strong>
<strong>mysql>ALTERUSER'root'@'localhost'IDENTIFIEDBY
'newPassword';</strong>
Afterassigningthenewpassword,youhavetousethenewpassword
wheneveryouwanttoconnectwithMySQL8.
<strong>shell>sudoservicemysqldstart</strong>
<strong>shell>sudoservicemysqldstatus</strong>
<strong>shell>mysql-uroot-p</strong>
Theprecedingcommandpromptsforthepassword,soenterthe
passwordandpresstheEnterkey.TheMySQLpromptwillbe
displayedwhereyoucanentermysqlcommandsforexecution.During
theexecutionoftheprecedingcommands,somecommonproblems
mayarrive,soherewewillpresentthefollowingtroubleshooting
suggestions:
1. Checkintothelogfilestofindtheexacterrorthatoccurred
duringtheservicestartup.Asmentionedintheprevioussection,
theerrorfileandlogfilesarelocatedunderthedatadirectory.
Itsnamingconventionsarehost_name.errandhost_name.log.
Byreadingthelastfewlinesofthefile,youcanidentifythe
problemthatoccurredduringthelastcommandexecuted.
2. Checkthattherequiredport/socketisavailable.Thefollowing
errorswillindicatethattherequiredportsandsocketsarenot
availableforuse,meaningthattheyareinusewithother
programs.Toidentifythis,trackalltheproblemsbydisablingthe
service.Anotherreasonisyourfirewallsettingsareblockingthe
accessoftherequiredport,somodifythefirewallsettingandgive
permissiontotherequiredports:
Can'tstartserver:BindontheTCP/IPport:theaddressis
alreadyinuse
Can'tstartserver:BindontheUnixsocket
3. DefiningthespecificparametersintotheOptionfileis
recommended.Iftheparametersarenotdefineintothefilethen
MySQL8willconsiderthedefaultparameters,sorefertoallthe
availableparametersprovidedbyMySQL8beforeusingit.
4. Verifythatthedatadirectorypathandpermissionareproperly
definedornot.Thisdirectoryisusedasthecurrentdirectoryfor
MySQL8.Tofindthecurrentlysetpathofthedatadirectory,
executethemysqldcommandwiththe--verboseand--help
command.Ifthedatadirectoryislocatedatadifferentplace
otherthantheMySQLinstallationdirectory,thenusethe--
datadiroptionwiththemysqldcommand.Forpermission,you
willgetanErrorcode13,whichindicatesthepermissiondenied
error.Toovercomethisissue,changethepermissionofthe
requiredfilesandfolder.Anotherwayistologinwiththeroot
user,butthisisnotpossibleinallthescenarios,sothefirst
approachisrecommendedtoovercomethepermissionissue.
<strong>shell>bin/mysqladminversion</strong>
<strong>mysql>mysqlshow</strong><br/>
<strong>mysql>mysqlshowmysql</strong>
Thefirstcommandshowsthelistofdatabasesavailableintheserver.
Listsmayvaryasperthesystem,butmysqlandinformation_schema
mustbeavailableinthelist.Thesecondcommandlistsallthetables
createdunderthemysqldatabase.
UpgradingMySQL8
In previous versions of MySQL, the data dictionary is stored in the file-based
systemwhileinMySQL8itisstoredinthedatadictionarystructure.So,theup-
gradation process will move the file-based structure into the data dictionary
structure. Up-gradation into MySQL 8 is possible from the MYSQL 5.7 GA
version, which means from 5.7.9 or higher. For non-GA versions of 5.7, up-
gradationisnotpossible.Beforestartingtheup-gradationprocess,thefollowing
pointsneedtobeunderstood.
Upgradingmethods
Two methods are in use for up-gradation that are differentiated by their
implementationmethod.Letusdiscussthesemethodsindetail.
<strong>ALTERINSTANCEROTATEINNODBMASTERKEY;
</strong>
<strong>SETGLOBALinnodb_fast_shutdown=1;--fast
shutdown</strong><br/><strong>SETGLOBAL
innodb_fast_shutdown=0;--slowshutdown</strong>
<strong>mysqladmin-uroot-pshutdown</strong>
<strong>mysql_upgrade-uroot-p</strong>
7. Afterup-gradation,shutdownandrestarttheservertocheck
whetherallthechangeshavebeenappliedornot.
<strong>mysqldump-uroot-p--add-drop-table--routines--events--
all-databases--<br/>force>data-for-upgrade.sql</strong>
<strong>mysqld--initialize--datadir=/path/to/8.0-datadir</strong>
<strong>mysqld_safe--user=mysql--datadir=/path/to/8.0-
datadir</strong>
<strong>mysql-uroot-p--force<data-for-upgrade.sql</strong>
<strong>mysql_upgrade-uroot-p</strong>
<strong>mysqlcheck-uroot-p--all-databases--check-
upgrade</strong>
<strong>SELECTTABLE_SCHEMA,TABLE_NAME</strong><br
/><strong>FROMINFORMATION_SCHEMA.TABLES</strong>
<br/><strong>WHEREENGINENOTIN('innodb','ndbcluster')
</strong><br/><strong>ANDCREATE_OPTIONSLIKE
'%partitioned%';</strong>
<strong>ALTERTABLEtable_nameENGINE=INNODB;
</strong><br/><strong>ALTERTABLEtable_nameREMOVE
PARTITIONING;</strong>
<strong>SELECTCONSTRAINT_SCHEMA,TABLE_NAME,
CONSTRAINT_NAME</strong><br/><strong>FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS</strong>
<br/><strong>WHERELENGTH(CONSTRAINT_NAME)>64;
</strong>
5. MakesureMySQL5.7doesn'tcontainfeaturesthatarenot
availableinMySQL8,forexample:
Ifatableusedastorageenginethatisnotsupportedby
MySQL8,sowasalteredwiththesupportedstorageengine
Aconfigurationchangewhereyouuseanoptionorvariable
thatisnotavailableinMySQL8
MySQL8downgrading
Downgradingisthereverseprocessofup-gradation,wherewewillmovefroma
higher version of MySQL to a lower version of MySQL. In this section, we
coverhowtodowngradefromMySQL8toMySQL5.7.Adowngradethatdoes
notsupportaversionskipmeansthatdowngradingfromMySQL8toMySQL
5.6isnot supported.Within thesameserieswherea versionskipissupported
meansyoucandowngradefromMySQL8.ztoMySQL
8.xbyskippingtheMySQL8.yversion.First,wewillexplainsomebasicpoints
thatneedtobeunderstoodbeforestartingdowngrading.
<strong>rmib_logfile*</strong>
<strong>mysqld_safe--user=mysql--datadir=/path/to/existing-
datadir</strong>
<strong>mysql_upgrade-uroot-p</strong>
6. ShutdownandrestarttheMySQLserveragaintocheckifallthe
changeshavebeenappliedornot.
ForMySQLinstallationbasedonAPT,SLES,andtheYumrepository
installations,in-placedowngradesarenotsupported
<strong>mysqldump-uroot-p</strong><span><strong>--add-drop-
table--routines--events</strong><br/><strong>--all-databases--
force>data-for-downgrade.sql</strong><br/></span>
<strong>mysqladmin-uroot-pshutdown</strong>
<strong>mysqld--initialize--user=mysql</strong>
<strong>mysqld_safe--user=mysql--datadir=/path/to/new-
datadir</strong>
<strong>mysql-uroot-p--force<data-for-upgrade.sql</strong>
<strong>mysql_upgrade-uroot-p</strong>
<strong>mysqladmin-uroot-pshutdown</strong><br/><strong>
mysqld_safe--user=mysql--datadir=/path/to/new-datadir</strong>
<strong><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>columns_priv<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span><spanclass="token
keyword">component</span><spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>db<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>default_roles<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>engine_cost<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>func<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>general_log<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>global_grants<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>gtid_executed<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>help_category<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>help_keyword<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>help_relation<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>help_topic<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>innodb_index_stats<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>innodb_table_stats<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span><spanclass="tokenkeyword">plugin</span>
<spanclass="tokenkeyword">TABLESPACE</span><span
class="tokenoperator">=</span>innodb_file_per_table<span
class="tokenpunctuation">;</span><br/><spanclass="token
keyword">ALTER</span><spanclass="token
keyword">TABLE</span>mysql<spanclass="tokenpunctuation">.
</span>procs_priv<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>proxies_priv<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>role_edges<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>server_cost<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>servers<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>slave_master_info<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>slave_relay_log_info<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>slave_worker_info<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>slow_log<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>tables_priv<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>time_zone<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>time_zone_leap_second<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>time_zone_name<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>time_zone_transition<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span>time_zone_transition_type<spanclass="token
keyword">TABLESPACE</span><spanclass="tokenoperator">=
</span>innodb_file_per_table<spanclass="tokenpunctuation">;
</span><spanclass="tokenkeyword"><br/>ALTER</span><span
class="tokenkeyword">TABLE</span>mysql<spanclass="token
punctuation">.</span><spanclass="tokenkeyword">user</span>
<spanclass="tokenkeyword">TABLESPACE</span><span
class="tokenoperator">=</span>innodb_file_per_table<span
class="tokenpunctuation">;</span></strong>
<strong>ALTERTABLEmysql.columns_privENGINE='MyISAM'
<br/>STATS_PERSISTENT=DEFAULT</strong>
<strong>ALTERTABLEmysql.userdropCreate_role_priv;
</strong><br/><strong>ALTERTABLEmysql.userdrop
Drop_role_priv;</strong>
InnoDBchanges:Beforestartingin-placedowngrading,shut
downMySQLusingtheinnodb_fast_shutdownoption.Shut
downtheserverwithinnodb_fast_shutdown=0.Removingthe
redologsisrecommendedforin-placedowngrading.
Summary
Tochoosethepropersoftwarewithitsversionfordevelopmentisanimportant
phase,right?Inthischapter,weunderstoodhowtoselecttheproperversionof
MySQL8
by understanding its version pattern. We also learned the execution steps of
MySQL
8installationusingtheinstallerandcommandline inMicrosoftWindows.For
the Linux platform, we installed MySQL 8 using the Yum repository, RPM
package,andDebianpackage.Post-installationdescribesthebasicconfiguration
tostartwithMySQL8.
Finally, we explained how to upgrade and downgrade from MySQL 8 with
executionsteps.
Inthenextchapter,wewilllearnaboutvariousprogramsandutilitiesavailable
for MySQL 8. It mainly focuses on how to use these programs for MySQL 8
alongwithcommand-lineexecutions.
MySQL 8 – Using Programs and
Utilities
Inthepreviouschapter,weinstalledMySQL8andgottoknowalternativeways
toinstallMySQL8.WealsolearnedhowtomigrateandupgradetoMySQL8.
Thefollowingarethesummarytopicsexplainedinthepreviouschapter:
MySQL8Installation
PostInstallationSetup
MySQL8Upgrading
MySQL8Downgrading
In this chapter, the reader will learn about various programs and utilities
availablein MySQL 8.The readerwill alsogettoknowhow touse programs
and utilities in MySQL 8. The reader will learn about using command-line
programsusedinMySQL8.
Thereaderwill learnthesyntax fortheprogram andhowthey arebeingused
withspecificoptionstoperformspecificoperations.Thefollowingisasummary
ofthetopicscoveredinthischapter.
OverviewofMySQL8programs
MySQL8command-lineprograms
MySQL8clientprograms
MySQL8administrativeprograms
MySQL8environmentvariables
MySQLGUItools
OverviewofMySQL8programs
There are various different programs in the MySQL installation. A brief
overviewof theseprograms iscoveredinthissection.Upcomingsectionswill
cover a detailed description for each of them and the description will have its
owninvocationsyntaxandoptionstoperformtheoperation.
MostoftheMySQLdistributionwillhavealltheseprograms,apartfromthose
that are platform-specific; for example, server startup script not used in
Windows.RPM
(Red-hatpackagemanager)distributionsareveryspecializedandarepartofthe
exceptionstoallprogramsavailableindistributions.Whatisspecializedabout
RPMdistributions?
Well, they have different programs for different operations; for example, one
programwillbeexecutedfortheserver,asecondprogramwillbeexecutedfor
theclient,and soon. Ifitlooks likeoneor moreprograms ismissingin your
installation,thendon'tworry.SeeChapter2,InstallingandUpgradingMySQL8,
for information on the types of distributions available and what is included in
them.Itmightbethecasethatthedistributionwhichyouhavedoesnotinclude
alltheprogramsandyouneedtoinstallanadditionalpackage.
EachoftheMySQL8programswillhavetheirownoptions,butmostofthem
willhavea--help optionthatcanbeusedto retrievedescriptions aboutall the
optionsthattheprogramhas.Forexample,trymysql--helponthecommandline
(thatisyourshellorCommandPrompt).
The description on the first few lines will have specific version information
about MySQL that is installed along with operating system and license
information.ThenextlinewillstartwithUsage:mysql[OPTIONS][database],thatis,
a syntax of the program command usage, and later lines describe the options
availabletobeusedalongwiththemaspertheusagedescription.Thiswasjusta
glimpseofwhatwewillbelookingat:programdetailswithoptions,theirusages
anddefaultoptions, overriding defaultoptionvalues on variouscommand-line
programs,clientprograms,administrativeprograms,andsoon.
For detailed information about executing programs and specifying program
optionsinthecommandlineseetheMySQL8commandlineprogramssection,
whichwillbefollowedbyalistofinstallations,clientandserverstartup,and
otherutilityprograms.
MySQLprogramsinbrief
LetusstartwiththeMySQLserverprogramsfirst!!
mysqldisthefirstprogram,alsoconsideredtobethemainprogramforMySQL
installation.
Itworks withseveral scriptstohelpwithstartingandstoppingtheserver.The
following are the programs divided into categories based on their operational
scope:
Startupprograms
Installation/upgradationprograms
Clientprograms
Administrativeandutilitiesprograms
Startupprograms
ThestartupprogramsaretheprogramsthatareusedduringMySQLstartupand
initiatetherequiredbackgroundservicesbasedontheconfiguration.
mysqld: This is the MySQL server daemon. All the other client programs
interactwiththedatabaseusingthisserverprogram.Itmustbestartedand
berunningatalltimesexceptformaintenance.
mysqld_safe:Thisisoneoftheserverstartupprogramscriptsandattemptsto
startthemysqldprogram.
mysql.server: Another server startup program script, which is used in those
systems, uses V-style run directories containing scripts. It starts system
servicesatparticularrunlevels.
Itcallsmysqld_safetostarttheMySQLserver.
mysqld_multi:Asthenamesuggests,thisisastartupprogramscripttostartor
stopmultipleMySQLserversonthesystem.
Installation/upgradationprograms
Theprogramsregardingtheoperationsofinstallationandupgradationarelisted
herewiththeirrespectiveusage:
comp_err: This program is used to compile error message files from error
sourcefilesanditisusedduringtheMySQLbuildorinstalloperation.
mysql_secure_installation: This program is used to update the security
configurationinordertoenablesecurityduringinstallationofMySQL.
mysql_ssl_rsa_setup:Asthenamesuggests,thisprogramisforgeneratingSSL
certificatesandkeyfilesandRSAkey-pairfiles,ifthosefilesaremissingand
arerequiredtosupportsecureconnections.
mysql_tzinfo_to_sql: This program gets the content of the host system zone
infodatabase(filesdescribingtimezones)andloadstheinformationinthe
timezonetablesofMySQL.
mysql_upgrade: As the name suggests, it is used for upgrade operations. It
checksforanyincompatibilityandmakesrepairsifitisnecessary.Italso
updatesthegranttableswithanychangesinnewversionsofMySQL.
Clientprograms
Theclientprogramsareamongtheprogramsthatarecommonlyusedtoconnect
totheMySQLdatabaseandperformdifferentqueryoperations:
mysql: This is the most commonly used program. It is an interactive
command-linetoolforexecutingSQLstatementsdirectlyorusingafilein
batchmode.
Detailed information is followed in the next MySQL 8 command line
programssection.
mysqladmin: This is the program responsible for performing various
administrativeoperations,suchascreatingordroppingdatabases,flushing
tables, reloading grant tables, reopening log files, and much more. The
program is also used to retrieve information from the server, such as
version,process,andstatus.
mysqlcheck: This is the client program used for maintenance of tables,
performinganalysis,checks,repairs,andoptimizingtables.
mysqldump:Thisis theclientprogram that dumpstheMySQLdatabaseto a
file in text, SQL, or XML formats. It is commonly known as a database
backupprogram.
mysqlimport:Thisistheclientprogramthatimportstextfilesintorespective
tablesusingLOAD_DATA_INFILE.Itisalsocommonlyknownasthedataimport
program.
mysqlpump:TheclientprogramwhichdumpsMySQLdatabaseintoSQLfile.
mysqlshow: The client that shows information of databases, tables, columns,
andindexes.
mysqlslap: This is the client program that is used to check client load
capability for the MySQL server. The program mimics multiple clients
accessingtheserver.
Administrative and utilities
programs
The following are the programs that perform various administrative activities.
Theyaredepictedalongwithsomeoftheutilitieswhichhelpinadministrative
operations:
innochecksum:TheprogramfortheInnoDBofflinefilechecksum.
myisam_ftdump: The utility program gives information of full-text indexes in
MyISAMtables.
myisamchk: The program used to check, describe,repair and optimize MyISAM
tables.
myisamlog:TheutilityprogramforprocessingaMyISAMlogfilecontents.
myisampack:Theutilityprogramthatproducessmallerread-onlyMyISAMtables
throughcompression.
mysql_config_editor: The utility program that enables authentication
credentials storage in an encrypted and secure login path file named
mylogin.cnf.
mysqlbinlog:Theutilityprogramthatcanreadbinarylogfilestatements.In
theeventofaservercrash,abinarylogfileexecutedstatementscanbebig
help.
mysqldumpslow:Theutilityprogramthatcanreadandsummarizethecontents
ofaslowquerylog.
Environmentvariables
The MySQL client programs that communicate with the MySQL server using
librariesusethefollowingenvironmentvariables:
MYSQL_UNIX_PORT:Thisvariable isresponsibleforthedefaultUnixsocketfile
whichwillbeusedforconnectingtoalocalhost
MYSQL_TCP_PORT: This variable is responsible for providing the default port
numberandisusedinTCP/IPconnections
MYSQL_PWD:Thisvariableisresponsibleforprovidingthedefaultpassword.
MYSQL_DEBUG: This variable is responsible for providing debug trace options
duringdebuggingoperations
TMPDIR: This variable is responsible for providing the directory where the
temporaryfilesandtableswillbecreated
Foradetailedlistandusesofenvironmentvariablesinprograms,
seeMySQL8environmentvariablessection.TheuseofMYSQL_PWDis
insecure.
MySQLGUItool
The MySQL Workbench GUI tool, provided by Oracle corporation, is used in
theadministrationofMySQLserversanddatabases,forcreating,executing,and
evaluating queries. It is also used for migrating schema and data from other
relational database management systems to be used with MySQL. There are
otherGUI tools,includingMySQL Notifier,MySQL forExcel,phpMyAdmin,
andmanymore.
MySQL8command-lineprograms
Intheprevioussection,wewentthroughvarioustypesofprogramsprovidedby
MySQL
8andoutlinedtheirusageinbrief.
In this section, we will look at command-line programs and learn about
executing programs from command lines. We will take a detailed look at the
provisionforoptionsandhowtheycanbeutilizedfortheadministration.
Executing programs from the
commandline
Executingprogramsfromthecommandline(shellorCommandPrompt)isone
ofthemostusedforms of administrationinMySQL. Plentyofprogramshave
beenaddedalongwithoptionsforadministration.
<strong>shell>mysql--verbose--help</strong><br/><strong>shell>
mysql--user=root--password=********mysampledb</strong><br/>
<strong>shell>mysqldump-urootpersonnel</strong><br/>
<strong>shell>mysqlshow--help</strong>
Therearenonoptionarguments,argumentswithoutanyleadingdash,
givingsupplementaryinformationtotheprogram.Asanexample,if
youseethesecondlineoftheprecedingexample,ithasathird
nonoptionargumentwithadatabasenamemysampledb,sothe
commandmysql--user=root--password=********mysampledb
tellsthemysqlprogramthatyouwantedtousemysampledbasthe
databasename.
Argumentsbeginningwithsingleordoubledash(-,--)areusedfor
specifyingtheprogramoptions.Specifyingtheprogramoptions
indicatesthetypeofconnectiontheprogramwillconnecttotheserver
orwillaffectthemodeofoperation.Syntaxfortheoptionsare
explainedwithdetails,seetheSpecifyingoptionsforprograms
section.
<strong>shell>mysql</strong>
<strong>shell>mysql--host=localhost--user=root--
password=mypwdmysampledb</strong>
Asyoucanseeintheprecedingexamplewithspecificoptionvalues,
thehostistobeconsideredasthelocalhostandtheuservalueis
providedasmyname.Thepasswordisalsospecifiedand,finally,anon-
optionargumentisspecifiedthattellstheprogramtousemysampledb
asthedefaultdatabasename.
Specifyingoptionsforprograms
Intheearliersection,wehaveseenhowprogramoptionschangetheoperation
modebasedonargumentvaluesspecifiedfortheoptionintheclientprogram.
Here we will look at several ways to specify options for MySQL programs.
Theseinclude:
Providingtheoptionsonthecommandlinefollowedbytheprogramname.
This is the common way of providing options but it will be applied
specificallytotheexecutionoftheprogramatthattimeonly.
Providingtheoptionsintheoptionsfilethatisbeingreadbytheprogram
beforeitstartsexecution.Thisisthecommonwayforprovidingtheoptions
thatyouwanttheprogramtouseeachtimeitexecutes.
Providingtheoptionsintheenvironmentvariables.Byusingthismethod,
youcanalsospecifyoptionsthatyouwanttoapplyeverytimetheprogram
isbeingexecuted.
Ingeneralpractice,usingoptionfilesiscommonlyusedforthispurposebut
specifyingoptionvaluesintheenvironmentvariablesisalsoveryusefulin
some cases; for example, when running multiple MySQL instances on a
Unixsystem.
TheMySQLprogramcheckswhichoptionsaretobegivenfirstbyexamining
the related environment variables, then it processes option files, and then it
considers option arguments in the command line. Thus, the command-line
options have the highest precedence and the environment variables have the
lowest.However,thereisoneexceptionthatappliesandthatisthemysqld-auto.cnf
optionfileinthedatadirectoryprocessedlast,soittakeshigherprecedenceto
thecommand-lineoptions.
<strong>shell>mysqladmin--count=1k--sleep=10ping</strong>
Forfilenameoptionsvalues,avoidusingthe~metacharacter
becauseitwillnotbeinterpretedasperexpectation.
Optionvaluescontainingspacesmustbeenclosedbyquotation
markswhenavalueisspecifiedonthecommandline.
<strong>--disable-column-names</strong><br/><strong>--skip-
column-names</strong><br/><strong>--column-names=0</strong>
Asyoucanseeintheprecedingexample,the=0suffixandthe--
skipand--disableprefixeshavethesameeffect.Itisalso
applicablewhenturningtheoptiononwiththe=1suffixandthe--
enableprefix.
Iftheoptionisspecifiedwiththe--looseprefix,andiftheoption
specifieddoesnotexist,theprogramwillissueawarninginsteadof
exiting.
Forsomeoftheprograms,the--maximumprefixisavailabletobe
usedwiththeoptionnameforspecifyingthelimit.Itcanalsobeused
withenvironmentvariables.
Modifyingoptionswithfiles
MostoftheMySQLprogramscanreadstartupoptionsfromtheoptionfiles,also
sometimescalledconfigurationfiles.Itisaveryconvenientwayofproviding
the options that are commonly used and once specified you need not specify
themeachtimeyouexecutetheprogram.Tocheckwhethertheprogramreads
option files, use the --help option. For example, consider the mysqld program,
whichshoulduse--verboseand--help,ifitreadsoptionfiles.Thehelpmessage
willindicatewhichoptionfileitlooksforandforwhichoptiongroup:
TheMySQLprogramwiththe--no-defualtsoptiondoesnotreadany
option files apart from .mylogin.cnf. If the server program started
with the option persisted_globals_load system variable disabled then
theprogramdoesnotreadthemysqld-auto.cnffile.
Themajorityoftheoptionfilesareplaintextfilesthatcanbecreatedandedited
by any text editors. Exceptions among those files are .mylogin.cnf , which has
loginpathoptions,encryptedbythemysql_config_editorutilityprogram.
MySQLchecksoptionfilesforWindowsandUnixsystemsinspecificorderand
follows the precedence that starts from reading global options, such as in the
Windowssystem:
%PROGRAMDATA%\MySQL\MySQL Server 8.0\my.ini and %PROGRAMDATA%\MySQL\MySQL Server
8.0\my.cnf
%WINDIR%\my.iniand%WINDIR%\my.cnf
C:\my.iniandC:\my.cnf
BASEDIR\my.iniandBASEDIR\my.cnf
Thefilespecifiedwith--defaults-extra-file,ifany
Loginpathoptionsin%APPDATA%\MySQL\.mylogin.cnf(clientprogramonly)
For system variables persisted with SET_PERSIST or PERSIST_ONLY (if it is the
serverprogram)inDATADIR\mysql-auto.cnf
Similarly, in Unix systems it follows the following order of precedence for
readingoptionfiles:
/etc/my.cnf
/etc/mysql/my.cnf
SYSCONFDIR/my.cnf
$MYSQL_HOME/my.cnf(serverprogramonly)
Thefilespecifiedwith--defaults-extra-file,ifany
~/.my.cnfforuser-specificoptions
~/.mylogin.cnfforuser-specificloginpathoptions(clientprogramonly)
For system variables persisted with SET_PERSIST or PERSIST_ONLY (if it is the
serverprogram)inDATADIR\mysql-auto.cnf
Intheprecedingoptions,~referstothecurrentuser'shomedirectory.
Emptylinesinoptionfilesareignored,alongwithcomments.Commentscanbe
specifiedusing#or;charactersand#canstartinthemiddleofanylineaswell.
group
groupisthenameoftheprogramorgroupforwhichoptionsaretobeset.They
are not case sensitive. Once a group line is added to the option file, all the
followinglinesapplytothenamedgroupuntilanothergrouplineisspecifiedor
attheendoftheoptionfile.
opt_name
This is similar to the --opt_name in the command line turning on the named
optimization.
opt_name=value
Thisissimilartothe--opt_nameinthecommandlinebutinplaceofthevalue,you
canspecifythevaluewithspaces,whichyoucannotinthecommandline.
Includedirectives
Itispossibleusing!includedirectivesintheoptionfilestoincludeanotheroption
fileand!includedirtosearchforspecificdirectoriestocheckforoptionfiles.For
example,!include /home/dev/myopt.cnfand!includedir /home/dev,fordirectories. The
only thing that MySQL does not consider is any order during the directory
search.
Anyoptionfilestobeusedinthe!includedirdirectiveonaWindows
systemmustendwiththe.inior.cnfextensionandinUnixsystems
theymustendwith.cnf.
Command-line options affecting
optionfilehandling
Most of the MySQL programs support option files. As they affect option file
handling,theymustbegiveninthecommandlineandnotaspartofanoption
file.
Inordertomakethemworkproperly,theymustbegivenbeforeotheroptions.
Some of the exceptions are as follows : --print-defaults might be used
immediatelyafter--login-path,--defaults-file,ordefaults-extra-file.
--no-defaultsand--print-defaultsarealsousedtomodifyoptionfilehandling.
Setting program variables with
options
ManyMySQLprogramshaveinternalvariablesthatwecansetduringruntime
operations
using the SET statement and also using the same syntax by which we specify
optionvalues.This
willworkwhentheprogramisstarted.Forexample,ifweusetheoptionvalue
syntax
thenwehavetospecifylikethis:shell>mysql--max_allowed_packet=16M.Tospecify
the runtime option using the SET, we can specify like this: mysql> SET GLOBAL
max_allowed_packet=16*1024*1024.
Tofindout ifthe optionvariable syntaxiscorrect, youcango to
mysqlandusethefollowing:mysql>showvariableslike'max%'.
<strong>SETUSER=your_user_name</strong>
<strong>MYSQL_TCP_PORT=3306</strong><br/><strong>export
MYSQL_TCP_PORT</strong>
<strong>setenvMYSQL_TCP_PORT3306</strong>
Thecommandstosetenvironmentvariablesthatareexecutedwill
immediatelyaffecttheprograminexecutionbutifyouwantedtoget
theenvironmentvariabletopersist,youneedtospecifyitonthe
interfaceprovidedbythesystemoryoumaysetitupinthestartup
filethatthecommandprocessorusesatstartup.OnWindows,thiscan
besetupfromthecontrolpanelsoptiontosetenvironmentvariables
andinUnix,thiscanbesetupbasedonthecommand-lineprocessor
youuse.Forbash,youneedtoputthevaluein.bashrcor
.bash_profileandfortcshuse.tcshrc.
Server and server-startup
programs
TherearespecificprogramsprovidedbyMySQLwhichyouneedtoexecutefirst
inordertomakeMySQLworkcorrectly.Inthefollowingsections,wewilllook
attheserverprogramsandrelatedstartupprogramsthatcanbeusedwithseveral
optionsasperyourrequirement.
mysqld - the MySQL server
program
TheMySQLserverisadaemonprogram.Allotherprogramsconnectwiththe
database
through this server, so it should be running at all times. The daemon program
usually
getsstartedfromascriptcalledmysqld_safe.Theprogramscriptisrequired,asit
setstheappropriateenvironmentvariables
andexecutesthemysqldprogramwiththerequiredarguments-optionvalues.
Options
Thefollowingaretheoptionsbriefedindetailforvariousoptionsavailablefrom
commandline:
-?,-I,--help:Displaystheusageinformationoftheprogram.
-#debuglevel,--debug=debuglevel:Setsthedebugginglevelasspecified.
-b directory, --basedir=directory: Specifies the base directory used to
determineallotherrelateddirectories.
--big-tables: Used to allow large result sets. They are saved as temporary
resultsinafile.
--bind-address=ip-number:SpecifiestheIPaddresstheserverwillbinditto.
-h directory, --datadir=directory: Specifies the directory where the database
datafilesarestored.
-l [logfile], --log[=logfile]: Add various log information, which includes
connections and error information. If an argument is not provided, then
hostname.logisusedasthelogfile,andherehostnameisthenameoftheserver
machine.
--log-isam[=logfile]: Adds changes to the data (ISAM) files in logs. If an
argument is not provided, then isam.log is used as the log file and the log
generated by this option can only be read and manipulated with the
theisamlogutility.
--log-update[=number]: Logging the database updates info. The log file gets
namedashostname.num,wherethehostnameisthenameoftheservermachine
andthenumistheargumenttotheoptionorgeneratesauniquenumberifthe
argumentisnotspecified.
-L=language, --language=language: To specify the language (English, French,
German,andsoon)fortheserver.
-n,--new:Toenablenewroutines(andpossiblyunsaferoutines).
-S,--skip-new:Todisable/enablenewroutines(andpossiblyunsaferoutines).
-Ovariable=value,--set-variablevariable=value:Tospecifyandsetvalueforthe
variables
--pid-file=file:TogetthenameofthefilehavingtheprocessID(PID)of
therunningserver.Thedefaultvalueforthefileishostname.pid,wherethe
hostnameistheservermachine'sname.
-Pport,--port=port:Tospecifythenetworkportnumber.
--secure: To enable network security checks. But this reduces database
performance.
--skip-name-resolve: To specify using only IP numbers (not names) for the
connections.Thisincreasesthenetworkperformance.
--skip-networking: To disable network connections, with only local access
beingallowed.
--skip-thread-priority:Forgivingallthethreadsthesamepriority.
-Sg:Todisableaccesschecking.Thisallowsalltheusersfullaccesstoall
thedatabases.
-Sl:Tospecifynottoperformthreadlocking.
--use-locking:Toenablethreadlocking.
--socket=file:TospecifythefilenamefortheUnixsocket.
-T,--exit-info: Used to display debugging information during the shutting
downoftheserver.
-v,-V,and--version:Toshowtheversioninformationoftheserver.
mysqld_safe - MySQL server
startupscript
ThisisthemostrecommendedwaytostarttheMySQLserverinaUnix-based
systemasitaddsafewsafetyfeatures,suchaslogginginformationtoerrorlog
ifanyerroroccursatruntimeandrestartingtheserverifthereisanerror.
InsomeoftheUnixplatforms,MySQLinstallationsfromRPMor
Debian packages include the systemd support to manage MySQL
startupandshutdownoperationsandsomysqld_safeisnotinstalled
onthosesystems.
mysqld_safe attempts to execute mysqld and to override the default behavior to
specifythenameoftheserverthatyouwantedtoexecute.Theoptiontospecify
the directory using --ledir is also available so that mysqld_safe will look for the
server in the directory. Most of the options in mysqld_safe are also available in
mysqldandifthespecifiedoptionisunknowntomysqld_safethenitgetspassedon
tomysqld.mysqld_safe,whichreadsoutalltheoptionsfromthemysqld,server,and
mysqld_safe sections in option files. For backward compatibility, mysqld_safe also
readssafe_mysqldsectionsbutyoushouldrenamesuchsectiontobeonthecurrent
onethatismysqld_safe.
Asstatedpreviously,thereareverycommonoptionsspecifiedinbothmysqldand
mysqld_safe,sosomeoftheoptionsareexcludedinthefollowinglistofoptions:
--core-file-size=size
Tospecifythesizeofthecorefilewhichmysqldshouldcreate.
--ledir=dir_name
Ifmysqld is not able to find the server, then use this option to specify the path
name of the directory in which the server is located. This option can be used
onlyonthecommandline,andnotinoptionfiles.Onplatformsthatusesystemd,
thevalueshouldbegiveninthevalueofMYSQLD_OPTS.
--mysqld-safe-log-timestamps
Thisoptionistospecifytheformatfortimestampsinthelogoutputproducedby
mysqld_safe.
--mysqld=prog_name
To specify the server program name contained in the ledir directory that you
wanttostart.Ifmysqld_safecannotfindtheserver,usethe--lediroptiontospecify
thepathnametothedirectorywheretheserverwiththespecifiednameislocated.
Thisoptionisonlyacceptedonthecommandline,andnotfromtheoptionfiles.
--open-files-limit=count
Thenumberoffileswhichmysqldcanopen.
--plugin-dir=dir_name
Tospecifythepathandnameoftheplugindirectory.
--timezone=timezone
Thisoptionistosetthetimezoneenvironmentvariabletothegivenoptionvalue,
dependingonoperatingsystemtimezonespecificationformats.
--user={username|user_id}
Runthemysqldserverasifyouhavethenameoftheuser.Specifytheuser_nameor
specifythenumericuserIDasuser_id.
<strong>basedir=dir_name</strong>
<strong>datadir=data_dir</strong>
<strong>pid-file=file_name</strong>
<strong>service-startup-timeout=seconds</strong>
Tospecifyinsecondshowlongtowaitforconfirmationoftheserver
startup.Iftheserverdoesnotstartwithinthistime,mysql.server
exitswithanerrorindication.Thedefaultvaluefortheoptionis900
secondsandavalueof0meansnottowaitatallforstartupand
providingnegativevaluesmeanstowaitforever(thereshouldnotbea
timeout).
<strong>shell>mysqld_multi[options]{start|stop|reload|report}
[GNR[,GNR]...]</strong>
Intheprecedingsyntax,start,stop,reload(stopandrestart)andreport
referstotheoperationtobeperformed.BasedontheGNRlistvalues
specified,youcanperformtargetedoperationsonsingleormultiple
servers.
Pleasemakesurethatthedatadirectoryforallserversisfully
accessibletotheUnixaccountbywhichthespecificmysqldprocessis
started.Donotusearootaccountunlessyouknowexactlywhatyou
aregoingtodowithit.
Installationprograms
Theprogramsdiscussedinthissectionareusedduringtheinstallationprocessor
when upgrading the MySQL, so make sure you understand it correctly before
doinganymodificationsontheprogram.
comp_err - compiling the MySQL
errormsgfile
This creates the errmsg.sys file which is used by mysqld to identify the error
messages and display individual error codes. comp_err is normally run
automaticallywhenMySQLisbuilt.Theerrmsg.sysfileiscompiledfromthetext
filelocatedin MySQL distributionsatsql/share/errmsg-utf8.txt. Italsogenerates
sql_state.h,mysqld_ername.h,andmysqld_error.hheaderfiles.
comp_err has several options and can be retrieved using the --help option in the
previouscommand.
<strong>shell>mysql_secure_installation[options]</strong>
Youcanusethe--helpoptionhereandretrievealistofotheroptions
wheneverrequired.
<strong>shell>mysql_ssl_rsa_setup[options]</strong>
Usethe--helpoptionhereandretrievealistofotheroptionsif
required.
Usingsslmysql_ssl_rsa_setuplowersthebarriertosslandmakes
iteasiertogeneratetherequiredfilesbutthefilesthataregenerated
areself-signed,whichisnotverysecure.Youcanconsiderobtaininga
CAcertificatefromtherespectiveauthority.
<strong>shell>mysql_tzinfo_to_sqltz_dir</strong><br/>
<strong>shell>mysql_tzinfo_to_sqltz_filetz_name</strong><br/>
<strong>shell>mysql_tzinfo_to_sql--leaptz_file</strong>
Afterrunningthemysql_tzinfo_to_sqlprogram,itishighly
recommendedtorestarttheserversothatitwillnotuseany
previouslycachedtimezonedata.
mysql_upgrade - checking and
upgradingMySQLtables
As the name suggests, this is used for upgrade operations. It checks for any
incompatibilityand makes repairs if it is necessary and also updates the grant
tableswithanychangesinnewversionsofMySQL.Italsoupdatesthesystem
tables so you can take advantage of any new privilege or compatibility that
mighthavebeenaddedinthenewerversion.
BeforeperforminganupgradealwaysbackupyourcurrentMySQL
installation.
Ifmysql_upgradefindsthatatablehaspossibleincompatibility,itperformsatable
checkandattemptsrepairingthetable,andifitcannotrepairit,itwillaskfora
manualtablerepair.
mysql_upgradeshouldbeexecutedeachtimeMySQLisupgraded.Itcommunicates
directly with the MySQL server and sends the required SQL statements to
performanupgrade.
Oncewerunmysql_upgrade,weshouldrestarttheserver.Ifanychangesmadeto
systemtablesaretakenintoeffect,beforerunningit,youshouldmakesurethe
serverisrunning.
Executemysql_upgradewiththefollowingsyntax:
shell>mysql_upgrade[options]
Youcanusethe--helpoptionhereandretrievealistofotheroptionswhenever
required.
MySQL8clientprograms
The MySQL 8 client programs are the programs that are commonly used to
connecttotheMySQLdatabaseandperformdifferentqueryoperations.
Theprogramsinformationdetailedinthefollowingsubsectionincludesmysql—
commandlinetoolswithmanycommandsandrelatedoptionsandconfiguration
forlogging,mysqlcheck,mysqldump,mysqlimport,mysqlsh,mysqladminandsoon.
mysql-thecommand-linetool
This is the most commonly used program. The command-line tool is used for
executingSQLstatementsdirectlyorusingafileinbatchmode.Ithassupport
forbothinteractive and non-interactivemodes.In thissection,we will lookat
themysqlcommandlineandthevariousoptions,commands,logging,andother
relatedprograms.
mysqloptions
mysqlisacommandlinetoolthathasbeenprovidedforalongtimeandsoithas
plentyof optionstogetyourwork done.The followingisthetableof options
withformatsanddescriptions:
Format Description
--auto-rehash Enablesautomaticrehashing
--auto-vertical-
output Enablesautomaticverticalresultsetdisplay
--batch Donotusethehistoryfile
--binary-as-hex Displaysbinaryvaluesinhexadecimalnotation
--binary-mode Disables\r\n-to-\ntranslationandtreatmentof\0as
end-of-query
--bind-address UsesspecifiednetworkinterfacetoconnecttoMySQL
server
--character-sets-dir Directorywherecharactersetsareinstalled
--column-names Writescolumnnamesinresults
--column-type-info Displaysresultsetmetadata
--comments Ascertainswhethertoretainorstripcommentsin
statementssenttotheserver
--compress Compressesallinformationsentbetweenclientandserver
--connect-expired-
password
Indicatestoserverthatclientcanhandleexpiredpassword
sandboxmode
--connect_timeout Numberofsecondsbeforeconnectiontimeout
--database Thedatabasetouse
--debug Writesdebugginglog;supportedonlyifMySQLwasbuilt
withdebuggingsupport
--debug-check Printsdebugginginformationwhenprogramexits
--debug-info Printsdebugginginformation,memory,andCPUstatistics
whenprogramexits
--default-auth Authenticationplugintouse
--default-character-
set Specifiesdefaultcharacterset
--defaults-extra-
file Readsnamedoptionfileinadditiontousualoptionfiles
--defaults-file Readsonlynamedoptionfile
--defaults-group-
suffix Optiongroupsuffixvalue
--delimiter Setsthestatementdelimiter
--enable-cleartext-
plugin Enablescleartextauthenticationplugin
--execute Executesthestatementandquit
--force ContinuesevenifanSQLerroroccurs
--get-server-public-
key PathnametofilecontainingRSApublickey
--help Displayshelpmessageandexit
--histignore Patternsspecifyingwhichstatementstoignoreforlogging
--host ConnectstoMySQLserverongivenhost
--html ProducesHTMLoutput
--ignore-spaces Ignoresspacesafterfunctionnames
--init-command SQLstatementtoexecuteafterconnecting
--line-numbers Writeslinenumbersforerrors
--local-infile EnablesordisableforLOCALcapabilityforLOADDATAINFILE
--login-path Readsloginpathoptionsfrom.mylogin.cnf
--max_allowed_packet Maximumpacketlengthtosendtoorreceivefromserver
--max_join_size Theautomaticlimitforrowsinajoinwhenusing--safe-
updates
--named-commands Enablesnamedmysqlcommands
--net_buffer_length BuffersizeforTCP/IPandsocketcommunication
--no-auto-rehash Disablesautomaticrehashing
--no-beep Donotbeepwhenerrorsoccur
--no-defaults Readsnooptionfiles
--one-database Ignoresstatementsexceptthoseforthedefaultdatabase
namedonthecommandline
--pager Usesthegivencommandforpagingqueryoutput
--password Passwordtousewhenconnectingtoserver
--pipe OnWindows,connecttoserverusingnamedpipe
--plugin-dir Directorywherepluginsareinstalled
--port TCP/IPportnumbertouseforconnection
--print-defaults Printdefaultoptions
--prompt Settheprompttothespecifiedformat
--protocol Connectionprotocoltouse
--quick Donotcacheeachqueryresult
--raw Writescolumnvalueswithoutescapeconversion
--reconnect Iftheconnectiontotheserverislost,automaticallytriesto
reconnect
--i-am-a-dummy,--
safe-updates
AllowsonlyUPDATEandDELETEstatementsthatspecifykey
values
--secure-auth Donotsendpasswordstoserverinold(pre-4.1)format
--select_limit TheautomaticlimitforSELECTstatementswhenusing--safe-
updates
--server-public-key-
path PathnametofilecontainingRSApublickey
--shared-memory-
base-name
Thenameofsharedmemorytouseforshared-memory
connections
--show-warnings Showswarningsaftereachstatementifthereareany
--sigint-ignore IgnoresSIGINTsignals(typicallytheresultoftyping
Control+C)
--silent Silentmode
--skip-auto-rehash Disablesautomaticrehashing
--skip-column-names Donotwritecolumnnamesinresults
--skip-line-numbers Skipslinenumbersforerrors
--skip-named-
commands Disablesnamedmysqlcommands
--skip-pager Disablespaging
--skip-reconnect Disablesreconnecting
--socket Forconnectionstolocalhost,theUnixsocketfileor
Windowsnamedpipetouse
--ssl-ca PathoffilethatcontainslistoftrustedSSLCAs
--ssl-capath PathofdirectorythatcontainstrustedSSLCAcertificates
inPEMformat
--ssl-cert PathoffilethatcontainsX509certificateinPEMformat
--ssl-cipher Listofpermittedcipherstouseforconnectionencryption
--ssl-crl Pathoffilethatcontainscertificaterevocationlists
--ssl-crlpath Pathofdirectorythatcontainscertificaterevocationlist
files
--ssl-key PathoffilethatcontainsX509keyinPEMformat
--ssl-mode Securitystateofconnectiontoserver
--syslog Logsinteractivestatementstosyslog
--table Displaysoutputintabularformat
--tee Appendsacopyofoutputtonamedfile
--tls-version Protocolspermittedforencryptedconnections
--unbuffered Flushesthebufferaftereachquery
--user MySQLusernametousewhenconnectingtoserver
--verbose Verbosemode
--version Displaysversioninformationandexit
--vertical Printsqueryoutputrowsvertically(onelinepercolumn
value)
--wait Iftheconnectioncannotbeestablished,waitandretry
insteadofaborting
--xml ProducesXMLoutput
Reference:https://dev.mysql.com/doc/refman/8.0/en/mysql-command-options.html
Togetmoreinformationonindividualoptions,usethatoptionalongwiththe--
helpoption.
mysqlcommands
EachoftheSQLstatementsthatyouissuearesenttotheserverforexecution.
Thereisalsoalistofcommandsthatmysqlitselfinterprets.Togetthelistofall
thosecommands,type\hor\helpatthemysql>prompt.
Eachofthecommandshavebothlongandshortformthatcanbeused;except
short form cannot be used in multi-line comments. The long form is not case
sensitivebuttheshortformcommandiscasesensitive.
help[arg],\h[arg],\?[arg],?[arg]
Thehelparg[]commandisusedtodisplayhelpmessages,alongwithlistingall
theavailablecommandsinmysql.
charset charset_name, \C
charset_name
Tochangedefaultcharsets,issuingtheSET_NAMESstatement.
clear,\c
Toclearthecurrentoutputorpreviousqueryresultsfromthecommandline.
connect[db_namehost_name],\r
[db_namehost_name]
Toreconnecttheserverbyprovidingdatabaseandhost_namearguments.
edit,\e
Toedittheinputstatementcurrentlyprovided.
exit,\q
Toexitthemysqlcommandline.
prompt[str],\R[str]
Tospecifyastringandreconfigureitwiththemysqlprompt.
quit,\q
Toexitthemysqlcommandline.
status,\s
This is used to check for the status of the server connection that is currently
beingused.
usedb_name,\udb_name
Tospecifyusingtheprovideddb_nameasthedefaultdatabase.
mysqllogging
Themysqlprogramcandologgingasperthefollowingtypes.
On Unix systems, it writes the logs to the history file with the default name
.mysql_historyinthehomedirectory.
Onallplatforms,ifthe--syslogoptionisprovided,itwritesthestatementstothe
systemloggingimplementation.
OnUnix,itissyslog,onWindows,itiseventlogs,onLinuxdistributions,itoften
goestothe/var/log/messagefile.
<strong>mysql>helpsearch_string</strong>
<strong>mysql>helpme</strong><br/><strong>Nothing
found</strong><br/><strong>Pleasetrytorun'helpcontents'froa
listofallaccessibletopics</strong>
Ifsearch_stringmatchesmultiplecontentsofatopic,thenitshowsa
listofmatchingtopicitems.Atopiccanalsobeusedas
search_stringandlooksfortheentryforthetopic.Italsocontains
thewildcardcharacter%and_,whichhavethesamemeaningfor
matchingoperationsperformedbytheLIKEoperator.
<strong>shell>mysqldb_name<text_file</strong>
<strong>shell>mysql<text_file</strong>
<strong>mysql>sourcefile_name</strong>
Byusingthe--verboseoption,eachstatementgetsdisplayedjust
beforetheresultproducedbyit.
<strong>shell>mysqladmin[options]command[command-arg]
[command[command-org]]...</strong>
mysqladminsupportsplentyofprogramcommands,startingfrom
createdb_nametocreatenewdatabasewithnamedb_name,debugto
getdebuginformation,dropdb_nametodropadatabase,flush-xxxx,
wherexxxxcanbereplacedwithlogs,hosts,privileges,status,tables,
threads,andsoon.killidtokilltheserverthreadormultiple
threads,passwordnew_passwordtosetanewpassword,pingtocheck
theserver'savailability,shutdowntostoptheserver,start-slaveto
startreplicationonaslaveserver,stop-slavetostopreplicationon
theslaveserver,variablestodisplayserversystemvariablesand
theirrespectivevalues.
mysqladminstatuscommandsgiveresultswithvaluesofuptime,
threads,questions,slowqueries,opens,andflushtableswithrelevant
information.
Alongwiththecommandlist,thereareoptionsthatcomeinhandy
whenretrievingspecificinformationfromtheserver.Such
informationcanberetrievedusingthemysqladmin--helpcommand.
<strong>shell>mysqlcheck[options]db_name[tbl_name...]
</strong><br/><strong>shell>mysqlcheck[options]--databases
db_name...</strong><br/><strong>shell>mysqlcheck[options]--
all-databases</strong>
mysqlcheckhasaspecialfeaturethatisthedefaultbehaviorof
checkingtables.Itcanbechangedbyrenamingthebinary,suchas
renamingmysqlchecktothemysqlrepairprogrambycreatingacopy
ofmysqlcheckandaddingasymboliclinktomysqlcheck,afterwhich
mysqlrepaircanrepairtablesinstead.Thisalsoworkswiththe
mysqlanalyzeandmysqloptimizeoptionstomakethemthedefault
operationforthemysqlcheckcommand.
Similartootheradministeringprograms,thisprogramalsohavemany
optionsthatcanbeusedtogetspecificinformation,andbyusingthe
mysqlcheck--helpcommand,alistofoptionscanberetrieved.
mysqldump - a database backup
program
This program is a utility program used for making a logical backup by
generating a set of SQL statements which can be executed to reproduce the
originaldatabasetabledataandobjectdefinition.Itdumpsoneormoredatabase
for backup or may transfer to another SQL server. It can also generate data
outputindifferentformats,suchasCSV,XML,orotherdelimitedtextfiles.
<strong>shell>mysqldump[options]db_name[tbl_name...]
</strong><br/><strong>shell>mysqldump[options]--databases
db_name...</strong><br/><strong>shell>mysqldump[options]--all-
databases</strong>
Therearemorethan25optionsavailableformodifyingtheoperation
ofthemysqldumpcommandandtheycanberetrievedbyusingthe
mysqldump--helpcommand.Specificmodificationscanbeusedin
thiscommandfordebuggingoptions,helpoptions,connection
options,DDLoptions,andsoon,basedonyourrequirement.
<strong>shell>mysqlimport[options]db_nametextfile1[textfile2...]
</strong>
OptionsforthecommandscanbespecifiedontheCLIorinthe
[mysqlimport]or[client]groupoftheoptionsfileasperyour
requirement.Itprovidedoptionstoretrieveandmodifyimport
operationsforthedata,suchasusingadifferentdelimiterformat,
debugging,forcingthepathofafile,providingdefaultvalues,
ignoringandlockingtables,andsoon,whichcanberetrievedby
usingthemysqlimport--helpcommand.
<strong>shell>mysqlpump--all-databases</strong>
<strong><spanclass="tokenprompt">shell></span><span
class="tokencommand">mysqlpump</span><spanclass="token
constant">--include-databases</span><spanclass="tokenattr-value">
<spanclass="tokenpunctuation">=</span>db1,db2</span><span
class="tokenconstant">--exclude-tables</span><spanclass="token
attr-value"><spanclass="tokenpunctuation">=
</span>db1.t1,db2.t2</span></strong>
Theprecedingcommanddumpsdatabasesdb1anddb2butitwill
excludetablet1fromthedatabasedb1andtablet2fromthedatabase
db2.
mysqlpumpusesparallelismtoachievetheconcurrentprocessingandit
canbebetweendatabasesorwithinadatabase.--default-
parallelism=Nspecifiesthedefaultnumberofthreadsusedinthe
queuecreatedbytheprogramandthevalueofNis2bydefault.--
parallel-schemas=[N:]db_listsetsuptheprocessingqueueasper
thedatabasenamelistprovided.Thus,additionalqueuesandthe
numberofthreadscanbecontrolled.
mysqlpumpdoesnotdumpperformance_schema,nbdinfo,orsysby
defaultbutcandosobyspecifyingthe--include-databasesoption
andsimilarlyitalsodoesnotdumptheINFORMATION_SCHEMA.
mysqlsh-theMySQLShell
The advanced command line client and editor for MySQL is the very well
knownMySQLShell.IthascapabilitiesforscriptinginPythonandJavaScript.
WhenconnectedtotheMySQLserverusingtheXProtocol,theXDevAPIcan
work with documents and relational data. It includes the AdminAPI, which
enablesyoutoworkwithanInnoDBcluster.
MySQL Shell has many options associated with it, but the important ones are
listedasfollows:
--port=port_num,-Pport_num
TheTCP/IPportnumbertousewithport_num.Thedefaultportis33060.
--node
CreatesanodesessiontoasingleserverusingtheXProtocolandisdeprecated
in8.0.3.
--js
StartsJavaScriptmode.
--py
StartsPythonmode.
--sql
StartsSQLmode.
--sqlc
StartsSQLmodeinClassicSession.
--sqln
StartsSQLmodeinNodeSession.
--sqlx
StartsSQLmodebycreatinganXprotocolconnection.
--ssl*
Optionsbeginningwith--sslspecifyconnecting theserverusingSSLandalso
finding certificates and SSL keys. It works the same way as for the MySQL
Serverand itacceptsSSLoptions :--ssl-crl,--ssl-crlpath,--ssl-mode,--ssl-ca, --
ssl-capath,--ssl-cert,--ssl-cipher,--ssl-key,--tls-version.
Otheroptionsnotlistedcanberetrievedusingthemysqlsh--helpcommand.
mysqlshow - showing database,
table,andcolumninformation
This is the client mainly used to quickly check which databases, their tables,
columns,andindexesexistornot.ItprovidesaninterfacetosomeoftheSQL
SHOWstatements.
Theexecutionsyntaxforthecommandisasfollows:
shell>mysqlshow[options][db_name[tbl_name[col_name]]]
By executing the preceding command, you will get information about the
databases,tables,orcolumnsforwhichyouhaveprivileges:
Alistofdatabasesisshownifnodatabaseisgiven
Alistofallmatchingtablesinthedatabaseisshownifnotableisgiven
A list of all the matching columns and column types in the table is
displayedifnocolumnisgiven
Inthepreviouscommandexecution,ifyouusedtheSQLwildcard
character(*,?,%,_),thennamesthatarematchedbythewildcard
aredisplayed.*and?wildcardcharacters,ifgiven,areconverted
into SQL % and _ wildcard characters. It might create confusion
when trying to display a column with a table or a column name
with_inthename,itdisplaysonlynamesmatchingthepattern,but
it can be fixed easily by adding an extra % at the end of the
commandlineasaseparateargument.
Theprogramhasmanyoptionstogetthedesiredinformationbyusingspecific
optionarguments.Afewoftheimportantonesaregivenasfollows:
--character-sets-dir=dir_name
Specifiesthedirectorynamewherecharactersetsareinstalled.
--compress,-C
Ifboththeclientandtheserversupportcompression,alltheinformationsentis
compressed.
--enable-cleartext-plugin
Enablesthecleartextauthenticationplugin.
--get--server-public-key
Requests the RSA public key from the server required for key-pair-based
password exchange. Also, if a client connects to the server using a secure
connection,RSA-basedpasswordexchangeisnotneededandisignored.
--keys,-k
Displaystableindexes.
--ssl*
Specifies options starting with --ssl to connect to the server using an SSL
connectionbyusingcertificatesandSSLkeys.
Manyotheroptionsnotlistedherecanberetrievedbyusingthemysqlshow--help
command.
<strong>shell>mysqlslap[options]</strong>
<strong>mysqlslap<spanclass="tokenconstant">--
delimiter</span>=<spanclass="tokenatrule">";"</span><span
class="tokenconstant">--create</span>=<spanclass="token
atrule">"CREATETABLEt(iint);INSERTINTOtVALUES(21)"
</span><spanclass="tokenconstant">--query</span>=<span
class="tokenatrule">"SELECT*FROMt"</span><span
class="tokenconstant">--concurrency</span><spanclass="tokenattr-
value"><spanclass="tokenpunctuation">=2</span>0</span><span
class="tokenconstant">--iterations</span><spanclass="tokenattr-
value"><spanclass="tokenpunctuation">=1</span>00</span>
</strong>
<strong>mysqlslap<spanclass="tokenconstant">--
concurrency</span><spanclass="tokenattr-value"><span
class="tokenpunctuation">=7</span></span><spanclass="token
constant">--iterations</span><spanclass="tokenattr-value"><span
class="tokenpunctuation">=</span>20</span><spanclass="token
constant">--number-int-cols</span><spanclass="tokenattr-value">
<spanclass="tokenpunctuation">=</span>2</span><span
class="tokenconstant">--number-char-cols</span><span
class="tokenattr-value"><spanclass="tokenpunctuation">=2</span>
</span><spanclass="tokenproperty">--auto-generate-sql</span>
</strong>
Here,mysqlslapwillbuildastatementwithatableoftwoINT
columnsandtwoVARCHARcolumnsandsevenclientsquerying20
timestoeachofthem.Italsosupportsspecifyingstatementfilesfor
creatingandqueryingseparatelyandrunningtheloadtest.Itprovides
manysuchalterationsinloadtestingexecutionwithoptionsthatyou
cancheckbyexecutingthemysqlslap--helpcommandonthe
commandline.
MySQL8administrativeprograms
This section describes different administrative programs along with some
utilities that will help in doing administration operations such as performing
checksum,compressionandextraction,andsoon.
ibdsdi - InnoDB tablespace SDI
extractionutility
This is a utility program that extracts serialized dictionary information from
InnoDB tablespace files. Serivalized dictionary information that is SDI data will
alwaysbepresentin allpersistent InnoDBtablespace files.Itcan berun onfile-
per-tableontablespacefilesandgeneraltablespacefiles,systemtablespacefiles,
anddatadictionarytablespacefiles,butusingatemporarytablespaceorundoing
atablespaceisnotsupported.
ibd2sdicanbeusedwhiletheserverisofflineoratruntime.Itreadsuncommitted
dataofSDIfromaspecifiedtablespaceandundoeslogsandredoeslogsthatare
notaccessible.
Executionfortheidb2sdiwilllooklikethefollowingcommandline:
shell>ibd2sdi[options]file_name1[file_name2file_name3...]
ibd2sdi also supports multiple tablespaces but does not run on more that one
tablespace at a time as the InnoDB system tablespace. Specifying each file will
workasfollows:
shell>ibd2sdiibdata1ibdata2
ibd2sdioutputsSDIdatainJSONformat.
Therearemanyoptionsavailablefortheprogramwhichcanberetrievedusing
theibd2sdi--helpcommand.
<strong>shell>innochecksum[options]file_name</strong>
innochecksumcommandalsohasfewoptionstodisplayinformation
ofthepagesbeingverifiedandcanberetrievedwithinnochecksum-
-helpcommand.
myisam_ftdump - displaying full-
textindexutility
This is a utility for displaying information about MyISAM tables and FULLTEXT
indexes.Itwillscananddumptheentireindex,whichcanbeaslowandlengthy
process.Iftheserverisalreadyrunning,thenyouneedtomakesuretoinserta
FLUSHTABLESstatementfirst.
Executionforthemyisam_ftdumpcommandwilllooklikethefollowingcodeblock:
shell>myisam_ftdump[options]<table_name><index_num>
Inthepreviousexample,table_nameshouldbethenameoftheMyISAMtablewiththe
.MYIindexextension.
Suppose the test database has a table named mytexttable with the following
definition:CREATETABLE mytexttable( id INT NOT NULL, txt TEXT
NOTNULL,PRIMARYKEY(id),FULLTEXT(txt))ENGINE=MyISAM;
Theindexcreatedonidis0onFULLTEXTindexandonthetxtitis1.Iftheworking
directory is the test database directory, then execute myisam_ftdump as follows:
shell>myisam_ftdumpmytexttable1
myisam_ftdump can also be used to generate a list of index entries in order of
frequencyofoccurrenceasfollows(thefirstlineinWindowsandthesecondline
forUnixsystems):shell>myisam_ftdump-cmytexttable1|sort/R
shell>myisam_ftdump-cmytexttable1|sort-r
myisam_ftdump also has several options that can be retrieved by using the
myisam_ftdump--helpcommand.
myisamchk - MyISAM table-
maintenanceutility
myisamchk is a command line tool for getting information about database tables,
checking,repairing,
andoptimizingnon-partitionedMyISAMtables.ItworkswithMyISAMtables.
CHECK_TABLEandREPAIR_TABLEstatementscanalsobeusedtocheckandrepairMyISAM
tables.
Executionforthemyisamchkcommandisshowninthefollowingcodeblock:
shell>myisamchk[OPTIONS]tables[.MYI|.MYD]
Beforerunningthemyisamchkcommand,youmustmakesurethatany
otherprogramisnotusingthetables.Otherwise,
itwilldisplaywarningmessagesaying:warning:clientsareusing
or haven't closed the table properly. To do this effectively, shut
downtheMySQLserverorlockalltablesbeingused
bymyisamchk.
Thisprogramhasmanyoptionstoperformtablemaintenance.
<strong>shell>myisamlog[options][file_name[tbl_name]...]
</strong><spanclass="tokenpunctuation"><br/></span>
Thedefaultoperationismarkedasanupdateandifrecoveryisdone
allwrites,updates,anddeletesaredoneanderrorsarecountedonly.
myisam.logisthedefaultlogfilename.
Theprogramhassomeoptionsusedtospecifyoffsets,recovery,open
anumberoffiles,andafewmore,whichcanberetrievedbyusingthe
myisamlog--helpcommand.
myisampack - generating
compressed, read-only MyISAM
tables
ThisisautilityprogramthatcompressesMyISAMtables.Itcompresseseachofthe
columnsintablesseparatelyandcompressesthedatafilebyabout40%to70%.
MySQL preferably uses the mmap() function to do memory mapping on
compressedtables;otherwise,itusesnormalread/writefileoperations.
myisampackdoesnotsupportpartitionedtables.
Oncetablesarepacked,theybecomereadonly.
Stoppingtheserverandthengoingforcompresstablesissafewaytoperform
thecompressoperation.
Executionsyntaxformyisampacklookslikethefollowingblockonthe command
line:
shell>myisampack[options]file_name...
Specifytheindexfilenamewithorwithoutthe.MYIfileandalsoaddthepathname
ifyouarenotinthedatabasedirectory.
Aftercompressingatablewithmyisampack,youshouldusemyisampack-rqtorebuild
theindexesof the compressedtable.It supports someofthe common options,
such as versioning, debugging, and so on along with specific compression
checks,suchas--test,--backup,--join=big_tbl_name,--silent,andsoon.Ifyouwant
tocheckindetail,youcanexecutethemyisampack--verbose--helpcommandonthe
commandline.
mysql_config_editor - MySQL
configurationutility
Thisisautilitytostoreandupdatetheauthenticationcredentialsinanencrypted
loginpathfilewiththename.mylogin.cnf.
Forfurtherdetails,usethemysql_config_editor--verbose--helpcommandtoexecute
onthecommandline.
<strong>shell>mysqlbinlog[options]log_file...</strong>
Thereareseveraloptionsthatmodifytheformatoftheoutputand
usageofmysqlbinlog.Theyarelistedasfollows:
Itcanbeconvertedintoahexdumpformatthatcontainsbyte
position,eventtimestamp,andtypeoftheeventthatoccurred
Italsoprovidesaroweventdisplayformatthatdisplaysdata
modificationsinformationintheformofpseudo-SQLstatements
Itisalsousedformakingabackupofthebinarylogfilesby
providingtherequiredoptionvalues,suchasapathforthe
backupfileandtypeorformatoftheoutputinthebackup
WhenyouconnecttotheMySQLserverusingmysqlbinlog,it
providesaspecificserverIDtoidentifyitselfandrequestsbinary
logfilesfromtheserver
Theprogramhassomecommonoptionswhicharenotmentionedbut
canberetrievedusingthemysqlbinlog--helpcommand.
<strong>shell>mysqldumpslow[options][log_file...]</strong>
Youcanmodifytheoutputbyusingsomeoptions,suchaslimitingthe
numberofresult-tN,whereNisthenumberofqueryresultstobe
displayed.-sstandsforsorttypebyquerytime,locktime,orbyrows
count,and-rforreversingthesortorder.
MySQL8environmentvariables
Inthissection,wewilllookatthenumberofenvironmentvariablesthatareused
directly or indirectly for different MySQL programs, changing their behavior
with
theuseofenvironmentvariables.
Optionsprovidedonthecommandlinetakeprecedenceovervaluesspecifiedin
the
option files and on the environment variables, and similarly values in options
take
precedenceoverthe environment variables;soin most cases,itis preferredto
use
anoptionfileinsteadofenvironmentvariablestomodifythebehavior.
The following is the list of environment variables and descriptions for the
variable:
CXX:ThenameofyourC++compilerforrunningCMake
CC:ThenameofyourCcompilerforrunningCMake
DBI_USER:ThedefaultusernameforPerlDBI
DBI_TRACE:TraceoptionsforPerlDBI
HOME:Thedefaultpathforthemysqlhistoryfileis$HOME/.mysql_history
LD_RUN_PATH:Usedtospecifythelocationoflibmysqlclient.so.
LIBMYSQL_ENABLE_CLEARTEXT_PLUGIN:Enablesthe mysql_clear_passwordauthentication
plugin
LIBMYSQL_PLUGIN_DIR:Directoryinwhichtolookforclientplugins
LIBMYSQL_PLUGINS:Clientpluginstopreload
MYSQL_DEBUG:Debugstraceoptionswhendebugging
MYSQL_GROUP_SUFFIX:optionalgroupsuffixvalue(suchasspecifying--defaults-
group-suffix)
MYSQL_HISTFILE: The path to the mysql history file; if this variable is set, its
valueoverridesthedefaultfor$HOME/.mysql_history
MYSQL_HISTIGNORE:Patternsspecifyingstatementsthatmysqlshouldnotlogto
$HOME/.mysql_history,orsyslogif--syslogisgiven
MYSQL_HOME:Thepathtothedirectoryinwhich theserver-specificmy.cnf file
resides
MYSQL_HOST:Thepathtothedirectoryinwhich theserver-specificmy.cnf file
resides
MYSQL_PWD: The default password when connecting to mysqld; using this is
insecure
MYSQL_TCP_PORT:DefaultTCP/IPportnumber
MYSQL_TEST_LOGIN_FILE:Nameofthe.mylogin.cnfloginpathfile
PATH:UsedbytheshelltofindMySQLprograms
PKG_CONFIG_PATH:Locationofthemysqlclient.pcpkg-configfile
TMPDIR:Directoryinwhichtemporaryfilesarecreated
TZ:Thisshouldbesettoyourlocaltimezone
UMASK:User-filecreationmodewhencreatingfiles
UMASK_DIR:User-directorycreationmodewhencreatingdirectories
USER:DefaultusernameonWindowswhenconnectingtomysqld
MYSQL_TEST_LOGIN_FILE is the pathname for the login path file that is created by
mysql_config_editor.
TheUMASKandUMASK_DIRvariablesareusedasmodesinsteadofmasks.
It is necessary to set PKG_CONFIG_PATH if using pkg-config for building MySQL
programs.
MySQLGUItools
TherearemanyMySQLGUItoolsavailableforperformingvariousoperations,
startingwithcreatingdatabasestoperformingdailyadministrationtasks.
MySQLWorkbench
MySQL Workbench is a graphical tool to work with the MySQL server and
databases.It
fully supports MySQL versions 5.1 and above. In this section, we will briefly
discuss
thecapabilitiesofMySQLWorkbench.
FivemainfunctionprovidedbyMySQLWorkbenchareasfollows:
SQL development: This creates and manages database connections,
andconfigurationforconnection
parameters. It executes SQL statements using the built-in SQL editor
anditreplaces
thestandaloneapplicationquerybrowserprovidedearlier.
Data modeling: This creates models of database schema graphically,
withreverseandforwardengineering
betweentwodifferentschemaaswellasonalivedatabase.Itprovides
acomprehensive
table editor, with easy to use facilities for editing tables, columns,
triggers,indexes,
options,inserts,partitioning,routines,views,andprivileges.
Serveradministration:Thiscreates,maintains,andadministersserver
instances.
Data migration: This allows migration from PostgreSQL, SQLite,
SybaseASE,MicrosoftSQLServer,
and other relational database management system objects, tables, and
datatoMySQL.
It also facilitates migration from earlier versions to the latest release
version.
MySQLEnterprisesupport:Thisprovidesenterpriselevelsupportfor
theproduct;forexample,MySQLEnterprise
backup,MySQLAudit.
MySQL workbench is available in two different editions, the
CommercialEditionand
the Community Edition. The Community Edition is provided
withoutanycost.TheCommercial
Edition provides additional features, such as database
documentationgeneration.
MySQLNotifier
MySQL Notifier is a simple tool used to monitor and adjust the status of
local/remote MySQL server instances. It is an indicator which is placed in a
systemtray.ItisinstalledwiththeMySQLinstalleritself.
MySQL Notifier acts as quick launcher with list actions clubbed together that
canbeactandmonitoredveryeasilyfromthesystemtrayitselfandalongwith
that it keeps monitoring based on specified interval and notifies on status
change.
MySQLNotifierusage
MySQLNotifierstaysinsystemtrayandprovidesoneclickoptionforMySQL
statusandmaintenance.FollowingsareimportantusageofMySQLNotifier.
MySQLNotifierprovidesstart,stop,andrestartofMySQLSeverinstances
MySQL Notifier configures MySQL server services and automatically
detectsandaddsnewMySQLserverservices
MySQLNotifiermonitorsbothlocalandremoteMySQLinstances
Summary
In this chapter, we dived deep into the ocean of commands that are used for
almostalltheactivitiesfortheMySQL
server, starting with installation, server start up, client programs to
administrative
programs, and several utility programs to cater for different purposes on a
routine
basis for database administration. The chapter also provided a working
knowledgeof
makingdatabasebackupsandimportingthe databaseswithorwithoutspecific
tables.
ThenextchapterwillfocusonMySQL8datatypesindetail.Itwillcategorize
data
types based on their content types and it will describe properties in detail for
each
of the categories and storage level details that should be kept in mind during
table
andcolumndesign.
MySQL8DataTypes
In the previous chapter, we learned how to use MySQL 8 command-line
programsandutilitiestoperformvariousoperationsontheMySQL8database.
Itisalwaysgoodtohaveholdoncommand-linetools.Itprovidesflexibilityto
workinnon-GUIenvironments.Thefocusofthischapterisdatatypes.Isn'tit
fascinatingtoknowthetypeofdatatheprogramminglanguagesupportsorthe
storage engine can store? It is a fundamental feature of any programming
languageordatabase.Atthesametime,itisthemostignoredtopic,aswell.The
majority of programmers don't spend enough time assessing the storage
requirements for variables used in a piece of code. Actually, it is extremely
important to understand the basic and custom data types that the database
supports,whichiswhythischapterexists.
Thefollowingisalistoftopicstobecoveredinthischapter:
OverviewofMySQL8datatypes
Numericdatatypes
Dateandtimedatatypes
Stringdatatypes
JSONdatatype
Storagerequirementsfordatatypes
Choosingtherightdatatypeforcolumns
OverviewofMySQL8datatypes
All standard SQL data types are supported in MySQL. These data types are
classifiedinafewcategories,suchasnumerictypes,stringtypes,dateandtime
types,andtheJSONdatatype.Whenweassignadatatypetoacolumn,certain
conventionsmustbefollowed.TheseconventionsarenecessaryforMySQLto
allowvaluestobestoredinacolumn:
Mdenotesthemaximumdisplaywidthforintegertypes.Forfloatingpoint
andfixedpointtypes,itisthetotalnumberofdigitsthatcanbestored.For
string types, it is the maximum length. The maximum value allowed
dependsonthedatatype.
D is applicable to floating points and fixed point types. It denotes the
numberofdigitsafterthedecimalpoint.Themaximumallowedvalueis30,
butmustbelessthanorequaltoM-2.
fspis applicable to date and time types. It denotes the fractional seconds
precision,whichmeansthenumberofdigitsfollowingthedecimalpointfor
thefractionalpartofseconds.
This overview is brief so that the detailed descriptions of the features of each
datatypecanbecoveredintopicstofollow.
Numericdatatypes
TheMySQL8numericdatatypesincludeintegerorexactdatatypes,decimalor
approximatedatatypes,andbitdatatypes.
Bydefault,REALdatatypevaluesarestoredasDOUBLE.Ifwehaveset
theREAL_AS_FLOATflagonMySQL,REALdatatypevaluesarestoredas
FLOAT.FLOAToccupieslessspacecomparedtoDOUBLE.
<strong>CREATETABLEemployees</strong><br/><strong>(salary
INTEGER(5)UNSIGNED);</strong>
<strong>CREATETABLEemployees</strong><br/><strong>(id
INT(255));</strong>
<strong>CREATETABLEdocuments</strong><br/><strong>
(document_noINT(5)ZEROFILL);</strong>
Wespecifiedthevaluetobestoredas111;itwillbestoredas00111if
weprovidedtheZEROFILLoption.
Fixedpointtypes
Fixed point types represent numbers with a fixed number of digits after the
decimalorradixpoint.MySQLhasDECIMALandNUMERIC as fixed point, or exact,
value data types. These values are stored in a binary format. Fixed point data
types are useful, especially in storing monetary values in multiplication and
division operations. The value of a fixed point data type is an integer number
scaledbyaspecificfactor,accordingtothetype.Forexample,thevalueof1.11
canberepresentedinfixedpointas111,withascalingfactorof1/100.Similarly,
1,110,000canberepresentedas1110,withascalingfactorof1000.
ThefollowingcodeblockdemonstratesthedeclarationofaDECIMALdatatype:
CREATETABLEtaxes
(tax_rateDECIMAL(3,2));
Intheprecedingexample,3istheprecisionand2isthescale.Anexamplevalue
couldbe4.65,where4istheprecisionand65isthescale:
Precision:Denotesthenumberofsignificantdigitsstoredforthevalues
Scale:Representsthenumberofdigitsafterthedecimalpoint
Precisionandscaledefinetherangeofvaluesthatcanbestoredinthecolumn.
So,intheprecedingcolumndeclaration,tax_ratecanstorevaluesfallingbetween
-9.99and9.99.
ThesyntaxfordefiningtheDECIMALtypeinstandardSQLisasfollows:
DECIMAL(M)
InMySQL,thisisequivalentto:
DECIMAL(M,0)
DeclaringacolumnwithDECIMALisequivalenttoDECIMAL(M,0)inMySQL.
InMySQL,10isthedefaultvalueforM,ifit'snotprovided.
The maximum number of digits supported for the DECIMAL type is 65, including
precisionandscale.Wecanlimitthenumberofdigitsonvalueswhichcanbe
enteredforacolumnbyusingprecisionandscale.Ifauserentersavaluewitha
larger number of digits than permitted in scale, the value will be truncated to
matchthepermittedscale.
DECIMAL is often considered to be an alternative to DOUBLE or FLOAT. As mentioned
earlier, DECIMAL numbers are an exact representation of REAL numbers in
mathematics. The only problem with the DECIMAL data type is that it occupies
much more space, even for small numbers. For example, to store a value of
0.000003,thecolumndeclarationshouldhavethedatatypedefinedasDECIMAL(7,
6).
Ifthescaleis0,thecolumnvaluesdon'thavedecimalpointsorfractionalvalues.
Floatingpointtypes
Floatingpointnumbersrepresentrealnumbersincomputing.Realnumbersare
usefulformeasuringcontinuousvalues,suchasweight,height,orspeed.
MySQLhastwofloatingpointdatatypesforstoringapproximate values:FLOAT
andDOUBLE.
For floating point numbers, precision is an important factor. Precision defines
themeasureofaccuracy.MySQLsupportssingleprecisionanddoubleprecision
floating point numbers. It consumes four bytes to store a single precision
floatingpointnumberwiththeFLOATdatatype,whereasitconsumeseightbytes
tostoreadoubleprecisionfloatingpointnumberwiththeDOUBLEdatatype.
In MySQL, REAL is a synonym for DOUBLE PRECISION. As mentioned earlier, if
REAL_AS_FLOATisenabled,acolumndefinedwiththeREALdatatypewillbetreated
similarlytoFLOAT.
TheprecedingdescriptiondepictsFLOATorDOUBLEassimilartoDECIMAL.No,itisnot.
Thereisahugedifference.Asdescribedearlier,fixedpointdatatypessuchas
DECIMAL or NUMERIC can store exact values, up to the maximum digit after the
decimal point, whereas floating point data types, such as FLOAT or DOUBLE, store
approximatevalues.Thevaluesstored aredetailedenough,butnotcompletely
accurate.Thereremainsaminorinaccuracy.
Let'sunderstandthisthroughthefollowingcodeexample:
mysql>CREATETABLEtyped_numbers(idTINYINT,float_valuesFLOAT,decimal_valuesDECIMAL(3,2));
mysql>INSERTINTOtyped_numbersVALUES(1,1.1,1.1),(2,1.1,1.1),(3,1.1,1.1);
mysql>SELECT*FROMtyped_numbers;
+------+--------------+------------------+
|id|float_values|decimal_values|
+------+--------------+------------------+
|1|1.1|1.10|
|2|1.1|1.10|
|3|1.1|1.10|
+------+--------------+------------------+
mysql>SELECTSUM(float_values),SUM(decimal_values)FROMtyped_numbers;
+--------------------+---------------------+
|SUM(float_values)|SUM(decimal_values)|
+--------------------+---------------------+
|3.3000000715255737|3.30|
+--------------------+---------------------+
Intheprecedingexample:
1. WecreatedatablecontainingFLOATandDECIMALtypecolumns.
2. We inserted the same values in two columns, named float_values and
decimal_values.
3. Weexecutedaselectquerytofetchthesumofstoredvalues.
Thoughthesamevalues,theoutputisdifferent.Thesumofdecimal_valueslooks
moreprecisecomparedtothatofthefloat_values.Thesumoffloat_values looks
less precise. This is because of internal rounding performed by the MySQL
enginefor floating point data types, which results in the approximation stored
value.
Standard SQL has a provision for specifying precision while defining a FLOAT
column. The precision is in bits specified following the keyword FLOAT within
parenthesis.MySQLalsosupportsspecifyingprecisionvaluesforFLOATorDOUBLE,
buttheprecisionisusedtodeterminethesize:
Precisionfrom0to23resultsina4bytesingleprecisionFLOATcolumn
Precisionfrom24to53resultsinan8bytedoubleprecisionDOUBLEcolumn
ThefollowingisanexampleofFLOATcolumndeclarationattributes:
FLOAT(M,D)
where,
M-numberofdigitsintotal
D-numberofdigitsmaybeafterthedecimalpoint
So,thecolumndefinedasthefollowingwillstoreavaluesuchas99.99:
FLOAT(4,2)
While storing floating point values, MySQL performs rounding. So, the value
inserted as 99.09 into a FLOAT(4, 2) column may be stored as 99.01 as an
approximateresult.
Though the floating point column definition supports specifying
precision, it is advisable to use FLOAT or DOUBLE PRECISION with no
precisionornumberofdigits,soastotakeadvantageofmaximum
flexibilityandportability.
<strong>mysql>CREATETABLEtemp(idINT,col1DOUBLE,col2
DOUBLE);</strong><br/><br/><strong>mysql>INSERTINTO
tempVALUES(1,5.30,2.30),(1,-3.00,0.00),</strong><br/>
<strong>(2,0.10,-10.00),(2,-15.20,4.00),(2,0.00,-7.10),</strong>
<br/><strong>(3,0.00,2.30),(3,0.00,0.00);</strong><br/><br/>
<strong>mysql>SELECTid,SUM(col1)asv1,SUM(col2)asv2
FROMtemp</strong><br/><strong>GROUPBYidHAVINGv1<>
v2;</strong><br/><strong>+------+--------+--------+</strong><br/>
<strong>|id|v1|v2|</strong><br/><strong>+------+--------+--------
+</strong><br/><strong>|1|2.3|2.3|</strong><br/><strong>|2|
-15.1|-13.1|</strong><br/><strong>|3|0.0|2.3|</strong><br/>
<strong>+------+--------+--------+</strong>
Intheprecedingexample,itseemsthatthefirsttworowsintheoutput
havesimilarnumbers.Itispossiblethattheymightnotbe,inthecase
offloatingpointtypes.Ifwewanttoensure,intheprecedingcase,
thatsimilar-lookingvaluesareconsidered,wehavetocomparethe
differenceagainstapredefinednumberwithprecision.Forexample,
intheprecedingcase,ifwemodifytheHAVINGclausetocheckthe
conditionABS(v1-v2)>0.1,itwillreturntheexpectedoutput.
Asinterpretationoffloatingpointnumbersisplatformdependent,if
wetrytoinsertavaluewhichisoutsideoftherangeoffloatingpoint
datatypesupportedvalues,itmayinsert+-infor+-0.
Bitvaluetype
Have you ever come across a requirement to store binary representations of
numbers?Canyouthinkofsuchusecases?Onesuchusecaseistostoreweekly
workingdaysinformationforayear.Wewilltouchbaseonthisexamplelaterin
thesection.
TheBITdatatypeisusedtostorebinarybitsorgroupsofbitvalues.Itisalsoone
oftheoptionstostoreBoolean,yes/noor0/1values.
TheBITtypecolumncanbedefinedas:
column_nameBIT
or
column_nameBIT(m)
wherem=numberofbitstobestored
ForaBITdatatype,mcanvaryfrom1to64.Supplyingmisoptional.Thedefault
valueformis1.
ThefollowingisanexampleofhowaBITcolumncanbedefined:
CREATETABLEworking_days(
yearINT,
weekINT,
daysBIT(7),
PRIMARYKEY(year,week));
AftertheBITdatatypecolumndeclaration,nextisstoringbitvaluesinacolumn.
The bit values are a combination of zeros (0s) and ones (1s). The b'value'
notationisusedtospecifybitvalues.
Thefollowingaretheexamplesofhowtostore11and55inaBITcolumn:
CREATETABLEbit_values(valBIT(7));
INSERTINTObit_valuesVALUES(b'1011');
INSERTINTObit_valuesVALUES(b'110111');
WhathappensifthevaluestoredintheBITcolumnislessthanthenumberofbits
(m)specifiedinthecolumndefinition?MySQLwillpadthevaluewith0sonthe
left of the number. So, for the preceding example, the values stored will be
0001011and0110111,respectively.
HowdowedefineaBITcolumntostoreboolean_values?Thefollowingcodeblock
showsthat:
CREATETABLEboolean_values(valueBIT(1));
or
CREATETABLEboolean_values(valueBIT);
INSERTINTOboolean_valuesVALUES(b'0');
INSERTINTOboolean_valuesVALUES(b'1');
<strong>mysql>SELECTb'1010110',CHARSET(b'1010110');
</strong><br/><strong>+--------------+----------------------+</strong>
<br/><strong>|b'1010110'|CHARSET(b'1010110')|</strong><br/>
<strong>+--------------+----------------------+</strong><br/><strong>|
V|binary|</strong><br/><strong>+--------------+----------------------+
</strong><br/><br/><strong>mysql>SELECT0b1100100,
CHARSET(0b1100100);</strong><br/><strong>+--------------+-------
---------------+</strong><br/><strong>|0b1100100|
CHARSET(0b1100100)|</strong><br/><strong>+--------------+------
----------------+</strong><br/><strong>|d|binary|</strong><br/>
<strong>+--------------+----------------------+</strong>
PracticalusesofBIT
Let'scontinuewiththeworkingdaysperweekinayearexample.Pleasereferto
theworking_daystableschemaprovidedearlier.
HowcanwespecifythattheMondayandFridayintheweek4intheyear2017
are non-working days? The following is the INSERT query for this: INSERT
INTOworking_daysVALUES(2017,4,0111011);
If we fetch the working_days records using the SELECT query, the following is the
output:
mysql>SELECTyear,week,daysFROMworking_days;
+--------+---------+--------+
|year|week|days|
+--------+---------+--------+
|2017|4|59|
+--------+---------+--------+
Intheprecedingoutput,thedays,thoughbeingofbitdatatypes,showinteger
values.Howcanweshowbitvaluesintheoutput?
TheansweristheBIN()MySQLfunction.Thefunctionconvertsanintegervalue
toitsbinaryrepresentation:
mysql>SELECTyear,week,BIN(days)FROMworking_days;
+--------+---------+------------+
|year|week|days|
+--------+---------+------------+
|2017|4|111011|
+--------+---------+------------+
As you can see, the leading zeros are removed from the days' bit value in the
output.Toaccomplishtherepresentationintheoutput,ontopoftheBINfunction,
wecanusetheLPADMySQLfunction:
mysql>SELECTyear,week,LPAD(BIN(days),7,'0')FROMworking_days;
+--------+---------+------------+
|year|week|days|
+--------+---------+------------+
|2017|4|0111011|
+--------+---------+------------+
Typeattributes
As shown earlier, while defining integer columns, we can also specify an
optionaldisplaywidthattribute.Forexample,INT(5)indicatesanintegernumber
withadisplaywidthof5digits.WhenthiscolumnisusedintheSELECTquery,the
outputwilldisplaythenumberleftpaddedwithspaces.So,ifthevaluestoredin
theINT(5)columnis123,thenitwillbedisplayedas__123.The_willbeaspacein
theactualoutput.
However,thedisplaywidthdoesn'tlimittherangeofvalueswhichcanbestored
intheINT(5)column.Thequestionthenarises:Whatifwestoreavalueforwhich
thedisplaywidth islargerthanthe displaywidthspecified?Thedisplaywidth
doesn't prevent values wider than the display width of a column from being
displayed correctly. So, values wider than the column display width are
displayedinfullwidth,usingmorethanthenumberofdigitsspecifiedwiththe
displaywidth.
Asmentionedearlier,MySQLcolumndefinitionprovidesanoptionalattribute
called ZEROFILL. This optional attribute, when specified, replaces left padded
spaceswithzeros.Forexample,foracolumndefinedasthefollowing,avalue
of82isretrievedas00082:
INT(5)ZEROFILL
This optional attribute is useful where the proper formatting of numbers is
important.
TheZEROFILLattributeisignoredwhenthecolumnvalue isusedin
expressionsorinaUNIONquery.
MySQLcreatestemporarytableswhencomplicatedjoinsareused
inaquerytostoreintermediateresults.Insuchacase,wemayface
issuesifwespecifiedacolumnwithdisplaywidth.Inthesecases,
MySQLconsidersthatthedatavaluesfitwithinthedisplaywidth.
Another important attribute is UNSIGNED. The UNSIGNED attribute permits only non-
negative values to be stored in the column. It is also useful when we need
supportforalargerrangeofvaluestobestoredwiththesamedatatype.
UNSIGNEDisalsosupportedbyfloatingpointtypesandfixedpointtypes.
If we specify a ZEROFILL attribute for a column, UNSIGNED is
automaticallyaddedtothecolumn.
Another important attribute for integer and floating point columns is
AUTO_INCREMENT. When we insert a NULL value in the column defined with the
AUTO_INCREMENTattribute,MySQLstoresvalue+1insteadofNULL.Avalueof0willbe
treated the same as that of a NULL value, unless the NO_AUTO_VALUE_ON_ZERO mode is
enabled.Here,thevalueisthelargestvaluestoredinthecolumn.Itisextremely
importantthatthecolumnisdefinedasNOTNULL.Otherwise,theNULLvaluewillbe
storedasNULL,eventhoughtheAUTO_INCREMENTattributeisprovided.
Overflowhandling
Whenanout-of-rangevalueisstoredinthenumerictypecolumninMySQL,the
valuestoreddependsontheMySQLmode:
Ifstrictmodeis enabled,MySQL willnotaccept thevalue andthrowan
error.Theinsertoperationfails.
If restrictive modes are enabled, the value is clipped by MySQL to an
appropriatevalue,andthatiswhatisstoredinthecolumn.
Dateandtimedatatypes
DATE,TIME,DATETIME,TIMESTAMP,andYEARformthegroupofdateandtimedatatypes
forstoringtemporalvalues.Eachofthesetypeshasarangeofpermittedvalues.
Apartfromthepermittedvalues,aspecialzerovaluecanalsobeusedtospecify
aninvalidvaluewhichMySQLcannotrepresent.Thezerovaluecanbe00-00-
0000.MySQLallowsthisvaluetobestoredinadatecolumn.Thisissometimes
moreconvenientthanstoringNULLvalues.
Thefollowingarethegeneralconsiderationswemusttakecareofwhileworking
withdateandtimetypes.
ThewayMySQLtreatsstorageandretrievaloperationsfordateortimetypesis
differentin the context of the format. Basically, for a date or time type value
storedinthetable,MySQLretrievesvaluesinastandardoutputformat.Inthe
caseofinputtingadateortimetypevalue,MySQLattemptstoapplydifferent
formatsonthesuppliedinputvalue.So,itisexpectedthatthesuppliedvalueis
valid,orunexpectedresultsmayoccurifusedvaluesinunsupportedformats.
ThoughMySQLcaninterpretinputvalueswithseveraldifferentformats,parts
of the date value must be supplied in a year-month-day format. For example,
2017-10-22or16-02-14.
Supplying a two-digit year creates ambiguity for MySQL to interpret the year
because of the unknown century. The following are the rules that must be
followed,usingwhichMySQLinterpretstwo-digityearvalues:
Yearvaluesbetween70-99areconvertedto1970-1999
Yearvaluesbetween00-69areconvertedto2000-2069
Itispossibletoconvertavaluefromonetemporaltypetoanothertemporaltype
followingcertainrules.Wewilldiscusstheseruleslaterinthechapter.
Ifthedateortimevalueisusedinanumericcontext,MySQLwillautomatically
convertthevaluetoanumber.
Wehaveoneinterestingusecase.Wewanttodevelopanauditlogfeaturewhere
westoreeveryuser-enteredvalue.Supposethatinoneofthedatefields,theuser
enteredan invaliddate,2017-02-31. Will thisbestored in theauditlog table?
Certainly not. How do we complete the feature, then? MySQL has the
ALLOW_INVALID_DATESmode.Ifenabled,itwillallowinvaliddatestobestored.With
thismodeenabled,MySQL verifiesthatthemonthisintherange of1-12and
dayisintherangeof1-31.
AsODBCcannothandlezerovaluesfordateortime,suchvalues
usedthroughConnector/ODBCareconvertedtoNULL.
Followingtableshowszerovaluesfordifferentdatatypes:
DataType ZeroValue
DATE 0000-00-00
TIME 00:00:00
DATETIME 0000-00-0000:00:00
TIMESTAMP 0000-00-0000:00:00
YEAR 0000
Reference:https://dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html
Theprecedingtableshowszero valuesfordifferenttemporal datatypes.These
arespecialvalues,astheseareallowedbyMySQLandareveryusefulincertain
cases.Wecanalsospecifyzerovaluesusing'0'or0.MySQLhasaninteresting
modeconfiguration:NO_ZERO_DATE.Ifthisconfigurationisenabled,MySQLshows
awarningifthetemporaltypehasavaluewiththedateaszero.
DATE, DATETIME, and
TIMESTAMPtypes
This section describes the most commonly used MySQL date and time data
types: DATE, DATETIME, and TIMESTAMP. This section explains the similarities and
differencesbetweenthesedatatypes.
TheDATEdatatypeissuitablewhenthevalueswewishtostorehaveadatepart,
butthetimepartismissing.ThestandardMySQLdateformatisYYYY-MM-
DD. The datevalues are retrieved and displayed in the standard format unless
DATEfunctionsareapplied.TheMySQLsupportedrangeofvaluesis1000-01-01
to 9999-12-31. Supported, here, means the values may work, but there is no
guarantee.ThesameisthecasefortheDATETIMEdatatype.
TheDATETIMEdatatypeissuitableforvaluescontainingdateandtimeparts.The
standardMySQLDATETIMEformatisYYYY-MM-DDHH:MM:SS.Thesupported
rangeofvaluesis1000-01-0100:00:00to9999-12-3123:59:59.
SimilartoDATETIME, the TIMESTAMP data type is also suitable for values containing
dateandtimeparts.However,therangeofvaluessupportedbytheTIMESTAMPdata
typeis1970-01-0100:00:01UTCto2038-01-1903:14:07UTC.
Thoughtheylooksimilar,theDATETIMEandTIMESTAMPdatatypesdiffersignificantly:
TheTIMESTAMPdatatyperequires4bytestostoredateandtimevalues.The
DATETIMEdatatyperequires5bytestostoredateandtimevalues.
TIMESTAMPcanstorevaluestill2038-01-1903:14:07UTC.Ifwewishtostore
valuesbeyond2038,theDATETIMEdatatypeshouldbeused.
TIMESTAMPconsidersUTCasthetimezonewhilestoringvalues.DATETIMEstores
valueswithouttimezoneconsideration.
Let'suseanexampletounderstandthedifferencebetweenDATETIMEandTIMESTAMP
withinthecontextoftime_zone.
Supposetheinitialtime_zonevalueissetto+00:00:
SETtime_zone='+00:00';
Let'screateatablecalleddatetime_temp.Thetablehastwocolumns;oneisDATETIME
andanotherisofthetypeTIMESTAMP.Wewillstorethesamedateandtimevalues
inbothcolumns.WiththehelpoftheSELECTquery,wewilltrytounderstandhow
therepresentationsdifferinoutput:
mysql>CREATETABLEdatetime_temp(
tsTIMESTAMP,
dtDATETIME);
mysql>INSERTINTOdatetime_temp
VALUES(NOW(),NOW());
mysql>SELECTts,dtFROMdatetime_temp;
+------------------------+-------------------------+
>|ts|dt|
+------------------------+-------------------------+
|2017-10-1418:10:25|2017-10-1418:10:25|
+------------------------+-------------------------+
Intheprecedingexample,NOW()istheMySQLfunctionwhichreturnsthecurrent
dateandtimevalues.Lookingattheoutput,itseemsthatboththeTIMESTAMPand
DATETIMErepresentationsaresame.Itisbecausethetime_zonevalueissettoUTC.
Bydefault,TIMESTAMPshowsthedatetimevalueconsideringtheUTCtime_zone.On
theotherpart,DATETIMEshowsdatetimewithoutatime_zone.
Let'schangethetime_zoneandobservetheoutput:
mysql>SETtime_zone='+03:00';
mysql>SELECTts,dtFROMdatetime_temp;
+------------------------+-------------------------+
|ts|dt|
+------------------------+-------------------------+
|2017-10-1421:10:25|2017-10-1418:10:25|
+------------------------+-------------------------+
Lookingattheoutput,itisclearthattheTIMESTAMPconsidersthetime_zonevalueset
inMySQL.So,theTIMESTAMPvaluegotadjustedwhenwechangedthetimezone.
DATETIMEisn'timpacted,sotheoutputisnotchanged,evenafterchangingthetime
zone.
IfTIMESTAMPisusedtostoredateandtimevalues,wemustconsiderit
seriously when migrating data to a different server located in a
differenttimezone.
If higher precision for the time value is required, DATETIME and TIMESTAMP can
include trailing fractional seconds as small as microseconds (six digits). So, if
weinsertadatetimevaluewithamicrosecondsvalue,it willbe storedin the
database. The format, including the fractional part, is YYYY-MM-DD
HH:MM:SS[.fraction], and the range is from 1000-01-01 00:00:00.000000 to
9999-12-3123:59:59.999999.The rangeforTIMESTAMP, including the fraction, is
1970-01-0100:00:01.000000to2038-01-1903:14:07.999999.
Thefractionalpartisseparatedfromthetimevaluebyadecimalpointbecause
MySQLdoesn'trecognizeanyotherdelimiterforfractionalseconds.
DateandtimevaluesstoredwiththeTIMESTAMPdatatypeareconvertedfromthe
server'stimezonetoUTCforstorageandfromUTCtotheserver'stimezonefor
retrieval.IfwestoredaTIMESTAMPvalueandthenchangedtheserver'stimezone
andretrievedthevalue,theretrievedvaluewouldbedifferentfromtheonewe
stored.
ThefollowingisthelistofpropertiesofdatevalueinterpretationinMySQL:
MySQL supports a relaxed format for values specified as string. In a
relaxed format, any punctuation character can be used as the delimiter
betweendatepartsortimeparts.Thisisalittlebitconfusing.Forexample,
avalue10:11:12mightlooklikeatimevaluebecauseoftheuseof:,butis
interpretedasa2010-11-12date.
The only recognized delimiter between the rest of the time part and the
fractionalsecondspartisthedecimalpoint.
It is expected that month and day values are valid. With strict mode
disabled,invaliddatesareconvertedtorespectivezerovaluesandawarning
messageisshown.
TIMESTAMPvaluesthatincludezerointhedayormonthcolumnarenotavalid
date.Theexceptiontothisruleisthezerovalue.
If MySQL is run with MAXDB mode enabled, TIMESTAMP is identical to
DATETIME. If this mode is enabled at the time of table creation,
TIMESTAMPvaluesareconvertedtoDATETIME.
<strong>mysql>SET@dt=NOW();</strong>
<strong>mysql>SELECT@dt;</strong><br/><strong>+--------------
-------+</strong><br/><strong>|@dt|</strong><br/><strong>+------
---------------+</strong><br/><strong>|2017-10-1513:43:17|
</strong><br/><strong>+---------------------+</strong>
<strong>mysql>SELECTDATE(@dt);</strong><br/><strong>+-----
-------------+</strong><br/><strong>|DATE(@dt)|</strong><br/>
<strong>+------------------+</strong><br/><strong>|2017-10-15|
</strong><br/><strong>+------------------+</strong>
<strong>mysql>SELECTTIME(@dt);</strong><br/><strong>+-----
-------------+</strong><br/><strong>|TIME(@dt)|</strong><br/>
<strong>+------------------+</strong><br/><strong>|13:43:17|
</strong><br/><strong>+------------------+</strong>
<strong>mysql>SELECT</strong><br/><strong>HOUR(@dt),
</strong><br/><strong>MINUTE(@dt),</strong><br/><strong>
SECOND(@dt),</strong><br/><strong>DAY(@dt),</strong><br/>
<strong>WEEK(@dt),</strong><br/><strong>MONTH(@dt),
</strong><br/><strong>QUARTER(@dt),</strong><br/><strong>
YEAR(@dt);</strong><br/><strong>+-----------+-------------+---------
----+---------+----------+</strong><br/><strong>|HOUR(@dt)|
MINUTE(@dt)|SECOND(@dt)|DAY(@dt)|WEEK(@dt)|
</strong><br/><strong>+-----------+-------------+-------------+---------
+----------+</strong><br/><strong>+------------+--------------+----------
-+</strong><br/><strong>|MONTH(@dt)|QUARTER(@dt)|
YEAR(@dt)|</strong><br/><strong>+------------+--------------+-------
----+</strong><br/><strong>+-----------+-------------+-------------+-----
----+----------+</strong><br/><strong>|13|43|17|15|41|
</strong><br/><strong>+-----------+-------------+-------------+---------
+----------+</strong><br/><strong>+------------+--------------+----------
-+</strong><br/><strong>|10|4|2017|</strong><br/><strong>+--
----------+--------------+-----------+</strong>
TIMEtype
MySQL DATETIME or TIMESTAMP data types are used to represent specific times at
particular dates. How about storing only the time of the day or the time
differencebetweentwoevents?MySQL'sTIMEdatatypeservesthepurpose.
The standard MySQL format for storing or displaying TIME data type values is
HH:MM:SS. The time value represents the time of the day, which is less than 24
hours, but the TIME data type, as mentioned earlier, can also be used to stored
elapsed time or time difference between two events. So, the TIME column can
storevaluesgreaterthan24hours.
TheMySQLTIMEcolumnisdefinedasfollows:
column_nameTIME;
TherangeofvaluesthatcanbestoredintheTIMEdatatypecolumnis-838:59:59
to838:59:59.
The MySQL TIME column can also store the fractional seconds part up to
microseconds (six digits), similar to the DATETIME column. Considering the
fractionalsecondprecision,therangeofvaluesvariesfrom-838:59:59.000000
to838:59:59.00000.
TheMySQLTIMEcolumncanalsohaveanoptionalvalue:
column_nameTIME(N);
whereNrepresentsnumberoffractionalpart,whichisupto6digits.
The TIME value usually takes 3 bytes for storage. In the case of the TIME value
includingfractional secondprecision, itwillrequireadditionalbytes,based on
thenumberoffractionalsecondprecision.
The following table shows the number of additional bytes required to store
fractional-secondprecision:
FractionalSecondPrecision Storage(bytes)
0 0
1,2 1
3,4 2
5,6 3
MySQLsupportsabbreviatedvaluesfortheTIMEcolumn.Therearetwodistinct
waysforMySQLtointerpretabbreviatedvalues:
Iftheabbreviatedvaluehasacolon(:),MySQLinterpretsitastimeofthe
day.Forexample,11:12isinterpretedas11:12:00andnotas00:11:12.
Iftheabbreviatedvaluedoesn'thaveacolon(:),MySQLassumesthatthe
tworightmostdigitsrepresentseconds.Thismeansthevalueisinterpreted
aselapsedtime,ratherthantimeoftheday.Forexample,'1214'and1214
areinterpretedbyMySQLas00:12:14.
The decimal point is the only delimiter accepted by MySQL to separate
fractionalsecondprecisionfromtherestofthetimevalueparts.
MySQL, by default, clips the values that lie outside of the permitted range of
values to the closest endpoint of the range. For example, -880:00:00 and
880:00:00 are stored as -838:59:59 and 838:59:59. Invalid TIME values are
convertedto00:00:00. As 00:00:00itselfis a validTIME value, it is difficult to
knowifthevalue00:00:00wasstoredintentionally,orconvertedfromaninvalid
TIMEvalue.
MySQLacceptsstringandnumericvaluesastheTIMEvalues.
<strong>mysql>SELECT</strong><br/><strong>
CURRENT_TIME()AS'CUR_TIME',</strong><br/><strong>
ADDTIME(CURRENT_TIME(),020000)AS'ADDTIME',</strong>
<br/><strong>SUBTIME(CURRENT_TIME(),020000)AS
'SUBTIME';</strong><br/><br/><strong>+----------+-----------+------
-----+</strong><br/><strong>|CUR_TIME|ADDTIME|SUBTIME
|</strong><br/><strong>+----------+-----------+-----------+</strong>
<br/><strong>|10:12:34|12:12:34|08:12:34|</strong><br/>
<strong>+----------+-----------+-----------+</strong>
TheUTC_TIME()functioncanbeusedtofetchtheUTCtime.
<strong>manufacturing_yearYEAR</strong><br/>
<strong>or</strong><br/><strong>manufacturing_yearYEAR(4)
</strong>
OnenotablethingisthatearlierMySQLversionssupportedthe
YEAR(2)typecolumndeclaration.ThesupportforYEAR(2)hasbeen
discontinuedfromMySQL8.Itispossiblethatwemightwantto
upgradetheolderMySQLdatabasetotheMySQL8database.Ina
latersection,wewillexplainthemigrationdetailsfromYEAR(2)to
YEAR(4).
MySQLrepresentsYEARvaluesinaYYYYformat.Therangeof
valuesisfrom1901to2155and0000.
ThefollowingisthelistofformatssupportedforinputtingYEAR
values:
Fourdigitnumberfrom1901to2155.
Fourdigitstringfrom1901to2155.
Oneortwodigitnumberwiththerangeof0to99.YEARvalues
from1to69areconvertedto2001to2069andfrom70to99are
convertedto1970to1999.
Oneortwodigitstringwiththerangeof0to99.YEARvalues
from1to69areconvertedto2001to2069andfrom70to99are
convertedto1970to1999.
Insertinganumeric0hasadisplayvalueof0000andaninternal
valueof0000.Ifwewanttoinsert0andwantittobeinterpreted
as2000,weshouldspecifyitasastring0or00.
TheresultofafunctionthatreturnsanacceptablevalueYEAR
context,forexample,NOW().
MySQLconvertsinvalidYEARvaluesto0000.
<strong>mysql>CREATETABLEtemp(yearYEAR(2));</strong>
<br/><strong>ERROR1818(HY000):SupportsonlyYEARor
YEAR(4)column.</strong>
TheALTERTABLEquery,whichrebuildsthetable,willautomatically
convertYEAR(2)toYEAR(4).TheYEAR(2)column,afterupgradingthe
databasetotheMySQL8database,remainsasYEAR(2),butthe
queriesgiveerrors.
TherearemultiplewaystomigratefromYEAR(2)toYEAR(4):
UsingtheALTERTABLEquerywithFORCEattributeconvertsthe
YEAR(2)columntoYEAR(4).Itdoesn'tconvertthevalues,though.
IftheALTERTABLEqueryisappliedtoareplicationmaster,the
replicationslaveswillreplicatetheALTERTABLEstatement.So,
thechangewillbeavailableonallthereplicationnodes.
Usingbinaryupgrade,withoutdumpingorreloadingdata,is
anotherwayofupgradingYEAR(2)toYEAR(4).Running
mysql_upgradesubsequentlyexecutesREPAIR_TABLEandconverts
YEAR(2)toYEAR(4)withoutchangingvalues.Similartothe
previousalternative,thiswillbereplicatedinreplicationslavesif
itisappliedtoareplicationmaster.
Animportantthingtonoteisthatwhileupgrading,wemustnotdump
theYEAR(2)datawithmysqldumpandreloadthedumpfileafter
upgrading.ThismethodhasthepotentialtochangetheYEAR(2)
valuessignificantly.
BeforeYEAR(2)toYEAR(4)migration,applicationcodemustbe
reviewedfor:
CodethatselectstheYEARvalueintwodigits.
Codethatdoesn'thandlenumeric0insertions.Inserting0into
YEAR(2)resultsin2000,whereasinserting0intoYEAR(4)results
into0000.
Stringdatatypes
Whichisthemostwidelyrequiredanduseddatatypeforrepresentingvalues?
Stringorcharacterdatatypes;it'seasy,right?MySQLsupportsawiderangeof
string data types to fulfill different storage requirements. String data types are
categorized into two categories: fixed length and variable length. CHAR, VARCHAR,
BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET are the MySQL-supported string data
types. The storage requirement for each data type is different and will be
explainedlaterinaseparatesection.
CHARandVARCHARdatatypes
TheCHARdatatypeisafixed-lengthstringdatatypeinMySQL.TheCHARdatatype
is often declared with a maximum number of characters that can be stored as
follows:
dataCHAR(20);
In the preceding example, the data column can store string values that are
capableofstoringmaximumcharacters.
CHARandVARCHARaresimilarinmanyways,withcertaindifferences.TheCHARdata
typeispreferred ifthe stringvaluesto bestoredareoffixed size.Itwill give
betterperformancecomparedtoifVARCHARisusedforfixedsizestrings.
Thelengthsvaryfrom0to255.ThevalueintheCHARcolumncannotexceedthe
maximumlengthdeclaredatthetimeoftablecreation.Ifthelengthofthestring
islessthanthemaximumallowedlength,MySQLaddspaddingontherightto
the length specified. At the time of retrieval, trailing spaces are removed.The
followingisanexample:mysql>CREATETABLEchar_temp(
dataCHAR(3)
);
mysql>INSERTINTOchar_temp(data)VALUES('abc'),('a');
mysql>SELECTdata,LENGTH(data)
FROMchar_temp;
+-------+--------------+
|data|LENGTH(data)|
+-------+--------------+
|abc|3|
+-------+--------------+
|a|2|
+-------+--------------+
Aswecanobserveintheprecedingexample,thesecondrecordwasinsertedas'
a',butintheoutput,thetrailingspaceisremoved.So,thelengthisdisplayedto
be2insteadof3.
MostMySQLcollationshaveapadattribute.Itdetermineshowtrailingspaces
are treated for comparison of non-binary strings. There are two types of
collations:PAD SPACEandNO PAD.IncaseofPAD SPACEcollation,trailingspacesare
not considered in comparison. Strings are compared without regard to trailing
spaces.
In the case of NO PAD collation, the trailing spaces are treated as any other
character.Thefollowingisanexample:mysql>CREATETABLEemployees
(emp_nameCHAR(10));
mysql>INSERTINTOemployeesVALUES('Jack');
mysql> SELECT emp_name = 'Jack', emp_name = 'Jack ' FROM
employees;
+-------------------+--------------------+
|emp_name='Jack'|emp_name='Jack'|
+-------------------+--------------------+
|1|1|
+-------------------+--------------------+
mysql>SELECTemp_nameLIKE'Jack',emp_nameLIKE'Jack'FROM
employees;
+----------------------+------------------------+
|emp_nameLIKE'Jack'|emp_nameLIKE'Jack'|
+----------------------+------------------------+
|1|0|
+----------------------+------------------------+
LIKE is a MySQL operator used for comparison in the WHERE clause. It is
specificallyusedforpatternsearchinginastring.Trailingspacesaresignificant
whencomparingstringvalueswiththeLIKEoperator.
IfPAD_CHAR_TO_FULL_LENGTHmodeisenabled,atthetimeofretrieval,the
trailingspaceswillnotberemoved.
The MySQL VARCHAR data type is a variable length string data type with a
maximumlengthofupto65,535characters.VARCHARvaluesarestoredbyMySQL
asaoneortwobytelengthprefix,alongwithactualdata.Theactualmaximum
lengthofa VARCHAR is subject to the maximum row size, which is 65,536 bytes
sharedamongallcolumns.
IftheVARCHARvaluerequireslessthan255bytes,onebyteisusedfordetermining
lengthprefix.Ifthevaluerequiresmorethan255bytes,twobytesareusedfor
determininglengthprefix.
IfMySQLstrictmodeisenabledandavaluetobeinsertedintheCHARorVARCHAR
columnvalueexceedsthemaximumlength,anerrorwillbegenerated.Ifstrict
modeis disabled, the value will be truncated to the maximum allowed length
withawarning.
UnlikeintheCHARdatatype,valuestobestoredinVARCHARarenotpadded.Also,
trailingspacesarenotremovedwhenthevaluesareretrieved.
BINARY and VARBINARY data
types
AnothersetofMySQLstringdatatypesisBINARYandVARBINARY.Thesearesimilar
toCHAR and VARCHAR data types. An important difference between CHAR/VARCHAR and
BINARY/VARBINARY is that BINARY/VARBINARY data types contain binary strings than
character strings. BINARY/VARBINARY uses binary character sets and collation.
BINARY/VARBINARY are different from CHAR BINARY and VARCHAR BINARY data types. The
basicdifferenceliesinthecharactersetandcollationreferredto.
Themaximumlengthforpermittedvaluesissimilartothatof CHARandVARCHAR.
The only difference is that the length of BINARY and VARBINARY is in bytes, rather
thancharacters.
HowwouldMySQLcomparebinaryvalues?Theansweristhatthecomparison
happensbasedonthenumericvaluesforthebytesinthevalues.
Similar to CHAR/VARCHAR data types, the values are truncated if the length of the
value exceedsthecolumn length, and a warning is generated. This is if strict
modeisnotenabled.Ifstrictmodeisenabled,anerrorisgenerated.
BINARY values are right-padded with the pad value 0x00 (zero bytes) to the
specifiedcolumnlength.Thepadvalueisaddedoninsert,butnotrailingbytes
areremovedonretrieval.WhilecomparingBINARYvalues,allbytesareconsidered
significant.ThisappliestoORDERBYandDISTINCToperators,aswell.Zerobytesand
spaces are different when compared with 0x00 < space. The following is an
exampleofinsertingabinaryvalue:
mysql>CREATETABLEtemp(
dataBINARY(3));
mysql>INSERTINTOtemp(data)VALUES('a');
In this case, 'a ' becomes 'a \0' on insertion. 'a\0' is converted to 'a\0\0'. On
retrieval,valuesremainunchanged.
VARBINARYisavariablelengthstringdatatype.UnlikeBINARY,forVARBINARY,padding
isnotaddedoninsertionandbytesarenotstrippedonretrieval.SimilartoBINARY,
allbytesaresignificantincomparisonforVARBINARY.
If the table has a unique index on columns, insertion of values in the column
differingonlyinnumberoftrailingpadbyteswillgiveaduplicate-keyerror.For
example,ifsuchacolumncontains'a'andwetrytoinsert'a\0',itwillcausea
duplicate-keyerror.
ThefollowingexampleexplainsthepaddingofBINARYvaluesincomparison:
mysql>CREATETABLEbin_temp(dataBINARY(3));
mysql>INSERTINTObin_temp(data)VALUES('c');
mysql>SELECTdata='c',data='c\0\0'frombin_temp;
+------------+-------------------+
|data='c'|data='c\0\0'|
+------------+-------------------+
|0|1|
+------------+-------------------+
In the case that it is required to retrieve the same value as specified without
padding,VARBINARYispreferable.
Ifthevalueretrievedmustbethesameasthevaluespecifiedforstoragewithno
padding, it might be preferable to use VARBINARY or one of the BLOB data types
instead.
BLOBandTEXTdatatypes
InwhatsituationcouldweberequiredtostoredatainaBinaryLargeObject
(BLOB)column?Anyidea?Storingafileorimage,yousaid?Itispartiallytrue.
Before we make a decision to store the images or files in a database or file
system,weneedtoassessthesituation.Ifthefilesarestoredinafilesystemand
migratedovertoanotheroperatingsystem,itispossiblethatfilepointerscould
getcorrupted.Itwillrequireadditionaleffortstofixthefilepointers.Insucha
case, storing files in a database is preferable. However, it might impact
performanceifwestorealargecloggedfileorimagedatainthedatabase.
BLOBisMySQL'ssolutiontostoringlargebinaryinformationofvariablelengths.
MySQL has four BLOB types: TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. The only
differenceamongthesedatatypesisthemaximumlengthofvalueswecanstore.
Thestoragerequirementsforthesedatatypesareexplainedinlatersectionsof
thechapter.
Similar to BLOB, TEXT data types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These
have maximum lengths and storage requirements similar to that of BLOB data
types.
Like BINARY data types, BLOB values are stored as byte strings and have binary
charactersets andcollation.Comparisonsandsortingaredoneonthenumeric
valuesofthecolumnvalues.TEXTvaluesarestoredasnon-binarystrings.
InthecaseofBLOBorTEXTdatatypes,ifthevaluecontainsexcesstrailingspaces,
MySQL truncates with a warning, regardless of the MySQL mode. MySQL
doesn't pad BLOB or TEXT column values on insertion and doesn't strip bytes on
retrieval.
ForaTEXTcolumnwhichisindexed,theindexcomparisonsaddtrailingspacesas
padding at the end of the values. So, a duplicate-key error may occur on
insertioniftheonlydifferencebetweenanexistingTEXTvalueandtheTEXTvalue
tobeinsertedisinthetrailingspaces.BLOBcanberegardedasVARBINARYandTEXT
canberegardedasVARCHAR,withnorestrictiononthelengthofthevalues.
ThefollowingarethedifferencesbetweenVARBINARY,VARCHARandBLOB,TEXT:
When creating indexes on BLOB or TEXT columns, we must specify index
prefixlength
BLOBandTEXTcannothavedefaultvalues
BLOBorTEXTvaluesarerepresentedinternallyasobjectswithseparateallocations,
unlikeotherdatatypes,forwhichthestorageisallocatedoncepercolumn.
ENUMdatatype
MySQL provides a data type for which lists of permitted values can be
predefinedwhenthetableiscreated.ThedatatypeisENUM.Ifwewanttorestrict
the user from inserting values outside a range of values, we should define the
column of data type ENUM. MySQL encodes the user input string values into
numbersforENUMdatatypes.
ENUMprovidesthefollowingmentionedbenefits:
Compactdatastorage
Readablequeriesandoutput
The following is an example that showcases when ENUM is useful: mysql>
CREATETABLEsubjects(
nameVARCHAR(40),
streamENUM('arts','commerce','science')
);
mysql> INSERT INTO subjects (name, stream) VALUES
('biology','science'),('statistics','commerce'),('history','arts');
mysql>SELECTname,streamFROMsubjectsWHEREstream='commerce';
+------------+----------+
|name|stream|
+------------+----------+
|statistics|commerce|
+------------+----------+
mysql>UPDATEsubjectsSETstream='science'WHEREstream='commerce';
ENUMvaluesrequireonebyteofstorage.Storingonemillionsuchrecordsinthis
tablewouldrequireonemillionbytesofstorage,opposedtothesixmillionbytes
requiredbytheVARCHARcolumn.
Thefollowingareimportantlimitationstoconsider:
ENUMvaluesarestoredinternallyasnumbers.So,iftheENUMvalueslooklike
numbers,literalvaluesmaymixupwiththeirinternalindexnumbers.
UsingENUM columns in ORDER BY clauses requires extra care. ENUM values are
assignedindexnumbersbasedontheorderoflisting.ENUMvaluesaresorted
basedontheirindexnumbers.So,itisimportanttomakesurethattheENUM
values list is in alphabetical order. Also, the column should be sorted
lexicallythanbyindexnumbers.
TheENUMvaluemustbeaquotedstringliteral.
Each ENUM value has an index beginning with 1. The index of the empty
stringorerrorvalueis0.WecanfindinvalidENUM valuesbyquerying the
tablewithenum_column_value=0intheWHEREclause.TheindexofNULLvalueis
NULL.IndexreferstothepositionofavaluewithintheENUMlistofvalues.
MySQL automatically removes trailing spaces from ENUM member values
when a table is created. Upon retrieval, values from an ENUM column are
displayed in the case used in the column definition. If a number is to be
storedintheENUMcolumn,thenumberistreatedasanindexintothepossible
values.ThevaluestoredistheENUMvaluewiththatindex.Inthecaseofa
quoted numeric value, it is still interpreted as an index if there is no
matchingstringinthelistofenumeratedvalues.
If an ENUM column is declared to contain NULL values, the NULL value is
consideredavalidvalueforthecolumnandNULLbecomesthedefaultvalue.
IfNULLisnotallowed,thefirstENUMvaluebecomesthedefaultvalue.
IfENUMvaluesareusedinanumericcontext,theindexisused.Thefollowingis
an example query to use ENUM values in a numeric context: mysql> SELECT
stream+1FROMsubjects;
+--------------+
|stream+1|
+--------------+
|4|
|3|
|2|
+--------------+
SETdatatype
MySQLSETisadatatypewhichcanhavezeroormorevalues.Apermittedlistof
valuesisspecifiedatthetimeoftablecreation.Eachvaluemustbefromwithin
thelistofpermittedvalues.Multiplesetmembersarespecifiedbyacomma(,)
separatedlistofvalues.ASET canhaveamaximumof 64distinctmembers.If
strictmodeisenabled,anerrorisgeneratedifduplicatevaluesarefoundinthe
columndefinition.
ItmustbetakencarethatSETmembervaluesdonotcontaincommas;otherwise,
theyareinterpretedasSETmemberseparators.
A column specified as SET('yes', 'no') NOT NULL can have any of the following
values:
''
'yes'
'no'
'yes,no'
Trailing spaces are removed automatically from SET member values. Upon
retrieval,SETcolumnvaluesaredisplayedusingthelettercasewhichwasusedin
thecolumndefinition.
The following is an example of inserting values in the SET data type: mysql>
CREATETABLEtemp(
hobbiesSET('Travel','Sports','FineDining','Dancing'));
mysql>INSERTINTOtemp(hobbies)VALUES(9);
TheSETvaluesarestoredintheMySQLtableasabitmapinwhicheachelement
is represented by one bit. In the preceding case, each element in the SET is
assigned a bit. If the row has a given element, the associated bit will be one.
Becauseofthisapproach,eachelementhasanassociateddecimalvalue.Also,
becauseof the bitmap, though there are only four values, SET will occupy one
byte.Thefollowingisthetableexplainingthis:
Element SETvalue Decimalvalue
Travel 00000001 1
Sports 00000010 2
FineDining 00000100 4
Dancing 00001000 8
MultipleSETelementscanberepresentedbyaddingtheirdecimalvalues.Inthe
precedingcase,thedecimalvalue9isinterpretedasTravel,Dancing.
TheSETdatatypeisnotsocommonlyused.Thisisbecausealthoughitisastring
datatype,itisabitcomplexinimplementation.Thevaluesthatcanbestoredare
limitedto64elements.WecannotaddcommasaspartofSETvalues,becausea
commaisastandardSETvalueseparator.Fromadatabasedesignpointofview,
usingSETmeansthedatabaseisnotnormalized.
JSONdatatype
JSONstandsforJavaScriptObjectNotation.Supposethatwewanttostoreuser
preferencesfor a web application in the database. Usually, we may choose to
createaseparatetablewithid,user_id,key,valuefields.Thismayworkwellfora
small number of users, but in the case of thousands of users, the cost of
maintenance is unaffordable compared to the value it adds to the web
application.
In MySQL, we can utilize the JSON data type for this requirement. MySQL
supports thenative JSON data type, which enables efficient storage for JSON
documents.MySQLsupportsautomaticvalidationofJSONdocumentsstoredin
the JSON column. Trying to store invalid JSON documents produces an error.
JSONdocuments storedinJSONcolumnsareconvertedtoaninternalformat.
Theformatisbinary,andstructuredtoenabletheservertolookupsubojbectsor
nestedvaluesdirectly,bykeyorarrayindex,withoutreadingothervalues.
A JSON column cannot have a default value. The JSON data type requires
similar storage to that of LONGTEXT or LONGBLOB. JSON columns are not indexed
directly,unlikeotherstringdatatypes.
ThefollowingisanexampleofinsertingJSONvaluesinatable:
mysql>CREATETABLEusers(
user_idINTUNSIGNEDNOTNULL,
preferencesJSONNOTNULL);
mysql>INSERTINTOusers(user_id,preferences)
VALUES(1,'{"page_size":10,"hobbies":{"sports":1}}');
mysql>SELECTpreferencesFROMusers;
+---------------------------------------------------------+
|preferences|
+---------------------------------------------------------+
|{"hobbies":{"sports":1},"page_size":10}|
+---------------------------------------------------------+
Intheprecedingexample,wehaveformattedtheJSONvalue.Asanalternative,
wecan also use the built-in JSON_OBJECT function. The function accepts a list of
key/valuepairsandreturnsaJSONobject.Anexamplefollows:
mysql>INSERTINTOusers(user_id,preferences)
VALUES(2,JSON_OBJECT("page_size",1,"network",JSON_ARRAY("GSM","CDMA","WIFI")));
TheprecedingINSERTquerywillinserttheJSONvalue{"page_size": 1, "network":
["GSM","CDMA","WIFI"]}.WecanalsousenestedJSON_OBJECTfunctions.TheJSON_ARRAY
functionreturnsaJSONarraywhenpassedasetofvalues.
Ifthesamekeyisspecifiedmultipletimes,onlythefirstkey/valuepairwillbe
retained.In thecaseoftheJSONdatatype, theobjectkeysaresortedandthe
trailing space between the key/value pairs is removed. The keys in the JSON
objectmustbestrings.
InsertingaJSONvalueinaJSONcolumnsucceedsonlyiftheJSONdocument
is valid. In the case that the JSON document is invalid, MySQL produces an
error.
MySQL has one more important and useful function which operates on JSON
values. The JSON_MERGE function takes multiple JSON objects and produces a
single,aggregateobject.
TheJSON_TYPEfunctiontakesa JSONas anargumentandtriestoparse itinto a
JSONvalue.Itreturnsthevalue'sJSONtypeifitisvalidandproducesanerror
ifotherwise.
PartialupdatesofJSONvalues
WhatshouldwedoifwewanttoupdateavalueinaJSONdocumentstoredina
JSON
datatype?Oneoftheapproachesistoremovetheolddocumentandinsertanew
document, with updates. The approach doesn't seem good, right? MySQL 8.0
supportspartial,inplaceupdateofaJSONdocumentstoredinaJSONdatatype
column. The optimizer requires that an update must meet the following
conditions:
ThecolumnmustbeofJSONtype.
Oneofthreefunctions,JSON_SET(),JSON_REPLACE()orJSON_REMOVE(),canbeused
to update the column. MySQL doesn't permit direct assignment of the
columnvalueasapartialupdate.
The input column and target column must be the same. For example, a
statement such as UPDATE temp SET col1 = JSON_SET(col2, 'one', 10) cannot be
performedasapartialupdate.
The changes only update existing arrays or objects, and no new elements
areaddedtotheparentobjectorarray.
Thereplacementvaluemustnotbelargerthanthevaluebeingreplaced.
Storage requirements for data
types
This section explains storage requirements for different data types in MySQL.
The storage requirements depend on different factors. The storage engines
representdatatypesandstorerawdatadifferently.
Atablehasamaximumrowsizeof65,535bytes,evenifthestorageengineis
capableofsupportinglargerrows.BLOBandTEXTdatatypesareexcluded.
Thefollowingtableexplainsthestoragedetailsfornumericdatatypes:
DataType
Storagerequired
TINYINT 1byte
SMALLINT 2bytes
MEDIUMINT 3bytes
INT,INTEGER 4bytes
BIGINT 8bytes
FLOAT(p)
4bytesif0<=p<=24,
8bytesif25<=p<=53
FLOAT 4bytes
DOUBLE[precision],REAL 8bytes
DECIMAL(M,D),NUMERIC(M,D) Varies
BIT(M) Approximately(M+7)/8bytes
Reference:https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html
The following table explains the storage requirements for DATE and TIME data
types:
DataType
StorageRequired
YEAR 1byte
DATE 3bytes
TIME 3bytes+fractionalsecondsstorage
DATETIME 5bytes+fractionalsecondsstorage
TIMESTAMP 4bytes+fractionalsecondsstorage
The following table explains the storage required for fractional seconds
precision:
FractionalSecondsPrecision
StorageRequired
0 0bytes
1,2 1byte
3,4 2bytes
5,6 3bytes
Thefollowingtableexplainsstoragerequirementsforstringdatatypes:
DataType
StorageRequired
CHAR(M)
M×wbytes,0<=M<=255,wherewisthe
numberofbytesrequiredforthemaximum-
lengthcharacterinthecharacterset
BINARY(M) Mbytes,0<=M<=255
VARCHAR(M),VARBINARY(M)
L+1bytesifthecolumnvaluesrequire0−255
bytes,L+2bytesifthevaluesmayrequire
morethan255bytes
TINYBLOB,TINYTEXT L+1bytes,whereL<28
BLOB,TEXT L+2bytes,whereL<216
MEDIUMBLOB,MEDIUMTEXT L+3bytes,whereL<224
LONGBLOB,LONGTEXT L+4bytes,whereL<232
ENUM('value1','value2',...) 1or2bytes,dependingonthenumberof
enumerationvalues(65,535valuesmaximum)
SET('value1','value2',...) 1,2,3,4,or8bytes,dependingonthenumber
ofsetmembers(64membersmaximum)
Reference:https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html
Inthecaseofstringdatatypes,variablelengthstringsarestoredusingthelength
of the value and the length prefix. The length prefix varies from one to four
bytes,dependingonthedatatype.
StoragerequirementsfortheJSONdatatypeare similartothat ofLONGBLOBand
LONGTEXT.However,astheJSONdocumentsarestoredinbinaryrepresentations,it
imposesanoverheadinstoringJSONdocuments.
Choosing the right data type for
column
Asageneralpractice,weshouldusethemostprecisetypeforstoringdata.For
example, a CHAR data type should be used to store a string value that varies in
lengthfrom1to255characters.AnotherexampleisthatMEDIUMINTUNSIGNEDshould
beusedtostorenumbersrangingfrom1to99999.
Basic operations such as addition, subtraction, multiplication, and division with
DECIMALdataareperformedwiththeprecisionof65decimaldigits.
Basedontheimportanceof accuracyorspeed,useof FLOATorDOUBLE should be
chosen.FixedpointvaluesstoredinBIGINTcanbeusedforhigherprecision.
Thesearegeneralguidelines,butthedecisiontousetherightdatatypeshouldbe
made based on the detailed characteristics explained separately for each data
typeintheearliersections.
Summary
It was an interesting chapter with important content to learn, right? In this
chapter, we understood the significance of data types in MySQL. We saw
differentcategoriesinwhichMySQLdatatypesareclassified.Welearnedand
understoodthecharacteristicsandspecificationsofeachdatatypeindepth.We
also learned MySQL data manipulation functions and understood some of the
MySQL settings and modes. In the later section of the chapter, we learned
storage requirements of data types. Finally, we learned general guidelines for
choosingtherightdatatypes.
Moving on to next chapter, we will learn MySQL database management. The
chapter will focus on server administration, understanding the basic building
blocksoftheMySQL
server,suchasthedatadictionary,systemdatabase,andsoon.Thechapterwill
explain how we can run multiple server instances on a single machine and
MySQLrolesandpermissions.
MySQL8DatabaseManagement
In the previous chapter, we learned about MySQL 8 data types, explaining in
detail which data types are available and how they are categorized. There are
various properties associated with each of these data types, and the storage
capacityvarieswitheachtype.Thepreviouschapteralsoprovidedyouwithan
in-depthunderstandingofMySQL
8 data types. Now its time to get some practical knowledge on MySQL 8
administrativefeatures.Isn'titinterestingtoknowmoreabouttheadministrative
featuresofMySQL
8, how configuration will be done for it, and much more? It's extremely
important for an administrator to have detailed knowledge on how MySQL 8
worksforglobalization,howlogsaremaintained,andhowtoenhancecapability
oftheserver.Now,let'sstartwithsomefundamentalconcepts.
Wewillcoverthefollowtopicsinthischapter:
MySQL8serveradministration
Datadirectory
Thesystemdatabase
Runningmultipleinstancesonasinglemachine
Componentsandpluginmanagement
Rolesandpermissions
Cachingtechniques
Globalization
MySQL8serverlogs
MySQL8serveradministration
TherearemanyoperatingparametersthatavailablewithMySQL8,andamong
them all the required parameters are set by default during the installation
process. After installation, you are allowed to change the option file by
removing or adding a comment sign (#) at the start of the line of a specific
parametersetting.Theuserisalsoallowedtosetparametersatruntimebyusing
commandlineargumentsortheoptionfile.
<strong>mysqld--help</strong>
<strong>mysqld–verbose--help</strong>
ServerSystemvariable:TheMySQLservermanagesmany
systemvariables.MySQLprovidesthedefaultvalueforeach
systemvariable.Systemvariablescanbesetusingthecommand
lineorcanbedefinedintheoptionfile.MySQL8hasthe
flexibilitytochangethesevariablesatruntimewithoutserverstart
orstop.Formoredetailsreferto:
https://dev.mysql.com/doc/refman/8.0/en/server-system-
variables.html.
Serverstatusvariable:TheMySQLserverusesmanystatus
variablestoprovideinformationaboutitsoperation.Formore
detailsreferto:https://dev.mysql.com/doc/refman/8.0/en/server-
status-variables.html.
ServerSQLmodes
MySQL 8 provides different modes that will affect MySQL support and data
validation checks. This option makes it easier for the user to use MySQL in
differentenvironments.
TosetdifferentmodesMySQLprovidesthesql_modesystemvariablewhichcan
besetateitheraglobalorsessionlevel.Refertothefollowingpointsindetailto
understandmodes:
<strong>SETGLOBALsql_mode='modes';</strong><br/>
<strong>SETSESSIONsql_mode='modes';</strong>
<strong>SELECT@@GLOBAL.sql_mode;</strong><br/>
<strong>SELECT@@SESSION.sql_mode;</strong>
TheavailableSQLmodes
ThissectiondescribesalltheavailableSQLmodes.Outofthem,thefirstthree
are
themostimportantSQLmodes:
ANSI:Thismodeisusedtochangesyntaxandbehavior,bymakingitcloser
tostandardSQL.
STRICT_TRANS_TABLES:Asthenameimplies,thismodeisrelatedtotransaction
anditismainlyusedfortransactionalstorageengines.Whenthismodeis
enablefornontransactionaltables,MySQL8willconvertinvalidvaluesto
theclosestvalidvalueandinserttheadjustedvalueintothecolumn.Ifthe
valueismissing,thenMySQL8willinsertanimplicitdefaultvaluerelated
tothe column'sdata type.In thiscase,MySQL8 willgenerateawarning
message instead of an error message, and continue with the statement
executionwithoutbreaking it.In thecaseof transactionaltables,however,
MySQL8givesanerrorandwillbreaksexecution.
TRADITIONAL: This mode generally behaves like traditional SQL database
system.Itindicatesgiveerrorinsteadofawarningwhenanincorrectvalue
insertedintothecolumn.
ALLOW_INVALID_DATES: This mode checks only the month range and the date
rangeofthedatevalue.Inotherwords,themonthrangemustbebetween1
to12anddaterangemustbebetween1to31.Thismodeisapplicablefor
DATEandDATETIMEdatatypesandnotfortimestampdatatype.
ANSI_QUOTES:Usedtoconsider" asanidentifierquotecharacter insteadofa
stringquotecharacter.Whenthismodeisenabled,youcannotusedouble
quotationtoquotestringliteral.
ERROR_FOR_DIVISION_BY_ZERO:Usedtohandlethecaseofdivision byzero. This
modeoutputalsodependsonstrictSQLmodestatus:
Ifthismodeisnotenabled,divisionbyzeroinsertsNULLandproduces
nowarning.
If this mode is enabled, division by zero inserts NULL and produces a
warning.
Ifthismodeandstrictmodeareenabled,divisionbyzeroproducesan
error,unlessIGNOREisgivenaswell.ForINSERTIGNOREandUPDATE IGNORE,
divisionbyzeroinsertsNULLandproducesawarning.
HIGH_NOT_PRECEDENCE: This mode is used to set a high precedence for the NOT
operator. For example, when the mode is enabled the expression NOT a
BETWEENb AND cisparsedasNOT(aBETWEEN bAND c)insteadof(NOT a) BETWEEN b
ANDc.
IGNORE_SPACE:Thismodeappliestobuilt-infunctionsratherthanuserdefined
functionsorstoredprocedures.
NO_AUTO_CREATE_USER: This mode is used to prevent GRANT statements by
automaticallycreatingnewuseraccountsunlessauthenticationinformation
isspecified.
NO_AUTO_VALUE_ON_ZERO:Thismodeisusedforautoincrementalcolumns.When
0isfound MySQLcreatesanewsequence numberfor thefield,and that
willcreateproblemswhenyouareloadingdump.Enablethismodebefore
reloadingdumptoresolvethisproblem.
NO_BACKSLASH_ESCAPES:Ifthismodeisenabled,backslashbecomesanordinary
character.
NO_DIR_IN_CREATE:Thisoptionisusefulforslavereplicationserverswherethe
INDEXDIRECTORYandDATADIRECTORYdirectivesareignoredontablecreation.
NO_ENGINE_SUBSTITUTION: Used to provide substitution of the default storage
engine.Whenthis modeisenabled andthedesired engineis unavailable,
MySQLgivesanerrorandatableisnotcreated.
NO_FIELD_OPTIONS:Thisindicates,don'tprintMySQLspecificcolumnoptions
intheoutputofSHOW_CREATE_TABLE.
NO_KEY_OPTIONS: This indicates, don't print MySQL specific index options in
theoutputofSHOW_CREATE_TABLE.
NO_TABLE_OPTIONS:Thisindicates,don'tprintMySQLspecifictableoptionsin
theoutputofSHOW_CREATE_TABLE.
NO_UNSIGNED_SUBTRACTION: When this mode is enabled, it makes sure that
subtractionresultmustbeasignedvalueeventhoughanyoftheoperandis
unsigned.
NO_ZERO_DATE:Theeffectofthismodedependsonthestrictmodeasdefined
below:
If it is not enabled, 0000-00-00 is allowed and MySQL produces no
warningoninsertion
Ifthismodeisenabled,0000-00-00isallowedandMySQLrecordsa
warning
If both this mode and strict mode are enabled, 0000-00-00 is not
allowedandMySQL
producesanerroroninsertion
NO_ZERO_IN_DATE: This mode effect is also depending on the strict mode as
definedbelow:
If it is not enabled, dates with zero parts are allowed and MySQL
producesnowarningoninsertion
Ifthismodeisenabled,dateswithzeropartsareallowedandproduce
awarning
Ifthismodeandstrictmodeareenabled,dateswithzeropartsarenot
allowedandMySQLproducesanerror
ONLY_FULL_GROUP_BY: If this mode is enabled, MySQL will reject queries in
which select list, order by list, and the HAVING condition refer to non
aggregatedcolumns.
PAD_CHAR_TO_FULL_LENGTH:Thismodeisappliedonthecolumnwhosedatatype
issetasCHAR.Whenthismodeisenabled,MySQLretrievescolumnvalues
bypaddingtotheirfulllength.
PIPES_AS_CONCAT:Whenthismodeissetasenabled||willbeconsideredasa
stringconcatenationoperatorinsteadofOR.
REAL_AS_FLOAT:Bydefault,MySQL8willconsiderREALasasynonymofDOUBLE,
but when this flag is enabled MySQL will consider REAL as a synonym of
FLOAT.
STRICT_ALL_TABLES:Inthismodeinvaliddatavaluesarerejected.
TIME_TRUNCATE_FRACTIONAL:ThismodeindicatesiftruncationisallowedonTIME,
DATE, and TIMESTAMP columns or not. The default behavior is to perform
roundingonthevaluesinsteadoftruncation.
CombinationSQLmodes
MySQL8alsoprovidessomespecialmodesascombinationsofmodevalues:
ANSI: It includes the effects of the REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES,
IGNORE_SPACE,andONLY_FULL_GROUP_BYmodes.
DB2: It includes the effects of the PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE,
NO_KEY_OPTIONS,NO_TABLE_OPTIONS,andNO_FIELD_OPTIONSmodes.
MAXDB: It includes the effects of PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE,
NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,andNO_AUTO_CREATE_USER.
MSSQL: It includes the effects of PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE,
NO_KEY_OPTIONS,NO_TABLE_OPTIONS,andNO_FIELD_OPTIONS.
MYSQL323:ItincludestheeffectsoftheMYSQL323andHIGH_NOT_PRECEDENCEmodes.
MYSQL40:ItincludestheeffectsoftheMYSQL40andHIGH_NOT_PRECEDENCEmodes.
ORACLE: It includes the effects of the PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE,
NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,andNO_AUTO_CREATE_USERmodes.
POSTGRESQL:ItincludestheeffectofthePIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,
NO_KEY_OPTIONS,NO_TABLE_OPTIONS,andNO_FIELD_OPTIONSmodes.
TRADITIONAL:It includestheeffectsofthe STRICT_TRANS_TABLES, STRICT_ALL_TABLES,
NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER and
NO_ENGINE_SUBSTITUTIONmodes.
<strong>ALTERTABLE</strong><br/><strong>CREATE
TABLE</strong><br/><strong>CREATETABLE...
SELECT</strong><br/><strong>DELETE(bothsingletableand
multipletable)</strong><br/><strong>INSERT</strong><br/>
<strong>LOADDATA</strong><br/><strong>LOAD
XML</strong><br/><strong>SELECTSLEEP()</strong><br/>
<strong>UPDATE(bothsingletableandmultipletable)</strong>
Youcangoto:https://dev.mysql.com/doc/refman/8.0/en/sql-
mode.htmlforadetailedlistoftheerrorsassociatedwithstrictSQL
modeinMySQL.
TheIGNOREkeyword
MySQL providesanIGNORE keyword which is optional for statement execution.
TheIGNORE keyword is used to downgrade errors to warnings and applicable to
severalstatements.
Formultiplerowstatements,theIGNOREkeywordallowsyoutoskiptheparticular
row,insteadofaborting.ThefollowingstatementssupporttheIGNOREkeyword:
CREATE TABLE ... SELECT: Individual CREATE and SELECT statements do not have
support on this keyword, but when we insert into the table using SELECT
statement, rows that duplicate an existing row on a unique key value are
discarded.
DELETE:IfthisstatementexecuteswiththeIGNOREoptionMySQLavoiderrors
occurredduringexecution.
INSERT: Duplicate values in unique key and data conversion issues will be
handled by this keyword during row insertion. MySQL will insert the
closestpossiblevaluesintothecolumnandignoretheerror.
LOADDATAandLOADXML:Atthetimeofloadingdataifduplicationisfoundthe
statementwilldiscarditandcontinueinsertionfortheremainingdataifthe
IGNOREkeywordisdefined.
UPDATE: In cases of duplicate key conflict on unique key during statement
execution,MySQL
willupdatethecolumnwiththeclosestidentifiedvalues.
TheIGNOREkeywordalsoappliesonsomespecificerrors,listedhere:
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html.
IPv6support
MySQL8providessupportforIPv6,withthefollowingcapabilities:
MySQL server will accept TCP/IP connections from clients with IPv6
connectivity
MySQL 8 account names permit IPv6 addresses, which enables DBA to
specifyprivileges
fortheclientsthatareconnectedwithserver,usingIPv6
The IPv6 functions enable conversions between string and internal IPv6
addressformats,
andcheckingwhetherthevaluesrepresentavalidIPv6addressornot
<strong>mysql-urootmysql<fill_help_tables.sql</strong>
Atthetimeofinstallationprocesscontentinitializationoccurs.Incase
ofupgradingitwillbeperformso;executetheabovecommand
manually.
Theservershutdownprocess
Theservershutdownprocessperformsthefollowingsteps:
1. Theshutdownprocessisinitiated:Thereareseveralwaystoinitializethe
shutdown process. Execute the mysqladmin shutdown command which can be
executedonanyplatform.Therearesomesystemspecificwaystoinitialize
the shutdown process; for example, Unix based systems will start to shut
down when it receives a SIGTERM signal. In the same way, Window
basedsystemswillstarttoshutdownwhentheservicemanagertellsthem
to.
2. The server creates a shutdown thread if necessary: Based on the
shutdowninitializationprocess,theserverwilldecidetocreatenewthread
or not. If it is requested by the client, a new thread will be created. If a
signalisreceived,thentheservermightcreateathreadoritmighthandleit
by itself. If the server tries to create a separate thread for the shutdown
processandanerroroccurs,thenitproducesthefollowingmessageinthe
errorlog:
Error:Can'tcreatethreadtokillserver
3. Theserverstopsacceptingnewconnections:Whentheshutdownactivity
isinitiated,theserverwillstopacceptingnewconnectionrequests,usinga
handlerof networkinterfaces.TheserverwillbeusingWindowsfeatures
suchasnamedpipe,TCP/IPport,theUnixsocketfile,andsharedmemory
onWindowsinordertolistentonewconnectionrequests.
4. The server terminates current activity: Once the shut down process is
initialized,theserver will startto break theconnectionwith the client.In
the normal scenario, the connection threads will die quickly, but the ones
whichareworkingorareinanongoingactivitystagewilltakealongtime
todie.Soifathreadisexecutingopentransactionsandifitgetsrollbackin
themiddleofexecutionthentheusermightgetonlypartiallyupdateddata.
Ontheotherhand,ifthethreadisworkingonatransaction,thentheserver
willwaituntilthetransactioniscompleted.Also,theusercanterminatethe
ongoingtransactionbyexecutingtheKILLQUERYorKILLCONNECTIONstatements.
5. Theservershutsdownorclosesstorageengines:Inthisphase,theserver
flushes the cache and closes all the open tables. Here, the storage engine
performsalltheactionsnecessaryfortables.InnoDBflushesitsbufferpool,
writesthecurrentLSNintotablespaceandterminatesitsthread.TheMyISAM
flushesthependingindex.
6. Theserverexits:Inthisphase,theserverwillprovideoneofthefollowing
valuestothemanagementprocesses:
0=successfultermination(norestartdone)
1=unsuccessfultermination(norestartdone)
2=unsuccessfultermination(restartdone)
Datadirectory
ThedatadirectoryistheplacewhereMySQL8storesalltheinformationthatis
managedbyitself.Eachsub-directoryofthedatadirectoryrepresentsadatabase
directory and its related data. All the MySQL installations have the following
standarddatabases:
Thesysdirectory: This represents the sys schema, which contains the
objectsusefulforthePerformanceSchemainformationinterpretation.
Theperformance schemadirectory: This directory is used to observe the
internalexecutionoftheMySQLserveratrun-time.
Themysqldirectory: This directory is related to the MySQL system
database,whichcontainsthedatadictionarytableandthesystemtables.It
contains the information that is required by the MySQL server once it is
running.
Thesystemdatabase
The system database mainly contains the data dictionary tables that stores the
object'smetadataandsystemtablesforotheroperationalpurposes.Thesystem
databasecontainsanumberofsystemtables.Wewilllearnmoreaboutthemin
thecomingsections.
Datadictionarytables
The data dictionary tables contains the metadata about data objects. Tables of
this directory are invisible and are not read by general SQL queries such
asSELECT,SHOWTABLES,INFORMATION_SCHEMA.TABLES,andsoon.MySQLmainlyexposes
themetadatausingtheINFORMATION_SCHEMAoption.
Grantsystemtables
These tables are used to manage and provide grant information of users,
database and relevant privileges. MySQL 8 uses grant tables as transactional
tables,notnontransactional(MyISAM,forexample)tables,soalltheoperationson
the transaction are either completed or failed; no partial case will be made
possible.
Objectinformationsystemtables
These tables contains information related to the stored programs, components
andserver-sideplugins.Thefollowingmaintablesareusedtostoreinformation:
Component:Worksasaregistryfortheserver.TheMySQL8serverloads
allthecomponentslistedbythistableonserverstartup.
Func: This table contains information related to all the user-defined
functions (UDF). MySQL 8 will load all the UDFs listed in this table
duringserverstartup.
Plugin: Contains the information related to the server-side plugins. The
MySQL8serverloadsalltheavailablepluginsduringstartup.
Logsystemtables
Thesetablesareusefulforloggingandusingcsvstorageengines.Forexample,
thefunctionsgeneral_logandslow_log.
The server-side help system
tables
These tables are useful to store help information. The following tables are
availableinthiscategory:
help_category:Providesinformationaboutthehelpcategories
help_keyword:Provideskeywordsassociatedwithhelptopics
help_relation:Helpsinmappingsbetweenhelpkeywordsandtopics
help_topic:Helptopiccontents
Timezonesystemtables
Thesetablesareusefultostoretimezoneinformation.Thefollowingtablesare
availableinthiscategory:
time_zone:ProvidesthetimezoneIDsandwhethertheyuseleapseconds
time_zone_leap_second:Willcomeinhandywhenleapsecondsoccur
time_zone_name:HelpsinmappingsbetweentimezoneIDsandnames
time_zone_transitionandtime_zone_transition_type:Timezonedescriptions
Replicationsystemtables
These tables are useful to support the replication feature. It helps to store
replication related information when it is configured to as mentioned in
followingtables.Thefollowingtablesareavailableinthiscategory:
gtid_executed:UsedforcreatingthetableforstoringGTIDvalues
ndb_binlog_index: Provides the binary log information for MySQL Cluster
replication
slave_master_info, slave_relay_log_info and slave_worker_info: Used to store
replicationinformationonslaveservers
Optimizersystemtables
This tables are useful for optimizer. The following tables are available in this
category:
innodb_index_statsandinnodb_table_stats:UsedforgettingtheInnoDBpersistent
optimizerstatistics
server_cost: Contains the optimizer cost estimates for general server
operations.
engine_cost: Contains the estimates for operations specific to particular
storageengines
Other miscellaneous system
tables
Tables that don't fall into the above-mentioned categories fall under this
category.
Thefollowingtablesareavailableinthiscategory:
servers:UsedbytheFEDERATEDstorageengine
innodb_dynamic_metadata: Used by the InnoDB storage engine to store fast
changing table metadata such as auto-increment counter values and index
treecorruptionflags
Youcanlearnmoreaboutthedifferentsystemtablesat:https://dev.
mysql.com/doc/refman/8.0/en/system-database.html.
Running multiple instances on a
singlemachine
There might be some situations where you are required to install multiple
instances on a single machine. It may be to check the performance of two
differentversions,orperhapsthereisaneedtomanagetwoseparatedatabases
ondifferentMySQLinstances.
The reason can be anything, but MySQL allows user to execute multiple
instances on the same machine by providing different configuration values.
MySQL8allowsuserstoconfigureparametersbymakinguseofthecommand
line,optionfile,orbysettingenvironmentvariables.Theprimaryresourceused
by MySQL 8 for this is the data directory and it must be unique for the two
instances. We can define the value for the same using the --datadir=dir_name
function.Apartfromthedatadirectory,wewillalsoconfigureuniquevaluesfor
thefollowingoptionsaswell:
--port=port_num
--socket={file_name|pipe_name}
--shared-memory-base-name=name
--pid-file=file_name
--general_log_file=file_name
--log-bin[=file_name]
--slow_query_log_file=file_name
--log-error[=file_name]
--tmpdir=dir_name
Setting up multiple data
directories
As described above, each of the MySQL instances must have a separate data
directory.
Theuserisallowedtodefineseparatedirectoriesusingthefollowingmethods:
Create a new data directory: In this method we must follow the same
procedure which was defined in Chapter 2, Installing and Upgrading
MySQL. For Microsoft Windows, when we install MySQL 8 from Zip
archives,copyitsdatadirectorytothelocationwhereyouwanttosetupthe
newinstance.InthecaseofanMSIpackagealongwiththedatadirectory,
create a pristine template data directory named data under the installation
directory.Oncetheinstallationiscomplete,copythedatadirectorytosetup
additionalinstances.
Copyanexistingdatadirectory:Inthismethod,wewillcopyanexisting
instance's data directory to the new instance's data directory. To copy an
existingdirectory,performthefollowingsteps:
1. StoptheexistingMySQLinstance.Makesureit'scleanlyshutdownso
thatnopendingchangesareavailableinthedisk.
2. Copythedatadirectorytothenewlocation.
3. Copythemy.cnformy.inioptionfileusedbytheexistinginstancetothe
newlocation.
4. Modify the new option as per the new instance. Make sure all the
uniqueconfigurationsaredoneproperly.
5. Startthenewinstancewiththenewoptionfile.
<strong>[mysqld]</strong><br/><strong>basedir=C:/mysql-
5.5.5</strong><br/><strong>port=3307</strong><br/><strong>
enable-named-pipe</strong><br/><strong>socket=
mypipe1</strong>
<strong>[mysqld]</strong><br/><strong>basedir=C:/mysql-
8.0.1</strong><br/><strong>port=3308</strong><br/><strong>
enable-named-pipe</strong><br/><strong>socket=
mypipe2</strong>
<strong>C:\>C:\mysql-5.5.5\bin\mysqld--installmysqld1--<br/>
defaults-file=C:\my-opts1.cnf</strong><br/><strong>C:\>C:\mysql-
8.0.1\bin\mysqld--installmysqld2--<br/>defaults-file=C:\my-
opts2.cnf</strong>
<strong>C:\>C:\mysql-5.5.9\bin\mysqld--installmysqld1</strong>
<br/><strong>C:\>C:\mysql-8.0.4\bin\mysqld--install
mysqld2</strong>
<strong>C:\>NETSTARTmysqld1</strong><br/><strong>C:\>
NETSTARTmysqld2</strong>
<strong>SELECT*FROMmysql.component;</strong>
MySQL8serverplugins
MySQL 8 server has a plugin API that enables the creation of server
components. With MySQL 8, you have the flexibility of installing a plugin at
runtimeoratstartup.
InthefollowingtopicswewilllearnaboutthelifecycleoftheMySQL8server
plugins.
Installingtheplugins
Theloadingoftheplugins varieswith theirtypesand characteristics.Togeta
clearerpictureofthis,let'sgothoughthefollowing:
Built-in plugins: The server knows about the built-in plugins and loads
themautomatically,onstartup.
Theuserisallowedtochangethestateofpluginsbyanyoftheiractivation
statuses,whichwillbediscussedinthefollowingsection.
Pluginsregisteredin themysql.pluginsystemtable: On startup MySQL 8
serverwillloadallthepluginswhichareregisteredinthemysql.plugintable.
Iftheserverisstartedwiththe--skip-grant-tablesoption,theserverwillnot
loadthepluginslistedthere.
Plugins named with command-line options: MySQL 8 provides the --
plugin-load, --plugin-load-add, and --early-plugin-load options for loading
plugins with the command line. The --plugin-load and --plugin-load-add
options load the plugins on server startup after the built-in plugins are
installed.
But, we can use the --early-plugin-load option to load the plugins, prior to
initializationofbuilt-inpluginsandstorageengines.
Plugins installed with the INSTALL PLUGIN statement: This is a permanent
pluginregistrationoption,whichwillregistertheplugininformationinthe
mysql.plugin table. It will also load all the plugins available in the plugin
library.
Activateplugin
To control the state (like the activation or deactivation) of plugins, MySQL 8
providesthefollowingoptions:
--plugin_name=OFF: Disables the named plugin. Some of the built-in plugins,
suchastheasmysql_native_passwordplugin,arenotaffectedbythiscommand.
--plugin_name[=ON]: This command enables the specified plugin. If plugin
initialization failed during startup MySQL 8 will start with the plugin
disabled.
--plugin_name=FORCE:Thisisthesameastheabovecommand,excepttheserver
doesnotstart.Thismeansthatitforcestheservertostartwiththepluginif
itismentionedonstartup.
--plugin_name=FORCE_PLUS_PERMANENT: The same as the FORCE option, but
additionallypreventsthepluginfrombeingunloadedatruntime.
Uninstallplugin
MySQL 8 uses the UNINSTALL PLUGIN statement to uninstall the plugin, without
considering whether it was installed during the runtime or at startup. But this
statementwillnotallowustouninstallthebuilt-inpluginsandthepluginsthat
wereinstalledbythe--plugin_name=FORCE_PLUS_PERMANENToption.Thisstatementjust
unloads the plugin and removes it from the mysql.plugin table, so it requires
additionaldeleteprivilegesonthemysql.plugintable.
<strong>SELECT*FROMinformation_schema.PLUGINS;
</strong>
<strong>SHOWPLUGINS;</strong>
Themysql.plugintablecontainsdetailsregardingalltheplugins
whichwereregisteredbytheINSTALLPLUGINfunction.
Cachingtechniques
Cache is a mechanism used to improve performance. MySQL uses several
strategiestocacheinformationinthebuffer.MySQL8makeuseofthecacheat
the storage engine level to handle its operations. It also applies the cache in
preparedstatementsandstoredprogramstoimproveperformance.MySQL8has
introduced various system level variables to manage cache, such as
binlog_stmt_cache_size, daemon_memcached_enable_binlog, daemon_memcached_w_batch_size,
host_cache_size, and many more. We will cover caching in detail in Chapter 12,
OptimizingMySQL8.
Globalization
Globalization is a feature which provides multi-language support for an
application, such as enabling the use of native languages. It is much easier to
understandmessagesinourownnativelanguagethanotherlanguages,right?To
achievethis,globalizationcomesintothepicture.Usingglobalizationausercan
store,retrieveandupdatedataintomanylanguages.Therearecertainparameters
thataretobeconsideredinglobalization.Wewilldiscussthemindetailinthe
followingsections.
Charactersets
Beforegoingintodetailaboutcharactersetsitisrequiredtounderstandwhata
charactersetactuallyis,aswellasitsrelatedterms,right?Let'sstartwiththe
termitself;thecharactersetisasetofsymbolsandencoding.Anotherimportant
term related to character set is collation, the set of rules used for comparing
characters.Let'stakeasimpleexampletounderstand
thecharactersetsandcollation.Considertwoalphabets,PandQ,andassigna
numbertoeach,sothatP=1andQ=2.Now,assumePisasymboland1isits
encoding.Here,thecombinationofboththelettersand
theirencodingisknownasthecharacterset.Nowsuppose,wewanttocompare
these
values; the simplest way is by referring the encoding values. With this as 1 is
less
than 2 we can say P is less than Q which is known as collation. This is the
simplestexampletounderstandcharacter
sets and collation, but in real life we have many characters, including special
characters,
andinthesamewaycollationshavemanyrules.
<strong>mysql>showcharacterset;</strong><br/><strong>+---------
-+---------------------------------+---------------------+--------+</strong>
<br/><strong>|Charset|Description|Defaultcollation|Maxlen|
</strong><br/><strong>+----------+---------------------------------+------
---------------+--------+</strong><br/><strong>|armscii8|ARMSCII-
8Armenian|armscii8_general_ci|1|</strong><br/><strong>|ascii|
USASCII|ascii_general_ci|1|</strong><br/><strong>|big5|Big5
TraditionalChinese|big5_chinese_ci|2|.........</strong><br/>
<strong>.........</strong><br/><strong>+----------+-----------------------
----------+---------------------+--------+</strong><br/><strong>41rows
inset(0.01sec)</strong>
<strong>mysql>SHOWCOLLATIONWHERECharset='ascii';
</strong><br/><strong>+------------------+---------+----+---------+------
----+---------+---------------+</strong><br/><strong>|Collation|
Charset|Id|Default|Compiled|Sortlen|Pad_attribute|</strong>
<br/><strong>+------------------+---------+----+---------+----------+------
---+---------------+</strong><br/><strong>|ascii_bin|ascii|65||Yes
|1|PADSPACE|</strong><br/><strong>|ascii_general_ci|ascii|
11|Yes|Yes|1|PADSPACE|</strong><br/><strong>+--------------
----+---------+----+---------+----------+---------+---------------+</strong>
<br/><strong>2rowsinset(0.00sec)</strong>
<strong>CREATETABLEemployee(</strong><br/><strong>
firstnameCHAR(10)CHARACTERSETlatin1,</strong><br/>
<strong>lastnameCHAR(10)CHARACTERSETascii</strong><br
/><strong>);</strong><br/><br/><strong>INSERTINTOemployee
VALUES('Mona','Singh');</strong><br/><br/><strong>select
concat(firstname,lastname)fromemployee;</strong><br/>
<strong>+----------------------------+</strong><br/><strong>|
concat(firstname,lastname)|</strong><br/><strong>+-------------------
---------+</strong><br/><strong>|MonaSingh|</strong><br/>
<strong>+----------------------------+</strong><br/><strong>1rowin
set(0.00sec)</strong>
UTF-8formetadata:Metadatameansthedataaboutthedata.In
termsofdatabasewecansaythatanythingthatdescribes
databaseobjectsisknownasmetadata.Forexample:column
names,usernames,andmanymore.MySQLfollowsthebelow
tworulesformetadata:
Includeallcharactersinallthelanguagesformetadata;this
enablesausertousehisownlanguageforcolumnnameand
tablename.
Manageonecommoncharactersetforallmetadata.
Otherwise,theSHOWandSELECTstatementsfortablesin
INFORMATION_SCHEMAwillnotworkproperly.
TofollowtheaboverulesMySQL8storesmetadataintotheUnicode
format.ConsiderthatMySQLfunctionssuchasUSER(),
CURRENT_USER(),SESSION_USER(),SYSTEM_USER(),DATABASE(),and
VERSION()havetheUTF-8charactersetbydefault.MySQL8server
hasdefinedcharacter_set_systemtospecifycharactersetsfor
metadata.MakesurethatthestorageofmetadatainUnicodedoesnot
meanthatcolumnheadersandtheDESCRIBEfunctionwillreturn
valuesintheformofthemetadatacharacterset.Itworksasperthe
character_set_resultssystemvariable.
Addingthecharacterset
ThissectiondescribeshowtoaddcharactersetsinMySQL8.Thismethodmay
varybasedonthecharactersettype-itmightbesimpleorcomplexdepending
onthecharactertype.Thefollowingfourstepsarerequiredforaddingcharacter
setsintoMySQL8:
1. Add a <charset> element for MYSET to the sql/share/charsets/Index.xml file. For
thesyntax,referthealreadydefinedfilefortheothercharacterset.
2. Inthisstep,theprocessisdifferentforsimpleandcomplexcharactersets.
For simple character sets, create a configuration file, MYSET.xml, in the
sql/share/charsets directory to describe the character set properties. In the
caseofcomplexcharactersets,theCsourcefileisrequired.Forexample,
create the ctype-MYSET.c type in the strings directory. For each <collation>
element,providectype-MYSET.cfile.
3. Modifytheconfigurationinformation:
1. Editmysys/charset-def.c,andregisterthecollationsforthenewcharacter
set.Addtheselinestothedeclarationsection:
#ifdefHAVE_CHARSET_MYSET
externCHARSET_INFOmy_charset_MYSET_general_ci;
externCHARSET_INFOmy_charset_MYSET_bin;
#endif
Add these lines to the registration section: #ifdef
HAVE_CHARSET_MYSET
add_compiled_collation(&my_charset_MYSET_general_ci);
add_compiled_collation(&my_charset_MYSET_bin);
#endif
2. Ifthecharactersetusesctype-MYSET.c,editstrings/CMakeLists.txtandadd
ctype-MYSET.ctothedefinitionoftheSTRINGS_SOURCESvariable.
3. Editcmake/character_sets.cmakewiththefollowingchanges:
AddMYSETtothevalueofwithCHARSETS_AVAILABLEinalphabeticorder.
AddMYSETtothevalueofCHARSETS_COMPLEXinalphabeticorder.This
is needed even for simple character sets, or CMake will not
recognizeDDEFAULT_CHARSET=MYSET.
4. Reconfigure,recompile,andtest.
Configuringthecharactersets
MySQL 8 provides the --character-set-server and --collation-server options to
configurethecharactersets.Thedefaultcharactersethasbeenchanged
fromlatin1toUTF8.UTF8isthedominatingcharacter set,thoughithadn'tbeen a
defaultoneinpriorversions
ofMySQL.Withthesechangesgloballyaccepted,charactersetsandcollations
arenowbasedonUTF8;oneofthecommonreasonsisbecausetherearearound
21differentlanguagessupported
byUTF8,whichmakessystemsprovidemultilingualsupport.Beforeconfiguring
collation,
refertothecollationlistavailableathttps://dev.mysql.com/doc/refman/8.0/en/show-coll
ation.html.
<strong>SETlc_messages='fr_FR';</strong>
<strong>mysqld--lc_messages_dir=/usr/share/mysql--
lc_messages=nl_NL</strong>
IfthemessagefiledoesnotexistunderthedirectorythenMySQL
8willignorethevalueofthelc_messagesvariableandconsider
thevalueofthelc_messages_dirvariableasalocationinwhich
tolook.
IftheMySQL8serverdoesnotfindthemessagefile,thenit
showsamessageintheerrorlogfileandusesEnglishforthe
messages.
<strong>mysql>SETGLOBALtime_zone=timezone;</strong>
<strong>mysql>SETtime_zone=timezone;</strong>
Thissessionvariableaffectsthedisplayandstorageofzonespecific
values.Forexample,valuesreturnedbytheNOW()andCURTIME()
functions.Ontheotherhand,thisvariabledoesnotaffectsvalues
whicharedisplayedandstoredinUTCformat,suchaswiththe
UTC_TIMESTAMP()function.
<strong>mysql>SETNAMES'utf8';</strong><br/><strong>Query
OK,0rowsaffected(0.09sec)</strong><br/><br/><strong>mysql>
SELECT@@lc_time_names;</strong><br/><strong>+----------------
-+</strong><br/><strong>|@@lc_time_names|</strong><br/>
<strong>+-----------------+</strong><br/><strong>|en_US|</strong>
<br/><strong>+-----------------+</strong><br/><strong>1rowinset
(0.00sec)</strong><br/><br/><strong>mysql>SELECT
DAYNAME('2010-01-01'),MONTHNAME('2010-01-01');</strong>
<br/><strong>+-----------------------+-------------------------+</strong>
<br/><strong>|DAYNAME('2010-01-01')|MONTHNAME('2010-
01-01')|</strong><br/><strong>+-----------------------+------------------
-------+</strong><br/><strong>|Friday|January|</strong><br/>
<strong>+-----------------------+-------------------------+</strong><br/>
<strong>1rowinset(0.00sec)</strong><br/><br/><strong>mysql>
SELECTDATE_FORMAT('2010-01-01','%W%a%M%b');
</strong><br/><strong>+-----------------------------------------+
</strong><br/><strong>|DATE_FORMAT('2010-01-01','%W%a
%M%b')|</strong><br/><strong>+----------------------------------------
-+</strong><br/><strong>|FridayFriJanuaryJan|</strong><br/>
<strong>+-----------------------------------------+</strong><br/>
<strong>1rowinset(0.00sec)</strong><br/><br/><strong>mysql>
SETlc_time_names='nl_NL';</strong><br/><strong>QueryOK,0
rowsaffected(0.00sec)</strong><br/><br/><strong>mysql>
SELECT@@lc_time_names;</strong><br/><strong>+----------------
-+</strong><br/><strong>|@@lc_time_names|</strong><br/>
<strong>+-----------------+</strong><br/><strong>|nl_NL|</strong>
<br/><strong>+-----------------+</strong><br/><strong>1rowinset
(0.00sec)</strong><br/><br/><strong>mysql>SELECT
DAYNAME('2010-01-01'),MONTHNAME('2010-01-01');</strong>
<br/><strong>+-----------------------+-------------------------+</strong>
<br/><strong>|DAYNAME('2010-01-01')|MONTHNAME('2010-
01-01')|</strong><br/><strong>+-----------------------+------------------
-------+</strong><br/><strong>|vrijdag|januari|</strong><br/>
<strong>+-----------------------+-------------------------+</strong><br/>
<strong>1rowinset(0.00sec)</strong><br/><br/><strong>mysql>
SELECTDATE_FORMAT('2010-01-01','%W%a%M%b');
</strong><br/><strong>+-----------------------------------------+
</strong><br/><strong>|DATE_FORMAT('2010-01-01','%W%a
%M%b')|</strong><br/><strong>+----------------------------------------
-+</strong><br/><strong>|vrijdagvrjanuarijan|</strong><br/>
<strong>+-----------------------------------------+</strong><br/>
<strong>1rowinset(0.00sec)</strong></strong>
<strong>SHOWCREATETABLEmysql.general_log;</strong>
<strong>SHOWCREATETABLEmysql.slow_log;</strong>
Theerrorlog
Thislogisusedtorecorddiagnosticmessageslikeerror,warningsandnotesthat
occur from the startup of MySQL 8 through till its end. MySQL 8 provides
variousconfigurationsandcomponentsforuserstogeneratelogfilesaspertheir
requirements. When we start writing into files some basics questions come to
mind;whatdo wewrite? Howdowe writeit?Wheredowe writeitto? Let's
startwithfirstquestion.MySQL8
usesthelog_error_verbositysystemvariableandassignsthebelowfilteringoptions
todecidewhattypeofmessagesshouldbewrittenintotheerrorlogfile:
ErrorOnly
ErrorsandWarnings
Errors,WarningsandNotes
TowriteatthedestinationplaceMySQLusesthebelowformatwherethetime
stamp depends on the log_timestamps system variable: timestamp thread_id
[severity]message
Afterwritinglogfiles,thefirstquestionthatcomestomindis,howdoweflush
theselogs?Forthat,MySQL8providesthreeways;FLUSHERRORLOGS,FLUSHLOGS,or
mysqladminflush-logs.Thesecommandswillcloseandreopenthelogfiletowhich
itiswriting.Whenwetalkabouthowtowriteandwheretowrite,thereareso
manythingstounderstand.
Componentconfiguration
MySQL 8 uses the log_error_services system variable to control error log
components. It allows users to define multiple components by semicolons,
separatedfortheexecution.Here,componentswillbeexecutedintheorderin
whichtheyaredefined.Theuserisallowedtochangethevaluesofthisvariable
withthefollowingconstraints:
INSTALLCOMPONENT:Toenableanylogcomponentwemustfirstinstallitusing
thiscommand,andthenusethecomponentbylistingitinlog_error_services
system variable. Follow the following commands to add the
log_sink_syseventlogcomponent:
INSTALLCOMPONENT'file://component_log_sink_syseventlog';
SETGLOBALlog_error_services='log_filter_internal;
log_sink_syseventlog';
Afterexecutionoftheinstallation commandMySQL8willregister the
component into the mysql.component system table to make it available for
loadingoneachstartup.
UNINSTALL COMPONENT: To disable any of the log components, first remove it
fromthelog_error_servicessystemvariablelistandthenuninstallitwiththis
command.Executethebelowcommandtouninstallacomponent:
UNINSTALLCOMPONENT'file://component_log_sink_syseventlog';
Toenableerrorlogcomponentsoneachstartup,defineitinthemy.cnffile
oruseSET_PERSIST.Whenwedefineitinmy.cnfittakeseffectfromthenext
restart, whereas SET_PERSIST will give an immediate effect. Use the
followingcommandforSET_PERSIST:SETPERSISTlog_error_services=
'log_filter_internal;
log_sink_internal;
log_sink_json';
MySQL8alsoallowsuserstowriteerrorlogsintosystemlogs:forMicrosoft,
considerEventlog,andforUnixbasedsystems,considersyslog.Toenableerror
loggingintosystemlogfibf,configurelog_filter_internalandthesystemlogwriter
log_sink_syseventlogcomponents andfollow thesameinstructions explainabove.
AnotherwayistowriteaJSONstringintothelogfileconfigurationlog_sink_json
component.AninterestingpointaboutaJSONwriteristhatitwillmanagefile
namingconventionsbyaddingNN(two-digitnumbers).Forexample,consider
filenamesasfile_name.00.json,file_name.01.json,andsoforth.
Default error log destination
configuration
Errorlogscanbewrittenintologfilesoronconsole.Thissectiondescribeshow
toconfigurethedestinationoferrorlogondifferentenvironments.
Default error log destination on
Windows
--console: If this is given then the console will be considered the default
destination.--consoletakesprecedenceover--log-errorin caseswhereboth
aredefined.Ifthedefaultlocationisconsole,thenMySQL8
serversetsthelog_errorvariable'svalueasstderror.
--log-error: If this is not given, or given without naming a file, then the
default file name is host_name.err and the file will be created in the data
directoryunlessthe--pid-fileoptionisspecified.Ifthefilenameisspecified
in–pid-file option, then the naming convention would be a PID file base
namewithasuffixof.errinthedatadirectory.
Default error log destination on
UnixandUnix-Likesystems
All the above mentioned scenarios in Microsoft Windows will be managed by
the–log_erroroptioninUnixsystems.
--log-error:Ifthisisnotgiventhenthedefaultdestinationistheconsole.If
nofilenameisgiven,thenaswithWindowsitwillcreateafileinthedata
directory with the host_name.err name. The user is allowed to specify –log-
errorinanoptionfileunderthemysqldormysqld_safesections.
<strong>SETGLOBALgeneral_log='OFF';</strong>
Oncethelogisdisabled,renamethelogfileandenablethelogagain
withtheONoption.Similarly,toenableordisablethelogatruntime
forparticularconnectionsusethesessionsql_log_offvariablewith
theONorOFFoption.Onemoreoptionisaligningwiththegenerallog
file,thatis,--log-output.Byusingthisoption,wecanspecifythe
destinationoflogoutput;itdoesnotmeanlogsareenabled.
Thethreefollowingdifferentoptionsareavailablewiththis
command:
TABLE:Logtotables
FILE:Logtofiles
NONE:Donotlogintotablesorfiles.NONE,ifpresent,takes
precedenceoveranyotherspecifiers.
Ifthe--log-outputoptionisomitted,thenthedefaultvalueisfile.
<strong>mysql>SETGLOBALbinlog_format='STATEMENT';
</strong><br/><strong>mysql>SETSESSIONbinlog_format=
'STATEMENT';</strong>
Therearetwoexceptionalcaseswherewecannotchangeformat:
Withinastoredprocedureorfunction
Incaseswheretherowbasedformatissetandtemporarytableis
open
MySQL8hasthe--binlog-row-event-max-sizevariabletocontrol
thesizeofthebinarylogfileintermsofbytes.Assignasavalueto
thisvariableamultipleof256;thedefaultvalueofthisoptionis8192.
IndividualstorageenginesofMySQL8havetheirowncapabilities
forlogging.Ifastorageenginesupportsrowbasedlogging,thenitis
knownasrow-loggingcapable,andifastorageenginesupports
statementbasedloggingthenitisknownasstatement-logging
capable.Refertothebelowtableformoreinformationonstorage
engineloggingcapabilities.
Storage
engine
Rowlogging
supported Statementloggingsupported
ARCHIVE Yes Yes
BLACKHOLE Yes Yes
CSV Yes Yes
EXAMPLE Yes No
FEDERATED Yes Yes
HEAP Yes Yes
InnoDB Yes Yeswhenthetransactionisolationlevelis
REPEATABLE,READ,orSERIALIZABLE;Nootherwise.
MyISAM Yes Yes
MERGE Yes Yes
NDB Yes No
Asdescribeinthissectionthebinarylogwillworkbasedontypesof
statementlikesafe,unsafe,orbinaryinjected,ontheloggingformat
suchasROW,STATEMENT,orMIXED,andwiththeloggingcapabilitiesof
storageengineslikerowcapable,statementcapable,both,orneither.
Tounderstandallthepossiblecasesofbinaryloggingrefertothe
tablegiveninthislink:
https://dev.mysql.com/doc/refman/8.0/en/binary-log-mixed.html.
Theslowquerylog
Slow query logs are used to record SQL statements that takes long time to
execute.
MySQL8hasdefinedthefollowingtwosystemvariablesfortimeconfiguration
ofslowquery:
long_query_time:Thisisusedtodefinetheidealtimeforqueryexecution.Ifa
SQL statement takes longer than this time, then it is considered a slow
queryandastatementisrecordedintothelogfile.Thedefaultvalueis10
seconds.
min_examined_row_limit:Thisistheminimumtimerequiredfortheexecutionof
eachquery.Thedefaultvalueis0seconds.
MySQL 8 will not consider the initial time of acquiring a lock into execution
timeandwillreturnslowquerylogsintoafileoncealllocksarereleasedand
queryexecutioniscompleted.WhenMySQL8isstarted,slowqueryloggingis
disabledbydefault;tostartthislogusetheslow_query_log[={0|1}]command,where
0 indicates slow query log is disabled and 1 or without argument is used to
enabled it. To log administrative statementsand queries without indexing, use
the log_slow_admin_statementsandlog_queries_not_using_indexes variables. Here,
administrativestatementsincludeALTERTABLE,ANALYZETABLE,CHECKTABLE,CREATEINDEX,
DROP INDEX,OPTIMIZE TABLE, and REPAIR TABLE. MySQL 8 allows users to specify the
nameofthelogfileusing--slow_query_log_file=file_namecommand.Ifnofilename
isspecified, thenMySQL8 willcreateafilewiththehost_name-slow.lognaming
conventioninthedatadirectory.Towriteminimalinformationintothislogfile
usethe--log-short-formatoption.
AlltheabovedescribedparametersarecontrolledbyMySQL8inthefollowing
sequence:
1. The query must either not be an administrative statement, or
log_slow_admin_statementsmustbeenabled
2. The query must have taken at least long_query_timeseconds, or
log_queries_not_using_indexes must be enabled and the query must have used
noindexesforrowlookups
3. Thequerymusthaveexaminedatleastmin_examined_row_limitrows
4. The query must not be suppressed according to the
log_throttle_queries_not_using_indexessetting
The--log-outputoptionisalsoavailableforthislogfile,andhasthe
sameimplementationandeffectasthegeneralpurposelog.
TheDDLlog
Asnameimplies,thislogfileisusedtorecordalltheDDLstatementexecution
related details. MySQL 8 uses this log file to recover from crashes that occur
duringthemetadataoperationexecution. Let'stakeone exampletounderstand
thescenarios:
Drop table t1, t2: We must be sure that both the t1 and t2 tables are
dropped
WhenweexecuteanyDDLstatement,arecordoftheseoperationsiswritteninto
theddl_log.logfileundertheMySQL8datadirectory.Thisfileisabinaryfileand
notinhumanreadableformat.Theuserisnotallowedtoupdatethecontentsof
thislogfile.
Metadata statements recording is not required in normal execution of MySQL
server;enableitonlyifitisrequired.
<strong>SETGLOBALgeneral_log='OFF';</strong>
<strong>SETGLOBALgeneral_log='ON';</strong>
Summary
ThiswasaninterestingchapterforanyMySQL8user,wasn'tit?Inthischapter
weunderstoodhowMySQL8managesdifferentlogfilesandwhichlogfileto
useatwhattime.Atthesametimewealsocoveredmanyoftheadministrative
features,suchasglobalization,systemdatadatabase,andcomponentandplugin
configuration,andexplainedhowtorunmultipleinstancesonasinglemachine.
Thelaterpartofthechaptercoveredlogmaintenance.
Moving on to the next chapter, we will provide you with information about
storage engines, such as what the different types of storage engine are, which
one to use for your application, and how to create our own custom storage
engineforMySQL8.
MySQL8StorageEngines
In the previous chapter, we learned about setting up a new system, data
dictionary,andsystemdatabase.Detailedinformationwasprovidedoncaching
techniques, globalization, different types of components, and plugin
configuration,alongwithseveraltypesoflogfileswhichareveryimportantfor
administration.
ThischaptergivesdetailedinformationonMySQL8storageengines.Itexplains
theInnoDBstorage engineanditsfeaturesindetailandalsoprovidesapractical
guideline on custom storage engine creation and how to make it pluggable so
thatitcanbeinstalledinMySQL8.Thetopicsthatwewillbecoveringinthis
chapterareasfollows:
Overviewofstorageengines
Severaltypesofstorageengines
TheInnoDBstorageengine
Creatingacustomstorageengine
Overviewofstorageengines
StorageenginesareMySQLcomponentsforhandlingtheSQLoperationsused
in different types of tables. MySQL storage engines are designed to manage
differenttypesoftasksindifferenttypesofenvironments.Itisveryimportantto
know and choose which storage engine is best suited for the system or
application requirements. In following sections, we will get to know in detail
aboutthetypesofstorageengines,thedefaultstorageengine,andthecreationof
customstorageengines.
Letusgothroughandseewhythestorageengineisaveryimportantcomponent
indatabases,includingMySQL8.Storageenginesworkwithdatabaseengines
toperformvarioustypesoftasksindifferentenvironments.Theyexecutecreate,
read,update,and deleteoperationsin the formofstatements ondatafrom the
database.ItlooksquitesimplewhenyouprovidetheENGINEparameterwiththe
create table statement but there is configuration for plentyof operations to be
doneonthedataforeachoftherequestssentviaSQLstatements.
Itismuchmorethanjustpersistingdata-theenginetakescareoffeaturessuch
as storage limits, transactions, locking granularity/level, multi-version
concurrencycontrol,geospatialdatatypes,geospatialindexing,B-treeindexes,
T-tree indexes, Hash indexes, full-text search indexes, clustered indexes, data
caches, index caches, compressed data, encrypted data, cluster databases,
replication,foreignkeys,backup, querycaches,andupdatingstatisticsforthe
datadictionary.
MySQL storage engine
architecture
The MySQL storage engine's pluggable architecture allows a database
professionalto
select any storage engine for the specialization required in any particular
application.
TheMySQLStorageenginearchitectureprovidesaneasyapplicationmodeland
APIwith
the consistency that isolates the database administrator and the application
programmer
from all the low-level implementation details underlying at the storage level.
Thus,
the application always works above different storage engines' different
capabilities.
Itprovidesstandardmanagementand supportservicesthat arecommonforall
underlying
storageengines.
Storage engines perform activities on the data that is persisted at the physical
server
level. Such modular and efficient architecture provides solutions to specific
needs
of any particular application, such as transaction processing, high availability
situations,
or data warehousing, and at the same time has the advantage of independent
interfaces
andservicesfromtheunderlyingstorageengines.
The database administrator and the application programmer interact with the
MySQL
database by Connector APIs and services on top of the storage engines. The
application
isshieldedbytheMySQLserverarchitecturefromthedetailedlevelcomplexity
of
the storage engines by providing easy to use APIs that are consistent and
applicable
onallthestorageengines.Iftheapplicationrequireschangesintheunderlying
storageengine,orifoneormorestorageenginesareaddedtosupporttheneeds
of
the application, no major coding or process changes are required to get things
working.
Severaltypesofstorageengine
Now we know the importance of storage engines and critical decisions to
identify which storage engines to use from plenty of storage engines available
for MySQL 8. Let us take a look at what is available and with which
specifications. InnoDB is the name that first entered your thoughts when you
startedthinkingofstorageengines,right?
InnoDBisthedefaultandmostgeneral-purposestorageengineinMySQL8and
itisrecommendedbyOracletousefortablesaswellasforspecialusecases.
TheMySQL
server has a pluggable storage engine architecture that enables storage engine
loadingaswellasunloadingfromthealreadyrunningMySQLserver.
To identify which storage engines your server supports is made very easy in
MySQL
8. We only have to go to the MySQL shell or prompt and use the SHOW ENGINES
statement.Hitthestatementwhenpromptedandresultwillbethelistofengines
with a few columns, such as Engine, Support, Transactions, Savepoints, and
Comment.
Values in Support column, DEFAULT, YES, and NO, indicate that a storage
engineisavailableandcurrentlysetasthedefaultstorage.
Overview of the InnoDB storage
engine
InnoDB is the default and most general-purpose storage engine in MySQL 8,
providinghighreliabilityandhighperformance.
If you have not configured a different default storage engine, then issuing the
SQL
statementCREATETABLEwithouttheENGINE = clausecreatesatablewiththestorage
engineInnoDBasthedefaultengineinMySQL8.
Thefeatures andadvantagesofferedbytheInnoDBstorageengine areexplained
laterintheTheInnoDBstorageenginesection.
Customstorageengine
storageenginearchitectureinMySQL5.1andallthelaterversionsandMySQL
8havetakenadvantageoftheflexiblestorageenginearchitecture.
Thestorageenginepluggablearchitectureprovidesthecapabilitytocreateand
addnewstorageengineswithoutrecompilationoftheserver,addingdirectlytoa
running MySQL server. The architecture makes it very easy to develop and
deploynewstorageenginestoMySQL8.
We will develop a new storage engine by using the pluggable feature of the
MySQLstorageenginearchitectureintheupcomingCreatingacustomstorage
enginesection.
Severaltypesofstorageengines
Inthissection,wewilltakeacloserlookatthewidelyusedstorageenginesthat
are supported by MySQL 8. But before checking on them, let us see how the
storage engine architecture has made it pluggable and provided flexibility to
enableusingmultiplestorageenginesinthesameschemaorserver.
ThefollowingisthelistofstorageenginessupportedinMySQL8:
InnoDB: The default storage engine for MySQL 8. It is an ACID compliant
(transaction-safe) storage engine that has commit, roll back, and crash-
recoveryforprotectingtheuserdataandreferential-integrityconstraintsto
maintaindataintegrity,andmuchmore.
MyISAM:Thestorageenginewithtableshavingasmallfootprint.Ithastable-
level locking and so is mostly used in read-only or read-mostly data
workloads,suchasindatawarehousingandwebconfigurations.
Memory:ThestorageenginepreviouslyknownastheHEAPengine.Itkeepsdata
inRAM,whichprovidesfasterdataaccess,mostlyusedinquicklookupsof
non-criticaldataenvironments.
CSV:Thestorageenginewithtablesascomma-separatedvaluesintextfiles
andtables.
Theyarenotindexedandaremostlyusedforimportinganddumpingdata
inCSVformat.
Archive:Thestorageenginecomprisescompact,unindexedtables,intended
tostoreandretrieveahugeamountofhistorical,archived,orsecurityaudit
data.
Blackhole: The storage engine with tables that can be used for replication
configuration.Aqueryalwaysreturnsanemptyset.DMLSQLstatementsare
senttoslaveservers.Itacceptsdatabutdataisnotstored,suchasinaUnix
/dev/nulldeviceuse.
Merge:Thestorageengineprovidesthecapabilitytologicallygroupaseries
ofsimilarMyISAMtablesandrefer tothemasoneobjectinsteadofseparate
table.
Federated:ThestorageenginethatcanlinkmanyseparatephysicalMySQL
servers into one logical database. It is ideal for data marts or distributed
environments.
Example: The storage engine that does nothing but works as a stub. It is
primarilyusedbythedevelopers whoillustratehow tobeginwritingnew
storageenginesintheMySQLsourcecode.
MySQL does not restrict using the same storage engine for an
entire server or schema; instead, specifying the engine at table
levelmakesitflexiblebasedonthetypeofdataandtheusecaseof
theapplication.
<strong>mysql>INSTALLPLUGINMyExampleSONAME
'MyExample.so';</strong>
<strong>mysql>UNINSTALLPLUGINMyExample;</strong>
The common database server
layer
The MySQL pluggable storage engine is responsible for executing I/O
operationsontheactualdataandalsotocatertothespecificapplicationneeds
that includes enabling and enforcing the required features whenever required.
Using a specific or single storage engine will more likely result in more
efficiency and higher database performance because the engine enables the
features only needed for a particular application, and resulting in less system
overheadonthedatabase.
A storage engine supports the following unique infrastructure components or
keys:
Concurrency: Some applications have granular lock levels (such as row-
level locks) requirements more than others. Overall performance and
overhead due to locking can be affected by choosing the right/wrong
lockingstrategyandthisalsoincludesmulti-versionconcurrencycontrolor
snapshotreadcapabilities.
Transaction support: Very well-defined requirements exist, such as ACID
complianceandmoreiftheapplicationneedstransactions.
Referentialintegrity:Theservercanenforcerelationaldatabasereferential
integrityusingDDL-definedforeignkeysifrequired..
Physicalstorage:Thisincludeseverythingfromthepagesizeoftablesand
indexesandalsoincludestheformatusedforstoringdataonaphysicaldisk
aswell.
Indexsupport:Thisincludesindexingstrategiesbasedontheapplication
needs,aseachofthestorageengineshavetheirownindexingmethods.
Memorycaches:Thecachingstrategiesbasedontheapplicationneeds,as
each of the storage engines have their own caching methods along with
commonmemorycachesacrossallthestorageengines.
Performance aids: This involves bulk insert handing, database check
pointing, multiple I/O threads for parallel operations, thread concurrency,
andmore.
Miscellaneous target features: This may includes support for security
restrictionson certaindatamanipulationoperations,geospatial operations,
andothersimilarfeatures.
Each of the preceding infrastructure components are designed to support a
specific set of features for a particular application's needs and so it is very
importanttounderstandtheapplicationrequirementverycarefullyandselectthe
right storage engine, as it may impact on the overall system efficiency and
performance.
<strong>CREATETABLEtable1(i1INT)ENGINE=INNODB;
</strong><br/><strong>CREATETABLEtable3(i3INT)ENGINE
=MEMORY;</strong><br/><strong>ALTERTABLEtable3
ENGINE=InnoDB;</strong>
<strong>SETdefault_storage_engine=MEMORY;</strong>
ThedefaultstorageengineforTEMPORARYtablesusingCREATE
TEMPORARYTABLEcanbesetseparatelybysettingthe
default_tmp_storage_enginevariableateitherstartuporruntime.
<strong>--myisam-recover-options=mode</strong>
Thisoptionwillsetthemodeintheautomaticrecoveryofcrashed
tablesinMyISAM.
SpacesneededforkeysinMyISAM,B-TreeindexesareusedbyMyISAM
tablesandspacecompressionisusedinStringindexes.Ifastringis
thefirstpartoftheindexthenprefixcompressionisalsodone,which
overallmakestheindexfilesizesmaller.Theprefixcompression
helpsifmanystringshaveasimilarprefix.Byusingthetableoption
PACK_KEYS=1inMyISAMtables,prefixcompressioncanalsobeapplied
onthenumbersiftherearemanynumberswithasimilarprefix.
PartitioningisnotsupportedforMyISAMtablesinMySQL8.0.
SomeoftheimportanttablescharacteristicsforMyISAMtablesareas
follows:
Alldatavaluesstoredhavethelowbytefirstorder,whichmakes
thedataindependentofmachineandoperatingsystems
Allnumerickeyvaluesarestoredwithhighbytefirstorder,
whichpermitsbetterindexcompression
MyISAMtableislimitedwith(232)2(1.844E+19)rows
MyISAMtableislimitedtoamaximumnumberof64indexesper
table
MyISAMtablecolumnsislimitedtoamaximumnumberof16
columnsperindex
ConcurrentinsertsaresupportedinMyISAM,ifatabledoesnot
haveanyfreeblocksinthemiddleofthedatafiles
TEXTandBLOBtypecolumnscanalsobeindexedinMyISAM
Inindexedcolumns,NULLvaluesarepermitted
Eachofthecolumnscanhaveadifferentcharacterset
ItalsosupportforatrueVARCHARtypecolumnwithastarting
lengthstoredof1or2byte,tableswithVARCHARcolumnswitha
fixedordynamicrowlength,andUNIQUEconstraintswithan
arbitrarylength
MyISAMtablestorageformats:Thefollowingthreedifferenttypes
ofstorageformatslistedaresupportedinMyISAM:
Statictable:ThedefaultformatforthetablesintheMyISAM
storageengine,withfixed-sizedcolumns
Dynamictable:Asthenamesuggests,theformatthatcontains
variablesizedcolumns,includingVARCHAR,BLOB,orTEXT
Compressedtable:Thetableformatforkeepingread-only
dataandcompressedformatsinMyISAMstorageenginetables
Thefirsttwoformats,fixedanddynamic,arechosenautomatically
basedonthecolumntypeused.Thecompressedformatcanbecreated
byusingthemyisampackutility.
MyISAMtableproblems:Thefileformathasbeenextensively
testedbutsomecircumstancesarisethatresultincorrupted
databasetables.Letuslookatsuchcircumstancesandthewayto
recoverthosetables.
Wecouldgetcorruptedtablesintheeventofanyofthefollowing
events:
Ifthemysqldprocessiskilledinthemiddleofawrite
Ifthereisanunexpectedcomputershutdown
Ifthereisanyhardwarefailure
IfatableisbeingmodifiedatthesametimebytheMySQLserver
andanexternalprogram,suchasmyisamchk
TheMySQLorMyISAMcodehasasoftwarebug
CheckthehealthofthetablewiththeCHECKTABLEstatementand
attempttorepairanycorruptedMyISAMtablebyusingtheREPAIR
TABLEstatement.
ThereisalsopossibleissueyougetwithMyISAMtablesandthatis
tablesarenotbeingclosedproperly.Inordertoidentifyifthetableis
closedproperlyornot,eachMyISAMindexfilekeepsacounterinthe
header.Thecountercanbeincorrectunderthefollowing
circumstances:
IfatableiscopiedwithoutissuingLOCKTABLESandFLUSH
TABLES
MySQLcrashedbeforethefinalcloseduringanupdate
mysqldisusingthetableandatthesametimeitismodifiedby
anotherprogram:myisamcheck--recoverormyisamchk--
update-state
TheMEMORYstorageengine
TheMEMORYstorageengine,alsopreviouslyknownastheHEAPengine,keepsdatain
RAM,whichprovidesfasterdataaccess.Itismostlyusedinquicklookupsofnon-
criticaldataenvironments.Itcreatesspecial-purposetableswithcontentsstored
inmemorybut the dataisvulnerable to crashes,poweroutages, and hardware
issues. Therefore, these tables are used in temporary work areas or possibly
usingreadonlydatathatiscachedafterthedataispulledfromothertables.
You should choose whether use MEMORY or NDB Cluster. You should check if the
applicationisrequiredforimportant,highlyavailable,orfrequentlyupdateddata
andconsiderwhetherNDBClusteristhebetterchoiceornot.NDB Clusterprovides
the same features as the MEMORY engine, but with higher performance levels and
additionalfeaturesnotprovidedbyMEMORYengine.Theseinclude:
Low contention between clients by multiple thread operations and row-
levellocking
Scalabilitywithstatementsmixes,includingwrites
Datadurability;itsupportsoptionaldisk-backedoperations
Shared-nothing architecture, providing multiple-host operations without a
singlepointoffailure,enabling99.999%availabilityfortheapplication
Automaticdatadistributionsacrossnodes
Supportforvariablelengthdatatypes,includingBLOBandTEXT
PartitioningisnotsupportedinMEMORYtables.
Performancedependsonhowbusytheserverisandtheeffectofsinglethread
executionwithtablelockoverheadduringupdatesprocessing.Thetablelocking
duringupdatesprocessingcausesaslowdownofconcurrentusagefrommultiple
sessionsonMEMORYtables.
MEMORYtablescharacteristics:TabledefinitionsarestoredontheMySQL
data dictionary and do not create any files on the disk. The following are the
tablefeaturehighlights:
100%dynamichashingforinsertsandspaceisallocatedinsmallblocks.
Noextrakeyspaceoroverflowareaorextraspaceforfreelistsisrequired.
Reuseofdeletedrowswhennewrecordsinsertedbyputtingrowsinlinked
lists.
Fixed length row-storage format, VARCHAR , is stored with fixed length.
CannotstoreBLOBorTEXTcolumns.
AUTO_INCREMENTcolumnsaresupported.
IndexinginHASHandBTREEtypesaresupportedbytheMEMORYstorageengine.MEMORY
tableshaveamaximumof64indexespertable,amaximumof16columnsper
indexandamaximumkeylengthof3,072bytes.MEMORYtablesalsocanhavenon-
uniquekeys.
User created and temporary tables: Internal temporary tables are created by
the server on the fly while processing queries. Two types of tables differ in
storageconversion,wheretheMEMORYtablesarenotsubjecttoconversion:
Whenaninternaltemporarytablebecomestoolarge,itisconvertedtoon-
diskstoragebytheserverautomatically
UsercreatedMEMORYtablesareneverconvertedbytheserver
Dataloadingcanbeperformedusingthe--init-fileoption,usingINSERT INTO ...
SELECTorLOADDATAINFILEstatementsfromanypersistencedatasourceifrequired.
TheCSVstorageengine
This storage engine stores data in the form of comma-separated values in text
files.
The engine is always compiled into the MySQL server and the source can be
examinedfromthestorage/csvdirectoryofyourMySQLdistribution.
Thedatafilecreatedbytheserverbeginswiththegiventableandtheextension
of.CSV.Thedata fileis aplaintext filecontaining datain thecomma-separate
valuesformat.
TheMySQLservercreatesacorrespondingmetafilealongwithaCSVtablethat
stores information about the state of the table and the count for the rows that
exists in the table. The metafile is also stored with the table name at the
beginningwiththe.CSMextension.
RepairingandcheckingCSVtables:ThestorageenginesupportsCHECKand
REPAIRstatementstoverifyandpossiblyrepairadamagedCSVtable.Youcan
usetheCHECKTABLEstatementtoverifyorvalidatethetableandusetheREPAIR
TABLEstatementtorepairatablethatcopiesvalidrowsfromanexistingCSV
datafileandreplacesanexistingfilewithnewlycopied/recoveredrows.
Duringrepair,onlyrowsfromtheCSVdatafiletothefirstdamaged
rowgetscopiedtothenewtableorcopieddatafile.
Therestoftherowsafterthedamagedrowgetsremovedfromthe
table,includingvalidrows,soIsuggestthatyoutakeenoughback
upofthedatafilepriortoproceedingwiththerepair.
Indexing or partitioning is not supported in the CSV storage engine and all the
tablescreatedwiththeCSVstorageenginemusthavetheNOTNULLattributeonall
thecolumns.
TheARCHIVEstorageengine
TheARCHIVEstorageenginecreatesspecial-purposetablesthatareusedforstoring
hugeamountsofunindexeddatawithaverysmallfootprint.
WhentheARCHIVEtableiscreated,itbeginswiththetablenameandendswiththe
.ARZextension.Duringoptimizationoperations,afilewithan.ARNextensionmay
appear.
The AUTO_INCREMENT column attribute is supported by the engine. It also supports
INSERT,REPLACE,SELECT,andBLOBcolumns(allbutspatialdatatypes)butitdoesnot
supportDELETE,UPDATE,ORDER,orBYoperations.
PartitioningisnotsupportedbytheARCHIVEstorageengine:
Storage:Theengineuseslosslessdatacompressionwithzlibandtherows
get compressed as inserted. It supports the CHECK TABLE operation. Several
typesofinsertionareusedintheengine:
INSERTstatementsendsrowsinto acompressionbuffer, andthebuffer
getsflushedasnecessary.
Insertioninthecompressionbufferisprotectedbythelockandflush
willonlyoccurifSELECTisrequested.
Oncecompletedabulkbuffercanbeseen.Itcanonlybeseenifany
other inserts occur at the same time. Here flush will not occur upon
SELECT,unlesswhileloadinganynormalinsert.
Retrieval:Afterretrieval,rowsgetsuncompressedasrequestedanditdoes
not use any row cache. A complete table scan is performed for the SELECT
operation:
SELECT checks how many rows are available currently and reads only
thatnumberofrows.
Itisperformedasaconsistentreadoperation.
ThenumberofrowsreportedbySHOWTABLESTATUSisalwaysaccuratefor
theARCHIVEtables.
Use OPTIMIZE TABLE or REPAIR TABLE operations to achieve better
compression.
TheBLACKHOLEstorageengine
TheBLACKHOLE storage engine acts as a black hole. It accepts data but does not
storeitandaqueryalwaysreturnsanemptyresult.
Theserveronlyaddsthetabledefinitionintheglobaldatadictionarywhenyou
createaBLACKHOLEtableandnofilesareassociatedwiththetable.
AllkindsofindexingissupportedintheBLACKHOLEstorageengineandsothesame
canbeincludedinthetabledefinition.
PartitioningisnotsupportedintheBLACKHOLEstorageengine.
Insertiontothetabledoesnotstoreanydatabutifbinaryloggingisenabledfor
statements, then the statements are logged and replicated to the slave servers.
Suchamechanismisusefulasafilterorrepeater.
TheBLACKHOLEstorageenginehasthefollowingpossibleuses:
Dumpfilesyntaxverification
Overhead measurement using binary logging enabled or disabled with a
BLACKHOLEperformancecomparison
Itcanalsobeusedforfindinganyperformancebottlenecks,exceptforthe
storageengineitself
Autoincrementcolumns:Astheengineisano-opengine,itwillnotincrement
any field values but it has implications in the replication, which can be very
important.Considerascenariothathasthefollowingconditions:
1. ThemasterserverhasaBLOCKHOLEtablewithanautoincrementfieldwitha
primarykey
2. ThesametableexistsontheslaveserverbutusestheMyISAMengine
3. Insertionisperformedintothemasterserver'stablewithoutsettinganyauto
incrementvalueintheINSERTstatementorusingtheSETINSERT_IDstatement
In the preceding scenario, the replication will fail on the primary key column
withaduplicateentry.
TheMERGEstorageengine
The MERGE storage engine, known also as the MRG_MyISAM engine, is collection of
similartablesthatcanbeusedasonetableinstead.Here,"similar"meansthatall
thetableshavesimilarcolumndatatypesandindexinginformation.
Itisnotpossibletomergetableswiththecolumnslistedinadifferentorderorto
havethesamedatatypesinrespectivecolumnsorhaveindexinginadifferent
order.
Thefollowingisthelistofdifferencesintablesthatwillnotrestrictamerge:
Namesofrespectivecolumnsandindexescanbedifferent.
Commentsinbetweentables,columns,andindexescanbedifferent.
AVG_ROW_LENGTH,MAX_ROWS,orPACK_KEYStableoptionscanbedifferent.
WhenaMERGEtableiscreated,MySQLalsocreatesa.MRGfileonthediskwiththe
namesofunderlyingMyISAMtablesbeingusedasone.Theformatofthetableis
storedintheMySQLdatadictionaryandtheunderlyingtablesdonotrequireto
beinthesamedatabaseastheMERGEtable.
HavingprivilegesareamustforSELECT,UPDATE,andDELETEontheMyISAMtablesthat
are being mapped with the MERGE table and so SELECT, INSERT, UPDATE, and DELETE
statementsontheMERGEtablecanbeused.
Executing the DROP TABLE statement on the MERGE table will drop only the
specificationfortheMERGEandnothingisimpactedontheunderlyingtables.
UsingMERGEtableshasthefollowingsecurityissues.Iftheuserhas
accesstotheMyISAMtablet1,thentheusercancreatetheMERGEtable
m1thatcanaccesst1.Now,iftheuser'sprivilegesonthetablet1are
revoked, the user can still continue accessing table t1 by using
tablem1.
TheFEDERATEDstorageengine
TheFEDERATEDstorageenginecanlinkmanyseparatephysicalMySQLserversinto
onelogicaldatabase
and so it can let you access data from a remote MySQL server without using
either
replicationorclustertechnology.
WhenwequerytothelocalFEDERATEDtable,thatautomaticallypullsthedatafrom
theremotefederatedtablesandthe
dataisnotrequiredtobestoredonlocaltables.
TheFEDERATEDstorageengineisnotsupportedbydefaultintheMySQLserverbut
startingtheserver
withthe--federatedoptionwillenabletheFEDERATEDengineoption.
WhentheFEDERATEDtableiscreatedthetabledefinitionisthesameasothertables,
butthephysical
storage of the associated data is handled on the remote server instead. The
FEDERATEDtableconsistsofthefollowingtwoelements:
Aremoteserverwithadatabasetableconsistingofatabledefinitionand
theassociatedtabledata.
Thistypeoftablecanbeanysupportedbytheremoteserverthatincludes
MyISAMorInnoDBaswell.
A local server with a database table consisting of a table definition the
sameastherespective
table on the remote server. The table definition is stored in the data
dictionary
andnoassociateddatafileonthelocalserverisstored.Instead,inaddition
to
the table definition, it keeps a connection string that is pointing to the
remote
tableitself.
The following is the flow of information between the local and remote server
when
aSQLstatementisexecutedontheFEDERATEDtable:
1. The engine checks each of the columns the table has and builds an
appropriateSQL
statementthatreferstotheremotetable.
2. TheMySQLclientAPIisusedforsendingtheSQLstatementtotheremote
server.
3. Thestatementisprocessedbytheremoteserverandtherespectiveresultis
retrieved
bythelocalserver.
TheEXAMPLEstorageengine
TheEXAMPLEstorageengineisonlyastubengineandthepurposeoftheengineis
toprovideexamplesintheMySQLsourcecode,whichhelpsdeveloperstowrite
newstorageengines.
ToworkwiththeEXAMPLEenginesourcecode,lookatthestorage/exampledirectory
oftheMySQLsourcecodedistributiondownload.
NofilesarecreatedifthetableiscreatedwiththeEXAMPLEengine.Datacannotbe
storedintheEXAMPLEengineanditreturnsemptyresults.
IndexingandpartitioningisnotsupportedintheEXAMPLEstorageengine.
TheInnoDBstorageengine
InnoDB is the most general-purpose storage engine and is the default engine in
MySQL8,providinghighreliabilityandhighperformance.
ThefollowingarethekeyadvantagesofferedbytheInnoDBstorageengine:
Its DML operations follows the ACID model and transactions have commit,
rollback,andcrash-recoveryfeaturestoprotectuserdata
Oracle-style gives consistent reads and row level locking increases the
performanceofmulti-userconcurrency
EachInnoDB table has a primary key index, known as the clustered index,
thatarrangesdataonthediskinordertooptimizequeriesbasedonprimary
keyandminimizesI/Oduringprimarykeylookups
By supporting foreign keys, inserts, deletes, and updates are checked,
ensuring consistency across different tables in order to maintain data
integrity
ThefollowingarethekeybenefitsofusingInnoDBtables:
Iftheserver crashes duetoany hardware orsoftwareissue, regardless of
what changes were being processed in the server at that time, you're not
required to do anything special after restarting the server. It has a crash
recoverysystemthattakescareofchangesthatwerecommittedduringthe
crash of the server. It will go to those changes and start where the
processingwasleftoff.
The engine has it's own buffer pool used for caching table and indexing
data to memory based on data accessed. Frequently used data is fetched
directly from the cache memory and so it speeds up processing. In
dedicated servers, it takes up to 80% of physical memory assigned to be
usedinthebufferpool.
Splittingrelateddatatotablesusingforeignkeysetupenforcesreferential
integrity which prevents inserting any unrelated data to a secondary table
withouttherespectivedataintheprimarytable.
In case of corrupt data in the memory or disk, the checksum mechanism
givesanalertaboutthecorruptdatabeforewegettouseit.
Change buffering automatically optimizes Insert, Update, and Delete. InnoDB
alsoallowsconcurrentreadandwriteaccesstothesametableandcaching
datachangestostreamlinethediskI/O.
When the same data rows are accessed from the table repeatedly, the
Adaptive Hash Index feature makes the lookups faster and gives
performancebenefits.
Compressionisallowedontablesandassociatedindexes.
Monitoring on internal workings and performance details of the storage
engineiseasybyqueryingINFORMATION_SCHEMAorPerformanceSchematables.
Now let us look at each of the areas of the storage engine where InnoDB is
enhancedoroptimizedtoprovideveryefficientandenhancedperformance.
ACIDmodel
The ACID model is a group of database design principles with an emphasis on
reliability,whichismostimportantformissioncriticalapplicationsandbusiness
data.
MySQLhascomponentssuchastheInnoDBstorageenginethatcloselyadhereto
the ACID model. Therefore, data is safe and not corrupted, even in exceptional
casesofhardwaremalfunctionsorsoftwarecrashes.
WithMySQL8,InnoDBsupportsatomicDDL,ensuring thatthe DDL operations are
fullycommittedorrolledback,eveniftheserverishaltedwhileperformingthe
operation.NowDDLlogscanbewrittentothemysql.innodb_ddl_logconfigurationfor
thedatadictionarytables,enablingtheinnodb_print_ddl_logsconfigurationoption
toprintDDLrecoverylogstostderr.
Multiversioning
InnoDBisamultiversionedstorageengine.Thatmeansithasthecapabilityto
keep old versions of changed row data information and support transnational
features, such as concurrency and roll back. The information is stored in the
tablespace,datastructure,andnamedrollbacksegment.
Internally,foreachoftherowsgettingstoredinthedatabase,InnoDBcreatesthree
fields: 6-byte DB_TRX_ID, 7-byte DB_ROLL_PTR (called a roll pointer) and 6-byte
DB_ROW_ID. With these fields, InnoDB creates clustered indexes to keep the
informationofchangedrowdatainthedatabase.
Architecture
Inthissection,wewillgiveabriefintroductiontothemajorcomponentsofthe
InnoDBarchitecture:
Buffer pool: Area of main memory where tables and indexing data are
cachedtospeedupprocessing
Changebuffer: Special data structure where changes to secondary index
pagesarecached
Adaptive Hash Index: Enables in-memory database, such as lookups,
operations on systems with balanced and appropriate combinations of the
bufferpool'smemoryandworkload
Redologbuffer:Memoryareawheredataisheldtobewrittenontheredo
log
System tablespace: Storage area where the doublewrite buffer, undo logs,
andthechange buffer, priorto the MySQL8data dictionaryinformation,
arestored
Doublewritebuffer:Storageareainthesystemtablespacewherepagesare
writtenthatareflushedfromthebufferpool
Undologs: Collectionof undo logrecordswhich areassociatedwith any
singletransaction
File-per-tabletablespaces: Single-table tablespace added to its own data
file
General tablespaces: Shared tablespace created by the CREATE TABLESPACE
syntax
Undotablespace:Oneormorefileswithundologs
Temporarytablespace:Utilizedfornon-compressedtemporarytablesand
theirrelatedobjects
Redo log: Disk-based data structure used for correcting incomplete
transactiondataduringcrashrecovery
With MySQL 8, the InnoDB storage engine utilizes the global MySQL data
dictionaryandnotitsownstorageengine-specificdatadictionary.
Lockingandtransactionmodel
ThissectiongivesbriefinformationonlockingusedbyInnoDBandthetransaction
modelimplementedbyInnoDB.InnoDBusesthefollowingdifferentlocktypes:
Sharedandexclusivelocks:Twotypesofstandardrow-levellockingare
implemented. A shared lock allows you to read a row to different
transactions;anexclusivelockholdstoupdateordeletearowanddoesnot
allowyoutoevenreadtherowtoanydifferenttransaction.
Intentionlocks: Table level locks to support multiple granularity locking
bywhichInnoDBpracticallymaintainsthecoexistenceofrow-levellocksand
entiretable-levellocks.
Record locks: Index record lock that prevents any other transaction to
insert,update,ordeletetherecord.
Gaplocks:Lockappliesonagap(range)betweenindexrecords.
Next-keylocks:Combinationofindexrecordlockplusgaplockonthegap
fortheprecedingindexrecord.
Insert intention locks: Type of gap lock which is set by INSERToperation
justbeforetherowinsertion.
AUTO-INClocks: Special table-level lock for inserting records with the
AUTO_INCREMENTcolumn.
Predicate locks for spatial indexes: Lock on spatial index, enabling
supportforisolationlevelsintableswithspatialindexes.
The goal of following the transaction model is to unite traditional two-phase
locking with the best of the multiversioning database properties. Row-level
lockingisperformedandqueriesarerunwithnonlockingconsistentreads.InnoDB
takescareoftransactionisolationlevels,autocommit,rollbackandcommit,and
locking reads. It allows nonlocking consistent reads as applicable. InnoDB also
uses a mechanism to avoid phantom rows and a configuration to support
automaticdeadlockdetection.
Configuration
Thissectionprovidesbriefinformationabouttheconfigurationandprocedures
usedintheInnoDBinitializationstartupfordifferentInnoDBcomponents:
InnoDBstartupconfiguration:Thisinvolvesspecifyingstartupoptions,log
fileconfiguration,storageconsiderations,systemtablespacedatafiles,undo
tablespaces,temporarytablespaces,pagesizes,andmemoryconfigurations
InnoDBforread-onlyoperation: This enables a MySQL instance for read-
only operation, using the --innodb-read-only=1 option, which is very helpful
whenusingread-onlymediasuchasCDorDVD
InnoDBbufferpoolconfiguration:Configuresthebufferpoolsize,multiple
instances,flushing,andmonitoring
InnoDBchange buffering: Configures the change buffer options for
secondaryindexcaching
Thread concurrency forInnoDB: Concurrent thread count limit
configuration
ThenumberofbackgroundInnoDBI/Othreads:Configuresthenumberof
backgroundthreadsservicingI/Oread/writeoperationsondatapages
Using asynchronous I/O on Linux: A configuration to use native
asynchronousI/OsubsytemsonLinux
TheInnoDBmaster thread I/O rate:Configuresoverall I/O capacityfora
masterthreadworkinginthebackground,responsibleformultipletasks
Spin lock polling: Configures a spin wait delay period to control the
maximumdelayforfrequentpollingbetweenmultiplethreadsrequestingto
acquiremutexesorrw-locks
InnoDBpurgescheduling:Configurespurgethreadsforapplicablescalability
Optimizer statistics forInnoDB: Configures persistent and non-persistent
optimizerstatisticsparameters
Themergethresholdforindexpages:ConfiguresMERGE_THRESHOLDtoreduce
merge-splitbehavior
Enabling automatic configuration fora dedicated MySQL Server:
Configures the dedicated server option --innodb_dedicated_server , which
makesautomaticconfigurationforthebufferpoolsizeandlogfilesize
Tablespaces
Thissectionprovidesbriefinformationontablespacesandoperationsrelatedto
tablespacesperformedinInnoDB:
ResizingtheInnoDBsystemtablespace:Increasinganddecreasingthesize
of the system tablespace with configuration while starting/restarting the
MySQLserver.
Changing the number or size of InnoDB redo log files: Configures
innodb_log_files_in_group and innodb_log_file_size values respectively in my.cnf
priortostarting/restartingtheMySQLserver.
Usingrawdiskpartitionsforthesystemtablespace:Configurestheraw
diskpartitionstobeusedasdatafilesinthesystemtablespace.
InnoDBFile-Per-Tabletablespaces:Thefeatureinnodb_file_per_table enabled
bydefaultwhichensuresthateachofthetablesandassociatedindexesare
storedinaseparate.idbdatafile.
Configuringundotablespaces:Aconfigurationtosetthenumberofundo
tablespaceswhereanundologresides.
Truncatingundotablespaces:Configuresinnodb_undo_log_truncatetoenable
truncating undo tablespace files exceeding the maximum limit defined in
innodb_max_undo_log_size.
InnoDBgeneral tablespaces: A shared tablespace created using the CREATE
TABLESPACEstatement.Itissimilartoasystemtablespace.
InnoDBtablespaceencryption:Supportfordataencryptionintablesstored
as file-per-table tablespaces which use the AES block-based encryption
algorithm.
Tablesandindexes
This section provides brief information on InnoDB tables and indexes and their
relatedoperations:
CreatingInnoDBtables:CreatestablesusingtheCREATETABLEstatement.
Thephysical rowstructure ofanInnoDBtable: Depends on the specified
row format during the table creation. If not specified, uses the default,
DYNAMIC.
Moving or copying InnoDB tables: Different techniques for moving or
copyingsomeorallInnoDBtablestoadifferentinstanceorserver.
Converting tables from MyISAM to InnoDB: Considers guidelines and tips
while converting MyISAM tables to InnoDB tables, except a partitioned table,
whichisnotsupportedwithMySQL8.
AUTO_INCREMENThandlinginInnoDB:ConfiguresthemodeforAUTO_INCREMENTwith
the innodb_autoinc_lock_mode parameter as 0,1, and 2 for traditional,
consecutive, or interleaved, respectively, where interleaved is the default
modefromMySQL8.
LimitsonInnoDBtables:Atablecancontainamaximumof1,017columns,
amaximumof64secondaryindexes,andseveralotherlimitsdefinedbased
onthepagesize,tablesize,anddata-rowformats.
Clustered and secondary indexes: InnoDB uses a special index called a
clusteredindex.Therestoftheindexesarecalledsecondaryindexes.
ThephysicalstructureofInnoDBindex:Forspatialindexes,InnoDBusesthe
R-treedatastructure,aspecializeddatastructure.Forrestoftheindexes,the
B-treedatastructureisused.
Sorted index builds: Bulk load when creating or rebuilding indexes for
inserts. They are known as sorted index builds, and are not supported in
spatialindexes.
InnoDBFULLTEXTindexes:Createdfortext-basedcolumns-char,varchar,ortext
type.Theyhelptospeedupqueriesandsearchingoperations.
<strong>mysql>SHOWTABLESFROM
INFORMATION_SCHEMALIKE'INNODB%';</strong>
Tablesaboutcompression:Thenumberofcompression
operationsandtheamountoftimespentforcompression-related
informationprovidedintheINNODB_CMPandINNODB_CMP_RESET
tables.Memoryallocationduringcompressionisprovidedinthe
INNODB_CMPMEMandINNODB_CMPMEM_RESETtables.
Transactionandlockinginformation:INNODB_TRXhas
informationontransactionscurrentlyexecutingandthe
data_locksanddata_lock_waitstablesfromthePerformance
Schematablegiveinformationaboutthelocks.
Schemaobjecttables:Thisprovidesmetadatainformationabout
theInnoDBschemaobjects.
FULLTEXTindextables:Thisprovidesmetadatainformationabout
FULLTEXTindexes.
Bufferpooltables:Thisprovidesstatusinformationand
metadataaboutthepagesinthebufferpool.
Metricstable:Thisprovidesperformanceandresourcerelated
information.
Temporarytableinformationtable:Thisprovidesmetadata
informationaboutallusersandsystem-createdtemporarytables
currentlyactiveinanInnoDBinstance.
RetrievingInnoDBtablespacemetadata:Thisprovidesmetadata
informationaboutallthetypesoftablespacesinanInnoDB
instance.
Anewview,INNODB_TABLESPACES_BRIEF,hasbeenaddedtoprovide
thename,path,flag,space,andspacetypedata.
Anewtable,INNODB_CACHED_INDEXES,hasbeenaddedtoprovidethe
numberofindexpagescachedinthebufferpoolforeachindex.
Memcachedplugin
MySQL8providesyouwiththeInnoDBmemcachedpluginnameddaemon_memcached,
which can help us in managing data easily. It will automatically store and
retrieve data from InnoDB tables and provide get, set, and incr operations that
removeperformanceoverheadbyskippingSQLparsing,whichspeedsupdata
operations. The memcached plugin uses the integrated memcached daemon that
automaticallyretrievesandstoresdatafromandtotheInnoDBtable,enablingthe
MySQLservertosenddataquicklytothekey-valuestore.
ThefollowingarethemajorbenefitsofusingtheInnoDBmemcachedplugin:
AccessestheInnoDB storageenginedirectly, reducingparsingand planning
SQLoverhead
memcached uses the same process space as the MySQL server, reducing
networkoverhead
Datawrittenorrequestedinthememcachedprotocolistransparentlywrittenor
queried from InnoDB tables, reducing having to go through SQL layer
overhead
Simplifiesapplicationlogicbyautomaticallytransferingbetweendiskand
memory
TheMySQLdatabasestoresdatasothatitisprotectedagainstcorruption,
crashes,oroutages
Ensures high availability using the daemon_memcached plugin on the master
serverandMySQLreplicationincombination
Repeated data requests are cached using the InnoDB buffer pool, providing
highspeedprocessing
As the data is stored in the InnoDB tables, the data consistency is enforced
automatically
The InnoDB memcached plugin supports multiple get operations (fetching multiple
key/valuepairsinasinglememcachedquery)andrangequeries.
Creatingacustomstorageengine
MySQLABintroducedpluggablestorageenginearchitectureinMySQL5.1and
alllater
versions, including MySQL 8, have taken advantage of the flexible storage
enginearchitecture.
Thestorageenginepluggablearchitectureprovidesthecapabilitytocreateand
add
newstorageengineswithoutrecompilingtheserver,addingdirectlytoarunning
MySQL
server.Thearchitecturemakesitveryeasytodevelopand deploynewstorage
engines
toMySQL8.
When developing new storage engine, it is required to take care of all the
components
that work for and with storage engines. These include installation handlers,
operations
ontablesuchascreating,opening,andclosing,DML,indexing,andsoon.
Inthissection,wewillcoverhowyoucanstartdevelopinganewstorageengine
on
ahigh-levelbasiswithreferencetotheMySQLdocumentationprovidedinthe
development
community. The creation of a custom storage engine requires a working
knowledgeofdevelopmentwithCandCPP,andcompilationwithcmakeandVisual
Studio.
Creating storage engine source
files
Theeasiestwaytoimplementanewstorageengineistobeginbycopyingand
modifying
theEXAMPLEstorageengine.Thefilesha_example.ccandha_example.hcanbefoundin
thestorage/exampledirectoryoftheMySQLsourcedistribution.
Whencopying thefiles,changethenamesfromha_example.ccandha_example.hto
somethingappropriatetoyourstorageengine,suchasha_foo.ccandha_foo.h.
Afteryouhavecopiedandrenamedthefiles,youmustreplaceallinstancesof
EXAMPLEandexamplewiththenameofyourstorageengine.
Adding engine-specific variables
andparameters
Aplugincanimplementstatusandsystemvariablesandinthissectionwehave
covered the changes to variables and parameters with appropriate values and
datatypes.
Theserverplugininterfaceenablespluginstoexposestatusandsystemvariables
usingthestatus_varsandsystem_varsmembersofthegeneralplugindescriptor.
status_varsisamemberofthegeneralplugindescriptor.Ifthevalueisnot0,then
itpointstoanarrayofthest_mysql_show_varstructurewhereeachofthemdescribe
one status variable followed by a structure with all the members set to 0. The
definition for the st_mysql_show_var structure is as follows: struct
st_mysql_show_var{
constchar*name;
char*value;
enumenum_mysql_show_typetype;
};
Whenthepluginisinstalled,thepluginnameandthenamevaluearejoinedwith
anunderscoretoformthenamedisplayedbytheSHOWSTATUSstatement.
Thefollowinglistshowsthepermissiblestatusvariabletypevaluesandwhatthe
correspondingvariableshouldbe:
SHOW_BOOL:Thisisapointertothebooleanvariable
SHOW_INT:Thisisapointertotheintegervariable
SHOW_LONG:Thisisapointertothelongintegervariable
SHOW_LONGLONG:Thisisapointertothelonglongintegervariable
SHOW_CHAR:ThisisaStringindex
SHOW_CHAR_PTR:ThisisapointertoStringindexes
SHOW_ARRAY:Thisisapointertoanotherst_mysql_show_vararray
SHOW_FUNC:Thisisapointertoafunction
SHOW_DOUBLE:Thisisapointertoadouble
Allsessionandglobalsystemvariableshavetobepublishedtomysqldbeforethey
are used. This is precisely done by constructing a NULL terminated array of the
variablesandlinkingtoitinthepluginpublicinterface.
All mutable and plugin system variables are stored internally in the HASH
structure.
The display of the server command-line help text is generated by compiling
DYNAMIC_ARRAY of all the relevant variables, sorting and iterating through them to
displayeachoption.
During the plugin installation process, the server processes command-line
options,immediatelyafterthepluginhasbeensuccessfullyloadedbuttheplugin
initializationfunctionisyettobecalled.
Pluginsloadedatruntimedonotbenefitfromanyconfigurationoptionsandmust
have usable defaults. Once they are installed, they are loaded at mysqld
initializationtimeandconfigurationoptionscanbesetatthecommandlineor
withinmy.cnf.
Thethdparametershouldbeconsideredasread-onlyinplugins.
<strong>handlertonexample_hton={</strong><br/><strong>
"EXAMPLE",/*Nameofthestorageengine*/</strong><br/>
<strong>SHOW_OPTION_YES,/*Itshouldbedisplayedinoptions
ornot*/</strong><br/><strong>"Examplestorageengine",/*
Descriptionofthestorageengine*/</strong><br/><strong>
DB_TYPE_EXAMPLE_DB,/*Typeofstorageengineitshouldrefer
to*/</strong><br/><strong>NULL,/*Initializehandlerton
*/</strong><br/><strong>0,/*slotavailable*/</strong><br/>
<strong>0,/*definesavepointsize.*/</strong><br/><strong>
NULL,/*handleclose_connection*/</strong><br/><strong>NULL,
/*handlesavepoint*/</strong><br/><strong>NULL,/*handle
rollbacktosavepoint*/</strong><br/><strong>NULL,/*handle
releasesavepoint*/</strong><br/><strong>NULL,/*handle
commit*/</strong><br/><strong>NULL,/*handlerollback
*/</strong><br/><strong>NULL,/*handleprepare*/</strong><br
/><strong>NULL,/*handlerecover*/</strong><br/><strong>
NULL,/*handlecommit_by_xid*/</strong><br/><strong>NULL,
/*handlerollback_by_xid*/</strong><br/><strong>NULL,/*
handlecreate_cursor_read_view*/</strong><br/><strong>NULL,/*
handleset_cursor_read_view*/</strong><br/><strong>NULL,/*
handleclose_cursor_read_view*/</strong><br/><strong>
example_create_handler,/*Createanewhandlerinstance*/</strong>
<br/><strong>NULL,/*handledropdatabase*/</strong><br/>
<strong>NULL,/*handlepaniccall*/</strong><br/><strong>
NULL,/*handlereleasetemporarylatches*/</strong><br/>
<strong>NULL,/*UpdaterelevantStatistics*/</strong><br/>
<strong>NULL,/*StartConsistentSnapshotforreference
*/</strong><br/><strong>NULL,/*handleflushlogs*/</strong>
<br/><strong>NULL,/*handleshowstatus*/</strong><br/>
<strong>NULL,/*handlereplicationReportSenttoBinlog
*/</strong><br/><strong>HTON_CAN_RECREATE</strong><br
/><strong>};</strong>
Thereare30handlertonelements,onlyfewofwhicharemandatory.
<strong>statichandler*tina_create_handler(TABLE*table);
</strong>
<strong>statichandler*myisam_create_handler(TABLE*table)
</strong><br/><strong>{</strong><br/><strong>returnnew
ha_myisam(table);</strong><br/><strong>}</strong>
<strong>constchar**ha_tina::bas_ext()const</strong><br/>
<strong>{</strong><br/><strong>returnha_tina_exts;</strong><br
/><strong>}</strong>
Byprovidingextensioninformation,youcanalsoskipimplementing
DROPTABLEfunctionality,astheMySQLserverwillimplementthe
samebyclosingthetableanddeletingallfileswiththeextensions
specified.
<strong>virtualintcreate(constchar*name,TABLE*form,
HA_CREATE_INFO*info)=0;</strong>
<strong>typedefstructst_ha_create_information</strong><br/>
<strong>{</strong><br/><strong>CHARSET_INFO*table_charset,
*default_table_charset;/*charsetintable*/</strong><br/><strong>
LEX_STRINGconnect_string;/*connectionstring*/</strong><br/>
<strong>constchar*comment,*password;/*storingcommentsand
passwordvalues*/</strong><br/><strong>constchar
*data_file_name,*index_file_name;/*dataandindexfilenames
*/</strong><br/><strong>constchar*alias;/*valuepointerforalias
*/</strong><br/><strong>ulonglongmax_rows,min_rows;</strong>
<br/><strong>ulonglongauto_increment_value;</strong><br/>
<strong>ulongtable_options;</strong><br/><strong>ulong
avg_row_length;</strong><br/><strong>ulongraid_chunksize;
</strong><br/><strong>ulongused_fields;</strong><br/><strong>
SQL_LISTmerge_list;</strong><br/><strong>enumdb_type
db_type;/*valuefordb_type*/</strong><br/><strong>enum
row_typerow_type;/*valueforrow_type*/</strong><br/><strong>
uintnull_bits;/*NULLbitsspecifiedatstartofrecord*/</strong><br
/><strong>uintoptions;/*ORofHA_CREATE_options
specification*/</strong><br/><strong>uintraid_type,raid_chunks;
/*raidtypeandchunksinfo*/</strong><br/><strong>uint
merge_insert_method;</strong><br/><strong>uintextra_size;/*
lengthofextradatasegments*/</strong><br/><strong>bool
table_existed;/*1increateiftableexisted*/</strong><br/><strong>
boolfrm_only;/*1ifnoha_create_table()*/</strong><br/><strong>
boolvarchar;/*1iftablehasaVARCHAR*/</strong><br/>
<strong>}HA_CREATE_INFO;</strong>
Storageenginescanignorethecontentsof*infoand*formbecause
thecreationandtheinitializationofthedatafilesisonlyreally
requiredwhenusedbythestorageengine.
<strong>intopen(constchar*name,intmode,inttest_if_locked);
</strong>
<strong>#defineHA_OPEN_ABORT_IF_LOCKED0/*default
*/</strong><br/><strong>#defineHA_OPEN_WAIT_IF_LOCKED
1/*waitiftableislocked*/</strong><br/><strong>#define
HA_OPEN_IGNORE_IF_LOCKED2/*ignoreiflocked*/</strong>
<br/><strong>#defineHA_OPEN_TMP_TABLE4/*Tableisatemp
table*/</strong><br/><strong>#define
HA_OPEN_DELAY_KEY_WRITE8/*Don'tupdateindex
*/</strong><br/><strong>#define
HA_OPEN_ABORT_IF_CRASHED16</strong><br/>
<strong>#defineHA_OPEN_FOR_REPAIR32/*openevenif
crashedwithrepair*/</strong>
Thetypicalstorageenginewillimplementsomeformofsharedaccess
controlinordertopreventfilecorruptioninamulti-threaded
environment.Forexample,seetheget_share()andfree_share()
methodsofsql/example/ha_tina.ccforimplementingfilelocking.
<strong>ha_tina::store_lock</strong><br/>
<strong>ha_tina::external_lock</strong><br/>
<strong>ha_tina::info</strong><br/>
<strong>ha_tina::rnd_init</strong><br/><strong>ha_tina::extra-
ENUMHA_EXTRA_CACHECacherecordinHA_rrnd()</strong>
<br/><strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/>
<strong>ha_tina::rnd_next</strong><br/><strong>ha_tina::extra-
ENUMHA_EXTRA_NO_CACHEEndcachingofrecords(def)
</strong><br/><strong>ha_tina::external_lock</strong><br/>
<strong>ha_tina::extra-ENUMHA_EXTRA_RESETResetdatabase
toafteropen</strong>
Thefollowingmethodscanbeimplementedtotakecareofspecific
operations:
Implementingthestore_lock():Thismethodcanmodifythe
locklevel,ignoringoraddinglocksformanytables
Implementingtheexternal_lock():Thismethodiscalledwhen
theLOCKTABLESstatementisissued
Implementingthernd_init():Thismethodisusedintable
scanningforresettingcountersandpointersatthestartofatable
Implementingtheinfo(uinfflag):Thismethodisusedto
provideextratableinformationtotheoptimizer
Implementingtheextra():Thismethodisusedtoprovideextra
hintsinformationtothestorageengine
Implementingthernd_next():Thismethodiscalledoneach
rowofscanninguntilEOFisreachedorthesearchconditionis
satisfied
<strong>intha_tina::close(void)</strong><br/><strong>{</strong>
<br/><strong>DBUG_ENTER("ha_tina::close");</strong><br/>
<strong>DBUG_RETURN(free_share(share));</strong><br/>
<strong>}</strong>
Storageenginesusetheirownsharemanagementsystems.They
shouldusetherequiredmethodsinordertoremovethehandler
instancefromthesharefortherespectivetableopenedintheir
handler.
Ifyourstorageengineiscompiledasasharedobject,duringloadingif
yougetanerrorsuchasundefinedsymbol:_ZTI7handler,then
makesureyoucompileandlinkyourextensionusingthesameflags
astheserveruses.TheusualreasonforthiserroristhatLDFLAGS
aremissingthe-fno-rttioption.
Reference for advanced custom
storageengine
We have gone through the preceding sections in detail, giving high-level
information
for custom storage engine components and the required changes. For
implementing INSERT, UPDATE, DELETE, indexing, and so on, in a custom storage
engine, requires a working knowledge of development with C/CPP and
compilation with cmake and Visual Studio. For advanced development for the
customstorageengines,pleaserefertothedetailed
informationgivenathttps://dev.mysql.com/doc/internals/en/custom-engine.html
Summary
Bynow,youhavelearnedthedifferentdatabaseenginesavailableinMySQL8
andwelearnedwhyweshouldcareaboutstorageenginesandavailablestorage
engineoptionsinMySQL 8.WecoveredindetailtheInnoDBstorageengineand
relatedimportantfeaturesalreadyprovidedwithintheInnoDBstorageengine.Now
you are practically able to create a custom storage engine as per the system
requirement and make it pluggable in MySQL 8. An important aspect was to
chooseasuitablestorageengineforyoursystem,whichiscovereddetail.
Inthenextchapter,youwilllearnabouthowindexingworksinMySQL8,the
newfeaturesintroducedrelatedtoindexing,thedifferenttypesofindexing,and
howtouseindexingonyourtables.Alongwiththat,acomparisonwillalsobe
provided along with in-depth knowledge of various ways of index
implementation.
IndexinginMySQL8
In the previous chapter, we learned about storage engines. Now we are aware
what types of storage engines are available and which ones to use for our
requirements. The previous chapter also covered the InnoDB storage engine in
detail, along with other storage engine information. It also described how to
defineacustomstorageengineforuse,withapracticalexample.Nowit'stime
to understand one more important functionality of MySQL 8 and that is,
indexing.
We will cover different types of indexes with their functionalities, which will
encourage you to use indexes and provided you with guidance on how to use
them.So,yourjourneyintoindexeshasstarted!Let'sgo.
Wewillcoverthefollowingtopicsinthischapter:
Anoverviewonindexing
Column-levelindexing
B-Treeindexes
Hashindexes
Indexextensions
Usinganoptimizerforindexes
Invisibleanddescendingindexes
Anoverviewonindexing
Todefineanindexonatableisthebestwaytoimprovetheperformanceofthe
SELECT operation. An index acts like a pointer for the table rows and permits
queriesto
quicklypoint tomatchingrowsbasedon theWHERE condition.MySQL8allows
youtocreateindexesonallthedatatypes.Althoughindexing
providesgoodperformanceonqueries,itisrecommendtodefineitintheproper
way,
becauseunnecessaryindexeswastespaceandtime(forMySQL8tofindwhich
index
is best to use). In addition to that, indexes also add costs to INSERT, UPDATE, and
DELETE operations, because during these operations, MySQL 8 will update each
index.
Aswedescribedpreviously,anindexisadatastructurethatimprovesthespeed
of
operations.Basedonthestructure,anindexisbifurcatedintotwomajorforms—
aclustered
indexandanon-clusteredindex:
Clustered index: A clustered index defines the order in which data is
physicallystoredinatable.
Therefore,onlyoneclusteredindexisallowedpertable.Itgreatlyincreases
the
speedofretrievalwhendataisretrievedinasequentialmanner,eitherinthe
same
order or in reverse order. A clustered index also provides better
performancewhen
arangeofitemsareselected.Aprimarykeyisdefinedasaclusteredindex.
Non-clustered index: A non-clustered index doesn't define the order in
whichdataisphysicallystored.
Thismeansanon-clusteredindexisstoredinoneplace,anddataisstored
inanother
place.Therefore,morethanonenon-clusteredindexisallowedpertable.It
refers
tonon-primarykeys.
Asweknow,theprimarykeyrepresentsthecolumn,orsetofcolumns,whichis
most
widelyusedforfetchingrecordsfromthetable.Theprimarykeyhasanindex
associated
withitandisusedforfastqueryperformance.Itprovidescomparativelyfaster
performance
becauseaprimarykeydoesnotallowaNULLvalue,sonocheckisrequiredonNULL
values. It is recommended that if your table does not have a column or set of
columns
to define as a primary key, then you define one auto increment field as the
primary
key for better performance. On the other hand, if your table contains many
columns
andthereisaneedtoexecuteaquerywithacombinationofmultiplecolumns,
then
it is advisable to the less frequently used data and transfer in onto a separate
table.
Relatealltheseparatetableswithprimaryandforeignkeyreferences,whichwill
helpyouinmanagingdata,andqueryretrievalprovidesyougoodperformance.
<strong>SELECTMIN(key_part2),MAX(key_part2)FROM
tble_nameWHERE<br/>key_part1=10;</strong>
SQL commands related to
indexes
MySQL 8 provides two main commands related to indexes. We will discuss
thesecommandsinthefollowingsections.
<strong>CREATE[UNIQUE|FULLTEXT|SPATIAL]INDEX
index_name</strong><br/><strong>[index_type]</strong><br/>
<strong>ONtbl_name(index_col_name,...)</strong><br/><strong>
[index_option]</strong><br/><strong>[algorithm_option|
lock_option]...</strong><br/><strong>index_col_name:</strong>
<br/><strong>col_name[(length)][ASC|DESC]</strong><br/>
<strong>index_option:</strong><br/><strong>KEY_BLOCK_SIZE
[=]value</strong><br/><strong>|index_type</strong><br/>
<strong>|WITHPARSERparser_name</strong><br/><strong>|
COMMENT'string'</strong><br/><strong>|{VISIBLE|
INVISIBLE}</strong><br/><strong>index_type:</strong><br/>
<strong>USING{BTREE|HASH}</strong><br/>
<strong>algorithm_option:</strong><br/><strong>ALGORITHM
[=]{DEFAULT|INPLACE|COPY}</strong><br/>
<strong>lock_option:</strong><br/><strong>LOCK[=]
{DEFAULT|NONE|SHARED|EXCLUSIVE}</strong>
Usingcol_name(length)syntax,theuserisabletospecifyanindex
prefixlength,whichwillconsideronlyaspecifiednumberof
charactersfromthestringvalue.Atthetimeofdefining,theprefix
considersthefollowingpoints:
TheprefixisoptionalforCHAR,VARCHAR,BINARY,andVARBINARY
columnindexes
TheprefixmustbespecifiedinthecaseofBLOBandTEXT
columnindexes
MySQL8willconsiderprefixesasanumberofcharactersfor
non-binarystringtypes(CHAR,VARCHAR,TEXT)andanumberof
bytesforbinarytypes(BINARY,VARBINARY,BLOB)
Theprefixisnotallowedforthespatialcolumns
Adetailedexampleoftheprefixoptionisdescribedlaterinthis
chapter,undertheColumnindexessection.AUNIQUEindexisa
constraintwhichindicatesthatallthevaluesintheindexwillbe
unique.Ifyoutrytoaddvalueswhichalreadyexist,thenMySQL8
displaysanerror.AlltypesofstorageengineswithaUNIQUEindex
permitmultiplenullvalues.InthecaseofprefixeswhenyouuseNULL
values,makesurecolumnvaluesareuniquewithintheprefixes.Ifan
indexprefixexceedsitssize,thenMySQL8willhandletheindexas
follows:
Foranon-uniqueindex:IfthestrictSQLmodeisenabled,then
MySQL8willthrowanerror,andifthestrictmodeisdisabled,
thentheindexlengthisreducedtothemaximumcolumndata
typesizeandwillproduceawarning.
Forauniqueindex:Inthiscase,MySQL8producesanerror
regardlessoftheSQLmode,becauseitmightbreakthe
uniquenessofthecolumn.Thismeansyouhavedefinedacolumn
with25lengthandtriedtodefineanindexonthesamecolumn
withaprefixlength27;thenMySQL8throwsanerror.
Spatialindexcharacteristics
MySQL8followsthefollowingrulesforspatialindexcharacteristics:
ItisonlyavailableforInnoDBandMyISAMstorageengines;ifyoutrytouseit
forotherstorageengines,thenMySQL8givesanerror.
ANULLvalueisnotallowedforindexedcolumns.
A prefix attribute is not allowed for this column. Full width will be
consideredfortheindex.
<strong>createtableemployee(idint(11)notnull,namevarchar(50));
</strong><br/><strong>CREATEINDEXemp_name_indexON
employee(name)USINGBTREE;</strong>
<strong>CREATEINDEXname_indexONemployee(name)
COMMENT<br/>'MERGE_THRESHOLD=40';</strong>
Ifthepage-fullpercentageforanindexislessthanthe
MERGE_THRESHOLDvalue,thentheInnoDBstorageenginewill
mergetheindexpagewithaneighboringindexpage.
VISIBLE,INVISIBLE:Thisparameterdefinestheindexvisibility.
Bydefault,allindexesarevisible.Theoptimizerwillnotusean
invisibleindexduringtheoptimizationprocess.
TheALGORITHMandLOCKattributeswillhaveanimpactwhenyoutry
tousethetableforreadingorwriting,andwhilesimultaneously
modifyingitsindexing.
<strong>DROPINDEXindex_nameONtbl_name</strong><br/>
<strong>[algorithm_option|lock_option]...</strong><br/>
<strong>algorithm_option:</strong><br/><strong>ALGORITHM
[=]{DEFAULT|INPLACE|COPY}</strong><br/>
<strong>lock_option:</strong><br/><strong>LOCK[=]
{DEFAULT|NONE|SHARED|EXCLUSIVE}</strong>
<strong><spanclass="tokenkeyword">DROP</span><span
class="tokenkeyword">INDEX</span>name_index<span
class="tokenkeyword">ONemployee;</span></strong>
<strong>CREATETABLEgeom_data(dataGEOMETRYNOT
NULL,SPATIALINDEX(data));</strong>
<strong>SELECTDISTINCTST_SRID(column_name)FROM
table_name;</strong>
Ifthequeryreturnsmultiplerows,thenitindicatesthatthecolumn
containsmixedSRIDs.Ifso,changethecontentsofthecolumnfor
thesameSRIDvalue.
DefineanexplicitSRIDforthecolumn.
RecreatetheSPATIALINDEX.
InnoDB and MyISAM index
statisticscollection
MySQL 8 will consider table statistics based on the value group, which is
nothing but a set of rows with the same prefix values. The storage engine
collectsstatisticsrelatedtothetable,whichareusedbytheoptimizer.Fromthe
optimizationperspective,averagevaluegroupsizeisanimportantstatistic.Ifthe
averagevalueofthegroupsizeincreases,thentheindexisnotmeaningful.
So, it's better to target a small number of rows for each index. This can be
achievedbytablecardinality,whichisnothingbutanumberofvaluegroup.For
InnoDB and MyISAM tables, MySQL 8 provides control on statistics by the
myisam_stats_methodandtheinnodb_stats_methodsystemvariables.Thefollowingare
thepossiblevaluesforthesevariables:
nulls_ignored:ItindicatesthatNULLvaluesareignored
nulls_equal:ItindicatesallNULLvaluesareidentical
nulls_unequal:ItindicatesallNULLvaluesarenotidentical
The innodb_stats_method system variable has a global value, while the
myisam_stats_methodsystemvariablehasbothglobalandsessionvalues.Whenwe
setaglobalvalueofavariable,itwillaffectstatisticscollectionfortablesfrom
the corresponding storage engine. In the case of session value statistics,
collectionisavailableonlyforthecurrentclientconnection.Thismeansthatyou
have to regenerate a table's statistics for the other client on the same table
withoutaffectingotherclients,andneedtosetitinasessionvalue.Toregenerate
MyISAMstatistics,useeitherofthesemethods:
Executethemyisamchk--stats_method=method_name--analyzecommand
Make changes to the table to make its statistics out of date, and then set
myisam_stats_methodandissueanANALYZETABLEstatement
Therearesomepointsthatmustbeconsideredbeforeusingthesetwovariables:
These variables are available only for InnoDB and MyISAM tables. For other
storageengines,onlyonemethodisavailabletocollecttablestatistics,and
itisveryneartothenulls_equalmethod.
MySQL8providesawaytogeneratestatisticsforatableexplicitly,butthis
isnotalways thecase.Sometimes, MySQL8may alsogeneratestatistics
automatically,ifitisrequired.Forexample,inthecaseofanyoperations,if
someoftheSQL
statements modified table data, then MySQL 8 will automatically collect
statistics.
Considerbulkinsertordeleteoperations.
Wecannotsaywhichmethodwasusedtogeneratestatisticsforatable.
Column-levelindexing
MySQL 8 allows you to create an index on a single column, as well as on
multiplecolumns.
Themaximumnumberofindexespertableandmaximumindexlengthdepend
onthestorageengine.Mostly,allthestorageenginesallowatleast16indexes
pertableand total indexlengthsof at least256bytes, but mostofthe storage
enginespermithigherlimits.
Columnindexes
Thisisthemostcommonwaytodefineanindexwhereonlyasinglecolumnis
involved.
MySQL8storesacopyofcolumnvaluesinadatastructuresothatrowscanbe
accessed
quickly.MySQL8usesaB-Treedatastructuretoenablevaluestobeaccessed
quickly.TheB-Treeexecutionwill
workbasedonoperators,suchas=,<,>,BETWEEN,IN,andmanymore,whichwere
definedinthewherecondition.Youcanget detailson theB-Treedata structure
anditsexecutionin
thenexttopic.Wewilldiscussthecharactersofcolumnindexesinthecoming
sections.
<strong>CREATETABLEperson(personal_dataTEXT,
INDEX(personal_data(8)));</strong>
Thiscommandcreatesanindexonthepersonal_datacolumnby
consideringthefirsteightcharacters.Theprefixlengthvaries,based
onthestorageengine.TheInnoDBstorageengineallowsuptoa767
byteprefixlengthforREDUNDANTorCOMPACTrowformats,whileinthe
caseofDYNAMICorCOMPRESSEDrowformats,itallowsupto3072
bytes.InthecaseoftheMyISAMstorageengine,theprefixcanbe
definedforupto1,000bytes.
Prefixlengthwillbemeasuredinbytesforbinarystringtypes,suchas
BINARY,VARBINARY,andBLOB,whileinthecaseofnon-binarystring
types,itwillbeconsideredasanumberofcharacters.
FULLTEXTindexes
Asthenameimplies,FULLTEXTindexesallowCHAR,VARCHAR,andTEXTcolumnsonly.
This index is supported by InnoDB and MyISAM storage engines. In this type,
indexingwilltakeplaceonanentirecolumn,ratherthanaprefixlength.MySQL
8evaluatesthe full textexpressionduring the optimizationphase of thequery
execution. Before making estimations, optimization evaluates the full text
expressionintheprocessofdevelopinganexecutionplan.Asaresult,theEXPLAIN
queryoffulltextisslowerthannon-fulltextqueries.Fulltextqueriesareuseful
inthefollowingscenarios:
WhenaFULLTEXTqueryreturnseitheradocumentIDoradocumentIDand
searchrank
When a FULLTEXT query sorts the matching rows by descending order and
usesaLIMITclausetofetchNnumberofrows,applyonlyasingleORDER BY
clauseindescendingorder,anddon'tuseaWHEREclauseinitforoptimization
When a FULLTEXT query fetches a COUNT(*) value from therows without any
additional WHERE clauses, apply the WHERE clause as WHERE MATCH(text)AGAINST
('other_text'),withoutany>0comparisonoperator
SpatialIndexes
MySQL 8 allows you to create indexes on spatial data types. The InnoDB and
MyISAM storage engines support R-Tree for spatial data, while other storage
engines use B-Tree. Since MySQL 5.7, spatial indexes are supported in MyISAM
andInnoDBdatabaseengines.
Indexes in the MEMORY storage
engine
MemorystorageenginessupportbothHASHindexesandB-Treeindexes,butHASH
indexesare,bydefault,setfortheMEMORYstorageengine.
<strong>CREATETABLEEmployee(</strong><br/><strong>id
INTNOTNULL,</strong><br/><strong>lastnamevarchar(50)not
null,</strong><br/><strong>firstnamevarchar(50)notnull,</strong>
<br/><strong>PRIMARYKEY(id),</strong><br/><strong>INDEX
name(lastname,firstname)</strong><br/><strong>);</strong>
<strong>SELECT*FROMEmployeeWHERElastname='Shah';
</strong><br/><strong>SELECT*FROMEmployeeWHERE
lastname='Shah'ANDfirstname='Mona';</strong><br/>
<strong>SELECT*FROMEmployeeWHERElastname='Shah'
AND(firstname='Michael'ORfirstname='Mona');</strong><br/>
<strong>SELECT*FROMEmployeeWHERElastname='Shah'
ANDfirstname>='M'ANDfirstname<'N';</strong>
<strong>SELECT*FROMEmployeeWHEREfirstname='Mona';
</strong><br/><strong>SELECT*FROMEmployeeWHERE
lastname='Shah'ORfirstname='Mona';</strong>
Remember,inthecaseofamultiple-columnindex,anyleft-most
prefixoftheindexcanbeusedbytheoptimizerforsearchingrows.
Forexample,iftheindexwasdefinedonthreecolumnsinsequence,
column1,column2,andcolumn3,thenyoucanuseindexedcapabilities
on(column1,column2,column3),(column1),(column1,column2),by
definingitintheWHEREclause.
<strong>CREATETABLEEmployee(</strong><br/><strong>
lastnamevarchar(50)notnull,</strong><br/><strong>firstname
varchar(50)notnull,</strong><br/><strong>dobdatenotnull,
</strong><br/><strong>genderchar(1)notnull,</strong><br/>
<strong>key(lastname,firstname,dob)</strong><br/><strong>);
</strong>
Asperthetabledefinitionindexwillcontainsvaluesincombination
ofthreecolumnsfirstname,lastname,anddob.Itwillsortvaluesas
pertheordergivenpreviously;thismeansthatifsomeemployees
havesimilarnames,thentheywillbesortedbytheirbirthdates.
ConsiderthefollowingtypesofquerieswhichwillbenefitfromtheB-
Treeindex:
Matchtherangeofvalues:Findstheemployeeswhoselast
namesarePatelandGupta.
Matchthefullvalues:FindsemployeewhosenameisMohan
Patelandwasbornon28/11/1981.
Matchleftmostprefix:Findsallemployeewithalastname.
Theseuseonlythefirstcolumnintheindex.
Matchwithcolumnprefix:Findstheemployeeswhoselast
namesbeginwithM.Itusesonlythefirstcolumnintheindex.
Matchonepartexactlyandwithrangeofanothercolumn:
FindstheemployeewhoselastnameisPatelandwhosefirst
namestartswithA.
ThefollowingarequerieswhereB-Treeisnotuseful:
Don'tuseanyconditionafterarangecondition:Forexample,
youhaveputtheWHEREconditionlastname='Patel'and
firstnamelike‘A%'anddob='28/11/1981'.Here,onlythefirst
twocolumnsareconsideredfortheindex,becauseLIKEisarange
condition.
Don'tskipanyofthecolumnsdefinedintheindex:Thismeans
youarenotallowedtouselastnameanddobtofindanemployee
wherefirstnameismissingintheWHEREcondition.
Lookupdoesn'tstartwithleft-mostsideofindexedcolumns:
Forexample,theindexwillnotworkifyoufindtheemployee
whosefirstnameisMohanandwhosedobisonacertaindate.In
thisquery,definedcolumnsarenotleft-mostintheindex.Inthe
sameway,theindexdoesnotworkinthecasewhereyoufindthe
employeewhoselastnameendswithsomething.
Hashindex
It is very difficult to find a single value from a large database by following
completetreetraversalswithmultiplelevels.Toovercomethisproblem,MySQL
hasprovidedanotherindextype,whichisknownas ahashindex. This index
createsahashtableratherthanatree,whichisveryflatinstructurecomparedto
aB-Treeindex.Hashingmainlyuseshashfunctionstogeneratetheaddressesof
data.Twoimportanttermsrelatedtohashingare:
Hashfunction:Themappingfunctionwhichwillbeusefultomapsearch-
keyswiththeaddresswhereactualrecordsarestored.
Bucket:Abucketisaunitofstoragewhereahashindexstoresthedata.A
bucket indicates a complete disk block, which will store one or more
records.
Along with the hashing mechanism, a hash index has some special
characteristics,describedasfollows:
Thewholekeyisusedtosearchtherow.WhileinthecaseofaB-Tree,only
theleft-mostprefixofthekeyisusedtofindrows.
TheoptimizerwillnotuseahashindextospeedupORDERBYoperations.In
otherwords,thisindexisneverusedtofindthenextentry.
Hashindexesareusedforequalitycomparisonbyusing=or<=>operators.It
willneverusecomparisonoperatorswhichwillreturnarangeofvalues.
Forexample,the<(lessthan)operator.
The range optimizer cannot actually gauge how many rows are available
betweenthetwovalues.And,ifweuseahash-indexedMEMORYtableinstead
ofInnoDBorMyISAM,thenitmayaffectthequeriesaswell.
<strong>SEToptimizer_switch='use_index_extensions=off';
</strong>
<strong>CREATETABLEtable1(</strong><br/><strong>c1INT
NOTNULLDEFAULT0,</strong><br/><strong>c2INTNOT
NULLDEFAULT0,</strong><br/><strong>d1DATEDEFAULT
NULL,</strong><br/><strong>PRIMARYKEY(c1,c2),</strong>
<br/><strong>INDEXkey1(d1)</strong><br/><strong>)ENGINE
=InnoDB;</strong><br/><br/><strong>--Insertvaluesinto
table</strong><br/><strong>INSERTINTOtable1
VALUES</strong><br/><strong>(1,1,'1990-01-01'),(1,2,'1991-01-
01'),</strong><br/><strong>(1,3,'1992-01-01'),(1,4,'1993-01-01'),
</strong><br/><strong>(1,5,'1994-01-01'),(2,1,'1990-01-01'),
</strong><br/><strong>(2,2,'1991-01-01'),(2,3,'1992-01-01'),
</strong><br/><strong>(2,4,'1993-01-01'),(2,5,'1994-01-01'),
</strong><br/><strong>(3,1,'1990-01-01'),(3,2,'1991-01-01'),
</strong><br/><strong>(3,3,'1992-01-01'),(3,4,'1993-01-01'),
</strong><br/><strong>(3,5,'1994-01-01'),(4,1,'1990-01-01'),
</strong><br/><strong>(4,2,'1991-01-01'),(4,3,'1992-01-01'),
</strong><br/><strong>(4,4,'1993-01-01'),(4,5,'1994-01-01'),
</strong><br/><strong>(5,1,'1990-01-01'),(5,2,'1991-01-01'),
</strong><br/><strong>(5,3,'1992-01-01'),(5,4,'1993-01-01'),
</strong><br/><strong>(5,5,'1994-01-01');</strong>
<strong>--Indexextensionissetasoff</strong><br/><strong>SET
optimizer_switch='use_index_extensions=off';</strong><br/><br/>
<strong>--Executeselectquerywithexplain</strong><br/>
<strong>EXPLAINSELECTCOUNT(*)FROMtable1WHEREc1=
3ANDd1='1992-01-01';</strong><br/><br/><strong>--Outputof
explainquery</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>id:
1</strong><br/><strong>select_type:SIMPLE</strong><br/>
<strong>table:table1</strong><br/><strong>type:ref</strong><br
/><strong>possible_keys:PRIMARY,key1</strong><br/><strong>
key:PRIMARY</strong><br/><strong>key_len:4</strong><br/>
<strong>ref:const</strong><br/><strong>rows:5</strong><br/>
<strong>Extra:Usingwhere</strong>
<strong>--Indexextensionissetason</strong><br/><strong>SET
optimizer_switch='use_index_extensions=on';</strong><br/><br/>
<strong>--Executeselectquerywithexplain</strong><br/>
<strong>EXPLAINSELECTCOUNT(*)FROMtable1WHEREc1=
3ANDd1='1992-01-01';</strong><br/><br/><strong>--Outputof
explainquery</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>id:
1</strong><br/><strong>select_type:SIMPLE</strong><br/>
<strong>table:table1</strong><br/><strong>type:ref</strong><br
/><strong>possible_keys:PRIMARY,key1</strong><br/><strong>
key:key1</strong><br/><strong>key_len:8</strong><br/>
<strong>ref:const,const</strong><br/><strong>rows:1</strong>
<br/><strong>Extra:Usingindex</strong>
Now,wewillcheckthedifferencebetweenthesetwoapproaches:
Thekey_lenvaluechangesfrom4bytesto8bytes,which
indicatesthatkeylookupsuseboththecolumnsd1andc1,not
onlyd1.
Therefvaluechangesfrom(const)to(const,const)which
indicateskeylookupusestwokeypartsinsteadofone.
Therowscountchangesfrom5to1,whichindicatesthatInnoDB
requiresfewerrowsthanthefirstapproachtoproducetheresult.
TheExtravaluechangesfromUsingwheretoUsingindex.It
indicatesthattherowscanbereadbyusingonlytheindex,
withoutconsultinganyothercolumnsinthedatarow.
<strong>CREATETABLEt1(c1INT,c2INTAS(c1+1)STORED,
INDEX(c2));</strong>
<strong>SELECT*FROMt1WHEREc1+1>100;</strong>
<strong>mysql>explainSELECT*FROMt1WHEREc1+1>100;
</strong><br/><strong>***************************1.row
***************************</strong><br/><strong>id:
1</strong><br/><strong>select_type:SIMPLE</strong><br/>
<strong>table:t1</strong><br/><strong>partitions:NULL</strong>
<br/><strong>type:range</strong><br/><strong>possible_keys:
c2</strong><br/><strong>key:c2</strong><br/><strong>key_len:
5</strong><br/><strong>ref:NULL</strong><br/><strong>rows:
1</strong><br/><strong>filtered:100.00</strong><br/><strong>
Extra:Usingindexcondition</strong>
<strong>name
TEXTAS(JSON_EXTRACT(emp,'$.name'))STORED</strong>
<strong>name
TEXTAS(JSON_UNQUOTE(JSON_EXTRACT(emp,'$.name')))STORED</strong>
<strong>c2INTAS(c1)STOREDincolumndefinition.</strong>
Useaindexhintiftheoptimizertriestousethewrongindex,
whichwilldisableditandforcetheoptimizertouseadifferent
choice
Invisibleanddescendingindexes
Theinvisibleindexisaspecialfeaturewhichwillmarkanindexasunavailable
fortheoptimizer.MySQL
8 will maintain invisible indexes and keep them up-to-date when data is
modified.
This will apply on indexes other than primary key. As we know, indexes are
visible by default; we have to make them invisible explicitly at the time of
creation, or by using the alter command. MySQL 8 provides the VISIBLE and
INVISIBLEkeywordstomaintainindexvisibility.Adescendingindexisthemethod
ofstoringkeyvaluesindescendingorder.Adescendingindexismoreefficient,
asitcanbescannedintheforwardorder.Let'sseetheseindexesindetail,with
examples.
Invisibleindex
As mention previously, an invisible index is not used by the optimizer. Then
whatistheuseofthisindex?Thisquestioncomesintoourmind,right?Wewill
explaintoyousomeoftheusecasesforinvisibleindexes:
Whenmanyindexesaredefined,butyouarenotsurewhichindexisnotin
use. In this case, you can make an index invisible and check the
performance impact. If it has an impact, then you can make that index
visibleonanimmediatebasis.
Special cases where only one query is using an index. In this case, an
invisibleindexisagoodsolution.
In the following example, we will create an invisible index using CREATE TABLE,
CREATEINDEX,orALTERTABLEcommands:
CREATETABLE`employee`(
`id`int(11)NOTNULLAUTO_INCREMENT,
`department_id`int(11),
`salary`int(11),
PRIMARYKEY(`id`)
)ENGINE=InnoDB;
CREATEINDEXidx1ONemployee(department_id)INVISIBLE;
ALTERTABLEemployeeADDINDEXidx2(salary)INVISIBLE;
Tochangethevisibilityoftheindexes,usethefollowingcommands:
ALTERTABLEemployeeALTERINDEXidx1VISIBLE;
ALTERTABLEemployeeALTERINDEXidx1INVISIBLE;
Togetinformationaboutanindex,executeINFORMATION_SCHEMA.STATISTICStableorSHOW
INDEXcommandsinthefollowingways:
mysql>SELECT*FROMinformation_schema.statisticsWHEREis_visible='NO';
***************************1.row***************************
TABLE_CATALOG:def
TABLE_SCHEMA:db1
TABLE_NAME:employee
NON_UNIQUE:1
INDEX_SCHEMA:db1
INDEX_NAME:idx1
SEQ_IN_INDEX:1
COLUMN_NAME:department_id
COLLATION:A
CARDINALITY:0
SUB_PART:NULL
PACKED:NULL
NULLABLE:YES
INDEX_TYPE:BTREE
COMMENT:
INDEX_COMMENT:
IS_VISIBLE:NO
mysql>SELECTINDEX_NAME,IS_VISIBLEFROMINFORMATION_SCHEMA.STATISTICS
->WHERETABLE_SCHEMA='db1'ANDTABLE_NAME='employee';
+------------+------------+
|INDEX_NAME|IS_VISIBLE|
+------------+------------+
|idx1|NO|
|idx2|NO|
|PRIMARY|YES|
+------------+------------+
mysql>SHOWINDEXESFROMemployee;
***************************1.row***************************
Table:employee
Non_unique:1
Key_name:idx1
Seq_in_index:1
Column_name:department_id
Collation:A
Cardinality:0
Sub_part:NULL
Packed:NULL
Null:YES
Index_type:BTREE
Comment:
Index_comment:
Visible:NO
MySQL 8 provides a use_invisible_indexes flag in the optimizer_switch system
variabletocontrolinvisibleindexesusedbythequeryoptimizer.Ifthisflagis
on, then the optimizer uses invisible indexes in execution plan construction,
while if the flag is off, the optimizer ignores invisible indexes. MySQL 8
providesa facility to use an implicit primary key if you have defined a UNIQUE
indexonaNOTNULLcolumn.Onceyoudefinetheindexonthisfield,MySQL8
doesnotallowyoutomakeitinvisible.Inordertounderstandthisscenario,let's
take one example with the following table. Let's try to execute the following
commandtomaketheidx1indexinvisible:
CREATETABLEtable2(
field1INTNOTNULL,
field2INTNOTNULL,
UNIQUEidx1(field1)
)ENGINE=InnoDB;
Theserverwillnowgiveanerror,asshowninthefollowingcommands:
mysql>ALTERTABLEtable2ALTERINDEXidx1INVISIBLE;
ERROR3522(HY000):Aprimarykeyindexcannotbeinvisible
Nowlet'saddtheprimarykeyintothetable,usingthefollowingcommand:
ALTERTABLEtable2ADDPRIMARYKEY(field2);
Now,wewilltrytomaketheidex1invisible.Thistime,theserverallowsit,as
showninthefollowingcommands:
mysql>ALTERTABLEtable2ALTERINDEXidx1INVISIBLE;
QueryOK,0rowsaffected(0.06sec)
Records:0Duplicates:0Warnings:0
<strong>CREATETABLEt1(</strong><br/><strong>aINT,bINT,
</strong><br/><strong>INDEXidx1(aASC,bASC),</strong><br
/><strong>INDEXidx2(aASC,bDESC),</strong><br/><strong>
INDEXidx3(aDESC,bASC),</strong><br/><strong>INDEXidx4
(aDESC,bDESC)</strong><br/><strong>);</strong>
<strong>ORDERBYaASC,bASC--optimizercanuse
idx1</strong><br/><strong>ORDERBYaDESC,bDESC--
optimizercanuseidx4</strong><br/><strong>ORDERBYaASC,b
DESC--optimizercanuseidx2</strong><br/><strong>ORDERBY
aDESC,bASC--optimizercanuseidx3</strong>
<strong>Query1:SELECT*FROMt1ORDERBYaDESC;
</strong><br/><strong>Query2:SELECT*FROMt1ORDERBYa
ASC;</strong><br/><strong>Query3:SELECT*FROMt1ORDER
BYaDESC,bASC;</strong><br/><strong>Query4:SELECT*
FROMt1ORDERBYaASC,bDESC;</strong><br/>
<strong>Query5:SELECT*FROMt1ORDERBYaDESC,b
DESC;</strong><br/><strong>Query6:SELECT*FROMt1
ORDERBYaASC,bASC;</strong>
ThefollowingstatisticalgraphisprovidedbyMySQL8on10million
rows,withrespecttothepreviouslymentionedqueries:
Reference:https://mysqlserverteam.com/mysql-8-0-labs-descending-
indexes-in-mysql/
Therearesomeimportantpointsthatyoushouldrememberatthetime
ofusingdescendingindexes,whichareasfollows:
Allthedatatypessupportedbyascendingindexesarealso
supportedbydescendingindexes.
DescendingindexesaresupportedforBTREEbutnotforHASH,
FULLTEXT,andSPATIALindexes.IfyoutrytouseASCandDESC
keywordsexplicitlyforHASH,FULLTEXT,andSPATIALindexes,
thenMySQL8willgenerateanerror.
DescendingindexesonlysupportInnoDBstorageengines,butthe
InnoDBSQLparserdoesnotusedescendingindexes.Change
bufferingisnotsupportedforsecondaryindexesiftheprimary
keyincludesadescendingindex.
DISTINCTcanuseanyindex,includingadescendingkey,butfor
MIN()/MAX(),nodescendingkeypartsareused.
Bothnon-generatedandgeneratedcolumnsallowuseof
descendingindexes.
Summary
Everythingbecomesveryinterestingwhenyouareawareofhowitworks,right?
Wehopeyouhavefoundthesamethingaboutindexinginthischapter.Wehave
covered very useful information which will help you to define indexes on the
right columns to get better performance. In addition to that, we have also
describedvarioustypesofindexingwiththeirstoragestructures.
Inthenextchapter,wewillprovideyouwithinformationaboutreplication.We
willexplaintheconfigurationandimplementationofreplicationindetail.
ReplicationinMySQL8
Inthepreviouschapter,wediveddeepintoMySQL8indexing.Indexesarean
importantentityforanydatabasemanagementsystem.TheyhelpimproveSQL
query performance by limiting the number of records to be visited. Database
administrators working on performance improvement must be aware of this
important technique. This chapter explains in detail the types of indexes and
theiradvantages.ThischapteralsoexplainshowindexingworksinMySQL8.
It'sgoingtobeaprettyinformativechapter!
Moving further along the same line, in this chapter, we will discuss database
replication.
Howmucharewealreadyawareaboutdatabasereplication?Itdoesn'tactually
matter.
This chapter covers insightful details about database replication. If you have
priorknowledgeofdatabasereplication,thischapterwilladdtoit.Ifyouhave
only just heard about it for the first time, you will find every detail that is
required to make it work in this chapter. So, are we ready to jump in? The
followingisalistoftopicsthatwewillbecoveringinthischapter:
Overviewofreplication
Configuringreplication
Implementingreplication
Groupreplicationversusclustering
Replicationsolutions
Overviewofreplication
Wewillwalkthroughthebasicsofdatabasereplicationinthissection.Wewill
understandwhatreplicationis,theadvantagesitprovides, andthescenariosin
whichreplicationcanbebeneficial.
<strong><spanclass="tokenconstant">GTID</span><span
class="tokenattr-value"><spanclass="tokenpunctuation">=</span>
source_id:transaction_id</span></strong>
<strong>1A22AF74<spanclass="tokenoperator">-
</span>17AC<spanclass="tokenoperator">-</span>E111<span
class="tokenoperator">-</span>393E<spanclass="tokenoperator">-
</span>80C49AB653A2:1</strong>
Thesequencenumberfortransactionscommittedstartswith1.Itcan
neverbe0.
AGTID-basedMySQLreplicationmethodistransactionalandsothis
iswhyitismorereliablethanabinarylogfile-basedreplication
method.GTIDguaranteesthereplicationaccuracyandconsistency
betweenmasterandslavedatabasesaslongasallthetransactions
committedonmasterdatabaseservershavealsobeenappliedonallof
theslavedatabaseservers.
Asmentionedearlier,MySQLdatabasereplicationisusually
asynchronous.However,MySQL8supportsdifferenttypesof
synchronizationforreplication.Theusualmethodofsynchronization
isasynchronous.Itmeansoneserveractsasamasterdatabaseserver.
Itwritesalleventstoabinarylogfile.Otherdatabaseserversactas
slaves.Slavedatabaseserversreadandcopyposition-basedevent
recordswithinbinarylogfilesfromthemasterdatabaseserver.So,it
isalwaysfromamasterdatabaseservertoaslavedatabaseserver.
MySQL8alsosupportssemisynchronoussynchronizationmethods.
Insemisynchronousmethodsofreplication,anytransaction
committedonamasterdatabaseserverisblockeduntilthemaster
databaseserverreceivesacknowledgementfromatleastoneofthe
slavedatabaseserversthatithasreceivedandloggedthetransaction
event.Delayedreplicationisanotherreplicationmethodsupportedby
MySQL8.Indelayedreplication,slavedatabaseserversintentionally
logthetransactioneventbehindmasterdatabaseserversbysome
amountoftime.
AdvantagesofMySQLreplication
As we are now familiar with what MySQL database replication is, it's time to
assessiftheaddedcomplexityofmaintainingmultipledatabaseserversisworth
itornot.
TheadvantagesofMySQL8databasereplicationareasfollows:
1. Scale out solutions: As described earlier, usually web applications are
read-heavy applications. The read operations are much higher in number
than the write operations. The applications provide features that require
heavy,complexSQLqueriestobeexecutedonthedatabaseserver.These
arenotthequeriesthattakemillisecondstoexecute.Suchcomplexqueries
maytakeafewsecondstominutesforexecution.Executionofsuchqueries
putupheavyloadondatabaseserver.Insuchcases, itisalways betterto
have such read operations performed on a separate database server than
masterdatabaseservers.
Write database operations will always be performed on master database
servers.Doyouknowwhy?It'sbecauseittriggersdatabasemodifications.
Events of these modifications must be written to binary log files for
replicationsynchronizationbyslaveservers.
Also, the synchronization is from master to slaves. So, if we performed
writedatabaseoperationsonslaves,thosewillneverbeavailableonmaster
databaseservers.Thisapproachimprovesperformanceofwriteoperations
with increased speed for read operations as the read operations are
performedacrossthenumberofslaveservers.
2. DataSecurity:Security,ingeneral,isanimportantfeaturethateveryweb
applicationneeds.
The security can on at an application layer or on a database layer. Data
securityprotectsagainstlossofdata.Datasecurityisachievedbybacking
up a database on a regular basis. If replication is not set up, backing up
production databases requires the application to be put on maintenance
mode. This is required because simultaneous access to a database by an
applicationandthebackupprocessmaycorruptthedata.
Withreplicationinplace,wecanuseoneoftheslavesforbackup.Asthe
slavedatabaseserverisalwaysinsynchronizationwiththemasterdatabase
server,wecanbackuptheslavedatabaseserver.Forthat,wecanmakethe
slavedatabaseserverstopreplicatingfromamasterdatabaseserverwhile
thebackupprocessisrunning.Thisdoesn'trequirethewebapplicationto
stop using a master database server. In fact, it doesn't impact the master
databaseserverinanyway.Anotherdatasecurityaspectistoproviderole-
basedaccesstoproductionormasterdatabaseservers.Wecanhaveonlya
fewroleswhocanaccessthemasterdatabaseserverfromthebackend.The
rest of the users or roles have access to the slave database server. This
reducestheriskofaccidentaldatalossbecauseofhumanerror.
3. Analytics: Analytics and reporting are always important features for a
databasebackedapplication.
These features require fetching of information from a database on a
frequent basis so that analysis on the data can be performed. If database
replicationissetup,wecanfetchthedatarequiredforanalyticsfromthe
slave database server without affecting the master database server
performance.
4. Long distance data distribution: It is a common requirement for
application developers to replicate production data on local development
environments. In a database replication enabled infrastructure, a slave
database server can be used to prepare database copy on a development
databaseserverwithoutconstantaccesstothemasterdatabaseserver.
Configuringreplication
In this section, we will learn configuration for different types of MySQL 8
replication methods. It includes step by step instructions for setting up and
configuringreplication.
Binarylogfilebasedreplication
OneofthemostcommontraditionalmethodsofMySQLdatabasereplicationis
thebinarylogfilepositionmethod.Thissectionfocusesonconfigurationofthe
binary log file position method of replication. Before we jump into the
configuration section, it would be good to revise and understand the basics of
binarylogpositionbasedreplication.
Asdescribedearlier,oneoftheMySQLdatabaseserversactsasmasterandthe
restoftheMySQLdatabaseserversbecomeslaves.Themasterdatabaseserver
istheoriginforthedatabasechanges.Themasterdatabaseserverwritesevents
basedonupdatesorchangestothedatabaseinthebinarylogfile.Theformatof
the information record being written in the binary log file varies based on the
databasechangebeingrecorded.
MySQL REPLICATION SLAVE database servers are configured so that they read the
binarylogeventsfromthemasterdatabaseserver.Slavesexecutetheeventson
localdatabasebinarylogfiles.
Thiswayslavessynchronizethedatabasewiththemasterdatabase.Whenslave
databaseserversreadthebinarylogfilefromthemasterdatabaseserver,slaves
getanentirecopyofthebinarylogfile.Oncethebinarylogfileisreceived,itis
uptotheslavesto decidewhich statementsto executeontheslavebinary log
file.Itispossibletospecifythatallstatementsfromthemasterdatabaseserver
binarylogfileshouldbeexecutedontheslavedatabaseserversbinarylogfile.It
isalsopossibletoprocesseventsfilteredbyparticulardatabasesortables.
Onlyslavedatabaseserverscanbeconfiguredtofiltereventsfrom
masterdatabaseserverlogfiles.Itisnotpossibletoconfigurethe
masterdatabaseservertologonlyspecificevents.
MySQL 8 provides a system variable that helps identify the database server
uniquely.
AllthedatabaseserversparticipatinginMySQLreplicationmustbeconfigured
tohaveauniqueID.Eachoftheslavedatabaseserversmustbeconfiguredwith
themasterdatabaseserverhostname,logfilename,andpositionwithinthelog
file. Once set up, it is possible to modify these details from within a MySQL
sessionusingtheCHANGEMASTERTOstatementexecutedontheslavedatabaseserver.
Whentheslavedatabaseserverreadstheinformationfromthemasterdatabase
binary log file, it keeps track of a record of the binary log coordinates. The
binary log coordinates consists of the filename and position within the file,
whichisreadandprocessedfromthemasterdatabaseserver.Theefficiencyof
slavedatabaseserversreadingthebinarylogfilefromthemasterdatabaseserver
is very high because multiple slave database servers can be connected to the
masterdatabaseserverandprocessdifferentpartsofthebinarylogfilefromthe
masterdatabaseserver.Themasterdatabaseserveroperationsremainunaffected
because the connecting and disconnecting of slave database servers from the
masterdatabaseserveriscontrolledbyslavesthemselves.Asmentionedearlier,
eachslavedatabaseserverkeepstrackofthecurrentpositionwithinthebinary
log file. So, it is possible for the slave database server to disconnect and
reconnect with the master database server and resume the binary log file
processing.
A number of methods for setting up database replication are available in
MySQL.The exactmethod forreplication dependson ifdataalreadyexistsin
thedatabaseandhowreplicationisbeingsetup.Eachofthefollowingsections
areastepforconfiguringMySQLreplication.
Replicationmasterconfiguration
Beforewesetupthereplicationmasterdatabaseserver,itmustbeensuredthat
thedatabaseserverhasauniqueIDestablishedandbinaryloggingisenabled.It
may be required to restart the database server after these configurations are
made.ThemasterdatabaseserverbinarylogisthebasisforMySQL8database
replication.
Toenablebinarylogging,thelog_binsystemvariableshouldbesettoON.Binary
loggingisenabledforaMySQLdatabaseserverbydefault.Ifmysqldisusedto
initialize the data directory manually with a --initialize or --initialize-insecure
option, the binary logging is disabled by default. It has to be enabled by
specifyingthe--log-binoption.The--log-binoptionspecifiesthebasenametobe
usedforthebinarylogfiles.
Ifthefilenameisnotspecifiedwiththestartupoption,thebinarylogfilenames
willbeset basedonthedatabase serverhostname.It isrecommendedthat the
binarylogfilenameisspecifiedwiththe--log-binoption.Ifthelogfilenameis
specified with --log_bin=old_host_name-bin, the log filename will be retained even
afterthedatabaseserverhostischanged.
Tosetupthemasterdatabaseserver,opentheMySQLconfigurationfileonthe
masterdatabaseserver:
sudovim/etc/mysql/my.cnf
Intheconfigurationfile,makethefollowingchanges.
Firstofall,findthesectionthatbindstheservertolocalhost:
bind-address=127.0.0.1
ReplacethelocalIPaddresswiththeactualdatabaseserverIPaddress.Thisstep
isimportantbecausetheslavescanaccessthemasterdatabaseserverusingthe
publicIPaddressofthemasterdatabaseserver:
bind-address=175.100.170.1
The following changes are required to configure a unique ID for the master
database server. It also includes the configuration required for setting up the
masterbinarylogfile:
[mysqld]
log-bin=/var/log/mysql/mysql-bin.log
server-id=1
Now,let'sconfigurethedatabasetobereplicatedontheslavedatabaseservers.
Ifmorethanonedatabaseisrequiredtobereplicatedonslavedatabaseservers,
repeatthefollowinglinemultipletimes:
binlog_do_db=database_master_one
binlog_do_db=database_master_two
Once these changes are done, restart the database server using the following
command:
sudoservicemysqlrestart
Now, we have the master database server set up. The next step is to grant
privilegestotheslaveuserasfollows:
mysql>mysql-uroot-p
mysql>CREATEUSER'slaveone'@'%'IDENTIFIEDBY'password';
mysql>GRANTREPLICATIONSLAVEON*.*TO'slaveone'@'%'IDENTIFIEDBY'password';
Theprecedingcommandscreatestheslaveuser,grantsprivilegesonthemaster
databaseserver,andflushesdatabasecachedprivileges.
Now,wehavetobackupthedatabasethatwewanttoreplicate.Wewillbackup
thedatabaseusingthemysqldumpcommand.Thisdatabasewillbeusedforcreating
theslavedatabase.Themasterstatusoutputdisplaysthenameofthebinarylog
filename,currentposition,andthenameofthedatabasetobereplicated:
mysql>USEdatabase_master_one;
mysql>FLUSHTABLESWITHREADLOCK;
mysql>SHOWMASTERSTATUS;
+------------------+----------+---------------------+------------------+
|File|Position|Binlog_Do_DB|Binlog_Ignore_DB|
+------------------+----------+---------------------+------------------+
|mysql-bin.000001|102|database_master_one||
+------------------+----------+---------------------+------------------+
1rowinset(0.00sec)
mysqldump-uroot-pdatabase_master_one>database_master_one_dump.sql
Before we take the database backup using the mysqldump command, we have to
lock the database to check the current position. This information will be used
latertosetuptheslavedatabaseserver.
After the database dump is taken, the database should be unlocked using the
followingcommands:
mysql>UNLOCKTABLES;
mysql>QUIT;
We are done with all the configuration required to set up a replication master
databaseserverandmakeitaccessiblebytheREPLICATIONSLAVEdatabaseservers.
Thefollowingoptionshaveanimpactonthemasterdatabaseserversetup:
1. innodb_flush_log_at_trx_commit=1 and sync_binlog=1 options should be set to
achieve higher durability and consistency. The options can be set in the
my.cnfconfigurationfile.
2. The skip-networking option must not be enabled. If it is enabled, the slave
cannotcommunicatewiththemasteranddatabasereplicationfails.
REPLICATION SLAVE
configuration
Similar to the master database server, each slave database server must have a
uniqueID.Oncesetup,thiswillrequiredatabaseserverrestart:
[mysqld]
server-id=2
Forsettingupmultipleslavedatabaseservers,auniquenonzeroserver-idmust
be configured that is different from that of master or any other slave database
servers.Binaryloggingonaslavedatabaseserverisnotrequiredforreplication
tobesetup.Ifenabled,abinarylogfileonaslavedatabaseservercanbeused
fordatabasebackupsandcrashrecovery.
Now,createanewdatabasethatwillbecomethereplicaofthemasterdatabase
and import the database from the database dump prepared from the master
databaseasfollows:
mysql>CREATEDATABASEdatabase_slave_one;
mysql>QUIT;
#mysql-uroot-pdatabase_slave_one</path/to/database_master_one_dump.sql
Now,wehavetoconfigureafewotheroptionsinthemy.cnffile.Likethebinary
log, a relay log consists of numbered files with database change events as
contentsofthe file.It alsocontainsan indexfile thathasthe namesofallthe
used relay log files. The following configurations set the relay log file, binary
logfile,andnameoftheslavedatabase,whichisareplicaofthemasterdatabase
asfollows:
relay-log=/var/log/mysql/mysql-relay-bin.log
log_bin=/var/log/mysql/mysql-bin.log
binlog_do_db=database_slave_one
A database server restart is required after this configuration change. The next
stepistoenableslavereplicationfromwithinMySQLshellprompt.Executethe
followingcommandtosetthemasterdatabaseinformationrequiredbytheslave
databaseserver:
mysql>CHANGEMASTERTOMASTER_HOST='12.34.56.789',MASTER_USER='slaveone',MASTER_PASSWORD='password',MASTER_LOG_FILE='mysql-bin.000001',MASTER_LOG_POS=103;
Asafinalstep,activatetheslaveserver:
mysql>STARTSLAVE;
If the binary logging is enabled on the slave database server, a slave can
participateinacomplexreplicationstrategy.Insuchareplicationsetup,database
serverA acts as a master for database server B.B acts as a slave to the Amaster
databaseserver.Now,BinturncanactasamasterdatabaseserverfortheCslave
databaseserver.Somethinglikethiscanbeseenasfollows:
A->B->C
Addingslavestoreplication
It is possible to add a new slave database server to an existing replication
configuration.Thisdoesn'trequirethemasterdatabaseservertobestopped.The
approach should be to make a copy of an existing slave database server. Once
copied,wehavetomodifythevalueforaserver-idconfigurationoption.
Thefollowinginstructionssetupanewslavedatabasetoanexistingreplication
configuration. First, an existing slave database server should be shut down as
follows:
mysql>mysqladminshutdown
Now,adatadirectoryfromtheexistingslaveshouldbecopiedtothenewslave
database server. Along with the data directory, binary logs and relay log files
mustbecopiedaswell.Itisrecommendedtousethesamevaluefor--relay-log
forthenewslavedatabaseserverasthatoftheexistingslavedatabaseserver.
Ifthemasterinfoandrelayloginforepositoriesusefilesthenthosefilesmustbe
copied from an existing slave database server to a new slave database server.
These files hold a master's current binary log coordinates and a slave's relay
logs.
Now,starttheexistingslaveserverthatwasstoppedearlier.
Now,weshouldbeabletostartthenewslavedatabaseserver.Wemusthavethe
uniqueserver-idconfiguredbeforestartingthenewslaveserver,ifitisnotsetup
already.
<strong>GTID=source_id:transaction_id</strong>
<strong>gtid_set:</strong><br/><strong>uuid_set[,uuid_set]...
</strong><br/><strong>|''</strong><br/><br/><strong>uuid_set:
</strong><br/><strong>uuid:interval[:interval]...</strong><br/><br
/><strong>uuid:</strong><br/><strong>hhhhhhhh-hhhh-hhhh-hhhh-
hhhhhhhhhhhh</strong><br/><br/><strong>h:</strong><br/>
<strong>[0-9|A-F]</strong><br/><br/><strong>interval:</strong>
<br/><strong>n[-n]</strong><br/><strong>(n>=1)</strong>
<strong>[mysqld]</strong><br/><strong>server-id=1</strong><br
/><strong>log-bin=mysql-bin</strong><br/>
<strong>binlog_format=ROW</strong><br/><strong>gtid_mode=
on</strong><br/><strong>enforce_gtid_consistency</strong><br/>
<strong>log_slave_updates</strong>
<strong>>CREATEUSER'slaveuser'@'%'IDENTIFIEDBY
'password';</strong><br/><strong>>GRANTREPLICATION
SLAVEON*.*TO'slaveuser'@'%'IDENTIFIED<br/>BY
'password';</strong><br/><strong>>mysqldump-uroot-p
databaseName>databaseName.sql</strong>
<strong>>mysql-uroot-pdatabaseName<
/path/to/databaseName.sql</strong>
<strong>[mysqld]</strong><br/><strong>server_id=2</strong>
<br/><strong>log_bin=mysql-bin</strong><br/><strong>
binlog_format=ROW</strong><br/><strong>
skip_slave_start</strong><br/><strong>gtid_mode=on</strong>
<br/><strong>enforce_gtid_consistency</strong><br/><strong>
log_slave_updates</strong>
<strong>sudoservicemysqlrestart</strong>
<strong>>CHANGEMASTERTO
MASTER_HOST='170.110.117.12',MASTER_PORT=3306,
</strong><br/><strong>MASTER_USER='slaveuser',
MASTER_PASSWORD='password',
MASTER_AUTO_POSITION=1;</strong>
<strong>STARTSLAVE;</strong>
<strong>----GTIDstateatthebeginningofthebackup--</strong>
<br/><strong>mysql>SET
@@GLOBAL.GTID_PURGED='b9b4712a-df64-11e3-b391-
60672090eb04:1-7';</strong>
MySQLmulti-sourcereplication
Thissectionfocusesonreplicatingfrommultipleimmediatemastersinparallel.
The method is known as multi-source replication. With multi-source
replication,aREPLICATIONSLAVEreceivestransactionsfrommultiplesourcesatthe
sametime.AchanneliscreatedbyaREPLICATIONSLAVEforeachmasterfromwhich
itshouldreceivetransactions.
The multi-source replication configuration requires at least two masters and a
slavetobeconfigured.Themasterscanbeconfiguredusingbinarylogposition
basedreplicationorGTID-basedreplication.Replicationrepositoriesarestored
inFILEorTABLEbasedrepositories.ATABLEbasedrepositoryiscrashsafe.MySQL
multi-sourcereplicationrequiresaTABLEbasedrepository.Therearetwowaysto
setupaTABLErepository.
One is to start mysqld with options as follows: mysqld —master-info-
repostiory=TABLE&&–relay-log-info-repository=TABLE
Another preferred way of doing this is to modify the my.cnf file as follows:
[mysqld]
master-info-repository=TABLE
relay-log-info-repository=TABLE
ItispossibletomodifyanexistingREPLICATIONSLAVEthatisusingaFILErepository
to use a TABLE repository. The following commands convert the existing
repositoriesdynamically:STOPSLAVE;
SETGLOBALmaster_info_repository='TABLE';
SETGLOBALrelay_log_info_repository='TABLE';
The following commands can be used to add a new GTID-based replication
master to an existing multi-source REPLICATION SLAVE. It adds a master to the
existing slave channel: CHANGE MASTER TO
MASTER_HOST='newmaster', MASTER_USER='masteruser',
MASTER_PORT=3451, MASTER_PASSWORD='password',
MASTER_AUTO_POSITION=1FORCHANNEL'master-1';
Thefollowingcommandscanbeusedtoaddanewbinarylogfilepositionbased
replicationmastertoanexistingmulti-sourceREPLICATIONSLAVE.Itaddsamasterto
the existing slave channel: CHANGE MASTER TO
MASTER_HOST='newmaster', MASTER_USER='masteruser',
MASTER_PORT=3451, MASTER_PASSWORD='password'
MASTER_LOG_FILE='master1-bin.000006', MASTER_LOG_POS=628
FORCHANNEL'master-1';
ThefollowingcommandsSTART/STOP/RESETalltheconfiguredreplicationchannels:
STARTSLAVEthread_types;--Tostartallchannels
STOPSLAVEthread_types;--Tostopallchannels
RESETSLAVEthread_types;--Toresetallchannels
The following commands START/STOP/RESET a named channel using a FOR CHANNEL
clause:STARTSLAVEthread_typesFORCHANNELchannel;
STOPSLAVEthread_typesFORCHANNELchannel;
RESETSLAVEthread_typesFORCHANNELchannel;
<strong>mysql>SHOWSLAVESTATUS\G</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>
Slave_IO_State:Waitingformastertosendevent</strong><br/>
<strong>Master_Host:master1</strong><br/><strong>
Master_User:root</strong><br/><strong>Master_Port:
3306</strong><br/><strong>Connect_Retry:60</strong><br/>
<strong>Master_Log_File:mysql-bin.000004</strong><br/>
<strong>Read_Master_Log_Pos:931</strong><br/><strong>
Relay_Log_File:slave1-relay-bin.000056</strong><br/><strong>
Relay_Log_Pos:950</strong><br/><strong>
Relay_Master_Log_File:mysql-bin.000004</strong><br/><strong>
Slave_IO_Running:Yes</strong><br/><strong>
Slave_SQL_Running:Yes</strong><br/><strong>
Replicate_Do_DB:</strong><br/><strong>Replicate_Ignore_DB:
</strong><br/><strong>Replicate_Do_Table:</strong><br/>
<strong>Replicate_Ignore_Table:</strong><br/><strong>
Replicate_Wild_Do_Table:</strong><br/><strong>
Replicate_Wild_Ignore_Table:</strong><br/><strong>Last_Errno:
0</strong><br/><strong>Last_Error:</strong><br/><strong>
Skip_Counter:0</strong><br/><strong>Exec_Master_Log_Pos:
931</strong><br/><strong>Relay_Log_Space:1365</strong><br/>
<strong>Until_Condition:None</strong><br/><strong>
Until_Log_File:</strong><br/><strong>Until_Log_Pos:0</strong>
<br/><strong>Master_SSL_Allowed:No</strong><br/><strong>
Master_SSL_CA_File:</strong><br/><strong>
Master_SSL_CA_Path:</strong><br/><strong>Master_SSL_Cert:
</strong><br/><strong>Master_SSL_Cipher:</strong><br/>
<strong>Master_SSL_Key:</strong><br/><strong>
Seconds_Behind_Master:0</strong><br/>
<strong>Master_SSL_Verify_Server_Cert:No</strong><br/>
<strong>Last_IO_Errno:0</strong><br/><strong>Last_IO_Error:
</strong><br/><strong>Last_SQL_Errno:0</strong><br/><strong>
Last_SQL_Error:</strong><br/><strong>
Replicate_Ignore_Server_Ids:0</strong>
<strong>mysql>SHOWPROCESSLIST\G;</strong><br/>
<strong>***************************4.row
***************************</strong><br/><strong>Id:
10</strong><br/><strong>User:root</strong><br/><strong>Host:
slave1:58371</strong><br/><strong>db:NULL</strong><br/>
<strong>Command:BinlogDump</strong><br/><strong>Time:
777</strong><br/><strong>State:Hassentallbinlogtoslave;
waitingforbinlogtobeupdated</strong><br/><strong>Info:
NULL</strong>
<strong>mysql>SHOWSLAVEHOSTS;</strong><br/><strong>+--
---------+--------+------+-------------------+-----------+</strong><br/>
<strong>|Server_id|Host|Port|Rpl_recovery_rank|Master_id|
</strong><br/><strong>+-----------+--------+------+-------------------+--
---------+</strong><br/><strong>|10|slave1|3306|0|1|</strong>
<br/><strong>+-----------+--------+------+-------------------+-----------+
</strong><br/><strong>1rowinset(0.00sec)</strong>
<strong>mysql>STOPSLAVE;</strong><br/><strong>mysql>
STARTSLAVE;</strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">STOP</span><spanclass="token
keyword">SLAVE</span><spanclass="token
keyword">IO_THREAD</span><spanclass="tokenpunctuation">;
</span><br/><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">STOP</span><spanclass="token
keyword">SLAVE</span><spanclass="token
keyword">SQL_THREAD</span></strong><spanclass="token
punctuation"><strong>;</strong><br/><br/><strong><span
class="tokenprompt">mysql></span><spanclass="token
keyword">START</span><spanclass="token
keyword">SLAVE</span><spanclass="token
keyword">IO_THREAD</span>;<br/><spanclass="token
prompt">mysql></span><spanclass="token
keyword">START</span><spanclass="token
keyword">SLAVE</span><spanclass="token
keyword">SQL_THREAD</span>;</strong><br/></span>
Implementingreplication
Thebasisforreplicationisthatthemasterdatabaseserverkeepstrackofallthe
changes taking place on the master database. The changes are tracked in the
binary log files in the form of events since the server was started. SELECT
operationsarenotrecordedastheymodifyneitherthedatabasenorthecontents.
EachoftheREPLICATIONSLAVEpullacopyofthebinarylogfilefrommasterinstead
ofamasterdatabasepushingthelogfiletotheslave.Theslaveinturnexecutes
the events as it is read from the master's binary log file. This maintains the
consistency between master and slave servers. In MySQL replication, each slave
functions independently from master and other slave servers. So, it is up to the
slave to request the master's binary log file at a convenient time without
impactingthemasterorslavefunctioning.
The focus for this section of the chapter is on MySQL replication details. We
havealreadyunderstoodthebasics,whichwillhelpusunderstandtheindepth
details.
Replicationformats
As we already know by now, MySQL replication works based on replicating
eventsfromthemasterservergeneratedbinarylogs.Later,theseeventsareread
andprocessedbytheslave.Whatwedonotyetknowistheformatinwhichthe
events are recorded in binary log files. Replication formats is the emphasis of
thissection.
When the events are recorded in the master's binary log files, the replication
format used depends on the binary log format used. Basically, two binary
loggingformatsexist:statementbasedandrowbased.
Withstatement-basedbinarylogging,SQLstatementsarewritteninthemaster's
binarylogfile.ReplicationontheslaveworksbyexecutingtheSQLstatements
on the slave database. This approach is called statement-based replication. It
correspondswiththeMySQLstatement-basedbinaryloggingformat.
ThiswastheonlytraditionalformatthatexisteduntilMySQLversions5.1.4and
earlier.
With row-based binary logging, the events written in the master binary log
indicate how individual table rows changed. Replication in this case works by
the slave copying the events representing changes to the table rows. This is
calledrow-basedreplication.
Row-basedloggingisthedefaultMySQLreplicationmethod.
MySQLsupportsconfigurationtomixstatement-basedandrow-basedlogging.
Thedecisiontousetheloggingformatdependsonthechangebeinglogged.This
is known as mixed-format logging. Statement-based logging is the default
formatwhenmixed-formatloggingisused.Basedonthetypeofstatementsand
storageenginebeingused,thelogautomaticallyswitchestorow-basedformat.
Replication based on the mixed logging format is known as mixed-format
replication.
Thebinlog_formatsystemvariablecontrolstheloggingformatusedinarunning
MySQL server. SYSTEM_VARIABLES_ADMIN or SUPER privileges are required to set the
binlog_formatsystemvariableatasessionorglobalscope.
Statement-based versus row-
basedreplication
In the earlier section, we learned three different logging formats. Each one of
these has its own advantages and disadvantages. In usual cases, mixed format
shouldprovidethebestcombinationofintegrityandperformance.However,to
achieve the best performance from either statement-based or row-based
replication, the advantages and disadvantages described in this section are
helpful.
Statement-basedreplicationisatraditionalandproventechniqueincomparison
withrow-basedreplication.Thenumberofrecordsoreventsrecordedinthelog
files is smaller. If a statement impacts many rows, only one statement will be
writtentothebinarylogfile.Incaseofrow-basedreplication,arecordwillbe
enteredforeverytablerowmodifiedthoughaspartofthesinglestatement.In
essence,thismeansstatement-basedreplicationrequiresmuchlessstoragespace
forlogfiles.Italsomeansbackingupandrestoringorreplicatingtheeventsis
muchquicker.
Alongwiththeadvantagesdescribedpreviously,statement-basedreplicationhas
disadvantagesaswell.AsthereplicationworksbasedontheSQLstatements,it
is possible that not all the statements that modify data can be replicated with
statement-basedreplication.
Afewexamplesaredescribedasfollows:
SQLstatementsdependonauser-definedfunctionthatisnon-deterministic
whenthevaluereturnedbysuchuser-definedfunctionsdependonfactors
otherthantheparameterssuppliedtoit.
UPDATEandDELETEstatementswithaLIMITclausewithoutanORDERBYclauseis
non-deterministic as it is possible that the order may have changed while
replicating.
FOR UPDATEorFOR SHARElocking read statements that useNOWAIT or SKIP LOCKED
options.
User-definedfunctionsmustbeappliedontheslavedatabases.
SQLstatementsusingfunctionssuchasLOAD_FILE(),UUID(),USER(),UUID_SHORT(),
FOUND_ROWS(), SYSDATE(), GET_LOCK(), and so on cannot be replicated properly
usingstatement-basedreplication.
INSERTorSELECTstatementsrequirehighernumberofrowlevellocks.
UPDATEwithtablescanrequireslockingahighernumberofrows.
Complex SQL statements must be evaluated and executed on the slave
databaseserverbeforerowsareinsertedorupdated.
Let'ssee advantagesprovidedbyrow-basedreplication.Row-basedreplication
is the safest form of replication because instead of depending on SQL
statements,itdependsonthevaluesstoredinthetablerows.So,everychange
canbereplicated.ItrequiresfewerrowlocksincaseINSERT...SELECTstatements.
UPDATEandDELETEstatementswithWHEREclausesthatdonotusekeysrequirefewer
rowlevellocks.
Themajordisadvantagewithrow-basedreplicationisthatitgeneratesmoredata
thatmustbelogged.Withstatement-basedreplication,oneDMLSQLstatement
is sufficient for logging though it modifies many rows. In case of row-based
replication,itrequires logging foreveryrow that changed.Thebinary log file
growsveryquicklywithrow-basedreplication.Ittakeslongertimetoreplicate
deterministicuserdefinedfunctionsthatgeneratelargeBLOBvalues.
<strong>mysql>SHOWPROCESSLIST\G</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>Id:
2</strong><br/><strong>User:root</strong><br/><strong>Host:
localhost:32931</strong><br/><strong>db:NULL</strong><br/>
<strong>Command:BinlogDump</strong><br/><strong>Time:
94</strong><br/><strong>State:Hassentallbinlogtoslave;waiting
forbinlogtobeupdated</strong><br/><strong>Info:
NULL</strong>
<strong>mysql>SHOWPROCESSLIST\G</strong><br/>
<strong>***************************1.row
***************************</strong><br/><strong>Id:
10</strong><br/><strong>User:systemuser</strong><br/>
<strong>Host:</strong><br/><strong>db:NULL</strong><br/>
<strong>Command:Connect</strong><br/><strong>Time:
11</strong><br/><strong>State:Waitingformastertosend
event</strong><br/><strong>Info:NULL</strong><br/>
<strong>***************************2.row
***************************</strong><br/><strong>Id:
11</strong><br/><strong>User:systemuser</strong><br/>
<strong>Host:</strong><br/><strong>db:NULL</strong><br/>
<strong>Command:Connect</strong><br/><strong>Time:
11</strong><br/><strong>State:Hasreadallrelaylog;waitingfor
theslaveI/Othreadtoupdateit</strong><br/><strong>Info:
NULL</strong>
Intheoutput,thread10istheslave'sI/Othreadandthread11isthe
slave'sSQLthread.TheI/Othreadiswaitingforthemaster'sbinlog
dumpthreadtosendbinarylogcontents.TheSQLthreadhasreadall
thestatementsloggedintheslaverelaylogs.FromtheTimecolumn,
itcanbedeterminedhowslowtheslaveisrunningbehindthe
master.
Replicationchannels
Areplicationchannelisapathoftransactionflowfromamastertoaslave.This
section explains how channels can be used in replication. The MySQL server
automatically creates a default channel with the name as "" (empty string) on
startup.Thedefaultchannelisalwayspresentandcan'tbecreatedordestroyed
by the user. Replication statements work on the default channel if no other
channel is created. This section describes statements that are applied to
replicationchannelswhenthereexistsatleastonenamedchannel.
In multi-source replication, the slave database server opens multiple channels,
oneforeachmaster.EachchannelhasitsownrelaylogandSQLthreads.The
replicationchannelhasahostnameandportassociation.
Multiplechannelscanbeassignedtothesamehostnameandportcombination.
A maximum of 256 channels can be added to one slave in a multi-source
replication topology in MySQL 8. The channel must have a nonempty unique
name.
TheFORCHANNELclauseisusedwithvariousMySQLstatementsforthereplication
operationstobeperformedonindividualchannels.Theclausecanbeappliedto
thefollowingstatements:
CHANGEMASTERTO
STARTSLAVE
STOPSLAVE
RESETSLAVE
SHOWRELAYLOGEVENTS
FLUSHRELAYLOGS
SHOWSLAVESTATUS
Apartfromthese,thefollowingfunctionshaveanadditionalchannelparameter:
MASTER_POS_WAIT()
WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS()
Formulti-sourcereplicationtoworkcorrectly,thefollowingstartupoptionsmust
beconfigured:
--relay-log-info-repository:Asdescribed earlier,this mustbeset toTABLEfor
multi-source replication. In MySQL 8, the FILE option is deprecated and
TABLEisthedefaultoption.
--master-info-repository:ThismustbesettoTABLE.
--log-slave-updates:Transactionsreceivedfromthemasterarewrittentothe
binarylogs.
--relay-log-purge:Eachchannelpurgesitsownrelaylogsautomatically.
--slave-transaction-retries:SQLthreadsofallchannelsretrytransactions.
--skip-slave-start:Noreplicationthreadsstartonanychannels.
--slave-skip-errors: Execution continues and errors are skipped for all
channels.
--max-relay-log-size=size: The relay log file is rotated after reaching the
maximumsize.
--relay-log-space-limit=size:Upperlimitfortotalsizeofallrelaylogsforeach
individualchannel.
--slave-parallel-workers=value:Numberofslaveparallelworkersperchannel.
--slave-checkpoint-group:WaitingtimebyI/Othread.
--relay-log-index=filename:Eachchannel'srelaylogindexfilename.
--relay-log=filename:Eachchannel'srelaylogfilename.
--slave-net-timeout=N:EachchannelwaitsforNsecondstocheckforbroken
connection.
--slave-skip-counter=N:EachchannelskipsNeventsfromthemaster.
Replicationrelayandstatuslogs
TheREPLICATIONSLAVEservercreateslogsthatholdthebinarylogeventssentfrom
themasterdatabase
servertotheslavedatabaseserver.Theinformationisrecordedaboutthecurrent
statusandlocationintherelaylog.Threetypesoflogsareusedinthisprocess:
1. Relaylog:Therelayloghaseventssentfromthemaster'sbinarylog.The
eventsarewritten
byaslave'sI/Othread.Eventsfromtheslave'srelaylogareexecutedonthe
slave
bytheslave'sSQLthread.
2. Master info log: The master info log has information about status and
currentconfigurationforthe
slave's connection to the master database server. The information held by
themaster
infologincludeshostname,logincredentials,andcoordinatesindicatinga
slave's
position on reading the master's binary log. These logs are written to the
mysql.slave_master_infotable.
3. Relayloginfolog:Therelayloginfologstoresinformationregardingthe
executionpointwithinthe
slave's relay log. The relay log info log is written in a
mysql.slave_relay_log_infotable.
No attempt should be made to insert or update rows in the
slave_master_info or slave_relay_log_info tables manually. This may
causeunexpectedbehavior.ItisnotsupportedinMySQL
replication.
Theslaverelay logconsistsof anindex filealongwith asetof numberedlog
files.
Theindexfilecontainsthenamesofallrelaylogfiles.MySQLdatadirectoryis
the default location for the relay log files. The relay log file indicates an
individually
numbered file containing events. Whereas the relay log denotes the set of
numbered
relaylogfilesandanindexfilecollectively.Theformatforrelaylogfilesis
the same as that of the binary log files. The index filename for relay log is
host_name-relay-bin.indexbydefaultforthedefaultchannelandhost_name-relay-bin-
channel.index for non-default replication channels. The default locations for the
relaylogfile
andrelaylogindexfilecanbeoverriddenwiththe--relay-logand--relay-log-index
serverstartupoptions.Iftheslave'shostnameischangedafterreplicationhas
been set up and the slave uses default host-based relay log filenames, it can
throw
errors such as Failed to open the relay log and Could not find target log
duringrelayloginitialization.Thismayfailthereplication.Sucherrorsmaybe
avoided by using --relay-log and --relay-log-index options to specify relay log
filenamesexplicitly.Usingtheseoptionsonslavesetup
willmakethenamesindependentoftheserver'shostname.
Evaluating replication filtering
rules
Thissectionfocusesonthefilteringrulesandhowserversevaluatetheserules.
Basically,ifthemasterdoesn'tlogthestatement,theslavedoesn'treplicatethe
statement. If the master logs the statement in its binary log file, the slave
receives the statement. However, it is up to the slave database server if it
processesthestatementorignoresit.Optionsareavailableforthemasterserver
to control which databases and tables should be replicated on the slaves. The
recommendedwayistousefiltersontheslavetocontroltheeventsthatareto
beexecutedontheslavedatabaseserver.Thedecisionaboutwhethertoexecute
or ignore the statements received from the master are made based on the --
replicate-* options used when the slave was started. Once the slave server is
started, the CHANGE REPLICATION FILTER statement can be used to set the options
dynamically.
All replication filtering options follow the same rules for case
sensitivity as names of databases and tables, including the
lower_case_table_namessystemvariable.
Groupreplication
Thissectionofthechapterexplainswhatgroupreplicationis,settingupgroup
replication, configure and monitor group replication. Basically, MySQL group
replication is a plugin that enables us to create elastic, highly-available, fault-
tolerantreplicationtopologies.
Thepurposeofthegroupreplicationistocreateafaulttolerantsystem.Tocreate
a fault tolerant system, the components should be made redundant. The
component should be removed without impacting the way system operates.
There are challenges in setting up such a system. The complexity of such a
system is of a different level. Replicated databases require maintenance and
administration of several servers instead of just one. The servers cooperate
together to create a group, which raises the problems related to network
partitioning and split-brain scenarios. So, the ultimate challenge is to have
agreementfrommultipleserversonthestateofthesystemanddataafterevery
changeappliedonthesystem.Thismeansthattheserversneedtooperateasa
distributedstatemachine.
MySQL group replication can provide such a distributed state machine
replicationwithstrongcoordinationbetweenservers.Theserversthatbelongto
thesamegroupcoordinatethemselvesautomatically.Inagroup,onlyoneserver
accepts updates at a time. The election of primary is done automatically. This
modeisknownassingle-primarymode.
MySQLprovidesagroupmembershipservice,whichisresponsibleforkeeping
theviewofthegroupconsistentandavailableforallservers.Theviewiskept
updated when the servers join or leave the group. In case, any of the servers
leaves the group unexpectedly, the failure detection mechanism notifies the
groupaboutviewchange.
Thisbehaviorisautomatic.
Themajorityofthegroupmembershavetoagreeontheorderofthetransaction
tocommitintheglobalsequenceoftransactions.Itisuptotheindividualserver
todecidewhetherthetransactionshouldbecommittedoraborted,butallservers
make the same decision. The system does not proceed until the members are
unabletoreachtoagreementasaresultofsplitduetonetworkpartition.This
meansthesystemhasbuilt-in,automatic,split-brainprotectionmechanism.All
thisisdonebyGroupCommunicationSystem(GCS)protocols.Itprovidesa
failure detection mechanism, group membership service, safe and completely
orderedmessagedelivery.TheimplementationofthePaxosalgorithmisatthe
coreofthistechnology,whichactsasthegroupcommunicationengine.
Primary-secondary replication
versusgroupreplication
Thissectionfocusesonsomebackgrounddetailsofhowreplicationworks.This
willbeusefulinunderstandingtherequirementsforgroupreplicationandhowit
isdifferentfromtheclassicasynchronousMySQLreplication.
The following figure showcases how traditional asynchronous primary-
secondaryreplicationworks.Theprimaryisthemasterandthesecondaryisone
ormoreslavesconnectedtothemaster,asshowninthefollowingfigure:
Figure1.MySQLAsynchronousReplication
MySQLalsosupportssemisynchronousreplicationinwhichthemaster waits
for at least one of the slaves to acknowledge the transaction receipt:
Figure2.MySQLSemisynchronousReplication
Thebluearrowsinthefiguresindicatethemessagespassedbetweenserversand
theclientapplication.
With group replication, a communication layer is provided that guarantees
atomic messages and total order message delivery. All read-write transactions
are committed only after they are approved by the group. The read only
transactionsarecommittedimmediatelyasitdoesnotneedcoordination.So,in
groupreplication,thedecisiontocommitatransactionornotisnotunilateralby
theoriginatingserver.Whenthetransactionisreadyforcommit,theoriginating
server broadcasts the write values and corresponding write set. All servers
receivethesamesetoftransactionsinthesameorder.So,allserversapplythe
same transactions in the same order. This way all servers remain consistent
withinthegroup:
Figure3.MySQLGroupReplicationProtocol
Groupreplicationconfiguration
Thissectionfocusesonconfiguringgroupreplication.
Firstofall,openthemy.cnfconfigurationfileandaddthefollowingentriesinthe
mysqldsectionasfollows:
[mysqld]
gtid_mode=ON
enforce_gtid_consistency=ON
master_info_repository=TABLE
relay_log_info_repository=TABLE
binlog_checksum=NONE
log_slave_updates=ON
log_bin=binlog
binlog_format=ROW
transaction_write_set_extraction=XXHASH64
loose-group_replication_bootstrap_group=OFF
loose-group_replication_start_on_boot=OFF
loose-group_replication_ssl_mode=REQUIRED
loose-group_replication_recovery_use_ssl=1
These are general configurations related to global transaction IDs and binary
loggingrequiredforgroupreplication.
Thenextstepistosetupgroupreplicationconfigurations.Theseconfigurations
include group UUID, group members white listing, and indicating seed
members:
#Sharedreplicationgroupconfiguration
loose-group_replication_group_name="929ce641-538d-415d-8164-ca00181be227"
loose-group_replication_ip_whitelist="177.110.117.1,177.110.117.2,177.110.117.3"
loose-group_replication_group_seeds="177.110.117.1:33061,177.110.117.2:33061,177.110.117.3:33061"
...Choosing
The following configuration is required for deciding whether a single-master
groupormulti-mastergroupistobesetup.Forenablingthemulti-mastergroup,
uncomment
loose-group_replication_single_primary_modeand
loose-group_replication_enforce_update_everywhere_checks directives. It will set up a
multi-masterormulti-primarygroup:
...
#SingleorMulti-primarymode?Uncommentthesetwolines
#formulti-primarymode,whereanyhostcanacceptwrites
loose-group_replication_single_primary_mode=OFF
loose-group_replication_enforce_update_everywhere_checks=ON
Itmustbeensuredthattheseconfigurationsarethesameonalltheservers.Any
changestotheseconfigurationsrequireMySQLgroupstoberestarted.
Thefollowingconfigurationsaredifferentoneachoftheserversinthegroup:
...
#Hostspecificreplicationconfiguration
server_id=1
bind-address="177.110.117.1"
report_host="177.110.117.1"
loose-group_replication_local_address="177.110.117.1:33061"
Theserver-idmustbeuniqueacrossallserversinthegroup.Theport33061is
the one used by members to coordinate for group replication. MySQL server
restartisrequiredafterthesechangesaremade.
Ifnotalreadydone,wehavetoallowaccesstotheseportsusingthefollowing
commands:
sudoufwallow33061
sudoufwallow3306
The next step is to create a replication user and enable the replication plugin.
Thereplicationuserisrequiredforeachservertoestablishgroupreplication.We
needtoturnbinaryloggingoffduringthereplicationusercreationprocessasthe
userwillbedifferentforeachserver,asshowninthefollowingblock:
SETSQL_LOG_BIN=0;
CREATEUSER'mysql_user'@'%'IDENTIFIEDBY'password'REQUIRESSL;
GRANTREPLICATIONSLAVEON*.*TO'mysql_user'@'%';
FLUSHPRIVILEGES;
SETSQL_LOG_BIN=1;
Now, use CHANGE MASTER TO to configure the server to use the credentials for the
group_replication_recoverychannel:
CHANGEMASTERTOMASTER_USER='mysql_user',MASTER_PASSWORD='password'FORCHANNEL'group_replication_recovery';
Now,weareallsettoinstalltheplugin.Connecttotheserverandexecutethe
followingcommand:
INSTALLPLUGINgroup_replicationSONAME'group_replication.so';
Usethefollowingstatementtoverifyifthepluginisactivatedornot:
SHOWPLUGINS;
Thenextstepistostartupthegroup.Executethefollowingstatementsonone
memberofthegroup:
SETGLOBALgroup_replication_bootstrap_group=ON;
STARTGROUP_REPLICATION;
SETGLOBALgroup_replication_bootstrap_group=OFF;
Now,wecanstartgroupreplicationonanotherserver:
STARTGROUP_REPLICATION;
WecancheckthegroupmemberslistusingthefollowingSQLquery:
mysql>SELECT*FROMperformance_schema.replication_group_members;
+---------------------------+--------------------------------------+
|CHANNEL_NAME|MEMBER_ID|
+---------------------------+--------------------------------------+
|group_replication_applier|13324ab7-1b01-11e7-9dd1-22b78adaa992|
|group_replication_applier|1ae4b211-1b01-11e7-9d89-ceb93e1d5494|
|group_replication_applier|157b597a-1b01-11e7-9d83-566a6de6dfef|
+---------------------------+--------------------------------------+
+---------------+-------------+--------------+
|MEMBER_HOST|MEMBER_PORT|MEMBER_STATE|
+---------------+-------------+--------------+
|177.110.117.1|3306|ONLINE|
|177.110.117.2|3306|ONLINE|
|177.110.117.3|3306|ONLINE|
+---------------+-------------+--------------+
3rowsinset(0.01sec)
Groupreplicationusecases
The MySQL group replication feature provides a way to build fault tolerant
systemsbyreplicating thestateof the systemthroughout a setofservers. The
group replication system stays available as long as the majority of servers are
functioning even if some of the servers fail. Server failures are tracked by a
groupmembershipservice.
The group membership service relies on the distributed failure detector, which
signalsifanyserverleavesthegroup,voluntarilyorduetounexpectedhalt.The
distributedrecoveryprocedureensuresthatwhentheserversjointhegroup,they
arebroughtuptodateautomatically.Therefore,continuousdatabaseserviceis
guaranteed with MySQL group replication. There is one problem though.
Although the database service is available, the clients connected to it must be
redirected to a different server when the server crashes. The group replication
does not attempt to resolve it. It should be dealt with by a connector, load
balancer,router,orsomeothermiddleware.
ThefollowingarethetypicalusecasesofMySQLgroupreplication:
1. Elastic replication: Group replication is suitable for fluid environments
where the number of servers grow or shrink dynamically with minimum
sideeffects.Theexampleiscloud-baseddatabaseservices.
2. Highly available shards: MySQL group replication can be used to
implement highly available write scale-out shards where each replication
groupmapstooneshard.
3. Alternative to master-slave replication: Group replication can be an
answer to contention problems arising in certain situations with single
masterserverreplication.
4. Autonomic systems: MySQL group replication can be deployed for the
automationbuiltintothereplicationprotocol.
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">UPDATE</span>performance_schema<span
class="tokenpunctuation">.</span>setup_instruments<span
class="tokenkeyword">SET</span>ENABLED<spanclass="token
operator">=</span><spanclass="tokenstring">'YES'</span><span
class="tokenkeyword">WHERE</span><spanclass="token
keyword">NAME</span><spanclass="token
operator">LIKE</span><spanclass="token
string">'stage/sql/Applyingbatchofrowchanges%'</span><span
class="tokenpunctuation">;</span></strong>
TheMySQL8replicationprocesscanworkeventhoughthesource
tableonthemasterandthedestinationtableontheslaveusesdifferent
enginetypes.Thedefault_storage_enginesystemvariableisnot
replicated.Thisisahugeadvantageinreplicationwhereindifferent
enginetypescanbeusedfordifferentreplicationscenarios.An
exampleisascale-outscenariowherewewantallreadoperationsto
beperformedontheslavedatabaseserver,whereasallwrite
operationsshouldbeperformedonthemasterdatabaseserver.Insuch
acase,wecanuseatransactionalInnoDBengineonthemasteranda
non-transactionalMyISAMenginetypeontheslavedatabaseserver.
Consideranexampleofanorganizationthatwantstodistributesales
datatodifferentdepartmentstospreadtheloadfordataanalysis.
MySQLreplicationcanbeusedtohaveasinglemasterreplicate
differentdatabasestodifferentslaves.Thiscanbeachievedby
limitingthebinarylogstatementsbyusingthe--replicate-wild-do-
tableconfigurationoptiononeachslave.
OnceMySQLreplicationissetup,asthenumberofslavesconnected
tothemasterincrease,theloadalsoincreases.Thenetworkloadon
themasteralsoincreasesaseachslaveissupposedtoreceiveafull
copyofthebinarylogs.Themasterdatabaseserverisalsobusy
processingrequests.Inthisscenario,itbecomesnecessarytoimprove
theperformance.Oneofthesolutionstoimproveperformanceisto
createadeeperreplicationstructurethatenablesreplicationofa
mastertoonlyoneslave.Therestoftheslavesconnecttotheprimary
slavefortheiroperations.
Summary
In this chapter, we learned insightful details about MySQL 8 replication, what
replicationis,andhowithelpssolvespecificproblems.Wealsolearnedhowto
setupstatement-basedandrow-basedreplicationtypes.Alongtheway,wealso
learnedaboutthesystemvariablesandserverstartupoptionsforreplication.In
thelaterpartofthechapter,wediveddeepintogroupreplicationandhowitis
different from the traditional method of MySQL replication. We also learned
logging and replication formats. Last but not least, we learned different
replicationsolutionsinbrief.Wecoveredalotofstuff,huh?
It'snowtimetomoveontoournextchapter,wherewewillbesettingupseveral
typesofpartitioning,andexploringtheselectionofpartitioning,andpruningof
partitioning.Italsoexplainshowtocopewithrestrictionsandlimitationswhile
partitioning. The reader will be able to understand which type of partitioning
suitsasituationaspertherequirement.
PartitioninginMySQL8
In the previous chapter, replication in MySQL 8 was explained. This included
detailed explanations of replication, configuration, and implementation. The
chapter also explained group replication versus clustering, and covered the
replicationapproachasasolution.
Inthischapter,wewilldopartitioninginMySQL8.Partitioningistheconcept
of managing and maintaining data with specific operations with several
operators,anddefiningrulestocontroloverpartitioning.Basically,itprovidesa
configurationhookformanagingtheunderlyingdatafilesinaspecifiedway.
Wewillcoverthefollowingtopicsonpartitioning:
Overviewofpartitioning
Typesofpartitioning
Partitionmanagement
Partitionselection
Partitionpruning
Restrictionandlimitationinpartitioning
<strong>CREATETABLEtp(tp_idINT,amtDECIMAL(5,2),
trx_dateDATE)</strong><br/><strong>
ENGINE=INNODB</strong><br/><strong>PARTITIONBYHASH
(MONTH(trx_date))</strong><br/><strong>PARTITIONS4;
</strong>
Partitioningisapplicableonallindexesandalldataofthetable.Itis
notapplicableoneitherindexesordata,andviceversaisalsonot
applicable.Itcanbeapplicableonbothindexesanddatatogetherand
itcannotbeappliedonpartofthetable.
Theprecedingtabletphasnouniqueorprimarykeysdefinedbutin
generalpracticeweusuallyhaveprimarykeys,uniquekeys,orboth
aspartofthetable,andpartitioningcolumnchoicedependsupon
thesekeysifanyofthemispresent.Thepartitioningcolumnchoiceis
givenindetailinthepartitioningkeys,primarykeys,anduniquekeys
section.Tosimplifytheconceptofpartitioningtheexamplesgiven
maynotincludethesekeys.
Typesofpartitioning
SeveraltypesofpartitioningaresupportedinMySQL8,listedasfollows:
RANGE Partitioning: Assigns rows to partitions from the column values that
comebetweenthegivenrangeofvalues
LIST Partitioning: Assigns rows to partitions from the column values that
matcheswithoneofthegivensetofvalues
COLUMNSPartitioning:Assignsrowstopartitionswithmultiplecolumnvalues
witheitherRANGEorLISTpartitioning
HASH Partitioning: Assigns partition based on user specified expressions
evaluatedoncolumnvalues
KEY Partitioning: In addition to HASH partitioning, allows the use of multiple
columnvalues
Subpartitioning: In addition to partitioning, allows further division in
partitionedtables,alsoknownascompositepartitioning
Differentrowsofthetablecanbeassignedtodifferentphysicalpartitions;thisis
knownashorizontalpartitioning.Differentcolumnsofthetablecanbeassigned
todifferentphysicalpartitions;thisisknownasverticalpartitioning.MySQL8
currentlysupportshorizontalpartitioning.
FortheLIST,RANGE,andLINEARHASHtypesofpartitioning,thevalueofpartitioning
columnsisgiven tothepartitioning function.Thepartitioning functionreturns
an integer value that is the partition number in which the record should be
stored.Thepartitionfunctionmustbenonrandomandnonconstant.Thepartition
functioncannotcontainqueriesand canusetheSQLexpressionwhichreturns
eitheranintegerorNULL,wheretheintegerasintvalmustfollowtheexpression-
MAXVALUE<=intval<=MAXVALUE.Here,-MAXVALUErepresentsthelowerlimitandMAXVALUE
istheupperlimitfortheintegertypevalue.
Thestorageenginemustbethesameforallpartitionsofthesametable,however
thereisnorestrictiononusingdifferentstorageenginesfordifferentpartitioned
tablesinthesamedatabaseorMySQLserver.
Partitioningmanagement
TherearedifferentwaystouseSQL statementsto modifypartitionedtablesand
perform operations such as add, redefine, merge, drop, or split existing
partitionedtables.Informationaboutpartitionedtablesandpartitionscanalsobe
obtainedwithSQLstatements.
MIN_ROWS and MAX_ROWS can be used to configure the maximum and minimum
numberofrowsandcanbestoredinthepartitiontable.
Partitionselectionandpruning
Explicit selection of partition and subpartition is also provided. It enables row
matchingtothe conditions giveninthe where clause.Inpartition, thepruning
conceptsdescribeddonotscanpartitionswherenopossiblematchingvaluescan
be present, and are applied using queries, whereas partition selection is
applicableforbothqueriesandmanyoftheDMLstatements.
Restrictions and limitations in
partitioning
Stored procedures or functions, user defined functions or plugins, and user
variables or declared variables are restricted in partitioning expressions. There
arealsoseveralrestrictionsandlimitationsapplicabletopartitioninggiveninthe
detailedsection.
Seethefollowinglistforsomeoftheadvantagesofpartitioning:
Partitioningfacilitatesstoringmoredatainonetablethancanbeheldona
filesystempartitionorsingledisk.
Datathathasbecomeuselesscanberemovedeasilybydroppingapartition
orpartitionsthatonlycontaintheuselessdata.Insomecaseswherespecific
data is required to be added separately, this can be done easily with
partitioninginsingleormultiplepartitionsbasedonthespecifiedrule.
Queryoptimizationthatoccursautomaticallybasedonpartitioneddataby
notsearchingfordatainpartitionsthatarenotapplicableasperthewhere
condition.
Inadditiontopartitionpruning,partitionselectionissupportedexplicitlyby
whichwhereclauseisappliedonaspecifiedpartitionormultiplepartitions.
Greater query throughput is achieved by separating data search into
multipledisks.
Typesofpartitioning
Inthissection, youwill understanddifferent typesofpartitioning andalso the
purposeofusingspecificpartitioning.Thefollowingisalistofthepartitioning
typesthatareavailableinMySQL8:
RANGEpartitioning
LISTpartitioning
COLUMNSpartitioning
HASHpartitioning
KEYpartitioning
Subpartitioning
In addition to the above list, we will also see NULLhandling in MySQL 8
Partitioningindetailedsection.
A verycommonuse casefor databasepartitioningis segregatingdata bydate.
MySQL
8 does not support date partitioning, which some database systems provide
explicitly, but it is easy to create partitioning schemes with date, time, or
datetime columns, or that are based on date/time related expressions that
evaluatevaluesfromthesecolumntypes.
You can use the date, time, or datetime types as column values for partition
columnswithoutanymodificationsifusingKEYorLINEARKEYpartitioning,whereas
inotherpartitioningtypesanexpressiongivingbackanintegerorNULLvalueis
required.
Irrespective of which type of partitioning you use, partitions always get
numbered automatically with an integer number in sequence of the partitions
created. If, for example, the table uses four partitions, they are numbered as
0,1,2,and3foreachofthepartitionsaspercreationsequence.
Whenyouspecifynumbersofpartitions,itmustbeevaluatedtoapositive,non
zero integer without any leading zeros. Decimal fractions are not allowed as
partitionnumbers.
Names of partitions are not case-sensitive and should follow conventions or
rules just like other MySQL identifiers such as tables. The options used in
partitiondefinitionarealreadyprovidedbytheCREATETABLEsyntax.
Now,let'slookatpartitionindetailandexamineeachofthetypestolearnhow
theyaredifferenttoeachother.
RANGEpartitioning
Inthistypeofpartitioning,asthenamestates,RANGEisgiveninanexpressionthat
evaluateswhetheravalueliesinthegivenrangeornot.Rangesaredefinedwith
theVALUESLESSTHANoperatorandtheyshouldnotbeoverlappingandcontiguous.
For the next few examples, suppose we are creating a table holding employee
personalrecordsfor25foodstores.Thestoresarenumberedfrom1to25andis
achainof25foodstores,asshowninthefollowingblock:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
);
Nowlet'sdopartitioningofthetable,soyoucanpartitionthetablebyrangeas
peryourneed.Supposeyouconsiderusingdivisiontosplitthedatafiveways
withthestore_idrangeforpartitioning.Forthis,thetablecreationdefinitionwill
lookasfollows:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
)
PARTITIONBYRANGE(store_id)(
PARTITIONp0VALUESLESSTHAN(6),
PARTITIONp1VALUESLESSTHAN(11),
PARTITIONp2VALUESLESSTHAN(16),
PARTITIONp3VALUESLESSTHAN(21),
PARTITIONp4VALUESLESSTHAN(26)
);
So, as per the above partitioning scheme, all inserted rows that contain the
employees working at stores 1 to 5 are stored in the p0 partition, employees
workingatstores6to10arestoredinthep1partition,andsoon.Ifyoutakea
lookatthepartitiondefinition,partitionsareorderedfromthelowesttohighest
store_id column values, and the PARTITION BY RANGE syntax looks similar to
programmingstatementsif…elseif…statements,doesn'tit?
Well,youarethinkingaboutwhatwillhappenifarecordcomeswithstore_id26;
this would result in an error as the server does not know where to place the
record.Therearetwowaystokeepthiserrorfromoccurring:
1. ByusingtheIGNOREkeywordwiththeINSERTstatement.
2. ByusingMAXVALUEinsteadofaspecifiedrange(26).
Andyes,ofcourse,youcanextendthelimitsbyusingtheALTERTABLEstatementto
addnewpartitionsforstores26-30,30-35,andsoon.
Similar to store_id, you could also partition the table based on the job codes -
based on the range of column values. Suppose if 5 digit codes are used for
managementpositions,4digitcodesareusedforofficeandsupportpersonnel,
and3digitcodesareusedforregularworkers,thenthepartitiontablecreation
definitionwouldbeasfollows:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
)
PARTITIONBYRANGE(job_code)(
PARTITIONp0VALUESLESSTHAN(1000),
PARTITIONp1VALUESLESSTHAN(10000),
PARTITIONp2VALUESLESSTHAN(100000)
);
You can also specify partitioning with one of the two columns of date type
values.Suppose youwishto partition basedonthe year eachofthe employee
joined-so bythe value ofYEAR(hired_date). Now the table definition will be as
follows:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
)
PARTITIONBYRANGE(YEAR(hired_date))(
PARTITIONp0VALUESLESSTHAN(1996),
PARTITIONp1VALUESLESSTHAN(2001),
PARTITIONp2VALUESLESSTHAN(2006),
PARTITIONp3VALUESLESSTHANMAXVALUE
);
Accordingtothisscheme,allemployeesrecordedhiredbefore1996willbestored
inthepartitionp0,thenrecordswithahiredatebefore2001willbestoredinthe
partitionp1,recordsbetween2001and2006inp2,andtherestoftherecordswillbe
storedinpartitionp3.
Partition schemes based on time intervals can be implemented using the
followingtwooptions:
1. PartitionthetablebyRANGEanduseafunctionoperatingonthedate,timeor
datetime column values to return an integer value for the partitioning
expression
2. Partition the table by RANGE COLUMN and use the date, time, or datetime
columnsasthepartitioncolumn
RANGE COLUMN is supported in MySQL 8 and is described in detail in the COLUMN
PARTITIONINGsection.
LISTpartitioning
Asthenamestates,LISTpartitioninguseslistsfor tablepartitioning.The listis
comma separated integer values defined while partitioning with VALUES IN
(value_list);here,value_listreferstocommaseparatedintegerliterals.
LIST partitioning is similar to RANGE partitioning in many ways, but there are
differences.Theoperatorusedineachpartitioningisdifferent.Theoperatoruses
a list of comma separated values to be matched with the column value or the
partitionexpressionevaluatingtointegervalue.
Consideringtheemployeetableasanexample,thebasicdefinitionforthetable
usingthecreatetablesyntaxwillbeasfollows:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
);
Supposeyouwishtodistributethese25foodstoresamongfivezones—North,
South, East, West, and Central, with the store ID numbers (1,2,11,12,21,22),
(3,4,13,14,23,24),(5,6,15,16,25), (7,8,17,18), and (9,10,19,20) respectively for
thezones.
Partitioningthetablewiththezoneslistwillprovidethefollowingdefinitionfor
tablepartition:
CREATETABLEemployee(
employee_idINTNOTNULL,
first_nameVARCHAR(30),
last_nameVARCHAR(30),
hired_dateDATENOTNULLDEFAULT'1990-01-01',
termination_dateDATENOTNULLDEFAULT'9999-12-31',
job_codeINTNOTNULL,
store_idINTNOTNULL
)
PARTITIONBYLIST(store_id)(
PARTITIONpNorthVALUESIN(1,2,11,12,21,22),
PARTITIONpSouthVALUESIN(3,4,13,14,23,24),
PARTITIONpEastVALUESIN(5,6,15,16,25),
PARTITIONpWestVALUESIN(7,8,17,18),
PARTITIONpCentralVALUESIN(9,10,19,20)
);
Asyoucanseeintheprecedingstatement,partitioningperzonesmeansitwill
beeasytoupdaterecordsforstoresbasedonzoneswithinparticularpartitions.
Supposetheorganizationsoldthewestzonetoanothercompany;thenyoumight
needtoremoveallemployeerecordsfromthewestzoneusingthepWestpartition
inquery.ExecutingALTER TABLEemployeeTRUNCATE PARTITION pWestwouldbemuch
easierandefficientthantheDELETEstatementDELETE from employee where store_id IN
(7,8,17,18);also,youcanusetheDROPstatementforemployeerecordsremoval-
ALTER TABLE employee DROP PARTITION pWest. Along with the previous statement
execution you will also remove the pWest PARTITION from the table partition
definition,andwillneedtousetheALTERstatementagaintoaddthepWestPARTITION
andrestorethepartitiontableschemeyouhadearlier.
SimilartoRANGEpartitioning,youcanalsouseLISTpartitioningusinghashorkey
to produce composite partitioning, which is also known assubpartitioning. You
will get to know more details on subpartitioning as a dedicated section for
subpartitioningfollows.
In LIST partitioning there is no catch-all mechanism such as MAXVALUE that can
containallpossiblevalues.Instead,youhavetomanagetheexpectedvalueslist
inthevalues_listitself,otherwisetheINSERTstatementwillresultinanerrorwhere
thetablehasnopartitionforvalue9,asinthefollowingexample:
CREATETABLEtpl(
cl1INT,
cl2INT
)
PARTITIONBYLIST(cl1)(
PARTITIONp0VALUESIN(1,3,4,5),
PARTITIONp1VALUESIN(2,6,7,8)
);
INSERTINTOtplVALUES(9,5);
AsyoucanseeintheprecedingINSERTstatement,value9isnotpartofthelist
givenduringpartitionschemaandsothereisanerror.Ifyouusemultiplevalue
insert statements, the same error can result in failure for all inserts and no
recordswillbeinserted;insteadusetheIGNOREkeywordtoavoidsucherrors,asin
thefollowingINSERTstatementexample:
INSERTIGNOREINTOtplVALUES(1,2),(3,4),(5,6),(7,8),(9,11);
COLUMNSpartitioning
Asthenamesuggests,thistypeofpartitioningusescolumnsthemselves.Wecan
usetwoversionsofcolumnpartitioning.OneisRANGECOLUMNandtheotherisLIST
COLUMN. In addition to both RANGE COLUMN and LIST COLUMN partitioning, MySQL 8
supports using non-integer types of column that can be used to define value
rangesorlistvalues.Thelistofpermitteddatatypesareasfollows:
AllcolumntypesofINT,BIGINT,MEDIUMINT,SMALLINT,andTINYINTaresupported
fortheRANGEandLISTpartitioningcolumns,butothernumericcolumntypes
suchasFLOATorDECIMALarenotsupported
DATEandDATETIMEaresupportedbutothercolumntypesrelatingtodateand
timearenotsupportedaspartitioningcolumns
ThestringcolumntypesBINARY,VARBINARY,CHARandVARCHARaresupportedbut
theTEXTandBLOBcolumntypesarenotsupportedaspartitioningcolumns
Now,let'sseeRANGECOLUMNpartitioningandLISTCOLUMNpartitioningindetailoneby
one.
<strong>CREATETABLEtable_name</strong><br/>
<strong>PARTITIONBYRANGECOLUMNS(column_list)
(</strong><br/><strong>PARTITIONpartition_nameVALUES
LESSTHAN(value_list)[,</strong><br/><strong>PARTITION
partition_nameVALUESLESSTHAN(value_list)][,</strong><br
/><strong>...]</strong><br/><strong>)</strong><br/>
<strong>column_list:</strong><br/><strong>column_name[,
column_name][,...]</strong><br/><strong>value_list:</strong><br
/><strong>value[,value][,...]</strong>
<strong>CREATETABLEtrc(</strong><br/><strong>pINT,<br/>
qINT,<br/>rCHAR(3),<br/>sINT<br/>)</strong><br/>
<strong>PARTITIONBYRANGECOLUMNS(p,s,r)(</strong><br
/><strong>PARTITIONp0VALUESLESSTHAN(5,10,'ppp'),
</strong><br/><strong>PARTITIONp1VALUESLESSTHAN
(10,20,'sss'),</strong><br/><strong>PARTITIONp2VALUESLESS
THAN(15,30,'rrr'),</strong><br/><strong>PARTITIONp3
VALUESLESSTHAN(MAXVALUE,MAXVALUE,MAXVALUE)
</strong><br/><strong>);</strong>
<strong>INSERTINTOtrcVALUES(5,9,'aaa',2),(5,10,'bbb',4),
(5,12,'ccc',6);</strong>
<strong>CREATETABLEcustomer_z(</strong><br/><strong>
first_nameVARCHAR(30),<br/>last_nameVARCHAR(30),<br/>
street_1VARCHAR(35),<br/>street_2VARCHAR(35),<br/>city
VARCHAR(15),<br/>renewalDATE<br/>)</strong><br/>
<strong>PARTITIONBYLISTCOLUMNS(city)(</strong><br/>
<strong>PARTITIONpZone_1VALUESIN('Ahmedabad','Surat',
'Mumbai'),</strong><br/><strong>PARTITIONpZone_2VALUES
IN('Delhi','Gurgaon','Punjab'),</strong><br/><strong>PARTITION
pZone_3VALUESIN('Kolkata','Mizoram','Hyderabad'),</strong>
<br/><strong>PARTITIONpZone_4VALUESIN('Bangalore',
'Chennai','Kochi')</strong><br/><br/><strong>);</strong>
SimilartoRANGECOLUMNpartitioning,itisnotrequiredtoprovideany
expressionintheCOLUMNS()clausethatconvertsthecolumnvalueto
anintegerliteral,andnothingotherthanthelistofcolumnnames
itselfispermitted.
<strong>CREATETABLEemployee(</strong><br/><strong>
employee_idINTNOTNULL,</strong><br/><strong>first_name
VARCHAR(30),</strong><br/><strong>last_nameVARCHAR(30),
</strong><br/><strong>hired_dateDATENOTNULLDEFAULT
'1990-01-01',</strong><br/><strong>termination_dateDATENOT
NULLDEFAULT'9999-12-31',</strong><br/><strong>job_code
INTNOTNULL,</strong><br/><strong>store_idINTNOT
NULL</strong><br/><strong>)</strong><br/><strong>PARTITION
BYHASH(store_id)</strong><br/><strong>PARTITIONS4;
</strong>
Intheabovestatement,ifyouexcludethePARTITIONSclause,the
numberofpartitionsautomaticallydefaultstoone.
<strong>CREATETABLEemployee(</strong><br/><strong>
employee_idINTNOTNULL,</strong><br/><strong>first_name
VARCHAR(30),</strong><br/><strong>last_nameVARCHAR(30),
</strong><br/><strong>hired_dateDATENOTNULLDEFAULT
'1990-01-01',</strong><br/><strong>termination_dateDATENOT
NULLDEFAULT'9999-12-31',</strong><br/><strong>job_code
INTNOTNULL,</strong><br/><strong>store_idINTNOT
NULL</strong><br/><strong>)</strong><br/><strong>PARTITION
BYLINEARHASH(YEAR(hired_date))</strong><br/>
<strong>PARTITIONS4;</strong>
Anadvantageofusinglinearhashingisfasterpartitioningoperations,
andadisadvantageislessevendatadistributioncomparedtoregular
hashingpartitioning.
<strong>CREATETABLEtk1(</strong><br/><strong>tk1_idINT
NOTNULLPRIMARYKEY,<br/>noteVARCHAR(50)<br/>)<br
/>PARTITIONBYKEY()<br/>PARTITIONS2;</strong>
<strong>CREATETABLEtk2(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2CHAR(10),</strong><br/>
<strong>cl3DATE</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYLINEARKEY(cl1)</strong><br/>
<strong>PARTITIONS3;</strong>
Asyoucanseeintheprecedingexamplestatement,similartoHASH
partitioning,KEYpartitioningalsosupportsLINEARKEYpartitioning
andhasthesameeffectasLINEARHASHpartitioning.
<strong>CREATETABLEtrs(trs_idINT,soldDATE)</strong><br
/><strong>PARTITIONBYRANGE(YEAR(sold))<br/>
SUBPARTITIONBYHASH(TO_DAYS(sold))<br/>
SUBPARTITIONS2(<br/>PARTITIONp0VALUESLESSTHAN
(1991),<br/>PARTITIONp1VALUESLESSTHAN(2001),<br/>
PARTITIONp2VALUESLESSTHANMAXVALUE<br/>);
</strong>
Asyoucanseeintheprecedingexamplestatement,tabletrshas
threeRANGEpartitionsandeachofthepartitionsp0,p1,p2isfurther
dividedintotwomoresubpartitions.Effectively,theentiretableis
dividedintosixpartitions.
SubpartitioningispossibleontablespartitionedusingRANGEorLIST
partitioning,andsubpartitioningcanusetheKEYorHASHpartitioning
types.Thesyntaxrulesforsubpartitioningarethesameasinregular
partitioning,withtheexceptiontospecifythedefaultcolumninKEY
partitioningasitdoesnottakethecolumnautomaticallyfor
subpartitioning.
Thefollowingisalistofpointstoconsiderwhenusing
subpartitioning:
Numberofpartitionsmustbesameforeachofthepartitions
defined
NamemustbespecifiedwiththeSUBPARTITIONINGclauseor
specifyadefaultoptioninstead
Namesspecifiedforsubpartitioningmustbeuniqueacrossthe
table
HandlingNULLinpartitioning
There is nothing specific to MySQL 8 that disallows NULL in partitioning as a
column value, partitioning expression, or the value from the user-defined
expression. Even if NULL is permitted as a value ,the value returned from the
expression must be an integer and so MySQL 8 has implementation for
partitioningsuchthatittreatsNULLaslessthananynon-NULLvalueasdoneinthe
ORDERBYclause.
BehaviorforNULLhandlingvariesamongdifferenttypesofpartitioning:
HandlingNULLinRANGEpartitioning:IfaNULLvaluecontainedinthecolumn
isinserted,therowwillbeinsertedinthelowestpartitionspecifiedinrange
Handling NULL with LIST partitioning: If the table has a partitioning
definitionwithLIST partitioningand itspartitionsaredefined witha value
listthatexplicitlyspecifiesNULLasavalueinvalue_list,theninsertionwillbe
successful; otherwise, it will give an error table that has no partition
specifiedforNULL
Handling NULL with HASH and KEY partitioning: NULL is handled differently
when table partitioning is defined with HASH or KEY partitioning, and if a
partitionexpressionreturnsNULLitiswrappedwithzerovalue.Sothatbased
onpartitioningtheinsertionoperationwillsuccessfullyinserttherecordto
partitionbeingzero.
Partitionmanagement
There are plenty of ways to use SQL statements in order to modify partitioned
tables—youcandrop,add,merge,split,orredefinepartitionswiththeALTERTABLE
statement. There are also ways to retrieve partitioned tables and partition
information.
Wewillseeeachoftheseinthefollowingsections:
RANGEandLISTpartitionmanagement
HASHandKEYpartitionmanagement
Partitionmaintenance
Obtainpartitioninformation
RANGE and LIST partition
management
PartitionaddinganddroppingishandledinasimilarwayfortheRANGEandLIST
partitiontypes.A tablepartitioned byRANGE or LIST partitioning can be dropped
usingtheALTERTABLEstatementwiththeDROPPARTITIONoptionavailable.
Make sure you have the DROP privilege before executing the ALTER TABLE ... DROP
PARTITION statement. DROP PARTITION will delete all the data and also remove the
partitionfromthetablepartitiondefinition.
The following example illustrates the DROP PARTITION option with the ALTER TABLE
statement:
SET@@SQL_MODE='';
CREATETABLEemployee(
idINTNOTNULLAUTO_INCREMENTPRIMARYKEY,
first_nameVARCHAR(25)NOTNULL,
last_nameVARCHAR(25)NOTNULL,
store_idINTNOTNULL,
department_idINTNOTNULL
)
PARTITIONBYRANGE(id)(
PARTITIONp0VALUESLESSTHAN(5),
PARTITIONp1VALUESLESSTHAN(10),
PARTITIONp2VALUESLESSTHAN(15),
PARTITIONp3VALUESLESSTHANMAXVALUE
);
INSERTINTOemployeeVALUES
('','Chintan','Mehta',3,2),('','Bhumil','Raval',1,2),
('','Subhash','Shah',3,4),('','Siva','Stark',2,4),
('','Chintan','Gajjar',1,1),('','Mansi','Panchal',2,3),
('','Hetal','Oza',2,1),('','Parag','Patel',3,1),
('','Pooja','Shah',1,3),('','Samir','Bhatt',2,4),
('','Pritesh','Shah',1,4),('','Jaymin','Patel',3,2),
('','Ruchek','Shah',1,2),('','Chandni','Patel',3,3),
('','Mittal','Patel',2,3),('','Shailesh','Patel',2,2),
('','Krutika','Dave',3,3),('','Dinesh','Patel',3,2);
ALTERTABLEemployeeDROPPARTITIONp2;
Intheprecedingstatement,afterexecutingtheALTER TABLE employee DROP PARTITION
p2;statement,youcanseethatalldataisremovedfrompartitionp2.Incaseyou
want to remove all the data but also need to keep the table definition andthe
partitioningscheme,youcanusetheTRUNCATEPARTITIONoptiontoachieveasimilar
result.
InordertoaddnewLISTorRANGEpartitionstoexistingpartitionedtablesyoucan
usetheALTERTABLE...ADDPARTITIONstatement.
ByusingtheSHOW CREATE TABLEstatementyoucanverifyandseeiftheALTER TABLE
statement has the desired effect on the table definition and the partitioning
schema.
<strong>CREATETABLEclient(</strong><br/><strong>client_id
INT,</strong><br/><strong>first_nameVARCHAR(25),</strong>
<br/><strong>last_nameVARCHAR(25),</strong><br/><strong>
signedDATE</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYHASH(MONTH(signed))</strong><br/>
<strong>PARTITIONS12;</strong>
<strong>ALTERTABLEclientCOALESCEPARTITION8;
</strong>
Intheprecedingstatementthenumber8representsthenumberof
partitionstoberemovedfromthetable.Youcannotremovemore
partitionsthanalreadyexistinthetablepartitioningschema.
Similarly,youcanaddmorepartitionsusingtheALTERTABLE...ADD
PARTITIONstatement.
<strong>ALTERTABLEtrpREBUILDPARTITIONp0,p1,p2;
</strong>
<strong>ALTERTABLEtopOPTIMIZEPARTITIONp0,p1,p2;
</strong>
<strong>ALTERTABLEtapANALYZEPARTITIONp1,p2;
</strong>
<strong>ALTERTABLEtrpREPAIRPARTITIONp3;</strong>
<strong>ALTERTABLEtcpCHECKPARTITIONp0;</strong>
ThereisanoptiontouseALLinsteadofaspecificpartition,specified
inallaboveoptions,inordertoperformtheoperationonallthe
partitions.
<strong>SHOWCREATETABLEemployee;</strong>
Theoutputfromtheprecedingstatementhasseparateinformationfor
partitioningschema,includingcommoninformationforthetable
schema.
Similarly,youcanretrieveinformationaboutpartitioningfromthe
INFORMATION_SCHEMA.PARTITIONStable.
TheEXPLAINoptiongivesalotofinformationonpartitioningwith
column.Forexampleitgivesnumberofrowsobtainedfromthequery
specifictopartitions.Thepartitionwouldbesearchedasperthequery
statement.Italsogivesinformationaboutkeys.
EXPLAINisalsousedtogetinformationfromnonpartitionedtables.It
doesnotgiveanyerroriftherearenopartitions,butgivesaNULL
valueinthepartitionscolumn.
Partitionselectionandpruning
Inthissection,youwillseehowpartitioningcanoptimizeSQLstatementsclause
execution with the optimizer known as partition pruning, and the use of SQL
statements to effectively use partition data for selection and perform
modificationoperationsonthepartitioning.
Partitionpruning
Partitionpruningisrelatedtotheoptimizationconceptinpartition.Inpartition
pruning the concept described as Do not scan partitions where no possible
matchingvaluescanbepresentisappliedbasedonthequerystatements.
Supposethereisapartitionedtable,tp1,createdwiththefollowingstatement:
CREATETABLEtp1(
first_nameVARCHAR(30)NOTNULL,
last_nameVARCHAR(30)NOTNULL,
zone_codeTINYINTUNSIGNEDNOTNULL,
dojDATENOTNULL
)
PARTITIONBYRANGE(zone_code)(
PARTITIONp0VALUESLESSTHAN(65),
PARTITIONp1VALUESLESSTHAN(129),
PARTITIONp2VALUESLESSTHAN(193),
PARTITIONp3VALUESLESSTHANMAXVALUE
);
Intheprecedingexampletabletp1,supposeyouwanttoretrievearesultfromthe
followingSELECTstatement:
SELECTfirst_name,last_name,dojfromtp1wherezone_code>126ANDzone_code<131;
Now,youcanseefromtheprecedingstatementthattherearenorowsthathave
datainpartitionsp0orp3asperthestatement,soweonlyneedtosearchthedata
inp1orp2formatchingcriteria.So,bylimitingthesearch,itispossibletospend
lesstimeandeffortmatchingandsearchingforthedatathroughallthepartitions
inthetable.Thiscuttingawayoftheunmatchedpartitionsisknownaspruning.
The optimizer can make use of partition pruning for performing the query
execution much faster compared to nonpartitioned tables that have the same
schema,data,andquerystatements.
TheoptimizercandopruninginthefollowingcasesbasedontheWHEREcondition
reduction:
partition_columnIN(constant1,constant2,...,contantN)
partition_column=constant
Inthefirstcase,theoptimizerevaluatesthepartitioningexpressionforeachof
the values in the list and creates a list of partitions that are matched during
evaluation,andthenscanningorsearchingisperformedonlyonthepartitionsin
thispartitionlist.
In the second case, the optimizer only evaluates the partitioning expression
based on the given constant or specific value and determines which partition
containsthevalue,andsearchingorscanningisperformedonlyonthispartition.
Therecanbeuseofanotherarithmeticcomparisoninsteadofequalsforthistype
ofcase.
Currently,pruningisnotsupportedonINSERTstatementsbutissupportedinSELECT,
UPDATE,andDELETEstatements.
Pruning is also applicable to short ranges where the optimizer can convert the
rangesintoanequivalentlistofvalues.Theoptimizercanbeappliedwhenthe
partitioning expression consists of equality or range that can be reduced to
equalitiessetorifanincreasingordecreasingrelationshipisrepresentedbythe
partitioningexpression.
Pruning can also applicable to the column types of DATE or DATETIME if the
partitioningusestheTO_DAYS()orYEAR()function,andalsoapplicableifsuchtables
usetheTO_SECONDS()functionintheirpartitioningexpression.
Supposeyouhaveatable,tp2,asperthefollowingstatement:
CREATETABLEtp2(
first_nameVARCHAR(30)NOTNULL,
last_nameVARCHAR(30)NOTNULL,
zone_codeTINYINTUNSIGNEDNOTNULL,
dojDATENOTNULL
)
PARTITIONBYRANGE(YEAR(doj))(
PARTITIONp0VALUESLESSTHAN(1971),
PARTITIONp1VALUESLESSTHAN(1976),
PARTITIONp2VALUESLESSTHAN(1981),
PARTITIONp3VALUESLESSTHAN(1986),
PARTITIONp4VALUESLESSTHAN(1991),
PARTITIONp5VALUESLESSTHAN(1996),
PARTITIONp6VALUESLESSTHAN(2001),
PARTITIONp7VALUESLESSTHAN(2006),
PARTITIONp8VALUESLESSTHANMAXVALUE
);
Now, in the preceding statement the following statements can benefit from
partitionpruning:
SELECT*FROMtp2WHEREdoj='1982-06-24';
UPDATEtp2SETregion_code=8WHEREdojBETWEEN'1991-02-16'AND'1997-04-26';
DELETEFROMtp2WHEREdoj>='1984-06-22'ANDdoj<='1999-06-22';
Forthelaststatement,theoptimizercanactasfollows:
1. FindingthepartitionthathasthelowendoftherangeasYEAR('1984-06-22')
givesthevalue1984,foundinthep3partition.
2. FindingthepartitionthathasthehighendoftherangeasYEAR('1999-06-22')
givesthevalue1999,foundinthep5partition.
3. Scan only the above two identified partitions and any partitions that lie
betweenthem.
So, in the above mentioned case the partitions to be scanned are p3,p4, and p5
only,andtherestofthepartitionscanbeignoredwhilematching.
The preceding examples use RANGE partitioning but partition pruning is also
applicableonothertypesofpartitioningaswell.Supposeyouhavethetabletp3
schemaasperthefollowingstatement:
CREATETABLEtp3(
first_nameVARCHAR(30)NOTNULL,
last_nameVARCHAR(30)NOTNULL,
zone_codeTINYINTUNSIGNEDNOTNULL,
descriptionVARCHAR(250),
dojDATENOTNULL
)
PARTITIONBYLIST(zone_code)(
PARTITIONp0VALUESIN(1,3),
PARTITIONp1VALUESIN(2,5,8),
PARTITIONp2VALUESIN(4,9),
PARTITIONp3VALUESIN(6,7,10)
);
Fortheprecedingtableschema,considerifthisstatementSELECT * FROM tp3 WHERE
zone_codeBETWEEN1AND3istobeexecuted.Theoptimizerdetermineswhichofthe
partitionscanhavethevalues1,2,and3andfindsp1andp0,soitskipstherestof
thepartitionsp3andp2.
Column values with a constant can be pruned, as in the following example
statement:
UPDATEtp3setdescription='ThisisdescriptionforZone5'WHEREzone_code=5;
The optimization is performed only when the size of the range is
smallerthanthenumberofpartitions.
Partitionselection
Explicitselectionofpartitionandsubpartitionisalsosupportedandthisenables
rowmatchingtoconditionsgiveninthewhereclause-thisisknownaspartition
selection. It is very similar to partition pruning as only specific partitions are
scannedformatching,butdiffersinthefollowingtwokeyaspects:
Thepartitionstobescannedarespecifiedbytheissuerofthestatementand
arenotautomaticsuchaswithpartitionpruning
The partition pruning is limited to queries, whereas partition selection
supportsbothqueriesandanumberofDMLstatements
SQLstatementssupportedforexplicitpartitionselectionarelistedasfollows:
INSERT
SELECT
UPDATE
REPLACE
LOADDATA
LOADXML
DELETE
The following syntax with the PARTITION option is used for explicit partition
selection:
PARTITION(partition_names)
partition_names:
partition_name,...
Theprecedingoptionisalwaysfollowedbythetablestructureortableschemait
belongs to. partition_names stands for the list of comma separated names of
partitions or subpartitions that will be used in partitioning. Partition and
subpartitionnamesinpartition_namescanbeinanyorderorevenoverlapbuteach
name from the list must be the existing partition or subpartition name of the
specific table, otherwise the statement will fail with the error message
partition_namedoesn'texist.
IfthePARTITIONoptionisused,onlylistedpartitionsandsubpartitionsarechecked
for matching rows.PARTITION option can also be used in the SELECT statement to
retrieverowsbelongingtoanygivenpartition.
Supposeyouhavethetableemployeecreatedwiththefollowingstatements:
SET@@SQL_MODE='';
CREATETABLEemployee(
idINTNOTNULLAUTO_INCREMENTPRIMARYKEY,
first_nameVARCHAR(25)NOTNULL,
last_nameVARCHAR(25)NOTNULL,
store_idINTNOTNULL,
department_idINTNOTNULL
)
PARTITIONBYRANGE(id)(
PARTITIONp0VALUESLESSTHAN(5),
PARTITIONp1VALUESLESSTHAN(10),
PARTITIONp2VALUESLESSTHAN(15),
PARTITIONp3VALUESLESSTHANMAXVALUE
);
INSERTINTOemployeeVALUES
('','Chintan','Mehta',3,2),('','Bhumil','Raval',1,2),
('','Subhash','Shah',3,4),('','Siva','Stark',2,4),
('','Chintan','Gajjar',1,1),('','Mansi','Panchal',2,3),
('','Hetal','Oza',2,1),('','Parag','Patel',3,1),
('','Pooja','Shah',1,3),('','Samir','Bhatt',2,4),
('','Pritesh','Shah',1,4),('','Jaymin','Patel',3,2),
('','Ruchek','Shah',1,2),('','Chandni','Patel',3,3),
('','Mittal','Patel',2,3),('','Shailesh','Patel',2,2),
('','Krutika','Dave',3,3),('','Dinesh','Patel',3,2);
Now,ifyoucheckwithpartitionp1,youseethefollowingoutputasrowsadded
inpartitionp1:
mysql>SELECT*FROMemployeePARTITION(p1);
+----+-----------+------------+----------+---------------+
|id|last_name|last_name|store_id|department_id|
+----+-----------+------------+----------+---------------+
|5|Chintan|Gajjar|1|1|
|6|Mansi|Panchal|2|3|
|7|Hetal|Oza|2|1|
|8|Parag|Patel|3|1|
|9|Pooja|Shah|1|3|
+----+-----------+------------+----------+---------------+
5rowsinset(0.00sec)
IfyouusethisstatementSELECT*FROMemployeeWHEREidBETWEEN5AND9;,itwillgive
thesameoutput.
Inordertoretrieverowsfrommultiplepartitionsyoucanuseacommaseparated
listofpartitionnames.Forexample,SELECT * FROM employee PARTITION (p1,p2), will
result in all the rows from partitions p1 and p2 and exclude the remaining
partitions.
Any supported partitioning types can be used using partitioning selection
statements.MySQL8automaticallyaddspartitionnameswhenatableiscreated
withtheLINEARHASHorLINEARKEYpartitioningtypesspecifiedwithoutanynames,
and this is also applicable to subpartitions as well. While executing the SELECT
statementonthistableyoucanspecifypartitionnamesgeneratedbyMySQL8
forpartitionspecificdataretrieval.
ThePARTITION option is also applicable on the SELECT statement for the INSERT ...
SELECTstatement,bywhichwecaninsertdataretrievedfromspecificpartitionsor
subpartitionsaswell.
ThePARTITIONoptionisalsoapplicableontheSELECTstatementwithjoinquerieson
tableswithspecificpartitionorsubpartitiondata.
Restrictions and limitations in
partitioning
In this section, you will see the restrictions and limitations in MySQL 8
partitioning, covering prohibited constructs, performance considerations, and
limitation aspects related to storage engines and functions in detail, to gain
optimumbenefitsfromthetablepartitioning.
<strong>CREATETABLEtk1(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2DATENOTNULL,
</strong><br/><strong>cl3INTNOTNULL,</strong><br/>
<strong>cl4INTNOTNULL,</strong><br/><strong>UNIQUE
KEY(cl1,cl2)</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYHASH(cl3)</strong><br/>
<strong>PARTITIONS4;</strong><br/><br/><strong>CREATE
TABLEtk2(</strong><br/><strong>cl1INTNOTNULL,</strong>
<br/><strong>cl2DATENOTNULL,</strong><br/><strong>cl3
INTNOTNULL,</strong><br/><strong>cl4INTNOTNULL,
</strong><br/><strong>UNIQUEKEY(cl1),</strong><br/>
<strong>UNIQUEKEY(cl3)</strong><br/><strong>)</strong><br
/><strong>PARTITIONBYHASH(cl1+cl3)</strong><br/>
<strong>PARTITIONS4;</strong>
<strong>CREATETABLEtk1(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2DATENOTNULL,
</strong><br/><strong>cl3INTNOTNULL,</strong><br/>
<strong>cl4INTNOTNULL,</strong><br/><strong>UNIQUE
KEY(cl1,cl2,cl3)</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYHASH(cl3)</strong><br/>
<strong>PARTITIONS4;</strong><br/><br/><strong>CREATE
TABLEtk2(</strong><br/><strong>cl1INTNOTNULL,</strong>
<br/><strong>cl2DATENOTNULL,</strong><br/><strong>cl3
INTNOTNULL,</strong><br/><strong>cl4INTNOTNULL,
</strong><br/><strong>UNIQUEKEY(cl1,cl3)</strong><br/>
<strong>)</strong><br/><strong>PARTITIONBYHASH(cl1+cl3)
</strong><br/><strong>PARTITIONS4;</strong>
<strong>CREATETABLEtk4(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2INTNOTNULL,</strong>
<br/><strong>cl3INTNOTNULL,</strong><br/><strong>cl4
INTNOTNULL,</strong><br/><strong>UNIQUEKEY(cl1,cl3),
</strong><br/><strong>UNIQUEKEY(cl2,cl4)</strong><br/>
<strong>);</strong>
<strong>CREATETABLEtk5(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2DATENOTNULL,
</strong><br/><strong>cl3INTNOTNULL,</strong><br/>
<strong>cl4INTNOTNULL,</strong><br/><strong>PRIMARY
KEY(cl1,cl2)</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYHASH(cl3)</strong><br/>
<strong>PARTITIONS4;</strong><br/><br/><strong>CREATE
TABLEtk6(</strong><br/><strong>cl1INTNOTNULL,</strong>
<br/><strong>cl2DATENOTNULL,</strong><br/><strong>cl3
INTNOTNULL,</strong><br/><strong>cl4INTNOTNULL,
</strong><br/><strong>PRIMARYKEY(cl1,cl3),</strong><br/>
<strong>UNIQUEKEY(cl2)</strong><br/><strong>)</strong><br
/><strong>PARTITIONBYHASH(YEAR(cl2))</strong><br/>
<strong>PARTITIONS4;</strong>
<strong>CREATETABLEtk7(</strong><br/><strong>cl1INT
NOTNULL,</strong><br/><strong>cl2DATENOTNULL,
</strong><br/><strong>cl3INTNOTNULL,</strong><br/>
<strong>cl4INTNOTNULL,</strong><br/><strong>PRIMARY
KEY(cl1,cl2)</strong><br/><strong>)</strong><br/>
<strong>PARTITIONBYHASH(cl1+YEAR(cl2))</strong><br/>
<strong>PARTITIONS4;</strong><br/><br/><strong>CREATE
TABLEtk8(</strong><br/><strong>cl1INTNOTNULL,</strong>
<br/><strong>cl2DATENOTNULL,</strong><br/><strong>cl3
INTNOTNULL,</strong><br/><strong>cl4INTNOTNULL,
</strong><br/><strong>PRIMARYKEY(cl1,cl2,cl4),</strong><br
/><strong>UNIQUEKEY(cl2,cl1)</strong><br/><strong>)
</strong><br/><strong>PARTITIONBYHASH(cl1+YEAR(cl2))
</strong><br/><strong>PARTITIONS4;</strong>
Ifthetabledoesnothaveauniquekeyorprimarykeythenthe
restrictionisnotapplicable,andanycolumnorcolumnscanbeused
inthepartitioningexpressionaspercompatiblecolumntypesforthe
partitioningtype.Allaboverestrictionsarealsoapplicabletothe
ALTERTABLEstatementsaswell.
Partitioninglimitationsrelatingto
storageengines
Partitioning support is not provided by MySQL server but from the storage
engine's
ownornativepartitioninghandlerinMySQL8.InMySQL8,theInnoDBstorage
engineonlyprovidesanativepartitioninghandlerandsothepartitioned
tablecreationisnotapplicablewithanyotherstorageengine.
ALTER TABLE ... OPTIMIZE PARTITION does not work correctly with the InnoDB storage
engine, so instead use the ALTER TABLE ... REBUILD PARTITION and ALTER TABLE ...
ANALYZEPARTITIONoperationsforsuchtables.
Partitioninglimitationsrelatingto
functions
In partitioning expressions only the following listed MySQL functions are
allowedinMySQL8:
ABS():Itprovidesanabsolutevalueforthegivenargument
CEILING(): It provides the smallest integer number possible for the given
argument
DAY():Itprovidesthedayofthemonthforthegivendate
DAYOFMONTH():ItprovidesthedayofthemonthforthegivendatesameasDAY()
DAYOFWEEK():Itprovidestheweekdaynumberforthegivendate
DAYOFYEAR():Itprovidesthedayoftheyearforthegivendate
DATEDIFF():Itprovidesthenumberofdaysbetweentwogivendates
EXTRACT():Itprovidespartofthegivenargument
FLOOR():Itprovidesthelargestintegervaluepossibleforthegivenargument
HOUR():Itprovidesthehourfromthegivenargument
MICROSECOND():Itprovidesthemicrosecondsfromthegivenargument
MINUTE():Itprovidestheminutefromthegivenargument
MOD(): It performs the Modulo operation and provides the remainder of N
dividedbyMwhereMOD(N,M)
MONTH():Itprovidesthemonthfromthegivenargument
QUARTER():Itprovidesthequarterfromthegivenargument
SECOND():Itprovidesthesecondfromthegivenargument
TIME_TO_SEC():Itprovidesthesecondfromthegiventimevalueargument
TO_DAYS():Itprovidesthenumberofdaysfromyear0forthegivenargument
TO_SECONDS():Itprovidesthenumberofsecondsfromtheyear0forthegiven
argument
UNIX_TIMESTAMP() (with TIMESTAMP columns):It providesthe secondssince '1970-
01-0100:00:00'UTCforthegivenargument
WEEKDAY():Itprovidestheweekdayindexforthegivenargument
YEAR():Itprovidestheyearforthegivenargument
YEARWEEK():Itprovidestheyearandweekforthegivenargument
PartitionpruningsupportstheTO_DAYS(),TO_SECONDS(),TO_YEAR(),andUNIX_TIMESTAMP()
functionsinMySQL8.
Summary
Inthischapter,welearnedaboutdifferenttypesofpartitioningandtheneedfor
partitions. We also covered detailed information on managing all types of
partitions.
Welearnedaboutpartitionpruningandselectionofpartitionswhichisusedby
the optimizer. We also discussed applicable limitations and restrictions to
considerwhileusingpartitioning.
Inthenextchapter,youwilllearnhowtodoscalinginMySQL8,anddiscover
commonchallengesfacedwhenprovidingscalabilityinMySQL8.Youwillalso
learn how to make the MySQL server highly available and achieve high
availability.
MySQL 8 – Scalability and High
Availability
In this chapter, we will cover the following important topics for MySQL 8
scalabilityandhighavailability:
OverviewofscalabilityandhighavailabilityinMySQL8
ScalingMySQL8
ChallengesinscalingMySQL8
Achievinghighavailability
Beforewemoveontothedetails,let'shaveanoverviewofscalabilityandhigh
availabilityinMySQL8
Overview of scalability and high
availabilityinMySQL8
In any type of application, be it mobile, web portals, websites, social, e-
commerce, enterprise or cloud applications, data is the core portion of the
business.Dataavailabilityisconsideredanutmostconcernforanybusinessor
organization.Datalossoranydowntimeofanapplicationcanresultinaheavy
lossintermsofmoneyandalsoimpactthecreditofthecompanyinthemarket.
Ifweconsideranexampleofanonlineshoppingsitewhichhasanicelycovered
market in a specific area, with customers and good business credit. If this
business faced an issue with data loss or any application server or database
server downtime, it would impact the whole business. Many customers would
losefaithinthebusinessandalsothebusinesswouldsufferalossbothinterms
offinanceandcredit.
Thereisnosingleformulathatcanprovideasolution.Differentbusinesseshave
theirownapplicationrequirements,businessneeds,distinctprocesses,different
infrastructure in different locations, and operational competencies. In these
circumstances,technologyplaysamajorroleinachievinghighavailability.
Aspertherequirementsofscalabilityandhighavailability,MySQLcanbeused
for various applications, and as per need it is capable of overcoming failures,
includingfailuresofMySQL,failuresfromtheoperatingsystem,oranyplanned
maintenance activity that may impact availability. Scalability in simple terms,
that has the capability to distribute database load and application queries
betweenMySQLservers.
Theattributesthatmatterwhenchoosingtherightsolutionforhighavailability
depend on to what extent the system can be called highly available, as such
requirements vary from system to system. For smaller applications, where the
user load is not expected to be very high, setting up the replication or cluster
environment can result in very high cost. In such cases, providing the correct
configurationoftheMySQLcanalsobeenoughtoreduceapplicationload.
The following sections briefly describe the primary solutions supported by
MySQL8
forhighavailability.
MySQLreplication
MySQL replication allows data from one server to be replicated onto the
multipleMySQL
servers. MySQL replication provides master-slave design, so that one of the
servers from the group acts as a master where write operations are performed
fromtheapplicationandthenthemasterservercopiesthedatatothemultiple
slaveservers.Replicationisawellestablishedsolutionforhighavailabilityand
isusedbythesocialgiantssuchasFacebook,Twitter,andsoon.
MySQLcluster
ThisisanotherpopularhighavailabilitysolutionforMySQL.Clusteringenables
datato be replicated to multiple MySQL servers with automated sharing. It is
designedforbetteravailabilityandthroughput.
OracleMySQLcloudservice
OracleMySQLcloudserviceprovidesanefficientmeanstohelpbuildasecure,
cost-effective MySQL database as a service for applications used in modern
world.Itprovestobescalableandcost-efficientwithlessresourceutilizationfor
managingtheservicewhencomparedtoon-premises.
MySQLwiththeSolariscluster
The sun Solaris cluster provided by the MySQL data service provides a
mechanism for orderly startup and shutdown, fault monitoring, and automatic
failoveroftheMySQL
service.ThefollowingMySQLcomponentsareprotectedbythesunclusterHA
fortheMySQLdataservice.
There are some further options available using third-party solutions. Each
architecture that is used to achieve highly available database services is
differentiatedbythelevelsofuptimethateachoffers.Thesearchitecturescanbe
groupedintothreemaincategories:
Datareplication
Clusteredandvirtualizedsystems
Geographically-replicatedclusters
Basedonthebestanswertothequestion,youcanselecttherightoptionforyour
application with optimal cost and a highly available solution. This discussion
givesusafairoverviewofMySQL8'shighavailability.
ScalingMySQL8
Scalabilityistheabilitytodistributetheloadofanyapplicationqueriesacross
various MySQL instances. For some cases, it is unpredictable that data cannot
exceed up to some limit or the number of users will not go out of bounds.
Scalabledatabaseswouldbeapreferablesolutionsothat,atanypoint,wecan
meetunexpecteddemandsofscale.MySQLisarewardingdatabasesystemfor
its scalability, which can scale horizontally and vertically; in terms of data,
distributionofclientqueriesacrossvariousMySQLinstancesisquitefeasible.It
isprettyeasytoaddhorsepowertotheMySQLclustertohandletheload.
The requirements for achieving High Availability (HA) and scalability may
vary from system to system. Each system requires a different configuration in
order to achieve these abilities. There are many questions that come to mind
when we think about scaling in MySQL, and while we perform scaling
operationsinMySQL:
Whyisscalingrequired?
WhataretheadvantagesofscalinginMySQL?
Whatpointsneedtoput acrossin ourmindswhen weperform scalingin
MySQL?
Howwillscalingwork?
Isitsecurefordata-doesitprovidesuretyofdatasecurity?
Plusmanymore...
Let'stakea realtimeexample to understandwhy we needscalingin MySQL.
We have an online e-commerce website that has covered a small market, with
limitedusersandlimitedhitsonthewebsite,withasingledatabaseserver.The
businessisgrowingupnicely;theperformanceofthebusinessiscontinuously
increasingandtheusercountisincreasing,andwithoursingledatabaseserver
all requests and performance cannot be scaled at all time. This may possibly
resultin aservercrashandthebusinessmight faceloss interms ofprofitand
creditinthemarket.Toavoidsuchasituation,scalabilitywillperformamajor
part.Ifanyrequestfromacustomerfailsduetoanyreason,orifthenodegoes
down, the other node will take care of it quickly and give the appropriate
responsetothecustomer.
Scaling is required for the continuous increase in performance of database
responsetimeandtoimprovetheproductivityoftheproduct.Itwillhelptheend
productintermsofdatascalability,performance,andbetterresults.Clusterand
replicationarebothkeyfeaturesinMySQLthatcanbeleveragedforscaling.
Scalingusingcluster
Basicclusterarchitectureisdividedintofourdifferentlayers:
Clientnode
Applicationnode
Managementnode
Datanode
Theseareshowninthefollowingimage:
Clientnode
Theclientnodeisanenduserorapplicationthatsendsarequestforanyqueryin
terms of read data or write data from a different device, such as a computer,
mobile,tablet,andsoon.
Applicationnode
The application node is meant to provide the bridge between the logic of the
application and the nodes containing the data in MySQL. Applications can
access the data, which is stored in the MySQL cluster, by SQL, with one or
many MySQL servers using the function of SQL. In the application we have
multipletechnologiesfromwhereweconnecttotheMySQLserver.Weconnect
MySQLserverwithstandardtheMySQLconnectors,whichgivesustheability
toconnectwithawiderangeofaccesstechnologies.
Asanotheroption,wehaveNDBAPI;ahighperformanceinterfacethatcanbe
used to control real-time user experiences and provide better throughput. In
MySQLwehaveNDBAPI,whichaddsalayeradditionallytoNoSQLinterfaces
thatconsistcapabilitytoaccesstheclusterdirectly.Applicationnodescanfetch
datafromallthedatanodes,sotheonlycauseoffailurecanbetheunavailability
ofapplicationservices,astheapplicationcanusealldatanodestoperformdata
manipulation.
Managementnode
Themanagementnodeperformstheimportantroleofpublishingrelevantcluster
informationacrossthenodesinitscluster,alongwithnodemanagement.Nodes
formanagementworkatstartupwhenallnodeswanttojointheMySQLcluster
andalsowhenreconfigurationofthesystemisrequired.Themanagementnode
can be stopped and restart all services without damaging or impacting an
ongoingoperation,execution,orprocessingofdataandtheapplicationnode.
Datanode
Thedatanodesstoresthedata.Tablesgetsharedacrossthedatanodes,which
alsohelpstohandleloadbalancing,replication,andhighavailabilityfailover.
Data nodes are the main nodes of a MySQL cluster solution. It provides the
followingfunctionalityandbenefits:
Data storage and management of
disk-basedandin-memorydata
Inashared-nothingscenario,dataisstoredinatleastonereplicawithouttheuse
of shared-disk space. MySQL create one replica of the database which does a
synchronous replication process. If any data node fails due to any specific
reason,thereplicateddatawilltakecareofitandprovidetherespectiveoutput.
It does a synchronous copy of the node so it consists of the same data as the
mainnodedata.
We can store the data either in memory or partially on disk based on the
requirement.
Data that frequently change are suggested to be stored in-memory. In-memory
dataisroutinelycheckedwiththelocaldiskandcoordinatestoupdatethedatato
therestofthedatanodes.
Automatic and user-defined
partitioning of tables or sharding
oftables
MySQL cluster provides low latency, high throughput, scalability, and high
availability.
Thisadoptshorizontalscalingandautoshardingtoserveheavyloadread/write
operations
throughthedifferentNoSQLqueries.AnNDBclusterisasetofdifferentnodes
where
eachtaskisrunningonitsownprocessor.
Synchronous data replication
betweendatanodes
When we have data replication for the data node it follows synchronous
replication,soatanytimeallnodedatawillbein-sync.Ifanynodefailsforany
reason, the other nodes have the same data and so will be able to provide the
dataforaquery.
So, without any downtime for data response, MySQL provides a perfect
solution.
Dataretrievalandtransactions
MySQLsupportseachofthetransactionsthatcanbemapped,asitiscommitted
onthemasterserverandappliedontheslaveserver.Thismethodisnotreferring
tobinlogfilesortherelevantpositioninthebinlogfile.GTIDreplicationissolely
working based on transactions; it becomes very easy to identify whether the
masterandtheslaveserversareinsyncornot.
Automaticfailover
If any data node fails for any reason, the other nodes take responsibility and
givestheresponsetotherequest.Replicationofthedatabaseisveryhelpfulin
criticalconditionsofdowntimeorafailureinanyofthenodes.
Automatic re-synchronization for
self-healingafterfailure
If any node is failed it will start automatically and again perform the
synchronizationofdatatotherestofthenodes,whichareactivenodes,andcopy
allrecentdatainthenode.Inthatcaseitdoesself-healingofthefailures.
Scaling using memcached in
MySQL8
In MySQL 8, using memcached is one of the ways to achieve scalability.
Memcachedisasimpleandhighlyscalablesolutionforstoringdatainkeyand
value form in cache whenever memory is available. Memcached is commonly
usedforquickaccessofdata.
Data stored in memory doesn't have I/O operations performed for fetching the
data.
As all the information is stored in memory, the access speed for data is much
faster than compared to loading every time from disk and results in a better
queryexecutiontimeonthedatabaseserver.Thispluginalsohasthefeatureof
serialization, which converts binary files, code blocks, or any other objects to
stringsthatcanbestored,andprovidesasimplemeanstoretrievesuchobjects.
Whilespecifyingamemoryallocationitshouldnotbelargerthantheavailable
physicalmemoryoftheserver.
If you specify too large of a value then some of the memory allocated for
memcached will use swap space and not physical memory. This may lead to
delays when storing and retrieving values because data is swapped to disk
insteadofstoringthedatadirectlyinmemory:
Theprecedingimagedepictsmemcached architecture,whichdisplaystheflow
ofthedatafrommemcachedtoaclientoranenduser,orarequestofthedata
fromanapplication.
Thedatainmemcachednevergetsstoredinthedatabase.It'salwaysavailablein
memoryitself.Ifeitherofthememcachedserversfail,datawillbefetchedfrom
thedatabase,so itwillnot impactend-usersfor dataretrievalor haveamajor
performance impact on the application. The only thing need to keep in mind
while we use a memcached server is that data related to any important
information, for instance a financial transaction, should not be placed in
memcached.Inthatcaseifthereisafailureinmemcached,thedatamightnotbe
retrieved. In a memcached server data integrity is not healthy as it stores in
memory, so during failure it would be good to have data that is important not
saved in memcached. When configuring a memcached server, memory size is
the key factor. If there is improper configuration, then you can expect a bad
situation.
This way we can use memcached to scale the MySQL server for an increased
dataresponsetime,andtoprovidefasterperformance.Itwillreducetheloadon
MySQLserverandmultipleserversasapartofcachegroupandalsoprovidesan
interfaceformultiplelanguages.Itissuggestedtobeusedideallywhenthereare
heavyreadoperations.
NoSQLAPIs
MySQL cluster provides numerous ways to help access the data store. One of
mostgeneric
wayisleveragingSQL;however,inreal-worldusecaseswecanalsodependon
native
APIs, which allow the fetching of the data from within the database without
affecting
performance or adding further complexity by developing an application to
convertSQL.
Scalingusingreplication
Replicationis thecopying ofaMySQL database.MySQLprovides replication
with a different approach. MySQL has a feature of replication that provides
scale-outsolutions,datasecurity,longdistancedatadistributionandmanymore
benefits.WehavediscussedthisatlengthinChapter8,ReplicationinMySQL8.
Thefollowing imageexplainsthebasicarchitectureofreplicationinMySQL:
ReplicationisoneofthebestfeaturesofMySQL.Itsimplycreatesacopyofthe
datatothenewserveroranotherphysicalmachine,whichwillimportthedata
from the master server. Whenever the data is required it will populate the
accurateresults.
Itfollowsthemasterandslaveapproachforthereplication.Themasterdatabase
is the actual database of the application and the slave database is created by
MySQL
inthedatabaseserverofanotherphysicalserver,whichcontainsreplicateddata
from the master server. We can configure the slave database for the specific
operation,suchaswhenthequeryrelatestoreadingthedatafromthedatabase;
wecanexecutethisontheslaveserver.Inthiscasethemasterdatawillhaveless
loadthanearlier.
Supposewehavearatioofthe40%writedataqueryand60%readdataquery;
inthiscaseifwehaveasingleserveritwillhandlealloperationsrelatedtothe
read and write operation. But, as defined in the preceding image we have
replicated the database in two different servers and read operations are
performedontheslaveservers,sowecanmakeuseofoneoftheslaveserverto
perform complex read queries. This makes it possible to generate reports for
doingdataanalysisonMySQL8,asperformingcomplexreadquerieswillnot
impacttheoverallapplicationperformance.
In standard MySQL replication the master server creates binary log files and
maintainsthe indexofthelogfilestomaintainandkeeptrack oflog rotation.
Thebinarylog filesservethe recordsupdatesand aresentto theslaveserver.
Whentheslaveserverconnectstothemasterdatabaseserveritconsidersthelast
positionithasreadinthelogfiles,afterwhichtheslaveserverthenreceivesany
updatesthathavetakenplacesincethattime.Theslavesubsequentlyblocksand
waitsforthemastertonotifyitforfurtherupdates.
Thequestioninmindiswhydoweneedreplication?Or,whatisthepurposeof
thereplication?Ifreplicationrequiresanotherdatabaseserver,complexity,and
additionalconfiguration,itincreasesthemaintenanceandmonitoringtime.Still,
wehavemanyadditionalbenefitsforbusinessanddatabaseadmin.
Singleserverdependancy
Inanycase,ifthemasterdatabaseserverfailswecaneasilyswitchourdatabase
connectiontothereplicatedslaveservertoprovidestabilityincriticalsituations.
This includes if there is network failure, server failure, hardware issues, and
manymorereasonsforfailure.
Performance
Performance is the main part in the database. When we have a distributed
databaseovermultipleserverswecanconnectdifferentapplicationstodifferent
databaseserverstoincreaseperformance.Thisfeaturereducestheresponsetime
ofthequery.
Backupandrecovery
Replicationhelpsbackupthemasterdatabase.Itismoreefficientthanstoring
the database on disk. Users can store the database in the master using the
replicated database as a backup instead of digging up the backup files. When
requiredtorestorethedataofthemasterserverausercaneasilygetitfromthe
slaveserver,withnoneedtoworkonthebackupfilesandgoaboutfindingthe
lastupdatesandotheroperations.
Loaddistribution
Byusingthereplicationloadofthedatabase, queryexecutioncanbereduced;
we can split read and write operations over the databases. If we execute write
operationsinthemasterdatabaseandreadoperationsintheslavedatabasethat
willimprovetheresponsetimeoftheapplication.Wecancreateloadbalanced
environments in MySQL, which share the load of all requests to the database
server. The load balancer then further sends requests to the database that can
handleeachtransactionwithmuchbetterthroughput.
Asynchronousdatareplication
Asynchronous data replication means that data is copied from one machine to
another, with a resultant delay. This delay is based on networking bandwidth,
resourceavailability,oratimeintervalsetbytheadministratorinconfiguration.
The correct configuration and time setting provides an accurate result in
response. It's based on the network administrator's configuration. Synchronous
datareplication impliesthatdataiscommittedtoone ormore machinesat the
sametime.
Geographicaldatadistribution
Groupreplicationmakesitpossibletocopythemaster'sdatatotheslaveserver
thatresidesataremotelocationandperformthereadoperationsforaseparate
groupofclientwithoutimpactingthemaster'soperations.
GTIDreplication
Global transaction identifiers (GTID) uses transaction based replication of
datainsteadofbinarylogfilebasedreplication.
Until and unless transactions that have been operated and committed on the
master servers are present on all the slave servers, GTID will not consider
replicationinaconsistentstate.
InMySQL8replication canbedone either inasynchronous mode orinsemi-
synchronous mode. In asynchronous mode, write operations are performed on
themasterserverimmediately,whilereplicationinslavesisdoneperiodicallyas
pertheconfiguration.
Inthesemi-synchronousmodeofreplication,ifsemi-synchronousconfiguration
isenabledonthemasterandatleastoneslaveserver,atransactiononthemaster
node waits before getting a transaction time out until the semi-synchronous
enablednode confirmsthat requireddata orupdate hasbeen received.And on
time-out, the master node again looks for the semi-synchronous slave and
performsthereplication.
MySQL8providesanewreplicationmethod,GTID,whereauniqueidentifieris
createdandconnectedwitheachtransactionsavedorcommittedonthemaster
server.Theuniquenessoftheseidentifiersisinallserversthatareintheserver
where it's created, and also in the replicated servers. GTID have one to one
mappingbetweenalltransactions.
The concept of the log file referencing a position within files is not required
whenstartinganewslavecreationorfailovertoanewMySQLmaster.Youcan
useeitherrow-basedorstatement-basedreplicationwithGTIDs.
UsingaglobaltransactionIDprimarilyprovidestwomajorbenefits:
It's easy to change a master server to connect with a slave server
duringfailover:GTIDisuniqueoutofallserversinthereplicationgroup.
TheslaveserverrememberstheglobaltransactionIDofthelasteventfrom
theoldmaster.Thismeansitbecomeseasytoidentifywheretoreinitialize
replication on the new MySQL master, as the global transaction IDs are
knownthroughouttheentirereplicationhierarchy.
The status of the slave provides a crash-safe method: The slave holds
current position information in the mysql.gtid_slave_pos system table. If this
table is using a transactional storage engine (such as InnoDB, which is the
default),thenfurtherupdatesaredoneinthesametransaction.
AGTIDsisauniquekeycreatedandassociatedwitheachtransaction(insertand
updateoperations)committedonthemasterserver.Thekeyisnotonlyuniqueto
themasterserver,butit'suniqueacrossallserversinreplication.
ZFSreplication
TheZFS filesystemhastheabilitytoprovision asnapshot oftheserverfiles,
such as file system contents, transfer the snapshot to another machine, and
extractthesnapshottorecreatethefilesystemonadifferentserver. Userscan
createasnapshotatanytimeandcancreateasmanysnapshotsasrequired.By
continually creating, transferring, and restoring snapshots, it can provide
synchronizationbetweenoneormoremachinesinafashionsimilartoDRBD.
We have seen all the possible ways to scale a database in MySQL, using
differenttechniques.
As per business need and flexibility we can perform scaling with database
backup.
Scaling is not an easy task but its possible in MySQL 8, with the proper
knowledge and understanding of the requirements of the business and a
configurationprovidedbyMySQL8.Fordatabasescaling,wemusthaveproper
understanding of the entire workflow of the database and communication
approach.
ChallengesinscalingMySQL8
Wehaveseenhowscalingworksandtheadvantagesandpurposeofscalingin
theprevioustopic.WhenwestartworkingwithscalinginMySQL8,whattype
of challenges will we face, and what steps need to be kept in mind while we
worktowardsscaling?Wehavetoaccountforifwe aredoingscaling andthe
masterserverfails,limitsarereached,readandwriteoperationsarenotableto
handle the requests of the application, or while re-platforming the database.
Scaling is not an easy task; it needs to ensure it is able to handle increasing
transactions without any difficulty. At the time of performing the scaling we
needtokeepinmindmanypoints,suchasthewriteandreadoperationlimitsin
themasterandslaveservers.Databaseloadbalancingisoneoftheapproaches
thathelpreducethetrafficofthetransaction,butagainitneedsperfection,and
needstounderstandtheloadbalancingconfigurationproperly.
Thefollowingarethemajorchallengesfacedwhenweperformscaling.
Businesstypeandflexibility
Thisisthefirstpointthatneedstokeptinmindwhileweperformthescaling.
Business type or business behavior is the core part; if the business is an e-
commerce, we already know e-commerce businesses have a number of
functionalities and very critical data about clients, such as product details,
monopolyofthebusinessforoffersanddiscounts.
Themainthingiscustomerdetailsandpaymentinformationsuchascreditcard
details,debitcarddetails,andcustomerfeedback.
Inthiscase,whilewearedoingscalinginMySQL8,allparametersneedtokept
inmind,suchasdatabasebackup,security,roles/privilegesofthedatabaseand
backwardcompatibilityofthescaling.Whiledoingscalingbyclusteringalldata
nodesneedtobeonthesamepage.Iftheapplicationisdevelopedusingmultiple
technologies and we perform the scaling for each of the stack, we can have
differentdatanodesavailable;inthiscasethedatabasesyncisoneofthemost
importantthingsthatneedtobesureinconfigurationwhilescaling.Whichtype
ofdatashouldresideincachedmemoryinmemcachedandindiskshouldalso
beclearbeforewedesignscaling.
Thebehavioroftheapplicationaccessesdatafromtheshareddatanodes.Ifwe
have an e-commerce site and we perform the sharding for the same and at a
certain level the data are not available for the client who uses the data of the
othershardserverforanyreason,atthattimethecross-nodetransactionwould
berequired.It'scompletelybasedonthebusinessbehavior,anddependsonhow
flexiblethebusinessiswhenitcomestoacceptingchangesregardingdatabase
scaling.
Understandserverworkload
Forthesetupofflexibility,scale,andperformanceimprovementmanyoptions
and
actions are available in MySQL 8. Many people face issues while performing
suchactivities
becausetheydonothaveenoughunderstandingorknowledgetohandlevarious
technology
stacks and configuration option selections that can improve scalability,
performance,
security, and the flexibility of the application and deployment activity. These
configuration
optionsincluding clustering,replication,sharding,memcached,storage engine,
and
many more, which can be well designed to handle the whole workload of the
application.
The database workload and business behavior helps to decide the MySQL
configuration.
Read-writeoperationlimit
Whathappenifthereadandwritelimitisreachedandthetransactionincreases
on the master database server. MySQL has limitations to the capacity; for
instance if a number of customers are visiting the site at the same time that a
read-write operation is running and the server or node are not synced, then at
thattimeitwillcreateconfusionormisunderstandingfortheenduser.Or,inan
e-commercesite,ifonecustomer ispurchasingthe product,which islastitem
leftinstock,andatsametimeanothercustomersearchesforthesameproduct
andit'sstillavailable,inthiscasebothoperationsarenotinsyncintermsofthe
readandwriteoperationofthedatabase.
Intheend,theothercustomermightpurchasethesameproduct,whichwedon't
haveinthewarehouse.Thisimpactsinventorycalculation,andcustomershave
doubtsabouttheprocessofthepurchasecycle.Inthatcasewewouldloosethe
faithofthecustomerinthebusinessandthecreditofthebusinesswouldalsobe
impacted.
Anotherapproachistohavedatabasesharding.Shardingcanbesimplystatedas
partitioningthedatabaseinmultipleservers.Shardinghelpstoreducetheload
on a single database or the master database. If we have databases sharding
geographically,andfordifferentcountryorregionwehavedifferentserversfor
Maintenance
WhilewehaveperformedscalinginMySQL8,wemustknowhowtomanage
masterandslaveservers,andwhichconfigurationisrequiredwhileperforming
scaling. What are the steps that need to be taken care of at the time when the
server is in a critical stage? What steps needs to be performed at time of
sharding,clustering,orreplicationofthedatabaseserver?
Scalingispossiblebutitsnotaneasyoperation.Ifwewanttoperformscaling
we should know that the database can handle more transactions without any
issue.Weshouldknowtheappropriateconfigurationtobedonetoovercomethe
default limits on the master server for the write and read operation. Once it's
completed, we need to perform similarly steps to configure the slave database
server, which should only have read operations available for the end user and
shouldalwaysbeinsyncwiththemasterdatabase.
Ifwehavemultipleservers,thenthemaintenanceoftheserveralsobecomesa
costlyoverhead.Alltheserverneedstobeonsamepage,configurationshould
beinpropermanner,andthecostoftheserverwillalsoaffectthebusiness.Ifthe
numberof dataconstantly increasesatthattime,serverspacealsoneedsto be
managedinanappropriatemanner.
Masterserverfailure
Ifthemasterserverfailsanddataisnotavailabletothecustomeratthattime,
the end user will get frustrated and the business will be hampered in terms of
creditinmarketandinlosingthecustomeralso.Thebusinesswillhavetosuffer
fromtheloss.
Synchronization
Whetherweperformthescalingwithclusteringorreplication,inbothcaseswe
needtosecuresynchronization.Allslaveserversshouldhavethesamedatabase
asthemasterserver.Ifwriteoperationsareperformedonthemasterserverand
readoperationsareperformedontheslaveserver,atthattimealldataneedsto
besyncedup.Allresultsshouldbesame,andifanyservergoesdownatatime
whendatawasnotsynced,itwillcreateissuesregardingthelossofdata.
Databasesecurity
How do we secure the database if we have different servers and sharding is
performed?
If we have different database servers at different locations and access to the
databaseisnotrestrictedtotheuserspecificatthattimethentheissueofadata
leakisastrongpossibility.Wehavetocompletelyunderstandaccesspointsof
the data in terms of IP configuration of the database server, with appropriate
rolesandprivilegesforthedatabaseuserswhoperformvariousactivities.Which
IPs have access and which IPs need to restrict the data transaction from the
server? While we are performing the cross node transaction on the database,
accurate data should be available; it should not give the permission to access
restricteddatafromtheserver.
Crossnodetransaction
Cross node transaction is required when we have multiple nodes after doing
scalingandonenoderequirestheothernodedataasapartofinput.Forinstance,
ifwehavedifferentnodesatdifferentlocationsandwehaveasingleinventory
for all the locations at that time, one user request for any product that is not
availableinthatdatanodeatthattimewillhavetocommunicatewithotherdata
nodesfortheinformationoftheproduct,basedontheuser'srequest.
Growingteamfordevelopment
Whiletheapplicationmayhaveapositiveresponse anditscontinuoussuccess
increasethebusinessteam,theexpansionofthedatabaseadministratorswillalso
berequired.
WhenweperformingsharingandscalingorreplicationinMySQL8,werequire
appropriateteammemberswiththeproperknowledgeandexperiencetohandle
continuous expansion and the management of database servers. It's not only
limited to the setup of database servers; we also need to keep an eye on
maintenanceoftheserverandkeepwatchingtheserveractivityalso.
Managechangerequest
When we have a change in any database structure and we have already
performedthescalingorreplicationthanafewthingsneedtobetakencareofas
partofachangerequest,orifweaddanewfeatureoranenhancementofthe
functionality.Thisincludesthingssuchasupdatingsharingkeys,modifyingthe
data distribution with replication of the nodes, updating the queries to take
replication latency into account to avoid stale data with on-going managing
shards,databalancing,andensuringthatdataisavailablewithnewupdates.
Scale-upandscale-out
Scale-updescribestheprocessofmaximizingthecapacitythatasingleMySQL
node can handle. The process of scaling-up can involve optimally tuning your
databasesoftwareandchoosingtherightstorageengine,aspreviouslydiscussed
in Chapter 6, MySQL 8 Storage Engines, and selecting appropriate hardware.
Therearelimitsonhowfaryoucanscale-upanodeandthesearedeterminedby
some combination of data size, schema complexity, CPU cycles, system
memory, and disk IO operations. While scale-out has been garnering much
attentionbecauseoftheneedtohandleincreasinglymassivedatasets,itisvery
importanttorememberthatthebetterwescale-up,thefewerscale-outnodesthat
wewillrequireandsothelessweneedtospendonhardware.
Scale-outcanbeusedtodeliversolutionsthatcoverseveraldifferentusecases.
Someofmostcommononesaretoincreasereadcapacitybyusingreplicationor
to use database sharding to increase total database size and overall transaction
throughput.
All of these are the key challenges faced while scaling MySQL 8. These
challenges need to be considered while we are performing scaling of the
databaseinMySQL8.
Asinglemistakecanputabusinessintoansituationwhichnoneofuswouldlike
to be in. Scaling is the the better way to improve the performance of the
database.
Achievinghighavailability
Highavailabilityreferstosystemsthataredurableandcanperformoperations
withoutanyhindranceonthedatathatisrequiredfortheresponseoranyrequest
from any mobile, web portals, websites, social, e-commerce, enterprise, and
cloud applications. Data availability is considered an utmost concern for any
businessororganization.Anyissueswithdowntimemayhaveanimpactonthe
businesscredit,andinsomecasesbusinesseshavetosufferfinancialloss.
For instance, if we have an e-commerce application with a single database
server, if that server goes down for reasons such as hardware failure, network
issue,virus,oroperatingsystemissues,itimpactsthedataalso.Ane-commerce
application may have a large number of customer hits at same time, and any
serverfailurestoservetheresponsetouserrequestswillimpacttheuser;they
willsearchforotheroptionsforthepurchasecommodity.
MySQL8hascapabilitiestoprovidebackendfortheapplicationtohelpachieve
highavailabilityandprepareafullyscalablesystem.Anabilityofthesystemto
keeptheconnectionpersistent,incaseapartoftheinfrastructurefails,andthe
abilityofthesystemtorecoverfromsuchfailuresisconsideredhighavailability.
A failureofthe systemcanbe causedbyeither amaintenanceactivity onone
partofthesystem,suchasahardwareorsoftwareupgrade,orbythefailureof
theinstalledsoftware.
Purposeofhighavailability
The requirements for achieving HA and scalability may vary from system to
system.
Eachsystemrequiresadifferentconfigurationinordertoachievetheseabilities.
MySQL 8 also supports different approaches, such as the replication of data
across multiple MySQL servers, or preparing multiple data centers based on
geographical locations and serving the client requests from the data centers
closest to the location of the client. Such solutions can be used to achieve the
highestuptimeofMySQL.
Today,intheworldofcompetitivemarketing,anorganization'skeypointisto
have their system up and running. Any failure or downtime directly impacts
business and revenue. Hence, high availability is a factor that cannot be
overlooked.MySQLisquitereliableandhasconstantavailabilityusingcluster
andreplicationconfigurations.
Cluster servers instantly handle failures and manage the failover part to keep
yoursystemavailablealmostallthetime.Ifoneservergetsdown,itwillredirect
theuser'srequesttoanothernodeandperformtherequestedoperation.
Dataavailability
Dataisalwaysavailableinanysituation.Inanyapplication,dataisthecorepart,
whichisactuallythewealthoftheapplicationowner.Ifwehaveahealthcare
system and at the time of medical check up of any patient their data is not
available, due to server downtime or any other reason, it might block further
processofthedoctorandinthiscaseimpactsthelifeofthepatient.
Securityofdata
Thefirstthingthatcomestomindissecuringdata,becausenowadaysdatahas
become precious and it can impact business continuity if legal obligations are
notmet;infact,itcanbesobadthatitcanclosedownyourbusinessinnotime.
MySQL isthe mostsecureand reliabledatabasemanagement system,usedby
manywell-knownenterprisessuchasFacebook,Twitter,andWikipedia.Itreally
providesagoodsecuritylayerthatprotectssensitiveinformationfromintruders.
MySQLgivesaccesscontrolmanagementsothatgrantingandrevokingrequired
accessontheuseriseasy.Rolescanalsobedefinedwithalistofpermissions
thatcanbegrantedorrevokedfortheuser.
All user passwords are stored in an encrypted format using plugin-specific
algorithms.
Synchronizationofdata
Whilewehaveasingledatabaseserver,ifitgoesdownforanyreasonwewould
lose the whole database, and if we have database backup available up to the
currentday,wecanrestorethedatabasetillthatday,butallcurrenttransactions
wouldalsobelostinthiscase.Thelasttransactiondatawouldnotbeavailableat
thattime.
Backupofthedata
Databasebackuptillthelasttransactionshouldbeintheplanwhenabusiness
hasanyserverbaseapplicationwhereasingledatabaseserverisperformingall
thetasks.Whendoinghighavailability,includeallscenariosofthebackupand
restoreoperationinthearchitecture.
Competitivemarket
Inthemarketmanycompetitorsareavailablewiththesamenatureofbusiness.
In this case, if a business is having issues with data availability to end users,
customers might not continue with that business and instead move to another
provider.Itsanintegralpartofbusinesscontinuity.
Performance
High availability is also important in terms of the performance of the data
operation.
Ifwehaveasingleserverandalloperationsareperformedonthatserveronly,it
willreachitslimitatsomestage,wheretheservercapacityisexhausted.So,in
thatcase,ifwehavehighavailabilityarchitectureimplementeditwouldprovide
a means to load the balance of a transaction and the performance of the data
manipulation operation. Replication and clustering enables for better
concurrencyandmanagestheworkload.
Updatesinthesystem
While any online site or application requires updates or any new production
release
is planned it directly impacts the end users. If an application has only limited
users
at that time, we can manage the update regarding all end-users via emails or
messages
within the application before the release. But in cases where there are a large
number
ofuserinasingleapplication,atthattimeitwillimpactthebusiness.Itwill
stop all users at the same time, and due to this running transactions would be
impacted.
Choosingthesolution
Again, we have to think about selecting the right solution for the availability.
ManythingsneedtobekeptinmindwhileweplanhighavailabilityinMySQL.
The requirements for achieving HA and scalability may vary from system to
system.Eachsystemrequiresadifferentconfigurationinordertoachievethese
abilities.
SuchsolutionscanbeusedtoachievethehighestuptimeofMySQLwithregard
tothefollowing:
Thelevelofavailabilityrequired
Thetypeofapplicationbeingdeployed
Acceptedbestpracticeswithinyourownenvironment
In MySQL, replication and clustering are the best options for achieving high
availability.
Allapplicationshavetheirownarchitecture,andnatureoftheirbusinessneeds
to be considered when we are selecting any technique to achieve high
availabilityofMySQL8.
Advantagesofhighavailability
The following are the advantages that we have when we perform high
availabilityinMySQL:
MySQL is quite reliable and has constant availability using cluster and
replicationconfigurations.
Cluster servers instantly handle failures and manage the failover part to
keepyoursystemavailablealmostallthetime.Ifoneservergoesdown,it
will redirect the user's request to another node and perform the requested
operation.
Anabilityofthesystemtokeeptheconnectionpersistent,incaseapartof
infrastructure fails, and the ability of the system to recover from such
failureisconsideredashighavailability.
MySQL 8 also supports different approaches such as replication of data
acrossmultipleMySQLserversorpreparingmultipledatacentersbasedon
geographicallocationsandservingtheclientrequestsfromthedatacenters
closesttothelocationoftheclient.
MySQLgiveshighspeedtransactionprocessingwithoptimalspeed.Itcan
cachetheresults,whichboostsreadperformance.
Replication and clustering enables better concurrency and manages the
workload.Groupreplicationbasicallytakescareofcommittingtransactions
once most of the members in group replication have acknowledged the
transactionhasbeenreceivedconcurrently.
Thishelpscreatebetterthroughputiftheoverallnumberofwritesdoesnot
exceedthecapacityofthemembersinthegroupreplication.
Clustering enables data to be replicated to multiple MySQL servers with
automatedsharing.Itisdesignedforbetteravailabilityandthroughput.
Memcached removes the SQL layer and directly accesses the InnoDB
databasetables.
Hence, overhead operations like SQL parsing will no longer be executed,
whichreallyimpactstheperformance.
MemcachedwithMySQLalsoprovidesyouwithawaytomakein-memory
datapersistentsothatwecanuseitforvariousdatatypeswithoutlosingit.
MemcachedAPIsareavailableindifferentprogramminglanguagessuchas
Perl,Python,Java,PHP,C,andRuby.WiththehelpofaMemcachedAPI,
an application can interact with the Memcached interface to store and
retrieveinformation.
Summary
Inthischapter,westartedwithanoverviewofscalabilityandhighavailabilityin
MySQL 8, which covered the various scalability needs, advantages, methods,
andkeypointstobenotedwhenwemakescalabledesignsofMySQL8.Wealso
discussed the shortcomings that we generally come across when we perform
scalabilityandhowtoovercomechallengeswithappropriatesolutions.Wehave
learned about scaling in MySQL 8 and troubleshooting challenges in scaling
MySQL8.Wealsolearnedaboutmanydiversewaystoachievehighavailability
inMySQL8.
Inthefollowingchapter,wewilllearnhowtotakecareofMySQL8security.
We will learn about general factors that affect security, the security of core
MySQL8files,accesscontrol,andsecuringthedatabasesystemitself.Wewill
alsolearnthedetailsofsecuritypluginsandgainanin-depthunderstandingof
databasesecurityingeneralforrelationaldatabases.
MySQL8–Security
Inpreviouschapters,welearnedaboutthescalabilityofMySQL8andhowto
troubleshoot challenges when scaling MySQL 8. Apart from that, we also
learnedhowtomakeMySQL
8highlyavailableforuse.Nowadays,securityisimportantforanyapplication,
right?
Whenwetalkaboutsecurity,itincludesaccountmanagement,roles,privileges,
and more. Considering these aspects, we will cover all of these topics in this
chapter.
This chapter mainly focuses on MySQL 8 database security and its related
features.
Thefollowingtopicsarecoveredinthischapter:
OverviewofsecurityforMySQL8
Commonsecurityissues
AccesscontrolinMySQL8
AccountmanagementinMySQL8
EncryptioninMySQL8
Securityplugins
OverviewofsecurityforMySQL8
The term security is not bound to a specific topic; it covers a wide range of
topics related to MySQL 8. Before starting a detailed discussion on it, let's
mentionsomeimportantpointsrelatedtosecurity:
Considersecuritywithinadatabasewhereusersandtheirprivilegesrelated
tovariousdatabaseobjectsneedtomanage.
Passwordsecurityforusers.
Security configuration during the installation process, which includes
varioustypesoffiles,such aslogfiles,datafiles, andmany more.These
filesmustbeprotectedfortheirread/writeoperations.
To handle system level failure scenarios, you must have a backup and
recoveryplan.
This includes all the required files, such as database files, configuration
files,andmanymore.
Manage network security of the system where MySQL 8 was installed,
whichpermitsalimitednumberofhostsfortheconnection.
Nowyourridebeginswithanotherimportantandveryinterestingtopic.Herewe
go.
Commonsecurityissues
Beforegoingintodetailoncomplexissues,youmustfirstunderstandsomebasic
pointsthatwillhelpyoupreventmisuseorattacks.
<strong>shell>tcpdump-l-ieth0-w-srcordstport3306|
strings</strong>
Guidelines for a secure
password
In this section, we describe guidelines for securing passwords with respect to
differentusersandcoverhowtomanageitduringtheloggingprocess.MySQL8
provides the validate_password plugin to define the policy for acceptable
passwords.
<strong>cmd>mysql-uroot--password=your_pwd</strong><br/>
<strong>--OR</strong><br/><strong>cmd></strong>
<strong>cmd>mysql-uroot-p</strong><br/><strong>Enter
password:*********</strong>
<strong>[client]</strong><br/><strong>
password=your_pass</strong>
<strong>shell>chmod600.my.cnf</strong>
Guidelinesforadministrators
For a database administrator, the following guidelines should be followed to
securepasswords:
Usevalidate_passwordtoapplythepolicyonacceptedpasswords
MySQL8usesthemysql.usertabletostoreuserpasswords,soconfigurethe
systeminawaythatonlyadministrativeuserscanaccessthistable
Usersshouldbeallowedtoresetaccountpasswordsinthecaseofexpired
passwords
Applyprotectiononthelogfileifitcontainspasswords
Manage access to the plugin directory and the my.cnf file, because it can
modifycapabilitiesprovidedbytheplugins
Passwordandlogging
MySQL8allowsyoutowritepasswordsasplaintextinSQLstatements,suchas
CREATEUSER,SETPASSWORD,andGRANT.Ifweexecutethesestatements,MySQL8will
writepasswordsastextinlogfiles,andtheyarevisibletoalltheusersthathave
accesstothelogfiles.Toovercomethisproblem,avoiddirectupdatesongrant
tablesusingthementionedSQLstatements.
Secure MYSQL 8 against
attackers
TosecureMySQL8againstattackers,stronglyconsiderthefollowingpoints:
SetapasswordforallMySQLaccounts.Neverdefineanaccountwithno
password,becausethispermitsaccesstoyouraccountbyanyuser.
TomakeaconnectionwithMySQL8,usesecureprotocols/channels,such
ascompressedprotocols,MySQL 8internalSSLconnections,or SSHfor
encryptedTCP/IPconnections.
ForaUnix-basedsystem,setread/writeprivilegesonthedatadirectoryfor
theUnixaccountwhichisusedforrunningmysqld.Don'tusetherootuserto
starttheMySQL8server.
Usethesecure_file_privvariabletospecifythedirectoryforreadandwrite
permission. Using this variable, you can restrict non-administrative users
from accessing important directories. Use this variable to set permissions
on plugin_dir; it is very important. In the same way, do not provide FILE
privilegestoalltheusers,becauseitpermitsuserstowritefilesanywherein
thesystem.
Usethemax_user_connectionsvariabletorestrictthenumberofconnectionsper
account.
At the time of creating grant table entries, use wildcards properly. It is
preferabletouseIPsinsteadofDNS.
Followsecurityguidelinesduringstoredprogramandviewcreation.
Security options and variables
providedbyMySQL8
The following mysqld options and variables are provided by MySQL 8 for
security:
Name
Cmd-
Line
Option
File
System
Var
Status
Var
Var
Scope
allow-suspicious-udfs Yes Yes
automatic_sp_privileges Yes Global
chroot Yes Yes
des-key-file Yes Yes
local_infile Yes Global
old_passwords Yes Both
safe-user-create Yes Yes
secure-auth Yes Yes Global
-Variable:secure_auth Yes Global
secure-file-priv Yes Yes Global
-Variable:
secure_file_priv Yes Global
skip-grant-tables Yes Yes
skip-name-resolve Yes Yes Global
-Variable:
skip_name_resolve Yes Global
skip-networking Yes Yes Global
-Variable:
skip_networking Yes Global
skip-show-database Yes Yes Global
-Variable:
skip_show_database Yes Global
Reference:https://dev.mysql.com/doc/refman/8.0/en/security-options.html
Security guidelines for client
programming
Don't trust any data entered by the application user, because there is the
possibility that the user has entered a drop or delete statement for the MySQL
database. So, there is always the risk of security leaks and data loss. As an
administratorofaMySQLdatabase,thefollowingchecklistshouldbefollowed:
ThesizeofthedatamustbecheckedbeforepassingittoMySQL8.
TomakeMySQL8morerestrictive,enablethestrictMySQLmode.
Fornumericfields,entercharacters,specialcharacters,andspacesinstead
of numeric itself. Change field values to their original forms by your
applicationbeforesendingthemtotheMySQL8server.
Usetwodifferent usersforapplicationconnectiontothedatabaseand for
databaseadministration.
Modifydatatypesfromnumerictocharactertypesbyaddingquotesinthe
case of dynamic URLs and web forms. Also add %22 ("), %23 (#), and
%27(')indynamicURLs.
Previouslydefinedfunctionalitiesareavailablebuiltintoalloftheprogramming
interfaces. For example, Java JDBC provides prepared statements with
placeholders,andRubyDBIprovidesthequote()method.
AccesscontrolinMySQL8
Privilegesaremainlyusedtoauthenticateusersandwillverifyusercredentials
and check if a user is allowed for the requested operation or not. When we
connectwiththeMySQL8server,itwillfirstchecktheidentityoftheuserby
theprovidedhostandusername.Afterconnection,whenarequestcomesin,the
system will grant privileges according to the user's identity. Based on this
understanding,wecansaythataccesscontrolcontainstwostageswhenwetryto
connectwiththeMySQL8serverusingtheclientprogram:
Stage 1: The MySQL server will either accept or reject the connection,
basedontheprovidedidentity
Stage2:AftergettingaconnectionfromtheMySQLserver,whentheuser
sendsarequestforperforminganyoperation,theserverwillcheckwhether
sufficientprivilegesareavailablefortheuserornot
TherearesomelimitationsoftheMySQL8privilegesystem:
Userisnotallowedtosetapasswordonspecificobjects,suchasatableor
aroutine.
MySQL8allowsitgloballyattheaccountlevel.
As an admin user, we cannot specify privileges in a way that create/drop
tableisallowedbutcreate/dropdatabaseofthattableisnotallowed.
Youarenotallowedtorestrictuseraccessexplicitly,whichmeansthatexplicitly
matchingtheuserandrefusingitsconnectionisnotpossible.MySQL8manages
thecontentofgranttablesinmemory,sointhecaseofINSERT,UPDATE,andDELETE
statements,executionongranttablesrequirestheservertorestartforeffect.
To avoid server restarts, MySQL has provided a command for flushing
privileges.Wecanexecutethiscommandinthreedifferentways:
1. ByissuingFLUSHPRIVILEGES.
2. Usingmysqladminreload.
3. Usingmysqladminflush-privileges.
Whenwereloadgranttables,itwillworkasperthefollowingmentionedpoints:
Tableandcolumnprivileges:Changesoftheseprivilegeswillbeavailable
fromthenextclient'srequest
Databaseprivileges:Changesoftheseprivilegeswillbeavailablethenext
timetheclientexecutesaUSEdbnamestatement
Global privileges and passwords: Changes of these privileges are
unaffectedforaconnectedclient;itwillbeapplicablefromthesubsequent
connections
PrivilegesprovidedbyMySQL8
Privileges define which operations are permissible to the user accounts. Based
onthelevelofoperationandthecontextinwhichitisapplied,itwillwork.Itis
mainlyclassifiedasfollows:
Database privileges: Applied on the database, and all objects of the
databasewithinit.Itcanbegrantedtoasingledatabaseordefinedglobally
toapplyonalldatabases.
Administrativeprivileges:Itisdefinedatthegloballevel,sonotrestricted
toasingledatabase.ItenablesuserstomanageoperationoftheMySQL8
server.
Databaseobject'sprivileges:Itisusedtodefineprivilegesonthedatabase
objects,suchastables,views,indexes,andstoredroutines.Itcanbeapplied
onaspecificobjectofthedatabase,canbeappliedonallobjectsofagiven
typeinadatabase,orcanbeappliedgloballyforalltheobjectsofagiven
typeinalldatabases.
MySQL8willstoreaccountprivilegerelatedinformationintogranttablesand
store the contents of these tables into memory upon server start-up for better
performance.
Privilegesarefurtherclassifiedintermsofstaticanddynamicprivileges:
Staticprivileges:Theseareavailablebuiltinwiththeserverandcannotbe
unregistered. These privileges are always available for the user to be
granted.
Dynamicprivileges:Theseprivilegescanberegisteredorunregisteredat
runtime. If privileges are not registered, then they are not available to be
grantedforuseraccounts.
Granttables
Granttablescontaininformationrelatedtouseraccountsandgrantedprivileges
for that user. MySQL 8 automatically inserts data into these tables when we
executeanyaccountmanagementstatementsinthedatabase,suchasCREATEUSER,
GRANT,andREVOKE.MySQLallowsinsert,update,ordeleteoptionsongranttables
totheadminuser,butit'snotapreferableapproach.Thefollowingtablesofthe
MySQL8databasecontaingrantinformation:
user:Itcontainsdetailsrelatedtouseraccounts,globalprivileges,andother
non-privilegecolumns
password_history:Itcontainshistoryofpasswordchanges
columns_priv:Itcontainscolumnlevelprivileges
procs_priv:Itcontainsprivilegesrelatedtostoredproceduresandfunctions
proxies_priv:Itcontainsprivilegesforproxyusers
tables_priv:Itcontainstablelevelprivileges
global_grants: It contains details related to dynamic global privileges
assignments
role_edges:Itcontainsedgesforrolesubgraphs
db:Itcontainsprivilegesatthedatabaselevel
default_roles:Itcontainsdetailsrelatedtodefaultuserroles
Granttablescontainscopeandprivilegecolumns:
Scopecolumn:Thiscolumndefinesthescopeofrowsinthetables,which
meansthecontextunderwhichtherowapplies.
Privilegecolumn: This column indicates which operation is permitted to
theuser.TheMySQLservercombinesinformationfromthevariousgrant
tablestobuildacompletedetailofauser'sprivileges.
FromMySQL8.0onward,granttablesusetheInnoDBstorageenginebymanaging
transactionalstates,butbeforethat,MySQLusedtheMyISAMenginebymanaging
nontransactional states. This change enables users to manage all account
management statements in the transactional mode, so in the case of multiple
statements, either all of them are successfully executed or none of them are
executed.
Verification of access control
stages
MySQL8performsaccesscontrolchecksintwodifferentstages.
Stage1-Connectionverification
This is the connection verification stage, so after verification, MySQL 8 will
either accept or reject your connection request. Verification will be performed
withthefollowingconditions:
1. Basedonauser'sidentity,withitspassword.
2. Whetherauser'saccountislockedornot.
The server will deny access if either of these cases fails. Here, the identity
containstheusernameandhostnamefromwhichtherequestiscoming.MySQL
performs a locking check on the account_locked column of the user table and a
credential check on the three columns of the user table scope: Host, User, and
authentication_string.
Stage2-Requestverification
OnceaconnectionisestablishedwiththeMySQLserver,stage2comesintothe
picture,wheretheMySQLservercheckswhichoperationyouwanttoperform
andwhetherthatispermissibletoyouornot.Forthisverification,MySQLuses
the privilege columns of the grant tables; it might be coming from user, db,
tables_priv,columns_priv,orprocs_privtables.
AccountmanagementinMySQL8
As the name implies, this topic describes how to manage user accounts in
MySQL8.Wewilldescribehowtoaddnewaccounts,howtoremoveaccounts,
howtodefineusernamesandpasswordsfortheaccounts,andmore.
<strong>#1mysql>CREATEUSER'user1'@'localhost'IDENTIFIED
BY'user1_password';</strong><br/><strong>#2mysql>GRANT
ALLPRIVILEGESON*.*TO'user1'@'localhost'WITHGRANT
OPTION;</strong><br/><br/><strong>#3mysql>CREATEUSER
'user2'@'%'IDENTIFIEDBY'user2_password';</strong><br/>
<strong>#4mysql>GRANTALLPRIVILEGESON*.*TO
'user2'@'%'WITHGRANTOPTION;</strong><br/><br/>
<strong>#5mysql>CREATEUSER'adminuser'@'localhost'
IDENTIFIEDBY'password';</strong><br/><strong>#6mysql>
GRANTRELOAD,PROCESSON*.*TO'adminuser'@'localhost';
</strong><br/><br/><strong>#7mysql>CREATEUSER
'tempuser'@'localhost';</strong><br/><br/><strong>#8mysql>
CREATEUSER'user4'@'host4.mycompany.com'IDENTIFIEDBY
'password';</strong><br/><strong>#9mysql>GRANT
SELECT,INSERT,UPDATE,DELETE,CREATE,DROPONdb1.*TO
'user4'@'host4.mycompany.com';</strong>
<strong>mysql>DROPUSER'user1'@'localhost';</strong>
Thiscommandwilldropthe'user1'accountfromthesystem.
Securityusingroles
Thesameasauseraccountrolehavingprivileges,wecanalsosaythataroleisa
collectionofprivileges.Asan adminuser, wecangrant andrevoke privileges
from the roles. MySQL 8 provides the following commands, functions, and
variablesrelatedtoroleconfiguration.
SETROLE
SETROLEchangestheactiveroleswithinthecurrentsession.Refertothefollowing
commands related to SET ROLE: mysql> SET ROLE NONE; SELECT
CURRENT_ROLE();
+----------------+
|CURRENT_ROLE()|
+----------------+
|NONE|
+----------------+
mysql>SETROLE'developer_read';SELECTCURRENT_ROLE();
+----------------+
|CURRENT_ROLE()|
+----------------+
|`developer_read`@`%`|
+----------------+
The firstcommand willdeactivate all rolesfor the user in the current session.
YoucanseetheeffectwiththeCURRENT_ROLE();function.Inthesecondcommand,
wearesettingthe'developer_read'roleasdefault,andthencheckingthecurrent
roleusingthepredefinedfunctionagain.
CREATEROLE
CREATE ROLEisusedtocreatearole;refertothefollowingcommand,whichwill
createarolewiththename'developer_role':
CREATEROLE'developer_role';
DROPROLE
DROPROLEisusedtoremovearole.Refertothefollowingcommand,whichwill
removethe'developer_role'role:
DROPROLE'developer_role';
<strong>GRANTALLONmy_db.*TO'developer_role';</strong>
<strong>GRANT'developer_role'TO'developer1'@'localhost';
</strong>
<strong>CREATEUSER'user1';</strong><br/><strong>CREATE
ROLE'role1';</strong><br/><strong>GRANTSELECTONmydb.*
TO'user1';</strong><br/><strong>GRANTSELECTONmydb.*TO
'role1';</strong><br/><strong>CREATEUSER'user2';</strong><br
/><strong>CREATEROLE'role2';</strong><br/><strong>GRANT
'user1','role1'TO'user2';</strong><br/><strong>GRANT'user1',
'role1'TO'role2';</strong>
Inthisexample,user1androle1iscreatedandGRANTisappliedon
theminasimplewaybyusingtheGRANTcommand.Now,foruser2
androle2,wehaveappliedGRANTfromtheuser1androle1,
respectively.
<strong>REVOKEdeveloper_roleFROMuser1;</strong><br/>
<strong>REVOKEINSERT,UPDATEONapp_db.*FROM'role1';
</strong>
Thefirstcommandisusedtoremove'developer_role'foruser1,
andthesecondcommandisusedtoremoveinsertandupdate
privilegesfromthe'role1'on'app_db'.
<strong>mysql>SETDEFAULTROLEapp_developerTO
root@localhost;</strong><br/><br/><strong>mysql>SELECT
CURRENT_ROLE();</strong><br/><strong>+---------------------+
</strong><br/><strong>|CURRENT_ROLE()|</strong><br/>
<strong>+---------------------+</strong><br/><strong>|
`app_developer`@`%`|</strong><br/><strong>+---------------------+
</strong><br/><strong>1rowinset(0.04sec)</strong>
Aftersettingthedefaultrole,restarttheserverandexecutethe
current_role()functiontocheckwhetheraroleisassignedornot.
<strong>mysql>showgrantsforapp_developer;</strong><br/>
<strong>+-------------------------------------------+</strong><br/>
<strong>|Grantsforapp_developer@%|</strong><br/><strong>+---
----------------------------------------+</strong><br/><strong>|GRANT
USAGEON*.*TO`app_developer`@`%`|</strong><br/>
<strong>+-------------------------------------------+</strong><br/>
<strong>1rowinset(0.05sec)</strong>
<strong>mysql>showgrantsforroot@localhost;</strong>
<strong>[mysqld]</strong><br/><strong>
mandatory_roles='app_developer'</strong>
<strong>SETPERSISTmandatory_roles='app_developer';</strong>
ThisstatementapplieschangesontherunningMySQL8instanceand
alsosavesitforsubsequentrestarts.Ifyouwanttoapplychangesfor
therunninginstanceandnotforotherrestarts,thenusethekeyword
GLOBALinsteadofPERSIST.
<strong>ALTERUSER'testuser'@'localhost'PASSWORDEXPIRE;
</strong>
Thiswillmarkapasswordasexpiredforthementioneduser.For
passwordpolicies,youhavetodefinethedurationintermsofthe
numberofdays.MySQLusesthesystemvariable
default_password_lifetime,whichcontainsapositiveinteger
numbertodefinethenumberofdays.Wecandefineitinthemy.cnf
fileorcandefineitatruntimeusingthePERSISToption:
Passwordreuserestrictions:Usedtopreventtheuseofold
passwordsagain.MySQL8definesthisrestrictionbasedontwo
parameters-thenumberofchangesandtimeelapsed;theycanbe
usedseparatelyorincombination.MySQL8defines
password_historyandpassword_reuse_intervalsystem
variables,respectively,toapplyrestrictions.Wecandefinethese
variablesinthemy.cnffile,orcanpersistthem.
password_history:Thisvariableindicatesthatnewpasswords
cannotbeset/duplicatedfromtheoldpasswords.Here,consider
themostrecentoldpasswordsasperthespecifiednumber.
password_reuse_interval:Thisvariableindicatesthatthe
passwordcannotbeset/duplicatedfromtheoldpassword.Here,
intervaldefinesthespecificperiodandMySQL8willchecknew
passwordwithallthepasswordswhichwerefallsunderthat
periodforauser.Forexample,iftheintervalissetas20days,
thenthenewpasswordshouldnothaveexistedinthelast20days
ofchangeddata.
Passwordstrengthassessment:Usedtodefinestrong
passwords.Itisimplementedusingthevalidate_password
plugin.
EncryptioninMySQL8
When there is a need to transfer data over the network, it is a must to use
encryptionfortheconnection.Ifyouareusingunencrypteddata,thensomeone
whohasaccesstothenetworkcaneasilywatchallofyourtrafficand cansee
whatdataistransferredbetweentheclientandserver.Toprotectyourdataover
thenetwork,useencryption.
Make sure the encryption algorithm used contains security elements to protect
your connection from known attacks, like changing the order of a message or
replay twice on data. Based on your application requirements, you can choose
either an encrypted or unencrypted type connection. MySQL 8 performs
encryptionperconnectionusingTransportLayerSecurity(TLS)protocol.
Configuring MySQL 8 to use
encryptedconnections
Thissectiondescribeshowtoconfiguretheserverandclientfortheencrypted
connection.
<strong>[mysqld]</strong><br/><strong>ssl-ca=ca.pem</strong><br
/><strong>ssl-cert=server-cert.pem</strong><br/><strong>ssl-
key=server-key.pem</strong>
The--ssloptionisenabledbydefault,soonserverstartup,MySQL
8willtrytofindthecertificateandkeyfileunderthedatadirectory,
eventhoughyouhavenotdefineditinthemy.cnffile.Ifthosefiles
arefound,thenMySQL8willprovideanencryptedconnection,or
elsecontinuewithoutanencryptedconnection.
Client-side configuration for
encryptedconnections
Attheclientside,MySQLusesthesame–ssloptionsusedattheserversideto
specifythecertificateandkeyfile,butapartfromthat,it has–ssl-modeoptions.
By default, the client is allowed to set up an encrypted connection with the
server if the server permits it. For further control, the client program uses the
following–ssl-modeoptions:
--ssl-mode=REQUIRED:Thisoptionindicatesthatanencryptedconnectionmust
beestablished,andfailsifitisnotestablished
--ssl-mode=PREFFERED:Thisoptionindicatestheclientprogramcanestablishan
encrypted connection if the server permits it, or else establish an
unencryptedconnectionwithoutafail
--ssl-mode=DISABLED:Thisoptionindicatestheclientprogramisunabletouse
anencryptedconnection,andonlyanunencryptedconnectionisallowed
--ssl-mode=VERIFY_CA: This option is the same as REQUIRED, but in addition to
that,itverifiestheCAcertificateagainsttheconfiguredCAcertificateand
returnsafailifnomatchesarefound
--ssl-mode=VERIFY_IDENTITY:ItisthesameastheVERIFY_CAoption,butinaddition
tothat,itwillperformthehostnameidentity
Command options for encrypted
connections
The following options are available in MySQL 8 for an encrypted connection.
You canusetheseoptionsonthecommandline,oryoucandefinetheminan
optionfile:
Format Description
--skip-ssl Donotuseencryptedconnection
--ssl Enableencryptedconnection
--ssl-ca FilethatcontainsalistoftrustedSSLCertificateAuthorities
--ssl-
capath
DirectorythatcontainstrustedSSLCertificateAuthority
certificatefiles
--ssl-cert FilethatcontainsX509certificate
--ssl-
cipher Listofpermittedciphersforconnectionencryption
--ssl-crl Filethatcontainscertificaterevocationlists
--ssl-
crlpath Directorythatcontainscertificaterevocationlistfiles
--ssl-key FilethatcontainsX509key
--ssl-mode Securitystateofconnectiontoserver
--tls-
version Protocolspermittedforencryptedconnections
Reference:https://dev.mysql.com/doc/refman/8.0/en/encrypted-connection-options.html
Connect with MySQL 8 remotely
fromWindowswithSSH
ToconnectremotelywithMYSQL8byusingSSHfromtheMicrosoftWindows
system,performthefollowingsteps:
1. InstalltheSSHclientonyourlocalsystem.
2. AfterstartingtheSSHclient,setthehostnameanduserIDbywhichyou
wanttoconnectwiththeserver.
3. Configureportforwardingasfollowsandsavetheinformation:
For remote forwarding configure: local_port:3306,
remote_host:mysqlservername_or_ip,remote_port:3306
For local forwarding configure: local_port:3306, remote_host:localhost,
remote_port:3306
4. LogintotheserverwiththecreatedSSHsession.
5. In your local Microsoft Windows machine, start any ODBC application,
suchasMicrosoftAccess.
6. In your local system, create new file and try to link with MySQL server
using the ODBC driver. Make sure you have defined localhost in the
connectioninsteadofmysqlservername.
Securityplugins
MySQL8providesseveralpluginstoimplementsecurity.Thesepluginsprovide
variousfeaturesrelatedtoauthenticationprotocols,passwordvalidation,secure
storage,andmuchmore.Let'sdiscussthevarioustypesofpluginsindetail.
<strong>CREATEUSER'testsha256user'@'localhost'</strong><br/>
<strong>IDENTIFIEDWITHsha256_passwordBY'userpassword';
</strong>
SHA-2pluggableauthentication
SHA-2pluggableauthenticationisthesameastheSHA-256pluggableplugin,
except its plugin name is caching_sha2_password. When compare to sha256_password,
thispluginhasthefollowingadvantages:
1. If you are using Unix socket-file and shared-memory protocols, then
supportisprovidedforclientconnections.
2. In-memorycachingisavailableinSHA-2plugins,whichprovidesfasterre-
authenticationforuserswhohaveconnectedpreviously.
3. This plugin provides RSA-based password exchange, which works
regardlessoftheSSL
libraryprovidedbyMySQL8.
Client-side cleartext pluggable
authentication
This plugin is used to send passwords to the server without hashing or
encryption. It is available at the client side with the name mysql_clear_password.
MySQL8providesitbuilt-inwithintheclientlibrary.
<strong>[mysqld]</strong><br/><strong>plugin-load-
add=mysql_no_login.so</strong>
<strong>INSTALLPLUGINmysql_no_loginSONAME
'mysql_no_login.so';</strong>
<strong>UNINSTALLPLUGINmysql_no_login;</strong>
<strong>[mysqld]</strong><br/><strong>plugin-load-
add=auth_socket.so</strong>
<strong>INSTALLPLUGINauth_socketSONAME'auth_socket.so';
</strong>
<strong>UNINSTALLPLUGINauth_socket;</strong>
Testpluggableauthentication
A test plugin is provided by MySQL 8 to check account credentials and log
successesorfailuresontheserverlogs.Itisnotabuilt-inpluginandneedstobe
installedbeforeuse.Thisisavailableforboththeserverandclientside,andis
named test_plugin_server and auth_test_plugin, respectively. MySQL 8 uses the
auth_test_plugin.so library for this plugin. To install and uninstall this plugin,
performthesamestepsmentionedintheprecedingplugin.
Theconnection-controlplugins
MySQL 8 uses these plugins to introduce an increasing delay in the server
responsetotheclientaftersomespecificnumberoffailedconnectionattempts.
MySQLhasprovidedtwopluginsforconnectioncontrol.
<strong>CONNECTION_CONTROL_FAILED_LOGIN_ATTEMPTS</strong>
ThispluginimplementsusesoftheINFORMATION_SCHEMAtableto
providedetailsonmonitoringofthefailedconnections.
<strong>[mysqld]</strong><br/><strong>plugin-load-add=
connection_control.so</strong>
<strong>INSTALLPLUGINCONNECTION_CONTROLSONAME
<br/>'connection_control.so';</strong><br/><strong>INSTALL
PLUGIN
CONNECTION_CONTROL_FAILED_LOGIN_ATTEMPTS
SONAME<br/>'connection_control.so';</strong>
Variables related to
CONNECTION-CONTROL
ThefollowingvariablesareprovidedbyCONNECTION-CONTROLplugins:
Connection_control_delay_generated: This is a status variable, mainly used to
managethecounter.Itindicateshowmanytimestheserveraddedadelayin
its response on failed connection attempts. It also depends on the
connection_control_failed_connections_threshold system variable, because this
statusvariabledoesnotincrementthecountunlessthenumberofattempts
reachesthelimitdefinedbythethresholdvariable.
connection_control_failed_connections_threshold:Thisisasystemvariablewhich
indicates how many consecutive failed attempts are allowed to clients
beforetheserveraddsadelayoneachattempt.
connection_control_max_connection_delay:Thisisasystemvariablewhichdefines
themaximumdelaytimeinmillisecondsfortheserverresponseonfailed
connections attempts. MySQL 8 will consider this variable once the
thresholdvariablecontainsavaluehigherthanzero.
connection_control_min_connection_delay: This system variable defines the
minimum delay time in milliseconds for the server to failed connection
attempt. MySQL 8 will consider this variable once the threshold variable
containsavaluehigherthanzero.
Thepasswordvalidationplugin
Forpasswordvalidation,MySQLprovidesapluginnamedvalidate_password.Itis
mainlyusedtotestpasswordsandimprovesecurity.Thefollowingarethetwo
majorcapabilitiesofthisplugin:
VALIDATE_PASSWORD_STRENGTH(): An SQL function used to find the strength of a
password.Ittakesapasswordasanargumentandreturnsanintegervalue
between0and100.Here,0indicatesaweakpasswordand100indicatesa
strongpassword.
Check password as per policy in SQL statements: For all the SQL
statementswhichuseapasswordasacleartextvalue,thepluginwillcheck
the provided password against the policy of the password and, based on
that, return a response. In the case of a weak password, the plugin will
return an ER_NOT_VALID_PASSWORD error. ALTER USER,CREATE USER, GRANT, SET PASSWORD
statements,andthePASSWORD()functionarealwayscheckedbythispluginif
thepasswordisdefinedascleartextinanargument.
<strong>[mysqld]</strong><br/><strong>plugin-load-
add=validate_password.so</strong>
<strong>INSTALLPLUGINvalidate_passwordSONAME
'validate_password.so';</strong>
Variables and options related to
thepasswordvalidationplugin
MySQL 8 provides following system variables, status variables and options
relatedtopasswordvalidationplugin.
validate_password_check_user_name:Thisisasystemvariable,andisenabledby
defaultinMySQL8.Asthenameimplies,itisusedtocompareapassword
withtheusernameofthecurrentlyeffectiveuser.
If the password matches with the username or its reverse, MySQL 8 will
reject the password, irrespective of the VALIDATE_PASSWORD_STRENGTH() function
value.
validate_password_dictionary_file:This systemvariable containsthe pathname
ofthedirectorywhichisusedbythevalidate_passwordplugin.Youcansetit
at runtime without a server restart, and it is available once the plugin is
installed. Set the password policy value as 2(strong), if you define the
directory for the password check. Possible values for password policy is
describeundervalidate_password_policysystemvariable.
validate_password_length: This system variable is available once a plugin is
installed and is used to define the minimum number of characters for a
passwordtocheckwiththevalidate_passwordplugin.
validate_password_mixed_case_count: This system variable is available once a
pluginisinstalledandisusedtodefinetheminimumnumberoflowercase
anduppercasecharactersforapasswordcheck.
validate_password_number_count: This system variable is available once the
pluginisinstalledandisusedtodefinetheminimumnumberofdigitsfor
thepasswordcheck.
validate_password_special_char_count: This system variable is available once a
plugin is installed and is used to define the minimum number of non-
alphanumericcharactersinapasswordcheck.
validate_password_policy: This system variable is available once a plugin is
installed,anditindicateshowapluginshouldbehaveinthecaseofother
system variables. The following values of this variable describe the
behaviorofthevalidate_passwordplugin:
Policy TestsPerformed
0orLOW Length
1or
MEDIUM Length;numeric,lowercase/uppercase,andspecialcharacters
2or
STRONG Length;numeric,lowercase/uppercase,andspecialcharacters;
dictionaryfile
Reference:https://dev.mysql.com/doc/refman/8.0/en/validate-password-options-variables.html
validate_password_dictionary_file_last_parsed: This is a status variable used to
indicatethetimewhenadirectoryfilewaslastparsed.
validate_password_dictionary_file_words_count: This is a status variable used to
indicatethenumberofwordsreadfromthedirectoryfile.
--validate-password[=value]: Thisoption is usedtodefine howaserver loads
the validate_password plugin on startup. This option is available only if the
pluginwasregisteredwithINSTALLPLUGINorifitisloadedwiththe--plugin-
load-addfeature.
MySQL8keyring
MySQL8providesakeyringservice,whichallowstheMySQLserver'sinternal
componentsandpluginstostoretheirsensitiveinformationforlateruse.Forthis
feature,MySQL8usesthekeyring_fileplugin,whichwillstoredataintothefile
locatedontheserverhost.ThispluginisavailableinalldistributionsofMySQL,
suchastheCommunityEditionandEnterpriseEdition.
<strong>mysqld]</strong><br/><strong>plugin-load-
add=keyring_file.so</strong>
<strong>INSTALLPLUGINkeyring_fileSONAME
'keyring_file.so';</strong>
System variables related to
keyringplugin
MySQL8providesbelowsystemvariablerelatedtokeyringplugin:
keyring_file_data:Thissystemvariableisavailableonceapluginisinstalled
and is used to define a pathname of the data file which is used by the
keyring_fileplugintostoresecuredata.Keyringoperationsaretransactional,
sothispluginusesabackupfileduringwriteoperationtohandlearollback
scenario. In this case, the backfile is also named with the same naming
conventionasdefinedinthekeyring_file_datasystemvariable,withthesuffix
as.backup.
Summary
Inthischapter,westartedwithanoverviewofsecurity,andthentheridebegan
withtheMySQL 8securityrelated features.Firstwe discussedsomecommon
security issues, then we showed how to assign privileges and how to manage
access control in MySQL 8. Encryption was also covered in this chapter, to
secureyoursensitivedata.
And finally, we covered some important security plugins, which are useful to
implementsecurityinMySQL8.
It's now time to move on to our next chapter, where we will be configuring
MySQL8
foroptimization.Foroptimization,wewillcoverdifferentareasofthedatabase,
suchasoptimizingqueries,optimizingtables,optimizingbufferingandcaching,
andmuchmore.Apartfromserverconfiguration,italsocovershowtoconfigure
aclientforoptimization.
OptimizingMySQL8
Inthepreviouschapter,welearnedaboutsecurity,whichisanimportantaspect
ofanyproduction-gradeapplication.Thechapterstartedwithanintroductionto
security and identifying common security issues. Moving on, the chapter
covered access control mechanisms, account management, and encryption in
MySQL8.WelearnedvariousMySQL
8 security plugins in the later part of the chapter. Security is an important
benchmark for every production-grade application. That's why the previous
chapterisanimportantone.
Movingalongasimilarline,withtheobjectiveofdevelopinghighlyoptimized
databases, this chapter focuses on optimization methods. It starts with an
overviewofwhatoptimizationmeansinMySQL8.Ittakesthereaderthrough
MySQL 8 server and client optimization, optimizing database structure, and
optimizingcommonqueriesanddatabasetables.Laterinthechapter,emphasis
isgiventobufferingandcachingtechniques.
Thefollowingisalistoftopicstobecovered:
OverviewofMySQL8optimization
OptimizingMySQL8serversandclients
Optimizingdatabasestructure
Optimizingqueries
Optimizingtables
Leveragingbufferingandcaching
Overview of MySQL 8
optimization
Let's start with understanding MySQL 8 optimization. Optimization is the
processof
identifying performance bottlenecks and implementing optimized solutions to
overcome
these issues. Optimization in MySQL 8 involves performance measurement,
configuration,
andtuningatseveraldifferentlevels.Itisanimportanttaskforanadministrator
to optimize the performance at different levels, like individual SQL queries,
entire
database applications, database servers, or distributed database servers.
Performance
optimizationattheCPUandmemorylevelsimprovesscalability.Italsoallows
the
database to handle more complex queries without slowing down the database
server.
The performance of a database depends on multiple factors. At the database
level,
thesefactorscanbetables,queries,andconfigurations.Databaseserverstartups
anddatabasequeryexecutionsareacoupleoftheeventswhentheseconstructs
impact
theCPUorperformI/O(Input/Output)operationsatthehardwarelevel.Thisis
a
responsibility of the MySQL 8 database administrator: to make sure that the
hardware
performancestandsatanoptimumlevel.Itisrequiredthatthehardwareisused
with
the maximum efficiency possible. At the software level, performance
optimizationstarts
bylearninggenericrulesandguidelinesandmeasuringperformancewithclock
time.
Gradually, we understand the internals of various database operations. We can
measure
theperformance interms ofCPUcyclesandI/Ooperations.Toattainthebest
database
performance, we can optimize the software and hardware configurations at a
basiclevel.
At an advanced level, we can improve MySQL itself by developing custom
storageengines
andhardwareappliances,whichexpandtheMySQLecosystem.
Optimizingthedatabase
What is the most important factor in making the database perform at the
optimumspeed?
Theansweris,basicdatabasedesign.Thefollowingisachecklisttokeepaneye
onfordatabasedesign:
Thedatabasecolumnshavetobeoftherightdatatypes.Tablesmusthave
appropriate
columns for the purposes to be served. Applications that have frequent
operations
to be performed on the database have many tables with fewer columns,
whereasapplications
thatanalyzelargeamountsofdatahavelimitedtableswithmanycolumns.
Aswelearnedinoneofthepreviouschapters,databaseindexingplaysan
important
role in enhancing query performance. So, it is important to have correct
indexesin
placeforqueryexecutionefficiency.
We discussed database storage engines, such as MyISAM or InnoDB, in earlier
chapters.Useofanappropriatestorageengineforeachindividualtable
isimportant.InnoDB ispreferablefor transactionaldatabasetables, whereas
MyISAMispreferablefordefiningnon-trasactionaldatabasetables.Thechoice
ofstorage
engineplaysavitalroleindefiningtheperformanceandscalabilityofthe
database.
In the chapter on MySQL 8 data types, we learned about row formats in
detail.Itis
againimportantforeachtohaveanappropriaterowformat.Thechoiceof
rowformat
dependsonthestorageenginechosen.Compressedtablesoccupylessdisk
spaceand
requirefewerdiskI/Ooperations.ForInnoDBtables,compressionisavailable
forallreadandwriteoperations.Onthecontrary,
compressionisavailableforread-onlyMyISAMtables.
TheMySQLdatabasesupportsmultiplelockingstrategies.Thelockingcan
beatatable-level
orarow-level.Theapplicationmustuseanappropriatelockingstrategy.By
granting
shared access wherever appropriate, it becomes possible to run database
operations
concurrently.Also,itshouldbepossibletorequestexclusiveaccess,sothat
critical
databaseoperationscanbeexecutedwithdataintegrityissuesandpriority
canbe
maintained.Inthis case,the choice ofstorage engineisagain significant.
The InnoDB storage engine handles most locking issues without user
involvement.Itallowsfor
betterconcurrencyandreducestheamountofexperimentationandtuning
forthecode.
The memory areas must use the correct caching size. It should be large
enoughtohold
frequently accessed data, and at the same time, not so large that they
overloadphysical
memoryandcausepaging.TheInnoDBbufferpoolandMyISAMkeycacheare
themainmemoryareastobeconfigured.
For newly created tables, MyISAM is the default storage engine. In
practical use, InnoDB advanced performance features mean that
tables with InnoDB storage engines outperform the MyISAM tables for
anoperations-heavydatabase.
Optimizingthehardware
Growthisthenatureofeverysoftwareapplication.Astheapplicationgrows,so
does the database. The database becomes more and more busy in performing
operations. At a certain point, the database application eventually hits the
hardware limits. An administrator must evaluate the possibility of tuning the
applicationorre-configuringtheservertoavoidtheseissues.Itshould alsobe
evaluated whether deploying more hardware resources would help. System
bottlenecksusuallyarisefromthefollowingsources:
Diskseeks:Aspartofthediskreadoperation,findingapieceofdatatakes
timeforthedisk.
The mean time for finding a piece of data is usually lower than 10
millisecondswithmoderndisks.So, intheory, itshouldbe 100seeksper
second.Withtechnologicalevolution,thenewdiskshaveimprovementson
thedisktime,butitisveryhardtooptimizeforsingletables.Tooptimize
theseektime,itisnecessarytodistributedataacrossmorethanonedisk.
Diskreadingandwriting:Toreadorwritedatafromadisk,itisrequired
forthedisktobeatthecorrectposition.Onediskdeliversatleast10to20
MB of throughput per second (throughput is the amount of data read or
written per second). So, the read and write throughput is more easily
optimizedthantheseektime,aswecanreadinparallelfrommultipledisks.
CPUcycles:Wemustprocessthedatawhenitisinthemainmemorytoget
thedesiredresult.
With large tables, the amount of memory is the most common limiting
factor.Withsmalltables,however,speedisusuallynotanissue.
Memory bandwidth: In an uncommon scenario, the main memory
bandwidthbecomesabottleneckwhentheCPUneedsmoredatathancan
befitintheCPUcachememory.
Optimizing MySQL 8 servers and
clients
ThissectionfocusesonoptimizationforMySQL8databaseserversandclients,
starting
with optimizing the server and followed by optimizing MySQL 8 client-side
entities.This
sectionismore relevanttodatabase administrators,toensure performanceand
scalability
acrossmultipleservers.Itwouldalso helpdevelopers preparingscripts (which
includes
settingupthedatabase)andusersrunningMySQLfordevelopmentandtesting
tomaximize
theproductivity.
OptimizingdiskI/O
Inthissection,wewilllearnwaystoconfigurestoragedevicestodevotemore
and
fasterstoragehardwaretothedatabaseserver.Amajorperformancebottleneck
is
disk seeking (finding the correct place on the disk to read or write content).
When
theamountofdatagrowslargeenoughtomakecachingimpossible,theproblem
with
diskseedsbecomesapparent.Weneedatleastonediskseekoperationtoread,
and
several disk seek operations to write things in large databases where the data
access
is done more or less randomly. We should regulate or minimize the disk seek
times
usingappropriatedisks.
In order to resolve the disk seek performance issue, increasing the number of
available
diskspindles,symlinkingthefilestodifferentdisks,orstrippingdiskscanbe
done.Thefollowingarethedetails:
Using symbolic links: When using symbolic links, we can create a Unix
symboliclinksforindexanddata
files. The symlink points from default locations in the data directory to
another
disk in the case of MyISAM tables. These links may also be striped. This
improvestheseekandreadtimes.The
assumption is that the disk is not used concurrently for other purposes.
Symbolic
linksarenotsupportedforInnoDBtables.However,wecanplaceInnoDBdata
andlogfilesondifferentphysicaldisks.
Striping:Instriping,wehavemanydisks.Weputthefirstblockonthefirst
disk,thesecond
blockontheseconddisk,andsoon.TheNblockonthe(N%number-of-
disks)disk.Ifthestripesizeisperfectlyaligned,
the normal data size will be less than the stripe size. This will help to
improve
theperformance.Stripingisdependentonthestripesizeandtheoperating
system.
Inanidealcase,wewouldbenchmarktheapplicationwithdifferentstripe
sizes.
The speed difference while striping depends on the parameters we have
used,likestripe
size.The differenceinperformancealsodependsonthenumberofdisks.
Wehaveto
chooseifwewanttooptimizeforrandomaccessorsequentialaccess.To
gainreliability,
we may decide to set up with striping and mirroring (RAID 0+1). RAID
standsforRedundantArrayofIndependentDrives.Thisapproachneeds
2 x N drives to hold N drives of data. With a good volume management
software,wecanmanagethissetup
efficiently.
Thereisanotherapproachtoit,aswell.Dependingonhowcriticalthetype
ofdata
is,wemayvarytheRAIDlevel.Forexample,wecanstorereallyimportant
data,such
ashostinformationandlogs,onaRAID0+1orRAIDNdisk,whereaswe
canstoresemi-important
dataonaRAID0disk.InthecaseofRAID,paritybitsareusedtoensure
theintegrity
ofthedatastoredoneachdrive.So,RAIDNbecomesaproblemifwehave
toomany
writeoperationstobeperformed.Thetimerequiredtoupdatetheparitybits
inthis
caseishigh.
If it is not important to maintain when the file was last accessed, we can
mountthe
filesystemwiththe-onoatimeoption.Thisoptionskipstheupdatesonthe
filesystem,whichreducesthedisk
seek time. We can also make the file system update asynchronously.
Dependingupon
whetherthefilesystemsupportsit,wecansetthe-oasyncoption.
UsingNFSwithMySQL
While using a Network File System (NFS), varying issues may occur,
dependingontheoperatingsystemandtheNFSversion.
Thefollowingarethedetails:
DatainconsistencyisoneissuewithanNFSsystem.Itmayoccurbecause
ofmessagesreceivedoutoforderorlostnetworktraffic.WecanuseTCP
withhardandintrmountoptionstoavoidtheseissues.
MySQLdataandlogfilesmaygetlockedandbecomeunavailableforuseif
placedonNFSdrives.IfmultipleinstancesofMySQLaccessthesamedata
directory,itmayresultinlockingissues.ImpropershutdownofMySQLor
power outage are other reasons for filesystem locking issues. The latest
versionofNFSsupportsadvisoryandlease-basedlocking,whichhelpsin
addressingthelockingissues.Still,itisnotrecommendedtoshare adata
directoryamongmultipleMySQLinstances.
Maximumfilesizelimitationsmustbeunderstoodtoavoidanyissues.With
NFS2,onlythelower2GBofafileisaccessiblebyclients.NFS3clients
supportlargerfiles.Themaximumfilesizedependsonthelocalfilesystem
oftheNFSserver.
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
performance_schema<spanclass="tokenpunctuation">.
</span>setup_instruments<spanclass="token
keyword">WHERE</span><spanclass="token
keyword">NAME</span><spanclass="tokenoperator">LIKE
</span><spanclass="tokenstring">'%memory%'</span><span
class="tokenpunctuation">;</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
performance_schema<spanclass="tokenpunctuation">.
</span>setup_instruments<spanclass="token
keyword">WHERE</span><spanclass="token
keyword">NAME</span><spanclass="token
operator">LIKE</span><spanclass="token
string">'%memory/innodb%'</span><spanclass="token
punctuation">;</span><br/><spanclass="tokenoutput"><span
class="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">+</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">+</span>
</span><br/><spanclass="tokenoutput"><spanclass="token
punctuation">|</span>NAME<spanclass="tokenpunctuation">|
</span>ENABLED<spanclass="tokenpunctuation">|</span>
TIMED<spanclass="tokenpunctuation">|</span></span><br/>
<spanclass="tokenoutput"><spanclass="tokenpunctuation">+
</span><spanclass="tokenpunctuation">-</span><span
class="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/adaptivehashindex<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|</span>
NO<spanclass="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/buf_buf_pool<spanclass="tokenpunctuation">|
</span>NO<spanclass="tokenpunctuation">|</span>NO<span
class="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/dict_stats_bg_recalc_pool_t<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|</span>
NO<spanclass="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/dict_stats_index_map_t<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|
</span>NO<spanclass="tokenpunctuation">|</span></span><br/>
<spanclass="tokenoutput"><spanclass="tokenpunctuation">|
</span>memory/innodb/dict_stats_n_diff_on_level<span
class="tokenpunctuation">|</span>NO<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|</span>
</span><br/><spanclass="tokenoutput"><spanclass="token
punctuation">|</span>memory/innodb/other<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|</span>
NO<spanclass="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/row_log_buf<spanclass="tokenpunctuation">|
</span>NO<spanclass="tokenpunctuation">|</span>NO<span
class="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/row_merge_sort<spanclass="tokenpunctuation">|
</span>NO<spanclass="tokenpunctuation">|</span>NO<span
class="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
memory/innodb/std<spanclass="tokenpunctuation">|</span>NO
<spanclass="tokenpunctuation">|</span>NO<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>
memory/innodb/trx_sys_t::rw_trx_ids<spanclass="token
punctuation">|</span>NO<spanclass="tokenpunctuation">|
</span>NO<spanclass="tokenpunctuation">|<br/></span></span>
<spanclass="tokenoutput"><spanclass="tokenpunctuation">+
</span><spanclass="tokenpunctuation">-</span><span
class="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span></strong>
<strong><spanclass="tokenconstant">performance-schema-
instrument</span><spanclass="tokenattr-value"><spanclass="token
punctuation">=</span>'memory/%=COUNTED'</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
performance_schema<spanclass="tokenpunctuation">.
</span>memory_summary_global_by_event_name<span
class="tokenkeyword">WHERE</span>EVENT_NAME<span
class="tokenoperator">LIKE</span><spanclass="token
string">'memory/innodb/buf_buf_pool'</span>\G;<br/><br
/>EVENT_NAME:<spanclass="tokenkeyword">memory</span>
<spanclass="tokenoperator">/</span>innodb<spanclass="token
operator">/</span>buf_buf_pool<br/>COUNT_ALLOC:<span
class="tokennumber">1<br/></span>COUNT_FREE:<span
class="tokennumber">0<br/>
</span>SUM_NUMBER_OF_BYTES_ALLOC:<spanclass="token
number">137428992<br/>
</span>SUM_NUMBER_OF_BYTES_FREE:<spanclass="token
number">0<br/></span>LOW_COUNT_USED:<spanclass="token
number">0<br/></span>CURRENT_COUNT_USED:<span
class="tokennumber">1<br/></span>HIGH_COUNT_USED:<span
class="tokennumber">1<br/>
</span>LOW_NUMBER_OF_BYTES_USED:<spanclass="token
number">0<br/>
</span>CURRENT_NUMBER_OF_BYTES_USED:<span
class="tokennumber">137428992<br/>
</span>HIGH_NUMBER_OF_BYTES_USED:<spanclass="token
number">137428992</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
function">SUBSTRING_INDEX</span><spanclass="token
punctuation">(</span>event_name<spanclass="tokenpunctuation">,
</span><spanclass="tokenstring">'/'</span><spanclass="token
punctuation">,</span><spanclass="tokennumber">2</span><span
class="tokenpunctuation">)</span><spanclass="token
keyword">AS</span><br/>code_area<spanclass="token
punctuation">,</span>sys<spanclass="tokenpunctuation">.
</span>format_bytes<spanclass="tokenpunctuation">(</span><span
class="tokenfunction">SUM</span><spanclass="token
punctuation">(</span>current_alloc<spanclass="token
punctuation">)</span><spanclass="tokenpunctuation">)</span><br
/><spanclass="tokenkeyword">AS</span>current_alloc<br/>
<spanclass="tokenkeyword">FROM</span>sys<spanclass="token
punctuation">.</span>x$memory_global_by_current_bytes<br/>
<spanclass="tokenkeyword">GROUP</span><spanclass="token
keyword">BY</span><spanclass="token
function">SUBSTRING_INDEX</span><spanclass="token
punctuation">(</span>event_name<spanclass="tokenpunctuation">,
</span><spanclass="tokenstring">'/'</span><spanclass="token
punctuation">,</span><spanclass="tokennumber">2</span><span
class="tokenpunctuation">)</span><br/><spanclass="token
keyword">ORDER</span><spanclass="token
keyword">BY</span><spanclass="tokenfunction">SUM</span>
<spanclass="tokenpunctuation">(</span>current_alloc<span
class="tokenpunctuation">)</span><spanclass="token
keyword">DESC</span><spanclass="tokenpunctuation">;</span>
<br/><spanclass="tokenoutput"><spanclass="token
punctuation">+</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">+</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>
code_area<spanclass="tokenpunctuation">|</span>current_alloc
<spanclass="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">+</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/innodb<span
class="tokenpunctuation">|</span>843.24MiB<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>
memory/performance_schema<spanclass="tokenpunctuation">|
</span>81.29MiB<spanclass="tokenpunctuation">|</span>
</span><br/><spanclass="tokenoutput"><spanclass="token
punctuation">|</span>memory/mysys<spanclass="token
punctuation">|</span>8.20MiB<spanclass="tokenpunctuation">|
</span></span><br/><spanclass="tokenoutput"><span
class="tokenpunctuation">|</span>memory/sql<spanclass="token
punctuation">|</span>2.47MiB<spanclass="tokenpunctuation">|
</span></span><br/><spanclass="tokenoutput"><span
class="tokenpunctuation">|</span>memory/memory<span
class="tokenpunctuation">|</span>174.01KiB<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/myisam<span
class="tokenpunctuation">|</span>46.53KiB<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/blackhole<span
class="tokenpunctuation">|</span>512bytes<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/federated<span
class="tokenpunctuation">|</span>512bytes<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/csv<span
class="tokenpunctuation">|</span>512bytes<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>memory/vio<span
class="tokenpunctuation">|</span>496bytes<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">+</span>
</span></strong>
<strong>mysql>showglobalstatus;</strong><br/><strong>+---------
--------------------+--------+</strong><br/><strong>|Variable_name|
Value|</strong><br/><strong>+-----------------------------+--------+
</strong><br/><strong>|Aborted_clients|0|</strong><br/>
<strong>|Aborted_connects|1|</strong><br/><strong>|
Acl_cache_items_count|0|</strong><br/><strong>|
Binlog_cache_disk_use|0|</strong><br/><strong>|
Binlog_cache_use|0|</strong><br/><strong>|
Binlog_stmt_cache_disk_use|0|</strong><br/><strong>|
Binlog_stmt_cache_use|0|</strong><br/><strong>|Bytes_received
|443|</strong><br/><strong>|Bytes_sent|346|</strong><br/>
<strong>|Threads_cached|0|</strong><br/><strong>|
Threads_connected|1|</strong><br/><strong>|Threads_created|1|
</strong><br/><strong>|Threads_running|2|</strong><br/>
<strong>+-----------------------------+--------+</strong>
<strong>mysql>showstatuslike'%Thread%';</strong><br/>
<strong>+------------------------------------------+-------+</strong><br/>
<strong>|Variable_name|Value|</strong><br/><strong>+------------
------------------------------+-------+</strong><br/><strong>|
Delayed_insert_threads|0|</strong><br/><strong>|
Performance_schema_thread_classes_lost|0|</strong><br/>
<strong>|Performance_schema_thread_instances_lost|0|</strong>
<br/><strong>|Slow_launch_threads|0|</strong><br/><strong>|
Threads_cached|0|</strong><br/><strong>|Threads_connected|1|
</strong><br/><strong>|Threads_created|1|</strong><br/>
<strong>|Threads_running|2|</strong><br/><strong>+---------------
---------------------------+-------+</strong>
Optimizinglockingoperations
Asdiscussedinoneoftheearlierchapters,MySQL8useslockingmechanisms
tomanagecontention.Contentionoccurswhenconcurrentlyexecutingqueriesin
multiplethreadstrytogetaholdofonetableatthesametime.Ifthesequeries
areperformedonthetableconcurrently,thetabledataisleftinaninconsistent
state. MySQL 8 supports two types of locking: internal locking and external
locking.
Internal locking is performed by multiple threads within the MySQL server to
managecontentionfortablecontents.Thistypeoflockingisperformedentirely
bytheMySQLserver,withoutinvolvinganyotherprograms.So,whyitiscalled
internal locking? In the case of external locking, the MySQL server and other
programs lock table files to decide which programs can access the table at a
time.
Thefollowingarethetwomethodsforinternallocking:
Row-levellocking.
Table-levellocking.
Row-level locking in MySQL supports simultaneous write access to multiple
sessions. This enables multi-user and highly concurrent applications. While
performing multiple concurrent write operations on a single table, it is highly
possiblethatadeadlockmayoccur.
Inordertoavoidsuchadeadlocksituation,alockingmechanismacquireslocks
atthe beginning of the transaction using the SELECT ... FOR UPDATE statement for
eachsetofrowstobemodified.MySQLappliesthestatementsinthesameorder
within each transaction if transactions lock more than one table. The InnoDB
database engine automatically detects deadlock conditions and rolls back the
affectedtransactions.Consideringthis,deadlocksaffectperformance.
Thedeadlockdetectionmaycauseslowdownifmanythreadswaitforthesame
lock in highly concurrent systems. In such cases, it becomes more efficient to
disabledeadlockdetection.Wecanrelyontheinnodb_lock_wait_timeoutsettingfor
transaction rollback when deadlock occurs. Using the innodb_deadlock_detect
configurationoption,wecandisablethedeadlockdetection.
Thefollowingaretheadvantagesofrow-levellocking:
Whendifferentsessionsaccessdifferentrowsinatable,thenumberoflock
conflictsisfewer
Thenumberofchangestoberolledbackisfewer
Itbecomespossibletolockasingletablerowforalongtime
Table-levellockingisusedbyMySQLforMyISAM,MEMORY,andMERGEtables.Inthe
case of table-level locking, MySQL permits only one session to update these
tablesatatime.Withtable-levellocking,thesestorageenginesbecomesuitable
for read-only or single-user applications. These storage engines request all the
requiredlocksatonce,whenthequerybegins,toavoidanydeadlocks.Italways
locksthetablesinthesameorder.Themajordrawbackwithtable-levellocking
is that it affects concurrency. If other sessions need to modify the table, they
mustwaituntiltheconcurrentdatachangestatementfinishes.
Thefollowingaretheadvantagesoftable-levellocking:
Itrequireslessmemorycomparedtorow-levellocking
Whenusedonalargepartofthetable,itisfast,becauseonlyonelockis
required
IfGROUPBYoperationsareperformedfrequently,itisfast
ThefollowingisthestrategyforMySQLtograntwritelocksontables:
1. Putawritelockonthetableiftherearenowritelocksonthetable
2. Puta lockrequestinthewritelockqueue ifthe tablealready hasa write
lock
ThefollowingisthestrategyforMySQLtograntreadlocksontables:
1. Putareadlockonthetableiftherearenoreadlocksonthetable
2. Putalockrequestinthereadlockqueueifthetablealreadyhasareadlock
Morepriorityisgiventotableupdatesthantableretrievals.Thelockisavailable
tothewritelockrequestsfirst,andthentothereadlockrequestswhenalockis
released.
Thefollowingisanexampletoanalyzetablelockcontention:
mysql>SHOWSTATUSLIKE'Table_locks%';
+-----------------------+-------+
|Variable_name|Value|
+-----------------------+-------+
|Table_locks_immediate|5|
|Table_locks_waited|0|
+-----------------------+-------+
TheMyISAMstorageengineinherentlysupportsmultipleconcurrentinsertsinorder
toreducecontentionbetweenreadersandwritersforatable.ItallowstheMyISAM
tabletoinsertrowsinthemiddleofadata file.Ifthe tabledoesnot haveany
freeblocksinthemiddleofthedatafile,therowsareinsertedattheendofthe
file.ThisenablesMySQLtoexecuteINSERTandSELECTqueriesonthesametable,
concurrently. concurrent_insert is the global system variable which controls the
behavioroftheMyISAMstorageenginetoallowexecutionofconcurrentINSERTand
SELECTstatements.IfthissystemvariableissettoAUTO,concurrentINSERTandSELECT
areallowed.
IfconcurrentinsertsarenotpossibleandwewanttoperformmultipleINSERTand
SELECToperationsonatabletab1,wecanusethetemporarytabletemp_tab1tohold
thetab1tabledataandupdatethetab1tablewiththerowsfromthetemp_tab1table.
Thefollowingisanexamplewhichdemonstratesthisscenario:
mysql>LOCKTABLEStab1WRITE,temp_tab1WRITE;
mysql>INSERTINTOtab1SELECT*FROMtemp_tab1;
mysql>DELETEFROMtemp_tab1;
mysql>UNLOCKTABLES;
<strong>BENCHMARK(loop_count,expression)</strong>
<strong>mysql>selectbenchmark(1000000,1+1);</strong><br/>
<strong>+-------------------------+</strong><br/><strong>|
benchmark(1000000,1+1)|</strong><br/><strong>+-------------------
------+</strong><br/><strong>|0|</strong><br/><strong>+-----------
--------------+</strong><br/><strong>1rowinset(0.15sec)</strong>
Fromtheprecedingexample,wecanfindthatthetimetakento
calculate1+1for1000000timesis0.15seconds.
<strong>mysql>showprocesslist;</strong><br/><strong>+----+------
-----------+-----------------+------+---------+--------+</strong><br/>
<strong>|Id|User|Host|db|Command|Time|</strong><br/>
<strong>+----+-----------------+-----------------+------+---------+--------+
</strong><br/><strong>+------------------------+-----------------------+
</strong><br/><strong>|State|Info|</strong><br/><strong>+-------
-----------------+-----------------------+</strong><br/><strong>+----+----
-------------+-----------------+------+---------+--------+</strong><br/>
<strong>|4|event_scheduler|localhost|NULL|Daemon|214901|
</strong><br/><strong>+----+-----------------+-----------------+------+--
-------+--------+</strong><br/><strong>|8|root|localhost:58629|
NULL|Query|0|</strong><br/><strong>+----+-----------------+------
-----------+------+---------+--------+</strong><br/><strong>+------------
------------+-----------------------+</strong><br/><strong>|Waitingon
emptyqueue|NULL|</strong><br/><strong>+------------------------
+-----------------------+</strong><br/><strong>|starting|showfull
processlist|</strong><br/><strong>+------------------------+-------------
----------+</strong>
<strong>mysql>select*frominformation_schema.processlist;
</strong><br/><strong>+----+-----------------+-----------------+------+--
-------+--------+</strong><br/><strong>|ID|USER|HOST|DB|
COMMAND|TIME|</strong><br/><strong>+----+-----------------+-
----------------+------+---------+--------+</strong><br/><strong>+-------
-----------------+----------------------------------------------+</strong><br
/><strong>|STATE|INFO|</strong><br/><strong>+-------------------
-----+----------------------------------------------+</strong><br/>
<strong>+----+-----------------+-----------------+------+---------+--------+
</strong><br/><strong>|8|root|localhost:58629|NULL|Query|0
|</strong><br/><strong>+----+-----------------+-----------------+------+-
--------+--------+</strong><br/><strong>|4|event_scheduler|
localhost|NULL|Daemon|215640|</strong><br/><strong>+----+-
----------------+-----------------+------+---------+--------+</strong><br/>
<strong>+------------------------+----------------------------------------------
+</strong><br/><strong>|executing|select*from
information_schema.processlist|</strong><br/><strong>+-------------
-----------+----------------------------------------------+</strong><br/>
<strong>|Waitingonemptyqueue|NULL|</strong><br/>
<strong>+------------------------+----------------------------------------------
+</strong>
Themysqladminprocesslistcommand.
Theperformanceschemathreadstable,stagetables,andlock
tables.
Wemustbeabletoviewtheinformationofuserthreads.ThePROCESS
privilegeisrequiredtoviewtheinformationaboutthreadsbeing
executed.Toaccessthreads,aMutexaccessisnotrequired.Ithasless
impactontheMySQLserverperformance.Accessing
INFORMATION_SCHEMA.PROCESSLISTandSHOWPROCESSLISTrequiresa
Mutexandhasanimpactonperformance.Threadsalsoprovide
detailsofbackgroundthreads.INFORMATION_SCHEMA.PROCESSLISTand
SHOWPROCESSLISTdonotprovideinformationaboutbackground
threads.
Thefollowingtableshowstheinformationcontainedineachprocess
listentry:
Information Details
Id Clientconnectionidentifierfortheclientthatthethreadis
associatedwith.
User,Host Accountassociatedwiththethread.
db DefaultdatabaseforthethreadorNULL.
Command,
State Itindicateswhatthethreadiscurrentlydoing.
Time Itindicateshowlongthethreadhasbeeninthecurrentstate.
Info Itcontainstheinformationofthestatementbeingexecutedby
thethread.
Thefollowingisthethreadstatevaluesassociatedwithgeneralquery
processing:
Aftercreate:Itoccurswhenthethreadcreatesatable,including
internaltemporarytables
Analyzing:ItoccurswhenthethreadiscalculatingMyISAMkey
distribution
Checkingpermissions:Itoccurswhencheckingiftheserverhas
therequiredprivilegestoexecutetheSQLstatement
Checkingtable:Itoccurswhenthethreadisperformingatable
checkoperation
Cleaningup:Itoccurswhenthethreadhasprocessedone
commandandfreesthememory
Closingtables:Itoccurswhenthethreadisflushingthe
changedtabledatatodiskandclosingtheusedtables
Alteringtable:Itoccurswhentheserverisprocessingthe
ALTERTABLEstatement
Creatingindex:ItoccurswhenthethreadisprocessingALTER
TABLE...ENABLEKEYSfortheMyISAMtable
Creatingtable:Itoccurswhenthethreadiscreatingatable
end:Itoccursattheend,butbeforethecleanupofALTERTABLE,
CREATEVIEW,DELETE,INSERT,SELECT,orUPDATEstatements
executing:Itoccurswhenthethreadhasbegunexecutinga
statement
init:ItoccursbeforetheinitializationofALTERTABLE,DELETE,
INSERT,SELECT,andUPDATEstatements
Thefollowingisthelistofcommonstatesinthemaster'sbinlog
dumpthreadforreplicationmasterthreads:
Finishedreadingonebinlog;switchingtonextbinlog
Masterhassentallbinlogtoslave;waitingformoreupdates
Sendingbinlogeventtoslave
Waitingtofinalizetermination
ThefollowingisalistofcommonstatesforaslaveserverI/Othread:
Checkingmasterversion
Connectingtomaster
Queueingmastereventtotherelaylog
Reconnectingafterafailedbinlogdumprequest
Reconnectingafterafailedmastereventread
Registeringslaveonmaster
Requestingbinlogdump
Waitingforitsturntocommit
Waitingformastertosendevent
Waitingformasterupdate
WaitingforslaveMutexonexit
WaitingfortheslaveSQLthreadtofreeenoughrelaylogspace
Waitingtoreconnectafterafailedbinlogdumprequest
Waitingtoreconnectafterafailedmastereventread
ThefollowingisalistofcommonstatesforaslaveserverSQL
thread:
Killingslave
Makingtemporaryfile(append)beforereplayingLOADDATA
INFILE
Makingtemporaryfile(create)beforereplayingLOADDATA
INFILE
Readingeventfromtherelaylog
Slavehasreadallrelaylog;waitingformoreupdates
Waitingforaneventfromcoordinator
WaitingforslaveMutexonexit
Waitingforslaveworkerstofreependingevents
Waitingforthenexteventinrelaylog
WaitinguntilMASTER_DELAYsecondsaftermasterexecutedevent
Optimizingdatabasestructure
Asadatabase administrator, wemustlook for efficient waystoorganizetable
schema, tables, and columns. We minimize I/O, plan ahead, and keep related
items together to tune the application code in order to keep performance high
withanincreaseindatavolume.Itusuallystartswithefficientdatabasedesign,
whichmakesiteasierforteammemberstowritehigh-performanceapplication
code.Italsomakesthedatabaselikelytosustainitselfasapplicationsevolveor
arerewritten.
Optimizingdatasize
In order to minimize the space on the disk, we should start designing the
database tables. This results in huge performance improvements, as it reduces
theamountofdatatobewrittentoandreadfromthedisk.Smallertablesusually
needlessmainmemory,whilethecontentsareactivelyprocessedduringquery
execution.Anyreductionintabledataspaceresultsinaneedforsmallerindexes
thatcanbeprocessedfaster.
As discussed in the chapter on MySQL 8 data types, MySQL supports many
different storage engines and row formats. We can decide the storage and
indexingmethodtobeusedforeachtable.Itisabigperformancegaintochoose
thepropertableformat.
Tablecolumns
Weshouldusethesmallestfeasibledatatypeforatablecolumn.Thisresultsin
the most efficient approach. MySQL supports specialized data types to save
memory and disk space. For example, we should use integer types wherever
possible to get smaller tables. Comparing MEDIUMINT and INT,MEDIUMINT is a better
choice,asituses25%lessspacecomparedtoINT.
We mustdeclare columnstobeNOT NULLwhereverpossible.Thisenables better
useofindexesandeliminatestheoverheadoftestingwhethereachvalueisNULL
ornot.ItresultsinfasterSQLoperations.Wecanalsosaveonebitpercolumn
ofstoragespace.WeshoulduseNULLifwereallyrequireit.NULLvaluesshouldnot
beallowedasaresultofdefaultsettingsforeverycolumn.
We can attain huge performance gain for a table and minimize storage space
requirementbyusingfollowingtechniques:
Rowformat
Asadefault,theDYNAMICrowformatisusedwhencreatingInnoDBtables.Wecan
configureinnodb_default_row_format to use row formats other than DYNAMIC. We can
also specify the ROW_FORMAT option explicitly in a CREATE TABLE or ALTER TABLE
statement.
The row formats include COMPACT, DYNAMIC, and COMPRESSED. They decrease row
storagespaceatthecostofincreasedCPUuseforsomeoperations.
Fortheaverageworkload,whichislimitedbythecachehitratesanddiskspeed,
itwillbefaster.IfitislimitedbytheCPUspeed,itwillbeslower.
TherowformatsalsooptimizetheCHARdatatypecolumnstoragewhenitusesa
variable length character set. With the REDUNDANT row format, the CHAR(N)column
valueoccupiesNtimesthemaximumbytelengthinthecharacterset.TheInnoDB
storageengineallocatesvariableamountsofstoragewithintherangeofNtoN
timesthemaximumbytelengthinthecharacterset.
Afixed-sizerowformatisusedifwedonothavevariable-lengthcolumns,such
asVARCHAR,TEXT,orBLOB,inthecaseofMyISAMtables.
Indexes
A table's primary index must be as short as feasible. This enables easy
identification of each row. It is efficient, too. In the case of InnoDB tables, the
primarykeycolumn isduplicatedin each secondaryindexentry. Ifwehave a
shortprimarykey,itsavesspaceinthecaseofmanysecondaryindexes.
We should create only those indexes which improve query performance. The
indexesimproveinformationretrieval,buttheyslowdowntheinsertandupdate
operations. Indexes must be created with proper attention to the performance
impact. If it is required to access a table by searching on a combination of
columns, it is preferred to have a composite index on the combination of
columns, rather than a separate index on each of the columns. The most used
columnshouldbethefirstpartoftheindex.Ifitisacommonrequirementtouse
many columns in selected operations on the table, it is advisable to have the
column with the most duplicates as the first column in the index. This gives
bettercompressionoftheindex.
If a long string column is supposed to have a unique prefix as the first few
characters,itis advisableto indexonlythe prefix,using MySQL'ssupportfor
indexingontheleftmostpartofthecolumn.Shorterindexesarepreferred,not
onlyforthelessspacetheyrequire,butalsobecausetheyprovidemorehitsin
theindexcacheandrequirefewerdiskseeks.
Joins
Ifatableisscannedveryoften,itisbeneficialtosplitthetableintotwotables,if
feasible. This holds true especially if it is a dynamic-format table. It is also
possible to use smaller static format tables, which can be used to search for
relevantrowswhilescanningthetables.
The columns with identical information should be declared in different tables
withidenticaldatatypes.Thisspeedsupjoinsbasedonmatchingcolumns.
Columnnamesmustbekeptsimple,soastousethesamenameacrosstables.It
simplifies join queries. For example, in a customer table, we should use the
columnnameofname,ratherthanusingcustomer_name.Inordertomakethenames
portabletootherSQLservers,weshouldkeepthecolumnnamesshorterthan18
characters.
Normalization
Thedatainthetablecolumnsmustbekeptnon-redundant,consideringthethird
normalforminthenormalizationtheory.Ifthecolumnholdsrepeatinglengthy
values, such as names or addresses, it is preferable to assign unique IDs and
repeat these IDs across multiple smaller tables. In the event of searching, join
queriesshouldbeusedbyreferencingIDsinthejoinclauses.
In an application, if the preference is speed and not disk space or the
maintenancecostsof usingmultiple copiesofdata, itis advisabletoduplicate
the information or create summary tables to gain more speed. An example
scenario could be a business intelligence system, where data is analyzed from
largetables.Inthiscase,normalizationrulesarenotstrictlyfollowed.
OptimizingMySQLdatatypes
Thefollowingaretheguidelinesforoptimizingnumericdatatypes:
Numeric columns must be preferred over string columns to store unique
IDsorother
valuesthatcanberepresentedaseitherstringsornumbers.Itisfasterand
occupies
less memory to transfer and compare, because large numeric values are
storedinfewer
bytescomparedtostrings.
Itisfastertoaccessinformationfromadatabasethanfromatextfile.This
is
especially true when numeric data is used. Information in the databaseis
storedin
a more compact format than in the text file. So, it requires fewer disk
accesses.
Thefollowingaretheguidelinesforoptimizingcharacterandstringdatatypes:
The binary collation order (logical sequence) should be used for faster
comparisons
andsortoperations.Thebinaryoperatorcanalsobeusedwithinaqueryto
usebinary
collationorder.
WithanInnoDBtable,whenweusearandomlygeneratedvalueasaprimary
key,itshouldbeprefixed
withanascendingvalue,suchasthedateandtime,iffeasible.Inthiscase,
primary
key values are stored nearer to each other, physically. InnoDB can insert or
retrievesuchvaluesfaster.
The binary VARCHAR data type should be used instead of BLOB for column
valuesthatareexpectedtoholdlessthan8KBofdata.Iftheoriginal
table does not have any BLOB columns, the GROUP BY and ORDER BY clauses
generatetemporarytables.ThesetemporarytablescanusetheMEMORYstorage
engine.
In order to avoid string conversions while running a query, the columns
shouldbe
declared with the same character set and order wherever possible when
comparingthe
valuesfromdifferentcolumns.
Ifthetableholdsstringcolumnswhicharenotfrequentlyusedinretrieval
operations,
splitting the string columns into a separate table should be considered. In
theretrieval
operations, join queries should be used with a foreign key wherever
necessary.MySQL
readsadatablockcontainingallthecolumnsofarowwhenitretrievesany
value
fromarow.Itallowsmorerowstofitwithineachdatablockwhenwekeep
therows
small, with only frequently used columns. These compact tables reduce
memoryusage
anddiskI/O.
ThefollowingaretheguidelinesforoptimizingBLOBdatatypes:
The performance requirements for a BLOB column may be different when
retrievinganddisplayinginformation.So,storingthe
BLOB specific table in a different storage device or a separate database
instanceshould
be considered. For example, it is required to retrieve a BLOB in a large
sequentialdiskread.So,atraditionalharddriveoranSSDdevicemight
bettersuitneeds.
Inordertoreducethememoryrequirementsforaquerywhichdoesnotuse
a BLOB column, for a table with several columns, splitting the BLOB into
separatetablesand referencingwithjoin queriesshouldbe considered,as
needed.
Ifatablecolumnisalargeblobwithtextualdata,compressingshouldbe
considered
first.Iftheentiretableiscompressedbythestorageengine,suchasInnoDB
orMyISAM,thistechniqueshouldnotbeused.
<strong>>mysqladminstatus</strong><br/><strong>Uptime:
262200Threads:2Questions:16Slowqueries:0Opens:111Flush
tables:2Opentables:87Queriespersecondavg:0.000</strong>
<strong>mysql>SHOWGLOBALSTATUSLIKE
'%Opened_Tables%';</strong><br/><strong>+---------------+-------+
</strong><br/><strong>|Variable_name|Value|</strong><br/>
<strong>+---------------+-------+</strong><br/><strong>|
Opened_tables|112|</strong><br/><strong>+---------------+-------+
</strong>
Useofaninternaltemporarytable
inMySQL
The MySQL 8 server creates temporary internal tables while processing SQL
statements, in some cases. The following are the conditions under which the
servercreatestemporarytables:
UNIONstatements
ViewswhichusestheTEMPTABLEalgorithm,UNION,oraggregation
Derivedtables
Commontableexpressions
Tablescreatedforsubqueryorsemijoinmaterialization
StatementsthatcontainORDERBYandGROUPBYclauses
StatementswithDISTINCTcombinedwithORDERBY
QueriesthatusetheSQL_SMALL_RESULTmodifier
INSERT...SELECTstatementsthatselectfromandinsertintothesametable
MultipletableUPDATEstatements
GROUP_CONCAT()orCOUNT(DISTINCT)expressions
TheEXPLAINstatementcanbeusedtodeterminewhetherthestatementrequiresa
temporarytable.
TheEXPLAINstatementhaslimitations.Itwillnotindicateifthestatementrequires
atemporarytableforderivedormaterializedtemporarytables.
The Created_tmp_tables status variable keeps track of the number of temporary
tablescreatedininternalmemory.WhentheMySQLservercreatesatemporary
table, it increments the value in the Created_tmp_tables status variable.
Created_tmp_disk_tablesisanotherstatusvariablethatkeepstrackofthenumberof
tablescreatedonthedisk.
Basedonthequeryconditions,theserverpreventstheuseoftemporarytablesin
memory.Insuchcases,theservercreatesatableonthedisk.Thefollowingare
someinstances:
IfthetablehasaBLOBorTEXTcolumn
Ifthestatementhasastringcolumnwithamaximumlengthlargerthan512
bytesintheSELECTlist,ifUNIONorUNIONALLisused
IftheSHOWCOLUMNSandDESCRIBEstatementsuseBLOBasthetypeofthecolumn
ThefollowingaretheconditionsinwhichaUNIONisevaluatedwithoutcreating
temporarytables:
TheunionisUNIONALLandnotUNIONorUNIONDISTINCT
ThereisnoglobalORDERBYclause
InaSELECTquery,theunionisnotatthetop-levelqueryblock
Optimizingqueries
Similartotables,databasequeriesarethemostcrucialelementofanydatabase.
Applications interact with the databases using queries. Queries are also called
executableSQL statements.Thissection focuses ontechniquesto improve the
performanceofqueryexecution.
<strong><spanclass="tokenpunctuation">(</span><span
class="tokenpunctuation">(</span>a<spanclass="token
operator">AND</span>b<spanclass="tokenpunctuation">)</span>
<spanclass="tokenoperator">AND</span>c<spanclass="token
operator">OR</span><spanclass="tokenpunctuation">(</span>
<spanclass="tokenpunctuation">(</span><spanclass="token
punctuation">(</span>a<spanclass="tokenoperator">AND</span>
b<spanclass="tokenpunctuation">)</span><spanclass="token
operator">AND</span><spanclass="tokenpunctuation">(</span>c
<spanclass="tokenoperator">AND</span>d<spanclass="token
punctuation">)</span><spanclass="tokenpunctuation">)</span>
<spanclass="tokenpunctuation">)</span><spanclass="token
punctuation">)</span><br/><spanclass="tokenprompt">->
</span><spanclass="tokenpunctuation">(</span>a<span
class="tokenoperator">AND</span>b<spanclass="token
operator">AND</span>c<spanclass="tokenpunctuation">)</span>
<spanclass="tokenoperator">OR</span><spanclass="token
punctuation">(</span>a<spanclass="tokenoperator">AND</span>
b<spanclass="tokenoperator">AND</span>c<spanclass="token
operator">AND</span>d<spanclass="tokenpunctuation">)</span>
</strong>
<strong><spanclass="tokenpunctuation">(</span>a<span
class="tokenoperator"><</span>b<spanclass="token
operator">AND</span>b<spanclass="tokenoperator">=
</span>c<spanclass="tokenpunctuation">)</span><span
class="tokenoperator">AND</span>a<spanclass="token
operator">=</span><spanclass="tokennumber">5</span><br/>
<spanclass="tokenprompt">-></span>b<spanclass="token
operator">></span><spanclass="tokennumber">5</span><span
class="tokenoperator">AND</span>b<spanclass="token
operator">=</span>c<spanclass="tokenoperator">AND</span>
a<spanclass="tokenoperator">=</span><spanclass="token
number">5</span></strong>
<strong><spanclass="tokenpunctuation">(</span>B<span
class="tokenoperator">>=</span><spanclass="token
number">5</span><spanclass="tokenoperator">AND</span>
B<spanclass="tokenoperator">=</span><spanclass="token
number">5</span><spanclass="tokenpunctuation">)</span><span
class="tokenoperator">OR</span><spanclass="token
punctuation">(</span>B<spanclass="tokenoperator">=</span>
<spanclass="tokennumber">6</span><spanclass="token
operator">AND</span><spanclass="tokennumber">5</span><span
class="tokenoperator">=</span><spanclass="token
number">5</span><spanclass="tokenpunctuation">)</span><span
class="tokenoperator">OR</span><spanclass="token
punctuation">(</span>B<spanclass="tokenoperator">=</span>
<spanclass="tokennumber">7</span><spanclass="token
operator">AND</span><spanclass="tokennumber">5</span><span
class="tokenoperator">=</span><spanclass="token
number">6</span><spanclass="tokenpunctuation">)</span><br/>
<spanclass="tokenprompt">-></span>B<spanclass="token
operator">=</span><spanclass="tokennumber">5</span><span
class="tokenoperator">OR</span>B<spanclass="tokenoperator">=
</span><spanclass="tokennumber">6</span></strong>
Optimizingindexes
Thebasicuseofindexesistoquicklyfindtherowswithspecificcolumnvalues.
Iftheindexisnotpresent,MySQLbeginswiththefirstrowandreadsthrough
theentiretabletofindallthematchingrows.Ittakesmoretime,dependingon
howlargeatableis.Iftheindexispresentfortheappropriatecolumns,MySQL
isabletoquicklydeterminethepositiontoseektointhemiddleofthedatafile,
withoutlookingatthewholetabledata.
ThefollowingisalistofoperationsforwhichMySQLusesindexes:
Tofindmatchingrows,basedonaWHEREclause,quickly.
MySQL uses the index with the smallest number of rows (most selective
index)inthecaseofchoosingfrommultipleindexestoeliminaterowsfrom
consideration.
Theoptimizerusestheleftmostprefixoftheindextolookuprowsifthe
table has a composite index. For example, in a table with three columns
indexed(oncol1,col2,col3),theoptimizercanlookforrowswithindexed
searchcapabilitieson(col1),(col1,col2),and(col1,col2,col3).
MySQLusesindexeswhileitfetchesrowsfromothertablesusingjoins.If
theindexesaredeclaredasthesametypeandsize,MySQLcanusethem
efficientlyonthecolumn.
TheVARCHARandCHARareconsideredthesamewhendeclaredasthesamesize.
MySQLalsousesindexestofindtheminimum(MIN())ormaximum(MAX())valuefor
anindexedcolumnkey_col.ThepreprocessorcheckswhetheritisusingWHERE
key_part_N=constantonallkeypartstooptimizeit.
It is also possible to optimize the query to retrieve values without
consultingthedatarows.(Acoveringindexisanindexthatprovidesallthe
resultsforaquery.)Ifthequeryusesonlythosecolumnsfromatablewhich
are included in some index, the selected values will be fetched from the
indextree.Thiswillhaveahigherspeedinretrievingvalues.
Queryexecutionplan
TheMySQLoptimizerconsidersoptimizationtechniquestoefficientlyperform
the lookups involved in the query, depending on the details of the tables,
columns,andindexes,andtheconditionsintheWHEREclause.Aquerycanalsobe
performedwithoutreadingalltherowsonahugetable.
An SQL join can also be performed without comparing every combination of
rows.Aqueryexecution plan isaset ofoperationsthat theMySQLoptimizer
choosestoperformthemostefficientquery.ItisalsoknownastheEXPLAINplan.
Asanadministrator,thegoalistorecognizetheaspectsofthequeryexecution
planwhichindicateifaqueryisoptimized.
The EXPLAIN statement is used to determine the query execution plan. The
followingisthesetofinformationprovidedbytheEXPLAINstatement:
The EXPLAIN statement works with SELECT, DELETE, INSERT, UPDATE, and REPLACE
statements.
MySQL displaysinformationfrom the MySQLoptimizerabout the query
execution plan when EXPLAIN is used with the SQL statement. This means
MySQL explains the process with which the statement is executed. It
includesinformationabouthowtablesarejoined,andinwhichorder.
If EXPLAIN displays the execution plan for the statement execution in the
namedconnectionifitisusedwithFOR CONNECTIONconnection_idinstead of
explainableSQLstatement.
EXPLAINdisplaysadditionalexecutionplaninformationforSELECTstatements.
EXPLAINisalsousefulinexaminingquerieswhichinvolvepartitionedtables.
EXPLAIN supports a FORMAT option, which can be used to select the output
format.TheTRADITIONALformatdisplaystheoutputinatabularformat.Thisis
thedefaultformatoption.
The JavaScript Object Notation (JSON) format option produces
informationintheJSONformat.
Based on the output from the EXPLAIN statement, it can be figured out where
indexescanbeaddedtothetables,sothatthestatementexecutesfaster.Itcan
also be found whether the optimizer joins the tables in the optimized order.
BeginthestatementwithSELECTSTRAIGHT_JOIN,insteadofjustSELECT,togiveahint
totheoptimizertousethejoin ordercorresponding totheorderthetablesare
namedintheSELECTstatement.AsSTRAIGHT_JOINdisablessemi-jointransformations,
itmaypreventtheuseofindexes.
The optimizer trace is another tool to find the information on the query
execution.
Itispossiblethattheoptimizertracemayprovideinformationdifferingfromthat
ofEXPLAIN.Theformatandcontentoftheoptimizertracearesubjecttovariation,
basedontheversions.
ThefollowingtableshowstheoutputformatoftheEXPLAINstatement:
Column JSONName Details
id select_id TheSELECTidentifier
select_type None TheSELECTtype
table table_name Thetablefortheoutputrow
partitions partitions Thematchingpartitions
type access_type Thejointype
possible_keys possible_keys Thepossibleindexestochoose
key key Theindexactuallychosen
key_len key_length Thelengthofthechosenkey
ref ref Thecolumnscomparedtotheindex
rows rows Estimateofrowstobeexamined
filtered filtered Percentageofrowsfilteredbytablecondition
Extra None AdditionalInformation
Reference:https://dev.mysql.com/doc/refman/8.0/en/explain-output.html#explain-output-
column-table
Optimizingtables
Database tables are the most basic building blocks for any database. In this
sectionofthechapter,wewillfocusonoptimizingtables.Thesectionprovides
detailed guidelines for improving performance through table optimization
techniques.
OptimizationforInnoDBtables
TheInnoDB storage engine is preferred in production environments in situations
wherereliabilityandconcurrencyareimportant.Itisthedefaultstorageengine
forMySQLtables.
ThissectionfocusesonoptimizingdatabaseoperationsforInnoDBtables.
ThefollowingaretheguidelinestooptimizeInnoDBtables:
Useofthe OPTIMIZE TABLE statement should be considered to reorganize the
tableandcompactthewastedspaceoncethedatareachesastablesizeor
thetablehasincreasedbytensofmegabytes.
ItrequireslessdiskI/Otoperformfulltablescansforreorganizedtables.
The OPTIMIZE TABLE statement copies the data in the table and rebuilds the
indexes. It is beneficial because of improved packing of the data within
indexes, and fragmentation reduction within the table spaces on the disk.
The benefits may vary, depending on the data in each table. It may be
noticeablethatthegainsaresignificantinsomecases,andnot forothers.
Thegainsmayalsodecreaseovertimeuntilthenexttableoptimizationis
done.The operationcanbeslowifthetableislargeor theindexesbeing
rebuiltdonotfitinthebufferpool.
AlongprimarykeyinaInnoDBtablewastesalotofdiskspace.Itshouldbe
avoided.
InInnoDBtables,preferenceshouldbegiventotheVARCHARdatatypeinsteadof
theCHARdatatypetostorevariablelengthstrings,orforcolumnswhichare
expected to contain NULL values. A CHAR(N) column always occupies N
characters to store data, even if the value is NULL. Smaller tables are more
suitabletofitinthebufferpoolandreduceddiskI/O.
Considerusinga COMPRESSED row format for big tables, or tables containing
lotsofrepetitivetextornumericdata.
OptimizationforMyISAMtables
Forread-onlyorread-mostlydata,orforlowconcurrencyoperations,theMyISAM
storage engine fits the best. This is because table locks limit the ability to
perform simultaneous updates. In this section, the focus will be on optimizing
queriestobeexecutedonMyISAMtables.
ThefollowingaretheguidelinesforspeedingupqueriesonMyISAMtables:
AvoidexecutingcomplexSELECTqueriesonfrequentlyupdatedMyISAMtables.
It prevents problems with table locking that occur because of contention
betweenwritersandreaders.
TheMyISAMstorageenginesupportsconcurrentinserts.Ifthetabledatafile
doesnothavefreeblocksinthemiddle,wecanINSERTnewrowsinitatthe
sametimethatotherthreadsarereadingfromthetable.Considerusingthe
table to avoid deleting rows if it is important to be able to do concurrent
read-write operations. Another option is to execute OPTIMIZE TABLE to
defragment the table after deletion of the rows. This behavior can be
controlledormodifiedbysettingtheconcurrent_insertsystemvariable.
Avoidallvariable-lengthcolumnsforfrequentlychangingMyISAMtables.The
dynamicrowformatisusedbythetableifitincludesevenasinglevariable
lengthcolumn.
The myisamchk --sort-index --sort-records=1 command can be used to sort an
index.Italsosortsdataaccordingtotheindex.
This makes the queries run faster if we have unique indexes, based on
whichwewanttoreadallrowsintheorderaccordingtotheindex.Ittakes
alongtimewhenwesortalargetablethiswayforthefirsttime.
Ifweusuallyretrieverowsintheorderofexpression1,expression2,andsoon,
use ALTER TABLE ... ORDER BY expression1, expression2,.., and so on. This will
give higher performance, if this option is used after extensive changes to
thetable.
OptimizationforMEMORYtables
MySQLMEMORYtablesshouldbeconsideredforuseonlyfornoncriticaldatathatis
accessed often and is read-only and rarely updated. The application should be
benchmarkedagainstequivalentInnoDBorMyISAMtablesunderrealisticworkloads
toconfirmthatadditionalperformanceisworththeriskoflosingdata.
Weshouldexaminethekindsofqueriesagainsteachtableforbestperformance
with MEMORY tables. We should also specify the type of use for each associated
index.ItcanbeaB-treeindexorahashindex.UsetheUSINGBTREEorUSING HASH
clauseontheCREATEINDEXstatement.
Leveragingbufferingandcaching
Thissectionfocusesonusing bufferingandcachingtechniquesto increasethe
performance.
InnoDBbufferpooloptimization
TheInnoDBstorageenginemaintainsastorageareaknownasthebufferpool.Itis
usedfor
cachingdataandindexesinthememory.ItisimportanttoknowhowtheInnoDB
bufferpoolworks,soastotakeadvantageofittokeepfrequentlyaccesseddata
inmemory.ItisanimportantaspectofMySQLtuning.
The following are the general guidelines for improving performance with the
InnoDBbufferpool:
In an ideal case, the size of the buffer pool should be set large enough,
whileleaving
enoughmemoryforotherprocessesontheservertorunwithoutexcessive
paging.With
larger buffer pools, more InnoDB functions, like an in-memory database. In
thiscase,itreadsdatafromthedisk
once,andthenaccessesthedatafrommemoryinsubsequentreads.
Wecanconsidersplittingthebufferpoolintomanypartsfor64-bitsystems
with
large memory sizes. This minimizes contention for memory during
concurrentoperations.
Thefrequentlyaccesseddatashouldbekeptinmemory.
ItispossibletocontrolwhenandhowInnoDBperformsread-aheadrequests
toprefetchpagesintothebufferpoolasynchronously.
InnoDBusestworead-aheadalgorithmstoimproveI/Operformance.Linear
readaheadpredicts
whatpagesmightbeneededsoon,basedonthepagesbeingaccessedinthe
bufferpool
sequentially. Random read ahead predicts when pages might be needed
basedonthepages
in the buffer pool, regardless of the order in which pages are read. The
innodb_read_ahead_thresholdconfigurationparametercontrolsthesensitivityof
linearreadahead.Wecanenable
randomreadaheadsbysettinginnodb_random_read_aheadtoON.
innodb_buffer_pool_read_ahead determines the number of pages read into the
InnoDBbufferpool.innodb_buffer_pool_read_ahead_evicteddeterminesthenumber
ofpagesreadintothebufferpoolbytheread-aheadbackground
thread that was subsequently evicted without having been accessed by
queries.The
innodb_buffer_pool_read_ahead_rnd determines the number of random read
aheadsinitiatedbyInnoDB.
MyISAMkeycache
The MyISAM storage engine incorporates a strategy that is supported by many
databasemanagementsystemstominimizethediskI/O.Thecachemechanism
is employed by MyISAM to keep the most frequently accessed table blocks in
memoryasfollows:
A special structure known as a key cache is maintained for index blocks.
Themostusedindexblocksareplacedinthestructurecontaininganumber
ofblockbuffers.
MySQL relies on the native operating system filesystem cache for data
blocks.
Thekey_buffer_sizesystemvariabledeterminesthesizeofthekeycache.Ifitis
set to zero, no key cache is used. The key cache is also not used if the
key_buffer_sizevalueistoosmalltoallocatetheminimumorderofblockbuffers.
Alltheblockbuffersinthekeycachestructureareofthesamesize.Thissize
canbeequal to, greaterthan,or lessthanthe size ofthetable indexblock.In
usualcases,oneofthesetwovaluesisamultipleoftheother.
When it is required to access data from any table index block, the server first
checks if it is available in some block buffer of the key cache. If the data is
available,theserveraccessesdatafromthekeycacheratherthanonthedisk.If
thedataisnotavailable,theserverselectsacacheblockbufferthatcontainsa
different table index block and replaces the data in it by copying the required
tableindexblock.
Theindexdatacanbeaccessedassoonasthenewindexblockisavailableinthe
cache.
TheMySQLserverfollowstheLeastRecentlyUsed(LRU)strategy.According
to it, it selects the least recently used index block while choosing a block for
replacement.ThekeycachemodulecontainsallusedblocksintheLRUchain(a
speciallist).Thelistisorderedbythetimeofuse.Itisthemostrecentlyused
whentheblockisaccessed.Theblockisplacedattheendofthelist.Blocksat
thebeginningofthelistaretheleastrecentlyusedwhentheblocksneedtobe
replaced.So,theblockatthetopbecomesthefirstcandidateforeviction.
The block is considered dirty if the block selected for replacement has been
modified.
Theblockcontentsareflushedtothetableindexfromwhichtheycamepriorto
replacement.
Based on the following conditions, the threads can access key cache buffers
simultaneously:
Thebufferwhichisnotbeingupdatedcanbeaccessedbymultiplesessions
Thebufferwhichisbeingupdatedcausessessionsthatrequirewaitinguntil
theupdateiscompletetouseit
As long as the sessions are independent and do not interfere with each
other, multiple sessions can initiate requests resulting in cache block
replacements
Inthisway,sharedaccesstothekeycacheimprovesperformancesignificantly.
Summary
In this chapter, we learned, in detail, the techniques to optimize MySQL 8
components.
The chapter started with the basics of optimization, including hardware and
softwareoptimizationguidelines.Wealsodiscussedoptimizationguidelinesfor
theMySQL8
server and client, database structure, queries, and tables. We also covered
optimization for tables belonging to different storage engines, such as MyISAM,
InnoDB,andMEMORY.Welearnedthetools,suchasEXPLAINandEXPLAINANALYZE,needed
to understand the query execution plan. In the later part of the chapter, we
learnedbufferingandcachingtechniquestoimproveperformance.
It's time to move on to the next chapter now. The next chapter focuses on
techniques to extend MySQL 8. The chapter will cover in-depth details of
MySQL8plugins,whichhelptoextendthedefaultMySQL 8features.Itwill
alsoexplainthe servicesto calltheseplugins. Thechapter willdiscussadding
newfunctions, debugging,and portingmethods. Itis goingto bean important
chapterfordatabaseadministrators.
ExtendingMySQL8
Inthepreviouschapter,welearnedhowtooptimizeMySQL8.Wealsolearned
what configurations need to be done to achieve optimization, and also how to
leveragecachingandbufferingforoptimization.Wewentthroughtheusecase
studystepbystepforachievingoptimizationinthefollowingcomponents:
OptimizingMySQL8serverandclient
Optimizingdatastructures
Optimizingqueries
Optimizingtables
In this chapter, we will learn about extending MySQL 8. We will check what
MySQL8
components are allowed to extend, and we will look at how to customize
MySQL 8 for specific business needs. You will learn about the fundamental
componentspriortoextendingMySQL8andthefeaturesoftheMySQLplugin
API that will be used to extend MySQL 8. The following is the list of topics
coveredinthischapter:
AnoverviewofextendingMySQL8
Extendingpluginsandusingservicestocallthem
Addingnewfunctions
Debuggingandporting
AnoverviewofextendingMySQL
8
Inthissection,youwilllearnaboutoneofthemostexcitingtopicsonhowto
extendMySQL8asperyourneeds.ThereareseveralcomponentsofMySQL8
thatyoushouldunderstandwellpriorattemptingtoextendMySQL8.Hereisa
listofthecomponentsthatareimportantforextendingMySQL8:
MySQL8internals
MySQL8pluginAPI
MySQL8servicesforcomponentsandplugins
AddingnewfunctionstoMySQL8
DebuggingandportingMySQL8
MySQL8internals
TherearefewthingsyoushouldknowbeforeyoustartworkingontheMySQL
code. To contribute or track MySQL development you should follow the
instructionsfortheinstallationofsourcecodedistributionasperyoursystemor
operating system platform. The source code includes internal documentation,
whichisveryimportanttounderstandhowMySQL
internally works from developer's perspective. You can also subscribe to the
internalsmailinglistfromhttps://lists.mysql.com/internals,whichincludespeople
whoworkonMySQLcode,andyoucanalsodiscusstopicsrelatedtoMySQL
developmentorpostingpatches:
MySQL 8 threads: MySQL server creates threads such as connection
manager threads, signal threads, read and write threads if using InnoDB
storageengine,schedulerthreadstohandleconnection,andreplicationand
eventprocessing.
MySQL 8 test suite: MySQL 8 provides the test systems included with
Unixsourcedistributiontohelpusersanddevelopersperformingregression
testingwithMySQLcode.Youcanalsowriteyourowntestcasesusingthe
testframework.
MySQL8pluginAPI
MySQL 8 provides support for plugin API by which server components
themselvescanbecreated.Thepluginscanbeloadedduringserverstartupand
canalsobeloadedandunloadedduringruntime;thereisnoneedtorestartthe
server.TheAPIisverygenericinthatitdoesnotspecifywhatpluginscandoin
terms of limitation but instead they are allowed to do more than build-in
components. The API supports interfaces for components such as storage
enginesplugins,full-textparserplugins,serverextensionsandsoon.
TheplugininterfacemakesuseoftheplugintableintheMySQL8databaseto
store the information about installed plugins permanently by using the INSTALL
PLUGIN statement. During the MySQL 8 installation process the plugin table is
created.Forsingleserverinvocationthepluginscanalsobeinstalledusingthe--
plugin--loadoption,butusingthisoptiondoesnotrecordtheinstalledpluginto
theplugintable.
MySQL 8 also provides support API for client plugins to be used for specific
purposes such as enabling the server connection by client through different
authenticationmethods.
MySQL 8 services for
componentsandplugins
The MySQL 8 server plugins can access and initiate server plugin services;
similarly, the server components can also access and request component
services.TheMySQL8
plugin Services interface complements the API plugin by exposing server
functionality, which can be called by plugins. The following are the plugin
servicecharacteristics:
The services enable plugins to access the server code using ordinary
functioncallsandcanalsocalluser-definedfunctions
Theservicesareportableandcanworkonmultipleplatforms
The services provide versioning support that protects against
incompatibilitiesbetweenpluginsandservices
Theservicesalsoprovidesupportfortestingpluginservices
MySQL provides two services types for plugins and components, listed as
follows:
1. Thelockingservice:Thelockingserviceinterfaceisprovidedattwolevels
—that is, at C level and at SQL level. The interface works on lock
namespace,lockname,andlockmodeattributes.
2. Thekeyringservice:Thekeyringserviceprovidesaninterfaceforsecurely
storingsensitiveinformationforinternalservercomponentsandpluginsto
retrievelater.
AddingnewfunctionstoMySQL8
YoucanaddyourownfunctionstoMySQL8,andthiscanbedonewithanyone
of the three supported types of function. The new function can be called the
same way we invoke the built-in functions such as ABS(), and that is true
irrespectiveofwhichfunctiontypeyouhavenewlyadded.Thefollowinglistis
ofthesupportedthreetypesofnewfunctioninMySQL8:
1. Addingafunctionthroughtheuser-definedfunction(UDF)interface.
2. Addingafunctionasnative(built-in)MySQLfunction.
3. Addingafunctionbycreatingastoredfunction.
DebuggingandportingMySQL8
Porting MySQL 8 to other operating systems is currently supported by many
operatingsystems;thelistofsupportedoperatingsystemsisprovidedathttp://ww
w.mysql.com/support/supportedplatforms/database.html. In case you have added a new
portandarerunningintoproblemswiththenewport,youmightusedebugging
ofMySQL8.
There are different possible ways to start debugging based on where you are
runningintotheproblems—theycouldbeinMySQLserverorinMySQLclient.
Dependingontheproblem'slocation,youcanstartdebugginginMySQLserver
or client respectively and also get help from the DBUG package to trace the
program'sactivities.
Extending plugins and using
servicestocallthem
In this section, you will gain an understanding of how the plugin API, its
interface, and the MySQL services interact with one another and provide
extensionsinMySQL8.
ThepluginsarealsoconsideredascomponentsintheMySQL8architecture,and
thereforeyou canuse themto providepluggable features.The pluginAPI and
thepluginservicesinterfaceshavethefollowingdifferences:
ThepluginAPIenablespluginsthatwillbeusedbytheserver.Thecalling
andinvokingofpluginsisinitiatedbytheserver,sothepluginscanextend
the server's functionality or can register themselves in order to receive
serverprocessingnotifications.
The plugin services interface allows plugins to call the server code. The
callingandinvokingofservicefunctionsisinitiatedbythepluginssothat
the same server functionality can be leveraged by many plugins without
requiringindividualimplementationforthefunctionality.
Writingplugins
To create a plugin library, providing the required descriptor information is a
must,asitspecifieswhichpluginsthelibraryfilecontains.Writingtheinterface
functionforeachofthepluginsspecifiedisalsonecessary.
Everyserverpluginmusthaveageneraldescriptorprovidinginformationtothe
plugin APIs, and a type specific descriptor providing information about the
interface for specified plugin types. The structure for specifying a general
descriptoristhe sameforall the plugintypes,and thetypespecific descriptor
can vary based on the requirements of the plugin's behavior or function. The
serverplugininterfaceallowspluginstoexposesystemvariablesandstatus.
Client-sidepluginshaveaslightlydifferentarchitecturethanthatofserverside
plugins.Forexample,eachpluginmusthavedescriptorinformation,butthereis
noseparatedivisionbetweengeneralandtypespecificdescriptors.
PluginscanbewritteninCorC++oranyotherlanguagethatcanuseCcalling
conventions.
Pluginsareloadedandunloadeddynamically,hencetheoperatingsystemmust
dynamically support where you have dynamically compiled the calling
application.Specifically,forserverpluginsthismeansthatmysqldmustbelinked
dynamically.
Aswe cannotbe sureofwhatapplicationwillusetheplugin,the
dependencies on the symbols of the calling application should be
avoidedbytheclientpluginwriters.
The following are the types of supported plugin creations that can implement
severalcapabilities:
Authentication
Passwordvalidationandstrengthchecking
Protocoltracing
Queryrewriting
Securekeyringstorageandretrieval
Storageengines
Full-textparsers
Daemons
INFORMATION_SCHEMAtables
Semisynchronousreplication
Auditing
Componentandpluginservices
YoucanidentifythecomponentservicesandfunctionsprovidedbyMySQLby
lookingintothe include/mysql/components and respective services directories of the
MySQL8sourcedistribution.
Similarly, you can identify the plugin services and functions provided by
MySQL by looking into the include/mysql directory of the MySQL 8 source
distributionandtherelevantfilesasfollows:
Theplugin.hfileincludestheservices.hfile,whichservices.hfilecontainsall
theavailableservice-specificheaderfileswithinit
Service-specificheaderfileswillhavenamesintheformofservice_xxx.h
ThefollowingisalistofavailablecomponentservicesinMySQL8:
component_sys_variable_register, component_sys_variable_unregister: For registering
andunregisteringsystemvariables
log_builtins,log_builtins_string:Forlogcomponentsservices
mysql_service_udf_registration, mysql_service_udf_registration_aggregate: For
enablingregistrationandunregistrationofscalarandaggregateuser-defined
functionsincomponentsandplugins
mysql_string:ForstringserviceAPIs
pfs_plugin_table:FordynamicPerformanceSchematablemanipulation
ThefollowingislistofavailablepluginsservicesinMySQL8:
get_sysvar_source:Forretrievingsystemvariablesettings
locking_service: For lock implementation with C language and SQL level
interfaces,havingtheattributesnamespace,name,andmode
my_plugin_log_service:Forwritingerrorsmessagestologs
my_snprintf: For string formatting to keep the output consistent across
platforms
status_variable_registration:Forregisteringthestatusvariable
my_thd_scheduler:Forthreadschedulerselection
mysql_keyring:Forkeyringstorageservice
mysql_password_policy:Forpasswordstrengthandvalidationchecking
plugin_registry_service: For accessing the component registry and related
services
security_context:Formanagingthreadsecuritycontexts
thd_alloc:Formemoryallocation
thd_wait:Forreportingtosleeporstall
Now,youhaveaclearunderstandingofpluginservicesandcomponentservices.
MySQL
8 provides the following types of services to support plugins and components
services:
1. Thelockingservice
2. Thekeyringservice
Thefollowingsectionsgivedetailedinformationonbothtypesofservices.
Thelockingservice
Thelockingserviceinterfaceisprovidedattwolevels:ClevelandatSQLlevel.
The interface works on the lock namespace, lock name, and lock mode
attributes. The C language interface is callable as a plugin service from user-
definedfunctionsorserverplugins,andtheSQLlevelinterfaceisusedassetof
user-definedfunctions,beingmappedtocalltheserviceroutines.
Thefollowingarethecharacteristicsofthelockinginterface:
Lock namespace, lock name, and lock mode are three three attributes of
locks.
Locks are identified by forming a lock namespace and lock name
combination.
Lockmodecanbeeitherreadorwrite.Readlocksaresharedwhereaswrite
locksareexclusive.
Lock names and namespaces can have a maximum of 64 characters and
mustbenon-NULL
andnon-emptystrings.
Locknamesandnamespacearetreatedasbinarystringssocomparisonwill
becase-sensitive.
Functionsareprovidedtoacquireandreleaselocksanddonotrequireany
specialprivilegestocallthefunctions.
Detectsdeadlockduringlockacquisitioncallsindifferentsessions;acaller
ischosenandterminatedforitslockacquisitionrequestandcallersessions
holdingreadlocksarepreferredoverthesessionsholdingwritelocks.
A typical session can request for multiple locks acquisition with a single
lock acquisition call. It provides atomic behavior for the request and
succeedsifalllocksareacquiredorfailsifanyofthelockacquisitionsfail.
Multiplelocksforthesamelockidentifiercanbeacquiredbythesession
where the lock instances can be write locks, read locks, or a mix of both
readandwritelocks.
Acquired locks are released from the session by explicitly calling the
release-lockfunction,orimplicitlyifthesessiongetsterminated.
All locks in the given namespace when released are released together
withinthesession.
<strong>boolmy_key_generate(constchar*key_id,const
char*key_type,<br/>constchar*user_id,size_tkey_len)</strong>
<strong>boolmy_key_fetch(constchar*key_id,constchar
**key_type,<br/>constchar*user_id,void**key,size_t*key_len)
</strong>
<strong>boolmy_key_remove(constchar*key_id,constchar*
user_id)</strong>
<strong>boolmy_key_store(constchar*key_id,constchar
*key_type,<br/>constchar*user_id,void*key,size_tkey_len)
</strong>
Addingnewfunctions
NewfunctionscanbeaddedwithanyofthethreesupportedtypesinMySQL8.
Each of the types have their own advantages and disadvantages. Where and
which type of function should be added or implemented depends on the
requirementsofthefunction.
ThefollowingisthelistofthesupportedthreetypesofnewfunctioninMySQL
8,whichwewilllookatinthefollowingsection:
1. Addingafunctionthroughtheuser-definedfunctioninterface.
2. Addingafunctionasanative(built-in)MySQLfunction.
3. Addingafunctionbycreatingastoredfunction.
Features of a user-defined
functioninterface
A user-defined function interface provides independent capabilities to a user
purposefunction.
ThefollowingfeaturesandcapabilitiesareprovidedbytheMySQLinterfacefor
user-definedfunctions:
Functions can accept arguments of integer, string, or real values and can
returnvaluesforthesametypes
Simplefunctionscanbedefinedtooperateonasinglerowatatimeorit
canbeaggregatefunctionstooperateongroupsofrows
Functionsaregiveninformationtoenablethemsothattheycancheckthe
types,names,andnumbersofargumentspassed
Beforepassingargumentstothegivenfunction,youcanalsoaskMySQL
tocoercearguments
IndicationscanbemadeifthefunctionresultsinanyerrororreturnsNULL
Adding a new user-defined
function
TheUDF functionsmust bewritteninCorC++andtheunderlyingoperating
systemmustsupportdynamicloadingbehavior.Thereisafile,sql/udf_example.cc,
that defines five UDF functions and it's included in the MySQL source
distributions.
Analyzingthefilewilllet youknowhow callingconventions workforUDFs.
User-defined function related symbols and data structures are defined in the
include/mysql_com.hfileandthefileisincludedinthemysql.hheaderfile.
TypicalcodecontainedintheUDFsgetsexecutedintherunningserver,soall
constraints are applicable when writing UDF code—server code. Currently
applicableconstraintsmaygetrevisedwhenaserver isupgraded,andthiscan
possiblyresultintotheneedtorewriteUDFcode,soitisessentialtobecareful
whenwritingcodefortheUDF.
InordertouseUDF,linkingmysqlddynamicallyisamust.Foranyfunctiontobe
used in SQL statements there must be underlying C or C++ functions. The
convention for separating SQL and C/C++ code is followed where xxx() in
uppercaseindicatesanSQLfunctioncallwhereasxxx()withlowercaseindicates
aC/C++functioncall.
EncapsulateyourCfunctionasshowninfollowingsentencewhen
you are using C++: extern "C"{ ... }This way it is ensured that
your C++ function names are readable in the completed user-
definedfunction.
TowriteandimplementtheinterfacefunctionnameXXX(),themainfunctionxxx()
isamustandadditionallyrequiresoneormorefunctiontobeimplementedfrom
thefollowing:
xxx():Themainfunctionwherethefunctionresultisbeingproduced
xxx_init():The initializationfunction forthemain functionxxx(), it canbe
usedforanyofthefollowingpurposes:
CheckingnumberofargumentstobepassedontoXXX()
Verifying argument types with a declaration when calling the main
function
Allocatingmemorytothemainfunctionwheneverrequired
Result'smaximumlengthverification
Settingadecimalnumberlimitformaximumintheresult
SpecifyingwhethertheresultcanbeNULLornot
xxx_deinit(): Represents deinitialization for the main function and
deallocatesmemoryifanyisallocatedbytheinitializationfunctionforthe
mainfunction
AggregateUDFsarehandledasinthefollowingsequenceinMySQL8:
1. Call xxx_init() so that it allocates the required memory to store result
information.
2. Sortthetable/resultasspecifiedbytheGROUPBYfunction.
3. Callxxx_clear()sothatitresetthecurrentaggregatevalueforthefirstrowin
eachnewgroup.
4. Callxxx_add()thataddstheargumenttothecurrentaggregatevalue.
5. Callxxx()to gettheresultof aggregatedataongroupbychangesorafter
processingthelastrow.
6. Repeatsteps3-5untilallspecified/resultedrowsareprocessed.
7. Callxxx_deinit()tofreeanyallocatedmemoryfortheUDF.
All the functions must be thread-safe, including the main function as well as
other additional functions as required, along with the initialization and
deinitializationfunctions.
Similartotheabovesequence,thefollowingareimportantaspectsthatneedto
betakencareofwhileaddingnewuser-definedfunctions:
UDFargumentprocessing
UDFreturnvaluesanderrorhandling
UDFcompilingandinstalling
UDFsecurityprecautions
<strong>doubleItem_func_newname::val()</strong><br/><strong>
<span>longlongItem_func_newname::val_int()<br/></span>String
*Item_func_newname::Str(String*str)</strong>
Ifyourobjectisinheritedfromanyofthestandarditemsthen
youprobablyneedtodefineonlyoneofthepreceding
functions,astheparentobjectwilltakecareotherofthe
function.YoucanrefertotheItem_str_funcclassthathas
definedtheval()functionthatexecutestheatof()function
onthereturnedvalueofthe::str()function.
5. Ifthefunctionisnondeterministic—thatis,ifthereturnedresult
variesatdifferentinvocationsforfixedgivenarguments-thenthe
followingstatementneedstobeincludedintheitemconstructor,
indicatingthatthefunctionresultsshouldnotbecached:
current_thd->lex->safe_to_cache_query=0;.
6. Youprobablyalsoneedtodefinethefollowingobjectfunctionfor
yournativefunction:
voidItem_func_newname::fix_length_and_dec()
Thefunctionshouldatleastincludethemax_length
calculationonthegivenarguments
Youshouldalsosetmaybenull=0ifyourmainfunction
cannotreturnanyNULLvalues
YoucanrefertoItem_func_mod::fix_length_and_decfor
thesame
Threadsafetyisamustforallfunctions.Youshouldnotbeusingany
staticorglobalvariablesinthefunctionswithoutbeingprotectedby
mutexes.
Debuggingandporting
Porting MySQL 8 to other operating systems is currently supported by many
operatingsystems.Thelistofthelatestsupportedoperatingsystemsisprovided
athttp://www.mysql.com/support/supportedplatforms/database.html. If you have added or
attemptedtoaddnewports(supportedplatforms)andarerunningintoproblems,
youmightusedebuggingofMySQL8tofindandfixtheproblems.
First,youshouldgetthetestprogrammysys/thr_locktoworkbefore
debuggingmysqld.Thismakessurethatyourthreadinstallationcan
havearemotechancetowork!
Therearedifferentpossibilitiesforstartingdebugging,basedonwhereyouare
runningintotheproblems-itcould bein MySQL serveror inMySQLclient.
Dependingontheproblem'slocationyoucanstartdebugginginMySQLserver
orMySQLclientrespectively,and fortracingtheprogram'sactivitiesyou will
gethelpfromtheDEBUGpackage.
The MySQL source code includes internal documentation written
usingDoxygen,whichisveryhelpfulinunderstandingthedeveloper
perspectiveonhowMySQLworks.
Inthissection,youwillseedetailedinformationonthefollowingtopics:
DebuggingMySQLserver
DebuggingMySQLclient
TheDBUGpackage
DebuggingMySQLserver
If you are using some of very new functionality in MySQL and facing some
issues—let's say the server is crashing—you can try running mysqld with the --
skip-new option. This option tells the MySQL server to disable all new and
potentiallyunsafefunctionality.
In cases where mysqld is not getting started, verify the my.cnf files, as they can
interferewiththesetup!Youcanchecktheargumentsinmy.cnfwiththemysqld--
print-defaults option and then start mysqld with the --no-defaults option to avoid
usingthem.
IncaseswheremysqldstartstoeatupmemoryorCPUorhangs,youcancheck
mysqladminprocessliststatusandfindoutifaqueryexecutedbysomeoneistaking
alongtime.Incaseswhereyouarefacingperformanceissuesorproblemsand
newclientsarenotabletoconnect,youcanusemysqladmin-i10processliststatus.
Youcanalsousethedebugcommandmysqladmin,whichdumpsinformationabout
query usage, memory usage, and locks in use to the MySQL log file and can
solvesomeproblemsforyou. Thiscommand alsoworksin caseyou havenot
compiledMySQLfordebugging,providingsomeusefulinformation.
Incaseswhereyouarefacinganyissuewiththetablegettingslower,youshould
try to optimize the table using myisamchk or OPTIMIZE_TABLE. You should probably
checktheslowqueries,ifthereareany,usingEXPLAINtofindandfixtheproblem
withqueries.
ThefollowingaretheimportantareastoconsiderwhendebugginginMySQL8:
CompilingMySQLfordebugging:Incaseofveryspecificproblemsyou
canalwaystry todebug MySQL.To dothatyou mustconfigure MySQL
with the -DWITH_DEBUG=1 option. The debugging configuration automatically
enableslotsofextrasafetycheckfunctionsthatmonitorthehealthofmysqld.
Creating trace files: You can attempt to find the problem by creating a
trace file. To do that you must have mysqld compiled with debugging
support.You canthenuse the --debug option, which will add trace logs in
/tmp/mysqld.traceonUnixand\mysqld.traceonWindows.
Using WER with PDB to create a Windows crashdump: Program
databasefilesareincludedintheZIParchivedebugbinariesandtestsuite
as a separate distribution of MySQL. These files provide information on
debugging for a MySQL installation problem. They can be used with
WinDbgorVisualStudiotodebugmysqld.
Debugging mysqld under gdb: You can use this option when you are
facingissueswiththreadsorwhenthemysqldserverhangspriortoreadyfor
connections.
Using a stack trace: You can also use this option when mysqld dies
unexpectedlyandfindouttheproblem.
Using server logs to find causes of errors in mysqld: You can use this
optionbyenablingthegeneralquerylog-priortothat,youshouldcheck
allyourtablesusingthemyisamchkutilityandverifyifthereareanyproblems
fromthelogs.
Making a test case if you experience table corruption: This option is
usedwhenyouarefacinganissuewithtablecorruptionandisapplicable
onlytoMyISAMtables.
DebuggingMySQLclient
In cases where you are facing an issue in MySQL client you can also debug
withinMySQLclientaswell,butinordertodosoyoumusthavetheintegrated
debug package. You need to configure MySQL with -DWITH_DEBUG=1 to enable
debugginginMySQLclient.
Prior to running MySQL client, you should set the environment variable
MYSQL_DEBUGasfollows:shell>MYSQL_DEBUG=d:t:O,/tmp/client.trace
shell>exportMYSQL_DEBUG
This makes MySQL client generate a trace file in /tmp/client.trace for Unix or
\client.traceforWindows.
Incaseswhereyouhaveproblemswithyourownclientcode,youcanattemptto
connectto the server by running your query using the client that is known to
work.Fordoingthisyoushouldrunmysqldindebuggingmode:shell>mysql--
debug=d:t:O,/tmp/client.trace
Thistracewillprovideusefulinformationifyouwanttomailabugreportfor
theproblem.
Incaseswhereyourclientcrashesatsomelegallookingcode,youcancheckthat
yourmysql.hheaderfileincludesfilematcheswithyourMySQLlibraryfile.This
is one of the very common mistakes, using an older mysql.h file from an old
MySQLinstallationwithanewMySQLlibrary,resultinginthisissue.
<strong><spanclass="tokenoperator">--</span>debug<span
class="tokenoperator">=</span>d<spanclass="tokenoperator">:
</span>t<br/><spanclass="tokenoperator">--</span>debug<span
class="tokenoperator">=</span>d<spanclass="tokenoperator">:
</span>f<spanclass="tokenpunctuation">,</span>main<span
class="tokenpunctuation">,</span>subr1<spanclass="token
operator">:</span>F<spanclass="tokenoperator">:</span>L<span
class="tokenoperator">:</span>t<spanclass="tokenpunctuation">,
</span>20<br/><spanclass="tokenoperator">--</span>debug<span
class="tokenoperator">=</span>d<spanclass="tokenpunctuation">,
</span>input<spanclass="tokenpunctuation">,</span>output<span
class="tokenpunctuation">,</span>files<spanclass="token
operator">:</span>n<br/><spanclass="tokenoperator">--
</span>debug<spanclass="tokenoperator">=</span>d<span
class="tokenoperator">:</span>t<spanclass="tokenoperator">:
</span>i<spanclass="tokenoperator">:</span>O<spanclass="token
punctuation">,</span>\\mysqld<spanclass="tokenpunctuation">.
</span>trace</strong>
Summary
Inthischapter,youlearnedhowtoextendMySQL8throughcustomfunctions
andAPIs.
Youalsogottoknowaboutwritingfunctionsandtheassociatedcharacteristics
of the plugin services and APIs. You can now create your own function or
plugin,catertospecificbusinessrequirements,andalsodebugifafunctiondoes
notworkasperexpectations,andtestwhetheritdoes.
Innextchapter,youwilllearnaboutMySQL8bestpracticesandbenchmarking
inMySQL
8.Youwilllearnaboutbenchmarkingandtoolsusedforbenchmarking.Youwill
alsolearnbestpracticesforsomeofveryimportantfeaturesofMySQL8,such
asmemcached,replication,datapartitioning,andindexing.
MySQL 8 Best Practices and
Benchmarking
Inthepreviouschapter,youlearnedhowtoextendMySQL8.Itcoveredalotof
interestingaspects,suchasextendingpluginsandcallingthembyusingservices
inMySQL8,addinganddebuggingnewfunctionstoMySQL8,andsoon.In
thischapter,wewillgothroughthebestpracticesofMySQL8,whichisamuch-
awaited version that promises to address many of the shortfalls of the prior
versionsandhasexcitingnewfeatures.
MySQL8promisesnottobejustastandalonedatabase,butitwillalsoplaya
significantroleinvariousareas,includingbigdatasolutions.Wewilllearnhow
best practices can be implemented for optimal use of features in MySQL 8.
Benchmarkingwillenhanceourunderstandingfurther.
Wewillcoverthefollowingtopicsinthischapter:
MySQLbenchmarkingandtools
Bestpracticesforthememcached
Bestpracticesforreplication
Bestpracticesfordatapartitioning
Bestpracticesforqueriesandindexing
Due to prominent optimizations and changes, MySQL 8 advanced its version
directlyfromthereleaseofMySQL5.7.MySQL8willnothavethelimitationof
files, which was previously restricting the number of databases that you could
have.Therearemanymoreexcitingfeatures,whichwehavecoveredinChapter
1, Introduction to MySQL 8. MySQL 8 can now store millions of tables in a
database.Itwillalsomakemodificationstotablesswiftly.
I am excited to go through this chapter, as MySQL 8 best practices not only
impactyourdatabaseperformance,scalability,security,andavailability,butwill
also,onthewhole,exposehowyoursystemperformsfortheenduser.Thisis
ourendgoal,isn'tit?Let'slookatsomebenchmarksthathavebeenderivedin
our test lab, which will raise your eyebrows for sure:
MySQLbenchmarkingandtools
WehavegonethroughvariousnewfeaturesandimprovementsinMySQL8.It
makesusmoreexcited,asperformanceisalwayswhatwecrave.WithMySQL8
notbeinggenerallyavailableyet,Oraclehasn'tpublisheditsbenchmarkresults.
Wedidn'twaitforittodosoandcarriedoutourownanalysisinafewareas.
Configuration best practices of MySQL is the cherry on the cake; without the
cherry,thecakeseemsincomplete.Inadditiontoconfigurations,benchmarking
helps us validate and find bottlenecks and address them. Let's look at a few
specific areas that will help us understand the best practices for configuration
andperformancebenchmarking.
Resourceutilization
IOactivity,CPU,andmemoryusageissomethingthatyoushouldnotmissout.
These metrics help us know how the system is performing while doing
benchmarking and at the time of scaling. It also helps us derive impacts per
transaction.
Stretching your benchmarking
timelines
We may often like to have a quick glance at performance metrics; however,
ensuringthatMySQLbehavesinthesamewayforalongerdurationoftestingis
alsoakeyelement.Thereissomebasicstuffthatmightimpactonperformance
when you stretch your benchmark timelines, such as memory fragmentation,
degradation of IO, impact after data accumulation, cache management, and so
on.
Wedon'twantourdatabasetogetrestartedjusttocleanupjunkitems,correct?
Therefore,itissuggestedtorunbenchmarkingforalongdurationforstability
andperformancevalidation.
Replicatingproductionsettings
Let's benchmark in a production-replicated environment. Wait! Let's disable
database replication in a replica environment until we are done with
benchmarking.Gotcha!
Wehavegotsomegoodnumbers!
Itoftenhappensthatwedon'tsimulateeverythingcompletelythatwearegoing
to configure in the production environment. It could prove to be costly, as we
mightunintentionallybebenchmarkingsomethinginanenvironmentthatmight
have an adverse impact when it's in production. Replicate production settings,
data, workload, and so on in your replicated environment while you do
benchmarking.
Consistency of throughput and
latency
Throughput and latency go hand in hand. It is important to keep your eyes
primarily focused on throughput; however, latency over time might be
somethingtolookoutfor.
Performancedips,slowness,orstallswerenoticedinInnoDBinitsearlierdays.It
hasimproveda lotsincethen, butasthere mightbeother casesdependingon
your workload, it is always good to keep an eye on throughput along with
latency.
Sysbenchcandomore
Sysbench is a wonderful tool to simulate your workloads, whether it be
thousands of tables, transaction intensive, data in-memory, and so on. It is a
splendidtooltosimulateandgivesyounicerepresentation.
Virtualizationworld
Iwould liketo keepthis simple;baremetalascomparedtovirtualizationisn't
thesame.Hence,whiledoingbenchmarking,measureyourresourcesaccording
toyourenvironment.You mightbesurprised toseethe difference inresults if
youcompareboth.
Concurrency
Big data is seated on heavy data workload; high concurrency is important.
MySQL 8 is extending its maximum CPU core support in every new release,
optimizing concurrency based on your requirements and hardware resources
shouldbetakencareof.
Hiddenworkloads
Donotmissoutfactorsthatruninthebackground,suchasreportingforbigdata
analytics,backups,andon-the-flyoperationswhileyouarebenchmarking.The
impactofsuchhiddenworkloadsorobsoletebenchmarkingworkloadscanmake
yourdays(andnights)miserable.
Nervesofyourquery
Oops!Didwemisstheoptimizer?Notyet.Anoptimizerisapowerfultoolthat
willreadthenervesofyourqueryandproviderecommendations.It'satoolthatI
usebeforemakingchangestoaqueryinproduction.It'sasaviorwhenyouhave
complexqueriestobeoptimized.
These are a few areas that we should look out for. Let's now look at a few
benchmarks that we did on MySQL 8 and compare them with the ones on
MySQL5.7.
Benchmarks
To start with, let's fetch all the column names from all the InnoDB tables. The
followingisthequerythatweexecuted:
SELECTt.table_schema,t.table_name,c.column_name
FROMinformation_schema.tablest,
information_schema.columnsc
WHEREt.table_schema=c.table_schema
ANDt.table_name=c.table_name
ANDt.engine='InnoDB';
The following figure shows how MySQL 8 performed a thousand times faster
whenhavingfourinstances:
Followingthis,wealsoperformedabenchmarktofindstatictablemetadata.The
followingisthequerythatweexecuted:
SELECTTABLE_SCHEMA,TABLE_NAME,TABLE_TYPE,ENGINE,ROW_FORMAT
FROMINFORMATION_SCHEMA.TABLES
WHERETABLE_SCHEMALIKE'chintan%';
The following figure shows how MySQL 8 performed around 30 times faster
thanMySQL5.7:
Itmadeuseagertogointoabitmoredetail.So,wethoughtofdoingonelast
testtofinddynamictablemetadata.
Thefollowingisthequerythatweexecuted:
SELECTTABLE_ROWS
FROMINFORMATION_SCHEMA.TABLES
WHERETABLE_SCHEMALIKE'chintan%';
The following figure shows how MySQL 8 performed around 30 times faster
thanMySQL5.7:
MySQL8.0bringsenormousperformanceimprovementstothetable.Scalingto
one million tables, which is a need for many big data requirements, is now
achievable.Welookforwardtomanymorebenchmarksbeingofficiallyreleased
onceMySQL8isavailableforgeneralpurposes.
Let'snowlookatournexttopic,whichwillmakeyourlifeeasier.It'sallabout
takingthingsintoconsiderationforbestpracticesofmemcached.
Bestpracticesformemcached
Multiple get operations are now possible with the InnoDB memcached plugin,
which will really help in improving the read performance. Now, multiple key
value pairs can be fetched in a single memcached query. Frequent
communicationtraffichasalsobeenminimized,aswecangetmultipledataina
singleshot.
Thekeytakeawaysthatyoushouldconsiderformemcachedconfigurationbest
practicesarewhatwewillbegoingthroughnow.
Resourceallocation
Memory allocation for memcached shouldn't be allocated over the available
physicalmemoryorwithoutconsideringotherresourcesthatwouldbeutilizing
memory. If we over-allocate memory, there is a high chance that memcached
would have memory allocated from the swap space. This may lead to delays
whileinsertingorfetchingvaluesbecausetheswapspaceisstoredonthedisk,
whichisslowerthanin-memory.
Operatingsystemarchitecture
Astheoperating system architecturehas32-bits, one needstobe cautious. As
we know, there are limitations to provision resources in a 32-bit operating
systemarchitecture.
Similarly, memcached with 4 GB RAM with a 32-bit operating system
architectureshouldn'tbesetmorethan3.5GBRAM,asitcanbehavestrangely
inperformanceandcanalsoresultincrashes.
Defaultconfigurations
Some key default configuration parameters should always be fine-tuned based
onyourneeds:
Memory allocation: By default, this is 64 MB; instead it should be
reconfiguredbasedonyourrequirementsandtesting
Connections: By default, this is 1,024 concurrent connections; instead it
shouldbereconfiguredbasedonyourrequirementsandtesting
Port:Bydefault,thislistensonport11211;insteaditshouldlistentoanother
portforsecuritypurposes
Networkinterface:Bydefault,thisacceptsconnectionsfromallnetwork
interfaces;insteaditshouldbelimitedforsecuritypurposes
Maxobjectsize
Youshouldlookatconfiguringthemaximumobjectsize,whichbydefaultis1
MB.
However,itcan bebumpedup to128 MB.Itis purelybasedon whattype of
datayouaregoingtostoreand,accordingly,itsmaximumobjectsizeshouldbe
allowed. Allowing overhead data to be stored in memcached can have an
adverse impact, as there may be much more data to retrieve, which can cause
failures.
Backlogqueuelimit
Thebacklogqueuelimitisallaboutthenumberofconnectionstomemcached
that should be kept in queue if it reaches the limit of allowed connections.
Ideally,yournumberofconnectionsallowedshouldbeconfiguredinawaythat
shouldsufficefor mostof yourneeds.Thebacklogqueuelimitcanbehelpful
whenthereisanunexpectedpeakloadonmemcached.Ideally,itshouldnotgo
beyond20%ofthetotalconnectionsoritcouldimpacttheexperienceofsystem
fetchinginformationfrommemcachedbecauseofheavydelays.
Largepagessupport
Onsystemsthatsupportlargememorypages,youshouldenablememcachedto
leverage them. Large pages support helps allocate a large data chunk to store
dataandalsoreducesthenumberofcachesmissedcallsusingthis.
Sensitivedata
Storing sensitive data in memcached could be a security threat, as somebody
with access to memcached could view the sensitive information. You should
obviously take precautions to limit the exposure of memcached. You can also
havesensitiveinformationencryptedbeforestoringitonmemcached.
Restrictingexposure
Memcacheddoesn'thavemanysecurityfeaturesbuiltin.Onemeasureinvolves
exposingmemcachedaccesswithintherequiredboundaries.Ifyourapplication
server needs to talk to memcached, it only allows memcached to be accessed
from that server with the help of system firewall rules, such as IP Tables or
similartechniques.
Failover
Memcacheddoesn'thavegoodfailovertechniques.Itissuggestedthatyouhave
your application configured in a way to failover to an unavailable node and
regeneratedataintoanotherinstance.Itisgoodtohaveatleasttwomemcached
configuredtoavoidfailureowingtotheunavailabilityoftheinstance.
Namespaces
You can leverage namespaces provided by memcached, which basically adds
prefixestothedatabeforestoringitinmemcached.Itcanhelpwhenyouhave
multiple applications talking to memcached. This is helpful and, using some
basicprinciplesofnamingconventions,youcanderiveasolution.Ifthereisdata
thatisstoringfirstnamesandlastnames,youcanuseprefixes,suchasFNand
LN,respectively.Thiswouldhelpyoueasilyidentifyandretrievedatafromthe
application.
Cachingmechanism
One of the easiest ways to start leveraging caching in memcached is to use a
two-columntable;youcanleveragenamespacesprovidedbymemcached,which
basicallyaddsprefixes.
Thefirstcolumnswouldbeaprimarykey,anddatabaseschemashouldbethe
addressrequirementofauniqueidentifierwiththehelpofprimarykeymapping
alongwithuniqueconstraints.Incaseyouwanttohaveasingleitemvalueby
combining multiple column values, you should make sure you choose
appropriatedatatypes.
QuerieswithasingleWHEREclausecanbemappedeasilyintomemcachedlookups
whileusing=orINoperatorsinthequeriesthemselves.Incaseswheremultiple
WHERE clauses are used or complex operations are parsed, such as <,>,LIKE, and
BETWEEN,memcachedwouldgetyouthroughchallenges.It issuggestedthatyou
have such complex operations using traditional SQL queries added to your
database.
Itwouldbebeneficialtocacheentireobjectsinmemcachedinsteadofoptingto
cacheindividualrowsfromMySQL8.Forinstance,forabloggingwebsite,you
shouldcachetheentireobjectoftheblogportinmemcached.
Memcachedgeneralstatistics
Tohelp youunderstandthe statisticsof memcachedbetter, wewillprovide an
overviewofhealthandperformance.Statisticsreturnedbymemcachedandtheir
meaning are shownin the following table: Terms used to define the value for
eachofthestatisticsare:
32u:32-bitunsignedinteger
64u:64-bitunsignedinteger
32u:32u:Two32-bitunsignedintegersseparatedbyacolon
String:Characterstring
Statistic Datatype Description
pid 32u ProcessIDofthememcachedinstance.
uptime 32u Uptime(inseconds)forthismemcachedinstance.
time 32u Currenttime(asepoch).
version string Versionstringofthisinstance.
pointer_size string Sizeofpointers forthis hostspecifiedinbits (32
or64).
rusage_user 32u:32u Total user time for this instance
(seconds:microseconds).
Total system time for this instance
rusage_system 32u:32u (seconds:microseconds).
curr_items 32u Currentnumberofitemsstoredbythisinstance.
total_items 32u Totalnumberofitemsstoredduringthelifeofthis
instance.
bytes 64u Current number of bytes used by this server to
storeitems.
curr_connections 32u Currentnumberofopenconnections.
total_connections 32u Total number of connections opened since the
serverstartedrunning.
connection_structures 32u Number of connection structures allocated by the
server.
cmd_get 64u Totalnumberofretrievalrequests(getoperations).
cmd_set 64u Totalnumberofstoragerequests(setoperations).
get_hits 64u Number of keys that have been requested and
foundpresent.
get_misses 64u Numberofitemsthathavebeenrequestedandnot
found.
delete_hits 64u Numberofkeysthathavebeendeletedandfound
present.
delete_misses 64u Number of items that have been delete and not
found.
incr_hits 64u Number of keys that have been incremented and
foundpresent.
incr_misses 64u Numberofitems thathave beenincrementedand
notfound.
decr_hits 64u Number of keys that have been decremented and
foundpresent.
decr_misses 64u Numberofitemsthathavebeendecrementedand
notfound.
cas_hits 64u Number of keys that have been compared and
swappedandfoundpresent.
cas_misses 64u Number of items that have been compared and
swappedandnotfound.
cas_badvalue 64u
Number of keys that have been compared and
swapped, but the comparison (original) valuedid
notmatchthesuppliedvalue.
evictions 64u Numberofvaliditemsremovedfromcachetofree
memoryfornewitems.
bytes_read 64u
Total number of bytes read by this server from
network.
bytes_written 64u Total number of bytes sent by this server to
network.
limit_maxbytes 32u Numberofbytesthisserverispermittedtousefor
storage.
threads 32u Numberofworkerthreadsrequested.
conn_yields 64u Numberofyieldsforconnections(relatedtothe-R
option).
Reference:https://dev.mysql.com/doc/refman/8.0/en/ha-memcached-stats-general.html
These are a few useful items that should be kept handy for best practices of
memcached.It's nowtimefor ustomove ahead andlookat bestpracticesfor
replication.
Bestpracticesforreplication
MySQL8hasmadesomegreatimprovementsonthereplicationside.MySQL8
is all about scalability, performance, and security with the utmost integrity of
data,whichisexpectedtobeagame-changerinbigdatatoo.
Throughputingroupreplication
Groupreplicationbasicallytakescareofcommittingtransactionsoncemostof
the members in group replication have acknowledged the transaction received
concurrently.
This results in a better throughput if the overall number of writes doesn't
exceeding the capacity of the members in group replication. If there is a case
wherecapacityisnotplannedappropriately,youwouldnoticelagsonaffected
membersascomparedtoothermembersinthegroup.
Infrastructuresizing
Infrastructure sizing is a common success factor for performance and the best
practices checklist. If infrastructure sizing is not proper or uneven across the
nodes in group replication, it could adversely impact the replication
fundamentalstopology.Eachcomponentshouldbeconsideredwhileconsidering
thethroughputrequiredfromthecomponents.
Constantthroughput
To achieve constant throughput is a good success factor. What if you start
experiencing a workload that starts affecting the rest of the members in group
replication?Itmightbeacasewhereyourmasterkeepsonacceptingadditional
workload and is lagging behind, after which it might return to an acceptable
level before burning out all the resources. Additionally, you can implement a
queuing methodology that can prevent you from burning down resources and
onlyallowsyoutopassonworkloadstothemembersthatarepredefinedbased
oncapacity.
While considering a queuing methodology, you mustn't allow queues grow
exponentially.
This would impact the end user, as there would be a lag in the data being
updated.
However,youneedstodecidebasedonyourneedsandthebusinessrequirement
toachieveconstantthroughputacrossthesystem.
Contradictoryworkloads
Fundamentally,groupreplication isdesigned toallowupdates fromanyof the
members in the group. Rollback of transactions based on overlap of rows is
checked for each of the transactions; the rest are committed and sent to be
updated to other members in the group. If several updates on the same row
happen frequently, it can result in multiple rollbacks. You might come across
cyclic situations where one server updates, requests others to update, and, in
parallel, another has already updated for the same row. This would result in
rollback.
Topreventsuchascenario,youcanhavethelastmemberofthegroupapplythe
update, after which you proceed to another one. You can have similar updates
routed only from the same node where the earlier one had been executed to
preventthechancesofcyclicrollbackconditions.
Writescalability
Distribute your write workload by sharing out write operations, which might
resultinbetterthroughputandbetterscalabilityonwriteperformance.Itwould
be dependent on contradictory workloads that you would be expecting in the
system.Thisishelpfulwhenyourpeakworkloadisbeingexecutedisonethat
cansharetheload.Incommoncases,ifyouhavegoodcapacityplanningdone
withwritescalability,youwouldseetrivialimprovement.
Refer to the following diagram that depicts this:
You willnoticethat withthehelpofmulti-mastersto distribute,yourloadhas
betterthroughput.Italsoconsidersthegroupsizeinmulti-masterconfiguration.
Best practices for data
partitioning
In general terms, partitioning is logically dividing anything into multiple
subgroups so that each subgroup can be identified independently and can be
combinedintoasinglepartition.
Let's now learn different partitioning methods and how partitioning can help
wheretherearelargedatatables.
For any organization, it is very important to store data in such a way that the
database provides scalability, performance, availability, and security. For
instance,inahighlyaccessede-commercestore,therearethousands,ormore,of
ordersplacedfrequently.
Sotomaintainday-to-dayorderdeliveryshowingadashboardofcurrentorders,
whatisrequiredistoqueryatableshowingordersfromthepastfiveyears;the
process will take a long time to execute with the current data. Here, historical
orderdataisneededfortheanalyticalpurposeoffindinguserbehaviorortrends,
butthiswillberequiredtobeperformedonlimiteddatasets.
Therearevariouswaystoachievethebestsuitablesolutionforhighavailability,
scalability,andhighlyperformingarchitecture;thekeyingredientispartitioning.
Inadatabase,dataineachtableisstoredinphysicalfilegroups.Sobydividing
thisdatatablefromasinglefilegrouptoamultiplefilegroupcanreducethefile
sizeandhelpuscreateascalableandhigh-performingdatabase.
Thefollowingarethekeybenefitsofusingpartitioninginadatabase:
Scalability:Asdatawillbesharedamongmorethanonepartition,servers
can be configured to use multiple nodes and partitions can be configured
among multiple nodes. Doing so will eliminate any hardware limits and
allow the database to scale up to a large extent to accommodate high
volumedata.
Highperformance:Asdataisstoredamongmultiplepartitions,eachquery
will be executed on a small portion of the data. For example, in an e-
commercestorewithanorderhistoryofmorethantwoyears,togetalistof
orders placed in the current month will require checking only a single
partitionandnottheentireorderhistory,thusreducingthequeryexecution
time.Tofetchthequeryonmorethanonepartition,wecanalsorunthisin
parallel,thusreducingtheoveralltimetofetchdatafromthedatabase.
High availability: In partitioning, data is divided across multiple file
groups. Each file group is logically connected but can be accessed and
worked on independently. So if one of the file groups or partitions gets
corrupted or one of the nodes in the server fails, then we will not lose
access to the entire table, but only a section of the database will not be
available,thuseliminatingthechancesofsystemfailureandmakingyour
systemhighlyavailable.
Security:Itmay bethatsome of thedatain tablesrequireshigh security
measurements to avoid data theft or data leaks. By partitioning, you can
provideadditionalsecuritytooneormorepartitionstoavoidanysecurity
issues,thusimprovingdataaccessibilitywithdatasecurity.
In general terms, partitioning is logically dividing anything into multiple
subgroups so that each subgroup can be identified independently and can be
combined into a single partition. Let's understand what partitioning means in
termsofRDBMS.
Partitioningisgenerallyusedtodividedataintomultiplelogicalfilegroupsfor
thepurposeofperformance,availability,andmanageability.Whendealingwith
bigdata,thenormaltendencyofdataistobeintermsofbillionsofrecords.So
to improve performance of the database, it is better to divide data among
multiple file groups. These file groups can be on a single machine or shared
acrossmultiplemachinesandidentifiedbyakey.Thesefilegroupsareknownas
partitioneddata.
Datainthetablecanbepartitionedintwoways:
Horizontalpartitioning
Verticalpartitioning
Horizontalpartitioning
Whenthenumberofrowsinthetableisverylarge,thetablecanbedividedinto
multiplepartitions; thisisknownas horizontalpartitioning. When horizontal
partitioning is used, each partition of the table contains the same number of
columns. It is possible to access all partitions at once, or you can access each
partitionindividually.
Verticalpartitioning
In vertical partitioning, the columns of the tables are partitioned to achieve
performanceandbettermanagementofthedatabase.Verticalpartitioningcanbe
achievedintwoways.Thefirstoneisbynormalizingtables.Insteadofhaving
toomanycolumnsinthetable,columnscanbedividedintomultipletablesby
dividingthedata.Thesecondoneisbycreatingseparatephysicalfilegroupsfor
definedcolumnsinthetable.
VerticalpartitioningiscurrentlynotsupportedinMySQL8.
Let'slookatafewofthebenefitsassociatedwithpartitioning:
Ifatablecontainshistoricaldata,suchaslogsofanapplication,dataolder
thansixmonthsdoesnotprovideanysignificancetotheapplicationtobe
active. If partitioning is created based on months, you can easily remove
oneofthepartitions.
Inthe sameprecedingcaseoflogs,ifwewanttofilterdata betweentwo
dates, the MySQL optimizer can identify the specific partitions, where it
canfindthefilteredrecords,whichcanresultinmuchfasterqueryresults,
asthenumberofrowstocheckisreduceddrastically.
MySQL8alsosupportsqueryingdataonparticularpartitions.Itcanreduce
thenumberofrecordstocheckwhenyouknowthepartitionthatneedsto
bequeriedforthedatarequired.
PruningpartitionsinMySQL
Pruningistheselectiveextractionofdata.Aswehavemultiplepartitions,itwill
gothrougheachpartitionduringretrieval,whichistimeconsumingandimpacts
onperformance.Someofthepartitionswillalsobeincludedinsearchingwhile
the requested data is not available inside that partition, which is an overhead
process. Pruning helps here to search for only those partitions that have the
relevant data, which will avoid the unnecessary inclusion of those partitions
duringretrieval.
Thisoptimizationthat avoids thescanningof partitionswherethere can beno
matchingvaluesisknownasthepruningofpartitions.Inpartitionpruning,the
optimizer analyzes FROM and WHERE clauses in SQL statements to eliminate
unneededpartitions,andscansthosedatabasepartitionsthatarerelevanttothe
SQLstatement.
Best practices for queries and
indexing
It would be difficult to write the best queries for reference and reuse. It will
alwaysvarybasedonthenatureofyourapplication,architecture,design,table
structure,andsoon.However,precautionscanbetakenwhilewritingMySQL
queriesforbetterperformance,scalability,andintegrity.
Let'sgothroughafewofthebestpracticesthatweshouldkeepinmindwhile
designingorwritingMySQLqueries.
Datatypes
A database table could consist of multiple columns with data types, such as
numerics or strings. MySQL 8 provides various data types rather than just
limitingtonumericsorstrings:
Smallis good.As MySQLloadsdatain memory,a largedata sizewould
haveanadverseimpactonitsperformance.Smallersetscanaccommodate
moredatainmemoryandreduceoverheadsofresourceutilization.
Fixyourlength.Ifyoudon'tfixthedatatypelength,itwouldhavetogo
andfetchtherequiredinformationeachtimeitneedsto.So,whereverit's
possible,youcanlimitthedatalengthbyusingthechardatatype.
Notnull
NotnulldataissomethingthatMySQLdoesn'tlikemuch.Notnullcolumnsuse
morestorage,impacttheperformance,andrequireadditionalprocessingwithin
MySQL.
Optimizingsuch queriesreferringtonulldataisdifficult aswell.Whenanull
datacolumnisindexed,itusesadditionalbytesforeachentry.
Indexing
Indexingisimportant,asitcanimprovetheperformanceofyourbadlydesigned
queryand table structure or it can even turn a well-designed query into a bad
one,whichcanimpactperformancetoo.
Searchfieldsindex
Generally,wedoindexingonfieldsthatareusedasfiltersinMySQLqueries.It
obviously helps reading faster but can adversely impact writes/updates so
indexingonlywhatyouneedwouldbeasmartdecision.
Datatypesandjoins
MySQLcandojoinsfordatatypesthataredifferentbuttheperformancecanbe
impacted if MySQL is asked to use different data types for join fields, as it
wouldhavetoconvertfromonetoanotherforeachrow.
Compoundindex
Ifaqueryissupposedtorefertomultiplecolumnsofatable,acompositeindex
forsuchcolumnsmightbehelpful.Acompoundindexrefersthecolumnsfrom
theresultssetbythefirstcolumn,secondcolumn,andsoon.
Theorderofcolumnsplaysasignificantroleintheperformanceofthequery,so
whiledesigningthetablestructureandindex,youneedtouseiteffectively.
Shorteningupprimarykeys
Smallisgoodforprimarykeystoo.Shorteningupprimarykeyswouldbenefit
analogously to how we discussed datatypes. Because of smaller primary keys,
yourindexsizewouldbesmallerandhencetheusageofcachewouldbeless,so
itcanaccommodatemoredatainmemory.
It is preferred to use numeric types, as these would be much smaller than
characterstoachievethegoalofshorteningupprimarykeys.It canbehelpful
whiledoingjoins,asgenerally,primarykeysarereferredforthejoining.
Indexingeverything
Indexing everything is a good idea; however, MySQL won't do this. Do you
know that MySQL will do a full table scan if it is supposed to scan an index
higherthan30%?
Donotindexvaluesthatdon'tneedtobeindexed.
We need to keep in mind that indexing helps—if done correctly—in fetching
data;however,whilewriting/updatingdata,itisanoverhead.
Fetchingalldata
select *... - Arrghh! Do not use this unless it is really needed. So far, my
experience hasn't needed this. Fetching all data will slow down the execution
timeandimpactheavilyonresourceutilizationoftheMySQLserver.Youneed
toprovideaspecificcolumnnameorappropriateconditions.
Lettingtheapplicationdothejob
Let the application also do the job for MySQL. You can avoid having clauses
such as order by by letting applications do the ordering. Doing ordering in
MySQL is much slower than in applications. You can identify queries that
shouldbeplannedtobetakencareofbytheapplication.
Existenceofdata
CheckingtheexistenceofdatawiththehelpoftheEXISTSclauseismuchfaster.
TheEXISTSclausewillreturntheoutputassoonasitfetchesthefirstrowfromthe
fetcheddata.
Limitingyourself
Limit yourself to the data that you need to fetch. Always ensure that you use
appropriate limits while fetching the data, as unwanted data being fetched
wouldn'tbeusefulandwouldimpactperformance.UsetheLIMITclauseinyour
SQLqueries.
Analyzingslowqueries
Thisisagoodpracticetofollow.Wemightmissoutqueriestoeitheroptimizeor
realize having adverse impact as data grows. You might have changes in the
requirementofthedatatobefetchedwherewemightmissseeingtheimpactof
the queries. It is good to always keep a watch on slow queries that can be
configuredinMySQLandoptimizethem.
Querycost
What is the cost of your query? Explain is the right answer to this. Use the
explainqueryparametertoknowwhatisimpactingyourquery—whetheritisa
full table scan, index scans, range access, and so on. Use the information
provided by explain wisely, to optimize the query further. It is a wonderful,
quickhandytoolofMySQL.Ifyouknowthatyouhavedoneyourbest,indexing
comesasasaviortooptimizeitfurtherbasedonyourneeds.
Best practices while writing a query start with requirements, designs,
implementations, and ongoing maintenance. It's a complete life cycle that we
can'tdiversify.Understandingschemas,indexes,andanalysesplaysasignificant
role.Whatmatterstousistheresponsetimeandoptimumresourceutilization.
Ipersonallylovetodeepdiveintothismuchmorethanwecanmentionhere—
it'saworldofrelations!Yourquerywillmeetaroworcolumnofatableorget
joined with another table. On top of this, if you haven't done it right, you are
trying to find a relation from a subset that is not required. How do we forget
indexesthataresaviorsifusedappropriately?Allthesetogetherwouldshowour
relationsandwouldpromptlyrespondtoarequestedquery.
Summary
Iamsurethatwhilereadingthechapter,youhavekeptinmindthethingstobe
takencareoforrecollectingthem,ifthere'sanythingmissinginyourMySQL8
implementation.
In these chapter, we discussed best practices for MySQL 8 which would be
helpful at various stages, such as implementation, usage, management, and
troubleshootingandwouldactaspointersforbestpracticesofMySQL8;these
might vary based on different use cases. Proper testing and verification would
helpaffirmthebenefitsofhavingbestpracticesimplemented.
WehavebroadlycoveredsomeexcitingtopicsaboutMySQL8benchmarksand
a few configuration parameters along with best practices of memcached. We
discussed MySQL replication best practices, in which we went through a few
critical pointers. Lastly, MySQL queries and indexing pointers were also
discussedwithbestpracticesfordatapartitioning.
Anything written in this chapter would be less, but the pointers provided are
necessary.
By now, we should have a good understanding of MySQL 8; it's now time to
solveproblems.
Let'snowmoveontothenextchapterandlookathowwecouldcomeacross
many common issues, identifying error codes along with real-world scenarios
fortroubleshootingMySQL8.
TroubleshootingMySQL8
In the previous chapter, we learned an important aspect of the MySQL 8
database,benchmarking,and bestpractices. Benchmarkinghelpsincomparing
thecurrentdatabaseperformanceagainsttheexpectedperformancematrices.We
learned what benchmarking is and the tools that can be used to find the
benchmarkperformanceofaMySQL8server.Inalaterpartofthechapter,we
learned about the best practices to be followed for memcached, replication,
partitioning,andindexing.Bestpracticeshelpensuretheoptimumconfiguration
oftheMySQL8database.
In this chapter, the focus will be on understanding the common errors that we
mayencounter whileworking withthe MySQL8database.The errorsmay be
servererrorsorclienterrors.Wewilllookatawaytodeterminethattheproblem
hasoccurred.
Wewillalsolearntroubleshootingandresolutiontechniquesforerrors.Inalater
partofthechapter,wewilllookintoreal-worldscenarioswherethesetechniques
areapplicable.Thefollowingisthelistoftopicstobecovered:
MySQL8commonproblems
MySQL8servererrors
MySQL8clienterrors
MySQL8troubleshootingapproach
Real-worldscenario
MySQL8commonproblems
When troubleshooting is an issue, the first thing to be done is to find out the
programorpieceofequipmentthatiscausingitwhenwerunintoaproblem.
Thefollowingaresymptomsthatindicateahardwareorkernelproblem:
The keyboard is not functioning. It can be checked by pressing the Caps
Lockkey.IfthelightontheCapsLockkeydoesnotlightup,itisanissue
withthekeyboard.Similarly,themousenotmovingindicatesanissuewith
themouse.
ping is an operating system command to check the accessibility of one
machine from another machine. The machine from which the ping
command is executed is called the local machine, whereas the machine
pinged is called the remote machine. If the remote machine does not
respond to the local machine's pings, it indicates a hardware or network
relatedissue.
It may indicate an issue with the operating system kernel program if the
programsotherthanMySQLarenotworkingcorrectly.
Itmayindicateanissuewiththeoperatingsystemorhardwareifthesystem
restartsunexpectedly.Inatypicalcase,auser-levelprogramshouldnever
beabletotakethesystemdown.
Totroubleshoottheissue,oneormoreofthefollowingcanbedone:
Runadiagnostictooltocheckhardware
Ensuretherelevantlibraryfilesareuptodate
Check for the availability of updates, patches, or service packs for the
operatingsystem
Checkallconnections
ECC memory is an error correcting code memory. It can detect and correct most
commoninternaldatacorruptionissues.ItisadvisabletouseECC memoryin
ordertodetectthememoryissuesatanearlystage.
Thefollowinginstructionsmayhelpfurtheridentifytheissue:
Examining the system log files may help to discover the reason for the
problem.MySQL
log files must also be checked in case there appears to be an issue with
MySQL.
Operating system specific commands can be used to check issues with
memory,filedescriptors,diskspace,orothercriticalresources.
A bug can be identified in the operating system kernel if a problematic
runawayprocessdoesnotdieeventhoughwehaveexecutedacommandto
killit.
Ifthereappearsnottobeaproblemwiththehardware,attemptsshouldbe
made to identify the program that may be causing the problem. Using
operatingsystemspecificcommands,suchasTaskmanageronWindows,ps
andtoponLinux,orsimilarprograms,wecanidentifyprogramsthateatup
CPUorblocksystemprocesses.
Itispossibletorecovertheaccesstothemachineeventhoughthekeyboard
islockedup.Thiscan bedone byloggingontothe systemfrom another
machine.Executethekbd_mode-acommanduponsuccessfullogin.
MySQLuserscanreportissuesbyusingoneofthemultiplechannelsprovided
byMySQL.
After having examined all the possible alternatives, if it can be decided that
either the MySQL server or the MySQL client causes the problem, a user can
either create a bug report for the mailing list or contact the MySQL support
team.Thebugreportermustprovidedetailedinformationaboutthebug,system
information,andbehaviorandtheexpectedbehavior.Thereportermustdescribe
thereasonbasedonwhyitseemstobeaMySQLbug.Itisusefultoknowthe
followinginformationiftheprogramfails:
With the help of the top command, check if the program in question has
takenupalltheCPUtime.Insuchcases,weshouldallowaprogramtorun
for a while because it is possible that the program may be executing
intensivecomputationalinstructions.
ObservetheresponsefromtheMySQLserverwhenaclientprogramtries
to connect to it. Has it stopped responding? Did the server provide any
output?
If it is found that the MySQL server is causing problems in the mysqld
program,trytoconnectusingthemysqladminprogramtocheckwhethermysqld
responds. The mysqladmin -u root ping or mysqladmin -u root processlist
commandscanbeused.
Didthefailedprogrammakeasegmentationfault?
MostcommonMySQLerrors
This section provides a list of the most common MySQL errors that users
encounterveryfrequently.
Accessdenied
MySQL provides a privilege system that authenticates the user who connects
from a host, and associates the user with access privileges on a database. The
privileges include SELECT, INSERT, UPDATE, and DELETE and are able to identify
anonymoususersandgrantprivilegesforMySQLspecificfunctions,suchasLOAD
DATAINFILEandadministrativeoperations.
Theaccessdeniederrormayoccurbecauseofmanycauses.Inmanycases,the
problemiscausedbecauseofMySQLaccountsthattheclientprogramsuseto
connectwiththeMySQLserverwithpermissionfromtheserver.
<strong><spanclass="tokencommand">>mysqladmin</span>
version<br/><spanclass="tokencommand">>mysqladmin</span>
variables<br/><spanclass="tokencommand">>mysqladmin</span>
<spanclass="tokenproperty">-h</span>`hostname`version
variables<br/><spanclass="tokencommand">>mysqladmin</span>
<spanclass="tokenproperty">-h</span>`hostname`<span
class="tokenconstant">--port</span><spanclass="tokenattr-value">
<spanclass="tokenpunctuation">=</span>3306</span>version<br
/><spanclass="tokencommand">>mysqladmin</span><span
class="tokenproperty">-h</span>host_ipversion<spanclass="token
command"><br/>>mysqladmin</span><spanclass="token
constant">--protocol</span><spanclass="tokenattr-value"><span
class="tokenpunctuation">=</span>SOCKET</span><span
class="tokenconstant">--socket</span><spanclass="tokenattr-
value"><spanclass="tokenpunctuation">=
</span>/tmp/mysql.sock</span>version</strong>
Intheprecedingcommands,hostnameisthehostnameofthemachine
onwhichtheMySQLserverisrunning.host_ipistheIPaddressof
theservermachine.
LostconnectiontoMySQLserver
ThelostconnectiontoMySQLservererrorcanoccurbecauseofoneofthethree
likely
causesexplainedinthissection.
One of the potential reasons for the error is that the network connectivity is
troublesome.
Networkconditionsshouldbecheckedifthisisafrequenterror.Iftheduring
query message is part of the error message, it is certain that the error has
occurredbecause
ofnetworkconnectionissues.
The connection_timeout system variable defines the number of seconds that the
mysqldserverwaitsforaconnectionpacketbeforeconnectiontimeoutresponse.
Infrequently,
this error may occur when a client is trying for the initial connection to the
server
andtheconnection_timeoutvalueissettoafewseconds.Inthiscase,theproblem
canberesolvedbyincreasing
theconnection_timeoutvaluebasedonthethedistanceandconnectionspeed.SHOW
GLOBAL STATUS LIKE and Aborted_connects can be used to determine if we are
experiencingthismorefrequently.Itcanbecertainly
saidthatincreasingtheconnection_timeoutvalueisthesolutioniftheerrormessage
containsreadingauthorizationpacket.
It is possible that the problem may be faced because of larger Binary Large
OBject(BLOB)valuesthanmax_allowed_packet.Thiscancausealostconnection
to the MySQL server error with clients. If the ER_NET_PACKET_TOO_LARGE error is
observed,itconfirmsthatthemax_allowed_packetvalueshouldbeincreased.
<strong>>mysql-uuser_name-p</strong><br/><strong>Enter
password:</strong>
Onafewsystems,itmayhappenthatthepasswordworksfinewhen
specifiedinanoptionfileoronthecommandline.Butitdoesnot
workwhenenteredinteractivelyontheCommandPromptatthe
Enterpassword:prompt.Itoccursbecausethesystem-provided
librarytoreadthepasswordslimitsthepasswordvaluestoasmall
numberofcharacters(usuallyeight).Itisanissuewiththesystem
libraryandnotwithMySQL.Asaworkaroundtothis,changethe
MySQLpasswordtoavaluethatiseightorfewercharactersorstore
thepasswordintheoptionfile.
<strong>Host'host_name'isblockedbecauseofmanyconnection
errors.</strong><br/><strong>Unblockwith'mysqladminflush-
hosts'</strong>
<strong>>mysqld_safe--max_connect_errors=10000</strong>
<strong>mysql>SETGLOBALmax_connect_errors=10000;
</strong>
ItshouldbecheckedfirstthatthereisnothingwrongwithTCP/IP
connectionsfromthehostifthehost_nameisblockederrorisreceived
foraparticularhost.Increasingthevalueofthemax_connect_errors
variabledoesnothelpifthenetworkhasproblems.
Toomanyconnections
This error indicates that all available connection are in use for other client
connections.
Themax_connectionsisthesystemvariablethatcontrolsthenumberofconnections
totheserver.The
default value for the maximum number of connections is 151. We can set a
largervalue
than151forthemax_connectionssystemvariabletosupportmoreconnectionsthan
151.
The mysqld server process actually allows one more than max_connections
(max_connections + 1) value clients to connect. The additional one connection is
keptreservedforaccounts
with CONNECTION_ADMIN or the SUPER privilege. The privilege can be granted to the
administrators with access to the PROCESS privilege. With this access, the
administratorcanconnecttotheserverusingthe
reservedconnection.TheycanexecutetheSHOWPROCESSLISTcommandtodiagnose
theproblemseventhoughthemaximumnumberofclientconnections
isexhausted.
Outofmemory
Ifthemysqldoesnothaveenoughmemorytostoretheentirerequestofthequery
issued by the MySQL client program, the server throws the following error:
mysql:Outofmemoryatline42,'malloc.c'
mysql:needed8136byte(8k),memoryinuse:12481367bytes(12189k)
ERROR2008:MySQLclientranoutofmemory
Inordertofixtheproblem,wemustfirstcheckifthequeryiscorrect.Dowe
expectthequerytoreturnsomanyrows?Ifnot,weshouldcorrectthequeryand
executeitagain.Ifthequeryiscorrectandneedsnocorrection,wecanconnect
mysql with the --quick option. Using the --quick option results in the
mysql_use_result() C API function for fetching the result set. The function adds
moreloadontheserverandlessloadontheclient.
<strong><spanclass="tokencommand">>mysql</span><span
class="tokenconstant">--max_allowed_packet</span><span
class="tokenattr-value"><spanclass="tokenpunctuation">=
</span>32M</span></strong>
ThedefaultvaluefortheMySQLserveris64MB.Itshouldbenoted
thatthereisnoharminsettingalargervalueforthissystemvariable,
astheadditionalmemoryisallocatedasneeded.
Thetableisfull
Thetable-fullerroroccursinoneofthefollowingconditions:
Thediskisfull
Thetablehasreachedthemaximumsize
TheactualmaximumtablesizeintheMySQLdatabasecanbedeterminedbythe
constraintsimposedbytheoperatingsystemonthefilesizes.
<strong>Can'tcreate<spanclass="tokenoperator">/</span>writeto
file'\\sqla3fe_0<spanclass="tokenpunctuation">.</span>ism'<span
class="tokenpunctuation">.</span></strong>
<strong>>mysqld--tmpdirC:/temp</strong>
<strong>[mysqld]</strong><br/><strong>tmpdir=C:/temp</strong>
Commandsoutofsync
Iftheclientfunctionsarecalledinthewrongorder,thecommandsoutofsync
error is received. It means that the command cannot be executed in the client
code.Asanexample,ifweexecutemysql_use_result()andtrytoexecuteanother
query before executing mysql_free_result(), this error may occur. It may also
happen if we execute two queries that return a result set without calling the
mysql_use_result()ormysql_store_result()functionsinbetween.
<strong>Foundwrongpasswordforuser'some_user'@'some_host';
ignoringuser</strong>
TheaccountisignoredbytheMySQLpermissionsystemasaresult.
Tofixtheproblem,weshouldassignanewvalidpasswordforthe
account.
<strong>Table'tbl_name'doesn'texist</strong><br/><strong>Can't
findfile:'tbl_name'(errno:2)</strong>
Insomecases,theusermaybereferringtothetableincorrectly.Itis
possiblebecausetheMySQLserverusesdirectoriesandfilesfor
storingdatabasetables.Dependingupontheoperatingsystemfile
management,thedatabaseandtablenamescanbecasesensitive.
Fornoncase-sensitivefilesystems,suchasWindows,thereferencesto
aspecifiedtableusedwithinaquerymustusethesamelettercase.
MySQL8servererrors
ThissectionfocusesonMySQL8servererrors.Thesectiondescribestheerrors
relatedtoMySQLserveradministration,tabledefinitions,andknownissuesin
theMySQL8server.
<strong>ERROR:Can'tfindfile:'path/with/file_name'(Errcode:13)
</strong>
<strong><spanclass="tokenprompt">></span><spanclass="token
command">UMASK</span><spanclass="tokenattr-value"><span
class="tokenpunctuation">=</span>384</span><spanclass="token
comment">#=600inoctal</span><br/><spanclass="token
prompt">></span><spanclass="tokencommand">export</span>
UMASK<br/><spanclass="tokenprompt">></span><span
class="tokencommand">mysqld_safe</span></strong>
<strong><spanclass="tokenprompt">></span><spanclass="token
command">UMASK_DIR</span><spanclass="tokenattr-value">
<spanclass="tokenpunctuation">=</span>504</span><span
class="tokencomment">#=770inoctal</span><br/><span
class="tokenprompt">></span><spanclass="tokencommand">
export</span>UMASK_DIR<br/><spanclass="tokenprompt">>
</span><spanclass="tokencommand">mysqld_safe</span>&
</strong>
<strong><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">USER</span><spanclass="token
string">'root'</span>@<spanclass="tokenstring">'localhost'</span>
<spanclass="tokenkeyword">IDENTIFIED</span><span
class="tokenkeyword">BY</span><spanclass="token
string">'NewPassword'</span><spanclass="tokenpunctuation">;
</span></strong>
<strong><spanclass="tokenprompt">C:\></span><span
class="tokencommand">cd</span><spanclass="token
atrule">"C:\ProgramFiles\MySQL\MySQLServer8.0\bin"</span>
<br/><spanclass="tokenprompt">C:\></span><spanclass="token
command">mysqld</span><spanclass="tokenconstant">--init-
file</span><spanclass="tokenattr-value"><spanclass="token
punctuation">=</span>C:\\mysql-root-reset.txt</span></strong>
<strong>>kill'cat/mysql-data-directory/host_name.pid'</strong>
<strong><spanclass="tokenkeyword">ALTER</span><span
class="tokenkeyword">USER</span><spanclass="token
string">'root'</span>@<spanclass="tokenstring">'localhost'</span>
<spanclass="tokenkeyword">IDENTIFIED</span><span
class="tokenkeyword">BY</span><spanclass="token
string">'NewPassword'</span><spanclass="tokenpunctuation">;
</span></strong>
<strong><spanclass="tokenprompt">></span><spanclass="token
command">mysqld</span><spanclass="tokenconstant">--init-
file</span><spanclass="tokenattr-value"><spanclass="token
punctuation">=</span>/home/me/mysql-reset-root</span>&
</strong>
<strong>>mysql</strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">FLUSH</span><spanclass="token
keyword">PRIVILEGES</span><spanclass="tokenpunctuation">;
</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">ALTER</span><spanclass="token
keyword">USER</span><spanclass="token
string">'root'</span>@<spanclass="tokenstring">'localhost'</span>
<spanclass="tokenkeyword">IDENTIFIED</span><span
class="tokenkeyword">BY</span><br/><spanclass="token
string">'NewPassword'</span><spanclass="tokenpunctuation">;
</span></strong>
5. Restarttheserverandloginwiththerootuserandnewlyset
password.
<strong>C:\ProgramFiles\MySQL\MySQLServer
8.0\bin>mysqladminversion-uroot-p</strong><br/><strong>Enter
password:*****</strong><br/><strong>mysqladminVer8.0.3-rcfor
Win64onx86_64(MySQLCommunityServer(GPL))</strong><br
/><strong>Copyright(c)2000,2017,Oracleand/oritsaffiliates.All
rightsreserved.</strong><br/><br/><strong>Oracleisaregistered
trademarkofOracleCorporationand/orits</strong><br/>
<strong>affiliates.Othernamesmaybetrademarksoftheir
respective</strong><br/><strong>owners.</strong><br/><br/>
<strong>Serverversion8.0.3-rc-log</strong><br/><strong>Protocol
version10</strong><br/><strong>Connectionlocalhostvia
TCP/IP</strong><br/><strong>TCPport3306</strong><br/>
<strong>Uptime:9days4hours4min52sec</strong><br/><br/>
<strong>Threads:2Questions:4Slowqueries:0Opens:93Flush
tables:2Opentables:69Queriespersecondavg:0.000</strong>
Theresolve_stack_dumpisautilityprogramthatresolvesanumeric
stackdumptosymbols.Toanalyzetherootcauseofwherethemysqld
serverprocessdied,wefindinthestacktraceerrorlogs.Itcanbe
resolvedwiththeresolve_stack_dumpprogram.Itmustbenotedthat
itispossiblethatvariablevaluesfoundintheerrorlogsmaynotbe
accurate.
CorrupteddataorindexfilescancausetheMySQLservertocrash.
Thesefilesareupdatedonthediskusingthewrite()systemcalled
upontheexecutionofeachSQLstatementandbeforetheclientis
notifiedabouttheresult.Itmeansthatthecontentsinthedatafilesare
safeevenintheeventofamysqldcrash.Thewritingoftheunflushed
dataonthediskistakencareofbytheoperatingsystem.The--flush
optioncanbeusedwithmysqldtoforceMySQLtoflusheverythingto
diskaftereverySQLstatementexecution.
OneofthefollowingcanbethereasonforMySQLcorruptedtables:
Ifthedatafileorindexfilecrashesthenitcontainscorrupted
data.
AbugintheMySQLserverprocesscausedtheservertodieinthe
middleofanupdate.
Anexternalprogrammanipulatedthedataandindexfilesatthe
sametimeasmysqldwithouttablelocking.
Inthemiddleofanupdate,theMySQLserverprocesswaskilled.
Manymysqldserversarerunningonthesystem.Theserversuse
thesamedatadirectory.Thesystemdoesnothavegood
filesystemlocksortheexternallockingisdisabled.
Itispossiblethatabugisfoundinthedatastoragecode.Wecan
trytochangethestorageenginebyusingALTERTABLEonthe
repairedcopyofthetable.
HandlingMySQLfulldisk
ThissectionfocusesontheresponsefromMySQLtodisk-fullerrorsandquota-
exceedederrors.ItismorerelevanttowritesinMyISAMtables.Itcanbeappliedto
writesinbinarylogfilesandanindexfile.Itexcludesthereferencestorowsand
recordsthatshouldbeconsideredanevent.
MySQLperformsthefollowingwhenadisk-fullconditionoccurs:
MySQL ensures that there is enough space available to write the current
row.
TheMySQLserverwritesanentryinthelogfileevery10minutes.Itwarns
aboutthedisk-fullcondition.
Thefollowingactionsshouldbetakentoremedytheproblem:
Thediskspaceshouldbefreedtomakesureenoughspaceisavailableto
insertallrecords.
We canexecutethe mysqladmin killcommand toabortthe thread.Thenext
timeitchecksthedisk,thethreadisaborted.
Itmayhappenthatafewthreadsarewaitingforthetablethatcausedthe
disk-fullsituation. Outof severallocked threads,killing thethread thatis
waitingonthedisk-fullconditionwillenableotherthreadstocontinue.
TheREPAIRTABLEorOPTIMIZETABLEstatementsareexceptionstothepreceding
condition.OtherexceptionsincludeindexescreatedinabatchaftertheLOAD
DATA INFILE or ALTER TABLE statements. These SQL statements can create
temporaryfileswith largevolumes.This maycreate big problemsfor the
restofthesystem.
MySQLtemporaryfilesstorage
ThevalueoftheTMPDIRenvironmentvariableisusedbyMySQLontheUnixas
the pathname ofthe directoryto store temporary files. MySQL uses a system
default,suchas/tmp,/var/tmp,or/usr/tmpiftheTMPDIRisnotset.
The values of the TMPDIR, TEMP, and TMP environment variables are checked by
MySQLonWindows.IfMySQLfindsoneset, itusesthatvalue anddoes not
checkforremainingvalues.Ifnoneofthesethreevariablesareset,MySQLuses
thesystemdefault,whichisC:\windows\temp\.
Ifthetemporaryfiledirectoryinthefilesystemistoosmall,wecanusethemysqld
--tmpdiroptionto specify adirectoryon thefilesystemwith enough space.For
thereplication,onslavemachines,wecanuse--slave-load-tmpdirandspecifythe
directory for holding temporary files during the replication of LOAD DATA INFILE
statements. It is possible to set a list of several paths used in a round-robin
fashionwiththe--tmpdiroption.OntheUnixsystem,thepathscanbeseparated
bythecoloncharacter(:),whereason Windows,the semicoloncharacter(;) can
beusedtoseparatethepaths.
To effectively distribute the load, multiple temporary directory
pathsshouldbelongtodifferentphysicaldisksandnotthedifferent
partitionsofthesamedisk.
For the MySQL server working as a replication slave, we must take care of
setting the --slave-load-tmpdir option so as not to point to a directory in the
memory-basedfilesystemortoadirectorythatiscleareduponserverorserver
hostrestarts.ToreplicatethetemporarytablesorLOAD DATA INFILEoperations,the
replication slave requires its temporary files on the machine restart. The
replicationfailsifthefilesinthetemporaryfiledirectoryarelost.
MySQL takes care of removing the temporary files when the mysqld server
processisterminated.OnUnix-likeplatforms,itcanbedonebyunlinkingafile
afteropeningit.Oneofthemajordisadvantageofthisisthatthenamedoesnot
appear in directory listings. It also happens that we cannot see a big file that
occupiesthefilesystem.
ibtmp1isthenameofthetablespacefilethattheInnoDBstorageengineusestostore
temporarytables.ThefileislocatedinthedatadirectoryofMySQL.Ifwewant
to specify a different filename and location, the innodb_temp_data_file_pathoption
canbeusedontheserverstartup.
If the ALGORITHM=COPY technique is used by the ALTER TABLE operation on the InnoDB
table, the storage engine creates a temporary copy of the original table in the
samedirectory.Thetemporarytable filenamesstartwiththe#sql- prefix. They
onlyappearbrieflywhiletheALTERTABLEoperationisbeingperformed.
If the InnoDB table is rebuilt by the ALTER TABLE SQL statement using the
ALGORITHM=INPLACEmethod,theInnoDBstorageenginecreatesanintermediatecopyof
the original table in the same directory as that of the original table. The
intermediate table filenames start with the #sql-ib prefix. They only appear
brieflywhiletheALTERTABLEoperationisbeingperformed.
The innodb_tmpdir option cannot be applied to intermediate table files. These
intermediatefilesarealwayscreatedandstoredinthesamedirectoryasthatof
theoriginaltable.
The ALTER TABLE SQL statements that rebuild the InnoDB table with the
ALGORITHM=INPLACE method create temporary sort files in the default MySQL
temporary directory. The default temporary directory is denoted by $TMPDIR on
Unix,%TEMP%onWindows,orthedirectorymentionedbythe--tmpdiroption.tmpdir
may need to be reconfigured if the temporary directory is not large enough to
storesuchfiles.Asanalternative,wecandefineanothertemporarydirectoryfor
onlineInnoDBALTERTABLEstatementsusingtheinnodb_tmpdiroption.Theinnodb_tmpdir
optioncanbeconfiguredatruntime,usingtheSETGLOBALorSETSESSIONstatements.
Replicating an innodb_tmpdir configuration should be considered in replication
environmentsifalltheservershavethesameoperatingsystemenvironment.In
othercases,an innodb_tmpdir setting replication can result in a failed replication
while executing online ALTER TABLE operations. It is recommended to configure
innodb_tmpdir for each server separately if the operating environments are
different.
<strong>chmod+t/tmp</strong>
<strong>[mysqld]</strong><br/><strong>
socket=/path/to/socket</strong><br/><br/><strong>[client]
</strong><br/><strong>socket=/path/to/socket</strong>
<strong>mysqladmin--socket=/path/to/socketversion</strong>
Timezoneproblems
TheMySQLservermustbetoldtheuser'scurrenttimezoneifwehaveproblem
with
SELECTNOW()returningavalueinUTCinsteadoftheuser'scurrenttimezone.Itis
alsoapplicable
ifUNIX_TIMESTAMP()returns awrong value.Itshouldbedonefortheenvironment
runningtheserver;
forexample,mysqld_safeormysql.server.
Wecanalsosettheservertimezonebyusingthe--timezone=timezone_nameoption
withmysqld_safe.ItcanalsobesetbyassigningthevaluetotheTZenvironment
variablebeforethemysqldisstarted.
Theallowedlistofvaluesfor--timezoneorTZdependsonthesystem.
MySQL8clienterrors
ThissectionfocusesonerrorsthatoccurontheMySQL8client.Thejobofa
MySQL
clientistoconnecttotheMySQLserversoastoexecutetheSQLqueriesand
get the results from the MySQL 8 database. This section lists errors related to
executionofthequeries.
<strong>col_name<spanclass="tokenkeyword">COLLATE</span>
utf8mb4_0900_as_cs<spanclass="tokenoperator">LIKE</span>
<spanclass="tokenstring">'a%'</span></strong><br/>
<strong>col_name<spanclass="tokenoperator">LIKE</span><span
class="tokenstring">'a%'</span><spanclass="token
keyword">COLLATE</span>utf8mb4_0900_as_cs</strong><br/>
<strong>col_name<spanclass="tokenkeyword">COLLATE</span>
utf8mb4_bin<spanclass="tokenoperator">LIKE</span><span
class="tokenstring">'a%'</span></strong><br/><strong>col_name
<spanclass="tokenoperator">LIKE</span><spanclass="token
string">'a%'</span><spanclass="token
keyword">COLLATE</span>utf8mb4_bin</strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SET</span><spanclass="token
keyword">NAMES</span><spanclass="token
string">'utf8mb4'</span><spanclass="tokenpunctuation">;</span>
<br/><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SET</span><spanclass="token
variable">@s1</span><spanclass="tokenoperator">=</span>
<spanclass="tokenstring">'MySQL'</span><spanclass="token
keyword">COLLATE</span>utf8mb4_bin<spanclass="token
punctuation">,</span><spanclass="tokenvariable">@s2</span>
<spanclass="tokenoperator">=</span><spanclass="token
string">'mysql'</span><spanclass="token
keyword">COLLATE</span>utf8mb4_bin<spanclass="token
punctuation">;</span><spanclass="tokenprompt">mysql></span>
<spanclass="tokenkeyword">SELECT</span><spanclass="token
variable">@s1</span><spanclass="tokenoperator">=</span>
<spanclass="tokenvariable">@s2</span><spanclass="token
punctuation">;<br/></span><spanclass="tokenoutput"><span
class="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>@s1
=@s2<spanclass="tokenpunctuation">|</span></span><br/>
<spanclass="tokenoutput"><spanclass="tokenpunctuation">+
</span><spanclass="tokenpunctuation">-</span><span
class="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>0<spanclass="token
punctuation">|</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span><br/><span
class="tokenprompt">mysql></span><spanclass="token
keyword">SELECT</span><spanclass="token
variable">@s1</span><spanclass="token
keyword">COLLATE</span>utf8mb4_0900_ai_ci<span
class="tokenoperator">=</span><spanclass="token
variable">@s2</span><spanclass="tokenpunctuation">;</span><br
/><spanclass="tokenoutput"><spanclass="tokenpunctuation">+
</span><spanclass="tokenpunctuation">-</span><span
class="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">+</span></span><br/><spanclass="tokenoutput">
<spanclass="tokenpunctuation">|</span>@s1COLLATE
utf8mb4_0900_ai_ci=@s2<spanclass="tokenpunctuation">|
</span></span><br/><spanclass="tokenoutput"><span
class="tokenpunctuation">+</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">+</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">|</span>1
<spanclass="tokenpunctuation">|</span></span><br/><span
class="tokenoutput"><spanclass="tokenpunctuation">+</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">-</span>
<spanclass="tokenpunctuation">-</span><spanclass="token
punctuation">-</span><spanclass="tokenpunctuation">+</span>
</span></strong>
<strong><spanclass="tokenkeyword">SELECT</span><span
class="tokenoperator">*</span><spanclass="token
keyword">FROM</span>table_name<spanclass="token
keyword">WHERE</span><spanclass="token
datatype">date_col</span><spanclass="tokenoperator">>=</span>
<spanclass="tokenstring">'2011-06-02'</span><spanclass="token
punctuation">;</span></strong>
WhenaconstantstringiscomparedtoDATE,TIME,DATETIME,or
TIMESTAMPusing<,<=,=,>=,>,orBETWEENoperators,MySQL
convertsthestringintoaninternallongintegervalue.MySQLdoes
thissoastoachieveafastercomparison.However,thefollowing
exceptionsareapplicabletothisconversion:
Comparingtwocolumns
ComparingaDATE,TIME,DATETIME,orTIMESTAMPcolumntoan
expression
Useofacomparisonmethodotherthanthosejustlisted,suchas
INorSTRCMP()
Thecomparisonisdonebyconvertingtheobjectsintostringvalues
andperformingastringcomparisonincaseoftheseexceptions.
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">INSERT</span><spanclass="token
keyword">INTO</span>my_table<spanclass="tokenpunctuation">
(</span>phone<spanclass="tokenpunctuation">)</span><span
class="tokenkeyword">VALUES</span><spanclass="token
punctuation">(</span><spanclass="tokenboolean">NULL</span>
<spanclass="tokenpunctuation">)</span><spanclass="token
punctuation">;</span><br/><spanclass="tokenprompt">mysql>
</span><spanclass="tokenkeyword">INSERT</span><span
class="tokenkeyword">INTO</span>my_table<spanclass="token
punctuation">(</span>phone<spanclass="tokenpunctuation">)
</span><spanclass="tokenkeyword">VALUES</span><span
class="tokenpunctuation">(</span><spanclass="token
string">''</span><spanclass="tokenpunctuation">)</span><span
class="tokenpunctuation">;</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
boolean">NULL</span><spanclass="tokenpunctuation">,</span>
<spanclass="tokennumber">1</span><spanclass="token
operator">+</span><spanclass="tokenboolean">NULL</span>
<spanclass="tokenpunctuation">,</span><spanclass="token
function">CONCAT</span><spanclass="tokenpunctuation">
(</span><spanclass="tokenstring">'Invisible'</span><span
class="tokenpunctuation">,</span><spanclass="token
boolean">NULL</span><spanclass="tokenpunctuation">)</span>
<spanclass="tokenpunctuation">;</span></strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
my_table<spanclass="tokenkeyword">WHERE</span>phone
<spanclass="tokenoperator">=</span><spanclass="token
boolean">NULL</span><spanclass="tokenpunctuation">;</span>
</strong>
<strong><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
my_table<spanclass="tokenkeyword">WHERE</span>phone
<spanclass="tokenoperator">IS</span><spanclass="token
boolean">NULL</span><spanclass="tokenpunctuation">;</span>
<br/><spanclass="tokenprompt">mysql></span><span
class="tokenkeyword">SELECT</span><spanclass="token
operator">*</span><spanclass="tokenkeyword">FROM</span>
my_table<spanclass="tokenkeyword">WHERE</span>phone
<spanclass="tokenoperator">=</span><spanclass="token
string">''</span><spanclass="tokenpunctuation">;</span></strong>
MySQL 8 troubleshooting
approach
In this section of the chapter, we will focus on the MySQL 8 troubleshooting
approach.
WhydoweneedtotroubleshootMySQL8?Thereasonsfortroubleshootingare
asfollows:
FasterexecutionofSQLqueries
Performanceenhancement
Efficientuseofresources
TheprimarysetofresourcesincludeCPU,diskIO,memory,andnetwork.There
aretwoapproachestomeasureMySQLperformance:
Inaqueryfocusedapproach,itisimportanttomeasurehowfastthequeries
getexecuted
In resource focused approach, it is important that the queries use fewer
resources.
LetustakeadeeperlookatwaystotroubleshootMySQLproblems.
<strong>mysql>SELECT*FROMtbl_nameWHERE
primary_key=1;</strong><br/><strong>mysql>SELECT*FROM
tbl_nameWHEREprimary_key_part1=1ANDprimary_key_part2=2;
</strong>
ref:Foreachcombinationofrowsfromtheearliertables,all
rowswithmatchingindexvaluesarereadfromthereftable.If
thejoinusesonlytheleftmostprefixofthekey,therefisused.
Real-worldscenario
MySQL query optimization is referred to as improving the time of query
execution.
Forexample,whenaqueryisnotperformingwellmeansthatthequeryistaking
a longer time than expected for execution. The time of the query execution is
important but there are other matrices as well that are used to measure
performance.Thissectionexplainswhatshouldbemeasuredandhowitshould
bedoneaspreciselyaspossible.
Thefollowingquestionarises:whyshouldweoptimizethequery?Doesitreally
requireoptimizationifitonlytakesahundredthofasecond?Yes,itdoesrequire
optimizationunlessthequeryisexecutedrarely.Weshouldoptimizethequeries
thataremostexpensive.
Let'sdiscussareal-timeexample.Inoneoftheapplications,wehadareportthat
was generated based on a complex query and was taking too much time. The
execution time was in minutes. To optimize such a complex query, we
consideredthefollowingapproach:
1. Analyze the query plan usingEXPLAIN: MySQL provides two ways to
analyze the performance of a query. One is the EXPLAIN method, which we
havealreadylearnedaboutintheprecedingsectionofthischapter.
Another tool is SHOW STATUS. Usually, we should prefer to use EXPLAIN to
understandthequeryplanofaSELECTquery.Inthecaseofthereportquery,
weconvertafewofthenon-SELECTqueriestoSELECTqueries.Thishelpsusin
understandingthequeryexecutionplanfornon-SELECTqueriesaswell.For
example,rewritinganUPDATEquerytoSELECTcanbedonebyusingtheWHERE
clauseintheUPDATEquery,whichispassedontotheSELECTquery.Wecould
alsofindfewmissingindexesonthetables.
2. SHOW STATUS: The SHOW STATUS statement outputs the internal counters for
MySQL. The counters are incremented by MySQL upon every query
execution.Withthehelpofthesecounters,wecouldunderstandthetypesof
operationsperformedbytheserverinaggregate.Italsohelpsinindicating
theworkdonebyeachindividualquery.
ThefollowingarethemeasurementsperformedforMySQLservervariables:
Select_: This counter is incremented whenever a SELECT query is executed.
Thiscountercanalsobeusedtoidentifyifatablescanisperformed.
Key_read:This variableprovides additionalinformation onthe usageofthe
keyindex.
Last_query_cost:Thisvalueindicateshowexpensivethelastexecutedquery
was.
Thefollowingarethestepstoperformqueryoptimization:
1. Querytheexecutionafewtimestoensureitreturnsthesameresult.
2. ExecuteSHOWSTATUS.Theoutputshouldbesaved.
3. Executethequery.
4. ExecuteSHOWSTATUStoobservethedifferencesfromthepreviousexecution.
5. ExecuteEXPLAINifrequired.
The following parameters should be analyzed for query performance
optimization:
Tableindex
Sorting
Overallperformance
Rowleveloperations
DiskI/Ooperations
Summary
Inthislastchapterofthebook,welearnedanimportantaspectofanydatabase:
troubleshootingerrorsthatwemayencounterusingtheMySQLserverorclient.
We started the discussion by understanding what troubleshooting is. We
discussed different ways for initial diagnostics of the error. We understood
common MySQL errors and what the error messages mean. We also learned
aboutthewaystofixtheseerrors.WealsolearnedabouttheMySQLserverand
clienterrorsandfixesfortheseerrors.Inthelaterpartofthechapter,welearned
abouttheMySQLtroubleshootingapproachandlookedatareal-worldscenario.
Prettyimportantstuffforthelastchapter,huh?
That'sitforthebook.
OtherBooksYouMayEnjoy
Ifyouenjoyedthisbook,youmaybeinterestedintheseotherbooksbyPackt:
MySQL8forBigData
Shabbir Challawala, Jaydip Lakhatariya, Chintan Mehta, Kandarp Patel ISBN:
978-1-78839-718-6
ExplorethefeaturesofMySQL8andhowtheycanbeleveragedtohandle
BigData
Unlock the new features of MySQL 8 for managing structured and
unstructuredBigData
IntegrateMySQL8andHadoopforefficientdataprocessing
PerformaggregationusingMySQL8foroptimumdatautilization
ExploredifferentkindsofjoinandunioninMySQL8toprocessBigData
efficiently
AccelerateBigDataprocessingwithMemcached
IntegrateMySQLwiththeNoSQLAPI
ImplementreplicationtobuildhighlyavailablesolutionsforBigData
MySQL8Cookbook
KarthikAppigatla
ISBN:978-1-78839-580-9
InstallandconfigureyourMySQL8instancewithoutanyhassle
Getto gripswith newfeatures ofMySQL8 likeCTE, Windowfunctions
andmanymore
Perform backup tasks, recover data and set up various replication
topologiesforyourdatabase
MaximizeperformancebyusingnewfeaturesofMySQL8likedescending
indexes,controllingqueryoptimizerandresourcegroups
Learn how to use general table space to suit the SaaS or multi-tenant
applications
Analyze slow queries using performance schema, sys schema and third
partytools
Manage and monitor your MySQL instance and implement efficient
performance-tuningtasks
Leaveareview-letotherreaders
knowwhatyouthink
Pleaseshareyourthoughtsonthisbookwithothersbyleavingareviewonthe
site that you bought it from.If you purchased the book from Amazon, please
leaveusanhonestreviewonthisbook'sAmazonpage.Thisisvitalsothatother
potential readers can see and use your unbiased opinion to make purchasing
decisions,wecanunderstandwhatourcustomersthinkaboutourproducts,and
ourauthorscanseeyourfeedbackonthetitlethattheyhaveworkedwithPackt
tocreate.Itwillonlytakeafewminutesofyourtime,butisvaluabletoother
potentialcustomers,ourauthors,andPackt.Thankyou!