MariaDB Crash Course - Pearsoncmg

Transcription

MariaDBCrash CourseBen FortaUpper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks. Where thosedesignations appear in this book, and the publisher was aware of atrademark claim, the designations have been printed with initial capital letters or in all capitals.Editor-in-ChiefMark TaubThe author and publisher have taken care in the preparation ofthis book, but make no expressed or implied warranty of any kindand assume no responsibility for errors or omissions. No liability isassumed for incidental or consequential damages in connection withor arising out of the use of the information or programs containedherein.Managing EditorKristy HartThe publisher offers excellent discounts on this book when ordered inquantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to yourbusiness, training goals, marketing focus, and branding interests. Formore information, please contact:U.S. Corporate and Government Sales(800) 382-3419corpsales@pearsontechgroup.comProject EditorsElaine WileyJovana San NicolasShirleyCopy EditorGeneil BreezeIndexerErika MillenProofreaderLeslie JosephFor sales outside the United States, please contact:International Salesinternational@pearson.comVisit us on the Web: informit.com/awLibrary of Congress Cataloging-in-Publication DataForta, Ben.MariaDB crash course / Ben Forta.p. cm.Includes index.ISBN 978-0-321-79994-4 (pbk.)1. MariaDB. 2. Database management. 3. Client/server computing. I. Title.QA76.9.D3F663 2012004’.36--dc232011023506Copyright 2012 Pearson Education, Inc.All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtainedfrom the publisher prior to any prohibited reproduction, storage in aretrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtainpermission to use material from this work, please submit a writtenrequest to Pearson Education, Inc., Permissions Department, OneLake Street, Upper Saddle River, New Jersey 07458, or you may faxyour request to (201) 236-3290.ISBN-13: 978-0-321-79994-4ISBN-10: 0-321-79994-1Text printed in the United States on recycled paper at R.R. Donnelleyin Crawfordsville, Indiana.First printing September 2011Acquisitions EditorMark TaberPublishingCoordinatorVanessa EvansBook DesignerGary AdairCompositorGloria Schurick

This page intentionally left blank

Table of ContentsIntroduction1What Is MariaDB Crash Course? 1Who Is This Book For? 2Companion Web Site3Conventions Used in This Book31: Understanding SQL 5Database Basics 5What Is a Database? 6Tables 6Columns and Datatypes 7Rows 8NULL 8Primary Keys 9What Is SQL? 10Try It Yourself 11Summary 112:Introducing MariaDB 1313What Is MariaDB?Client-Server Software 14MySQL Compatibility 15MariaDB Tools 16mysql Command Line 16MySQL Workbench 17Summary 193:Working with MariaDB 21Making the Connection 21Selecting a Database22Learning About Databases and Tables 23Summary 264:Retrieving Data27The SELECT Statement27Retrieving Individual Columns 27Retrieving Multiple Columns 29Retrieving All Columns 30

ContentsRetrieving Distinct Rows31Limiting Results 32Using Fully Qualified Table Names 34Using Comments 35Summary 365:Sorting Retrieved Data3737Sorting DataSorting by Multiple Columns 39Specifying Sort Direction 40Summary 436:Filtering Data45Using the WHERE Clause45The WHERE Clause Operators46Checking Against a Single Value 47Checking for Nonmatches 48Checking for a Range of Values 49Checking for No Value 50Summary 517:Advanced Data Filtering53Combining WHERE Clauses53Using the AND Operator 53Using the OR Operator 54Understanding Order of Evaluation 55Using the IN Operator57Using the NOT Operator58Summary 598:Using Wildcard Filtering61Using the LIKE Operator61The Percent Sign (%) Wildcard 62The Underscore ( ) Wildcard 6465Tips for Using WildcardsSummary 659:Searching Using Regular ExpressionsUnderstanding Regular Expressions 67Using Regular Expressions 6867v

