You are on page 1of 149

MySQL

The MySQL database server is the world's most popular open source database. MySQL 5.1, the latest production-ready release includes numerous enhancements that improve performance, internationalization, and the ability to embed the MySQL Server with other hardware and software solutions.

How to Install the MySQL Database Server on Your Windows PC

Log into the computer as an administrator. This will give you administrator rights, which will make the installation smoother. Note that, once installed, the program doesnt need to be run as an administrator. Download the free MySQL Server Community Edition. Be sure to download a version that includes a Windows Installer. Save the file on your Windows Desktop.If youre not sure which version to select, download MySQL Installer for Windows. Double-click the downloaded file. The installation file comes as a .zip file, so double-clicking it should initiate your unzipping software and take you to an archive folder.

Click Next. This begins the setup.

Click Custom > Next. This will enable you to specify where you want to install MySQL. If you have Apache installed in C:\Server, you will want to install MySQL in the same directory.In the next window, highlight MySQL Server, and then click the Change.
In the next window, in the text box Folder Name, change the directory toC:\Server\MySQL\ exactly as its written here and then click OK. On the next window, click Next. Now MySQL is ready to install.

Click Install. Wait while the program self-installs.

Click Skip Sign-Up and then Next. Once the installation is complete, you will be presented with a MySQL Sign-Up window. Skip signing up with MySQL for now since you can sign up later if you like. Once youve skipped, your new dialogue box should sayWizard Completed.

Configure MySQL. Leave the check box Configure the MySQL Server Now checked and click Finish.

Click Next. This will initialize the configuration setup.

Check Standard Configuration and then click Next. This is the default configuration and is recommended for most users. Make sure Install As Windows Service and Launch the MySQL Server Automatically are checked, then click Next. Create a root password. Type in what you want your root password to be and make sureEnable root access from remote machines is checked. Make sure you choose a difficult to guess password and 'write it down so you don't forget it. Click Next. Click Execute. This will start the MySQL server. After MySQL has done its thing, clickFinish.

Enter your root password and hit Enter. This should initiate the program.

How to use MySQL Administrator to backup a database

Step 1. Enter the login details for the MySQL connection. The Server Host should be your domain name and you can use your cPanel login details in order to access all databases in your account. Alternatively, you can use the MySQL username you have created through the MySQL Databases tool in your cPanel in order to connect to the database that it has access to. You should leave the Port setting to its default value 3306. Once you have entered your credentials, click on the OK button.

Step 2. Once you have logged in, a screen with the MySQL server status will appear. If you are using the application on a local server you will be able to execute administrative tasks like restarting the MySQL server for example. On a Shared hosting account, however, you can only create backups and restore your databases with this application.

Step 3. To create a backup of your database, click on the "Backup" button from the left menu. Then click on the "New Project" button, set the name for your backup and click on the "Save Project" button.

Step 4. Once you have created a project, you have to select which databases you want to backup. To do this, mark the database from the left column that shows the available databases. Next, click on the rightpointing arrow to mark the database for backup. Once you have done that, click on the "Execute Backup Now" button in order to start the backup of your database.

Step 5. The application will ask you where to store the backup file of your database. Select a suitable location on your local computer and click on the "Save" button.

How to use MySQL Administrator to restore a database

Step 1. Click on the "Restore" Button from the left menu. Next, press the "Open Backup File" button at the bottom of your screen. Locate and open the .sql file you have previously created using the Backup option.

Step 2.The MySQL Administrator application will automatically detect which database should be restored. All you have to do is press the "Start Restore" button to initiate the backup restore.

Versions of the MySQL Server

The My SQL Server Instance Configuration Wizard is used to set up the initial configuration of the My SQL server and set up the My SQL server as an automatically running Windows service. The service accesses the mysqld-nt or similar server script to actually run a My SQL server. MySQL supports a Standard edition, a Max edition and a Debug edition (rarely used). As you probably noticed when you downloaded the Windows distribution file, you were not given the option to select an edition. Windows distribution files, unlike other operating systems, include all editions in one file, so you do not have to make a decision about editions until after you install MySQL. Initially, that choice is made for you by running the MySQL Server Instance Configuration Wizard. There might come a time, though, when you want to choose a different edition of the server.

The Windows distribution of MySQL includes five editions of the MySQL server. These editions can be divided into the broader categories that you saw earlier - Standard and Max. The following table describes the five server editions available in a MySQL Windows installation.

Server Edition

Description
This is the basic compiled edition of the MySQL server. It supports all the basic features found in a production release of MySQL. This edition also contains full debugging support, which means that it might run more slowly and use more memory than other editions of the MySQL server.

mysqld

mysqld-debug

The binaries are compiled with additional debug data and are not intended for use in a production environment.
This edition of the MySQL server is optimized to run on Windows NT, Windows 2000, Windows XP, and Windows Server 2003. In addition, the mysqld-nt server supports named pipes. The mysqld-max server is the Max edition of the MySQL server. As a result, it includes all features found in the mysqld server, plus additional features. Like the mysqld-nt server, the mysqld-maxnt server is optimized to run on Windows NT, Windows 2000, Windows XP, and Windows

mysqld-nt

mysqld-max

mysqld-max-nt

On variants of Windows (NT, Server 2000, XP, or Server 2003), we will start with the mysqld-nt server. If additional features of the Max version become a need, we can move to Max version later.

The mysqld program is the MySQL server daemon, though we will rarely interact with it directly. We will use the daemon through a wrapper script called mysqld_safe. The mysqld_safe wrapper adds a few extra safety-related logging features and system- integrity features when the daemon is started and is the preferred way to start the server.

MySQL installs more than a thousand files and directories on your system. The location of these files differs depending on the installation mechanism you choose. The tar ball root directory structure contains the following:

Directory Bin tools you will Data with log files Docs version. Include compiling other Lib Scripts files and Share files for using sql-bench support-files

Contents - Binaries - mysqld server program, all client programs and run to use and administer MySQL. - The data files where MySQL reads and writes its data, along for the server. - Documentation - HTML and text files pertaining to installed
- A set of header files that may be used when writing or programs. - MySQL library files. - mysql_install_db script, which is used to install initial data accounts. - SQL scripts for fixing privileges, as well as a set of language MySQL in a variety of languages. - A set of benchmarking tools included with MySQL. - Several configuration file examples and other support scripts.

Securing the MySQL Server: Set root Password


After a new installation, anyone can log in as root without a password to MySQL and have unrestricted privileges to read, change, and delete all databases. For reasons of security it is absolutely necessary that you give a password for root.
Here are some methods to set or change the root password for a MySQL installation. That password is normally an empty string at initial installation. Use SET PASSWORD command: Code Sample: SET PASSWORD FOR 'root'@'localhost' = PASSWORD('abcd1234'); Use mysqladmin root# mysqladmin -u root password "<password-string>" if there was already a mysql root password set, change this to: OS> mysqladmin -u root password <old-password> "<newpassword> root# mysqladmin -u root password 'secret' root# mysqladmin -u root -h your-host-domain password 'secret'

You may see an error Host 'your-host-domain' is not allowed to connect to this MySQL server'. This error indicates that MySQL Access-Control database mysql has no domain name set.

To solve this, we will restart the mysql and,


Update the table mysql.user with an UPDATE command. Then we change the second root password with mysqladmin. The following lines summarize the commands, once with and once without the domain name: root# mysql -u root -p Enter password: ******* mysql> USE mysql; mysql> UPDATE user SET host="<your-host-domain>" WHERE host="<computer-name>"; mysql> FLUSH PRIVILEGES; mysql> exit root# mysqladmin -u root -h computer-name password 'secret'

As seen above, we can also use UPDATE to directly edit the users table OS> mysql -u root mysql> use mysql; mysql> UPDATE user SET Password = PASSWORD('"<new-password>"') WHERE User = 'root'; mysql> FLUSH PRIVILEGES; This requires knowing the current password for root user. Alternately, you can restart mysql as shown: OS> mysqld --skip-grant-tables user=root and use method shown above.

Delete Anonymous Accounts As an important security measure, one should delete all anonymous users. These are users for whom the user column is empty. In other words, allow only explicitly registered users in the mysql.user table to log in. Code Sample: DELETE FROM user WHERE user = ' Creating an Account for Basic Use One core initial task is setting up a new database and making it available to a user, who can create tables and fill them with data. Code Sample: GRANT ALL ON sakila.* TO sakilaadmin IDENTIFIED BY 'sakila'; GRANT SELECT,UPDATE,DELETE,INSERT ON sakila.* TO sakilauser IDENTIFIED BY 'sakila'; Code Explanation

