100% found this document useful (2 votes)
15 views

PDF Beginning MySQL 1st Edition Robert Sheldon download

The document provides information on downloading the book 'Beginning MySQL' by Robert Sheldon and Geoff Moes, along with links to additional ebooks. It includes details about the book's content, authors, and publication information. The book covers topics such as installing MySQL, working with databases, and SQL programming.

Uploaded by

nasbycoiratu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
15 views

PDF Beginning MySQL 1st Edition Robert Sheldon download

The document provides information on downloading the book 'Beginning MySQL' by Robert Sheldon and Geoff Moes, along with links to additional ebooks. It includes details about the book's content, authors, and publication information. The book covers topics such as installing MySQL, working with databases, and SQL programming.

Uploaded by

nasbycoiratu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Visit https://ebookultra.

com to download the full version and


explore more ebooks

Beginning MySQL 1st Edition Robert Sheldon

_____ Click the link below to download _____


https://ebookultra.com/download/beginning-mysql-1st-
edition-robert-sheldon/

Explore and download more ebooks at ebookultra.com


Here are some suggested products you might be interested in.
Click the link to download

Beginning Silverlight 3 1st Edition Robert Lair

https://ebookultra.com/download/beginning-silverlight-3-1st-edition-
robert-lair/

Beginning iOS 3D Unreal Games Development 1st Edition


Robert Chin

https://ebookultra.com/download/beginning-ios-3d-unreal-games-
development-1st-edition-robert-chin/

Algebra and Trigonometry 1st Edition Sheldon Axler

https://ebookultra.com/download/algebra-and-trigonometry-1st-edition-
sheldon-axler/

Learning MySQL First Edition Williams

https://ebookultra.com/download/learning-mysql-first-edition-williams/
MySQL 4th Edition Paul Dubois

https://ebookultra.com/download/mysql-4th-edition-paul-dubois/

Master of the Game Sidney Sheldon

https://ebookultra.com/download/master-of-the-game-sidney-sheldon/

Head First PHP MySQL 1st Edition Lynn Beighley

https://ebookultra.com/download/head-first-php-mysql-1st-edition-lynn-
beighley/

High Availability MySQL Cookbook 1st Edition Alex Davies

https://ebookultra.com/download/high-availability-mysql-cookbook-1st-
edition-alex-davies/

Oculomotor Systems and Perception 1st Edition Sheldon M.


Ebenholtz

https://ebookultra.com/download/oculomotor-systems-and-perception-1st-
edition-sheldon-m-ebenholtz/
Beginning MySQL 1st Edition Robert Sheldon Digital
Instant Download
Author(s): Robert Sheldon, Geoff Moes
ISBN(s): 9780764579509, 0764579509
Edition: 1
File Details: PDF, 11.98 MB
Year: 2005
Language: english
Beginning MySQL®

Robert Sheldon and Geoff Moes

TEAM LinG - Live, Informative, Non-cost and Genuine !


Beginning MySQL®
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 0-7645-7950-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/RW/QT/QV/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any
means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections
107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or
authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood
Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be
addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)
572-3447, fax (317) 572-4355, e-mail: brandreview@wiley.com.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO
REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE
CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT
LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED
OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED
HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE
UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE
AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION
OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF
FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE
INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY
MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY
HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services or to obtain technical support, please contact our
Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317)
572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be
available in electronic books.
Library of Congress Cataloging-in-Publication Data
Sheldon, Robert, 1955-
Beginning MySQL / Robert Sheldon and Geoff Moes.
p. cm.
Includes bibliographical references and indexes.
ISBN 0-7645-7950-9 (paper/website : alk. paper)
1. SQL (Computer program language) 2. MySQL (Electronic resource) I. Moes, Geoff, 1963- II. Title.
QA76.3.S67S54 2005
005.75'65--dc22
2004031058
Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trademarks of
John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without
written permission. MySQL is a registered trademark of MySQL AB Limited Company. All other trademarks are
the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
TEAM LinG - Live, Informative, Non-cost and Genuine !
About the Authors

Robert Sheldon
Robert Sheldon’s MySQL programming is rooted in ten years of experience working with SQL, as it is
implemented not only in a MySQL environment, but also within SQL Server, Microsoft Access, and Oracle
environments. He has programmed with SQL directly through database interfaces and script files and
indirectly through PHP, JSP, ASP, and ASP.NET applications that connected to various databases
and issued SQL statements. Robert has also managed the maintenance and development of Web sites and
online tools, which has included performing project analysis, developing functional specifications,
and managing database and Web development. He has designed and implemented various Microsoft
Access, SQL Server, and MySQL databases, as well as developed and implemented a variety of Web-based
solutions. In all these roles, he has had to perform numerous types of ad hoc queries and modifications,
build databases, create and modify database objects, create and review embedded statements, and
troubleshoot system- and data-related problems.

In addition to having a technical and SQL background, Robert has written or co-written nine books on
various network and server technologies, including two that have focused on SQL Server design and
implementation, one on SQL programming (based on the SQL:1999 standard), and one on Microsoft
Office Access 2003. The books that Robert has written contain training material that is designed to teach
users specific skills and to test their knowledge of the material covered. Having contracted as the senior
developmental editor for the Microsoft certification team, he brought to these books his experience devel-
oping exam items that helped to focus readers on the skills necessary to perform specific tasks. Robert
has also written and edited a variety of other documentation related to SQL databases and other computer
technologies. He works as an independent technical consultant and writer in the Seattle area.

Geoff Moes
Geoff Moes is a software architect and developer who has designed and implemented databases in
MySQL as well as having designed and implemented software systems in PHP, Java/J2EE, and ASP.NET
that have utilized MySQL databases through various database connectivity interfaces. Geoff received his
bachelor’s degree in Computer Science from Virginia Tech and has worked in the software industry for
18 years. He specializes in software and database architecture and development as it relates to Web-
based systems. He has worked with several database products in addition to MySQL, including SQL
Server, DB2, and Oracle. He has also developed a variety of software applications that have connected to
various databases using several different languages and platforms including Java J2EE/JDBC/EJB,
C++/ODBC, and ASP.NET/ODBC/OLEDB.

Geoff’s publishing credits include “Passing Arrays Between Jscript and C++” (September 7, 2000,
ASPToday.com, under WROX) and three articles published in Windows & .NET Magazine (online):
“Common Internet Hacker Attacks” (December 1, 1998), “Remote Web Administration, Part 2”
(November 1, 1998), and “Remote Web Administration, Part 1” (October 1, 1998). Geoff works as an
independent software consultant in the Washington D.C. metro area. When he is not in front of the
keyboard, he enjoys photography, mountain biking, hiking, and international travel.

TEAM LinG - Live, Informative, Non-cost and Genuine !


Credits
Acquisitions Editor Vice President and Publisher
Debra Williams Cauley Joseph B. Wikert

Development Editor Project Coordinator


Brian Herrmann Erin Smith

Technical Editor Quality Control Technician


David Mercer Brian H. Walls

Copy Editor Text Design and Composition


Nancy Hannigan Wiley Composition Services

Editorial Manager Proofreading and Indexing


Mary Beth Wakefield TECHBOOKS Production Services

Vice President & Executive Group Publisher


Richard Swadley

Acknowledgments

As with any publication, too many people were involved in the development of Beginning MySQL to
name them all, but we would like to acknowledge those who we worked with the closest in order to
complete this project in a timely manner (and with our sanity still somewhat intact). Our special thanks
goes to Debra Williams-Cauley, the acquisitions editor at John Wiley & Sons, Inc., who pulled this project
together in such a professional and responsive manner. And we particularly want to thank Brian Herrmann,
the development editor on this book who patiently and efficiently (and pleasantly, we might add) kept
this project moving forward, while always paying attention to details and answering our never-ending
stream of questions. We also want to acknowledge David Mercer, the technical editor, for his grasp of the
subject matter and his invaluable input into the book. In addition, we want to acknowledge all the edi-
tors, proofreaders, indexers, designers, illustrators, and other participants whose efforts made this book
possible. Finally, we want to thank our agent, Margot Maley Hutchison, at Waterside Productions, Inc.,
for her help in moving forward on this project and for tending to all the details.

TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents

Acknowledgments v
Introduction xxv

Chapter 1: Introducing the MySQL Relational Database Management System 1


Databases and Database Management Systems 2
What Is a Database? 2
The Hierarchical Model 3
The Network Model 5
The Relational Model 6
Database Management Systems 7
The MySQL RDBMS 8
The Open-Source Movement 9
The SQL Framework 9
What is SQL? 10
A Brief History of SQL 11
The Nonprocedural Nature of SQL 14
SQL Statements 14
Types of Execution 26
Implementation-Specific SQL 31
Data-Driven Applications 32
The Application Server 32
Connecting to a MySQL Database 33
Creating a Data-Driven Application 35
Summary 40
Exercises 42

Chapter 2: Installing MySQL 43


Getting Started 43
Making the Preliminary Decisions 44
Selecting a Version of MySQL 44
Selecting a Platform to Run MySQL 44
Selecting a MySQL Distribution Type 45
Selecting an Edition of MySQL 46
Downloading Distribution Files 46

TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents
Installing MySQL 48
Using RPM Files to Install MySQL on Linux 49
Using a Tar File to Install MySQL on Linux 51
Creating the User and Group Accounts 51
Copying the Tar File 52
Unpacking the Distribution File 53
Initializing the Installation 54
Starting the MySQL Server 55
Installing MySQL on Windows 57
Running the Installation Program 57
Configuring the MySQL Server 61
Editions of the MySQL Server 64
Testing Your MySQL Installation 65
Verifying Your Linux Installation 65
Verifying Your Windows Installation 68
Summary 70
Exercises 71

Chapter 3: Working with MySQL 73


Understanding the MySQL Directory Structure 73
MySQL File Storage 74
File Storage for a Linux RPM Installation 74
File Storage for a Linux Tar Installation 75
File Storage for a Windows Installation 76
The Data Directory 77
The mysql Database 78
The Grant Tables 79
Using the MySQL Programs 83
Specifying Program Options 83
Specifying Options at a Command Prompt 83
Specifying Options in a Configuration File 85
Server-Related Programs, Scripts, and Library Files 88
Client Programs 89
The mysql Utility 90
Using mysql in Interactive Mode 90
Using mysql in Batch Mode 97
Assigning Account Passwords 100
Setting Up a Configuration File 103
Summary 106
Exercises 107

vi TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents

Chapter 4: Designing a Relational Database 109


The Relational Model 109
Data Normalization 111
First Normal Form 111
Second Normal Form 113
Third Normal Form 115
Relationships 116
One-to-One Relationships 117
One-to-Many Relationships 117
Many-to-Many Relationships 119
Creating a Data Model 119
Identifying Entities 122
Normalizing Data 124
Identifying Relationships 125
Refining the Data Model 126
Designing the DVDRentals Database 127
Summary 136
Exercises 137

Chapter 5: Managing Databases, Tables, and Indexes 139


Managing Databases 139
Creating Databases 140
Modifying Databases 142
Deleting Databases 142
Managing Tables 142
Creating Tables 143
Creating Column Definitions 144
Defining a Column’s Nullability 152
Defining Default Values 153
Defining Primary Keys 154
Defining Auto-Increment Columns 155
Defining Foreign Keys 156
Defining Table Types 158
Creating Tables in the DVDRentals Database 160
Modifying Tables 167
Deleting Tables 169
Managing Indexes 171
Index Types 171
Creating Indexes 172
Defining Indexes When Creating Tables 172
Adding Indexes to Existing Tables 175
Removing Indexes 179

TEAM LinG - Live, Informative, Non-cost and Genuine ! vii


Contents
Retrieving Information About Database Objects 179
Using SHOW Statements 180
Using Database-Related SHOW Statements 180
Using Table-Related SHOW Statements 181
Using DESCRIBE Statements 183
Summary 187
Exercises 188

Chapter 6: Manipulating Data in a MySQL Database 189


Inserting Data in a MySQL Database 189
Using an INSERT Statement to Add Data 190
Using the <values option> Alternative of the INSERT Statement 191
Using the <values option> Alternative to Insert Data in the DVDRentals Database 195
Using the <set option> Alternative of the INSERT Statement 203
Using a REPLACE Statement to Add Data 205
Using the <values option> Alternative of the REPLACE Statement 206
Using the <set option> Alternative of the REPLACE Statement 208
Updating Data in a MySQL Database 210
Using an UPDATE Statement to Update a Single Table 211
Using an UPDATE Statement to Update Joined Tables 216
Deleting Data from a MySQL Database 219
Using a DELETE Statement to Delete Data 219
Deleting Data from a Single Table 220
Deleting Data from Joined Tables 222
Using a TRUNCATE Statement to Delete Data 226
Summary 227
Exercises 227

Chapter 7: Retrieving Data from a MySQL Database 229


The SELECT Statement 230
Using Expressions in a SELECT Statement 238
Using Variables in a SELECT Statement 241
Using a SELECT Statement to Display Values 243
The SELECT Statement Options 245
The Optional Clauses of a SELECT Statement 249
The WHERE Clause 250
The GROUP BY Clause 254
The HAVING Clause 259
The ORDER BY Clause 261
The LIMIT Clause 265
Summary 267
Exercises 268

viii TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents

Chapter 8: Using Operators in Your SQL Statements 269


Creating MySQL Expressions 269
Operator Precedence 270
Grouping Operators 271
Using Operators in Expressions 272
Arithmetic Operators 272
Comparison Operators 277
Logical Operators 291
Bitwise Operators 296
Sort Operators 302
Summary 306
Exercises 306

Chapter 9: Using Functions in Your SQL Statements 309


Comparing and Converting Data 310
Comparison Functions 310
GREATEST() and LEAST() Functions 310
COALESCE() and ISNULL() Functions 311
INTERVAL() and STRCMP() Functions 312
Control Flow Functions 314
IF() Function 314
IFNULL() and NULLIF() Functions 315
CASE() Function 316
Cast Functions 320
Managing Different Types of Data 322
String Functions 323
ASCII() and ORD() Functions 323
CHAR_LENGTH(), CHARACTER_LENGTH(), and LENGTH() Functions 323
CHARSET() and COLLATION() Functions 324
CONCAT() and CONCAT_WS() Functions 325
INSTR() and LOCATE() Functions 325
LCASE(), LOWER(), UCASE(), and UPPER() Functions 326
LEFT() and RIGHT() Functions 327
REPEAT() and REVERSE() Functions 327
SUBSTRING() Function 328
Numeric Functions 333
CEIL(), CEILING(), and FLOOR() Functions 333
COT() Functions 333
MOD() Function 334
PI() Function 334
POW() and POWER() Functions 334
ROUND() and TRUNCATE() Functions 334
SQRT() Function 335

TEAM LinG - Live, Informative, Non-cost and Genuine ! ix


Contents
Date/Time Functions 339
ADDDATE(), DATE_ADD(), SUBDATE(), DATE_SUB(), and EXTRACT() Functions 339
CURDATE(), CURRENT_DATE(), CURTIME(), CURRENT_TIME(), CURRENT_TIMESTAMP(),
and NOW() Functions 341
DATE(), MONTH(), MONTHNAME(), and YEAR() Functions 342
DATEDIFF() and TIMEDIFF() Functions 344
DAY(), DAYOFMONTH(), DAYNAME(), DAYOFWEEK(), and DAYOFYEAR() Functions 344
SECOND(), MINUTE(), HOUR(), and TIME() Functions 345
Summarizing Data 349
Summary Functions 350
AVG() Function 350
SUM() Function 351
MIN() and MAX() Functions 352
COUNT() Function 353
Bit Functions 354
Performing System Operations 358
Encryption Functions 358
ENCODE() and DECODE() Functions 358
PASSWORD(), MD5(), SHA(), and SHA1() Functions 359
System-Related Functions 361
CURRENT_USER(), SESSION_USER(), SYSTEM_USER(), and USER() Functions 361
CONNECTION_ID(), DATABASE(), and VERSION() Functions 361
INET_ATON() and INET_NTOA() Functions 362
Query and Insert Functions 362
FOUND_ROWS() Function 362
LAST_INSERT_ID() Function 363
Summary 366
Exercises 366

Chapter 10: Accessing Data in Multiple Tables 369