viContentsBasic Character Matching 68Performing OR Matches 70Matching One of Several Characters 71Matching Ranges 72Matching Special Characters 73Matching Character Classes 75Matching Multiple Instances 75Anchors 77Summary 7910:Creating Calculated Fields 81Understanding Calculated Fields 81Concatenating Fields 82Using Aliases 84Performing Mathematical Calculations 85Summary 8711:Using Data Manipulation FunctionsUnderstanding Functions 8989Using Functions 90Text Manipulation Functions 90Date and Time Manipulation Functions 92Numeric Manipulation Functions 96Summary 9612:Summarizing Data97Using Aggregate Functions 97The AVG() Function 98The COUNT() Function 99The MAX() Function 100The MIN() Function 101The SUM() Function 102Aggregates on Distinct Values 103Combining Aggregate Functions 104Summary 10513:Grouping Data107Understanding Data Grouping 107Creating Groups 108Filtering Groups 109

ContentsGrouping and Sorting 112SELECT Clause Ordering 113Summary 11414:Working with Subqueries 115Understanding Subqueries 115Filtering by Subquery 115Using Subqueries as Calculated Fields 119Summary 12215:Joining Tables123Understanding Joins 123Understanding Relational Tables 123Why Use Joins? 125Creating a Join 125The Importance of the WHERE Clause 127Inner Joins 129Joining Multiple Tables 130Summary 13216:Creating Advanced Joins 133Using Table Aliases 133Using Different Join Types134Self Joins 134Natural Joins 136Outer Joins 137Using Joins with Aggregate FunctionsUsing Joins and Join Conditions139140Summary 14017:Combining Queries141Understanding Combined Queries 141Creating Combined Queries 141Using UNION 142UNION Rules144Including or Eliminating Duplicate RowsSorting Combined Query ResultsSummary146145144vii

viii18:ContentsFull-Text Searching147Understanding Full-Text SearchingUsing Full-Text Searching147148Enabling Full-Text Searching SupportPerforming Full-Text Searches148149Using Query Expansion 152Boolean Text Searches 154Full-Text Search Usage Notes 158Summary 15919:Inserting Data 161Understanding Data Insertion 161Inserting Complete Rows 161Inserting Multiple Rows 165Inserting Retrieved Data166Summary 16820:Updating and Deleting DataUpdating Data 169Deleting Data169171Guidelines for Updating and Deleting DataSummary 17321:Creating and Manipulating TablesCreating Tables 175Basic Table Creation 176Working with NULL Values 177Primary Keys Revisited 179Using AUTO INCREMENT 180Specifying Default Values 181Engine Types 182Updating Tables 183Deleting Tables 185Renaming Tables 185Summary 186175172

Contents22:Using Views 187Understanding Views 187Why Use Views 188View Rules and Restrictions 188Using Views 189Using Views to Simplify Complex Joins 189Using Views to Reformat Retrieved Data 191Using Views to Filter Unwanted Data 192Using Views with Calculated Fields 193Updating Views 194Summary 19523:Working with Stored Procedures197Understanding Stored Procedures 197Why Use Stored Procedures 198Using Stored Procedures 199Executing Stored Procedures 199Creating Stored Procedures 200Dropping Stored Procedures 201Working with Parameters 202Building Intelligent Stored Procedures 205Inspecting Stored Procedures 208Summary 20824:Using Cursors209Understanding Cursors 209Working with Cursors 209Creating Cursors 210Opening and Closing Cursors 210Using Cursor Data 212Summary 21625:Using Triggers 217Understanding Triggers 217Creating Triggers 218Dropping Triggers 219ix

xContentsUsing Triggers 219INSERT Triggers 219DELETE Triggers 221UPDATE Triggers 223More on Triggers 223Summary 22426:Managing Transaction Processing225Understanding Transaction Processing 225Controlling Transactions 227Using ROLLBACK 227Using COMMIT 228Using Savepoints 229Changing the Default Commit Behavior 230Summary 23027:Globalization and Localization231Understanding Character Sets and Collation Sequences 231Working with Character Set and Collation Sequences 232Summary 23428:Managing Security235Understanding Access Control 235Managing Users 236Creating User Accounts 237Deleting User Accounts 238Setting Access Rights 238Changing Passwords 241Summary 24229:Database Maintenance243243Backing Up DataPerforming Database Maintenance 243Diagnosing Startup Problems 245Review Log Files 245Summary 24630:Improving Performance247Improving Performance 247Summary 249