General Information using MySQL Monitor The MySQL client that ships with the My SQL distribution is named mysql. Next, we will connect to the server using the MySQL Client mysql, and execute some simple SQL commands. Run the client from your command prompt by switching to the bin directory of your My SQL installation: OS> mysql -u root -p Password: ***** Code Sample: SHOW DATABASES; SHOW TABLES; SELECT COUNT(*) FROM user;

Configuring My SQL MySQL reads configuration file(s) when it starts up. If you use the defaults or an installer, you probably don't need to add anything to the configuration file. However, if you install MySQL in a nonstandard location or want the databases to be stored somewhere other than the default, you might need to edit the configuration file. The configuration file is namedmy.ini or my.cnf. It's located in your system directory (such as Windows or Winnt) if you are using Windows or in /etc on Linux, Unix, and Mac. The configurations file contains several sections and commands for various components and processes in MySQL. As an example, the following commands in the mysqld section sometimes need to be reconfigured: [mysqld] # The TCP/IP Port the MySQL Server will listen on port=3306 #Path to installation directory. All paths are # usually resolved relative to this. basedir="C:/Program Files/MySQL/MySQL Server 5.0/"

#Path to the database root

The # at the beginning of the line makes the line into a comment. The basedir line tells the MySQL server where MySQL is installed. The datadir line tells the server where the databases are located. You can change the port number to tell the server to listen for database queries on a different port.

MySQL Programs and Executables

This lesson provides a quick reference for the key programs, options and functions of the key MySQL tools. We discuss the server mysqld, the command interpreter mysql, and the administration tools mysqladmin, myisamchk, etc.
MySQL server provides several varieties of programs: The MySQL server and server startup scripts: mysqld starts the MySQL database server. mysqld_safe, mysql.server, and mysqld_multi are server startup scripts. mysql_install_db initializes the data directory and the initial databases. MySQL Instance Manager monitors and manages MySQL server instances.

Client programs that access the server: mysql is a command-line client for executing SQL statements interactively or in batch mode. mysqladmin is an administrative client. mysqlcheck performs table maintenance operations. mysqldump and mysqlhotcopy make database backups. mysqlimport imports data files. mysqlshow displays information about databases and tables. Utility programs that operate independently of the server: myisamchk performs table maintenance operations. myisampack produces compressed, read-only tables. mysqlbinlog is a tool for processing binary log files. my_print_defaults print option values from options files. perror displays the meaning of error codes. Note: Generally, most MySQL distributions include all of these programs, except for programs that are platform-specific such as server startup scripts. The distributions for different operating systems do not look alike; for example, the RPM distributions are more specialized - for server, for client and so forth.

The following table provides an overview of the commands discussed in this section. MySQL Server and Included Administrative Tools Is the actual MySQL server. The program is usually not started directly, but under Windows as a system service and under Unix/Linux via an Init-V script with the help of mysqld_safe . Should be used under Unix/Linux for a secure server launch. Client-tool that enables interactive execution of SQL commands. Assists in various administrative tasks (display status, reinput privileges, execute shutdown, etc.).

Mysqld

mysqld_safe

Mysql

mysqladmin

MySQL Server and Included Administrative Tools

Mysqldump Mysqlimport Mysqlshow

Saves contents of a MySQL database in a text file. Inputs data into a table from a text file.

Displays information on databases, tables, and columns. Checks the integrity of MyISAM table files and repairs them as necessary. Compresses MyISAM table files for more efficient read-only access.

Myisamchk

Myisampack

Common Options to Commands Various options can be passed to all commands when they are executed. As is usual with Unix/Linux, commands can be prefixed with a hyphen (short form) or two hyphens (full option name). Please note that the short forms of options are casesensitive.

The common feature exhibited by the commands introduced in this section is that they are launched as external programs in a command window (Windows) or in a command shell (Unix/Linux). The entire operation of these programs is carried out in text mode and is therefore not what one would term excessively convenient. However, these commands are very well suited for execution in scripts in the automation of administrative tasks.
Common Options of the MySQL Server (mysqld) and the MySQL Client Tools (mysql, mysqladmin, mysqldump, mysqlimport, etc.) --help - Displays a brief operation introduction. --print-defaults - Displays default values for options; default values can come from configuration files or system variables. --nodefaults - Causes no configuration files to be read at startup. --defaults-file=filename - Causes only this configuration file to be read at startup. --defaults-extra-file=filename - First the global configuration file is read, and then filename, and finally (only under Unix/Linux), the user-specific configuration file.

Displays the version number of the program. Common Options of the MySQL Client Tools -u <username> -p --user=username --password
Determines the user name for registration with MySQL. Asks for input of password immediately after start of the command.

-p<password>

--password=xxx

Passes the password directly; in contrast to other options, there can be no space after - p; this is more convenient than interactive input of the password, but it represents a considerable security risk and thus should generally be avoided. Under some operating systems, any user can see the password by looking at the process list.

-h hostname

Supply the name or IP number of the computer on which the server is running (assumed by default to OS> mysql -h staginghr -u username -p belocalhost, that is, the local computer).

--host=hostname

Enter Password: xxxxxx

For a connection to the MySQL server to be at all possible, the following two options are generally used at the start of each client command: OS> mysql -u username -p Enter Password: xxxxxx If MySQL is not yet password-secured, then this will work without a password being specified. We discuss users and setting password for root in other lessons. If you execute MySQL commands under Windows and create a directory with options, then instead of the backslash you should use the forward slash (/). If the file name contains space characters, then put the entire path in quotation marks, as in the following example: --basedir="C:/Programs/MySQL/MySQL Server 5.0/". Specifying Options There are several ways to specify options for MySQL programs: Command Line: List the options on the command line following the program name. This allows for options to be appled to a specific invocation of the program. Options File: List the options in an option file that the program reads when it starts. This helps by setting options in one place, one time that we want programs to use each time they run. Environment Variables: Set the options via environment variables at the OS level. This method is useful for options that you want to apply each time the

Options on the Command Line Program options specified on the command line follow these rules: Options are given after the command name. An option argument begins with one dash or two dashes, depending on whether it has a short name or a long name. Many options have both forms. For example, -? and --help are the short and long forms of the option that instructs a MySQL program to display its help message. Option names are very case sensitive. -v and -V are both legal and have different meanings. (They are the corresponding short forms of the --verbose and --version options.) Some options follow their name = a value. For example, -h localhost or -host=localhost indicate the MySQL server host to a client program. The option value tells the program the name of the host where the MySQL server is running. For a long option that takes a value, separate the option name and the value by an = sign. For a short option that takes a value, the option value can immediately follow the option letter, or there can be a space between: -hlocalhost and -h localhost are equivalent. An exception to this rule is the option for specifying your MySQL password. This option can be given in long form as --password=pass_val or as -password. In the latter case (with no password value given), the program prompts you for the password. The password option also may be given in short form as ppass_val or as -p. However, for the short form, if the password value is given, it must follow the option letter with no intervening space. The reason for this is that if

Code Sample: mysql -usakilaadmin -psakila mysql -usakilaadmin -p sakila Code Explanation The first command instructs mysql to use sakila as password and specifies no default database. The second command causes mysql to prompt for the password value and to use sakila as the default database. We will see more on setting options in later lessons.

my_print_defaults: Display options from files


The my_print_defaults program displays the options that are present in the various option groups of option files. The output indicates what options will be used by programs that read the specified option groups.

For example, the mysqlcheck program reads the [mysqlcheck] and [client] option groups. The output consists of options, one per line, in the form that they would be specified on the command line. To see what options are present in those groups in the standard option files, invoke my_print_defaults like this: Code Sample: my_print_defaults mysqlcheck client Code Explanation

List options present in the client group: shell> my_print_defaults mysqlcheck client --user=sakiladmin --password=**** --host=localhost --port=3306

Here are the options one can use with the my_print_defaults program: --help, -?:Display a help message and exit. --config-file=file_name,--defaults-file=file_name,-c file_name:Read only the given option file. --debug=debug_options, -#debug_options: Write a debugging log. The debug_options string often is 'd:t:o,file_name'.The default is 'd:t:o,/tmp/my_print_defaults.trace'.

