MYSQL - Adding Field Modifiers and Keys

A number of additional constraints, or modifiers, can be applied to a field to increase the consistency of the data that will be entered into it and to mark it as “special” in some way. These modifiers can either appear as part of the field definition, if they apply only to that specific field (for example, a default value for a field), or after all the field definitions, if they relate to multiple fields (for example, a multicolumn primary key).

• To specify whether the field is allowed to be empty or if it must necessarily be filled with data, place the NULL and NOT NULL modifiers after each field definition.

• To specify a default value for a field, use the DEFAULT modifier. This default value is used if no value is specified for that field when inserting a record. In the absence of a DEFAULT modifier for NOT NULL fields, MySQL automatically inserts a nonthreatening default value into the field.

• To have MySQL automatically generate a number for a field (by incrementing the previous value by 1), use the AUTO_INCREMENT modifier. This is particularly useful to generate row numbers for each record in the table. However, the AUTO_INCREMENT modifier can only be applied to numeric fields that are both NOT NULL and belong to the PRIMARY KEY. A table may only contain one AUTO_INCREMENT field.

• To specify the character set for fields containing string values, use the CHARACTER SET modifier.

• To index a field, use the INDEX modifier. When a field is indexed in this manner, MySQL no longer needs to scan each row of the table for a match when performing queries; instead, it can simply look up the index. Indexing is recommended for fields that frequently appear in the WHERE, ORDER BY, and GROUP BY clauses of SELECT queries and for fields used to join tables together.

• A variant of the INDEX modifier is the UNIQUE modifier, which is a special type of index used to ensure that values entered into a field must be either unique or NULL.

• To specify a primary key for the table, use the PRIMARY KEY modifier. The PRIMARY KEY constraint can best be thought of as a combination of the NOT NULL and UNIQUE constraints because it requires values in the specified field to be neither NULL nor repeated in any other row. It thus serves as a unique identifier for each record in the table, and it should be selected only after careful thought has been given to the inter-relationships between tables.

• To specify a foreign key for a table, use the FOREIGN KEY modifier. The FOREIGN
KEY modifier links a field in one table to a field (usually a primary key) in another table, setting up a base for relationships. However, foreign keys are only supported in MySQL’s InnoDB storage engine; the FOREIGN KEY modifier is simply ignored in all other engines.

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

Specifying MYSQL Field Data Types

When creating a MySQL table, specifying a data type for every field is necessary. This data type plays an important role in enforcing the integrity of the data in a MySQL database and in making this data easier to use and manipulate. MySQL offers a number of different data types, which are summarized below.

TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT : Integer values
FLOAT : Single-precision floating-point values
DOUBLE : Double-precision floating-point values
DECIMAL : Decimal values
BIT : Bit-field values
CHAR : Fixed-length strings up to 255 characters
VARCHAR : Variable-length strings up to 255 characters
TINYBLOB, BLOB, MEDIUMBLOB, LONGBLOB : Binary data
TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT : Text blocks
DATE : Date values
TIME : Time values or durations
YEAR : Year values
DATETIME,TIMESTAMP : Combined date and time values
ENUM,SET : Predefined sets of values

Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MySQL Applications

MySQL’s technical architecture, built as it is around the three tenets of performance,
reliability, and ease of use, have made the product extremely popular, both on and off the Web. According to the MySQL website, more than 100 million copies of MySQL have been downloaded and distributed to date, and 50,000 more are added to that total every day. MySQL software today powers a variety of applications, including Internet websites, e-commerce applications, search engines, data warehouses, embedded applications, high-volume content portals, and mission-critical software systems.



Web Applications
It should come as no surprise that MySQL’s primary applications today lie in the arena of the Web. As websites and web-based distributed applications grow ever more complex, it becomes more and more important that data be managed efficiently to improve transactional efficiency, reduce response time, and enhance the overall user experience. Consequently, a pressing need exists for a data management solution that is fast, stable, and secure—one that can be deployed and used with minimal fuss and that provides solid underpinnings for future development.