ContentsA:Getting Started with MariaDB 251What You Need 251Obtaining the Software 252Installing the Software 252Preparing to Try It Yourself 253B:The Example Tables255Understanding the Sample Tables 255Table Descriptions 256Creating the Sample Tables259Using mysql 260Using MySQL Workbench 261C: MariaDB Datatypes 263String Datatypes 263Numeric Datatypes 265Date and Time Datatypes 266Binary Datatypes 266D: MariaDB Reserved Words 269Index275xi

ForewordAs the creator of MariaDB (and MySQL), I am thrilled to see the first MariaDBbook in print. I am equally thrilled that Ben Forta wrote it. Ben has a gift forpresenting complex topics (and really understanding SQL can be complex) inan easy-to-understand way. MariaDB Crash Course is an easy read and goesfrom explaining the basics to the very complex (including joins, regular expressions, and triggers) simply and without painful effort. I recommend this bookto anyone new to SQL who wants to quickly learn how to get the best out ofMariaDB.Michael “Monty” WideniusCreator of MariaDB and MySQL

AcknowledgmentsI’d like to thank the folks at Addison-Wesley for once again granting me theflexibility and freedom to build this book as I saw fit. Special thanks to MarkTaber for helping turn this one around in record time, and for his guidanceinto what this series is evolving into.Thanks to project editor Elaine Wiley for keeping the project moving and meon schedule, no easy task.Thanks to Monty Widenius, (creator of MariaDB and MySQL), DanielBartholomew, and Colin Charles for their thorough technical review andfeedback.And finally, this book was written in response to an unsolicited requestby Monty Widenius. Monty is the driving force behind some of the mostsuccessful database projects in history, and yet he still took the time to reviewthe manuscript, provide feedback, and write a much-appreciated foreword andrecommendation. Thank you for your time and support, Monty. I hope thistitle lives up to your expectations.

About the AuthorBen Forta is Adobe Systems’ Director of Developer Relations and has morethan 20 years experience in the computer industry in product development,support, training, and product marketing. Ben is the author of the best-sellingSams Teach Yourself SQL in 10 Minutes (now in its third edition, and translatedinto more than a dozen languages), spinoff titles on MySQL and SQL ServerT-SQL, ColdFusion Web Application Construction Kit and Advanced ColdFusionApplication Development (both published by Adobe Press), Sams Teach YourselfRegular Expressions in 10 Minutes, as well as books on Flash, Java, Windows,and other subjects. He has extensive experience in database design and development, has implemented databases for several highly successful commercialsoftware programs and Web sites, and is a frequent lecturer and columnist onInternet and database technologies. Ben lives in Oak Park, Michigan, with hiswife, Marcy, and their seven children. Ben welcomes your e-mail atben@forta.com and invites you to visit his Web site at http://forta.com/.