Creating Joins in Your SQL Statements 369
Joining Tables in a SELECT Statement 370
Creating Full Joins 373
Creating Outer Joins 385
Creating Natural Joins 391
Joining Tables in an UPDATE Statement 393
Joining Tables in a DELETE Statement 394
Creating Subqueries in Your SQL Statements 396
Adding Subqueries to Your SELECT Statements 396
Working with Comparison Operators 396
Working with Subquery Operators 399
Working with Grouped Data 403

x TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents
Adding Subqueries to Your UPDATE Statements 410
Adding Subqueries to Your DELETE Statements 411
Creating Unions That Join SELECT Statements 414
Summary 417
Exercises 418

Chapter 11: Exporting, Copying, and Importing Data 421


Exporting Data Out of a Table 421
Exporting Data to an Out File 423
Exporting Data to a Dump File 430
Copying Data into a Table 431
Copying Data into a New Table 432
Copying Data into an Existing Table 435
Using the INSERT Statement to Copy Data 435
Using the REPLACE Statement to Copy Data 436
Importing Data into a Table 438
Using the mysql Utility to Import Data 438
Using the LOAD DATA Statement to Import Data 438
Using the source Command to Import Data 444
Using the mysql Command to Import Data 446
Using the mysqlimport Utility to Import Data 449
Summary 452
Exercises 453

Chapter 12: Managing Transactions 455


Introducing Transactions 455
Performing a Transaction 457
Performing a Basic Transaction 457
The START TRANSACTION Statement 458
The COMMIT Statement 458
The ROLLBACK Statement 459
Statements That Automatically Commit Transactions 460
Adding Savepoints to Your Transaction 463
The SAVEPOINT Statement 464
The ROLLBACK TO SAVEPOINT Statement 465
Setting the Autocommit Mode and Transaction Isolation Level 468
Setting the Autocommit Mode 468
Setting the Transaction Isolation Level 472
Data Anomalies in a Transaction 472
Transaction Isolation Levels 475
Using the SET TRANSACTION Statement 476

TEAM LinG - Live, Informative, Non-cost and Genuine ! xi


Contents
Locking Nontransactional Tables 479
The LOCK TABLES Statement 480
The UNLOCK TABLES Statement 480
Summary 483
Exercises 483

Chapter 13: Administering MySQL 485


Performing Administrative Tasks 485
Managing System Variables 494
Retrieving System Variable Settings 495
Using the SHOW VARIABLES Statement to Retrieve Server System Variable Settings 495
Using the SELECT Statement to Retrieve Dynamic System Variable Settings 497
Using the SHOW STATUS Statement to Retrieve Server Status Variable Settings 498
Modifying the Server Configuration 502
Specifying System Settings at the Command Line 502
Specifying System Settings in an Option File 503
Specifying System Settings at Runtime 503
Managing Log Files 506
Working with Error Log Files 506
Enabling Query and Binary Logging 507
Setting Up Query Logging 507
Setting Up Binary Logging 507
Summary 515
Exercises 516

Chapter 14: Managing MySQL Security 517


The Access Privilege System 517
MySQL Grant Tables 518
The user Table 518
The db Table 520
The host Table 521
The tables_priv Table 522
The columns_priv Table 523
MySQL Privileges 524
MySQL Access Control 527
Authenticating Connections 527
Verifying Privileges 529
Managing MySQL User Accounts 533
Adding Users and Granting Privileges 533
Using the GRANT Statement 533
Using the SHOW GRANTS Statement 545

xii TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents
Setting Passwords for MySQL User Accounts 551
Using the SET PASSWORD Statement 551
Using the FLUSH PRIVILEGES Statement 551
Dropping Users and Revoking Privileges 553
Using the REVOKE Statement 553
Using the DROP USER Statement 555
Summary 558
Exercises 559

Chapter 15: Optimizing Performance 561


Optimizing MySQL Indexing 561
Optimizing SQL Queries 565
Optimizing Data Retrieval 566
Using the EXPLAIN Statement 566
Using the OPTIMIZE TABLE Statement 571
Understanding the SELECT Statement Guidelines 573
Optimizing Data Insertion 577
Optimizing Data Modification and Deletion 578
Optimizing MySQL Tables 579
Optimizing Your System’s Cache 580
Summary 584
Exercises 584

Chapter 16: Managing Backup, Recovery, and Replication 587


Backing Up Your Database 588
Backing Up a Single Database 588
Backing Up the Entire Database 588
Backing Up Individual Tables 594
Backing Up Multiple Databases 594
Backing Up Specific Databases 595
Backing Up All Databases 595
Restoring Your Database 599
Reloading Your Database 600
Using the mysql Client Utility in Batch Mode to Reload Your Database 600
Using the mysql Client Utility in Interactive Mode to Reload Your Database 600
Updating the Restored Database from Binary Log Files 601
Restoring Data Directly from a Binary Log 601
Restoring Binary Log Data from a Text File 602
Enabling and Disabling Binary Logging 603
Replicating Your Database 606
Implementing Replication 608

TEAM LinG - Live, Informative, Non-cost and Genuine ! xiii


Contents
Managing Replication 610
Managing the Master Server 611
Managing the Slave Server 612
Summary 615
Exercises 616

Chapter 17: Connecting to MySQL from a PHP Application 617


Introduction to PHP 618
Building a Data-Driven PHP Application 619
Connecting to a MySQL Database 619
Retrieving Data from a MySQL Database 621
Processing the Result Set 622
Manipulating Data in PHP 623
Converting Date Values 625
Working with HTML Forms 626
Redirecting Browsers 627
Working with Include Files 627
Creating a Basic PHP Application 628
Inserting and Updating Data in a MySQL Database 639
Adding Insert and Update Functionality to Your Application 640
Deleting Data from a MySQL Database 660
Summary 664
Exercises 665

Chapter 18: Connecting to MySQL from a Java/J2EE Application 667


Introduction to Java/J2EE 667
Building a Java/J2EE Web Application 669
Importing Java Classes 669
Declaring and Initializing Variables 670
Connecting to a MySQL Database 671
Retrieving Data from a MySQL Database 672
Processing the Result Set 673
Manipulating String Data 674
Converting Values 675
Working with HTML Forms 677
Redirecting Browsers 678
Including JSP Files 678
Managing Exceptions 679
Creating a Basic Java/J2EE Web Application 679
Inserting and Updating Data in a MySQL Database 692
Adding Insert and Update Functionality to Your Application 693
Deleting Data from a MySQL Database 716

xiv TEAM LinG - Live, Informative, Non-cost and Genuine !


Contents
Summary 721
Exercises 721

Chapter 19: Connecting to MySQL from an ASP.NET/C# Application 723


Introduction to ASP.NET/C# 724
Building an ASP.NET/C# Application 725
Setting up the ASP.NET Web Page 725
Declaring and Initializing Variables 725
Connecting to a MySQL Database 727
Retrieving Data from a MySQL Database 728
Processing the Result Set 729
Manipulating String Data 730
Converting Values 731
Working with HTML Forms 732
Redirecting Browsers 733
Including ASP.NET Files 733
Managing Exceptions 734
Creating a Basic ASP.NET/C# Application 735
Inserting and Updating Data in a MySQL Database 748
Adding Insert and Update Functionality to Your Application 750
Deleting Data from a MySQL Database 773
Summary 777
Exercises 778

Appendix A: Exercise Answers 781


Chapter 1 781
Exercises Solutions 781
Chapter 2 782
Exercises Solutions 782
Chapter 3 782
Exercises Solutions 782
Chapter 4 783
Exercises Solutions 783
Chapter 5 784
Exercises Solutions 784
Chapter 6 785
Exercises Solutions 785
Chapter 7 786
Exercises Solutions 786
Chapter 8 787
Exercises Solutions 787

TEAM LinG - Live, Informative, Non-cost and Genuine ! xv


Contents
Chapter 9 788
Exercises Solutions 788
Chapter 10 789
Exercises Solutions 789
Chapter 11 790
Exercises Solutions 790
Chapter 12 791
Exercises Solutions 791
Chapter 13 792
Exercises Solutions 792
Chapter 14 793
Exercises Solutions 793
Chapter 15 794
Exercises Solutions 794
Chapter 16 795
Exercises Solutions 795
Chapter 17 797
Exercises Solutions 797
Chapter 18 798
Exercises Solutions 798
Chapter 19 799
Exercises Solutions 799

Appendix B: MySQL APIs 801

Appendix C: MySQL 5 805


Stored Procedures 806
Triggers 807
Views 808

Index 811

xvi TEAM LinG - Live, Informative, Non-cost and Genuine !


Introduction

Welcome to Beginning MySQL, the definitive resource for anyone new to the MySQL database manage-
ment system. As the most popular open source database system in the world, MySQL has gained not only
recognition among its peers but a place of prominence in the worldwide technical industry, ensuring an
ever-growing need for information and training on how to implement a MySQL database and access and
manage data in that database.

Because of its ease of implementation, low overhead, reliability, and lower Total Cost of Ownership (TCO),
MySQL has made remarkable inroads in the database management system market. As a result, the number
of programmers who must connect to a MySQL database and embed SQL statements in their applications
is growing steadily. There are now over five million MySQL installations worldwide, and that number is
increasing rapidly. In addition, MySQL supports connectivity to numerous application languages and envi-
ronments, including C, C++, PHP, ASP, ASP.NET, Java, Perl, C#, and Python, and it can be implemented on
a number of platforms, including Windows, Linux, Unix, Solaris, FreeBSD, Mac OS, and HP-UX.

Corporate implementations continue to grow and include such companies as Yahoo!, Cox Communications,
Google, Cisco, Texas Instruments, UPS, Sabre Holdings, HP, and the Associated Press. Even NASA and the
U.S. Census Bureau have implemented MySQL solutions. MySQL has been proven to work in large deploy-
ments, while reducing system downtimes and administrative overhead and lowering hardware expendi-
tures and licensing costs.

As organizations continue to seek ways to cut their TCO, MySQL will continue to gain in popularity—
and its user-base will continue to grow. As a result, MySQL will gain further ground in becoming a
prominent force in the industry. To meet this demand, Beginning MySQL provides you with a valuable
resource and step-by-step learning tool that supplies you with the background information, examples,
and hands-on exercises that you need to implement MySQL and manage data in its databases. Concepts
are introduced in a logical manner, with each chapter building on the previous chapters. By the end of
this book, you’ll have a complete foundation in MySQL, its implementation, and the methods necessary
to connect to databases and manipulate data.

Who This Book Is For


Before beginning any book that covers a computer technology such as MySQL, it’s always useful to
know who the book is intended for, what assumptions are made about your level of knowledge, and
what system setup—if any—is required to perform the exercises in the book. Beginning MySQL is no
exception. So before you delve into the book too deeply, take a closer look at each of these issues.

Because MySQL is such a robust, flexible, and easy-to-implement application, a beginner’s book about
the product will benefit a wide audience, both at home and at the office. The primary audience for
Beginning MySQL can be any of the following readers:

❑ Experienced PHP, Java, or ASP.NET programmers who are developing applications that access
backend databases and who are new to MySQL

TEAM LinG - Live, Informative, Non-cost and Genuine !


Introduction
❑ Experienced application programmers in any language who are new to MySQL and who want
to better understand how to implement a MySQL database and use SQL as it is implemented in
MySQL
❑ Experienced SQL programmers new to MySQL
❑ Experienced database designers, administrators, or implementers who are migrating to MySQL
❑ First-time SQL programmers who have no database experience
❑ First-time database designers, administrators, or implementers new to MySQL
❑ Users new to application programming and databases

In addition to the primary audiences, Beginning MySQL can be useful to the following readers:

❑ The home user who wants to create simple databases for such information stores as address
books, CD collections, or recipes
❑ The home business owner who wants to create database applications for such tasks as managing
customers and contacts, tracking inventories, or recording orders
❑ Managers and owners of small businesses who need database solutions that are both easy and
inexpensive to implement
❑ Group managers in larger companies who need database solutions that meet immediate needs
in their groups
❑ Directors, staff, or volunteers at nonprofit organizations who require database solutions that are
simple and inexpensive to implement
❑ Any other individual who wants to learn how to create and manage a MySQL database that can
support various data-driven applications

Nearly anyone new to MySQL will be able to benefit from Beginning MySQL. In addition, users who
have had experience with earlier versions of MySQL or with other database products will be able to use
the book to refresh and expand their skills.

To benefit from Beginning MySQL, you do not have to have a strong background in databases or any
other computer technology. You should, however, have at least a basic understanding of the following:

❑ You should know to negotiate your way around your operating system environment. The book
focuses on implementing MySQL on Linux and Windows, so whichever one you choose, you
should know how to use that system to copy and access files, add programs, change system set-
tings, or whatever tasks are common to your particular environment. If you’re using a Unix-like
system other than Linux, you should find that much of the Linux-related information will apply
to your system.
❑ You will need to know how to use your Web browser to access the Internet and download files
and view information.
❑ You should know how to use a text editor to create and edit text files.

These requirements are all you really need to use Beginning MySQL successfully and learn about how to
implement MySQL databases and manage data in those databases. For Chapters 17, 18, or 19, you should
have at least basic knowledge of Web development techniques. These three chapters focus on developing
a Web application that accesses data in a MySQL database. Chapter 17 covers PHP, Chapter 18 covers

xviii TEAM LinG - Live, Informative, Non-cost and Genuine !


Introduction
JSP/Java, and Chapter 19 covers ASP.NET/C#. Each chapter assumes that you have a basic knowledge of
developing an application in that language and of Web development in general. If you’re new to these
technologies and you want to build an application in one of these languages, it’s recommended that you
first review documentation specific to that language and to Web development in general.

What This Book Covers


The book uses a task-oriented structure that allows you to work through the steps necessary to install
MySQL 4.1 on Linux and Windows platforms, create and manage MySQL databases, query and manipu-
late data stored in those databases, administer the MySQL database management system, and connect to
MySQL databases from your PHP, JSP/Java, and ASP.NET/C# applications.

The next section, which describes the book’s structure, provides additional details about the specifics of
what the book covers.

How This Book Is Structured


Beginning MySQL provides you with an instructional tool that gives you a complete look at MySQL, how
it is implemented, and how it is accessed from various programming languages. The book takes a task-
oriented, step-by-step approach to explain concepts and demonstrate how those concepts are used in
real-world situations.

The structure of Beginning MySQL supports the complete beginner (those new to databases and SQL) as
well as those who are experienced with programming and other database products, but new to MySQL.
The book provides the conceptual and background information necessary for all readers to understand
individual topics, but each chapter is modular to support those readers who simply dip into different
parts of the book to use it as a reference. For example, someone completely new to databases might read
the book from cover to cover, applying information learned in one chapter to the material in the next
chapter. On the other hand, an experienced PHP programmer might want to reference only the chapters
related to SQL statements and PHP connectivity, without having to review chapters on database design
or administration.

Beginning MySQL describes and demonstrates each step necessary to create a MySQL database and access
and manage data in that database. Each chapter correlates with one of the primary tasks necessary to imple-
ment MySQL and to access data, either directly or through an application programming language. The
goal of the book is to provide you with a complete learning experience.

In Chapters 1 through 4, you are introduced to MySQL and relational databases. You are shown the steps
necessary to install MySQL on Windows and Linux, set up the initial MySQL configuration, and access
the MySQL server. You are also shown where to find MySQL components on your system and what tools
are available to access and manipulate data. Finally, you learn how to design a database that conforms to
the relational model. From this information, you will be ready to build a database in which you can store
and manage data.

Chapters 5 through 12 build on the concepts introduced to you in the first four chapters. These chapters
describe how to create databases that store data and help to enforce the integrity of that data. You then
learn how to insert data into those databases, update that data, and then delete the data. You also learn a
variety of methods to retrieve data from the database so that you can display exactly the data you need and
perform operations on that data. You are also shown the steps necessary to copy, import, and export data.

TEAM LinG - Live, Informative, Non-cost and Genuine ! xix


Introduction
In Chapters 13 through 16, you learn how to perform tasks related to administering MySQL. The chapters
include the steps necessary to perform such tasks as verify system settings and perform server-related
operations, set up logging, manage security, optimize performance, back up and restore your system, and
set up replication.

Chapters 17 through 19 are a little different from the other chapters. Each chapter describes how to access
a MySQL database from a specific programming language, including PHP, JSP/Java, and ASP.NET/C#.
You learn how to establish a connection to a database and issue SQL statements against the database. In
each chapter, you will build a data-driven application that allows you to display data that you retrieve
from a MySQL database.