MySQL fits the bill for a number of reasons. Its proven track record generates confidence in its reliability and longevity; its open-source roots ensure rapid bug fixes and a continued cycle of enhancements (not to mention a lower overall cost); its portability and support for various programming languages and technologies make it suitable for a wide variety of applications; and its low cost/high performance value proposition makes it attractive to everyone from home users to small- and mediumsized businesses and government organizations. For these reasons and more, MySQL is a key component of modern web applications, particularly those built on the popular LAMP stack.

Wondering what a LAMP stack is? Well, the term refers to a set of open-source software components that are commonly used in conjunction with each other to build web-based applications. These components are
• A base operating system and server environment (Linux)
• A web server (Apache) to intercept HTTP requests and either serve them directly or pass them on to the PHP interpreter for execution
• A database engine (MySQL) that holds application data, accepts connections from the application layer, and modifies or retrieves data from the database
• A programming toolkit (PHP, Perl, or Python) that parses and executes program code, processes database results, and returns results to the client



Data Warehouses
As the opening paragraph in this chapter notes, businesses are becoming more and more intelligent in how they store, filter, and use information. Data warehouses are a key source of this business intelligence. Typically, data in a data warehouse is gathered from an enterprise’s internal information systems, linked, and stored for long periods of time. In its simplest form, this data merely provides a record of past events; however, it can also be “mined” to detect patterns, which serve as input into an organization’s decision-making. Speed of data retrieval is thus one crucial component of a data warehouse; long-term reliability is another.

MySQL scores high on both counts. It supports engine-level data integrity through the use of primary key and foreign key constraints. An extremely efficient querycaching mechanism dramatically enhances response times for queries that are called upon to retrieve the exact same data as a previous query. MySQL InnoDB table format uses asynchronous I/O and a sequential read-ahead buffer to improve data retrieval speed, and a “buddy algorithm” and Oracle-type tablespaces for optimized file and memory management. For data storage reliability, MySQL supports replication, a data distribution mechanism that places copies of tables and databases in remote locations to reduce downtime in case of a server failure.



Business Applications
As a reliable, feature-rich database server, MySQL also has applications in business, education, science, and engineering—a fact amply demonstrated by its customer list, which includes such names as Motorola, Sony, NASA, HP, Xerox, and Silicon Graphics. Whether it is small, embedded applications or high-availability data processing systems, MySQL offers the scalability and performance needed to achieve business objectives. The MySQL website states that “MySQL scales to deal with billions of rows and terabytes of data, making it suitable for a wide range of transactional and analytic applications.”

To take advantage of multiprocessor architecture, MySQL is built using a multithreaded design, which allows threads to be allocated between processors to achieve a higher degree of parallelism. MySQL’s clustering technology allows data to be distributed across multiple nodes to achieve greater redundancy, while its fully ACID-compliant transactional engine provides a high degree of safety from undetected data loss. At the other end of the scale, MySQL’s embedded server library has a 1-MB memory/4-MB disk space footprint and provides a multithreaded, cross-platform data storage engine for use in kiosk-style applications or appliances. Finally, MySQL uses a two-tier privilege system (at the connection level and at the individual object level) to ensure the security and integrity of its data, and supports the SSL encryption protocol for client/server communication.


Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MySQL Technical Architecture

MySQL is based on a tiered architecture, consisting of both primary subsystems and support components that interact with each other to read, parse, and execute queries, and to cache and return query results.



Subsystems
There are three primary subsystems within the MySQL architecture, as discussed in the following sections.

Memory and Connection Management
This subsystem manages user connections, via modules for network connection management with clients, and synchronizes competing tasks and processes, via modules for multithreading, thread locking, and performing thread-safe operations. It also handles all memory management issues between requests for data by the query subsystem and the data storage subsystem.

Query Parsing and Execution
Query parsing and execution is handled by two interrelated components: the syntax parser and the query optimizer. The syntax parser decomposes the SQL commands it receives from calling programs into a form that can be understood by the MySQL engine. It also checks the objects being referenced to ensure that the privilege level of the calling program allows it to use them. The query optimizer then prepares the most efficient plan for query execution, making decisions about table-versus-index scans, join methods, and range optimization, and using a bottom-up methodology to detect the optimal execution plan.