IntroductionMariaDB is an offshoot of MySQL, one of the most popular database managementsystems in the world. From small development projects to some of the best-knownand most prestigious sites on the Web, MySQL has proven itself to be a solid, reliable, fast, and trusted solution to all sorts of data storage needs.In 2008, MySQL was acquired by Sun Microsystems, which was in turnacquired by Oracle Corporation in 2010. While the initial acquisition by Sunwas hailed by many in the MySQL community as exactly what the projectneeded, that sentiment did not last, and the subsequent acquisition by Oraclewas unfortunately met with far lower expectations. Many of MySQL’s developers left Sun and Oracle to work on new projects. Among them was Michael“Monty” Widenius, creator of MySQL and one of the project’s longtime technical leads.Monty and his team created a fork (offshoot) of the MySQL codebase andnamed his new DBMS MariaDB. The stated goals for the new MariaDBDBMS include Create a DBMS that is so compatible with MySQL that it could beused as a drop-in replacement (you could uninstall MySQL, installMariaDB, and your programs should continue to run as is). This isaccomplished by building MariaDB on the MySQL codebase. Improve the source code to make MariaDB far more reliable andstable. Add features (and community contributions) at a faster rate. Develop a new underlying database engine (don’t worry if that soundsobscure for now) named Aria to improve performance and reliability.What Is MariaDB Crash Course?This book is based on my best-selling Sams Teach Yourself SQL in 10 Minutes.That book has become one of the most-used SQL tutorials in the world, withan emphasis on teaching what you really need to know—methodically, systematically, and simply. But as popular and as successful as that book is, it doeshave some limitations:

Introduction2 In covering all the major DBMSs, coverage of DBMS-specific featuresand functionality had to be kept to a minimum. To simplify the SQL taught, the lowest common denominator hadto be found—SQL statements that would (as much as possible) workwith all major DBMSs. This requirement necessitated that betterDBMS-specific solutions not be covered. Although basic SQL tends to be rather portable between DBMSs,more advanced SQL most definitely is not. As such, that book couldnot cover advanced topics, such as triggers, cursors, stored procedures,access control, transactions, and more, in any real detail.And that is where this book comes in. MariaDB Crash Course builds on theproven tutorials and structure of Sams Teach Yourself SQL in Ten Minutes, without getting bogged down with anything but MariaDB. Starting with simpledata retrieval and working on to more complex topics, including the use ofjoins, subqueries, regular expression and full text-based searches, stored procedures, cursors, triggers, table constraints, and much more. You learn whatyou need to know methodically, systematically, and simply—in highly focusedchapters designed to make you immediately and effortlessly productive.Who Is This Book For?This book is for you if You are new to SQL. You are just getting started with MariaDB and want to hit the groundrunning. You want to quickly learn how to get the most out of MariaDB. You want to learn how to use MariaDB in your own applicationdevelopment. You want to be productive quickly and easily using MariaDB withouthaving to call someone for help.It is worth noting that this book is not intended for all readers. If you are anexperienced SQL user, you may find the content in this book too elementary.Similarly, if you have existing MySQL experience, you’ll likely find this bookto be less useful (as noted, MariaDB is based on MySQL). If you own myMySQL Crash Course, I do not recommend that you buy this book, as much of

Conventions Used in This Book3the content is similar, and your existing MySQL knowledge will easily transferas is to MariaDB.But, if the preceding list describes you and your needs relative to MariaDB,you’ll find this MariaDB Crash Course to be the fastest and easiest way to get upto speed with MariaDB.This book is also useful if you are new to MySQL, as most of the content alsoapplies to that DBMS. For you, this book has an extra benefit in that it helpsdemonstrate some reasons to consider switching to MariaDB.Companion Web SiteThis book has a companion Web site online athttp://forta.com/books/0321799941/. Visit the site to access Table creation and population scripts used to create the example tablesused throughout this book The online support forum Online errata (should one be required) Other books that may be of interest to youConventions Used in This BookThis book uses different typefaces to differentiate between code and regularEnglish, and also to help you identify important concepts.Text that you type and text that should appear on your screen is presentedin monospace type. It looks like this to mimic the way textlooks on your screen.Placeholders for variables and expressions appear in monospace italicfont. You should replace the placeholder with the specific value it represents.This arrow ( ) at the beginning of a line of code means that a single line ofcode is too long to fit on the printed page. Continue typing all the charactersafter the as though they were part of the preceding line.

Introduction4NoteA Note presents interesting pieces of information related to the surrounding discussion.TipA Tip offers advice or teaches an easier way to do something.CautionA Caution advises you about potential problems and helps you steer clear of disaster.New TermProvides clear definitions of new, essential terms. InputThe Input icon identifies code that you can type in yourself. It usually appearsnext to a listing. OutputThe Output icon highlights the output produced by running MariaDB code. Itusually appears after a listing. AnalysisThe Analysis icon alerts you to the author’s line-by-line analysis of input oroutput.