In addition to the 19 chapters in this book, Beginning MySQL includes several appendices that provide
additional information about MySQL and the book. Appendix A provides the answers to the exercises
presented in each chapter. (The exercises are described in the text that follows.) Appendix B includes a
brief description of each application programming interface (API) supported by MySQL, and Appendix
C gives you an overview of features that you can expect to see in the next release of MySQL.

By the end of the book, you will have installed MySQL, configured it, created a database and its tables,
added data to the database and manipulated that data, performed administrative tasks, and created
applications that access the data in the database. To support this process, the chapters contain a number
of elements, including examples that demonstrate how to perform various tasks, Try It Out sections that
provide you with hands-on experience in using MySQL, and exercises that help you better understand
the concepts explained in each chapter.

Exercises and Examples


To provide the various examples and exercises throughout the chapters, Beginning MySQL is based on
MySQL 4.1. This means that the statement and command structures, various procedures, and expected
results all conform to that version of the product. Specifically, most of what you find in the book applies
to the MySQL 4.1.7 release or later. If you use another release of MySQL, however, you might find that
some procedures and their results are different from what are described here.

As you work your way through the you’ll find that MySQL sometimes supports more than one way
that an SQL statement can be written to achieve the same results. As MySQL has evolved, so too have the
statements—to improve performance, simplify the statement, or conform to industry standards. The orig-
inal version of the statements, however, continues to be maintained to support legacy MySQL systems or
to provide portability from one database system to the next. In these situations, you should use whatever
approach is best suited to your particular situation. This sometimes means trying different versions of a
statement to determine which one performs the best. Often, you’ll find that using the simplest version not
only is the easiest approach but will meet most of your needs.

Some of the code that you’ll run in the examples and Try It Out sections is available for download. Be sure
to visit the Wrox Web site at www.wrox.com to determine whether code is available. Generally, anything
that is more than a few lines (anything that you cannot easily type yourself) is available for download.

Each chapter in Beginning MySQL includes a number of elements that demonstrate how to perform spe-
cific tasks related to implementing MySQL databases and managing data in those databases. In addition
to providing a thorough explanation of each concept, the chapters include examples, Try It Out sections,
and exercises.

xx TEAM LinG - Live, Informative, Non-cost and Genuine !


Introduction

Examples
For each concept presented in the book, one or more examples are provided to demonstrate that concept.
When appropriate, statement or command syntax precedes the examples. Syntax refers to the basic form
that the statement or command should take. The syntax shows which elements must be included, which
elements are optional, how parameters should be included, and in what order the elements should be
placed. In other words, the syntax provides a blueprint for how a statement or command should be con-
structed. (Chapter 1 provides you with more information about syntax and supplies an example of how
it is used.)

After the syntax has been provided, the chapter includes examples that demonstrate how real-life state-
ments and commands are created. The examples are meant only as a way to demonstrate the actual code.
You are not expected to try out the examples in an actual database environment. With the correct setup, the
statements and commands do indeed work.

If you decide to try out an example, you can use the test database installed by default when you install
MySQL, or you can create your own database for testing purposes. Keep in mind, however, that you have
to pay particular attention to how the database is set up to try out the examples. You cannot assume that a
table named Books used in the examples in one chapter is defined the same as a table named Books in
another chapter. In addition, you cannot assume that, as examples progress through a chapter, they neces-
sarily build on each other, although this is sometimes the case.

Whenever appropriate, a chapter will provide you with details about how the system is set up to demon-
strate the examples. For instance, you’re often provided with the details about how a table is defined and
what data it includes before the examples are provided. You can then use this table setup information to
create your own table in order to try out an example. One example, however, can affect a table in such a
way as to change its original structure or data, so you must be aware of this from one example to the next.

Again, the examples are meant only to demonstrate how a statement or command works. You’re not
expected to try out each example, so if you do, pay close attention to your setup. The book also includes a
number of Try It Out sections, which provide you with a more controlled environment to try out statements
and commands.

Try It Out Sections


Most chapters include one or more Try It Out sections that provide the details necessary for you to try
out the concepts explained in the chapter. Each Try It Out section contains steps that you should follow
to perform specific tasks correctly. Each step explains what action you should take and, when applicable,
provides the code that you should execute. At the end of each Try It Out section, you will find a How It
Works section that explains in detail the steps that you took in the Try It Out section.

Many of the Try It Out sections build on each other as you progress through the book. For example, in
Chapter 4 you design a database, in Chapter 5 you create a database based on that design, and in Chapter 6
you add data to the database. The same database is then used in most of the Try It Out sections that follow
Chapter 6. In fact, you will use the same database to support the data-driven application that you create in
Chapter 17, 18, or 19.

As you work your way through the book, you’ll also find that concepts introduced in earlier chapters
and demonstrated in the related Try It Out sections are not explained in detail in later Try It Out sections.
The assumption in the later Try It Out sections is that you performed the earlier exercises and now know
the material.

TEAM LinG - Live, Informative, Non-cost and Genuine ! xxi


Introduction
In general, you’ll find that the most effective way to use the Try It Out sections is to perform them in
sequential order and make certain that you thoroughly understand them before moving on to the next
set of Try It Out sections. By performing the exercises sequentially, you will have, by the end of the chap-
ter, designed and created a database, added data to and manipulated data in that database, administered
the MySQL server and the database, and built a PHP, JSP/Java, or ASP.NET/C# application that accesses
data in the database.

Exercises
In addition to the examples and the Try It Out sections, each chapter ends with a set of exercises that
allow you to further build on and test the knowledge that you acquired in that chapter. The answers to
these exercises can be found in Appendix A. Keep in mind, however, that the answers provided for the
exercises sometimes represent only one possible solution. As a result, you might come up with an answer
that is also correct but different from what is shown in Appendix A. If this is the case, you can refer to the
actual chapter content to confirm your answer. The answers shown in the appendix normally represent
the most straightforward solution to the exercise, based on the information in the chapter.

Overall, you’ll find the exercises to be a useful tool to help better comprehend the concepts presented in
the chapter. The exercises, along with the examples and Try it Out sections, provide you with a cohesive
presentation of the material so that you can understand each concept completely. By taking advantage of
each of these elements, you will have a thorough foundation of MySQL and will understand the steps
necessary to install and implement MySQL and manipulate data in a MySQL database.

What You Need to Use This Book


Beginning MySQL contains numerous examples and exercises. If you plan to try out these exercises, you
need a system on which to implement MySQL. Specifically, your system should meet the following
requirements:

❑ You should be working on a computer that has a Windows or Linux operating system installed.
You can usually substitute another Unix-like system for Linux, although some of the exercises
might work a little differently from those that focus on Linux.
❑ Eventually, you will need to install the MySQL database management system on your computer.
Chapter 2 explains how to install MySQL.
❑ If you plan to download MySQL or any other files from the Web, you will need high-speed
Internet access.
❑ You will need a text editor such as Vim (for Linux) and Notepad (for Windows).
❑ For Chapters 17, 18, and 19, you will need the appropriate environment in which to implement
your application. For example, PHP requires a Web server such as Apache. JSP/Java requires a
Web server or application server such as JBoss. Depending on your JSP/Java Web server or appli-
cation server, you might also need a special compiler. ASP.NET/C# requires a Web server such as
Internet Information Services. In addition, regardless of the type of application you create, your
system must be set up with the MySQL driver necessary to allow your application to connect to
the MySQL server.

Once you have your system set up the way you need it, you’re ready to begin working your way
through Beginning MySQL.

xxii TEAM LinG - Live, Informative, Non-cost and Genuine !


Introduction

Conventions
To help you get the most from the text and keep track of what’s happening, a number of conventions are
used throughout the book.

Try It Out
The Try It Out is an exercise you should work through, following the text in the book.

1. They usually consist of a set of steps.


2. Each step has a number.
3. Follow through the steps with your copy of the database.

How It Works
After each Try It Out, the code you’ve typed will be explained in detail.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

❑ New terms and important words are italicized when they are introduced.
❑ Keyboard strokes are shown like this: Ctrl+A.
❑ File names, URLs, and code in the text are shown like so: persistence.properties.
❑ Code is presented in two different ways:

In code examples we highlight new and important code with a gray background.

The gray highlighting is not used for code that is less important in the present
context or has been shown before.

Source Code
As you work through the examples in this book, you may choose either to type all the code manually or
to use the source code files that accompany the book. Much of the source code used in this book is
available for download at http://www.wrox.com. (Generally, if the code in an example or in a step in a
Try It Out section is only a few lines, that code is not included.) Once at the site, simply locate the book’s
title (either by using the Search box or by using one of the title lists) and click the Download Code link
on the book’s detail page to obtain all the source code for the book.

Because many books have similar titles, you may find it easiest to search by ISBN; for this book the
ISBN is 0-764-57950-9.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can
go to the main Wrox code download page at http://www.wrox.com/dynamic/books/download.aspx
to see the code available for this book and all other Wrox books.

TEAM LinG - Live, Informative, Non-cost and Genuine ! xxiii


Introduction

Errata
We make every effort to ensure that there are no errors in the text or in the code. No one is perfect, though,
and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty piece
of code, we would be very grateful for your feedback. By sending in errata, you may save another reader
hours of frustration, and at the same time you will be helping us provide even higher-quality information.

To find the errata page for this book, go to http://www.wrox.com and locate the title using the Search
box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you
can view all errata submitted for this book and posted by Wrox editors. A complete book list including
links to each’s book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml
and complete the form there to send us the error you have found. We’ll check the information and, if appro-
priate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based system
for you to post messages relating to Wrox books and related technologies and interact with other readers
and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choos-
ing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow
readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you
read this book, but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com and click the Register link.


2. Read the terms of use and click Agree.
3. Complete the required information to join as well as any optional information you wish to provide
and click Submit.
4. You will receive an e-mail with information describing how to verify your account and complete
the joining process.

You can read messages in the forums without joining P2P, but in order to post your own messages, you
must join.

Once you join, you can post new messages and respond to messages other users post. You can read mes-
sages at any time on the Web. If you would like to have new messages from a particular forum e-mailed
to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques-
tions about how the forum software works as well as many common questions specific to P2P and Wrox
books. To read the FAQs, click the FAQ link on any P2P page.

xxiv TEAM LinG - Live, Informative, Non-cost and Genuine !


1
Introducing the MySQL
Relational Database
Management System

In the world of online auction houses, instant mortgages, worldwide reservations, global
communication, and overnight deliveries, it’s not surprising that even the least technically savvy
individuals in our culture are, to some degree, familiar with the concept of a database. As anyone
who works with data knows, databases form the backbone for this age of information, and access
to those databases can determine one’s ability to perform critical tasks effectively and efficiently.
To meet the ever-increasing demands for information, programmers are continuously building
bigger and better applications that can access and modify data stored in various database systems.
Yet in order to create these applications, programmers must have some knowledge of the systems
that contain the needed data.

Over the years, as the demands for information have grown, so too have the database systems
that have attempted to meet these demands. However, along with this evolution, we have seen an
increase in the costs associated with storing data as well as an increase in the demand for products
that can run on multiple platforms and can be optimized based on the needs of specific types of
organizations. In response to this changing climate, MySQL has emerged as the most popular
open-source database management system (DBMS) in the world. Consequently, organizations
everywhere are jumping on the MySQL bandwagon, increasing the demand for those who know
how to use MySQL to manage data and those who know how to create applications that can access
data in MySQL databases.

In learning to use MySQL, whether to work directly in the MySQL environment or create data-driven
applications, an individual should have a thorough understanding of how MySQL, as a relational
database management system (RDBMS), allows you to manage data and support applications that
rely on access to MySQL data. To this end, this chapter introduces you to MySQL and provides
you with an overview of databases, RDBMSs, SQL, and data-driven applications. By the end of
the chapter, you will understand the following concepts:

TEAM LinG - Live, Informative, Non-cost and Genuine !


Chapter 1
❑ What a relational database is, how it differs from other types of databases, and how it relates to
a database management system.
❑ The programming language SQL, how to interpret SQL syntax, how to create SQL statements,
and how SQL is implemented in MySQL.
❑ How applications can use a host programming language, a MySQL application programming
interface (API), and SQL statements to access information in a MySQL database.

Databases and Database Management


Systems
Databases and database management systems have become the backbone of most Web-related applications
as well as an assortment of other types of applications and systems that rely on data stores to support
dynamic information needs. Without the availability of flexible, scalable data sources, many organizations
would come to a standstill, their ability to provide services, sell goods, rent movies, process orders, issue
forms, lend books, plan events, admit patients, and book reservations undermined by the inability to
access the data essential to conducting business. As a result, few lives are unaffected by the use of databases
in one form or another, and their ubiquitous application in your everyday existence can only be expected
to grow.

What Is a Database?
Over the years, the term database has been used to describe an assortment of products and systems that
have included anything from a collection of files to a complex structure made up of user interfaces, data
storage and access mechanisms, and client/server technologies. For example, a small company might
store payroll records in individual files, while a regional electric company uses an integrated system to
maintain records on all its customers; generate electric bills to those customers; and create reports that
define power usage patterns, profit and loss statements, or changes in customer demographics. In both
cases, the organizations might refer to each of their systems as databases.

Despite how a database is used, the amount of data that it stores, or the complexity of the data, a num-
ber of common elements define what a database is. At its simplest, a database is a collection of data that
is usually related in some fashion. For instance, a database that a bookstore uses might contain informa-
tion about authors, book titles, and publishers. Yet a database is more than simply a collection of related
data. The data must be organized and classified in a structured format that is described by metadata,
which is data that describes the data being stored. In other words, the metadata defines how the data is
stored within the database. Together, the data and the metadata provide an environment that logically
organizes the data in a way that can be efficiently maintained and accessed.

One way to better understand what constitutes a database is to use the analogy of a telephone book. A
phone book contains the names, addresses, and phone numbers of most of the telephone customers in
a particular town or region. If you think of that phone book as a database, you find a set of related data
(the names, addresses, and phone numbers of the telephone customers) and you find a structured
format (the metadata) that is defined by the way that the pages are bound and by how the information
is organized. The phone book provides a system that allows you easy and efficient access to the data
contained in its pages. Without the structure of the phone book, it would be next to impossible to locate
specific customer data.

2 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
In the same way that a phone book provides structure to the customer information, the metadata of
a database defines a structure that organizes data logically within that structure. However, not all
database structures are the same, and through the years, a number of different data models have
emerged. Of these various models, the three most commonly implemented are the hierarchical,
network, and relational models.

The Hierarchical Model


In the early days of database design, one of the first data models to emerge was the hierarchical model.
This model provides a simple structure in which individual records are organized in a parent-child
relationship to form an inverted tree. The tree creates a hierarchical structure in which data is decomposed
into logical categories and subcategories that use records to represent the logical units of data.

Take a look at an example to help illustrate how to structure a hierarchical database. Suppose you’re
working with a database that stores parts information for a company that manufactures wind generators.
Each model of wind generator is associated with a parent record. The parts that make up that model are
then divided into categories that become child records of the model’s parent record, as shown in Figure 1-1.
In this case, the parent record — Wind Generator Number 101 — is linked to three child records: Tower
assemblies, Power assemblies, and Rotor assemblies. The child records are then divided into subcategories
that are assigned their own child records. As a result, the original child records now act as parent records
as well. For example, the Tower assemblies record is a parent of the Towers record but a child of the
Wind Generator Number 101 record.

As you can see in the figure, a parent record can be associated with multiple child records, but a child
record can be associated with only one parent record. This structure is similar to what you might see in a
directory structure viewed through a graphical user interface (GUI) file management application, such as
Windows Explorer. At the top of the directory structure would be Wind Generator Number 101. Beneath
this, would be Tower assemblies, Power assemblies, and Rotor assemblies, each with their own set of
subdirectories.

After its introduction, the hierarchical data model achieved a great deal of success. One of the most
popular implementations of this model is found in IBM’s Information Management System (IMS),
which was introduced in the 1960s and is still widely used on IBM mainframe computers.