--defaults-extra-file=file_name, --extra-file=file_name, -e file_name :Read this option file after the global option file but (on Unix) before the user option file.
--defaults-group-suffix=suffix,-g suffix:In addition to the groups named on the command line, read groups that have the given suffix. --no-defaults, -n:Return an empty string. --verbose, -?, -v:Verbose mode. Print more information about what the program does.

Code Sample: my_print_defaults -debug=d:t:o,my_print_defaults.trace --verbose mysqlcheck client Code Explanation List options present in the client group in a trace file. perror: Explain Error Codes For most system errors, MySQL displays, in addition to an internal text message, the system error code in one of the following styles: Syntax

message ... (errno: #)

You can discover the meaning of the error code by viewing your system's documentation for or by using the perror utility. The perror program prints a description for a system error code or for a storage engine (table handler) error code. The syntax of perror is shown below with an example: Syntax shell> perror [options] errorcode(s) Code Sample: perror 12 41 42; This results in the following:

OS error code 12: Not enough space OS error code 41: Directory not empty OS error code 42: Illegal byte sequence
Note: The meaning of system error messages may be dependent on your operating system. It is possible for a given error code to

Here are the options supported by the perror command:

--help, --info,-I, -?: Display a help message and exit. --ndb: Print the error message for a MySQL Cluster error code. --silent, -s: Silent mode. Print only the error message. --verbose, -v: Verbose mode. Print error code and message (default behavior). --version, -V: Display version information and exit.

Overview of User Interfaces

MySQL provides three main GUI client programs for use with MySQL Server. EMS SQL Manager for MySQL is a high performance tool for MySQL database administration and development. SQL Maestro for MySQL Overview: is the premier MySQL admin tool for MySQL database management, control and development. SQLyog MySQL GUI is the most powerful MySQL manager and admin tool, combining the features of MySQL Query Browser, Administrator, phpMyAdmin and other MySQL Front Ends and MySQL GUI tools in a single intuitive interface. MySQL Query Browser: This graphical tool is used for creating, executing, and optimizing queries on MySQL databases. MySQL Administrator: This tool is used for administering MySQL servers, databases, tables, and user accounts. MySQL Migration Toolkit: This tool helps you migrate schemas and data from other relational database management systems

MySQL Query Browser The main purpose of the MySQL Query Browser is to help you in composing and testing SQL commands. Additionally, the program offers some auxiliary functions: you can insert data into tables, alter data in tables, test regular expressions (for the SQL operator REGEX), read MySQL help texts, etc.
To become familiar with the MySQL Query Browser, input a simple SQL command. SQL keywords are shown automatically in color. Execute the command with the EXECUTE button. The first window in Query Browser provides you the capability of writing your scripts and seeing the results in the window. You can manage your schemas, manage users, etc. Query browser is divided into many sections for achieving these tasks. Query Area - This area allows for inputting your desired query. Result Area - This area shows the results after the query is executed. Query Toolbar - Basic buttons for executing queries. Advanced Toolbar - Contains transaction buttons like Start, Commit, Rollback, Query Building buttons like Select, From, Where, Group By and other operations. Object Browser - View databases, tables, views, bookmarks, and history. Information Browser - Part of the sidebar to look up syntax, built-in functions, parameters, etc

Keyboard Shortcuts A few keyboard shortcuts make using the MySQL Query Browser more efficient and convenient: Ctrl+Return executes the current SQL command (like EXECUTE). Ctrl+Shift+Return executes the command but shows the result in a new dialog sheet. This has the advantage that the results of previous commands remain available. F11 changes the arrangement of the individual windows and enlarges the input region for SQL commands. This makes it easier to enter long SQL commands. If you press F11 again, the standard layout is restored.

F12 closes the individual windows except for the current result region. This makes it easier to read extensive results. Pressing F12 again restores the original window layout.

SQL Commands with Mouse Clicks Using various arrow buttons of the Toolbar, you can assemble SQL commands with minimal typing effort. The following click sequences provide an example: Click on the button SELECT. Expand table film to see its columns. Click on the columns title, rating, and rental_rate of the film table. Click on the button WHERE. Click on the column film_id of the film table. Type in =101 (for the WHERE condition) from the keyboard. Click on the button ORDER. Click on the column title of the film table. Note: If you do not see SELECT buttons, click on the menu

From the mouse clicks (and minimal typing) above, the MySQL Query Browser forms the following command: SELECT f.`title`, f.`rating`, f.`rental_rate` FROM film f WHERE f.`film_id`=101 ORDER BY f.`title` f is an alias for the flim table. MySQL Query Browser does not use the optional AS. Execute: Click on the EXECUTE button or hit Ctrl+Enter to run the SQL statement and see its results. Save: Select FILE | SAVE AS from the menu to save the query to a file. Exporting results: With FILE | EXPORT RESULTSET you can export the most recent result of SELECT commands in the formats CSV, HTML, XML, and Excel. View BLOBs: The content of BLOB columns are not displayed by default. You can view BLOB data in a separate editor window, even dump the blob to a file. Explain Query: The button EXPLAIN gives internal, execution-related information about the planned execution of the most recent SQL command by MySQL. The meaning of various aspects of the Explain Plan is discussed in another lesson.

Updating Data: We can execute UPDATE, INSERT, DELETE, and other data altering commands. Transactions: With InnoDB tables, we can execute transaction-oriented commands via buttons for START TRANSACTION | COMMIT | ROLLBACK. Refresh: In a multi-session, multi-user situation, the displayed result set may be refreshed to get the latest matching rows. Multiple Result Regions: With FILE | NEW QUERY TAB you open an additional SQL input field and result region. In this way you can test several SQL commands in parallel. History and Bookmarks for SQL Commands The MySQL Query Browser stores all executed SQL commands automatically in a History List, available in the sidebar to the right of the window. With drag and drop you can move the command into the input region and execute it with a double click.

Using Scripts: Executing Several Commands Open a SQL script input area with FILE | NEW SCRIPT TAB. There you can specify several SQL commands separated by semicolons. You can then execute these commands all at once (EXECUTE button) or step by step (SCRIPT menu).

These scripts represent several ordinary SQL commands, not stored procedures. The commands can be stored as a *.sql file using the FILE menu. The history and bookmark functions, however, are not available.

MySQL Help - Information Browser The Information Browser provides access to all information that is not directly related to actual data within your database. The Syntax Browser - A convenient reference to MySQL query

syntax, it is your quick help in finding the correct syntax for building up the queries. The Function Browser - The Function Browser is a quick reference to the various functions built into MySQL. The Parameter Browser - The Parameter Browser provides different local, global, and dynamic parameters that can help build your queries. Local parameters affect the query in the current query window only. Global parameters affect all queries. Dynamic parameters are generated automatically from existing queries. The Transaction Browser - A single transaction could be made up of many queries. The Transaction Browser lists all queries that make up a single transaction and serves as a history for a single transaction.

Object Browser In the Object Browser, you can view the databases and their various components in a nested tree-style. Database Browser - The Database/schemata Browser is the primary screen of the Object Browser. You can use the Database Browser to select tables and fields, edit tables, create new tables and databases, and drop tables and databases. The Database Browser can be used to set the default database, which is required before you can issue queries against tables. Result Browser - You can place your more commonly used queries in bookmarks so that you can quickly retrieve them and re-use them later. To add a query to your bookmarks, highlight and drag it from the query area into the bookmark browser. Your bookmarks can be organized into folders and subfolders to help with management of your queries. The Bookmark Browser is one of a number of XML files use for internal purposes by the Query Browser. The History Browser - With the History Browser you can browse through all the queries you have previously issued. You can create bookmarks from history items by right-clicking on a selected history item and choosing the Add History Item as Bookmark menu option.

Changing Data in SELECT Results

With simple SELECT queries containing data from only one table (no JOINs) and without GROUP BY or aggregation functions, the results can be changed. To do so, click on the EDIT button at the bottom of the table. This button is available only for results that can be changed. To edit the contents of the result area you must enable edit mode through the use of the Edit button at the bottom of the result area. Any edits you make are not immediately applied, but instead you need to click the Apply Changes button next to the Edit button. Clicking the Discard Changes button throws away any changes you have made to the data. To change a table field, you must activate it with a double-click. You simply add new records to the end of the table. To delete a record (a row), execute DELETE ROWS with the right mouse button. Changes take effect only after you click the button APPLY CHANGES.

Stored Procedures The MySQL Query Browser makes available a number of elementary functions for input of stored procedures, which are functions composed of several SQL commands that are controlled directly by the MySQL server. Stored procedures are a characteristic of the MySQL server, while scripts belong to the MySQL Query Browser. We will discuss stored procedures in greater detail in a later lesson.

MySQL Administrator While the MySQL Query Browser helps in assembling and trying out SQL commands, the MySQL Administrator helps with administrative tasks related to management of a MySQL server. The various operations one can perform using the Administrator are covered in a later lesson.

SHOW and DESCRIBE Statements

Using Table-Related SHOW Statements We can use the SHOW COLUMNS statement to lists the columns in a table, along with information about the columns. Syntax SHOW [FULL] COLUMNS FROM <table name> [FROM <database name>] [LIKE '<value>'] FULL keyword shows more complete information about each column, and LIKE can be used to limit the values returned. Code Sample: USE sakilakubili; SHOW COLUMNS FROM film_review; SHOW COLUMNS FROM user FROM mysql LIKE 'max%'; You can also retrieve construction information of a table by using a SHOW CREATE TABLE statement, which shows the actual table definition. Code Sample: USE sakilakubili; SHOW CREATE TABLE film_review; Note::The entire results may not fit on the screen and what you see depends on

The next statement displays a list of indexes in a table. The output SHOW INDEX statement is shown below. Code Sample: USE sakila; SHOW INDEX FROM film_review; SHOW INDEX FROM user FROM mysql; +-------------+------------+---------+-------------+----------| Table | Non_unique | Key_name| Seq_in_index| Column_name Collation | Cardinality | ... | Null | Index_type | Comment | +-------------+------------+---------+-------------+----------| film_review | 0 | PRIMARY | 1| review_id A | 0 | ... | | BTREE | | +-------------+------------+---------+-------------+----------1 row in set (0.00 sec)

The next statement is the SHOW TABLES statement, which displays a list of tables in the current database or a specified database.
Code Sample: USE sakila; SHOW TABLES; SHOW TABLES FROM mysql LIKE 'time%';

+------------------------+ | Tables_in_sakilakubili | +------------------------+ | film_review | +------------------------+ 1 row in set (0.00 sec)

Using DESCRIBE Statement DESCRIBE is another statement useful for viewing table information. The following example shows a DESCRIBE statement that returns information about all columns in the user table that end with "priv": DESCRIBE user '%priv'; Code Sample: SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | sakila | | test | +--------------------+ 4 rows in set (0.11 sec) Code Sample: SHOW CREATE DATABASE sakilakubili;

INFORMATION_SCHEMA Tables INFORMATION_SCHEMA is the information database in MySQL server that provides access to database metadata, or data about the data, such as a table name, the constraints on a column, or access privileges. The same informationis also referred to as data dictionary and system catalog. Here is an example to list all the tables in sakila database, in reverse alphabetical order: Code Sample: SELECT table_name, table_type, engine FROM information_schema.tables WHERE table_schema = 'sakila' ORDER BY table_name DESC; +----------------------------+------------+--------+ | table_name | table_type | engine | +----------------------------+------------+--------+ | actor | BASE TABLE | InnoDB | | actor_info | VIEW | NULL | | ... | | ... | | store | BASE TABLE | InnoDB | | studio | BASE TABLE | InnoDB | +----------------------------+------------+--------+ 26 rows in set (0.20 sec)

The following example lists the various tables found in INFORMATION_SCHEMA. Code Sample: SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'INFORMATION_SCHEMA' AND table_name LIKE '%';
Showing Databases Here is a read of another table which shows that the following statements are equivalent: SELECT SCHEMA_NAME AS `Database` FROM INFORMATION_SCHEMA.SCHEMATA [WHERE SCHEMA_NAME LIKE ' wild '] SHOW DATABASES [LIKE ' wild ']

Code Sample:
SELECT SCHEMA_NAME AS `Database` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME LIKE 'sakila%'; SHOW DATABASES LIKE 'sakila%';

Identifiers in MySQL

Identifier Names Like all programming models, MySQL identifiers follow certain rules and conventions. Here are the rules to adhere to for naming identifiers to create objects in MySQL: Contain any alphanumeric characters from the default character set Include underscores (_) and dollar signs ($) Begin with any acceptable character, including digits Cannot be made up entirely of digits Cannot include a period (.) Cannot include an OS pathname separator, backslash (\) or forward slash (/)

Schema Object Names


Names for objects within MySQL - database, table, index, column, alias, view, stored procedure, partition, tablespace are known as identifiers. This section describes the allowable syntax for identifiers in MySQL alongwith which types of identifiers are case sensitive and under what conditions.

An identifier may be quoted or unquoted. If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. A normal name usually comprises the alphanumeric character set from the current character set, underscore _ and $. MySQL Reserved words can be found in their documentation. An exception is when a reserved word that follows a period in a qualified name must be an identifier, so it need not be

Code Sample: CREATE TABLE create (select1 varchar(10)); CREATE TABLE `create` (`select` varchar(10));
INSERT INTO `create` VALUES('data1'); INSERT INTO `create` VALUES('data2'); SELECT `create`.select FROM `create`; DROP TABLE `create`;

Code Explanation
creates a table named create that contains a column named select. The first creation fails, as the names are reserved words and not quoted. The second create and the DML statements go through just fine.

As seen in the example, the normal identifier quote character is the backtick `: mysql> SELECT * FROM `qtest` WHERE `qtest`.`id` = 201; Using Double Quotes If the ANSI_QUOTES SQL mode is enabled, it is allowable to quote identifiers within double quotes. Consequently, when this mode is not-enabled, string literals must be enclosed within single quotes. They cannot be enclosed within double quotes. Code Sample: DROP TABLE `qtest`; CREATE TABLE "qtest" (id INT); SET sql_mode='ANSI_QUOTES'; CREATE TABLE "qtest" (id INT); SET sql_mode='';

Code Explanation The first create table statement fails due to use of doublequotes: ERROR 1064: You have an error in your SQL syntax... The second create succeeds once ANSI_QUOTES SQL mode is

Using Quote Within Names Quote characters can be included within an identifier if we quote the identifier. If the character to be included within the identifier is the same as that used to quote the identifier itself, then we need to repeat that character twice: Code Sample: DROP TABLE `c``est`; CREATE TABLE `c``est` (`la"vie` VARCHAR(10)); INSERT INTO `c``est` VALUES ('one'); INSERT INTO `c``est`(`la"vie`) VALUES ('two'); SELECT `la"vie` FROM `c``est`; Code Explanation creates a table named c`est that contains a column named la"vie. Some basic DML statements are shown as well.

Using Digits Identifiers may begin with a digit but and may consist solely of digits. Code Sample: CREATE TABLE 1234 ( 789 varchar(10)); CREATE TABLE `1234` ( 1id SMALLINT, `789` varchar(10)); INSERT INTO `1234` VALUES(1,'digits1'); INSERT INTO `1234` VALUES(2,'digits2'); SELECT 1id, `789` FROM `1234`; DROP TABLE `1234`; Code Explanation creates a table named 1234 that contains two columns named 1id and 789. The first create table statement fails due to missing backtick for 789: ERROR 1064: You have an error in your SQL syntax... The 1id column does not need a backtick. Some basic DML statements are included as well.

Some Restrictions There are some restrictions on the characters that may appear in identifiers: Note: Please avoid using 5e or 2e2 as identifiers, because where the names themselves make up an expression. Depending on context, it might be interpreted as the expression1e + 3 or as an exponential number 1e+3. Warning: Avoid using any algorithms such SHA or MD5 to generate table names because these programs can produce names in illegal or ambiguous formats. A user variable cannot be used directly in an SQL statement as an identifier or as part of an identifier. No identifier can contain ASCII 0 (0x00) or a byte with a value of 255. Database, table, and column names should not end with space characters.

MySQL has relaxed some restrictions 5.1.6 onwards for database and table names. Earlier, these objects could contain characters that are not allowed in filenames, such as /, \, .. As of MySQL 5.1.6, special characters in database and table names are encoded in the corresponding filesystem names

The following table describes the maximum length for each type of identifier. Max Length (chars) Identifier Database Table Column Index Stored Function or Procedure Trigger 64 64 64 64 64 64

View

64

Identifier 64 Event 64 Tablespace 64 Log File Group 255 Alias

Max Length (chars)

Identifiers are stored using Unicode (UTF-8). This applies to identifiers in table definitions that are stored in .frm files and to identifiers stored in the grant tables in the mysqldatabase. The allowable Unicode characters are those in the Basic Multilingual Plane (BMP). Supplementary characters are not allowed.

Identifier Qualifiers MySQL uses names with a single identifier or a multiple-part name with identifiers separated by a period ".". The initial parts of a multiple-part name affect the context to which the final identifier is related. In MySQL, you can refer to a table column as column_name (read from first table with the column) or table_name.column_name (read from default database) or fully-qualifieddb_name.table_name.column_name. Prefixing db_name or table_name is optional unless the reference to column would be ambiguous. Note: When using quotes, quote components individually rather than name as a group. For example, write `some-table`.`some-column` and not `some-table.somecolumn`.Reserved words need not be quoted. Code Sample: USE `sakila`; SELECT `category`.`name` FROM `category`; USE `mysql`; SELECT `category`.`name` FROM `sakila`.`category`; Code Explanation The components are selected specifying qualified names.

The syntax .tbl_name means the table tbl_name in the default database (Accepted for ODBC compatibility). Code Sample: SELECT * FROM .category;
Code Explanation The category table has a DOT prefixing it in SELECT.

Creating Databases

To store data in MySQL, we will set up a database and then place tables, relationships and other objects in that database, following a design that maps to our application requirements. We will use a command-line tool - mysql, running a script to generate our objects. Several other options are available to create components via User Interfaces such as phpMyAdmin, MySQL Query Browser and MySQL Workbench. MySQL Query Browser A product from MySQL that provides a good set of drag-and-drop tools to visually define, run, manage and optimize SQL queries for MySQL Databases. Covered in another lesson. Syntax <database definition>::= CREATE DATABASE [IF NOT EXISTS] <database name> [[DEFAULT] CHARACTER SET <character set name>] [[DEFAULT] COLLATE <collation name>]

Note: If the database named above already exists, the statement above will throw an error. By specifying the IF NOT EXISTS clause, MySQL returns just a note (warning).

The CHARACTER SET specifies the default character set to use and the COLLATE clause selects default collation for ordering. More on these later. We will now set up our new database sakilakubili using mysql. Code Sample: CREATE DATABASE sakilakubili; USE sakilakubili;

The 1 row affected response from mysql indicates that one row was changed in the internal MySQL table containing the list of all databases. On statement execution, a database named sakilakubili is added to MySQL server. The database uses the default character set and collation as we didn't specify any. Note:On Windows, all object names, such as databases and tables, are converted to lowercase. In Linux and other Unix-like operating systems, the case is preserved. More on case- senstivity in other lessons.

Here, we actually specify the character set and collation to use: Code Sample: CREATE DATABASE sakilakubili DEFAULT CHARACTER SET latin1 DEFAULT COLLATE latin1_bin;

Creating Databases Deleting databases

Deleting Databases A database is dropped via the DROP DATABASE statement. Syntax DROP DATABASE [IF EXISTS] <database name> Code Sample: DROP DATABASE sakilakubili; Warning: When a database is dropped, the tables and their data stored in that database are also deleted. Exercise extreme caution executing the DROP DATABASE command.

Creating Tables We will now create additional tables in the sakila database using CREATE TABLE. First, we must specify the database we will be working with. The USE database sets the default database to which further commands will be applied. In other words, the USEcommand selects an active database among several databases under MySQL management. Tables provide a structure for storing and securing the data. All data exists within the structure of the tables, and tables are grouped inside of the database. In addition to creating tables, you can also modify the table definitions or drop the tables from the database. The CREATE TABLE statement includes appropriate column definitions and constraints to be used for the entity associated with the table. The fundamental CREATE TABLEstatement is complex and contains various clauses and options to complete its definition. This lesson focuses on the essential clauses in a table definition. The syntax block below shows the basic CREATE TABLE syntax. We will discuss theses clauses one by one in this lesson. Syntax <table definition>::= CREATE [TEMPORARY] TABLE [IF NOT EXISTS] <table name>( <table element> [{, <table element>}...]

Here is an example:
Code Sample: DROP TABLE IF EXISTS film_review; CREATE TABLE film_review ( review_id INTEGER, film_id SMALLINT NOT NULL, review_text VARCHAR(255) NOT NULL ) ENGINE=InnoDB; Tip:The CREATE TABLE command can span multiple lines, and each line is terminated with a Carriage Return.

Dropping Tables To drop or delete a table, use the DROP TABLE statement.
Syntax DROP [TEMPORARY] TABLE [IF EXISTS] <table name> [{, <table name>}...] Some Tips: The optional TEMPORARY keyword prevents the inadvertent loss of a permanent table. When the IF EXISTS clause is used with a non-existent table, a warning is thrown instead of an error. Warnings do not stop the execution of a multi-statement script in its tracks. We can use the DROP statement to drop several tables. Code Sample: DROP TABLE IF EXISTS reservation; Warning: A master table referenced in a foreign key cannot be dropped without first removing the reference.

Defining Table Types One especially important MySQL table options allows us to define the type of table that you create in your table definition. Syntax CREATE TABLE table-name ( ... columns ... ) ENGINE = {MYISAM | INNODB | MEMORY | MERGE}

We will create a table called film_info of type ISAM.


Code Sample:

DROP TABLE IF EXISTS film_info; CREATE TABLE film_info ( film_id SMALLINT NOT NULL, info_text VARCHAR(10000) NOT NULL ) ENGINE=MyISAM;

Altering Existing Table Structures Using ALTER TABLE, MySQL allows you to change an existing table in several ways, such as adding or dropping columns, change existing column definitions, adding PRIMARY KEY and FOREIGN KEY constraints, or remove constraints. Altering table requires a good understanding of columns and constraints which are discussed in subsequent lessons.

Syntax
ALTER TABLE <table name> <alter option> [{, <alter option>}...] <alter option>::= {ADD [COLUMN] <column definition> [FIRST | AFTER <column name>]} | {ADD [COLUMN] (<table element> [{, <table element>}...])} | {ADD [CONSTRAINT <constraint name>] PRIMARY KEY (<column name> [{, <column name>}...])} | {ADD [CONSTRAINT <constraint name>] FOREIGN KEY [<index name>] (<column name> [{, <column name>}...]) <reference definition>} | {ADD [CONSTRAINT <constraint name>] UNIQUE [<index name>] (<column name> [{, <column name>}...])} | {ADD INDEX [<index name>] (<column name> [{, <column name>}...])} | {ADD FULLTEXT [<index name>] (<column name> [{, <column name>}...])}

Cont.., | {ALTER [COLUMN] <column name> {SET DEFAULT <value> | DROP DEFAULT}} | {MODIFY [COLUMN] <column definition> [FIRST | AFTER <column name>]} | {CHANGE [COLUMN] <column name> <column definition> [FIRST | AFTER <column name>]} | {DROP [COLUMN] <column name>} | {DROP PRIMARY KEY} | {DROP INDEX <index name>} | {DROP FOREIGN KEY <constraint name>} | {RENAME [TO] <new table name>} | {ORDER BY <column name> [{, <column name>}...]} | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name] | [DEFAULT] CHARACTER SET charset_name [COLLATE collation_name] | {<table option> [<table option>...]}

Each of the alter options relates to a table definition option, and is preceded with an action keyword - ADD, ALTER, or DROP.

Add a column A basic use of altering table is to add columns. In this demo, we are adding a column we forgot to add. Code Sample:

ALTER TABLE film_review ADD COLUMN review_date DATETIME;


Renaming Tables An existing table can be renamed with another name, as shown Code Sample: CREATE TEMPORARY TABLE temp_table( column1 SMALLINT ); ALTER TABLE temp_table RENAME temp2_table; DROP TABLE temp_table; -- Should give an error ! DROP TABLE temp2_table; -- That works !!

Creating Column Definitions We will create column definitions for each column that needs to be part of the table. Two core elements required in a column definition are the column name (any acceptable MySQL identifier) and a supported data type, but several other elements can be specified with a column as shown in the syntax for table elements below. Syntax <table element>::= <column definition> | {[CONSTRAINT <constraint name>] PRIMARY KEY (<column name> [{, <column name>}...])} | {[CONSTRAINT <constraint name>] FOREIGN KEY [<index name>] (<column name> [{, <column name>}...]) <reference definition>} | {[CONSTRAINT <constraint name>] UNIQUE [INDEX] [<index name>] (<column name> [{, <column name>}...])} | {{INDEX | KEY} [<index name>] (<column name> [{, <column name>}...])} | {FULLTEXT [INDEX] [<index name>] (<column name> [{, <column name>}...])} <column definition>::= <column name> <type> [NOT NULL | NULL] [DEFAULT <value>] [AUTO_INCREMENT] [PRIMARY KEY] [COMMENT '<string>'] [<reference definition>]

Cont., <type>::= <numeric data type> | <string data type> | <data/time data type> <reference definition>::= REFERENCES <table name> [(<column name> [{, <column name>}...])] [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }] [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }] [MATCH FULL | MATCH PARTIAL]