Data Storage
The data storage subsystem interfaces with the operating system (OS) to write to disk all of the data in the user tables, indexes, and logs, as well as the internal system data. MySQL 5.1 also introduced a new pluggable architecture, which allows developers to create new table storage mechanisms and “plug them in” to the server at run-time. This pluggable architecture also creates a level of abstraction between the data storage subsystem and the rest of the MySQL server, making it possible for developers to add new data storage engines that interact with the other MySQL subsystems through a standard API.



Connectivity
MySQL is designed on the assumption that the vast majority of its applications will be running on a TCP/IP (Transmission Control Protocol/Internet Protocol) network. This is a fairly good assumption, given that TCP/IP is not only highly robust and secure, but is also common to UNIX, Windows, OS/2, and almost any other serious operating system you’ll likely encounter. When the client and the server are on the same UNIX machine, MySQL uses TCP/IP with UNIX sockets, which operate in the UNIX domain; that is, they are generally used between processes on the same UNIX system, as opposed to Internet sockets, which operate between networks.



Standards Compliance
The Structured Query Language (SQL) is an open standard that has been maintained by the American National Standards Institute (ANSI) since 1986. Although it’s true that the implementation of this standard does differ in varying degrees from vendor to vendor, it’s fair to say that SQL is today one of the most widely used cross-vendor languages. As with other implementations, such as SQL Server’s T-SQL (Transact-SQL) and Oracle’s SQL, MySQL has its own variations of the SQL standard that add power beyond what is available within the standard. Beginning with v5.1, MySQL also includes support for data import and export using Extensible Markup Language (XML), a widely accepted, vendor-neutral format for data markup and sharing.



Transactions
In the SQL context, a transaction consists of one or more SQL statements that operate as a single unit. Each SQL statement in such a unit is dependent on the others, and the unit as a whole is indivisible. If one statement in the unit does not complete successfully, the entire unit will be rolled back, and all the affected data will be returned to the state it was in before the transaction was started. Thus, a transaction is said to be successful only if all the individual statements within it are executed successfully. The MySQL transaction system fully satisfies the ACID tests for transaction safety via its InnoDB and BDB table types (older table types, such as the MyISAM type, do not support transactions).

• Atomicity is handled by storing the results of transactional statements (the modified rows) in a memory buffer and writing these results to disk and to the binary log from the buffer only once the transaction is committed. This ensures that the statements in a transaction operate as an indivisible unit and their effects are seen either collectively or not at all.

• Consistency is primarily handled by MySQL’s logging mechanisms, which record all changes to the database and provide an audit trail for transaction recovery. In addition to the logging process, MySQL provides locking mechanisms that ensure that all of the tables, rows, and indexes that make up the transaction are locked by the initiating process long enough to either commit the transaction or roll it back.

• Server-side semaphore variables and locking mechanisms act as traffic managers to help programs manage their own isolation mechanisms. MySQL’s BDB table handler, for example, uses page-level locking to safely handle multiple simultaneous transactions, while the InnoDB table handler uses a more fine-grained row-level locking.

• MySQL implements durability by maintaining a binary transaction log file that tracks changes to the system during the course of a transaction. In the event of a hardware failure or abrupt system shutdown, recovering lost data is a relatively straightforward task by using the last backup in combination with the log when the system restarts.

Because transactional tables incur some performance overhead, it’s also possible to specify whether to use transactions on a per-table basis.



Query Caching
If a query returns a given set of records, repeating the same query should return the same set of records, unless the underlying data has somehow changed. As obvious as this sounds, few of the other major RDBMS vendors provide features that take advantage of this principle. Other database products are efficient in storing optimized access plans that detail the process by which data is retrieved; such plans allow queries similar to those that have been issued previously to bypass the process of analyzing indexes yet again to get to the data.

Result-set caching takes this principle a step further by storing the result sets themselves in memory, thus circumventing the need to search the database at all. The data from a query is simply placed in a cache, and when a similar query is issued, this data is returned as if in response to the query that created it in the first place. The MySQL engine uses an extremely efficient result set–caching mechanism, known as the Query Cache, that dramatically enhances response times for queries that are called upon to retrieve the exact same data as a previous query. This mechanism is so efficient that a major computing publication declared MySQL queries to be faster than those of Oracle and SQL Server (which are both known for their speed). If implemented properly, decision support systems using MySQL with canned reports or data-driven web pages can provide response speeds far beyond those that would be expected without the Query Cache.