However, despite the popularity of the hierarchical model, it is unsuitable for many of today’s applications.
Inherent in the simplicity of the parent-child organization is a rigid structure that results in a cumbersome
navigation process that requires application developers to programmatically navigate through the
connected records to find the necessary information. Records must be accessed one at a time by moving
up and down through the hierarchical levels, which often made modifications to the database and
application a complicated, time-consuming process. In addition, the hierarchical structure cannot support
complex relationships between records. For example, if you return to the wind generator database example,
you discover that Figure 1-1 doesn’t show a record for the belts used to connect the generators to the
shafts. If you were to create a child record for belts, should it be added under the Generators record or
the Shaft assemblies record? The hierarchical design makes it difficult to fully represent the relationship
that exists between the belts and the generators and shafts. Indeed, a child record can be associated with
only one parent record.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 3


Chapter 1
Even with the limitations of the hierarchical model, a large amount of data is still being stored in hierarchical
databases, and many management systems have found ways to work around some of these limitations.
In addition, this is the type of system used primarily for file management systems associated with operating
systems because it allows users to go directly where they need to go to find a file, rather than having to
iterate through a lot of nodes. As a result, the hierarchical database probably isn’t going anywhere
anytime soon.

Wind Generator
Number 101

Tower Rotor
assemblies assemblies

Towers Ground mount Blade Braking Shaft Furling


assemblies assemblies systems assemblies tails

Guy wire Hubs Blades Governors


assemblies

Bearings Cases Shafts

Anchors Wires Bearings

Power
assemblies Rotation Yaw

Battery
Anemometers packs
Shutdown
systems

Wiring
Generators Dump load
systems

Cables Connectors
Brushes Magnets Regulators Heaters

Coils

Wiring

Commutators

Figure 1-1

4 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System

The Network Model


To work around the limitations of hierarchical databases, a new model of database design, built upon
the hierarchical model, emerged in the 1970s. The network model enhanced the hierarchical model by
allowing records to participate in multiple parent-child relationships. For example, suppose the wind
generator database must also store data about employees, customers, and orders. A hierarchical database
might contain four parent records: Orders, Employees, Customers, and Wind generators. Each of these
records would then contain the necessary child records to support this structure, as shown in Figure 1-2.

Employees

Max N.
Orders

Sarah W.

Order 1002

Customers
Order 1003

Order 1001 ABC


DEF Company
Company

Wind
generators

Wind Wind
generators generators
Number 103 Number 102

Wind
generators
Number 101
Figure 1-2

TEAM LinG - Live, Informative, Non-cost and Genuine ! 5


Chapter 1
If each of these categories operated without interaction with each other, then the need for the network
model would be minimal. However, if you consider the fact that each order is related to the employee
who took the order, the customer who bought the order, and the wind generator model that was purchased,
you can see that the hierarchical model is inadequate to support the complex relationships that exist
between records. For example, Sarah W. took Order 1001 for the DEF Company. The company bought
two wind generators: models 101 and 102. As a result, the Order 1001 record is related to the Sarah W.
record, the DEF Company record, the Wind Generator Number 101 record, and the Wind Generator
Number 102 record.

The network model still has many of the disadvantages of the hierarchical model, but it provides far
more flexibility in allowing programmers to navigate through records. Despite the flexibility, developers
must still program record navigation within the application. In addition, any changes to the database
or application can result in complicated updates. A database must be well planned in advance, taking
into account record navigation at the application level.

The Relational Model


Because of the limitations of the hierarchical and network models, a new model began gaining
momentum in the late 1970s, and by the end of the 1980s, emerged as the standard for the next generation
of databases. The relational data model represents a radical departure from the rigid structures of the
hierarchical and network models. Applications accessing a hierarchical database rely on a defined
implementation of that database, and the database structure must be hard-coded into the application’s
programming language. If the database changes, the application must change.

However, a relational database is independent of the application. It’s possible to modify the database
design without affecting the application because the relational model replaces the parent-child framework
with a structure based on rows and columns that form tables of related data. As a result, you can define
complex relationships between the tables, without the restrictions of earlier models.

For example, suppose you want to change the original wind generator database that you saw in Figure 1-1
to a relational database. The database might include a table for the individual parts and a table of the
individual categories of parts, as shown in Figure 1-3. As you can see from the illustration, the Parts table
includes a list of parts from different areas of the wind generator. The table could contain every part for
the entire wind generator, with each row in the table representing a specific part, just as a record in the
hierarchical database represents a specific part. For example, the guy wire assembly (in the first row of
the Parts table) is a component of the tower assembly, and the generator (in the fifth row) is a component
of the power assembly.

Each row in the Parts table represents one part. The part is assigned a unique part ID, a name, and a
reference to the category to which it belongs. The Categories table lists each category. Note that the last
column in the Parts table references the first column in the Categories table. A relationship exists between
these two tables. For instance, the brushes product has been assigned a PartID value of 1004. If you look
in the CatID column for this product, you see that it contains a value of 504. If you now look at the
Categories table, you find that 504 refers to the Generator category, which is itself a part. Because of this
structure, programmers are less restricted when moving through data, resulting in applications that can
be more flexible when retrieving information and databases that can better accommodate change after
the applications have been written.

Don’t be concerned if you do not fully grasp the concepts of tables, rows, and columns or the relation-
ships between the tables. Chapter 4 discusses the relational model in greater detail.

6 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System

Parts Categories
PartID PartName CatID CatID CatName Parent
1001 Guy wire assembly 503 501 Wind Generator 101 NULL
1002 Magnet 504 502 Rotor assembly 501
1003 Regulator 505 503 Tower assembly 501
1004 Brushes 504 504 Generator 506
1005 Generator 506 505 Dump load system 506
1006 Dump load system 506 506 Power assembly 501
1007 Power assembly 501
1008 Tower assembly 501
1009 Rotor assembly 501

Figure 1-3

As the popularity of the relational model has grown, so too has the number of database products that
use this model to store and manage data. Included in the family of relational products are DB2, Oracle,
SQL Server, and of course, MySQL. However, a relational database alone is not enough to provide the
type of data management, storage, connectivity, security, analysis, and manipulation that is required of a
dynamic information store. For this, you need a complete management system that works in conjunction
with the relational database to provide the full spectrum of database services.

Database Management Systems


Most databases rely on a database management system to manage the data stored within the system’s
databases and to make the data available to users who need access to specific types of information. A
DBMS is made up of a comprehensive set of server and client tools that support various administrative
and data-related tasks. For example, most DBMSs provide some type of client tool that allows you to
interact directly with the data stored in a database.

At the very least, a DBMS must store data and allow data to be retrieved and modified in a way that
protects the data against operations that could corrupt or insert inconsistencies into the data. However,
most systems provide many more capabilities. In general, nearly any comprehensive DBMS supports the
following types of functionality:

❑ Managing storage
❑ Maintaining security
❑ Maintaining metadata
❑ Managing transactions
❑ Supporting connectivity
❑ Optimizing performance
❑ Providing back-up and recovery mechanisms
❑ Processing requests for data retrieval and modification

TEAM LinG - Live, Informative, Non-cost and Genuine ! 7


Chapter 1
The extent to which a DBMS supports a particular functionality and the exact nature in which that
functionality is implemented is specific to the DBMS. For any one system, you must refer to the
product documentation to determine what and how specific functionality is implemented.

The MySQL RDBMS


As database models evolved, so too did the DBMS products that supported the various types of
databases. It’s not surprising, then, that if there are DBMSs, there are RDBMSs. MySQL is such as system,
as are Oracle, DB2, SQL Server, and PostgreSQL. These products, like any DBMS, allow you to access
and manipulate data within their databases, protect the data from corruption and inconsistencies, and
maintain the metadata necessary to define the data being stored. The primary difference, then, between
a DBMS and a RDBMS is that the latter is specific to relational databases. It supports not only the storage
of data in table-like structures, but also the relationships between those tables.

Emerging as a major player in the RDBMS market is MySQL. As with other RDBMS products, MySQL
provides you with a rich set of features that support a secure environment for storing, maintaining, and
accessing data. MySQL is a fast, reliable, scalable alternative to many of the commercial RDBMSs available
today. The following list provides an overview of the important features found in MySQL:

❑ Scalability: MySQL can handle large databases, which has been demonstrated by its implemen-
tation in organizations such as Yahoo!, Cox Communications, Google, Cisco, Texas Instruments,
UPS, Sabre Holdings, HP, and the Associated Press. Even NASA and the US Census Bureau
have implemented MySQL solutions. According to the MySQL product documentation, some of
the databases used by MySQL AB, the company that created MySQL, contain 50 million records,
and some MySQL users report that their databases contain 60,000 tables and 5 billion rows.
❑ Portability: MySQL runs on an assortment of operating systems, including Unix, Linux,
Windows, QS/2, Solaris, and MacOS. MySQL can also run on different architectures, ranging
from low-end PCs to high-end mainframes.
❑ Connectivity: MySQL is fully networked and supports TCP/IP sockets, Unix sockets, and
named pipes. In addition, MySQL can be accessed from anywhere on the Internet, and multiple
users can access a MySQL database simultaneously. MySQL also provides an assortment of
application programming interfaces (APIs) to support connectivity from applications written in
such languages as C, C++, Perl, PHP, Java, and Python.
❑ Security: MySQL includes a powerful system to control access to data. The system uses a host- and
user-based structure that controls who can access specific information and the level of access to
that information. MySQL also supports the Secure Sockets Layer (SSL) protocol in order to
allow encrypted connections.
❑ Speed: MySQL was developed with speed in mind. The amount of time it takes a MySQL
database to respond to a request for data is as fast as or faster than many commercial RDBMSs.
The MySQL Web site (www.mysql.com) provides the results of numerous benchmark tests that
demonstrate the fast results you receive with a MySQL implementation.
❑ Ease of use: MySQL is simple to install and implement. A user can have a MySQL installation
up and running within minutes after downloading the files. Even at an administrative level,
MySQL is relatively easy to optimize, especially compared to other RDBMS products.
❑ Open-source code: MySQL AB makes the MySQL source code available to everyone to
download and use. The open-source philosophy allows a global audience to participate in the
review, testing, and development of code. (See the Open-Source Movement section below for
information about open-source technology.)

8 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
As you can see, MySQL can provide you with a fast, reliable solution to your database needs. Not only is
it easy to use and implement, it offers the advantages and flexibility of an open-source technology. You
can download the MySQL distribution files directly from the MySQL Web site, and start using the
product immediately.

The Open-Source Movement


One of the most distinctive features of MySQL compared to RDBMSs such as Oracle and DB2 is that
MySQL is an open-source application. As a result, the MySQL source code is available for anyone to use
and modify, within the constraints of the GNU General Public License (GPL), an open-source licensing
structure that supports the distribution of free software. (GNU, pronounced Guh-New, is an acronym for
“GNU’s Not Unix.” GNU is an operating system based on the Linux kernel.)

For specific information about the most current MySQL licensing structure, visit the MySQL site at
www.mysql.com. For information about the GNU GPL, visit the GNU licensing site at
www.gnu.org/licenses.

The open-source nature of MySQL is part of a worldwide movement that promotes the free access of
application source code. As a result, users are allowed to download and use open-source applications for
free. One of the most well known examples of this technology is the Linux operating system, which has
been instrumental in unifying the open-source community and promoting a wider base of users and
developers who test and contribute to the operating system’s development. The same is true of MySQL,
which is reported to be the most popular open-source RDBMS in the world. As an open-source application,
developers everywhere contribute to the development process, and millions of users test new versions
of the application as it is being developed.

As applications such as MySQL and Linux continue to see a steady growth in their global user base, so
too does the acceptance of the open-source philosophy, evidenced by the increasing number of other
types of applications and technologies that now participate in the open-source movement, providing a
richer user experience, a more robust developer environment, and a wider spectrum of options for
everyone.

The SQL Framework


Soon after the relational data model appeared on the database scene, research began on the development
of relational databases. From this research came the realization that traditional programming languages,
such as COBOL or Fortran, were not suited to implementing these types of databases and that a special
language was needed. Out of these beginnings came SQL, a database-specific language that has become
the definitive language of relational databases and that, as a result, has seen widespread implementation
and usage, regardless of products, platforms, or operating system environments.

There is some debate about what SQL stands for and how to pronounce it. In some sources, you see SQL
defined as an acronym that means Structured Query Language, yet other sources treat SQL as simply
the three letters that stand for the language. The American National Standards Institute (ANSI), which
published the SQL:2003 standard, makes no mention of “structured query language” and treats SQL
simply as the three letters. As a result, no definite resource says that SQL stands for Structured Query
Language, despite the fact that many publications define it this way.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 9


Chapter 1
Another area of debate that surrounds SQL is whether to pronounce it one letter at a time, as in “S-Q-L,”
or to pronounce it as a word, as in “sequel.” This is why some publications, when preceding SQL with
an article, use the word an (“an SQL database”) and some use the word a (“a SQL database”). With
regard to this particular issue, the SQL:2003 standard prefers “S-Q-L,” so that is the convention used
in this book.

What is SQL?
SQL is, above all else, a computer language used to manage and interact with data in a relational
database. SQL is the most universally implemented database language in use, and it has become the
standard language for database management. SQL works in conjunction with a RDBMS to define
the structure of the database, store data in that database, manipulate the data, retrieve the data, control
access to the data, and ensure the integrity of the data. Although other languages have been developed
to implement the relational model, SQL has emerged as the clear winner.

Nearly all RDBMSs implement some form of SQL in order to manage their relational database. This is
true not only for MySQL, but also for SQL Server, DB2, Oracle, PostgreSQL, and all the major players in
the world of RDBMSs. However, do not confuse SQL with the programming languages used to develop
the RDBMS. For example, MySQL is built with C and C++. The functions that such an application performs
in order to support connectivity, provide APIs, enable network access, or interact with client tools are
carried out at the C and C++ programming level. The primary purpose of SQL is to allow the RDBMS to
interact with the data. The C and C++ environment provides the structure that houses the SQL environ-
ment, which itself allows you to define and interact with the data. In other words, the RDBMS facilitates
the ability of SQL to manage data.

Figure 1-4 illustrates how SQL interacts with the MySQL RDBMS. In this figure, MySQL is running as a
server on a specific platform such as Linux or Unix. The database, stored either internally or externally,
depending on your storage configuration, hosts the actual database files. Although the RDBMS facili-
tates (through the C/C++ applications) the creation and maintenance of the database and the data
within the database, SQL actually creates and maintains the database and data.

MySQL SQL
RDBMS database
C/C++
SQL statements

Figure 1-4

10 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
SQL, then, is a standardized language, not a stand-alone product, such as MySQL. SQL relies on the
interaction with a RDBMS in order to manage data. You cannot develop an SQL-based application,
although you can build an application that connects to a database managed by a RDBMS and then
sends SQL statements to the database in order to request and modify data. (You learn more about how
SQL fits into application development later in the chapter, in the section Data-Driven Applications.)
However, despite the inability of SQL to stand on its own, it remains the foundation of most relational
databases; therefore, anyone who creates applications that interact with an SQL database should have a
basic understanding of SQL.

A Brief History of SQL


After the relational model was introduced to the database development community in the early 1970s,
IBM began researching ways to implement that model. IBM’s research, referred to as the System/R pro-
ject, resulted in a prototype of the first RDBMS. As part of the System/R project, IBM produced the first
incarnation of a relational database language, which was known Structured English Query Language
(SEQUEL). Over the next few years, IBM updated the prototype and released SEQUEL/2, which was
later renamed to SQL.

In the late 1970s, IBM released System R to a number of its customers for evaluation. The development
and release of System R brought with it increased attention to relational databases, RDBMSs, and
SQL, and reconfirmed to the public IBM’s commitment to the relational model. Soon a group of engineers
formed Relational Software, Inc., a company whose primary goal was to develop a RDBMS system
based on SQL. Before long, the company released its own product — Oracle — the first commercial
RDBMS to hit the market. It wasn’t until 1981 that IBM released their first commercial RDBMS — SQL/DS.

The ANSI Standard


By the mid-1980s, relational databases and SQL had become an industry standard. During this time, the
performance of RDBMSs had improved dramatically, and other companies were investing into the rela-
tional technologies, either releasing or preparing to release their own SQL-based RDBMSs. However, as
SQL became more widely implemented, so too did the need to standardize the language across various
products. In an attempt to achieve this goal, ANSI released the first published SQL standard (SQL-86) in
1986, giving SQL official status in the software development industry.

ANSI updated the standard in 1989 (SQL-89) and again in 1992 (SQL-92). SQL-92 represented a major
revision to the language and included expanded and improved features, some of which exceeded the
capabilities of existing RDBMSs. In fact, SQL-92 was substantially longer than SQL-89 in an attempt to
address many of the weaknesses of the earlier standard.