3Working with MariaDBIn this chapter, you learn how to connect and log in to MariaDB, how to issueMariaDB SQL statements, and how to obtain information about databases andtables.Making the ConnectionNoteExample Tables Required From this point on, all chapters will use the exampledatabases and tables. If you have yet to install these, see Appendix B, “The ExampleTables,” before proceeding.Now that you have a MariaDB DBMS and client software to use with it, itwould be worthwhile to briefly discuss connecting to the database.MariaDB, like all client-server DBMSs, requires that you log in to the DBMSbefore being able to issue commands. Login names might not be the same asyour network login name (assuming that you are using a network); MariaDBmaintains its own list of users internally and associates rights with each.When you first installed MariaDB, you may have been prompted for anadministrative login (usually named root) and a password (if you weren’t, thenthe root user account was created with no password). If you are using yourown local server and are simply experimenting with MariaDB, using this loginis fine. In the real world, however, the administrative login is closely protected(as access to it grants full rights to create tables, drop entire databases, changelogins and passwords, and more).To connect to MariaDB you need the following pieces of information: The hostname (the name of the computer)—this is localhost ifconnecting to a local MariaDB server The port (if a port other than the default 3306 is used) A valid user name The user password (if required)

Chapter 322Working with MariaDBAs explained in Chapter 2, “Introducing MariaDB,” all this information can bepassed to the mysql command line utility, or entered into the server connection screen in MySQL Workbench.NoteUsing Other Clients If you are using a client other than the ones mentioned here, youstill need to provide this information to connect to MariaDB.After you are connected, you have access to whatever databases and tables yourlogin name has access to. (Logins, access control, and security are revisited inChapter 28, “Managing Security.”)Selecting a DatabaseWhen you first connect to MariaDB, you do not have any databases openfor use. Before you can perform any database operations, you need to select adatabase. To do this you use the USE keyword.New TermKeyword A reserved word that is part of the MariaDB SQL language. Never name atable or column using a keyword. Appendix D, “MariaDB Reserved Words,” lists theMariaDB keywords.For example, to use the crashcourse database you would enter thefollowing: InputUSE crashcourse; OutputDatabase changed AnalysisThe USE statement does not return any results. Depending on the client used,some form of notification might be displayed. For example, the Databasechanged message shown here is displayed by the mysql command line utilityupon successful database selection.TipPreselecting a Database If you are using the mysql command line tool, you can preselect a database by typing its name after mysql when running the tool.

Learning About Databases and Tables23Remember, you must always USE a database before you can access anydata in it.Learning About Databases and TablesBut what if you don’t know the names of the available databases? And for thatmatter, how are clients like MySQL Workbench able to display a list of available databases?Information about databases, tables, columns, users, privileges, and more isstored within databases and tables themselves (yes, MariaDB uses MariaDBto store this information). But these internal tables are generally not accesseddirectly. Instead, the MariaDB SHOW command can be used to display thisinformation (information that MariaDB then extracts from those internaltables). Look at the following example: InputSHOW DATABASES; Output -------------------- Database -------------------- information schema crashcourse mysql forta coldfusion flex test -------------------- AnalysisSHOW DATABASES; returns a list of available databases. Included in thislist might be databases used by MariaDB internally (such as mysql andinformation schema in this example). Of course, your own list of databasesmight not look like those shown here.To obtain a list of tables within a database, use SHOW TABLES;, as seen here: InputSHOW TABLES;