Extensibility
In keeping with its open-source roots, MySQL makes the original source code available as part of the distribution, which permits developers to add new functions and features that are compiled into the engine as part of the core product. MySQL also allows separate C and C++ libraries to be loaded in the same memory space as the engine when MySQL starts up.

MySQL also allows developers to add new functions at run-time through a special user-defined function interface. User-defined functions are created initially as special C/C++ libraries and are then added and removed dynamically by means of the CREATE FUNCTION and DROP FUNCTION statements.



Symmetric Multiprocessing Support
To take advantage of multiprocessor architecture, MySQL is built using a multithreaded design, which allows threads to be allocated between processors to achieve a higher degree of parallelism. This is important to know not only for the database administrator, who needs to understand how MySQL takes best advantage of processing power, but also for developers, who can extend MySQL with custom functions. All custom functions must be thread-safe—that is, that they must not interfere with the workings of other threads in the same process as MySQL.

MySQL makes use of various thread packages, depending on the platform. POSIX threads are used on most UNIX variants, such as FreeBSD and Solaris. LinuxThreads are used for Linux distributions. For efficiency reasons, Windows threads are used on the Windows platform, but the code that handles them is designed to simulate POSIX threads. Because MySQL is a threaded application, it is able to let the operating system take over the task of coordinating the allocation of threads to balance the workload across multiple processors. MySQL uses a global connection thread to handle all connection requests and creates a new dedicated thread to handle authentication and SQL query processing for each connection. In addition, in replication, master-host synchronization is handled by separate threads.

Of course, another way to take advantage of multiprocessing is to run multiple instances of MySQL on the same machine, thereby spawning a separate process for each instance. This approach is especially practical for hosting companies and even for internal hosting within corporate environments. By running multiple instances of MySQL on the same computer, you can easily accommodate multiple user bases that need different configuration options.



Security
The process of accessing a MySQL database can be broken down into two tasks: connecting to the MySQL server itself and accessing individual objects, such as tables or columns, in a database. MySQL has built-in security to verify user credentials at both stages.

• MySQL manages user authentication through user tables, which check not only that a user has logged on correctly with the proper username and password, but also that the connection is originating from an authorized TCP/IP address.

• Once a user is connected, a system administrator can bestow user-specific privileges on objects and on the actions that can be taken in MySQL. For example, you might allow fred@thiscompany.com to perform only SELECT queries against an inventory table, while allowing anna@thatcompany.net to run INSERT, UPDATE, and DELETE statements against the same table.

The actual data that travels over a network, such as query results, isn’t encrypted and is, therefore, open to viewing by a hacker. To secure your data, you can use one of the Secure Shell (SSH) protocols; you’ll need to install it on both the client applications and the operating system you’re using. If you’re using MySQL 4.0 or later, you can also use the Secure Socket Layer (SSL) encryption protocol, which can be configured to work from within MySQL, making it safe for use over the Internet or other public network infrastructures.



Application Programming Interfaces
For application developers, MySQL provides a client library that is written in the C programming language and a set of APIs that provide an understandable set of rules by which host languages can connect to MySQL and send commands. Using an API protects client programs from any underlying changes in MySQL that could affect connectivity. Currently, MySQL provides hooks to C, C++, Eiffel, Java, Perl, PHP, Python, Ruby, and Tcl, and connectors are also available for JDBC, ODBC, and .NET applications.


Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

MySQL Product Family

In addition to the core MySQL database server, Oracle makes available a number of MySQL-related products and tools. This section introduces you to some of the other members of the MySQL product family.

MySQL Server
This core product consists of a high-performance database server, which is the main software engine responsible for creating and managing databases, executing queries and returning query results, and maintaining security. This core product also includes a number of client-side tools, such as a command-line SQL client; tools to manage user permissions; and utilities to import, export, copy, and repair databases.