Data Types in MySQL

Every table is composed of a number of columns. For each column, an intended data type must be specified. This section provides an overview of the data types available in MySQL. A data type is essentially a constraint on a column which defines and limits the type of values that can be stored in that column.

Numeric Data Types Numeric data types fall under two key categories: integer or fractional. UNSIGNED option disallows negative values in the column. There are several integer types in MySQL to store various range of values as shown: Data type TINYINT Acceptable values Signed: -128 to 127 Storage Unsigned: 0 to 255 1 byt e 2 byt es 3 byt es 4 byt es 8 byt es

SMALLINT

Signed: -32768 to 32767

Unsigned: 0 to 65535

MEDIUMINT

Signed: -8388608 to 8388607 Signed: -2147483648 to 2147483647 Signed: 9223372036854775808 to

Unsigned: 0 to 16777215

INT/INTEGER

Unsigned: 0 to 4294967295

BIGINT

Unsigned: 0 to 18446744073709551615

The fractional data types support the use of data in post decimals places.

Data type

Range of Values

Storage

FLOAT

-3.402823466E+38 to 1.175494351E-38 0 1.175494351E-38 to 3.402823466E+38

4 bytes

DOUBLE [PRECISION]/REAL

1.7976931348623157E+30 8 to 2.2250738585072014E-308 0 2.2250738585072014E308 to 1.7976931348623157E+30 8