Because of the significant expansion of the standard, SQL-92 defined three levels of conformance:

❑ Entry: This level represented the most basic stage of conformance, and was based primarily on
the SQL-89 standard, with only a few improvements.
❑ Intermediate: Although this level represented significant advancements to the product, it was
believed that most products could achieve compliance.
❑ Full: A RDBMS had to be in complete compliance with the standard.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 11


Chapter 1
To be in conformance to the SQL-92 standard, a RDBMS had to comply with at least the Entry level,
which has been achieved by most RDBMSs on the market. However, no known product achieved an
Intermediate level of conformance, let alone Full. Part of the problem is that some of the features
specified in the Intermediate level met with little interest from users. As a result, RDBMS vendors saw
little reason to implement these features.

In 1999, ANSI, along with the International Organization for Standardization (ISO) published SQL:1999,
the first complete update to the SQL standard since 1992. However, during those seven years, interim
standards were published to incorporate features that RDBMS vendors were already being implementing.
These interim publications were then incorporated in the SQL:1999 standard, which represented another
significant expansion of the standard.

Because most products reached only an Entry level of conformance to SQL-92, the SQL:1999 standard
took a different approach to conformance levels. To be in conformance to the new standard, a RDBMS
had to be in compliance with Core SQL. Core SQL contained all the features of Entry level SQL-92, many
of the features of Intermediate level, and some of the features of Full level, plus some features new to
SQL:1999. In addition to claiming Core SQL conformance, a RDBMS could claim conformance to one of
the supported packages. A package is a set of features that a vendor could implement in a RDBMS. The
SQL:1999 standard supported the following packages:

❑ PKG001: Enhanced date/time facilities


❑ PKG002: Enhanced integrity management
❑ PKG003: OLAP (online analytical processing) facilities
❑ PKG004: PSM (persistent stored module)
❑ PKG005: CLI (call-level interface)
❑ PKG006: Basic object support
❑ PKG007: Enhanced object support
❑ PKG008: Active database
❑ PKG009: SQL/MM (multimedia) support

Most RDBMSs, including MySQL, conform to the Entry level of SQL-92 and achiev some confor-
mance to Core SQL in SQL:1999. However, ANSI and ISO have released yet another version of the
standard — SQL:2003. In many ways, the new standard merely reorganizes and makes corrections
to SQL:1999. However, the latest standard does include additional features that were not part of
SQL:1999, particularly in the area of Extensible Markup Language (XML). As a result, compliance
with SQL:1999 does not necessarily imply compliance to SQL:2003.

With the advent of SQL:2003, future releases of RDBMS products will inevitably change, and some
vendors are already working on achieving compliance with the new standard. However, as of today,
no product claims compliance to SQL:2003.