MySQL Cluster
MySQL Cluster is a version of the MySQL database server that supports “clustering,” a technology that allows data to be transparently distributed across two or more physical servers to increase redundancy. This clustering technology plays an important role in high-availability applications, as it ensures continuous data availability even if one of the nodes in the cluster fails. At the time of this writing, MySQL Cluster supports up to 255 nodes in a single cluster and uses synchronous replication to copy data between nodes.

MySQL Proxy
MySQL Proxy is a proxy server that serves as a “gatekeeper” between the MySQL database server and connecting clients. It includes the ability to intercept and rewrite queries, modify result sets, implement query queues, analyze query traffic for reporting purposes, and perform load balancing tasks.

MySQL Administrator
MySQL Administrator is an all-in-one control center for a MySQL database server, allowing database administrators to track server status in real time. It includes visual tools for user administration, database backup and restore, and log analysis, as well as server fine-tuning.

MySQL Query Browser
MySQL Query Browser is a visual tool for graphically constructing queries and viewing the results. It includes tools to manage database connections, databases, and tables, as well as a debugger (with breakpoint support) to assist in optimizing and troubleshooting complex queries.

MySQL Workbench
MySQL Workbench is a visual design tool that enables database administrators and developers to graphically design and validate data models, generate database schema code, and manage changes to database schemas. It also includes the ability to visually compare and synchronize two versions of a database and create import/export scripts to transfer data from one system to another.

MySQL Migration Toolkit
The MySQL Migration Toolkit is a graphical, wizard-driven tool to port databases from other RDBMS products to MySQL. It includes support for Oracle, Microsoft SQL
Server, and Microsoft Access, and provides automated tools to remap and rebuild table schemas; copy records; and transfer indexes, views, triggers, and stored procedures.

MySQL Embedded Server
MySQL Embedded Server is a low-footprint version of the MySQL database server that is intended specifically for use in embedded applications, such as networking equipment, diagnostic tools, or point-of-sale (POS) systems. This embedded database also includes a number of useful administrative features: automatic space expansion, auto-restart, and dynamic reconfiguration.

MySQL Drivers and Connectors
MySQL provides drivers and connectors for many different programming languages, thereby making it possible to build database-driven applications using any one of several different development toolkits. Currently, MySQL provides drivers and connectors for C, C++, Java, Perl, PHP, Python, Ruby, JDBC, ODBC, and .NET applications.


Are there Different Versions of the MySQL Database Server?
MySQL’s core database server comes in two flavors: Community and Enterprise. The Community server is “free”: Users can download and use it at no cost under the terms of the GNU GPL, but by the same token, are required to perform all maintenance and administrative tasks themselves, with no support from the MySQL development team. For companies and individuals looking for a greater level of support, the Enterprise server is a commercial offering that provides regular updates and bug fixes, consultancy services and advice from MySQL engineers, and proprietary database-monitoring software in return for a subscription fee.


Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition

What Makes MySQL so Fast?

Part of the reason for MySQL’s blazing performance is its fully multithreaded architecture, which allows multiple concurrent accesses to the database. This multithreaded architecture is the core of the MySQL engine, allowing multiple clients to read the same database simultaneously and providing a substantial performance gain. The MySQL code tree is also structured in a modular, multilayered manner, with minimum redundancies and special optimizers for such complex tasks as joins and indexing.

MySQL also includes a query cache, which can substantially improve performance by caching the results of common queries and returning this cached data to the caller without having to re-execute the query each time. This is different from competing systems such as Oracle, in that those systems merely cache the execution plan, not the results. However, they still need to execute the query, including all joins, and re-retrieve the query results on every run. MySQL benchmarks claim that this feature improves performance by more than 200 percent, with no special programming required on the part of the user2. It is worth noting that MySQL’s designers initially left out many of the features that cause performance degradation on competing systems, including transactions, referential integrity, and stored procedures. These features typically add complexity to the server and result in a performance hit. User requests for these features have, however, resulted in their inclusion in newer versions of the product.


Source of Information : MCGraw Hill - SQL the Complete Reference 3rd Edition


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner