Considering the fact that more than 80% of the world's websites now run on MySQL, it could easily be argued that we accelerated the growth of the Internet, and almost. Because of these factors, we have been able to give young organizations what they need to become important components of the Internet and an important part of the lives of most people in today's world.
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
It is also useful for beginners who have only learned parts of MySQL and feel that there may be key aspects that are commonly used that they do not know, that they somehow missed or skipped over when they first learned it .
Reading Strategy
Text-Based Interface and Operating Systems
Conventions Used in This Book
Using Code Examples
Safari® Books Online
How to Contact Us
Acknowledgments
The Software
Introduction
The success of MySQL as a leading database is not only due to its price – after all, there are other free and open source databases available – but also its reliability, performance and features. MariaDB is fast becoming the replacement for MySQL, and is seen by many as the heir to the spirit of the MySQL community.
The Value of MySQL and MariaDB
Mailing Lists and Forums
Other Books and Other Publications
Installing MySQL and MariaDB
This chapter briefly explains the process of installing MySQL or MariaDB on Linux, Mac OS X, and Windows operating systems. You can install MySQL for any platform by reading just three sections of this chapter: the next section on choosing a distribution; the section that applies to the distribution you select; and After installation at the end of the chapter.
The Installation Packages
Licensing
Finding the Software
Look for the section related to your MySQL or MariaDB distribution (eg Mac OS X) and skip to the bottom of that section to see how to start the daemon. However, if you are unable to start the daemon, read the entire section for the distribution of your choice.
Choosing a Distribution
The _AMP Alternatives
Linux Binary Distributions
The naming scheme for these packages is generally MySQL-server-version.rpm, MySQL-client-version.rpm, and MySQL-shared-version.rpm, where version is the actual version number. To install .rpm files after downloading them to your server, you can use the rpm tool or something more comprehensive like yum.
Mac OS X Distributions
For Mac servers that don't have a GUI or desktop manager, or if you want to install it remotely, there are TAR files for installing MySQL.[3] Whether you are going to download a DMG file or a TAR file, make sure you download the package related to the type of processor on your server (e.g. 32-bit or 64-bit) and for the minimum version of the operating system from the server. (e.g. Mac OS X, version 10.6 or later). To install the MySQL package file, from the Finder desktop manager, double-click the disk image file (the DMG file) that you downloaded.
Windows Distributions
Just make sure you have the MySQL server and MySQL clients installed somewhere you can access them. In the Configuration section, you can also enter the password for the MySQL root user.
FreeBSD and Sun Solaris Distributions
The third line changes the ownership of the MySQL directories and programs to the file system user mysql. To start MySQL or MariaDB at boot time, copy the mysql.server file located in the /usr/local/mysql support files subdirectory to the /etc/init.d directory.
Source Distributions
The first line here changes the ownership of the MySQL libraries and programs to the file system user, mysql. To make MySQL or MariaDB start at startup, copy the mysql.server file located in the support files subfolder of /usr/local/mysql to the /etc/init.d folder.
Post-Installation
Special Configuration
Setting Initial Password for root
After entering this line, you will be prompted for the old password, which will initially be blank, so press the Enter key. Throughout this book, I will refer to this MySQL user by default when using the term root.
More on Passwords and Removing Anonymous Users
On the rare occasion that I need to refer to the root user of the operating system, I will explain this. After you finish changing the initial batch of users, you must flush user privileges for the new passwords to take effect.
Creating a User
The Basics and the mysql Client
There are alternative clients with graphical interfaces, but they are not as useful in the long run. However, they will always have the mysql client because it is installed with the MySQL server.
The mysql Client
Connecting to the Server
Until you either enter; or \g, the mysql client will not transfer what you entered to the MySQL server. This will clear everything you entered, even on previous lines, from the buffer of the mysql client and return you to the mysql> prompt.
Starting to Explore Databases
First SQL Commands
If you will be working primarily on one database (you usually will be), you can set the default database so that you don't have to specify the database each time. In these results you can see that we have created three data entry fields, called book_id.
Inserting and Manipulating Data
After you enter the USE command, you can reenter the previous SQL statement to display the tables in the database without specifying that you want to test. Let's enter another UPDATE statement so you can see how you can do more with just one statement.
A Little Complexity
Notice that we have provided the same syntax as before with the UPDATE statement, but we have specified two pairs of columns and values to set. In our examples here it doesn't matter because we're not entering much data, but small specs like this will make a huge performance difference in large databases.
Summary
Exercises
Try doing it based on the value of relation_id and then again based on the value of the relationship.
Database Structures
Creating Databases and Tables
The exercises at the end of this chapter require you to make some changes and additions to the database and its tables on your computer. The database and tables that we create in this chapter will be used in several chapters of this book, especially in Part III.
Creating a Database
This little command will set the new database that was just created as the default database for the mysql client. It will remain the default database until you change it to another or until you exit the client.
Creating Tables
In the first column of this result set, Field contains the fields or columns of the generated table. Be careful with this SQL statement as it is not reversible and deletes all data in the table.
Inserting Data
More Perspectives on Tables
Altering Tables
Despite the best planning, sometimes you will need to change the structure or other aspects of your tables. In this chapter, we'll explore the ways to modify tables: how to add and delete columns, how to change their data types, how to add indexes, and how to change table and column options.
Prudence When Altering Tables
We need to use the mysql client at the command line to restore a dump file. Note that to restore from the dump file, we use another redirect, the less-than sign (
Essential Changes
Note that the new column, wing_id, has been added to the end of the table. Note that the syntax for the MODIFY COLUMN clause lists the name of the column once.
Dynamic Columns
Based on this, we can change the values in the numbered list in the bird table to something easier to type (eg, LR-LC for lower risk - less concern) and then put the longest description in the reference table that we would create. However, it will be simpler to treat the endangered column like the other reference tables we have created (eg, birds_wing_shapes) and use numbers for the values in the birds table.
Optional Changes
Setting a Column’s Default Value
We decided earlier that we want to set the default value of this column to Lower Risk - Least Concern, or the status_id value for this combination of columns in the conservation_status table. However, if you wanted to set only the default value for a column, you could use the ALTER clause of the ALTER TABLE statement.
Setting the Value of AUTO_INCREMENT
Run the SHOW COLUMNS statement again on your computer to see that the default has been reset.
Another Method to Alter and Create a Table
AUTO_INCREMENT so that the bird table is sure that the rows in the new table have the correct identification numbers. It also copies the data from the two columns in the bird table to the.
Renaming a Table
The table with birds used to be the table with birds_new that we had modified in the test database. The other tables in the results set here are the tables we created earlier in this chapter.
Reordering a Table
As you can see, the data is already in alphabetical order based on the values in the . Let's use the ALTER TABLE statement with the ORDER BY clause to reorder the data in the table based on the country_code column.
Indexes
In the same SQL statement, using the CHANGE COLUMN expression, change the name of the column description to bird_description. When you are done, execute the SELECT statement to see all the values in the table.
Basics of Handling Data
Inserting Data
It is easier to learn the language of MySQL and MariaDB if you use the keywords to describe what you are doing. As you do the exercises, you may need to refer back to the examples in this chapter and in Chapter 4.
The Syntax
Practical Examples
The Table for Bird Orders
Before entering the order of birds, let's prime the order_id by setting first. This will set order_id to 100 for the first order that we enter into our bird_orders table.
The Table for Bird Families
This puts the NULL we intended for the family_id column and puts it in the letter_description column. If you do not include the WHERE clause, you will delete all the data in the table.
The Table for Birds
Now that we have the family_id for the shorebirds, let's look at the columns in the birds table and decide which ones to set. First, we tell MySQL to join the birds table to the bird_families table where the family_id from both tables is the same or matches.
Other Possibilities
Inserting Emphatically
Inserting Data from Another Table
I can take the family names, use the examples for a brief description, and use both to complete the data in the bird_families table. In the SELECT statement here, I added an ORDER BY clause to sort the results set by the family_id value.
A Digression: Setting the Right ID
First, it changes the bird_families table only where the order_id has not yet been set. SET bird_families.order_id = bird_orders.order_id WHERE bird_families.order_id IS NULL.
Replacing Data
I mention the communities because in the MySQL and MariaDB communities you can sometimes find tables with data like this that you can download for free and then manipulate for your own use, thus saving you a lot of work and getting out of the ever annoying tedium of database management. Also, in the previous examples, if the scientific_name column was not UNIQUE or otherwise a key column, new rows would be created for the three families we tried to replace with the REPLACE statement.
Priorities When Inserting Data
Selecting Data
In this chapter we will cover one main objective that makes the other worthwhile: retrieving the data stored in a database. Download rookery.sql to get the entire rookery database, with lots of data to use in our explorations.
Basic Selection
Selecting by a Criteria
Ordering Results
This is why the scientific_name column is needed and why the common_name column cannot be a key column in the table. We could have set up the table so that birds without common names had NULL in the common_name column, but we chose that.
Limiting Results
Combining Tables
So we need to change the selected column in the field list from bird_families.scientific_name to. To join the third table correctly, we had to add another evaluator to the WHERE clause: families.order_id.
Expressions and the Like
WHERE common_name REGEXP BINÆR 'Hawk' OG common_name NOT REGEXP 'Hawk-Owl' ORDER BY family_id LIMIT 10;. WHERE common_name REGEXP '[[:space:]]Hawk|[[.hyphen.]]Hawk' OG common_name NOT REGEXP 'Hawk-Owl|Hawk Owl'.
Counting and Grouping Results
Updating and Deleting Data
For those situations where you want to change or add pieces of data, you will mostly use the UPDATE statement. In cases where you want to delete an entire row of data, you will use the DELETE statement first.
Updating Data
Updating Specific Rows
Looking at the results, we can see that there is indeed only Rusty Osborne, and the value of her human_id is 3. We will use that value in the UPDATE statement to make sure we only update this one row. In the SET clause, we set the value of the formal_title column to a substring of the current value.
Limiting Updates
In this chapter we will work with a few string functions that are useful with UPDATE. Because we want to make sure that every member wins in the end, we enter a row i.
Ordering to Make a Difference
This is probably the better choice for maintaining the data, but we will use the simpler method of inserting an entry for each member in the prize winners. There is no reason why this id should be the same as the human_id column because we will use the human_id column when we need information from it.
Updating Multiple Tables
For this last part, we need to reset the values of the rows in the price_winners table based on the value of the country_id in the people table. UPDATE, we only update rows where the winner_date value is NULL.
Handling Duplicates
So we need to separate the conditions as we do here: in the WHERE clause of the. This will set the value of the possible_duplicate column to 1 where the names in the .
Deleting Data
Deleting in Multiple Tables
Joining and Subquerying Data
Most of the examples used so far in this book have intentionally involved one table per SQL statement to enable you to focus on the basic syntax of each SQL statement. This chapter covers how to join results from multiple SQL statements, how to join tables, and how to use subqueries to achieve similar results.
Unifying Results
AND families.order_id = orders.order_id AND orders.scientific_name = 'Pelecaniformes' GRUPPE EFTER families.family_id. AND families.order_id = orders.order_id AND orders.scientific_name = 'Suliformes' GRUPPE EFTER families.family_id;.
Joining Tables
Here we use the USING keyword in the JOIN clause to indicate the identical column to join. In the following subsections, we'll look at the methods for using JOIN with each of these three SQL statements, and look at some examples for each.
Selecting a Basic Join
This is because no value has been entered in the conservation_status_id column of the row associated with that bird species. Because of the LEFT join, the results show all birds with the word Egret in the common name, even if we don't know their conservation status.
Updating Joined Tables
We use the UPDATE statement to set the rows for the birds in Ardeidae to this new state, so we want to know the conservation_status_id. We could have removed the LEFT JOIN to the conservation_status table and then simply updated all the rows for the Ardeidae birds that have a NULL value in conservation_status_id.
Deleting Within Joined Tables
In this DELETE statement, we've only listed the prizewinners table in the FROM clause because that's the only one we want to delete rows from. So in the WHERE clause here, we use this as the condition to find the orphan rows in the prizewinners table.
Subqueries
In the following subsections, we will look at each of these types along with examples of them.
Scalar Subqueries
Instead, we select human_id and join_date (ie the date the member joined). GROUP BY clause, we group members based on human_id to get a count with.
Column Subqueries
In this example, the nested query is contained within the parentheses of the IN operator - the most nested query. Then we wrap it in another query, the outer query to GROUP BY the bird family.
Row Subqueries
This SQL statement selects the bird family name where the order name is Galliformes. We used the same alias to select that field in the outer query column list.
Performance Considerations with Subqueries
The GROUP BY clause tells MySQL to group the results based on the family field, which is the alias in the subquery for the. There must be two fields in the result set: one with the human_id with.