8 bytes

DEC/DECIMAL/NUMERIC/FIXED

Range and Storage Depends requirements depend on the <length> and <decimals> values specified in the column definition

Relational Database Concepts

Brief History of SQL In 1970, Dr. E.F. Codd published "A Relational Model of Data for Large Shared Data Banks," an article that outlined a model for storing and manipulating data using tables. Shortly after Codd's article was published, IBM began working on creating a relational database. Between 1979 and 1982, Oracle (then Relational Software, Inc.), Relational Technology, Inc. (later acquired by Computer Associates), and IBM all put out commercial relational databases, and by 1986 they all were using SQL as the data query language. In 1986, the American National Standards Institute (ANSI) standardized SQL. This standard was updated in 1989, in 1992 (called SQL2), and again in 1999 (called SQL3). Standard SQL is sometimes called ANSI SQL or SQL92. All major relational databases support this standard but each has

Relational Database Management System A Relational Database Management System (RDBMS), commonly (but incorrectly) called a database, is software for creating, manipulating, and administering a database. For simplicity, we will often refer to RDBMSs as databases. Popular Databases Commercial Databases Oracle: Oracle is the most popular relational database. It runs on both Unix and Windows. It used to be many times more expensive than SQL Server and DB2, but it has come down a lot in price. SQL Server: SQL Server is Microsoft's database and, not surprisingly, only runs on Windows. It has only a slightly higher market share than Oracle on Windows machines. Many people find it easier to use than Oracle. DB2: IBM's DB2 was one of the earliest players in the database market. It is still very commonly used on mainframes and runs on both Windows and Unix.

Popular Open Source Databases


MySQL: Because of its small size, its speediness, and its support with solid documentation, MySQL has quickly become the most popular open source database. MySQL is available on several operating systems, including Windows and Unix. PostgreSQL: Until recently, PostgreSQL was the most popular open source database until that spot was taken over by MySQL. PostgreSQL now calls itself "the world's most advanced Open Source database software." The latest versions support features like native-language programming, advanced indexes and a query rewrite systemthat allows the database designer to create rules to dynamically transform operations on tables/views into alternate operations upon processing. A relational database at its simplest is a set of tables used for storing data. Each table has a unique name and may relate to one or more other tables in the database through common values.

Tables A table in a database is a collection of rows and columns. Tables are also known as entities or relations. Rows A row contains data pertaining to a single item or record in a table. Rows are also known as records or tuples. Columns A column contains data representing a specific characteristic of the records in the table. Columns are also known as fields or attributes. Relationships A relationship is a link between two tables (i.e, relations). Relationships make it possible to find data in one table that pertains to a specific record in another table. Datatypes Each of a table's columns has a defined datatype that specifies the type of data that can exist in that column. For example, the FirstName column might be defined as varchar(20), indicating that it can contain a string of up to 20 characters. Unfortunately, datatypes vary widely between databases. Primary Keys Most tables have a column or group of columns that can be used to identify records. For example, an Employees table might have a column called EmployeeID that is unique for every row. This makes it easy to keep track of a record over time and to associate a record with records in other tables. Foreign Keys Foreign key columns are columns that link to primary key columns in other tables,

Valid Object References server.database.owner.object server.database..object server..owner.object server...object database.owner.object database..object owner.object object SQL Statements Database Manipulation Language (DML) DML statements are used to work with data in an existing database. The most common DML statements are: SELECT INSERT REPLACE UPDATE DELETE Database Definition Language (DDL) DDL statements are used to structure objects in a database. The most common DDL statements are: CREATE ALTER DROP

Database Control Language (DCL) DCL statements are used for database administration. The most common DCL statements are: GRANT DENY (SQL Server Only) REVOKE Database Design Principles Modeling and designing a database comes first in any database application. Database design greatly impacts the development, performance, maintenance and the flexibility of the application. Bad decisions and errors of the design phase will continue to cause long-term trouble and ill- effects. Database design for any non-trivial application is not easy and usually requires experience. This lesson will present a quick refresher with some pointers to the fundamentals of relational databases. It summarizes different data types, table types available under MySQL, and demonstrates normalization rules. In addition, indexes and integrity rules such as foreign key constraints are also covered. The database design should be centered around the needs of various users, generally understood via a detailed requirement analysis of the system. A database designer must understand the usage patterns of the data. This understanding is reached by interviewing potential users towards analysis of the organization's database needs. The database designer must determine items such as: Data items to be stored Tasks or Operations to be performed with this data Frequency of these operations Restrictions and Constraints on the data

Basic Modeling Process: Creating a Data Model A relational model is based on tables and on the meaningful relationships between those tables. Specifically, a table is made up of columns and rows that form a table-like structure. The rows are identified through the use of primary keys, and the columns map to various attributes for an entity. Using these concepts, we design a database that adheres to the standards of the relational model. A data model for a relational database should show all of the following information:

The tables or potential entities that make up the database


The columns that make up each table The data type that defines each column The primary key that identifies each row The relationships that exist between tables Refine the data model towards full normalization

The Entity-Relationship Model The popular Entity-Relationship (ER) model is often used for modeling databases. Its benefits lie in its simplicity, clarity, and simple graphical representation of data and their relationships. Data is described using concepts such as "entities," "entity sets," "attributes," and "relationships." Entities And Entity Sets An entity is a distinct object distinguishable from other objects. For example, a film and a customer are two different entities. A collection of similar entities group to form entity sets. Attributes Properties of Entities are called attributes. For example, the rating of a film is an attribute of the entity film, and the last name and address of a customer are attributes of the entity customer. Attributes have values associated with them, individually identified with an entity. For example, a film has a rental rate of $3.99, and is different from another film with the same rate of $3.99. A customer entity whose attribute last name has the value Burke is different from another customer with last name as Hagan. Different attribute values distinguish similar entities in the same entity set from each other, but many entities can have the same attribute value. For example, there can be several film entities with the same rental rate.

An entity must have one or more attributes. All entities in an entity set have the

Relationships A relationship instance specifies an association between entities. For example, Customers reserve and rent films. The process of Reservations relates a customer and the films reserved. Entities can have several types of relationships: One-To-One: An entity in one entity set is associated with at most one entity in the other entity set and vice versa. One-To-Many: An entity in one entity set is associated with many (zero or more) entities in the other entity set. Many-To-One: Many (zero or more) entities in one entity set can be associated with one entity in the other entity set. Many-To-Many: Many (zero or more) entities in one entity set can be associated with many entities in the other entity set. Business rules indicate a relationship between two or more tables. Let us identify persistent (worth-storing) relationships in our sakila database. Customers reserve films - Many to many Customers have rental transactions on film copies - Many to many A film is of a certain category and in a certain language - Many to one Different staff reserves and rents films to customers - Many to many Relationships can also have attributes. They are used to give information about the relationship. For example, the rental_date attribute in the rent relationship can be used to describe when a film was rented.

Relationship Types
One of the defining characteristics of a relational database is the fact that various types of relationships exist between tables. These relationships allow the data in the tables to be associated with each other in meaningful ways that help ensure the integrity of normalized data. Because of these relationships, actions in one table cannot adversely affect data in another table. For any relational database, there are three fundamental types of relationships that can exist between tables: one-to-one relationships, oneto-many relationships, and many-to-many relationships. This section takes a look at each of these relationships.

One-to-One Relationships A one-to-one relationship can exist between any two tables in which a row in the first table can be related to only one row in the second table and a row in the second table can be related to only one row in the first table. Several different systems are used to represent the relationships between tables, all of which connect the tables with lines that have special notations at the ends of those lines. The examples in this lesson use a very basic system to represent the relationships. Generally, one-to-one relationships are the least likely type of relationships to be implemented in a relational database; however, there are sometimes reasons to use them. For example, you might want to separate tables simply because one table would contain too much data, or perhaps you would want to separate data into different tables so you could set up one table with a higher level of security. Even so, most databases contain relatively few, if any, one-to-one relationships. The most common type of relationship you're likely to find is the one-to-many.

One-to-Many Relationships As with one-to-one relationships, a one-to-many relationship can exist between any two tables in your database. A one-to-many relationship differs from a one-to-one relationship in that a row in the first table can be related to one or more rows in the second table, but a row in the second table can be related to only one row in the first table. A one-to-many relationship is probably the most common type of relationship you'll see in your databases. A many-to-one relationship is simply a reversing of the order in which the tables are referred. Many-to-Many Relationships A many-to-many relationship can exist between any two tables in which a row in the first table can be related to one or more rows in the second table, but a row in the second table can be related to one or more rows in the first table. When a many-to-many relationship exists, it is implemented by adding a third table between these two tables that matches the primary key values of one table to the primary key values of the second table, making a many-to-many relationship as logical.

Linking via Foreign Keys One other aspect to notice in the film table is the language_id column tagged FK1. FK is an acronym for a Foreign Key. As a foreign key, the language_id column contains a key values from the associated row in the language_id column in the language table. The foreign key represents a relationship between the two tables, designated by a line connecting the two tables. Graphical Representation of a Model The ER model allows the database design to be represented graphically: An entity set is represented by a rectangle. A relationship is represented by a diamond with lines connecting it to the entity sets that it relates. A "many" relationship is indicated by an "N" next to the line. A "one" relationship is indicated by a "1" next to the line. An attribute is represented by an oval connected by a solid line to the entity set rectangle or to the relationship diamond. As an example, consider the basic ER diagram for a few of sakila entities:

Modeling sakila - Film Rentals Database Our understanding so far leads us to model the sakila database as consisting of following entity sets: Customers, Transactions, Films, and following (named) relationships, Reservations between Customers and Films, and Rentals between Customers and Films. Note: Based on our experience, we interpret the non-specific requirement of storing name and address of a customer in practice as stored in component form, such as The first and last names of the customer should be stored separately as should the various sub-elements of the address. The attributes listed may not uniquely identify a customer (several customers can belong the same company, several customers can have the same name, a family can share an address, and so on). Moreover, it may also be desirable to have a single identifier to uniquely refer to a customer. Consequently, we will add an "ID" attribute, which will have a unique value for each customer. Let us examine the reservation operation ReservationId (a unique id that identifies each order), CustomerId, ReserveDate, Status, Each reservation must contain information about the customer and the film reserved. These attributes cannot be in Customers or in Films.

Here is a more complete ER model for some of the tables in the sakila database:

The key (unique value) attributes in the three entity sets are identified by shaded ovals. Note: ER modeling may not lead to a unique solution. Usually, complex

Physical Model: Mapping The ER Model To A Relational Database Each entity set in the ER model is represented by a table in a relational database. Attributes of an entity set becomes the columns of the table. Primary Key attributes such as film_id, uniquely identify members of the entity sets. Each relationship is also represented by a table. A relationship table includes the key columns of the two entity set tables it relates. Relationship attributes become columns of the relationship table. A one-to-many relationship table can be eliminated by storing the relationship information in one of the tables being related. This is also possible for many-to-one and one-to-one relationships. For example, relationships film.language or address.city do not need attributes, and it would be sufficient to simply put the language_id and city_id into the film and address entities. Note: For one-to-many and many-to-one relationships, the mapping information must be stored in the "many" entity set to avoid creating extra rows.

Database Normalization One of the concepts most important to a relational database is that of normalized data. Normalized data is organized into a structure that preserves the integrity (consistent with no loss) of the data while minimizing redundant data by keeping logically related data together. Once we have identified core entities and their attributes, we will normalize the data structure and further refine the tables and columns, one entity at a time. A normalized database contains table structures refined according to the normalization rules referred to as normal forms - With the introduction of relational model, Codd included three normal forms. Extended normal forms have been defined after than, but the first three remain central to a relational model.

There is often a trade-off and therefore a balancing point between strict adherence to the normal forms and system performance. Often, the more normalized the data, the more taxing it can be on a system. In most situations, the first three normal forms sufficiently provide that balance. As a start, memorize the 3 normal forms so that you can chant them in your sleep:
1NF: No repeating elements or groups of elements 2NF: No partial dependencies on a composite key 3NF: No dependencies on non-key attributes

First Normal Form For tables in the first normal form (1NF), each column in a row must be atomic. In other words, the column can contain only one value for any given row. Each row in a table must contain the same number of columns. Given that each column can contain only one value, this means that each row must contain the same number of values. All rows in a table must be different. Although rows might include the same values, each row, when taken as a whole, must be unique in the table. The 1NF property ensures that a data element or column or attribute of a row is NOT a composite or multi-valued item. The use of set valued column types can lead to redundancy, loss of data and inconsistency.

Second Normal Form

Tables in the second normal form (2NF) must be in 1NF and, All their columns not part of a key must be dependent upon the whole key, which can be a composite. Note: A primary key made up of more than one column is referred to as a composite primary key. As an example, suppose we have identified that entity film also contains rental information that differs for various cities where the films are rented. In other words, we have some data in this entity that is for a film and some data for the combination of city and film. This table is certainly NOT in 2NF ! A Non-key column rental_rate, that stores a rate for each film for a given city is in the film table. This rate does depend on film_id but also depends on a city_id. So moving out rental_rate column which depends on the non-key city column will make the film table be in 2NF (assuming it satisfies the 1NF requirement). Values of the eliminated rate column, will be fetched for a combination of a given store/city and a film. Before the move, the film table is not in 2NF. Note that changing the daily rate for a film without corresponding changes in column city_id will lead to data inconsistency.

Third Normal From Tables in the third normal form (3NF) must be in 2NF and, No non-key column should depend upon another non-key column. In other words, all non-key columns must depend only upon the entity's key. All nonprimary key columns in the table must be dependent on the primary key and must be independent of each other. A 2NF table can be converted to 3NF by removing the non-key columns whose values are determined by other non-key columns. For example, all films are made by a certain studio. If attributes like studiosize are present in the film table, it is not in 3NF, as the studio-size has no dependence on the film itself, rather the non-key studio which made the film. Moving studio-size into the studio entity will bring film closer to 3NF. Note: Specifying column B as being dependent (functionally dependent to be precise) upon column A is equivalent to saying that the values in column A determine the corresponding values in column B.