You can purchase the ANSI/ISO SQL:2003 standard online at the ANSI eStandards Store
(http://webstore.ansi.org). The standard is divided into 14 parts, which you must purchase
individually.

12 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
Object-Relational Model
As explained earlier, SQL was developed as a way to implement the relational model. To this end, the
language has been quite successful, attested to by its widespread implementation and the commitment
of companies such as Microsoft, IBM, Oracle, and MySQL AB to relational databases and SQL. However,
most RDBMS vendors have extended the SQL-based capabilities of their products to include features
that go beyond the pure relational nature of SQL. Many of these new features are similar to some of the
characteristics found in object-oriented programming, a type of programming based on self-contained
collections of routines and data structures that each perform a specific task. As SQL, as well as various
RDBMS products, has become more advanced, it has taken a turn toward object-oriented programming
(although, strictly speaking, SQL is far from being an object-oriented language).

Java and C# are both examples of object-oriented programming languages. In these languages, objects
interact with one another in a way that addresses complex programming issues that cannot be easily
addressed with traditional procedural languages.

A good example of the object-oriented nature of some of the extended features in RDBMSs is the stored
procedure. A stored procedure is a collection of SQL statements that are grouped together to perform a
specific operation. The SQL statements are saved as a single object stored in the database and that users
can evoke as needed.

By the mid-1990s, most RDBMS products had implemented some form of the stored procedure. To
address this trend, ANSI released in 1996 an interim publication referred to as SQL/PSM, or PSM-96.
(PSM refers to persistent stored module.) A PSM is a type of procedure or function stored as an object in
the database. A procedure is a set of one or more SQL statements stored as a unit, and a function is a
type of operation that performs a specific task and then returns a value.

The SQL/PSM standard defined how to implement PSMs in SQL. Specifically, SQL/PSM included the
language necessary to support stored procedures (which were referred to as SQL-invoked procedures in
the standard). SQL/PSM was later incorporated into the SQL:1999 standard.

The problem that ANSI ran into when trying to standardize the SQL language related to stored procedures
is that the way in which stored procedures were implemented from product to product varied widely.
As a result, the manner in which stored procedures are called and retrieved can be very different not
only between products and the SQL:1999 standard, but also among the products themselves. As a result,
the implementation of stored procedures remains very proprietary, with few products conforming to the
actual standard.

MySQL currently does not support stored procedures, although SQL AB is including this functionality
in version 5.0. The stored procedure functionality is based on the SQL:2003 standard.

The differences among the products extend beyond only stored procedures. Other features have experi-
enced the same fate as stored procedures because so many of these features had been implemented prior
to the standardization of related SQL statements. Still, many of SQL’s advanced features, with their
object-oriented characteristics, are here to stay, as can be seen in both the SQL:1999 and SQL:2003 stan-
dards and in the RDBMS products, making SQL an object-relational database language and the RDBMS
products object-relational database management systems.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 13


Chapter 1

The Nonprocedural Nature of SQL


Despite the influence of object-oriented programming on SQL, SQL is still very different from other
programming languages. Traditional procedural programming languages such as COBOL, Fortran,
and C were designed for very specific purposes, none of which were for accessing data. For this reason,
SQL was intended for use in conjunction with these languages in order to build applications that could
easily access data. For this reason, SQL is not intended for use as a standalone language, which is why
it is sometimes referred to as a sublanguage. Insufficient for writing complete applications, SQL was
designed with the idea that there would always be a host language for application building.

Traditional programming languages, which range from Fortran to C, are considered to be procedural
languages; that is, they define how to carry out an application’s operations and the order in which to
carry them out. SQL, on the other hand, is nonprocedural in nature. It is concerned primarily with the
results of an operation. The host language determines how to process the operation. Of course, this doesn’t
mean that SQL doesn’t include procedural elements. For example, stored procedures are such an
element, and certainly RDBMS vendors recognize the need for at least some procedural functionality.

Yet these procedural elements do not make SQL a procedural language. SQL doesn’t have many of the
basic programming capabilities of the other languages. As a result, you cannot build an application with
SQL alone. You must use a procedural language that works in conjunction with SQL to manipulate data
stored in a RDBMS.

SQL Statements
SQL is made up of a set of statements that define the structure of a database, store and manage data
within that structure, and control access to the data. At the heart of each SQL statement is a syntactical
structure that specifies how to create the statement can be created. The syntax acts as blueprint for
building statements that the RDBMS interprets. Most RDBMS products provide little leeway for state-
ments that don’t adhere strictly to the syntactical foundations. As a result, you should know how to read
and interpret statement syntax if you plan to use SQL in your applications or access data in an SQL
database.

Working with Statement Syntax


When you create an SQL statement, you must often rely on the statement syntax defined in a product’s
documentation. The syntax provides the guidelines you need to create a statement that RDBMS can
interpret. For each statement, the syntax — through the use of keywords and symbols — defines the
statement’s structure, the elements required within the statement, and options you can include to help
refine the statement.

When you first look at the complete syntax for any statement, it might seem overwhelming, depending on
the statement. For some statements, there are relatively few elements, so interpretation is easy. However,
other syntax can be pages long. Despite the complexities of a particular statement, the basic syntax
elements are the same, and if you learn how to interpret those elements, you can, with practice, understand
any syntax presented to you.

The elements comprising a syntactic structure can vary from reference to reference and from product
to product, although in many cases, the symbols used are the same. This book follows ANSI’s SQL:2003
standards. You may encounter partial syntax throughout this book. In some cases, there are simply too
many syntactic elements, and many of those elements are rarely implemented. Whenever you want to be
certain that you’re seeing a statement’s syntax in its entirety, be certain to check the MySQL documentation.

14 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
Below is an example of a statement’s syntax so that you can get a better feel for how to compose an SQL
statement. The example below is based on the MySQL CREATE TABLE statement. The statement varies
somewhat from the statement as it’s defined in the SQL:2003 standard; however, the basic elements are
the same. The following syntax demonstrates all the elements that comprise any SQL statement, in terms
of the structure and symbols used:

<table definition>::=
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table name>
(<table element> [{, <table element>}...])
[ENGINE = {BDB | MEMORY | ISAM | INNODB | MERGE | MRG_MYISAM | MYISAM}]

<table element>::=
{<column name> <type> [NOT NULL | NULL] [DEFAULT <value>] [AUTO_INCREMENT]}
| {PRIMARY KEY (<column name> [{, <column name>}...])}
| {INDEX [<index name>] (<column name> [{, <column name>}...])}

The syntax shown here does not represent the CREATE TABLE statement in its entirety, but it does
include the fundamental components. Chapter 5 examines the table definition syntax in far more
detail, but for now, the primary concern is that you learn how to interpret SQL statement syntax.

The syntax method employed here is referred to as BNF (Backus Naur Form) notation. Most resources
that discuss syntax for SQL statements use BNF notation or something similar to this.

Before examining the syntax example in detail, review the symbols used as part of syntax notation.
The following conventions define how to create a statement, based on the meaning of the symbols
within the context of the syntax:

❑ Vertical bar ( | ): The vertical bar can be interpreted to mean “or.” Whenever you can choose
from two or more options, those options are separated with a vertical bar. For example, in the
sixth line, you can choose either NOT NULL or NULL.
❑ Square brackets ( [ ] ): A set of square brackets indicates that the syntax enclosed in those brackets
is optional.
❑ Angle brackets ( < > ): A set of angle brackets indicates that the syntax enclosed is a place-
holder, in which case, you must insert a specific value in place of the angle brackets and the
text within those brackets. If the meaning of the placeholder is not self-evident, a later section
within the syntax usually defines it.
❑ Curly brackets ( { } ): A set of curly brackets indicates that the syntax enclosed in those brackets
should be treated as a unit. As a result, if one element within the brackets is used, all elements
are used, unless a vertical bar separates options within the brackets.
❑ Three periods (...): A set of three periods means that the clause that immediately precedes the
periods can be repeated as often as necessary.
❑ Two colons/equal sign (::=): The colon/equal sign construction defines placeholders. Literally,
it is the equivalent to an equal sign. The syntax to the right of the symbols defines the specified
placeholder to the left.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 15


Chapter 1
Once you understand how to use these six symbols, you should be able to interpret most syntax.
However, one other syntactic element that you should be aware of is the use and placement of keywords.
A keyword is a reserved word or set of reserved words that are part of the SQL lexicon. The keywords
define a statement’s action and how that action is carried out. For example, the CREATE TABLE keywords
indicate that this statement does what you would expect it to do — create a table.

Normally, keywords are represented in all uppercase to distinguish them from placeholders, but SQL is
a case-insensitive language, so the use of uppercase is meant only as a way to write more readable code.
You could also write Create Table, create table, or CREate taBLE, and MySQL would interpret the code
in the same way.

Not only is SQL indifferent to capitalization, it also isn’t concerned with tabs, extra spaces, or line
breaks. In theory, you could write your entire SQL statement on one line, or you could place each word
on separate lines. However, it’s recommended that you construct your statements in such a way that
they are easy to read and understand, so breaking a statement into several lines is a common approach
to take.

Returning to the example syntax and reviewing it line by line, the syntax begins by identifying the type
of statement that is being defined:

<table definition>::=

Literally, the syntax means that the <table definition> placeholder is equivalent to the syntax that
follows. SQL-related documentation often omits this introductory line, and it is seldom necessary at the
beginning of the syntax. Usually, the syntax itself clearly defines the statement’s purpose. However, it’s
included here so that you recognize it should you run into it in SQL documentation. To review the second
line of the syntax:

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table name>

This line represents the actual first part of a CREATE TABLE statement. Notice that the keyword TEMPORARY
separates the CREATE TABLE keywords. Because square brackets enclose this keyword, the keyword is
optional. You would include it only if you plan to create a temporary table. (Temporary tables are
discussed in Chapter 5.) Because of the optional keyword, a table definition can begin with CREATE
TABLE or CREATE TEMPORARY TABLE.

The next part in this line of syntax is the keywords IF NOT EXISTS. Again, these keywords are
optional and would be included only if you want to check for the existence of a table with the same
name. Note, however, that when a set of brackets encloses multiple words in this manner, all the keywords
are included or none are included. You would not use IF, NOT, or EXISTS alone within this context of
this part of the statement. In other words, you would never create a statement that begins with the
following:

CREATE TABLE EXISTS <table name>

Notice that the final element in this line of syntax is the <table name> placeholder. This is the position
within the statement in which you provide a name for the table that you’re creating. When the table is
added to the database, it is assigned the name that you provide here, and this is the name that you use
whenever referring to the table. Now look at the next line of syntax:

(<table element> [{, <table element>}...])

16 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
The first thing you might notice is that parentheses enclose all the elements. Whenever you include
parentheses in this way (and the parentheses are not enclosed by square brackets), the parentheses are
required. As a result, the required elements of this line are (<table element>). Because the <table element>
placeholder represents a more complex syntax than merely the name of an object, the placeholder is
defined later in the code.

The important point to remember is that at least one <table element> is required, but you can
include as many as necessary. However, this is when the syntax gets a little trickier. Notice that several
elements are enclosed in square brackets — [{, <table element>}...] — telling you that this part
of the syntax is optional. However, curly brackets group together parts of the syntax within the square
brackets — {, <table element>} — and they are followed by three periods. The curly brackets mean
that the elements within those brackets must be kept together, and the periods mean that the group of
elements can be repeated as often as necessary. As a result, whenever you include an additional
<table element> in your statement, you must precede it with a comma, but you can do this as many
times as necessary. For example, if the statement includes four table elements, your syntax would
be as follows:

(<table element>, <table element>, <table element>, <table element>)

As you can see, when you include more than one <table element>, you must follow each one with a
comma, except for the last one. And keep in mind that parentheses must enclose them all. Moving on to
the next line of syntax:

[ENGINE = {BDB | MEMORY | ISAM | INNODB | MERGE | MRG_MYISAM | MYISAM}]

One of the first things that you notice is that square brackets enclose the entire line, which means that
the entire line is optional. The line defines the type of table that you plan to create. If you do include
this line in your CREATE TABLE statement, then you must include ENGINE = plus one of the table
type options. You can tell that you’re allowed to select only one option because a vertical bar separates
each option. You could read this as BDB or MEMORY or ISAM or INNOBD, and so on. For example, if
you want to define the table as an INNODB table, you would include the following line in your syntax:

ENGINE = INNODB

You should now have a basic understanding of how to create a CREATE TABLE statement. However,
as you may recall, the <table element> placeholder could not be easily defined by its placement or
usage. As a result, the syntax goes on to define the components that can make up a <table element>.
You can tell that the syntax defines the <table element> placeholder because it precedes the
definition with the actual placeholder, as shown in the first line in the next section of syntax:

<table element>::=

From this, you know that whatever follows is part of the syntax that defines the <table element>
placeholder. Before you look too closely at the first line in the <table element> definition, take a look
at all three lines that make up that definition:

{<column name> <type> [NOT NULL | NULL] [DEFAULT <value>] [AUTO_INCREMENT]}


| {PRIMARY KEY (<column name> [{, <column name>}...])}
| {INDEX [<index name>] (<column name> [{, <column name>}...])}

TEAM LinG - Live, Informative, Non-cost and Genuine ! 17


Chapter 1
What you might have noticed is that a vertical bar precedes the last two lines and that curly brackets
enclose all three lines. This means that each line represents one of the options you can use to define a
<table element> placeholder. In other words, for each <table element> that you include in your
CREATE TABLE statement, you can define a column, a primary key, or an index.

A primary key is a constraint placed on one or more columns within a table to indicate that the columns
act as the primary identifier for each row in that table. Values within a primary key’s columns must be
unique when taken as a whole. You learn about primary keys in Chapter 5, which discusses how to
create a table.

Take a look at the first line of the <table element> definition:

{<column name> <type> [NOT NULL | NULL] [DEFAULT <value>] [AUTO_INCREMENT]}

This line defines a column within the table. Each column definition must include a name (<column
name>) and a data type (<type>). A data type determines the type of data that can be stored in a
table. The line also includes three optional elements. The first of these is [NOT NULL | NULL], which
means that you can set a column as NOT NULL or NULL. A null value indicates that a value is undefined
or unknown. It is not the same as zero or blank. Instead it means that a value is absent. When you
include NOT NULL in your column definition, you’re saying that the column does not permit null
values. On the other hand, the NULL option permits null values.

The next optional element in the column definition is [DEFAULT <value>]. This option allows you to
define a value that is automatically inserted into a column if a value isn’t inserted into the column when
you create a row. When you include the DEFAULT keyword in your column definition, you must include
a value in place of the <value> placeholder.

The final optional element of the column definition is [AUTO INCREMENT]. You include this option in
your definition if you want MySQL to automatically generate sequential numbers for this column
whenever a new row is added to the table.

With regard to the three options available in the <table element> definition, the column definition is
the one you use most often. However, as stated above, you can choose any of three options, so take a
look at the second line:

| {PRIMARY KEY (<column name> [{, <column name>}...])}

The purpose of this line is to define a primary key for the table. If you choose this option, you must
include the PRIMARY KEY keywords and at least one column name, enclosed in parentheses. The
elements contained in the square brackets — [{, <column name>}...] — indicate that you can
include one or more additional columns and that a comma must precede each additional column.
For example, if you base your primary key on three columns, your syntax is as follows:

PRIMARY KEY (<column name>, <column name>, <column name>)

Don’t worry if you don’t understand how primary keys are created or how they can be made up of
multiple columns. Primary keys are discussed in detail in Chapter 5.

18 TEAM LinG - Live, Informative, Non-cost and Genuine !


Introducing the MySQL Relational Database Management System
Now examine the last optional element in the <table element> definition:

| {INDEX [<index name>] (<column name> [{, <column name>}...])}

This line creates an index. If you use this option, you must include the INDEX keyword and at least one
column name, enclosed in parentheses. As was the case when creating a primary key, you can also
include additional columns, as long as a comma precedes each additional column. However, unlike a
primary key, the index name is optional. It’s up to you whether you want to name the index, although
naming all objects in a database is generally considered a good practice.

You should now have a fairly good sense of how to interpret a statement’s syntax. As you have seen from
the table definition example, the syntax for an SQL statement can contain many elements. However,
once you’re comfortable with syntax structure and how symbols define this structure, you should be
able to interpret the syntax for nearly any SQL statement (albeit some statements might present a far
greater challenge than other statements). The next section discusses how to use this syntax to create an
SQL statement.

Creating an SQL Statement


An SQL statement can range from very simple — only a few words — to very complicated. If at any
point in the statement-creation process you’re uncertain how to proceed, you can refer to the syntax for
direction. Even experienced SQL programmers must often refer back to the syntax in order to under-
stand the subtleties of a particular statement, but once you have that syntax as a frame of reference,
you’re ready to build your statement.

Below is an example of a statement based on the table definition syntax. The following CREATE TABLE
statement creates a table named Parts:

/* Creates the Parts table */


CREATE TABLE Parts
(
PartID INT NOT NULL,
PartName VARCHAR(40) NOT NULL,
CatID INT NOT NULL,
PRIMARY KEY (PartID)
)
ENGINE=MYISAM;

The first thing to note is that the CREATE TABLE example is a single SQL statement. Notice that it ends
with a semi-colon, which is sometimes referred to as a terminator. When you access a MySQL database
directly (for example, by using the mysql client utility), you must terminate each SQL statement with a
semi-colon.

As mentioned earlier, SQL is indifferent to extra spaces, tabs, and line breaks. However, the statement is
written in such a way as to facilitate readability and to make it easier to explain each element. For example,
the table elements are indented and the opening and closing parentheses are placed on their own lines.

TEAM LinG - Live, Informative, Non-cost and Genuine ! 19


Chapter 1
The first line of code reads:

/* Creates the Parts table */

The code is merely a comment and is not processed by MySQL. (In fact, you normally wouldn’t use
comments when working with MySQL interactively, but the comment is included here to demonstrate
how they work.) It is there only to provide information to anyone who might be viewing the code.
Adding comments to your code to explain the purpose of each part or to provide any special information
is always a good idea. Comments are particularly useful when updating code you had created in the
past or when someone else is working on code that you created. Comments are also very useful if you’re
trying to debug your code.

You can also create a comment by preceding the text with double dashes (--). However, the comment
cannot include any line breaks.

As you can see from the line of code, a comment begins with /* and ends with */. Everything between
the two symbols, including line breaks, is considered part of the comment and therefore ignored by
MySQL when processing the SQL statements.

The next line of code is the first line of the actual CREATE TABLE statement:

CREATE TABLE Parts

As you can see, the line includes the CREATE TABLE keywords and the name of the new table — Parts.
If you refer to the related line of syntax, you can see how to form the CREATE TABLE clause :

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table name>

Notice that the optional keyword TEMPORARY and the optional keywords IF NOT EXISTS are not
included in the clause, only the required elements. Now take a look at the <table element>
definitions:

(
PartID INT NOT NULL,
PartName VARCHAR(40) NOT NULL,
CatID INT NOT NULL,
PRIMARY KEY (PartID)
)

This part of the CREATE TABLE statement includes four <table element> components. The first
three represent column definitions and the last represents a primary key definition. The elements are
enclosed in parentheses and separated by commas. If you compare this to the syntax, you can see
how the <table element> placeholders represent each component:

(<table element>, <table element>, <table element>, <table element>)

20 TEAM LinG - Live, Informative, Non-cost and Genuine !


Another Random Scribd Document
with Unrelated Content
“It is his Majesty’s pleasure.” He recommended it to them to consider
the circumstances, and inform the King of them.
Pitt, in reply, bad him consider all that had passed for the last six
months, and then judge if the Lords of the Admiralty were the
proper persons to make representations on this case. He had no
reason to expect any tenderness to himself or his friends; and,
indeed, he supposed this speech of Fox was calculated to throw
them under difficulties in another place. For himself, he had too
much awe on his mind, to make so free with descriptions, as Fox
had of personal colloquies.
Fox repeated, that this had been a very undue time to change the
words, “the King’s consent,” to “the King’s pleasure.” In all late
instances pleasure had never been used. That in what he had said,
he had intended to agree with Mr. Pitt. On the present occasion he
thought it particularly the duty of the Admiralty to speak out. And as
to throwing them under difficulties, the more danger there would be
in their speaking out, the more it was their duty. And to Mr. Pitt’s
complaint of want of credit in the closet, he said, there never wanted
a grain of ministerial influence to incline his Majesty to pardon.
Pitt asked, how Mr. Fox knew what might have passed on this
occasion, when not an iota had transpired? His insinuations had
been uncandid, nor had he egged Fox on to say what had fallen
from him. The Speaker interposed; said, he disapproved these
altercations, and begged they would only speak on what concerned
the public. Hunter and Elliot produced precedents to show they had
taken the word pleasure from the minutes in the books of the
Admiralty. Prince George had particularly notified Queen Anne’s
pleasure on Kirby and Wade: and the latter dropped, that it was
decided by political writers, that in general Commanders-in-Chief
should not be tried but for treachery. Lord Strange spoke to order,
and to have the question read, that these discussions might be
finished. The day concluded with Fox’s saying with great solemnity,
that he had not said, and he thanked God had not heard, a word to
exclude mercy—an asseveration he had better not have made. He
had fastened the duty of representation on the Admiralty; if they
applied for mercy, the odium would be theirs.—If they did not, the
King remained in possession of pleading; that as the Admiralty had
made no application for mercy, after being publicly exhorted to it, it
was evident that they had no favourable circumstances to represent.
The next day Pitt did move the King for mercy, but was cut very
short; nor did his Majesty remember to ask his usual question,
whether there were any favourable circumstances? The Duke of
Bedford, whose good heart broke from his connexions, applied too,
was better heard, but with no better success. Mrs. Osborn, the
Admiral’s sister, being advised to solicit the same Duke to present a
petition from her, he excused himself, nor in all the openings to
compassion that followed did his Grace take the least part; though
he had been one of the most vehement to condemn the Court-
Martial. He was always allowed by his governors to speak as he
thought—seldom to act as he spoke. The same day seven of the
Court-Martial applied to Lord Temple to intercede for mercy; he
reported their solicitation to the King, but to no purpose.
25th.—Admiral Norris went to George Grenville, and told him he
had something on his conscience which he wanted to utter, and
desired Mr. Grenville to apply to the House of Commons to absolve
them from their oath of secrecy. Grenville did not care to meddle in
it. Norris, Keppel, and Moore, mentioned it again to him at the
Admiralty that morning; and he declining it, Moore said to him with
wrath, “Then, Sir, the Admiral’s blood will not lie on us.” It happened
that Horace Walpole, who had taken this affair much to heart, was
not then in Parliament, having vacated his seat for Castlerising, that
he might be chosen at Lynn, by desire of the corporation, in the
room of his cousin, become a peer by the death of his father, Lord
Walpole. Coming late that day to the House, though not a member,
Horace Walpole was told of the application that had been made to
Mr. Grenville, and looking for him to try to engage him to undertake
the cause, Walpole was told that Mr. Keppel desired to be absolved
from his oath as well as Norris. Walpole ran up into the gallery, and
asked Keppel if it was true? and being true, why he did not move the
House himself? Keppel replied, that he was unused to speak in
public, but would willingly authorize anybody to make application for
him. “Oh! sir,” said Walpole, “I will soon find you somebody;” and
hurried him to Fox, who, Walpole fondly imagined, could not in
decency refuse such a request, and who was the more proper, from
his authority in the House, and as a relation of Mr. Keppel. Fox was
much surprised, knew not what to determine, said he was uncertain
—and left the House.
The time pressed, the Speaker was going to put the question for
the Orders of the Day, after which no new Motion can be made; it
was Friday too; the House would sit neither on Saturday nor Sunday,
and but a possibility of two days remained to intercept the
execution, which was to be on Monday; and the whole operation of
what Keppel should have to say, its effects, the pardon if procured,
the dispatch to Portsmouth, and the reprieve, all to be crowded into
so few hours! Walpole was in agony what step to take—at that
instant he saw Sir Francis Dashwood going up the House; he flew
down from the gallery, called Sir Francis, hurried the notification to
him, and Sir Francis, with the greatest quickness of tender
apprehension, (the Speaker had actually read the question and put it
while all this was passing,) called out from the floor before he had
time to take his place, “Mr. Speaker”—and then informed the House
of Mr. Keppel’s desire that some method might be found of
empowering him and the other members of the Court-Martial to
declare what had been their intention in pronouncing Mr. Byng guilty.
Sir John Philipps opposed the Motion, saying, the cause was not
before the House. George Townshend approved the question, saying
he seconded it, not pleading so much for mercy to the prisoner, as to
his Judges. Pitt rose and begged the House would consider seriously
before they proceeded on so nice a matter: he wished first to see a
direct application to the House. For himself, he should probably
smart for it; he had received a menacing letter that very morning.
He addressed himself to Keppel, wished he would break through his
bashfulness and rise: it would be a foundation to him to vote for the
Bill demanded; and then he should despise threats. Keppel rose.
Dennis, a member of the Court-Martial, and of Parliament, was
present, but had refused to join with Keppel in the application. The
latter spoke with great sense and seriousness; declared, he did
desire to be absolved from his oath; he had something on his mind
that he wished to say. Many others of the Court-Martial, he said, had
been with him that morning, and exhorted him to make the demand.
Sir Richard Lyttelton said, another had been with him to the same
end; and read a letter from the President, Admiral Smith, entreating
him to move in the same cause. He then injudiciously went into the
case of Mr. Byng, which, he said, he should think murder, if this
method was not followed. Ellis had difficulties, he said; it ought to
be known if the whole body desired this. It ought to be considered,
that their opinions had been given in confidence of secrecy. Sir R.
Lyttelton replied, Admiral Smith says they are all willing to be
dispensed from their oath.
Lord Strange said, he had always been averse to meddling with
Mr. Byng’s cause in Parliament, yet it was very difficult to avoid it,
now the Judges themselves desired it. To refuse this dispensation to
them would be a cruelty his blood ran cold at. Then the oath of
secrecy being read, Thornbagh, a foolish man, who knew to do
nothing but what he had sometimes seen done, moved for the
Orders of the Day. Sir Francis Dashwood reprimanded him severely;
and the House behaved with great decency: the Duke of Newcastle’s
faction with total silence. Campbell, whose natural goodness could
not on a surprise prefer the wrong side to the tender one, said, he
rose for fear of being included in his opinion of the other day. He
thought the Bill so necessary now, that he wished to have it read
three times directly. George Grenville thought the members of the
Court-Martial might speak without the Bill, as their oath only forbad
them to divulge the opinion of any single man. Lord George Sackville
was of the same opinion, and wished what had passed might be
communicated to his Majesty without any address in form.
Keppel professed he had still doubts whether he could speak
without a dispensing Act. Mr. Conway agreed with Lord George, and
thought that such members of the Court-Martial as were in town
ought to have a day to consider on it. Pitt said, he honoured Mr.
Keppel for his doubt; wished him to consult with his friends that
night; and told him, that in regard to them the House would sit the
next day. For himself, he should in their case have no hesitation to
speak without the Act, as they only desired to tell where it was most
proper for them to tell: he hoped they would lay their sentiments at
his Majesty’s feet the next morning. Some other opinions of no
consequence following, Lord George Sackville begged the Debate
might end, that Mr. Keppel might go immediately and consult his
friends. Sir Francis Dashwood said they were not all in town; Mr.
Keppel hoped if the major part were, it would be sufficient. The
Speaker proposed that nothing of what had passed should be
inserted in the votes.
26th.—A Cabinet Council was held to consider what was proper to
be done on Mr. Keppel’s demand. Pitt told the King, that the House
of Commons wished to have the Admiral pardoned. He replied
shrewdly and severely, “Sir, you have taught me to look for the
sense of my subjects in another place than in the House of
Commons.”—However, it was determined that sentence should be
respited for a fortnight, till the Bill could be passed, and his Majesty
acquainted with what the members of the Court-Martial had to say.
A temporary reprieve was accordingly dispatched to Portsmouth; and
Mr. Pitt the same day delivered a message to the House of
Commons, that his Majesty having been informed that a Member of
that House had in his place declared that he had something of
weight to say, which it was proper his Majesty should know, his
Majesty had accordingly postponed execution till the matter could be
cleared up. It had been objected in Council, that the words Member
in his place would give offence, as unusual and inconsistent with the
liberty of speech in Parliament, the Crown being supposed to have
no knowledge or cognizance of what is said there. Pitt treated the
objection with scorn; and, unluckily, commenced his Administration
with a German subsidy and a breach of privilege.
Fox had immediate notice by Rigby from the Duke of Bedford of
what had passed in Council, and came armed to attack Pitt on this
indiscretion. Pitt had no sooner delivered the Royal Message, than
Fox rose cavilling. He desired to have the Message read again:—
there were words in it that struck his ear in a very extraordinary
manner! The King having been informed that a Member in his place!
Who informed him? Who betrayed to the Crown what was said in
Parliament? What Minister was so ignorant as to advise the Crown to
take notice of having had such intelligence? Did Ministers dare to
avow that they made representations of the speeches of particular
men? Indeed, it had now been done for a laudable purpose; but by
the same rule might be practised for a bad one; and on no account
must be suffered to strengthen into a precedent. He desired to be
showed one instance since the reign of James the First, where the
privileges of Parliament had been so sported with.
Pitt replied with great indignation, that the time had been too
pressing to consult precedents. He had not thought the life of a man
was to be trifled with while clerks were searching records. He had
founded himself on a peculiarity of case, that was its own precedent,
and could be so to no other: a precedent that could never be
extended but by a wicked Parliament. He had been doing his duty in
Parliament the day before, had heard the momentous doubts of Mr.
Keppel, and had represented them:—he should have been ashamed
to run away basely and timidly, and hide his head, as if he had
murdered somebody under a hedge. It had been the sense of the
House, that what had passed should be laid before his Majesty; and
he had accordingly thought it his duty to represent it. What would
Mr. Fox have done? not have represented it? “You, sir,” said he, to
the Chair, “may enter it with proper caution.” He appealed to the
House, if what he had done had not been directly implied; and
concluded, that he was ready to undergo the correction of the
House.
Fox replied with as much temper as the occasion seemed to call
for resentment, (but it is not always true that one is most angry
when one is most in the wrong,) that he did not think his
observation had been indecent. That he would now say nothing to
Mr. Pitt’s charge, but would prove his own conduct good-natured.
Had he said some things that Mr. Pitt had said, he should have
thought his nature base. It had not been necessary to express a
member of the House in his place. Yet if the Speaker could think of
any palliative way of entering it in the journals, he should never
think of it more.
Pitt said, the manner had been chosen to show the public that
every method had been taken to ease the mind of his Majesty: and
Lord Strange bore him testimony, that the communication had been
intended by the House: and however Parliament would take it, he
knew it was manly and right.
Mr. Keppel then said, that the definitions given the day before of
the oath had engaged his utmost attention: and he had represented
as well as he could to some of his brethren what latitude it had been
thought they might take in dispensing with it: but they were not
altered in the least, and till an absolving Act should pass, could say
nothing.
“Do they still desire the Act?” said Lord Strange. “Could anybody,”
replied Keppel, “mention what weight they had on their minds, and
not desire it still?”
The Speaker then, trimming between Pitt and Fox, declared
himself extremely hurt with the words, pronounced them wrong, and
of most dangerous consequence, and what had always been
reckoned breaches of privilege;—he was satisfied there had been no
bad intention in it. He knew Mr. Pitt would as soon lose his hand, as
violate the rights of Parliament—indeed, there had been no necessity
for the words in question; the message might have been worded
differently; but he would pawn his soul there had been no wrong
design in it. It might be entered, observing that objections had been
made to the offensive phrase; the necessity of which might be
stated too. For Mr. Fox, he had done his duty, and himself would do
public right to him. “I did the same justice to Mr. Pitt,” said Fox.
General Conway agreed that there had been little occasion to
describe so particularly what had passed; and he asked whether it
was necessary to enter the whole of the Message.
“The House,” said the Speaker, “may enter what it pleases; but it
is a Message sent solemnly by the King, and I never knew an
instance of overlooking it.” George Grenville went farther, and said,
he would never consent to have it entered defectively. Beckford
called the Bill so unpopular a measure, that he wished to have it
imputed to the House of Commons, not to the King, who, he desired
it might be reported, had yielded to it unwillingly, and only for the
sake of justice: Pitt he commended. Sir Francis Dashwood, with
much more sincerity, said he was glad of the Bill, come how it
would. It was gracious of the King to give room for it, and wise of
his Ministers. Fox asked, now the respite was granted, whether it
were not better to wait for a petition from the Court-Martial before
the Bill was passed? better to wait at least till Monday for some
material information, which might be hinted in the petition. Sir
Francis replied, that the very words of the Message from the Crown
were, that a respite was granted till the Bill should pass. Would it be
decent, after such a message, to say we will postpone the Bill,
however, till the Court-Martial petitions? If six only of the thirteen
should desire the Bill, would you not grant it? The House cried, “No,
no!”—as if it was justice due to the consciences of an indefinite, and
not of a determined number!
Nugent said, his constant opinion had been, that the Admiral was
sentenced for error of judgment only; and the oath he thought only
a conditional one.
Fox, after refining much on the oath, said it was impossible but at
the desire of the whole number, to permit some to disclose the
opinions of others. Each man might tell his own motives. At least, let
the desires of the majority be taken. He then asked if it was proper
that a set of Judges should go about for three weeks, hearing
solicitations from the friends of the prisoner, and then come and
complain of their own sentence? For his part, his feeling sometimes
operated upon his reason, and, he supposed, did on that of others.
See, then, whither solicitation and bribery might go. The King
desires to have his doubts cleared up—but don’t let this Bill go
immediately to pardon. Give way to the Bill—what was to follow
would be a subsequent consideration. The Court had gone no farther
than to acquit the Admiral of cowardice. He hoped the Parliament
would ask the King for the examination, either, to rescind the
sentence or to order a new trial. He had not, he said, run away
basely the day before, but from his judgment: Mr. Keppel had told
him what he meaned to do. He did not think himself necessary to
every council, and had foreseen what confusion would follow. He
had not voted against the Bill, and said, “Let Mr. Byng die on
Monday.” He had gone away, his compassion struggling with his
reason. On consideration, he had returned like a man to the hard
part. If the King had felt, was it not proper he should feel too? He
begged care might be taken not to establish this measure for a
precedent; nor could it be reasonable to frame a new Article of War,
because the Court-Martial had not understood the present. He
should be for the Bill, though he would not (like Mr. Pitt) declare that
most good would follow from pardon. Hearing a great Minister say
so, he thought pardon was determined. Yet, for himself, he should
have left the merit of it to the King’s mercy—but now it was the act
of the Minister. He still wished to see more grounds for the Bill. He
would not require any of the members of the Court, he would only
enable such as thought fit, to discover what had passed. Something
extraordinary he would have to conclude this extraordinary act.
The art and abilities of this speech are evident: it will be much
more difficult to discover in it the good-nature he had promised to
display.
Nugent expressed his disapprobation of two trials. Pitt declared he
would speak very shortly and clearly; sometimes, he owned, he did
speak too warmly. He gave much commendation to Mr. Fox’s speech,
though he did not foresee the same consequences; nor would he
decide, whether in the present instance Fox’s reason or good-nature
had got the better. He defended Mr. Keppel’s behaviour, which had
sprung from former proceedings, not from solicitation. [For] himself,
[he] did not wish the Admiral saved out of compassion, but out of
justice: “for how,” said he, “can it be for my interest to take the part
I now do?—I look only at the sentence. Is it so necessary that he
should be executed just now?” On the other hand he would not give
time for the Court-Martial to be tampered with. Like Fox, he had
wished for better grounds; but when Mr. Keppel rose and
pronounced what he did, it was irresistible. It became the
unanimous opinion of the House to yield to his emotions. Some even
would have passed the Bill that very day. Nor had anything ever
come before Parliament that almost commanded such rapidity.
“Ought not,” said he, “Mr. Byng, ought not his family, to be put out
of that cruel situation? ought not the King? ought not the Court-
Martial, some of whom were on the point of sailing to America? Why
hang this matter up for some days, in which the fate of the nation
might be decided?” There was nothing of party in this—any number
that were willing to tell, ought to be heard: might not they want to
say that they had thought themselves bound to find error of
judgment capital? To them he would have the Article explained. He
feared, if this was pending too long it might produce riots.
Henley, the Attorney-General, endeavoured still to show that the
Bill was unnecessary, and that the members might dispense with
their oath. He suggested that the Bill might be rejected in the other
House; and asked, who was to examine the members of the Court-
Martial?
Doddington said, he had sought compassion and relief—had found
compassion even when he called; but relief could only come
constitutionally through justice. The Court-Martial indeed did at last
perceive that they might have been mistaken. Were he in their
place, he should not have waited for a Bill—he should have thought
a life was to be saved at any rate.
Legge declared himself free from any bias one way or other. Had
Mr. Byng been found guilty, nobody would be more ready to
condemn him: but it appeared that he was only a sacrifice to
discipline; and we must not imagine that we should draw down
blessings on our Fleets by human sacrifices. He begged that, by
adhering to the letter of this Article, demonstrated to be both
obscure and severe, they would not prevent Courts-Martial from
bringing in nobody guilty.
Martin proposed that the members of the Court should be asked
directly, if they had meant error of judgment: and then, if they
thought error of judgment capital.
Lord George Sackville begged the Debate might finish, as the
longer the question was agitated, the more difficulties would be
started. Potter accordingly brought in the Bill, and it was read the
first time. Fox then asked Mr. Keppel, which of his associates had
empowered him to make the demand? He named, Holmes, Norris,
Geary, and Moore. Fox said he asked this, because it was reported
that none of the members desired to be absolved from their oath.
The Bill was read the second time. Fox said, the King’s message
prescribed a separate examination on oath; he hoped that direction
would be observed. Potter moved to proceed to the Committee on
the Bill. Lord Strange and Haldane objected; but Pitt asking if they
wished to detain Holbourn, Broderick, and Holmes at home at so
critical a time; and how they could proceed on Monday, if their
difficulties were not then stated in the Committee; it was agreed that
the Committee should immediately sit; and Fox said, that now it was
agreed to have the Bill, the sooner it should pass the better. He
moved, and was seconded by Pitt, that the members of the Court-
Martial should be examined on oath. It was then settled that they
were to disclose what they had to say only to the King and Council:
that they should only tell the motives of their own behaviour, not
those of others. George Grenville added a clause, that they should
not be obliged to speak, if not willing. The Bill went through the
Committee, and was ordered to be reported on Monday.
It may easily be imagined what variety of passions were excited
by this extraordinary affair. Curiosity to know what black
management had left such[77] scruples on the minds of some of the
Judges of the Court-Martial, was the common and natural
consequence: the very novelty of tools of power sinking under a
consciousness of guilt, or under the conviction of having unwittingly
been made the tools of power, was sufficient to raise the utmost
attention. The few poor well-wishers of the condemned saw a gleam
of truth darting upon a prison which they had scarce ventured to
incur the odium of approaching—and if there had been such black
management (a question scarce admitting an if, considering all that
had preceded and all that followed) the actors in so dark a tragedy
undoubtedly did not feel the most pleasing sensations from the
illustration that now seemed unavoidable. The latter description of
men appeared to be in danger of changing unpopular situations with
the Admiral—they were soon the only satisfied class, the only
triumphant—for by the very next day after the Bill had been read in
the House of Commons, by Sunday evening it was blazed over the
town, that the four sea-officers named by Mr. Keppel disclaimed him,
and denied having empowered him to apply in their names. Mr. Pitt
was thunderstruck—and well he might: he saw what consequences
Fox would draw from this disavowal. Enquiry was made into the
truth of the report. Holmes and Geary persisted that they had not
commissioned Keppel. Sir Richard Lyttelton, an intimate friend of the
latter, applied to him, and, as Sir Richard himself told me within an
hour after he had seen Geary, begging him to consider the injustice
and dishonourableness of retracting what he had authorized Keppel
to say; he replied in these very words, “It will hurt my preferment to
tell.”
Can I pass over these words cursorily?—or rather, do they want a
comment? What dissertation could express more fully than they do
themselves all they contained? Who had power to stop a sea-
officer’s preferment? would it hurt his preferment to tell what
affected no[78] powerful man with guilt? Did those words imply that
he had nothing to tell? As thick a veil as was drawn over the
particulars of this transaction, can it be doubted but that particulars
there were of a heinous dye? And though Mr. Keppel’s scruples were
treated as idle, though it was asserted that he had nothing to tell,
though he saw Mr. Byng die, without telling; did not that attention of
Geary to his interest supply articulation to Mr. Keppel’s conscience?—
a fact that I shall mention presently, when the father[79] of the man
whose power Geary dreaded, asked for a day of peculiar
significance, will explain and cannot in the nature of things be
disjoined from that sagacious captain’s conception of what interests
were concerned to impose silence on the Court-Martial.
Monday, 28th.—The Bill was reported, and Potter moved to have it
read the third time; when Fox rising, said, he heard some
information was going to be given, which ought to precede any
progress in the Bill. Holmes, a brother of one of the four, said, he
had heard something had passed on Saturday, which he supposed
the gentleman that had occasioned it would stand up and explain.
Keppel rose, and said, he had particularized the names of four, who
he understood and did believe had commissioned him to move the
House on their behalf. That Holmes had said, “Sure you mistook
me!” Another of them said the same. He argued it with them; they
persisted, and said he had mistaken: Holmes adding, “I am easy in
my mind, and desire to say nothing farther.” That he believed it
would be useless to call Mr. Holmes. That for Geary, he was not
absolutely off nor on, but should have no objection to speak if all
were compelled. For the other two, Norris and Moore, they were
desirous to abide by what they had said; that they had even written
him a letter, in which they said, “The world says we have varied, but
we desire to adhere to what we told you.” He read their letter, in
which were these words: “We do authorize you to solicit for the Bill.”
For himself, he thought his honour clear: when he had first spoken,
it was from the uneasiness of his mind. He was told his oath did not
bind him: he thought it did. If the House would think fit to relieve
him, he should be glad. When he signed the sentence, he thought
he did right—he had since been startled at what he had done.
Thus, of the four named, two adhered: one (Geary) did not prove
that Keppel mistook him. Whether he mistook Holmes must remain a
doubt—it is scarce probable that Holmes had been very positive
against the measure: Keppel would scarce have named a man, who
was far from agreeing with him. That it will remain a doubt too,
whether there had not been unwarrantable practices in, or even
with, the Court-Martial, is the fault of those who stifled conscientious
evidence. Charity itself would grow suspicious, had it observed all I
observed; and yet I give but as suspicions what I do not know was
fact. That some wished for time to practise afterwards on the Court-
Martial; that Geary was willing to be practised on; and that some
were practised on before they appeared in the House of Lords, can,
I think, never be a doubt more.
Fox assured Mr. Keppel that his character was not affected by
what Holmes and Geary had said: the Bill indeed was affected by it:
yet what he would have done for five, he would do for three; that is,
if the three would petition for it. Of the Court-Martial, seven, he
observed, were in town. Of them, Holbourn had declined to meddle;
Dennis had withdrawn from the House; Holmes declared himself
easy in his mind; Geary had desired not to speak, unless the whole
number did. Thus a majority of those in town did not approve the
Bill. He therefore desired that the three willing ones would sign a
petition, saying, in their opinions they had something to tell material
for the King’s information. If it was not material enough to have the
sentence reversed, but only that they might explain their own
motives, he should not think the Bill necessary.
Nugent said, though not one should apply, the absurdity of the
sentence was glaring enough to call for the Bill. Fox interrupted him,
speaking to order—the sentence was not before the House. Nugent
replied, every man in the House had read the sentence—could they,
who, in conscience, honour, and justice, had signed the letter for
mercy, refuse to speak if their mouths were opened? Fox said, the
sentence and letter ought first to be called for. The sentence was on
oath, the letter not. He affirmed he did not believe they had
anything material to say. Would Mr. Keppel say he thought it
material?
Velters Cornwall condemned the Bill, and said, Mr. Byng had
undone one Ministry, was going to undo another: the King had been
advised ignobly and unwisely.
Colonel John Fitzwilliam, who had never opened before in
Parliament, came with much importance and a list of questions to
examine Mr. Keppel; but they were so absurd and indecent, that at
every one the House expressed their disgust by a groan—such were,
“Had he not voted Mr. Byng to be shot because he thought he
deserved it? Did he not think so still? Would his conscience be easier
after he had spoken?”—It is sufficient to say of this man, that his
character was hateful. In the Army he was odious as a spy and
creature of the Duke. That very morning he had passed two hours
with Mr. Keppel, labouring to divert him from his purpose. Stanley
severely censured Fitzwilliam, observing that he had put many
questions to Keppel, which he was under oath not to discover, and
from which this Bill was calculated to absolve him: and he took
notice sensibly, (of what seemed to have been totally overlooked,)
that any man who is to die, has at least a right to know for what he
is to die. Fox urged, that the words of the Royal Message were,
“because their discovery may show the sentence to be improper.”
From Mr. Keppel’s present silence, he inferred that there was nothing
material to be discovered. He moved to call Norris and Moore, to
hear if what they had to say would affect the sentence. But Sir
Francis Dashwood objected, that this was the very question which
the House was passing the Bill in order to have answered. Mr. Keppel
(who Mr. Fox might have suspected had had other solicitations than
from the relations of the Admiral) rose, and said, he would explain
himself as fully as he could:—when he signed, he thought he did
right—he would go further—no, he had better not—had uneasiness,
or would never have signed the letter of intercession—the
explanation of the Article has increased his inquietude—he had
rather it should be thought poor weakness than a desire of giving
trouble. He concluded with these words: “I do think my desire of
being at liberty does imply something great, and what his Majesty
should know.” The House was struck:—Fox said, “I am satisfied.
Afterwards I shall propose means to prevent such Bills for the
future.”
Charles Townshend, who had taken no part hitherto, and who had
followed Mr. Pitt into a system built on the ruin of Mr. Fox, said, to
the surprise of everybody, that he had intended to second Fox, but
was content too. He congratulated the House on obtaining these
grounds for their proceedings by Mr. Fox’s means. His brother,
offended at this wonderful declaration, told him, if he had been
present the first day, he would not have wanted those grounds.
Charles appealed to the House, if first, second, or third day, they had
been so fully explained. Pitt, still more provoked, said, with the
utmost contempt, and with the most marked accent, no man of
common sense or common integrity could say this matter had been
opened on any other foundation—yet he wished Charles Townshend
joy that his conscience was made easy. But how did it appear that
the King was so misinformed? “May I,” added Pitt, “fall when I refuse
pity to such a suit as Mr. Keppel’s, justifying a man who lies in
captivity and the shadow of death! I thank God, I feel something
more than popularity; I feel justice!” The Message, he owned, had
been disorderly, and he was under correction for it, yet it was strict
truth. For this attack, it went to the very veracity of a man: but he
did not, like Fox and Townshend, go upon hearsay. For his part, if his
country were safe that day twelvemonth, he should pray that Mr. Fox
might be in his place, nor would he use those miserable arts that are
employed to prop a wretched station. He congratulated the House
on that act of necessary justice. His equal wish was, that Mr. Byng
might live or die to the satisfaction of the nation.
Fox, sneering and insulting, said, he was glad Mr. Pitt had heard
commendations of him from Mr. Charles Townshend[80]—indeed they
had a little ruffled Mr. Pitt’s temper. By his wishing to continue in the
Administration for a twelvemonth, he seemed to think he could save
this country. For himself, he had not been driven out; he had had
reasons for retiring. Since, had he obstructed any public measure?
Had he, totidem verbis, proposed some questions that had been
opposed last year, they would have been opposed again: he had
chosen rather to retire; and in the distressed situation of his country,
would not oppose; unless he saw measures carried on destructive to
England, or distressful to his Majesty. His own consistence should be
literal, lest afterwards he should not have parts enough to show it
was substantial—indeed, he had never understood a Court.
The Speaker observed, that two-thirds of what both had said, was
nothing to the question. Pitt replied, that he was surprised at being
coupled with Mr. Fox, who had spoken five times, he but once—yet
Fox had not been suppressed. “Could I,” said he, “sit silent under the
accusation of misinforming the King?” The Speaker vindicated
himself, talked of his unbiassed impartiality and integrity; and the Bill
passed, Cornwall dividing the House with 22 more against 153; and
it was sent to the Lords.

F O OT N OT E S :
[76] Indeed they could not with much consistence condemn him
of neglect, after they had previously and unanimously voted the
following resolution, which was their 25th:
“The Court are of opinion, that while the Ramillies (the Admiral’s
own ship) was firing in going down, the Trident and ships
immediately ahead of the Ramillies proved an impediment to the
Ramillies continuing to go down.”
It was proved, too, beyond contradiction, that he could not
foresee that the French fleet would not stay for him, as they
remained with their sails aback to the mast; and that he must
have been up with them in ten or fifteen minutes, if the
impediment had not happened from the Trident and Princess
Louisa.
[77] I do not mean to say that none of the Judges on the Court-
Martial had really been convinced that by the severity of the law
they could not acquit the Admiral, though they thought him guilty
of only a momentary error of judgment.
[78] I say, powerful man, not man in power, for Lord Hardwicke,
Lord Anson, the Duke of Newcastle, &c., were not then in place—
but them Geary must have meant, for he could not fear
disobliging Mr. Pitt and Lord Temple by speaking out, when it was
his silence that prejudiced them. It was plain Geary thought, what
happened so soon afterwards, that the command of the Admiralty
would still be in Lord Anson.
[79] [Lord Hardwicke. Lord Anson had married his daughter. It
must, however, be admitted, that our author’s language in this
passage is as obscure as his reasoning is unfair and inconclusive.
—E.]
[80] Mr. Pitt, loud enough to be heard by half the House, cried
out, “I wish you joy of him.”
CHAPTER XI.

Debate in the House of Lords on the Court-Martial Bill—Lord Mansfield—Proposal


to examine the Members of the Court-Martial—Their Examination—Bill debated
and dropped in the House of Lords—Result of the Proceedings in Parliament—
Intended Petition for Mercy from the City not proceeded with—Execution of
Admiral Byng—Reflections on his behaviour—Rochester Election—Death of
Archbishop Herring—Abolition of the Office of Wine-Licences—Intrigues to
dismiss Mr. Pitt, and form a new Ministry—The Duke of Cumberland goes to
Hanover to command the Army.
March 1st.—The Lords read the Bill. Lord Mansfield treated
Keppel’s behaviour as weak and inconsistent: made a panegyric on
the twelfth Article, which he said had restored discipline: censured
the House of Commons for precipitate proceedings; and went
indecently into the question of the Admiral’s behaviour; for which he
was called to order by Lord Denbigh, who told him, that to evade
the pressing arguments that called for the Bill, he had endeavoured
cruelly to raise indignation against the prisoner, who might receive
benefit from the scruples of his Judges; whose scruples and request
were alone the objects before the House. The Chief Justice replied,
he did not intend to oppose the whole Bill—but he must ask, who
they were that demanded it? What! a month[81] after sentence!—
was what they had to say within the oath of secrecy? Indeed, he
had always been against the oath; he never approved judging in a
mask. He had heard of a case where a majority voted that a
sentence should be unanimous. He said the proviso, empowering
only the willing to speak, was partial. If all should say they meaned
error of judgment, the Admiral ought to be acquitted. If the
sentence was iniquitous, it ought to be annulled. But it was cruel to
fix this examination on the King: the Lords ought to step between
the Crown and the people. The sentence, he said, could only be
annulled by Parliament. A Bill might be necessary, but one totally
different from this. He proposed to have the members of the Court-
Martial called to the bar of the House; and he concluded with no
humane observations, nor more to the Bill than his former speech,
that there had been times when a sea-officer had blown up his ship,
rather than be taken, or retreat.
As I would by no means blend in one censure the behaviour of the
two lawyers, Mansfield and Hardwicke, I will here say a few words
on the former. He took a severe part against the persecuted Admiral
—why, I pretend not to determine. As the death of Mr. Byng tended
no ways to his interest, as he had no guilt to expiate by the blood of
another, and as friendship infuses humanity, but not cruelty, one
should not suppose that Lord Mansfield acted on personal motives,
or from a desire of screening Newcastle. I will not even suppose that
a propensity to thwarting Pitt dictated his asperity. He saw his
country undone; might think Mr. Byng had hastened its fate; might
feel a national resentment; might think severity necessary; and as it
is observed that timorous natures, like those of women, are
generally cruel, Lord Mansfield might easily slide into rigour on this
as he did on other occasions, when he was not personally afraid.
Lord Temple gave much the same account that I have given, of his
own behaviour, as first Lord of the Admiralty; he read the letter from
the Court-Martial, and thought that their anxiety must have
proceeded from having meant error of judgment.
Lord Halifax spoke strongly for the Bill, and urged that it was
founded on justice and humanity; condemned the sentence, and
said, it appealed from itself. That if the Judges of that Court had
thought the Admiral really guilty, they had been most guilty to write
such a letter. As that could not be the case, could their Lordships
avoid wishing to have the bottom of such a strange transaction
known? He excused the Court-Martial for having stayed so long
between their letter and any farther step, because they waited to
see what effect, and concluded the effect they promised themselves
would follow from their letter. That the sentence could not be
annulled without this Bill, nor explained without it, for had it been
possible for any man, Lord Mansfield would have made sense of it.
Lord Hardwicke pleaded against the Bill, upon the single
supposition that they were to tell the opinions of each other. He
desired that all of them might be ordered to attend, and asked
whether these scruples had not flowed from solicitations, and from
being tampered with by the Admiral’s friends—and he, who said he
wished to inquire whether they had not been tampered with by the
Admiral’s friends—proposed—what? that they should not attend till
Thursday—it was then Tuesday.
Lord Granville replied, that they would not speak even there, till
their mouths were legally opened. That he had always disapproved
the oath of secrecy; and now particularly, when his Majesty and the
House of Commons were willing that the oath should be set aside,
who could refuse it?
The Duke of Newcastle, as usual, echoed his oracle, and wished to
have all the lights that could be had in twenty-four hours. The Duke
of Bedford asked what objection there was to hearing them the very
next day? There could but two questions be asked of them: “Were
they willing to speak?” “Had they anything to say?” Lord Halifax
pressed for the next day. Lord Temple defended them from private
influence, and proved that their present behaviour was entirely
consonant to their sentence and letter. When they found that all the
difficulties on their minds, which they had hinted at in their letter,
had no effect, could they do otherwise than apply to the Legislature
to be empowered to set forth their difficulties at large? Lord
Sandwich owned, that if he did not think the Bill necessary, he would
oppose it, because he was astonished to find that an unprecedented
message to the Commons was pleaded as a reason for the
acquiescence of the Lords.
Lord Hardwicke caught up that argument, and said the Royal
Message ought not to be pleaded there, since it had not been
vouchsafed to that House. I hesitate to repeat the latter part of his
speech. Will it not be thought that the part I took in this affair
influenced me to misrepresent a man, to whose intrigues and
authority I cannot help imputing in great measure the Admiral’s
catastrophe? Who, when I paint a shrewd old lawyer, as weakly or
audaciously betraying his own dark purposes in so solemn an
assembly, but will suspect that I forged an event which seems so
strongly to prove all that I have charged on him? In answer to these
doubts, I can only say, that this was one of the events on which I
formed my opinion; that it is strictly true; and that I would not
venture to report it, unless it had passed in so solemn and public a
place as the House of Lords, where all who there were present
heard, and could not but avow that I speak truth—in short, Lord
Hardwicke, as a reason for deferring to hear till Thursday the
members of the Court-Martial, pleaded that there was an Irish cause
depending before the House, which was appointed for the next day,
(Wednesday.) If ever the least public business that pressed, had not
made all law-suits give way, this might have been at least a
precedented reason. But what was the Bill in question? Certainly in
the then situation of affairs of as critical importance, and of as much
expectation as had ever engaged the attention of the public; and to
want to postpone it to an obscure Irish cause! Could good-nature in
person forbear to surmise, that this demand of an intervening day
was, could only be made, to gain time to tamper with the witnesses?
Good-nature at least, would allow, that who suspects such men as
Geary of being tampered with by the poor and powerless relations of
a criminal, might be suspected of a disposition to tamper, when he
had power,[82] and only wanted time; which too he had the
confidence to demand—I say confidence, for Lord Hardwicke said
authoritatively, “I adhere to Thursday.” Alas! he did not know how
much he could do in half the time.
Lord Denbigh asked with indignation, “does that noble Lord put in
competition with the honour of his country a cause of Irish
bankruptcy?” And the Duke of Devonshire begged that the Court-
Martial might be heard on the morrow, because some of them were
under sailing orders. Lord Hardwicke, unmoved, said, “the Bill will
not be before you to-morrow: the officers in question must be
examined separately.” Lord Temple replied, that the wind might
change by Thursday, and that some of them were going on
expeditions of the utmost consequence to this country. He begged
their retardment might not be laid at his door. He repeated the
urgency of their sailing. The Duke of Bedford desired then to have
the orders of the House reversed, and to have the second reading of
the Bill fixed for the morrow. Lord Hardwicke (who, if I have
suspected him wrongfully, was at least conscientiously impatient to
do justice on those Irish bankrupts) persisted; and maintained that
the orders could not be reversed, unless every Lord present
consented. Have I dared to forge all this? The rest of the Lords, who
did seem to think that winds and that fleets sailing in their country’s
cause were of more instant importance than a case of Irish
bankruptcy, prevailed even on the late scrupulous Chancellor to
postpone private justice for one day, and the Court-Martial were
ordered to attend the next.
March 2nd.—The day opened with a complaint preferred by Lord
Sandwich against the publisher of a newspaper, who had printed the
oath of secrecy with false additions. Lord Mansfield took on himself
the management of the examination. To combat his ability and
Hardwicke’s acrimony, the unhappy Admiral had no friend among the
Lords but the Earl of Halifax; honest and well-disposed, but no
match for the art of the one, or the overbearingness of the other,
and on too good terms with both to oppose them in a manner to do
any service; and Lord Temple, circumscribed both in interest and
abilities from being thoroughly useful. The Chief Justice acquainted
the House that the questions he proposed to put to the members of
the Court-Martial were, “Whether they knew any matter previous to
the sentence, which would show it to be unjust, or procured by any
unlawful means? and, whether they thought themselves restrained
by their oath from disclosing such matter?” Lord Temple said,
“Everybody would be at liberty to ask any other questions;” and Lord
Halifax said, “They would not be confined to those of Lord
Mansfield.”
Admiral Smith, the President of the Court, was then called; a grey-
headed man, of comely and respectable appearance; but of no
capacity, of no quickness to comprehend the chicanery of such a
partial examination. He, and the greater part of his comrades, were
awed too with the presence of the great persons before whom they
were brought. Moore, and one or two others, were neither awed nor
haggled with their inquisitors. Lord Morton caused the twelfth Article
to be read; and would have asked Admiral Smith, whether he then
thought, or ever did think, that Article applicable to error of
judgment? The impropriety of the question, and the intemperate
warmth of the Lord who put it, when he was checked by Lord Talbot,
broke in on the solemnity of the scene, and disturbed it. Lord
Temple observed, that Smith had already answered the Earl’s
question by stating in their letter the words, even by error of
judgment. Lord Hardwicke said, that letter was not an oath, and
hoped would be out of the question; yet he owned the interrogatory
was most improper. Lord Temple insisted that they were under the
virtue of their oath till the sentence was pronounced, and they were
dissolved as a Court.
Lord Mansfield then asked the President, whether he knew any
matter previous to the sentence which would show it to be unjust.
He answered, “Indeed I do not.” Lord Mansfield—“If it was given
through any undue practice?” Admiral Smith—“Indeed I do not.”
Lord Halifax then asked him, if he desired to have the Bill? He
replied, “I have no desire for myself. It will not be disagreeable to
me, if it will be a relief to the consciences of any of my brethren.”
Lord Halifax asked him farther, whether he could reveal anything
relative to the sentence, that was necessary for the King to know,
and to incline him to mercy? The Admiral said, “Indeed I have not,
farther than what I wrote at that time to Lord Lyttelton, signifying
that we were willing to attend, to give our reasons for signing that
letter.” Lord Lyttelton said, “He had returned that letter to the
Admiral, that he might read it there.” Lord Hardwicke asked, whether
he thought himself restrained by his oath from mentioning those
reasons? He answered, “The application for mercy was unanimous. I
think I am at liberty to give the reasons why I requested that
mercy.” Nobody chose to ask him those reasons—the friends of Mr.
Byng, one must suppose, lest it should interfere with the necessity
of the Bill. His enemies did not desire to know themselves, or that
anybody else should.
Admiral Holbourn was then called, and to the two former
questions of Lord Mansfield, and to the two of Lord Halifax,
answered bluntly, “No.”
The next that appeared was Admiral Norris; a most weak man,
who after resisting, from the friends of Mr. Byng, great solicitations
to interpose in time in favour of the prisoner, to whom he was
believed the best disposed, (except Moore, the greatest professor of
tenderness to Mr. Byng’s family,) had at last sunk under great
inquietudes of remorse; and had pressed most earnestly for
parliamentary relief. If in effect he overturned all the consequences
of that compunction, he was to be pitied more than blamed. Struck
with awe of the tribunal before which he appeared, he showed how
little qualified he had been for a Judge, when so terrified at superior
Judges. He lost all comprehension, understood no questions that
were asked, nor knew how or when to apply the very answers he
came prepared to give. When Lord Mansfield put his question to
him, whether he knew anything previous that would show the
sentence to be unjust, he replied, that he desired to be excused
from answering while under the oath of secrecy. Lord Mansfield said,
to what did he apprehend his oath went? had he anything to tell, if
released from the sanction of it? Lord Fortescue objected, that
nobody had a right to ask him his reasons for desiring to be
absolved from his oath; and Lord Ravensworth said, an answer in
the affirmative would look like accusing himself—indeed it was
difficult to know how the Court-Martial could complain of what they
had done or submitted to, without accusing themselves in the
heaviest manner. Lord Hardwicke declared, if this question was not
answered, that he would vote against the Bill. “And why,” said he,
“are these excuses made for Mr. Norris? he does not make them for
himself. Ask him in the very words of the Bill.” It was evident that
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like