Chapter 324 Working with MariaDBOutput ----------------------- Tables in crashcourse ----------------------- customers orderitems orders products productnotes vendors ----------------------- AnalysisSHOW TABLES; returns a list of available tables in the currently selecteddatabase.To show a table’s columns, you can use DESCRIBE: InputDESCRIBE customers; Output -------------- ----------- ------ ----- --------- ---------------- Field Type Null Key Default Extra -------------- ----------- ------ ----- --------- ---------------- cust id int(11) NO PRI NULL auto increment cust name char(50) NO cust address char(50) YES NULL cust city char(50) YES NULL cust state char(5) YES NULL cust zip char(10) YES NULL cust country char(50) YES NULL cust contact char(50) YES NULL cust email char(255) YES NULL -------------- ----------- ------ ----- --------- ---------------- AnalysisDESCRIBE requires that a table name be specified (customers in this example), and returns a row for each field containing the field name, its datatype,whether NULL is allowed, key information, default value, and extra information(such as auto increment for field cust id).

Learning About Databases and Tables25NoteWhat Is Auto Increment? Some table columns need unique values. For example,order numbers, employee IDs, or (as in the example just seen) customer IDs. Ratherthan have to assign unique values manually each time a row is added (and havingto keep track of what value was last used), MariaDB can automatically assign thenext available number for you each time a row is added to a table. This functionality is known as auto increment. If it is needed, it must be part of the table definitionused when the table is created using the CREATE statement. We look at CREATE inChapter 21, “Creating and Manipulating Tables.”TipThe SHOW COLUMNS FROM Statement DESCRIBE is actually a shortcut for SHOWCOLUMNS FROM. In other words, the statement DESCRIBE customers;is functionally identical to the statement SHOW COLUMNS FROM customers;.Other SHOW statements are supported too, including SHOW STATUS—Used to display extensive server status information SHOW CREATE DATABASE and SHOW CREATE TABLE—Used todisplay the MariaDB statements used to create specified databases ortables respectively SHOW GRANTS—Used to display security rights granted to users (allusers or a specific user) SHOW ERRORS and SHOW WARNINGS—Used to display server error orwarning messagesIt is worthwhile to note that client applications use these same MariaDB SQLcommands as you’ve seen here. Applications that display interactive lists ofdatabases and tables, that allow for the interactive creation and editing of tables,that facilitate data entry and editing, or that allow for user account and rightsmanagement, and more, all accomplish what they do using the same MariaDBSQL commands that you can execute directly yourself.TipLearning More About SHOW In the mysql command line utility, execute commandHELP SHOW; to display a list of allowed SHOW statements.NoteWant Even More Information? MariaDB supports the use of INFORMATIONSCHEMA to obtain and filter even more schema details. Coverage of INFORMATIONSCHEMA is beyond the scope of this book. But, if you should need it, know that it’sthere for you.

26Chapter 3Working with MariaDBSummaryIn this chapter, you learned how to connect and log in to MariaDB; how toselect databases using USE; and how to introspect MariaDB databases, tables,and internals using SHOW and DESCRIBE. Armed with this knowledge, you cannow dig into the all-important SELECT statement.

IndexSymbolsaliases, 84-85, 133-134ALL argument, 103* (asterisk), 30alphabetical sort order, 40-43\ (backslash), 74ALTER TABLE statement, 183-185/* */ comment syntax, 36% (percent sign) wildcard, 62-63# (pound sign), 36ANALYZE TABLE statement, 244anchor metacharacters, 77anchors, 77-79; (semicolon), 28AND keyword, 50--(two hyphens), 35AND operator, 53-54(underscore) wildcard, 64Aapplication filtering, 46AS keyword, 84-85asterisk (*), 30Abs() function, 96auto increment, 25access control, 235-236AUTO INCREMENT, 180-181access rights, 238-241AVG() function, 98-99accounts. See user accountsBadvantages of MySQL, 13-14Against() function, 149-152backing up data, 243aggregate functionsbackslash (\), 74ALL argument, 103AVG(), 98-99combining, 104-105COUNT(), 99-100defined, 97DISTINCT argument, 103-104explained, 97joins and, 139-140MAX(), 100-101MIN(), 101-102naming aliases, 105SUM(), 102-103BACKUP TABLE statement, 243BETWEEN operator (WHERE clause), 49BINARY datatype, 266-267BIT datatype, 265boolean text searches, 154-158Ccalculated fieldsaliases, 84-85concatenating fields, 82-83explained, 81-82