MySQL Triggers

Database triggers or triggers are SQL statements storing in the database catalog. Once a trigger is activated by database events such as UPDATE, DELETE or INSERT, it will execute either before or after the event that initiated it.

Advantages of using SQL trigger SQL Trigger provides an alternative way to check integrity. SQL trigger can catch the errors in business logic in the database level. SQL trigger provides an alternative way to run scheduled tasks. With SQL trigger, you dont have to wait to run the scheduled tasks. You can handle those tasks before or after changes being made to database tables. SQL trigger is very useful when you use it to audit the changes of data in a database table.

Disadvantages of using SQL trigger


SQL trigger only can provide extended validation and cannot replace all the validations. Some simple validations can be done in the application level. For example, you can validate input check in the client side by using javascript or in the server side by server script using PHP or ASP.NET. SQL Triggers executes invisibly from client-application which connects to the database server so it is difficult to figure out what happen underlying database layer. SQL Triggers run every updates made to the table therefore it adds workload to the database and cause system runs slower. Triggers or stored procedures? It depends on the the situation but it is practical that if you have no way to get

Trigger Implementation in MySQL


MySQL finally supports one of the most important features of an enterprise database server which is called trigger since version 5.0.2. Trigger is implemented in MySQL by following the syntax of standard SQL:2003. When you create a trigger in MySQL, its definition stores in the file with extension .TRG in a database folder with specific name as follows: /data_folder/database_name/table_name.trg The file is in plain text format so you can use any plain text editor to modify it. While trigger is implemented in MySQL has all features in standard SQL but there are some restrictions you should be aware of like following: It is not allowed to call a stored procedure in a trigger. It is not allowed to create a trigger for views or temporary table. It is not allowed to use transaction in a trigger. Return statement is disallowed in a trigger. Creating a trigger for a database table causes the query cache invalidated. Query cache allows you to store the result of query and corresponding select statement. In the next time, when the same select statement comes to the database server, the database server will use the result which stored in the memory instead of parsing and executing the query again. All trigger for a database table must have unique name. It is allowed that triggers for different tables having the same name but it is recommended that trigger should have unique name in a specific database. To create the trigger, you can use the following naming convention: (BEFORE |

CREATE TRIGGER statement is used to create triggers. The trigger name should follow the naming convention [trigger time]_[table name]_[trigger event], for example before_employees_update Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you define a trigger. You use BEFORE when you want to process action prior to the change being made in the table and AFTER if you need to process action after changes are made. Trigger event can be INSERT, UPDATE and DELETE. These events cause trigger to fire and process logic inside trigger body. A trigger only can fire with one event. To define trigger which are fired by multiple events, you have to define multiple triggers, one for each event. Be noted that any SQL statements make update data in database table will cause trigger to fire. For example, LOAD DATA statement insert records into a table will also cause the trigger associated with that table to fire. A trigger must be associated with a specific table. Without a table trigger does not exist so you have to specify the table name after the ON keyword. You can write the logic between BEGIN and END block of the trigger. MySQL gives you OLD and NEW keyword to help you write trigger more efficient. The OLD keyword refers to the existing row before you update data and the NEW keyword refers to the new row after you

Managing Trigger in MySQL Summary: In this tutorial, you will learn how to manage triggers in MySQL including listing all triggers in a given database or removing triggers. Once created trigger associated with a table, you can view the trigger by going directly to the folder which contains the trigger. Trigger is stored as plain text file in the database folder as follows: /data_folder/database_name/table_name.trg, with any plain text editor such as notepad you can view it. MySQL provides you another way to view the trigger by executing SQL statement:
1 SELECT * FROM Information_Schema.Trigger

WHERE Trigger_schema = 'database_name' AND

MySQL Views

A database view is known as a "virtual table" which allows you to query the data against it. Understanding database view and using it correctly are very important. In this section, you will learn how database view is, how it implemented in MySQL and how to use it effectively

Introduction to Database View


By definition, a database view or view is a virtual or logical table which is composed of result set of a SELECT query. Because the database view is similar to the database table which consists of row and column so you can retrieve and update data on it in the same way with table. The database view is dynamic because it is not related to the physical schema. Database view is stored as view definition as SELECT statements. When the tables which are the source data of a view changes; the data in the view change also.

Views Advantages
Database views provide several advantages as follows: Simplify complex query. A view is defined by an SQL statement with join on many underlying tables with complex business logic. The view now can be used to hides the complexity of underlying tables to the end users and external applications. Only simple SQL statement is used to work with view. Limited access data to the specific users. You may dont want a subset of sensitive data can be retrievable by all users (both human and applications). You can use view to expose what data to which user to limit the access. Provide extra security. Security is vital parts of any relational database management system.Views provide extra security the database management system. View allows you to create only read-only view to expose read-only data to specific user. User can only retrieve data in read-only view but cannot update it. Computed column. The database table should not have the calculated columns in it so you can use views to create computed columns. Suppose in the orderDetails table you havequantityOrder (number of ordered product) and priceEach (price per product item) columns but it

Backward compatibility. You have a center database and all applications use that database as their sources of data. One day you redesign the database to make it more clean and normalized. You then move the entire legacy data into the new database but you dont want affect the legacy application in accessing it. In this case, you can use views to make them like the legacy database schema and return the same data so the legacy application wont be affected.

MySQL Views MySQL supports views from version 5.x and almost views features conform to the SQL: 2003 standard. Queries of views in MySQL are processed in two ways:
MySQL creates a temporary table based on the query which defined the view and then execute the input query on this table. MySQL first combines the input query and query which defined the view, then MySQL executes this query. MySQL supports versioning system for views. Each time when the view is altered or replaced, a copy of the existing view is back up in arc (archive) folder which is resided in specific database folder. The name of back up file is view_name.frm00001. If you later change the view again, it will be named as view_name.frm-00002. MySQL also allows you to create views of views. In the SELECT statement of view definition, you can reference to another views. If the cached is enabled, the query against view is stored in the cache. As the result, it increases the performance of query by

Algorithms
The algorithm attribute allows you to control which mechanism is used when creating a view. MERGE means the input query will combine with the SELECT statement in the view definition and MySQL will execute the combined query to return the result set. This mechanism is more efficient than using TEMPTABLE (temporary table) but MERGE only allowed when the rows in the view represent a one-to-one relationship with the rows in the underlying table. In case the MERGE is not allowed, MySQL will switch the algorithm to UNDEFINED. The combination of input query and query in view definition into one query sometimes refers as view resolution. TEMPTABLE means MySQL first create a temporary table based on SELECT statements in the view definition, and then it executes the input query against this temporary table. Because MySQL has to create temporary table to store the result set so it has to move the data from the real database table to the temporary table therefore TEMPTABLE mechanism is less

View name
Each view is associated with a specific database therefore you can have database name prefix with the view name. View name is shared the same domain with tables so it cannot be the same name with existing tables or other views within a database. SELECT statement In SELECT statement, you can query any tables or views existed in the database. There are several rules which SELECT statement has to follows: Subquery cannot be included in the SELECT statement. Any variables such as local, user and session variables cannot be used in the SELECT statement. The prepared statement cannot be used in the view. Temporary tables or views cannot be used in the SELECT

Creating Updateable Views


Views are not only read-only but also updateable. However in order to create an updateable view, the SELECT statement which defines View has to follow several following rules: SELECT statement must not reference to more than one table. It means it must not contain more than one table in FROM clause, other tables in JOIN statement, or UNION with other tables. SELECT statement must not use GROUP BY or HAVING clause. SELECT statement must not use DISTINCT in the selection list. SELECT statement must not reference to the view that is not updateable SELECT statement must not contain any expression (aggregates, functions, computed columns)

Sample codes using Query browser

Sample code: create database db_mysql; use db_mysql; show databases;

Sample codes: create database db_mysql; use db_mysql; CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255)); show databases; show tables;

create database db_mysql; use db_mysql; CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255)); show databases; show tables; select * from Persons;

create database db_mysql; use db_mysql; CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255)); show databases; show tables; select * from Persons; insert into Persons values('1','Bautista','Guia Lynn','San Pedro Sto.Tomas','Batangas City'); insert into Persons values('2','Reazo','Rachel','San Joaquin Sto.Tomas','Batangas city');

The actual view of the sample code

You might also like