Search This Blog
Showing posts with label MySQL Database Tutorial. Show all posts
Showing posts with label MySQL Database Tutorial. Show all posts
MySQL : Restore Database From the Command Prompt
mysql - u user_name -p your_password database_name < file_name.sql
MySQL : Backup Database From the Command Prompt
mysqldump -u user_name -p your_password database_name > File_name.sql
MySQL Function : mysql_affected_rows
Get number of affected rows in previous MySQL operation
Description
int mysql_affected_rows ([ resource $link_identifier ] )
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier .
Example #
The above example will output something similar to:
Records deleted: 10
Records deleted: 0
Description
int mysql_affected_rows ([ resource $link_identifier ] )
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier .
Example #
= mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id <>);
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
The above example will output something similar to:
Records deleted: 10
Records deleted: 0
MySQL : Have the new Query Analyzer graphs helped you solve development problems internally?
We use it about every day for our own products, specifically for finding performance issues in development. For example, one of the things we found in this release was that we had more updates than we expected compared to the previous version. We learned it because we saw a peak in “updates” in the row activity graph in the Enterprise Monitor. We highlighted the peak in the updates, and we figured out exactly which part of our code related to these updates through the Query Analyzer, and finally we fixed the problem. This process would have taken much longer if we did it manually because it was actually a certain set of updates that were increasing at a certain point of time, while other normal updates were happening at the same time. If we just looked at the logs, it wouldn't have been as obvious which one was causing that increase.
In addition, our support team also runs the Query Analyzer on internal servers, and they actually found some problem queries. In some occasions they solve performance issues that they didn't know the root cause; in other situations they see the performance drop and have actually been able to tune some queries that they didn't even know were problematic.
In addition, our support team also runs the Query Analyzer on internal servers, and they actually found some problem queries. In some occasions they solve performance issues that they didn't know the root cause; in other situations they see the performance drop and have actually been able to tune some queries that they didn't even know were problematic.
MySQL : How do the Query Analyzer graphs benefit customers?
It saves a lot of time. The first release of the Query Analyzer saved a lot of time by removing the need to send query activity to logs, gather all that information, and post-process the data in order to figure out which queries were running, how often and for how long. The logical next step was correlating this information with the metrics the Enterprise Monitor collects and displays the data with graphs. If you see something happening performance-wise in the Enterprise Monitor, using the correlation graphs you can very quickly see what queries were happening at that time, before that time or even after that time from a query perspective in the Query Analyzer. That was possible to do in our earlier release, except that it was a very manual process.
MySQL : What type of metrics can be correlated with the Query Analyzer?
Any graph you see, anything we collect – that could be anything from operating system metrics, such as CPU usage, memory usage, I/O counters, to MySQL-specific counters. You can look at the query profiles over time, i.e. how many selects and updates and other classes of queries were running at any point of time, connections created, threads created, InnoDB row accesses, buffer pool, locks taken over time -- all of these are implemented in this correlation graph feature.
MySQL Useful Function
Here is the list of all important MySQL functions. Each function has been explained along with suitable example.
MySQL Group By Clause - The MySQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result dataset by certain database table column(s).
MySQL IN Clause - This is a clause which can be used alongwith any MySQL query to specify a condition.
MySQL BETWEEN Clause - This is a clause which can be used alongwith any MySQL query to specify a condition.
MySQL UNION Keyword - Use a UNION operation to combine multiple result sets into one.
MySQL COUNT Function - The MySQL COUNT aggregate function is used to count the number of rows in a database table.
MySQL MAX Function - The MySQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.
MySQL MIN Function - The MySQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
MySQL AVG Function - The MySQL AVG aggregate function selects the average value for certain table column.
MySQL SUM Function - The MySQL SUM aggregate function allows selecting the total for a numeric column.
MySQL SQRT Functions - This is used to generate a square root of a given number.
MySQL RAND Function - This is used to generate a random number using MySQL command.
MySQL CONCAT Function - This is used to concatenate any string inside any MySQL command.
MySQL DATE and Time Functions - Complete list of MySQL Date and Time related functions.
MySQL Numeric Functions - Complete list of MySQL functions required to manipulate numbers in MySQL.
MySQL String Functions - Complete list of MySQL functions required to manipulate strings in MySQL.
MySQL Group By Clause - The MySQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result dataset by certain database table column(s).
MySQL IN Clause - This is a clause which can be used alongwith any MySQL query to specify a condition.
MySQL BETWEEN Clause - This is a clause which can be used alongwith any MySQL query to specify a condition.
MySQL UNION Keyword - Use a UNION operation to combine multiple result sets into one.
MySQL COUNT Function - The MySQL COUNT aggregate function is used to count the number of rows in a database table.
MySQL MAX Function - The MySQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.
MySQL MIN Function - The MySQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
MySQL AVG Function - The MySQL AVG aggregate function selects the average value for certain table column.
MySQL SUM Function - The MySQL SUM aggregate function allows selecting the total for a numeric column.
MySQL SQRT Functions - This is used to generate a square root of a given number.
MySQL RAND Function - This is used to generate a random number using MySQL command.
MySQL CONCAT Function - This is used to concatenate any string inside any MySQL command.
MySQL DATE and Time Functions - Complete list of MySQL Date and Time related functions.
MySQL Numeric Functions - Complete list of MySQL functions required to manipulate numbers in MySQL.
MySQL String Functions - Complete list of MySQL functions required to manipulate strings in MySQL.
MySQL Database Import - Recovery Methods
There are two simple ways in MySQL to load data into MySQL database from a previously backed up file.
Importing Data with LOAD DATA:
MySQL provides a LOAD DATA statement that acts as a bulk data loader. Here's an example statement that reads a file dump.txt from your current directory and loads it into the table mytbl in the current database:
mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl;
If the LOCAL keyword is not present, MySQL looks for the datafile on the server host using looking into absolute pathname fully specifies the location of the file, beginning from the root of the filesystem. MySQL reads the file from the given location.
By default, LOAD DATA assumes that datafiles contain lines that are terminated by linefeeds (newlines) and that data values within a line are separated by tabs.
To specify a file format explicitly, use a FIELDS clause to describe the characteristics of fields within a line, and a LINES clause to specify the line-ending sequence. The following LOAD DATA statement specifies that the datafile contains values separated by colons and lines terminated by carriage returns and new line character:
mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl
-> FIELDS TERMINATED BY ':'
-> LINES TERMINATED BY '\r\n';
LOAD DATA assumes the columns in the datafile have the same order as the columns in the table. If that's not true, you can specify a list to indicate which table columns the datafile columns should be loaded into. Suppose your table has columns a, b, and c, but successive columns in the datafile correspond to columns b, c, and a. You can load the file like this:
mysql> LOAD DATA LOCAL INFILE 'dump.txt'
-> INTO TABLE mytbl (b, c, a);
Importing Data with mysqlimport
MySQL also includes a utility program named mysqlimport that acts as a wrapper around LOAD DATA so that you can load input files directly from the command line.
To load a data from dump.txt into mytbl use following command at UNIX prompt.
$ mysqlimport -u root -p --local database_name dump.txt
password *****
If you use mysqlimport, command-line options provide the format specifiers. mysqlimport commands that correspond to the preceding two LOAD DATA statements look like this:
$ mysqlimport -u root -p --local --fields-terminated-by=":" \
--lines-terminated-by="\r\n" database_name dump.txt
password *****
The order in which you specify the options doesn't matter for mysqlimport, except that they should all precede the database name.
The mysqlimport statement uses the --columns option to specify the column order:
$ mysqlimport -u root -p --local --columns=b,c,a \
database_name dump.txt
password *****
Handling Quotes and Special Characters:
The FIELDS clause can specify other format options besides TERMINATED BY. By default, LOAD DATA assumes that values are unquoted, and interprets the backslash (\) as an escape character for special characters. To indicate the value quoting character explicitly, use ENCLOSED BY; MySQL will strip that character from the ends of data values during input processing. To change the default escape character, use ESCAPED BY.
When you specify ENCLOSED BY to indicate that quote characters should be stripped from data values, it's possible to include the quote character literally within data values by doubling it or by preceding it with the escape character. For example, if the quote and escape characters are " and \, the input value "a""b\"c" will be interpreted as a"b"c.
For mysqlimport, the corresponding command-line options for specifying quote and escape values are --fields-enclosed-by and --fields-escaped-by
Importing Data with LOAD DATA:
MySQL provides a LOAD DATA statement that acts as a bulk data loader. Here's an example statement that reads a file dump.txt from your current directory and loads it into the table mytbl in the current database:
mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl;
If the LOCAL keyword is not present, MySQL looks for the datafile on the server host using looking into absolute pathname fully specifies the location of the file, beginning from the root of the filesystem. MySQL reads the file from the given location.
By default, LOAD DATA assumes that datafiles contain lines that are terminated by linefeeds (newlines) and that data values within a line are separated by tabs.
To specify a file format explicitly, use a FIELDS clause to describe the characteristics of fields within a line, and a LINES clause to specify the line-ending sequence. The following LOAD DATA statement specifies that the datafile contains values separated by colons and lines terminated by carriage returns and new line character:
mysql> LOAD DATA LOCAL INFILE 'dump.txt' INTO TABLE mytbl
-> FIELDS TERMINATED BY ':'
-> LINES TERMINATED BY '\r\n';
LOAD DATA assumes the columns in the datafile have the same order as the columns in the table. If that's not true, you can specify a list to indicate which table columns the datafile columns should be loaded into. Suppose your table has columns a, b, and c, but successive columns in the datafile correspond to columns b, c, and a. You can load the file like this:
mysql> LOAD DATA LOCAL INFILE 'dump.txt'
-> INTO TABLE mytbl (b, c, a);
Importing Data with mysqlimport
MySQL also includes a utility program named mysqlimport that acts as a wrapper around LOAD DATA so that you can load input files directly from the command line.
To load a data from dump.txt into mytbl use following command at UNIX prompt.
$ mysqlimport -u root -p --local database_name dump.txt
password *****
If you use mysqlimport, command-line options provide the format specifiers. mysqlimport commands that correspond to the preceding two LOAD DATA statements look like this:
$ mysqlimport -u root -p --local --fields-terminated-by=":" \
--lines-terminated-by="\r\n" database_name dump.txt
password *****
The order in which you specify the options doesn't matter for mysqlimport, except that they should all precede the database name.
The mysqlimport statement uses the --columns option to specify the column order:
$ mysqlimport -u root -p --local --columns=b,c,a \
database_name dump.txt
password *****
Handling Quotes and Special Characters:
The FIELDS clause can specify other format options besides TERMINATED BY. By default, LOAD DATA assumes that values are unquoted, and interprets the backslash (\) as an escape character for special characters. To indicate the value quoting character explicitly, use ENCLOSED BY; MySQL will strip that character from the ends of data values during input processing. To change the default escape character, use ESCAPED BY.
When you specify ENCLOSED BY to indicate that quote characters should be stripped from data values, it's possible to include the quote character literally within data values by doubling it or by preceding it with the escape character. For example, if the quote and escape characters are " and \, the input value "a""b\"c" will be interpreted as a"b"c.
For mysqlimport, the corresponding command-line options for specifying quote and escape values are --fields-enclosed-by and --fields-escaped-by
MySQL Database Export and Backup
The simplest way of exporting a table data into a text file is using SELECT...INTO OUTFILE statement that exports a query result directly into a file on the server host.
Exporting Data with the SELECT ... INTO OUTFILE Statement:
The syntax for this statement combines a regular SELECT with INTO OUTFILE filename at the end. The default output format is the same as for LOAD DATA, so the following statement exports the tutorials_tbl table into /tmp/tutorials.txt as a tab-delimited, linefeed-terminated file:
mysql> SELECT * FROM tutorials_tbl
-> INTO OUTFILE '/tmp/tutorials.txt';
You can change the output format using options to indicate how to quote and delimit columns and records. To export the tutorial_tbl table in CSV format with CRLF-terminated lines, use this statement:
mysql> SELECT * FROM passwd INTO OUTFILE '/tmp/tutorials.txt'
-> FIELDS TERMINATED BY ',' ENCLOSED BY '"'
-> LINES TERMINATED BY '\r\n';
The SELECT ... INTO OUTFILE has the following properties:
The output file is created directly by the MySQL server, so the filename should indicate where you want the file to be written on the server host. There is no LOCAL version of the statement analogous to the LOCAL version of LOAD DATA.
You must have the MySQL FILE privilege to execute the SELECT ... INTO statement.
The output file must not already exist. This prevents MySQL from clobbering files that may be important.
You should have a login account on the server host or some way to retrieve the file from that host. Otherwise, SELECT ... INTO OUTFILE likely will be of no value to you.
Under Unix, the file is created world readable and is owned by the MySQL server. This means that although you'll be able to read the file, you may not be able to delete it.
Exporting Tables as Raw Data:
The mysqldump program is used to copy or back up tables and databases. It can write table output either as a raw datafile, or as a set of INSERT statements that recreate the records in the table.
To dump a table as a datafile, you must specify a --tab option that indicates the directory where you want the MySQL server to write the file.
For example, to dump the tutorials_tbl table from the TUTORIALS database to a file in the /tmp directory, use a command like this:
$ mysqldump -u root -p --no-create-info \
--tab=/tmp TUTORIALS tutorials_tbl
password ******
Exporting Table Contents or Definitions in SQL Format:
To export a table in SQL format to a file, use a command like this:
$ mysqldump -u root -p TUTORIALS tutorials_tbl > dump.txt
password ******
This will create file having content as follows:
--------------------------------------------------------------------------------
-- MySQL dump 8.23
--
-- Host: localhost Database: TUTORIALS
---------------------------------------------------------
-- Server version 3.23.58
--
-- Table structure for table `tutorials_tbl`
--
CREATE TABLE tutorials_tbl (
tutorial_id int(11) NOT NULL auto_increment,
tutorial_title varchar(100) NOT NULL default '',
tutorial_author varchar(40) NOT NULL default '',
submission_date date default NULL,
PRIMARY KEY (tutorial_id),
UNIQUE KEY AUTHOR_INDEX (tutorial_author)
) TYPE=MyISAM;
--
-- Dumping data for table `tutorials_tbl`
--
INSERT INTO tutorials_tbl
VALUES (1,'Learn PHP','John Poul','2007-05-24');
INSERT INTO tutorials_tbl
VALUES (2,'Learn MySQL','Abdul S','2007-05-24');
INSERT INTO tutorials_tbl
VALUES (3,'JAVA Tutorial','Sanjay','2007-05-06');
To dump multiple tables, name them all following the database name argument. To dump an entire database, don't name any tables after the database as follows:
$ mysqldump -u root -p TUTORIALS > database_dump.txt
password ******
To backup all the databases available on your host use the following:
$ mysqldump -u root -p --all-databases > database_dump.txt
password ******
The --all-databases option is available as of MySQL 3.23.12.
These method can be used to implement a database backup stretegy.
Copying Tables or Databases to Another Host:
If you want to copy tables or databases from one MySQL server to another then use mysqldump with database name and table name.
Run the following command at source host. This will dump complete database into dump.txt file:
$ mysqldump -u root -p database_name table_name > dump.txt
password *****
You can copy complete database without using a particular table name as explained above.
Now ftp dump.txt file on another host and use the following command. Before running this command, make sure you have created database_name on destination server.
$ mysql -u root -p database_name < dump.txt
password *****
Another way to accomplish this without using an intermediary file is to send the output of mysqldump directly over the network to the remote MySQL server. If you can connect to both servers from the host where the cookbook database resides, use this command:
$ mysqldump -u root -p database_name \
states | mysql -h other-host.com database_name
The mysqldump half of the command connects to the local server and writes the dump output to the pipe. The mysql half of the command connects to the remote MySQL server on otherhost.com. It reads the pipe for input and sends each statement to the other-host.com server.
Exporting Data with the SELECT ... INTO OUTFILE Statement:
The syntax for this statement combines a regular SELECT with INTO OUTFILE filename at the end. The default output format is the same as for LOAD DATA, so the following statement exports the tutorials_tbl table into /tmp/tutorials.txt as a tab-delimited, linefeed-terminated file:
mysql> SELECT * FROM tutorials_tbl
-> INTO OUTFILE '/tmp/tutorials.txt';
You can change the output format using options to indicate how to quote and delimit columns and records. To export the tutorial_tbl table in CSV format with CRLF-terminated lines, use this statement:
mysql> SELECT * FROM passwd INTO OUTFILE '/tmp/tutorials.txt'
-> FIELDS TERMINATED BY ',' ENCLOSED BY '"'
-> LINES TERMINATED BY '\r\n';
The SELECT ... INTO OUTFILE has the following properties:
The output file is created directly by the MySQL server, so the filename should indicate where you want the file to be written on the server host. There is no LOCAL version of the statement analogous to the LOCAL version of LOAD DATA.
You must have the MySQL FILE privilege to execute the SELECT ... INTO statement.
The output file must not already exist. This prevents MySQL from clobbering files that may be important.
You should have a login account on the server host or some way to retrieve the file from that host. Otherwise, SELECT ... INTO OUTFILE likely will be of no value to you.
Under Unix, the file is created world readable and is owned by the MySQL server. This means that although you'll be able to read the file, you may not be able to delete it.
Exporting Tables as Raw Data:
The mysqldump program is used to copy or back up tables and databases. It can write table output either as a raw datafile, or as a set of INSERT statements that recreate the records in the table.
To dump a table as a datafile, you must specify a --tab option that indicates the directory where you want the MySQL server to write the file.
For example, to dump the tutorials_tbl table from the TUTORIALS database to a file in the /tmp directory, use a command like this:
$ mysqldump -u root -p --no-create-info \
--tab=/tmp TUTORIALS tutorials_tbl
password ******
Exporting Table Contents or Definitions in SQL Format:
To export a table in SQL format to a file, use a command like this:
$ mysqldump -u root -p TUTORIALS tutorials_tbl > dump.txt
password ******
This will create file having content as follows:
--------------------------------------------------------------------------------
-- MySQL dump 8.23
--
-- Host: localhost Database: TUTORIALS
---------------------------------------------------------
-- Server version 3.23.58
--
-- Table structure for table `tutorials_tbl`
--
CREATE TABLE tutorials_tbl (
tutorial_id int(11) NOT NULL auto_increment,
tutorial_title varchar(100) NOT NULL default '',
tutorial_author varchar(40) NOT NULL default '',
submission_date date default NULL,
PRIMARY KEY (tutorial_id),
UNIQUE KEY AUTHOR_INDEX (tutorial_author)
) TYPE=MyISAM;
--
-- Dumping data for table `tutorials_tbl`
--
INSERT INTO tutorials_tbl
VALUES (1,'Learn PHP','John Poul','2007-05-24');
INSERT INTO tutorials_tbl
VALUES (2,'Learn MySQL','Abdul S','2007-05-24');
INSERT INTO tutorials_tbl
VALUES (3,'JAVA Tutorial','Sanjay','2007-05-06');
To dump multiple tables, name them all following the database name argument. To dump an entire database, don't name any tables after the database as follows:
$ mysqldump -u root -p TUTORIALS > database_dump.txt
password ******
To backup all the databases available on your host use the following:
$ mysqldump -u root -p --all-databases > database_dump.txt
password ******
The --all-databases option is available as of MySQL 3.23.12.
These method can be used to implement a database backup stretegy.
Copying Tables or Databases to Another Host:
If you want to copy tables or databases from one MySQL server to another then use mysqldump with database name and table name.
Run the following command at source host. This will dump complete database into dump.txt file:
$ mysqldump -u root -p database_name table_name > dump.txt
password *****
You can copy complete database without using a particular table name as explained above.
Now ftp dump.txt file on another host and use the following command. Before running this command, make sure you have created database_name on destination server.
$ mysql -u root -p database_name < dump.txt
password *****
Another way to accomplish this without using an intermediary file is to send the output of mysqldump directly over the network to the remote MySQL server. If you can connect to both servers from the host where the cookbook database resides, use this command:
$ mysqldump -u root -p database_name \
states | mysql -h other-host.com database_name
The mysqldump half of the command connects to the local server and writes the dump output to the pipe. The mysql half of the command connects to the remote MySQL server on otherhost.com. It reads the pipe for input and sends each statement to the other-host.com server.
MySQL Handling Duplicate
Tables or result sets sometimes contain duplicate records. Sometime it is allowed but sometime it is required to stop duplicate records. Sometime it is required to identify duplicate records and remove them from the table. This chapter will describe how to prevent duplicate records occurring in a table and how to remove already existing duplicate records.
Preventing Duplicates from Occurring in a Table:
You can use a PRIMARY KEY or UNIQUE Index on a table with appropriate fields to stop duplicate records. Lets take one example, The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name
CREATE TABLE person_tbl
(
first_name CHAR(20),
last_name CHAR(20),
sex CHAR(10)
);
To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it's also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values:
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
sex CHAR(10)
PRIMARY KEY (last_name, first_name)
);
The presence of a unique index in a table normally causes an error to occur if you insert a record into the table that duplicates an existing record in the column or columns that define the index.
Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error.
Following example does not error out and same time it will not insert duplicate records.
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( 'Jay', 'Thomas');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( 'Jay', 'Thomas');
Query OK, 0 rows affected (0.00 sec)
Use REPLACE rather than INSERT. If the record is new, it's inserted just as with INSERT. If it's a duplicate, the new record replaces the old one:
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( 'Ajay', 'Kumar');
Query OK, 1 row affected (0.00 sec)
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( 'Ajay', 'Kumar');
Query OK, 2 rows affected (0.00 sec)
INSERT IGNORE and REPLACE should be chosen according to the duplicate-handling behavior you want to effect. INSERT IGNORE keeps the first of a set of duplicated records and discards the rest. REPLACE keeps the last of a set of duplicates and erase out any earlier ones.
Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
sex CHAR(10)
UNIQUE (last_name, first_name)
);
Counting and Identifying Duplicates:
Following is the query to count duplicate records with first_name and last_name in a table.
mysql> SELECT COUNT(*) as repetitions, last_name, first_name
-> FROM person_tbl
-> GROUP BY last_name, first_name
-> HAVING repetitions > 1;
This query will return a list of all the duplicate records in person_tbl table. In general, to identify sets of values that are duplicated, do the following:
Determine which columns contain the values that may be duplicated.
List those columns in the column selection list, along with COUNT(*).
List the columns in the GROUP BY clause as well.
Add a HAVING clause that eliminates unique values by requiring group counts to be greater than one.
Eliminating Duplicates from a Query Result:
You can use DISTINCT along with SELECT statement to find out unique records available in a table.
mysql> SELECT DISTINCT last_name, first_name
-> FROM person_tbl
-> ORDER BY last_name;
An alternative to DISTINCT is to add a GROUP BY clause that names the columns you're selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns:
mysql> SELECT last_name, first_name
-> FROM person_tbl
-> GROUP BY (last_name, first_name);
Removing Duplicates Using Table Replacement:
If you have duplicate records in a table and you want to remove all the duplicate records from that table then here is the procedure.
mysql> CREATE TABLE tmp SELECT last_name, first_name, sex
-> FROM person_tbl;
-> GROUP BY (last_name, first_name);
mysql> DROP TABLE person_tbl;
mysql> ALTER TABLE tmp RENAME TO person_tbl;
An easy way of removing duplicate records from a table is that add an INDEX or PRIMAY KEY to that table. Even if this table is already available you can use this technique to remove duplicate records and you will be safe in future as well.
mysql> ALTER IGNORE TABLE person_tbl
-> ADD PRIMARY KEY (last_name, first_name);
Preventing Duplicates from Occurring in a Table:
You can use a PRIMARY KEY or UNIQUE Index on a table with appropriate fields to stop duplicate records. Lets take one example, The following table contains no such index or primary key, so it would allow duplicate records for first_name and last_name
CREATE TABLE person_tbl
(
first_name CHAR(20),
last_name CHAR(20),
sex CHAR(10)
);
To prevent multiple records with the same first and last name values from being created in this table, add a PRIMARY KEY to its definition. When you do this, it's also necessary to declare the indexed columns to be NOT NULL, because a PRIMARY KEY does not allow NULL values:
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
sex CHAR(10)
PRIMARY KEY (last_name, first_name)
);
The presence of a unique index in a table normally causes an error to occur if you insert a record into the table that duplicates an existing record in the column or columns that define the index.
Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error.
Following example does not error out and same time it will not insert duplicate records.
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( 'Jay', 'Thomas');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( 'Jay', 'Thomas');
Query OK, 0 rows affected (0.00 sec)
Use REPLACE rather than INSERT. If the record is new, it's inserted just as with INSERT. If it's a duplicate, the new record replaces the old one:
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( 'Ajay', 'Kumar');
Query OK, 1 row affected (0.00 sec)
mysql> REPLACE INTO person_tbl (last_name, first_name)
-> VALUES( 'Ajay', 'Kumar');
Query OK, 2 rows affected (0.00 sec)
INSERT IGNORE and REPLACE should be chosen according to the duplicate-handling behavior you want to effect. INSERT IGNORE keeps the first of a set of duplicated records and discards the rest. REPLACE keeps the last of a set of duplicates and erase out any earlier ones.
Another way to enforce uniqueness is to add a UNIQUE index rather than a PRIMARY KEY to a table.
CREATE TABLE person_tbl
(
first_name CHAR(20) NOT NULL,
last_name CHAR(20) NOT NULL,
sex CHAR(10)
UNIQUE (last_name, first_name)
);
Counting and Identifying Duplicates:
Following is the query to count duplicate records with first_name and last_name in a table.
mysql> SELECT COUNT(*) as repetitions, last_name, first_name
-> FROM person_tbl
-> GROUP BY last_name, first_name
-> HAVING repetitions > 1;
This query will return a list of all the duplicate records in person_tbl table. In general, to identify sets of values that are duplicated, do the following:
Determine which columns contain the values that may be duplicated.
List those columns in the column selection list, along with COUNT(*).
List the columns in the GROUP BY clause as well.
Add a HAVING clause that eliminates unique values by requiring group counts to be greater than one.
Eliminating Duplicates from a Query Result:
You can use DISTINCT along with SELECT statement to find out unique records available in a table.
mysql> SELECT DISTINCT last_name, first_name
-> FROM person_tbl
-> ORDER BY last_name;
An alternative to DISTINCT is to add a GROUP BY clause that names the columns you're selecting. This has the effect of removing duplicates and selecting only the unique combinations of values in the specified columns:
mysql> SELECT last_name, first_name
-> FROM person_tbl
-> GROUP BY (last_name, first_name);
Removing Duplicates Using Table Replacement:
If you have duplicate records in a table and you want to remove all the duplicate records from that table then here is the procedure.
mysql> CREATE TABLE tmp SELECT last_name, first_name, sex
-> FROM person_tbl;
-> GROUP BY (last_name, first_name);
mysql> DROP TABLE person_tbl;
mysql> ALTER TABLE tmp RENAME TO person_tbl;
An easy way of removing duplicate records from a table is that add an INDEX or PRIMAY KEY to that table. Even if this table is already available you can use this technique to remove duplicate records and you will be safe in future as well.
mysql> ALTER IGNORE TABLE person_tbl
-> ADD PRIMARY KEY (last_name, first_name);
MySQL Sequences
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently used in databases because many applications require each row in a table to contain a unique value, and sequences provide an easy way to generate them. This chapter describes how to use sequences in MySQL.
Using AUTO_INCREMENT column:
The simplest way in MySQL to use Sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care.
Example:
Try out following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because its auto incremented by MySQL.
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO insect (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM insect ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
Obtain AUTO_INCREMENT Values:
LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. otherwise PERL and PHH scripts provide exclusive functions to retrieve auto incremented value of last record.
PERL Example:
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle:
$dbh->do ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};
PHP Example:
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ):
mysql_query ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);
Renumbering an Existing Sequence:
There may be a case when you have deleted many records from a table and you want to resequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having join with other table.
If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique:
mysql> ALTER TABLE insect DROP id;
mysql> ALTER TABLE insect
-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
-> ADD PRIMARY KEY (id);
Starting a Sequence at a Particular Value:
By default MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100.
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE.
mysql> ALTER TABLE t AUTO_INCREMENT = 100;
Using AUTO_INCREMENT column:
The simplest way in MySQL to use Sequences is to define a column as AUTO_INCREMENT and leave rest of the things to MySQL to take care.
Example:
Try out following example. This will create table and after that it will insert few rows in this table where it is not required to give record ID because its auto incremented by MySQL.
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO insect (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM insect ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
Obtain AUTO_INCREMENT Values:
LAST_INSERT_ID( ) is a SQL function, so you can use it from within any client that understands how to issue SQL statements. otherwise PERL and PHH scripts provide exclusive functions to retrieve auto incremented value of last record.
PERL Example:
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This attribute is accessed through either a database handle or a statement handle, depending on how you issue the query. The following example references it through the database handle:
$dbh->do ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};
PHP Example:
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling mysql_insert_id( ):
mysql_query ("INSERT INTO insect (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);
Renumbering an Existing Sequence:
There may be a case when you have deleted many records from a table and you want to resequence all the records. This can be done by using a simple trick but you should be very careful to do so if your table is having join with other table.
If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again. The following example shows how to renumber the id values in the insect table using this technique:
mysql> ALTER TABLE insect DROP id;
mysql> ALTER TABLE insect
-> ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
-> ADD PRIMARY KEY (id);
Starting a Sequence at a Particular Value:
By default MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation. Following is the example where MySQL will start sequence from 100.
mysql> CREATE TABLE insect
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT = 100,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE.
mysql> ALTER TABLE t AUTO_INCREMENT = 100;
MySQL Database Info
There are three information which you would like to have from MySQL.
Information about the result of queries: This includes number of records effected by any SELECT, UPDATE or DELETE statement.
Information about tables and databases: This includes information pertaining to the structure of tables and databases.
Information about the MySQL server: This includes current status of database server, version number etc.
Its very easy to get all these information at mysql prompt. BUt while using PERL or PHP APIs then we need to call various APIs explicitely to obtain all these information. Following section will show you how to obtain these information.
Obtaining the Number of Rows Affected by a Query:
PERL Example:
In DBI scripts, the affected-rows count is returned by do( ) or by execute( ), depending on how you execute the query:
# Method 1
# execute $query using do( )
my $count = $dbh->do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
# Method 2
# execute query using prepare( ) plus execute( )
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
Information about the result of queries: This includes number of records effected by any SELECT, UPDATE or DELETE statement.
Information about tables and databases: This includes information pertaining to the structure of tables and databases.
Information about the MySQL server: This includes current status of database server, version number etc.
Its very easy to get all these information at mysql prompt. BUt while using PERL or PHP APIs then we need to call various APIs explicitely to obtain all these information. Following section will show you how to obtain these information.
Obtaining the Number of Rows Affected by a Query:
PERL Example:
In DBI scripts, the affected-rows count is returned by do( ) or by execute( ), depending on how you execute the query:
# Method 1
# execute $query using do( )
my $count = $dbh->do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
# Method 2
# execute query using prepare( ) plus execute( )
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
MySQL Clone Tables
There may be a situation when you need an exact copy of a table, and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values, and so forth.
You can handle this situation by following steps.
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have exact clone table.
Optionally, If you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Example:
Try out following example to create a clone table for tutorials_tbl
Step 1:
Get complete structure about table
mysql> SHOW CREATE TABLE tutorials_tbl \G;
*************************** 1. row ***************************
Table: tutorials_tbl
Create Table: CREATE TABLE `tutorials_tbl` (
`tutorial_id` int(11) NOT NULL auto_increment,
`tutorial_title` varchar(100) NOT NULL default '',
`tutorial_author` varchar(40) NOT NULL default '',
`submission_date` date default NULL,
PRIMARY KEY (`tutorial_id`),
UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
) TYPE=MyISAM
1 row in set (0.00 sec)
ERROR:
No query specified
Step 2:
Rename this table and create another table
mysql> CREATE TABLE `clone_tbl` (
-> `tutorial_id` int(11) NOT NULL auto_increment,
-> `tutorial_title` varchar(100) NOT NULL default '',
-> `tutorial_author` varchar(40) NOT NULL default '',
-> `submission_date` date default NULL,
-> PRIMARY KEY (`tutorial_id`),
-> UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
-> ) TYPE=MyISAM;
Query OK, 0 rows affected (1.80 sec)
Step 3:
After executing step 2 you will a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
mysql> INSERT INTO clone_tbl (tutorial_id,
-> tutorial_title,
-> tutorial_author,
-> submission_date)
-> SELECT tutorial_id,tutorial_title,
-> tutorial_author,submission_date,
-> FROM tutorials_tbl;
Query OK, 3 rows affected (0.07 sec)
Records: 3 Duplicates: 0 Warnings: 0
Finally you will have exact clone table as you wanted to have.
You can handle this situation by following steps.
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have exact clone table.
Optionally, If you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Example:
Try out following example to create a clone table for tutorials_tbl
Step 1:
Get complete structure about table
mysql> SHOW CREATE TABLE tutorials_tbl \G;
*************************** 1. row ***************************
Table: tutorials_tbl
Create Table: CREATE TABLE `tutorials_tbl` (
`tutorial_id` int(11) NOT NULL auto_increment,
`tutorial_title` varchar(100) NOT NULL default '',
`tutorial_author` varchar(40) NOT NULL default '',
`submission_date` date default NULL,
PRIMARY KEY (`tutorial_id`),
UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
) TYPE=MyISAM
1 row in set (0.00 sec)
ERROR:
No query specified
Step 2:
Rename this table and create another table
mysql> CREATE TABLE `clone_tbl` (
-> `tutorial_id` int(11) NOT NULL auto_increment,
-> `tutorial_title` varchar(100) NOT NULL default '',
-> `tutorial_author` varchar(40) NOT NULL default '',
-> `submission_date` date default NULL,
-> PRIMARY KEY (`tutorial_id`),
-> UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
-> ) TYPE=MyISAM;
Query OK, 0 rows affected (1.80 sec)
Step 3:
After executing step 2 you will a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
mysql> INSERT INTO clone_tbl (tutorial_id,
-> tutorial_title,
-> tutorial_author,
-> submission_date)
-> SELECT tutorial_id,tutorial_title,
-> tutorial_author,submission_date,
-> FROM tutorials_tbl;
Query OK, 3 rows affected (0.07 sec)
Records: 3 Duplicates: 0 Warnings: 0
Finally you will have exact clone table as you wanted to have.
MySQL Temporary Tables
The temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be knows for temporary tables is that they will be deleted when the current client session terminates.
Temporary tables where added in MySQL version 3.23. If you use an older version of MySQL than 3.23 you can't use temporary tables, but you can use heap tables.
As stated earlier temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQl database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.
Example
Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysql_query() function.
mysql> CREATE TEMPORARY TABLE SalesSummary (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SalesSummary
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command then your temporary table would not be listed out in the list. Now if you will log out of the MySQL session and then you will issue a SELECT command then you will find no data available in the database. Even your temporary table would also not exist.
Dropping Temporary Tables:
By default all the temporary tables are deleted by MySQL when your database connection gets terminated. Still you want to delete them in between then you do so by issuing DROP TABLE command.
Following is the example on dropping a temproary table.
mysql> CREATE TEMPORARY TABLE SalesSummary (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SalesSummary
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SalesSummary;
mysql> SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist
Temporary tables where added in MySQL version 3.23. If you use an older version of MySQL than 3.23 you can't use temporary tables, but you can use heap tables.
As stated earlier temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQl database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.
Example
Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysql_query() function.
mysql> CREATE TEMPORARY TABLE SalesSummary (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SalesSummary
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command then your temporary table would not be listed out in the list. Now if you will log out of the MySQL session and then you will issue a SELECT command then you will find no data available in the database. Even your temporary table would also not exist.
Dropping Temporary Tables:
By default all the temporary tables are deleted by MySQL when your database connection gets terminated. Still you want to delete them in between then you do so by issuing DROP TABLE command.
Following is the example on dropping a temproary table.
mysql> CREATE TEMPORARY TABLE SalesSummary (
-> product_name VARCHAR(50) NOT NULL
-> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
-> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
-> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO SalesSummary
-> (product_name, total_sales, avg_unit_price, total_units_sold)
-> VALUES
-> ('cucumber', 100.25, 90, 2);
mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber | 100.25 | 90.00 | 2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SalesSummary;
mysql> SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist
MySQL INDEXES
A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
While creating index it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, Indexes are also type of tables which keeps primary key or index field and a pointer to each record in to the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements takes more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to inert or update index values as well.
Simple and Unique Index:
You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example we can create an index on tutorials_tbl using tutorial_author
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can creates a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name:
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
ALTER command to add and drop INDEX:
There are four types of statements for adding indexes to a table:
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) : This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD INDEX index_name (column_list): This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): This creates a special FULLTEXT index that is used for text-searching purposes.
Here is the example to add index in an existing table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created index.
mysql> ALTER TABLE testalter_tbl DROP INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created inde x.
ALTER Command to add and drop PRIMARY KEY:
You can add primary key as well in the same way. But make sure Primary Key works on columns which are NOT NULL.
Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can use ALTER command to drop a primary key as follows:
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.
Displaying INDEX Information:
You can use SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound:
Try out following example:
mysql> SHOW INDEX FROM table_name\G
........
While creating index it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, Indexes are also type of tables which keeps primary key or index field and a pointer to each record in to the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements takes more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to inert or update index values as well.
Simple and Unique Index:
You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example we can create an index on tutorials_tbl using tutorial_author
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can creates a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name:
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)
ALTER command to add and drop INDEX:
There are four types of statements for adding indexes to a table:
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) : This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
ALTER TABLE tbl_name ADD INDEX index_name (column_list): This adds an ordinary index in which any value may appear more than once.
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): This creates a special FULLTEXT index that is used for text-searching purposes.
Here is the example to add index in an existing table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created index.
mysql> ALTER TABLE testalter_tbl DROP INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created inde x.
ALTER Command to add and drop PRIMARY KEY:
You can add primary key as well in the same way. But make sure Primary Key works on columns which are NOT NULL.
Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can use ALTER command to drop a primary key as follows:
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.
Displaying INDEX Information:
You can use SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound:
Try out following example:
mysql> SHOW INDEX FROM table_name\G
........
MySQL ALTER Command
MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table.
Lets begin with creation of a table called testalter_tbl
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table testalter_tbl
-> (
-> i INT,
-> c CHAR(1)
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| i | int(11) | YES | | NULL | |
| c | char(1) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Dropping, Adding, or Repositioning a Column:
Suppose you want to drop an existing column i from above MySQL table then you will use DROP clause along with ALTER command as follows
mysql> ALTER TABLE testalter_tbl DROP i;
A DROP will not work if the column is the only one left in the table.
To add a column, use ADD and specify the column definition. The following statement restores the i column to testalter_tbl
mysql> ALTER TABLE testalter_tbl ADD i INT;
After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have quite the same structure. That's because new columns are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one:
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column, or AFTER col_name to indicate that the new column should be placed after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has:
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT FIRST;
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT AFTER c;
The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.
Changing a Column Definition or Name:
To change a column's definition, use MODIFY or CHANGE clause along with ALTER command. For example, to change column c from CHAR(1) to CHAR(10), do this:
mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);
With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name. Try out following example:
mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;
If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement be as expected:
mysql> ALTER TABLE testalter_tbl CHANGE j j INT;
The Effect of ALTER TABLE on Null and Default Value Attributes:
When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values, and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes.
Here is the example where NOT NULL column will have value 100 by default.
mysql> ALTER TABLE testalter_tbl
-> MODIFY j BIGINT NOT NULL DEFAULT 100;
If you don't use above command then MySQL will fill up NULL values in all the columns.
Changing a Column's Default Value:
You can change a default value for any column using ALTER command. Try out following example.
mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | 1000 | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
You can remove default constraint from any column by using DROP clause along with ALTER command.
mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Changing a Table Type:
You can use a table type by using TYPE clause alongwith ALTER command. Try out following example to change testalter_tbl to MYISAM table type.
To find out the current type of a table, use the SHOW TABLE STATUS statement.
mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;
mysql> SHOW TABLE STATUS LIKE 'testalter_tbl'\G
*************************** 1. row ****************
Name: testalter_tbl
Type: MyISAM
Row_format: Fixed
Rows: 0
Avg_row_length: 0
Data_length: 0
Max_data_length: 25769803775
Index_length: 1024
Data_free: 0
Auto_increment: NULL
Create_time: 2007-06-03 08:04:36
Update_time: 2007-06-03 08:04:36
Check_time: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
Renaming a Table:
To rename a table, use the RENAME option of the ALTER TABLE statement. Try out following example to rename testalter_tbl to alter_tbl
mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;
You can use ALTER command to create and drop INDEX on a MySQL file. We will see this feature in next chapter.
Lets begin with creation of a table called testalter_tbl
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table testalter_tbl
-> (
-> i INT,
-> c CHAR(1)
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| i | int(11) | YES | | NULL | |
| c | char(1) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Dropping, Adding, or Repositioning a Column:
Suppose you want to drop an existing column i from above MySQL table then you will use DROP clause along with ALTER command as follows
mysql> ALTER TABLE testalter_tbl DROP i;
A DROP will not work if the column is the only one left in the table.
To add a column, use ADD and specify the column definition. The following statement restores the i column to testalter_tbl
mysql> ALTER TABLE testalter_tbl ADD i INT;
After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have quite the same structure. That's because new columns are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one:
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column, or AFTER col_name to indicate that the new column should be placed after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has:
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT FIRST;
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT AFTER c;
The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.
Changing a Column Definition or Name:
To change a column's definition, use MODIFY or CHANGE clause along with ALTER command. For example, to change column c from CHAR(1) to CHAR(10), do this:
mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);
With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name. Try out following example:
mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;
If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement be as expected:
mysql> ALTER TABLE testalter_tbl CHANGE j j INT;
The Effect of ALTER TABLE on Null and Default Value Attributes:
When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values, and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes.
Here is the example where NOT NULL column will have value 100 by default.
mysql> ALTER TABLE testalter_tbl
-> MODIFY j BIGINT NOT NULL DEFAULT 100;
If you don't use above command then MySQL will fill up NULL values in all the columns.
Changing a Column's Default Value:
You can change a default value for any column using ALTER command. Try out following example.
mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | 1000 | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
You can remove default constraint from any column by using DROP clause along with ALTER command.
mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c | char(1) | YES | | NULL | |
| i | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Changing a Table Type:
You can use a table type by using TYPE clause alongwith ALTER command. Try out following example to change testalter_tbl to MYISAM table type.
To find out the current type of a table, use the SHOW TABLE STATUS statement.
mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;
mysql> SHOW TABLE STATUS LIKE 'testalter_tbl'\G
*************************** 1. row ****************
Name: testalter_tbl
Type: MyISAM
Row_format: Fixed
Rows: 0
Avg_row_length: 0
Data_length: 0
Max_data_length: 25769803775
Index_length: 1024
Data_free: 0
Auto_increment: NULL
Create_time: 2007-06-03 08:04:36
Update_time: 2007-06-03 08:04:36
Check_time: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
Renaming a Table:
To rename a table, use the RENAME option of the ALTER TABLE statement. Try out following example to rename testalter_tbl to alter_tbl
mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;
You can use ALTER command to create and drop INDEX on a MySQL file. We will see this feature in next chapter.
MySQL Transactions
A transaction is a sequential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will never be complete unless each individual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail.
Practically you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.
Consistency: ensures that the database properly changes states upon a successfully committed transaction.
Isolation: enables transactions to operate independently of and transparent to each other.
Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.
In MySQL, transactions begin with the statement BEGIN WORK and end with either a COMMIT or a ROLLBACK statement. The SQL commands between the beginning and ending statements form the bulk of the transaction.
COMMIT and ROLLBACK:
These two keywords Commit and Rollback are mainly used for MySQL Transactions.
When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect.
If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state.
You can control the behavior of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction, and committed by default when it finishes. When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT=0 command, the subsequent series of statements acts like a transaction, and no activities are committed until an explicit COMMIT statement is issued.
You can execute these SQL commands in PHP by using mysql_query() function.
Generic Example on Transaction
This sequence of events is independent of the programming language used; the logical path can be created in whichever language you use to create your application.
You can execute these SQL commands in PHP by using mysql_query() function.
Begin transaction by issuing SQL command BEGIN WORK
Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE
Check if there is no error and everything is according to your requirement.
If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
Transaction-Safe Table Types in MySQL:
You can not use transactions directly, you can but they would not be save and guaranteed. If you plan to use transactions in your MySQL programming then you need to create your tables in a special way. There are many type of tables which support transactions but most popular one is InnoDB.
Support for InnoDB tables requires a specific compilation parameter when compiling MySQL from source. If your MySQL version does not have InnoDB support, ask your Internet Service Provider to build a version of MySQL with support for InnoDB table types, or download and install the MySQL-Max binary distribution for Windows or Linux/UNIX and work with the table type in a development environment.
If your MySQL installation supports InnoDB tables, simply add a TYPE=InnoDB definition to the table creation statement. For example, the following code creates an InnoDB table called tcount_tbl:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table tcount_tbl
-> (
-> tutorial_author varchar(40) NOT NULL,
-> tutorial_count INT
-> ) TYPE=InnoDB;
Query OK, 0 rows affected (0.05 sec)
Practically you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.
Consistency: ensures that the database properly changes states upon a successfully committed transaction.
Isolation: enables transactions to operate independently of and transparent to each other.
Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.
In MySQL, transactions begin with the statement BEGIN WORK and end with either a COMMIT or a ROLLBACK statement. The SQL commands between the beginning and ending statements form the bulk of the transaction.
COMMIT and ROLLBACK:
These two keywords Commit and Rollback are mainly used for MySQL Transactions.
When a successful transaction is completed, the COMMIT command should be issued so that the changes to all involved tables will take effect.
If a failure occurs, a ROLLBACK command should be issued to return every table referenced in the transaction to its previous state.
You can control the behavior of a transaction by setting session variable called AUTOCOMMIT. If AUTOCOMMIT is set to 1 (the default), then each SQL statement (within a transaction or not) is considered a complete transaction, and committed by default when it finishes. When AUTOCOMMIT is set to 0, by issuing the SET AUTOCOMMIT=0 command, the subsequent series of statements acts like a transaction, and no activities are committed until an explicit COMMIT statement is issued.
You can execute these SQL commands in PHP by using mysql_query() function.
Generic Example on Transaction
This sequence of events is independent of the programming language used; the logical path can be created in whichever language you use to create your application.
You can execute these SQL commands in PHP by using mysql_query() function.
Begin transaction by issuing SQL command BEGIN WORK
Issue one or more SQL commands like SELECT, INSERT, UPDATE or DELETE
Check if there is no error and everything is according to your requirement.
If there is any error then issue ROLLBACK command otherwise issue a COMMIT command.
Transaction-Safe Table Types in MySQL:
You can not use transactions directly, you can but they would not be save and guaranteed. If you plan to use transactions in your MySQL programming then you need to create your tables in a special way. There are many type of tables which support transactions but most popular one is InnoDB.
Support for InnoDB tables requires a specific compilation parameter when compiling MySQL from source. If your MySQL version does not have InnoDB support, ask your Internet Service Provider to build a version of MySQL with support for InnoDB table types, or download and install the MySQL-Max binary distribution for Windows or Linux/UNIX and work with the table type in a development environment.
If your MySQL installation supports InnoDB tables, simply add a TYPE=InnoDB definition to the table creation statement. For example, the following code creates an InnoDB table called tcount_tbl:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table tcount_tbl
-> (
-> tutorial_author varchar(40) NOT NULL,
-> tutorial_count INT
-> ) TYPE=InnoDB;
Query OK, 0 rows affected (0.05 sec)
MySQL Regexps
You have seen MySQL pattern matching with LIKE ...%. MySQL supports another type of pattern matching operation based on regular expressions and the REGEXP operator. If you are aware of PHP or PERL then its very simple for you to understand because this matching is very similar to those scripting regular expressions.
Following is the table of pattern which can be used along with REGEXP operator.
Pattern What the pattern matches
^ Beginning of string
$ End of string
. Any single character
[...] Any character listed between the square brackets
[^...] Any character not listed between the square brackets
p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3
* Zero or more instances of preceding element
+ One or more instances of preceding element
{n} n instances of preceding element
{m,n} m through n instances of preceding element
Examples:
Now based on above table you can device various type of SQL queries to meet your requirements. Here I'm listing few for your understanding. Consider we have a table called person_tbl and its having a field called name:
Query to find all the names starting with 'st'
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';
Query to find all the names ending with 'ok'
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';
Query to find all the names which contains 'mar'
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';
Query to find all the names starting with a vowel and ending with 'ok'
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$';
Following is the table of pattern which can be used along with REGEXP operator.
Pattern What the pattern matches
^ Beginning of string
$ End of string
. Any single character
[...] Any character listed between the square brackets
[^...] Any character not listed between the square brackets
p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3
* Zero or more instances of preceding element
+ One or more instances of preceding element
{n} n instances of preceding element
{m,n} m through n instances of preceding element
Examples:
Now based on above table you can device various type of SQL queries to meet your requirements. Here I'm listing few for your understanding. Consider we have a table called person_tbl and its having a field called name:
Query to find all the names starting with 'st'
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';
Query to find all the names ending with 'ok'
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';
Query to find all the names which contains 'mar'
mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';
Query to find all the names starting with a vowel and ending with 'ok'
mysql> SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$';
MySQL NULL Value
We have seen SQL SELECT command along with WHERE clause to fetch data from MySQL table. But when we try to give a condition which compare field or column value to NULL it does not work properly.
To handle such situation MySQL provides three operators
IS NULL: operator returns true of column value is NULL.
IS NOT NULL: operator returns true of column value is not NULL.
<=> operator compare values, which (unlike the = operator) is true even for two NULL values
Conditions involving NULL are special. You cannot use = NULL or != NULL to look for NULL values in columns. Such comparisons always fail because it's impossible to tell whether or not they are true. Even NULL = NULL fails.
To look for columns that are or are not NULL, use IS NULL or IS NOT NULL.
Using NULL values at Command Prompt:
Suppose a table tcount_tbl in TUTORIALS database and it contains two columns tutorial_author and tutorial_count, where a NULL tutorial_count indicates that the value is unknown:
Example:
Try out following examples:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table tcount_tbl
-> (
-> tutorial_author varchar(40) NOT NULL,
-> tutorial_count INT
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('mahran', 20);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('mahnaz', NULL);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('Jen', NULL);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('Gill', 20);
mysql> SELECT * from tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| mahnaz | NULL |
| Jen | NULL |
| Gill | 20 |
+-----------------+----------------+
4 rows in set (0.00 sec)
mysql>
You can see that = and != do not work with NULL values as follows:
mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
Empty set (0.00 sec)
mysql> SELECT * FROM tcount_tbl WHERE tutorial_count != NULL;
Empty set (0.01 sec)
To find records where the tutorial_count column is or is not NULL, the queries should be written like this:
mysql> SELECT * FROM tcount_tbl
-> WHERE tutorial_count IS NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahnaz | NULL |
| Jen | NULL |
+-----------------+----------------+
2 rows in set (0.00 sec)
mysql> SELECT * from tcount_tbl
-> WHERE tutorial_count IS NOT NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| Gill | 20 |
+-----------------+----------------+
2 rows in set (0.00 sec)
Handling NULL Values in PHP Script:
You can use if...else condition to prepare a query based on NULL value.
Example:
Following example take tutorial_count from outside and then compare it with the value available in the table.
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if( isset($tutorial_count ))
{
$sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl
WHERE tutorial_count = $tutorial_count';
}
else
{
$sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl
WHERE tutorial_count IS $tutorial_count';
}
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']}
".
"Count: {$row['tutorial_count']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
To handle such situation MySQL provides three operators
IS NULL: operator returns true of column value is NULL.
IS NOT NULL: operator returns true of column value is not NULL.
<=> operator compare values, which (unlike the = operator) is true even for two NULL values
Conditions involving NULL are special. You cannot use = NULL or != NULL to look for NULL values in columns. Such comparisons always fail because it's impossible to tell whether or not they are true. Even NULL = NULL fails.
To look for columns that are or are not NULL, use IS NULL or IS NOT NULL.
Using NULL values at Command Prompt:
Suppose a table tcount_tbl in TUTORIALS database and it contains two columns tutorial_author and tutorial_count, where a NULL tutorial_count indicates that the value is unknown:
Example:
Try out following examples:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table tcount_tbl
-> (
-> tutorial_author varchar(40) NOT NULL,
-> tutorial_count INT
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('mahran', 20);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('mahnaz', NULL);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('Jen', NULL);
mysql> INSERT INTO tcount_tbl
-> (tutorial_author, tutorial_count) values ('Gill', 20);
mysql> SELECT * from tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| mahnaz | NULL |
| Jen | NULL |
| Gill | 20 |
+-----------------+----------------+
4 rows in set (0.00 sec)
mysql>
You can see that = and != do not work with NULL values as follows:
mysql> SELECT * FROM tcount_tbl WHERE tutorial_count = NULL;
Empty set (0.00 sec)
mysql> SELECT * FROM tcount_tbl WHERE tutorial_count != NULL;
Empty set (0.01 sec)
To find records where the tutorial_count column is or is not NULL, the queries should be written like this:
mysql> SELECT * FROM tcount_tbl
-> WHERE tutorial_count IS NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahnaz | NULL |
| Jen | NULL |
+-----------------+----------------+
2 rows in set (0.00 sec)
mysql> SELECT * from tcount_tbl
-> WHERE tutorial_count IS NOT NULL;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| Gill | 20 |
+-----------------+----------------+
2 rows in set (0.00 sec)
Handling NULL Values in PHP Script:
You can use if...else condition to prepare a query based on NULL value.
Example:
Following example take tutorial_count from outside and then compare it with the value available in the table.
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if( isset($tutorial_count ))
{
$sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl
WHERE tutorial_count = $tutorial_count';
}
else
{
$sql = 'SELECT tutorial_author, tutorial_count
FROM tcount_tbl
WHERE tutorial_count IS $tutorial_count';
}
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']}
".
"Count: {$row['tutorial_count']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
MySQL Joins
Thus far we have only been getting data from one table at a time. This is fine for simple takes, but in most real world MySQL usage you will often need to get data from multiple tables in a single query.
You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table.
You can use JOINS in SELECT, UPDATE and DELETE statements to join MySQL tables. We will see an example of LEFT JOIN also which is different from simple MySQL JOIN.
Using Joins at Command Prompt:
Suppose we have two tables tcount_tbl and tutorials_tbl in TUTORIALS. A complete listing is given below:
Example:
Try out following examples:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * FROM tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| mahnaz | NULL |
| Jen | NULL |
| Gill | 20 |
| John Poul | 1 |
| Sanjay | 1 |
+-----------------+----------------+
6 rows in set (0.01 sec)
mysql> SELECT * from tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | John Poul | 2007-05-24 |
| 2 | Learn MySQL | Abdul S | 2007-05-24 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-06 |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.00 sec)
mysql>
Now we can write a SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pickup corresponding number of tutorials fromtcount_tbl. mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
-> FROM tutorials_tbl a, tcount_tbl b
-> WHERE a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
2 rows in set (0.01 sec)
mysql>
Using Joins in PHP Script:
You can use any of the above mentioned SQL query in PHP script. You only need to pass SQL query into PHP function mysql_query() and then you will fetch results in usual way.
Example:
Try out following example:
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a, tcount_tbl b
WHERE a.tutorial_author = b.tutorial_author';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']}
".
"Count: {$row['tutorial_count']}
".
"Tutorial ID: {$row['tutorial_id']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
MySQL LEFT JOIN:
A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives extra consideration to the table that is on the left.
If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join - thus ensuring (in my example) that every AUTHOR gets a mention:
Example:
Try out following example to understand LEFT JOIN:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
-> FROM tutorials_tbl a LEFT JOIN tcount_tbl b
-> ON a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 2 | Abdul S | NULL |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
3 rows in set (0.02 sec)
You would need to do more practice to become familiar with JOINS. This is a but complex concept in MySQL/SQL and will become more clear while doing real examples.
You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table.
You can use JOINS in SELECT, UPDATE and DELETE statements to join MySQL tables. We will see an example of LEFT JOIN also which is different from simple MySQL JOIN.
Using Joins at Command Prompt:
Suppose we have two tables tcount_tbl and tutorials_tbl in TUTORIALS. A complete listing is given below:
Example:
Try out following examples:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * FROM tcount_tbl;
+-----------------+----------------+
| tutorial_author | tutorial_count |
+-----------------+----------------+
| mahran | 20 |
| mahnaz | NULL |
| Jen | NULL |
| Gill | 20 |
| John Poul | 1 |
| Sanjay | 1 |
+-----------------+----------------+
6 rows in set (0.01 sec)
mysql> SELECT * from tutorials_tbl;
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 1 | Learn PHP | John Poul | 2007-05-24 |
| 2 | Learn MySQL | Abdul S | 2007-05-24 |
| 3 | JAVA Tutorial | Sanjay | 2007-05-06 |
+-------------+----------------+-----------------+-----------------+
3 rows in set (0.00 sec)
mysql>
Now we can write a SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pickup corresponding number of tutorials fromtcount_tbl. mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
-> FROM tutorials_tbl a, tcount_tbl b
-> WHERE a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
2 rows in set (0.01 sec)
mysql>
Using Joins in PHP Script:
You can use any of the above mentioned SQL query in PHP script. You only need to pass SQL query into PHP function mysql_query() and then you will fetch results in usual way.
Example:
Try out following example:
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
FROM tutorials_tbl a, tcount_tbl b
WHERE a.tutorial_author = b.tutorial_author';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Author:{$row['tutorial_author']}
".
"Count: {$row['tutorial_count']}
".
"Tutorial ID: {$row['tutorial_id']}
".
"--------------------------------
";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
MySQL LEFT JOIN:
A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives extra consideration to the table that is on the left.
If I do a LEFT JOIN, I get all records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join - thus ensuring (in my example) that every AUTHOR gets a mention:
Example:
Try out following example to understand LEFT JOIN:
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count
-> FROM tutorials_tbl a LEFT JOIN tcount_tbl b
-> ON a.tutorial_author = b.tutorial_author;
+-------------+-----------------+----------------+
| tutorial_id | tutorial_author | tutorial_count |
+-------------+-----------------+----------------+
| 1 | John Poul | 1 |
| 2 | Abdul S | NULL |
| 3 | Sanjay | 1 |
+-------------+-----------------+----------------+
3 rows in set (0.02 sec)
You would need to do more practice to become familiar with JOINS. This is a but complex concept in MySQL/SQL and will become more clear while doing real examples.
Subscribe to:
Posts (Atom)