276calculated fieldsmathematical calculations, 85-86subqueries as, 119-121views, 193-194calculated values, totaling, 102calling stored procedures, 199Cartesian products, 127case sensitivity, 28, 42changing passwords, 241-242character classes, matching, 75character matchinganchors, 77-79basic character matching, 68-70character classes, 75multiple instances, 75-77one of several characters, 71-72OR matches, 70ranges, 72-73special characters, 73-74character sets, 232-234checkingfor nonmatches, 48-49for NULL value, 50-51for range of values, 49-50against single value, 47CHECK TABLE statement, 244clauses. See also specific clausesdefinition of, 38positioning, 46, 51SELECT clause ordering, 113-114client-based results formatting, 82client-server software, 14-15multiple, sorting query results by,39-40NULL, 8, 177-178omitting, 164padded spacesRTrim() function, 83-84primary keys, 9-10retrievingall columns, 30individual columns, 27-28multiple columns, 29unknown columns, 31subquery result restrictions, 118updating multiple, 170values, deleting, 171viewing, 24combined queriescreating, 141-144duplicate rows and, 144-145explained, 141sorting results, 145-146combiningaggregate functions, 104-105WHERE clausesAND operator, 53-54OR operator, 54-55order of evaluation, 55-56comments, 35-36commits, 227default commit behavior, 230explicit commits, 228-229implicit commits, 228CLOSE statement, 211COMMIT statement, 228-229closing cursors, 211compatibility with MySQL, 15collation sequences, 232-234compound queries. See combined queriescolumns. See also fieldsconcatenating fields, 82-83aliases, 84-85derived, 85explained, 7-8fully qualified names, 126GROUP BY clause, 109Concat() function, 82conditional operators, 46correlated subqueries, 120Cos() function, 96

date and time datatypesCOUNT() function, 98-100, 139COUNT* subquery, 119-121create.sql script, 262CREATE FULLTEXT statement, 148-149CREATE PROCEDURE statement, 200-201CREATE TABLE statement, 175-177DEFAULT keyword, 181-182engine types, 182-183CREATE TRIGGER statement, 218CREATE USER statement, 237CREATE VIEW statement, 189-191currency datatypes, 266cursorsclosing, 211creating, 210explained, 209opening, 210-211retrieving data with, 212-216customers table, 257Ddatabreaking correctly (columns), 7deletingguidelines, 172-173TRUNCATE TABLEstatement, 172filtering. See data filteringgroupingexplained, 107filtering groups, 109-111GROUP BY clause, 108-109grouping and sorting, 112-113nested groups, 108updating, 172-173277databases. See also tablesexplained, 5-6maintenancebacking up data, 243diagnosing startup problems, 245performing, 243-244reviewing log files, 245-246schemas, 7selecting, 22viewing available databases, 23database servers, 14data filteringgroups, 109-111by subqueries, 115-118WHERE clause, 45-46checking against single value, 47checking for nonmatches, 48-49checking for NULL value, 50-51checking for range of values,49-50combining clauses, 53-56conditional operators, 46IN operator, 57-58NOT operator, 58-59wildcard filteringLIKE operator, 61% (percent sign) wildcard, 62-63tips, 65(underscore) wildcard, 64with views, 192datatypes, 8binary, 266-267currency, 266date and time, 266numeric, 265-266string, 263-264usefuln

11: Using Data Manipulation Functions 89 Understanding Functions 89 Using Functions 90 Text Manipulation Functions 90 Date and Time Manipulation Functions 92 Numeric Manipulation Functions 96 Summary 96 12: Summarizing Data 97 Using Aggregate Functions 97 The AVG() Function 98 The COUNT() Function 99 The MAX() Function 100 The MIN() Function 101