www.it-ebooks.info www.it-ebooks.info Learning MySQL and MariaDB Russell J.T Dyer Beijing • Cambridge • Farnham • Kưln • Sebastopol • Tokyo www.it-ebooks.info To Fortunata Serio, my mother, who gave me life, taught me to be kind and loving, and to speak — which is a precursor to being a writer And to Andrew Gambos, who had the thankless job of being my stepfather, but taught me how to assert myself in life and in my career www.it-ebooks.info www.it-ebooks.info Special Upgrade Offer If you purchased this ebook directly from oreilly.com, you have the following benefits: DRM-free ebooks — use your ebooks across devices without restrictions or limitations Multiple formats — use on your laptop, tablet, or phone Lifetime access, with free updates Dropbox syncing — your files, anywhere If you purchased this ebook from another retailer, you can upgrade your ebook to take advantage of all these benefits for just $4.99 Click here to access your ebook upgrade Please note that upgrade offers are not available from sample content www.it-ebooks.info www.it-ebooks.info Foreword Before you begin to read the main chapters of this book to learn about MySQL and MariaDB, it might be useful to understand what we were trying to accomplish when we first created MySQL about 20 years ago and MariaDB about 5 years ago, as well as the current state of these database systems and my expectations of them going forward And I’d like to encourage you in your decision to learn these database systems and to assure you that they will be in use for a long time and that you will benefit from the time and energy you put into reading this book and learning what it has to teach you www.it-ebooks.info Origins of MySQL When my business partner David Axmark and I started MySQL, there weren’t any good, free, open source database systems There was mSQL, which wasn’t open source, but it inspired us to create a new database system for our clients, which would later become MySQL We had no plans to do anything more with this embryo of MySQL other than satisfy the needs of our clients We were learning, discovering, and creating out of practical concerns and needs, much as you might and perhaps should be doing as a reader of this book and a newcomer to MySQL and MariaDB Although we had accomplished our task in creating a straightforward database to meet our requirements, it wasn’t long before we noticed that there were many other organizations that were looking for a solution similar to what we had already developed So we decided to make the software available to the public and we named it MySQL Part of our motivation for doing this was that we felt that it was a way in which we could give something back to the open source community that would be very useful Most open source projects at that time weren’t as useful We wanted to make the world a little better — we had no idea at that time how much of an impact MySQL would have on the world At the same time, we were hoping that by going public with the software, it might finance further development of MySQL for as long as we might want We had expectations of getting rich from MySQL We hoped only to be able to work full-time on this project because we believed in it The result, though, was that we contributed much to the world — much more than we thought possible Given the fact that over 80% of the websites in the world are now running on MySQL, one could easily argue that we accelerated the growth of the internet and almost everything that has grown out of it The impact it’s had is immeasurable Many of the sites and businesses that have been successful, including the ones that are now huge, probably would never have started if it were not for MySQL being free and dependable At that time, those founders and startup companies just didn’t have the financial resources to start their sites The cost of commercial database software was a barrier to some of the most creative web-based organizations being launched, including organizations like Google, Wikipedia, and Facebook Plus, the commercial database systems posed other problems for startups of that time First, they were too slow — they weren’t optimized for the Web and that was critical for organizations like these The commecial alternatives were also too difficult to use and manage, requiring higher paid developers Because of these factors, we were able to give fledgling organizations what they needed to become the significant components of the Internet and a major part of the lives of most people in the world today We were a critical component of the development of the Internet and we still are There’s nothing to indicate that we won’t continue to be so The growth of MySQL and especially of MariaDB is increasing It’s not decreasing as some people expected with the introduction of new databases systems and methods such as NoSQL MySQL became a dominant database system long ago Once something becomes dominant, it’s difficult to replace it Even if something better comes along, people prefer what’s already familiar to them and what they already know and are using For something www.it-ebooks.info to replace MySQL as the dominant open source database, it would have to be not only critically better, but also offer a way for people to migrate without much effort, and without wasting all of the knowledge they accumulated from their current system This is why MariaDB can replace MySQL: it’s basically the same thing, but with more features and more potential for the future www.it-ebooks.info www.it-ebooks.info Special Upgrade Offer If you purchased this ebook from a retailer other than O’Reilly, you can upgrade it for $4.99 at oreilly.com by clicking here www.it-ebooks.info www.it-ebooks.info Learning MySQL and MariaDB Russell J.T Dyer Editor Andy Oram Revision History 2015-03-23 First release Copyright © 2015 Russell Dyer O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://safaribooksonline.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com The O’Reilly logo is a registered trademark of O’Reilly Media, Inc Learning MySQL and MariaDB, the image of a banded angelfish, and related trade dress are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work Use of the information and instructions contained in this work is at your own risk If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights O’Reilly Media 1005 Gravenstein Highway North Sebastopol, CA 95472 2015-03-28T14:05:40-07:00 www.it-ebooks.info Learning MySQL and MariaDB Table of Contents Dedication Special Upgrade Offer Foreword Origins of MySQL State of MySQL and MariaDB Beyond the Server MariaDB: The Differences and Expectations The Future of MySQL and MariaDB Your Future in Learning MySQL and MariaDB Advice on Learning MySQL and MariaDB Preface Reading Strategy Text-Based Interface and Operating Systems Conventions Used in This Book Using Code Examples Safari® Books Online How to Contact Us Acknowledgments www.it-ebooks.info I The Software Introduction The Value of MySQL and MariaDB Mailing Lists and Forums Other Books and Other Publications Installing MySQL and MariaDB The Installation Packages Licensing Finding the Software Choosing a Distribution The _AMP Alternatives Linux Binary Distributions Mac OS X Distributions Windows Distributions FreeBSD and Sun Solaris Distributions Source Distributions Post-Installation Special Configuration Setting Initial Password for root More on Passwords and Removing Anonymous Users Creating a User The Basics and the mysql Client The mysql Client Connecting to the Server Starting to Explore Databases First SQL Commands Inserting and Manipulating Data A Little Complexity Summary Exercises www.it-ebooks.info II Database Structures Creating Databases and Tables Creating a Database Creating Tables Inserting Data More Perspectives on Tables Summary Exercises Altering Tables Prudence When Altering Tables Essential Changes Dynamic Columns Optional Changes Setting a Column’s Default Value Setting the Value of AUTO_INCREMENT Another Method to Alter and Create a Table Renaming a Table Reordering a Table Indexes Summary Exercises III Basics of Handling Data www.it-ebooks.info Inserting Data The Syntax Practical Examples The Table for Bird Orders The Table for Bird Families The Table for Birds Other Possibilities Inserting Emphatically Inserting Data from Another Table A Digression: Setting the Right ID Replacing Data Priorities When Inserting Data Lowering the priority of an insert Delaying an INSERT Raising the priority of an INSERT Summary Exercises Selecting Data Basic Selection Selecting by a Criteria Ordering Results Limiting Results Combining Tables Expressions and the Like Counting and Grouping Results Summary Exercises www.it-ebooks.info Updating and Deleting Data Updating Data Updating Specific Rows Limiting Updates Ordering to Make a Difference Updating Multiple Tables Handling Duplicates Deleting Data Deleting in Multiple Tables Summary Exercises Joining and Subquerying Data Unifying Results Joining Tables Selecting a Basic Join Updating Joined Tables Deleting Within Joined Tables Subqueries Scalar Subqueries Column Subqueries Row Subqueries Table Subqueries Performance Considerations with Subqueries Summary Exercises IV Built-In Functions www.it-ebooks.info 10 String Functions Formatting Strings Concatenating Strings Setting Case and Quotes Trimming and Padding Strings Extracting Text Searching Strings and Using Lengths Locating Text Within a String String Lengths Comparing and Searching Strings Replacing and Inserting into Strings Converting String Types Compressing Strings Summary Exercises 11 Date and Time Functions Date and Time Data Types Current Date and Time Extracting Date and Time Components Formatting Dates and Time Adjusting to Standards and Time Zones Adding and Subtracting Dates and Time Comparing Dates and Times Summary Exercises www.it-ebooks.info 12 Aggregate and Numeric Functions Aggregate Functions Counting Values Calculating a Group of Values Concatenating a Group Numeric Functions Rounding Numbers Rounding Only Down or Up Truncating Numbers Eliminating Negative Numbers Summary Exercises V Administration and Beyond 13 User Accounts and Privileges User Account Basics Restricting the Access of User Accounts Username and Host SQL Privileges Database Components and Privileges Restricting to specific databases Restricting to specific tables Restricting to specific columns Administrative User Accounts User Account for Making Backups User Account for Restoring Backups User Account for Bulk Importing User Account to Grant Privileges Revoking Privileges Deleting a User Account Changing Passwords and Names Setting a User Account Password Renaming a User Account User Roles Summary Exercises www.it-ebooks.info 14 Backing Up and Restoring Databases Making Backups Backing Up All Databases Understanding Dump Files Backing Up Specific Databases Creating Backup Scripts Backing Up Specific Tables Restoring Backups Restoring a Database Restoring a Table Modifying a dump file Restoring with a temporary database Using a limited user account Restoring Only Rows or Columns Recovering from a Binary Log Finding information in the binary log Extracting and executing information from the binary log Developing a Backup Policy Summary Exercises www.it-ebooks.info 15 Bulk Importing Data Preparing to Import Loading Data Basics Watching for Warnings Checking the Accuracy of the Import Selecting Imported Data Better Loading Mapping Fields Setting Columns More Field and Line Definitions Starting, Terminating, and Escaping Replacing Data Versus Ignoring Errors Importing from Outside MySQL Importing Local Files Using mysqlimport Importing Without FILE Privileges Bulk Exporting Data Summary Exercises www.it-ebooks.info 16 Application Programming Interfaces Creating API User Accounts C API Connecting to MySQL Querying MySQL Complete Minimal C API Program Compiling with C Includes Perl DBI Installing Connecting to MySQL Querying MySQL Selecting data Updating data A Full Example with Perl DBI More Information PHP API Installing and Configuring Connecting to MySQL Querying MySQL More Information Python Installing Connecting to MySQL Querying MySQL Sample Python Program More Information Ruby API Installing and Preparing MySQL/Ruby Connecting to MySQL Querying MySQL Sample MySQL/Ruby Program More Information SQL Injection Summary Exercises www.it-ebooks.info Index About the Author Colophon Special Upgrade Offer Copyright www.it-ebooks.info ... operating systems distributors, hardware makers, and software packagers are now shipping their products with MariaDB, either together with MySQL or without it Many websites that used MySQL software have switched to MariaDB It s easy to do, and for... Vice President of Services at MySQL, Inc., along with other former employees of MySQL, left Sun and Oracle and started SkySQL Ab, providing support, consulting, training, and other services related to MySQL and MariaDB software... Another key program, used extensively through this book, is the basic MySQL client, called simply, mysql With it, you can interact with the mysqld daemon, and thereby the databases It s a textual user interface There’s nothing fancy about it — a mouse is not