Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Jun 21, 2011

Last updating time Storing in MySQL field

We can keep one date & time field in a record of MySQL table which automatically gets updated with current time and date when the record is added. For example we are adding names to a user or member table. In the member table there will be more fields like name, email, password etc but for simplicity we will use three fields only. One field is id which is a auto increment field, next one is name field and last tm is a datetime field. Here once we add name to the table the id automatically gets generated as it is an auto increment field and the field tm stores the date and time value showing the time of record insertion. 

We are not inserting current date time by calculating through PHP to the table like given here. 

While creating the table we will set the tm field ( DATETIME) Attributes to ON UPDATE CURRENT_TIMESTAMP and Default value to NOW(). 

See the MySQL dump to create the table here.
CREATE TABLE `test_time2` (
`id` int(2) NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`tm` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;


Now once the table is created use this command to add one record. Note that we are only adding the name field value. 


insert into test_time2 (name) values('my_name')


After executing the query you can see tm field has the current date and time value, as usual the id field has the new unique id for the record. Now let us try to update the same record by using this query. 


update test_time2 set name='my_name1' where name='my_name'


After using the above query you can see the value of tm files also changed and now it has the new date and time value of when record was updated. 

If you are giving option to change password in a member table then such a field can be kept to keep the last updated time of the record. 

Another application is if you are storing the login time of the members. You can update one field and show the visitors their last login time. Here before updating the current login info you have to collect the previous record and display. 

Apr 27, 2011

MySQL DELETE Statement across Multiple Tables Tutorial

Single-table syntax:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
For the single-table syntax, the DELETE statement deletes rows from tbl_name and returns a count of the number of deleted rows. This count can be obtained by calling the ROW_COUNT() function. The WHERE clause, if given, specifies the conditions that identify which rows to delete. With no WHERE clause, all rows are deleted. If the ORDER BY clause is specified, the rows are deleted in the order that is specified. The LIMIT clause places a limit on the number of rows that can be deleted.
Multiple-table syntax:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]
OR
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]
For the multiple-table syntax, DELETE deletes from each tbl_name the rows that satisfy the conditions. In this case, ORDER BY and LIMIT cannot be used.
where_condition is an expression that evaluates to true for each row to be deleted.
Important facts:
  • Currently, you cannot delete from a table and select from the same table in a subquery.
  • You need the DELETE privilege on a table to delete rows from it. You need only the SELECT privilege for any columns that are only read, such as those named in the WHERE clause.
  • DELETE statement with no WHERE clause deletes all rows. A faster way to do this, when you do not need to know the number of deleted rows, is to use TRUNCATE TABLE. However, within a transaction or if you have a lock on the table, TRUNCATE TABLE cannot be used whereas DELETE can.
  • If you delete the row containing the maximum value for an AUTO_INCREMENT column, the value is reused later for a BDB table, but not for a MyISAM or InnoDB table.
  • If you delete all rows in the table with DELETE FROM tbl_name (without a WHERE clause) in autocommit mode, the sequence starts over for all storage engines except InnoDB and MyISAM. There are some exceptions to this behavior for InnoDB tables.
  • The time required to delete individual rows is exactly proportional to the number of indexes. To delete rows more quickly, you can increase the size of the key cache by increasing the key_buffer_size system variable.
  • To delete all rows from a table, TRUNCATE TABLE tbl_name is faster than than DELETE FROM tbl_name. Truncate operations are not transaction-safe; an error occurs when attempting one in the course of an active transaction or active table lock.
The DELETE statement supports the following modifiers:
  • If you specify LOW_PRIORITY, the server delays execution of the DELETE until no other clients are reading from the table. This affects only storage engines that use only table-level locking (MyISAM, MEMORY, MERGE).
  • For MyISAM tables, if you use the QUICK keyword, the storage engine does not merge index leaves during delete, which may speed up some kinds of delete operations.
  • The IGNORE keyword causes MySQL to ignore all errors during the process of deleting rows. (Errors encountered during the parsing stage are processed in the usual manner.) Errors that are ignored due to the use of IGNORE are returned as warnings.
Examples:
DELETE FROM user WHERE name = ‘Veer’;
This query will delete all the rows from the table user.
DELETE FROM user WHERE name = ‘Veer’ LIMIT 4;
Normally, MySQL makes no guarantees about which four records selected by the WHERE clause it will delete. An ORDER BY clause in conjunction with LIMIT provides better control.
DELETE FROM user WHERE name = ‘Veer’ ORDER BY id LIMIT 4;
This will delete the first four record from the table sorted in the ascending order of id field. That means it leaves the records which has higher id value.
Multiple-table DELETE statements can be written in two formats. For the first multiple-table syntax, only matching rows from the tables listed before the FROM clause are deleted. For the second multiple-table syntax, only matching rows from the tables listed in the FROM clause (before the USING clause) are deleted. The effect is that you can delete rows from many tables at the same time and have additional tables that are used only for searching. The following example demonstrates one syntax, for a query that deletes rows from a table t1 where the id values match those in a table t2:
DELETE t1 FROM t1, t2 WHERE t1.id = t2.id;
The second syntax is slightly different:
DELETE FROM t1 USING t1, t2 WHERE t1.id = t2.id;
To delete the matching records from both tables, the statements are:
      DELETE t1, t2 FROM t1, t2 WHERE t1.id = t2.id;
Or
DELETE FROM t1, t2 USING t1, t2 WHERE t1.id = t2.id;
Delete statement using JOINS
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
Or
DELETE FROM t1, t2 USING t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
Above both statements use all three tables when searching for rows to delete, but delete matching rows only from tables t1 and t2.
DELETE t1 FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL;
Above statement delete rows that exist in t1 that have no match in t2.
In DELETE statement you can use the alias also like this:
DELETE a1, a2 FROM db1.t1 AS a1 INNER JOIN db2.t2 AS a2
WHERE a1.id=a2.id;
DELETE Statement using a group by function and on single table.
DELETE FROM employee USING employee INNER JOIN (SELECT employee_id
FROM employee
GROUP BY employee_id
HAVING COUNT(*)>1) AS emp USING (employee_id);
DELETE statement can work with multiple joins
DELETE a1, a2, a3, a4, a5
FROM atom AS a1
LEFT JOIN atom_desc AS a2 ON a2.desc_id = a1.id
LEFT JOIN atom_review AS a3 ON a3.review_id = a2.id
LEFT JOIN atom_content AS a4 ON a4.content_id = a1.id
LEFT JOIN atom_history AS a5 ON a5.history_id = a4.id
WHERE a1.name = ‘Veer’;

Apr 25, 2011

Exporting and importing data in MySQL

In this part of the MySQL tutorial, we will be exporting data from MySQL database and importing data back.

Simple data export

In our first example, we will save data in a text file.
mysql> SELECT * FROM Cars INTO OUTFILE '/tmp/cars';
Query OK, 8 rows affected (0.00 sec)
We select all rows (8) from the Cars table into the cars file located in the /tmp directory. We need to have permissions to write to that directory.
$ cat /tmp/cars
1       Audi    52642
2       Mercedes        57127
3       Skoda   9000
4       Volvo   29000
5       Bentley 350000
6       Citroen 21000
7       Hummer  41400
8       Volkswagen      21600
We show the contents of the file.
mysql> DELETE FROM Cars;

mysql> LOAD DATA INFILE '/tmp/cars' INTO TABLE Cars;
In the first statement we delete all rows from the table. In the second statement we load all data from the text file into the Cars table.

mysql> SELECT * FROM Cars INTO OUTFILE '/tmp/cars.csv'
    -> FIELDS TERMINATED BY ',';
In the above SQL statement, we dump all data from the Cars table into a cars.csv file. The FIELDS TERMINATED BY clause controls, how the data will be terminated in the text file. We have chosen a comma character. The csv stands for Comma Separated Values and it is a very common and very portable file format. It can be imported by numerous other applications. Like OpenOffice, other databases etc.
$ cat /tmp/cars.csv 
1,Audi,52642
2,Mercedes,57127
3,Skoda,9000
4,Volvo,29000
5,Bentley,350000
6,Citroen,21000
7,Hummer,41400
8,Volkswagen,21600
This is the contents of the cars.csv file.
mysql> DELETE FROM Cars;

mysql> LOAD DATA INFILE '/tmp/cars.csv' INTO TABLE Cars
    -> FIELDS TERMINATED BY ',';

mysql> SELECT * FROM Cars;
+----+------------+--------+
| Id | Name       | Cost   |
+----+------------+--------+
|  1 | Audi       |  52642 |
|  2 | Mercedes   |  57127 |
|  3 | Skoda      |   9000 |
|  4 | Volvo      |  29000 |
|  5 | Bentley    | 350000 |
|  6 | Citroen    |  21000 |
|  7 | Hummer     |  41400 |
|  8 | Volkswagen |  21600 |
+----+------------+--------+
We delete all the data and restore it from the cars.csv file.

Exporting to XML files

It is possible to export and import XML data using the mysql monitor.
$ mysql -uroot -p --xml -e 'SELECT * FROM mydb.Cars' > /tmp/cars.xml
The mysql monitor has an --xml option, which enables us to dump data in XML format. The -e option executes a statement and quits the monitor.
$ cat /tmp/cars.xml 
<?xml version="1.0"?>

<resultset statement="SELECT * FROM mydb.Cars
" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <row>
        <field name="Id">1</field>
        <field name="Name">Audi</field>
        <field name="Cost">52642</field>
  </row>

  <row>
        <field name="Id">2</field>
        <field name="Name">Mercedes</field>
        <field name="Cost">57127</field>
  </row>

  <row>
        <field name="Id">3</field>
        <field name="Name">Skoda</field>
        <field name="Cost">9000</field>
  </row>

  <row>
        <field name="Id">4</field>
        <field name="Name">Volvo</field>
        <field name="Cost">29000</field>
  </row>

  <row>
        <field name="Id">5</field>
        <field name="Name">Bentley</field>
        <field name="Cost">350000</field>
  </row>

  <row>
        <field name="Id">6</field>
        <field name="Name">Citroen</field>
        <field name="Cost">21000</field>
  </row>

  <row>
        <field name="Id">7</field>
        <field name="Name">Hummer</field>
        <field name="Cost">41400</field>
  </row>

  <row>
        <field name="Id">8</field>
        <field name="Name">Volkswagen</field>
        <field name="Cost">21600</field>
  </row>
</resultset>
This is the XML file generated by the mysql monitor.
mysql> TRUNCATE Cars;

mysql> LOAD XML /tmp/cars.xml INTO TABLE Cars;
We truncate the Cars table. We load data from the XML file. Note, that LOAD XML statement is available for MySQL 5.5 and newer.

Using mysqldump tool

The mysqldump is a command tool to create backups for MySQL. The word dump is used when we transfer data from one place to another. From a database file to a text file. From a memory to a file. And similar.

Dumping table structures

mysqldump -u root -p --no-data mydb > bkp1.sql
The above command dumps table structures of all tables in the mydb database to the bkq1.sql file. The --no-data option causes that the data is not saved, only the table structures.
--
-- Table structure for table `Cars`
--

DROP TABLE IF EXISTS `Cars`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Cars` (
  `Id` int(11) NOT NULL,
  `Name` varchar(50) DEFAULT NULL,
  `Cost` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
Here we see a portion of the bkp1.sql file. This is the SQL for the creation of the Cars table.

Dumping data only

$ mysqldump -uroot -p --no-create-info mydb > bkp2.sql
This command dumps all data from all tables of the mydb databases. It omits the table structures. The omission of the table structures is caused by the --no-create-info option.
--
-- Dumping data for table `Cars`
--

LOCK TABLES `Cars` WRITE;
/*!40000 ALTER TABLE `Cars` DISABLE KEYS */;
INSERT INTO `Cars` VALUES (1,'Audi',52642),(2,'Mercedes',57127),(3,'Skoda',9000),
(4,'Volvo',29000),(5,'Bentley',350000),(6,'Citroen',21000),
(7,'Hummer',41400),(8,'Volkswagen',21600);
/*!40000 ALTER TABLE `Cars` ENABLE KEYS */;
UNLOCK TABLES;
Here we can see the data for the Cars table.

Dumping the whole database

$ mysqldump -uroot -p mydb > bkp3.sql
This command dumps all tables from the mydb database to the bkp3.sql file.

Restoring data

We show, how to restore the database from the backup SQL files.
mysql> DROP DATABASE mydb;
ERROR 1010 (HY000): Error dropping database (can't rmdir './mydb/', errno: 17)

mysql> SHOW TABLES;
Empty set (0.00 sec)
We drop the mydb database. An error is shown. The tables were dropped but not the database.
$ sudo ls /var/lib/mysql/mydb
cars  cars.txt
$ sudo rm /var/lib/mysql/mydb/cars
$ sudo rm /var/lib/mysql/mydb/cars.txt
The reason is that (in my case) while doing backups, some of the data were written in the mydb directory, in which MySQL stores the mydb database. These two alien files could not be removed, hence the above error. By removing the files the error is fixed.
mysql> DROP DATABASE mydb;
Query OK, 0 rows affected (0.04 sec)

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| testdb             |
| world              |
+--------------------+
4 rows in set (0.00 sec)
The mydb database was fully removed.
mysql> CREATE DATABASE mydb;

mysql> USE mydb;

mysql> source bkp3.sql
We create the mydb database. Change to the database. And use the source command to execute the bkp3.sql script. The database is recreated.
mysql> SHOW TABLES;
+----------------+
| Tables_in_mydb |
+----------------+
| AA             |
| Ages           |
| Animals        |
| Authors        |
| BB             |
| Books          |
| Books2         |
| Brands         |
| Cars           |
...

mysql> SELECT * FROM Cars;
+----+------------+--------+
| Id | Name       | Cost   |
+----+------------+--------+
|  1 | Audi       |  52642 |
|  2 | Mercedes   |  57127 |
|  3 | Skoda      |   9000 |
|  4 | Volvo      |  29000 |
|  5 | Bentley    | 350000 |
|  6 | Citroen    |  21000 |
|  7 | Hummer     |  41400 |
|  8 | Volkswagen |  21600 |
+----+------------+--------+
The data is verified.

In this part of the MySQL tutorial, we have shown several ways how we can export and import data in MySQL.


Apr 20, 2011

Export XML file directly into MySQL

CREATE SCHEMA xmltest;
CREATE TABLE cities (   
    name CHAR(35) NOT NULL DEFAULT '',
    country CHAR(52) NOT NULL DEFAULT '',
    population int(11) NOT NULL DEFAULT '0'
);

====================================================

INSERT INTO cities VALUES ('Mumbai (Bombay)','India',10500000);
INSERT INTO cities VALUES ('Seoul','South Korea',9981619);
INSERT INTO cities VALUES ('São Paulo','Brazil',9968485);
INSERT INTO cities VALUES ('Shanghai','China',9696300);
INSERT INTO cities VALUES ('Jakarta','Indonesia',9604900);
INSERT INTO cities VALUES ('Karachi','Pakistan',9269265);
INSERT INTO cities VALUES ('Istanbul','Turkey',8787958);
INSERT INTO cities VALUES ('Ciudad de México','Mexico',8591309);
INSERT INTO cities VALUES ('Moscow','Russian Federation',8389200);
INSERT INTO cities VALUES ('New York','United States',8008278);
=====================================================================
SELECT * FROM cities c;
----------------------------------------------------------------------
E:\Program Files\\products\core{db}\run\mysql\MySQL Ser
ver 5.1\bin>mysqldump -u root --xml -p  xmtest cities>xx.xml
Enter password: ********
xx.xml file is created in bin folder
==============================================================================
the data of xml file is
===================================================================================
<?xml version="1.0"?>
<mysqldump xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<database name="xmtest">
 <table_structure name="cities">
  <field Field="name" Type="char(35)" Null="NO" Key="" Default="" Extra="" />
  <field Field="country" Type="char(52)" Null="NO" Key="" Default="" Extra="" />
  <field Field="population" Type="int(11)" Null="NO" Key="" Default="0" Extra="" />
  <options Name="cities" Engine="InnoDB" Version="10" Row_format="Compact" Rows="10" Avg_row_length="1638" Data_length="16384" Max_data_length="0" Index_length="0" Data_free="4194304" Create_time="2011-04-14 14:17:59" Collation="utf8_general_ci" Create_options="" Comment="" />
 </table_structure>
 <table_data name="cities">
 <row>
  <field name="name">New York</field>
  <field name="country">United States</field>
  <field name="population">8008278</field>
 </row>
 <row>
  <field name="name">Moscow</field>
  <field name="country">Russian Federation</field>
  <field name="population">8389200</field>
 </row>
 <row>
  <field name="name">Ciudad de México</field>
  <field name="country">Mexico</field>
  <field name="population">8591309</field>
 </row>
 <row>
  <field name="name">Istanbul</field>
  <field name="country">Turkey</field>
  <field name="population">8787958</field>
 </row>
 <row>
  <field name="name">Karachi</field>
  <field name="country">Pakistan</field>
  <field name="population">9269265</field>
 </row>
 <row>
  <field name="name">Jakarta</field>
  <field name="country">Indonesia</field>
  <field name="population">9604900</field>
 </row>
 <row>
  <field name="name">Shanghai</field>
  <field name="country">China</field>
  <field name="population">9696300</field>
 </row>
 <row>
  <field name="name">São Paulo</field>
  <field name="country">Brazil</field>
  <field name="population">9968485</field>
 </row>
 <row>
  <field name="name">Seoul</field>
  <field name="country">South Korea</field>
  <field name="population">9981619</field>
 </row>
 <row>
  <field name="name">Mumbai (Bombay)</field>
  <field name="country">India</field>
  <field name="population">10500000</field>
 </row>
 </table_data>
</database>
</mysqldump>
================================================================================================================

Apr 14, 2011

Export/Import CSV file directly into MySQL



Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.


Export:

SELECT * INTO OUTFILE 'c:/mysqldump.csv' FIELDS TERMINATED BY ','
 OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n'
FROM cities

Import:

load data local infile 'C:\\mysqldump.csv' into table cities
fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(name, country, population)


The fields here are the actual cities table fields that the data needs to sit in. The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.
You can then import it into a MySQL table by running:

Jan 12, 2011

How to drop the triiger from a db using mysqldump command

 
<>mysql -u root -p116court databse1-e "drop trigger trgname" 

username,password and data base name

Dec 22, 2010

MySQL: Partition-wise backups with mysqldump

How it works

The script works by querying the information_schema.PARTITIONS system view to generate an appropriate expression for mysqldump's --where option. The generated command also redirects the output to a file with this name pattern:
<schema>.<table>.<partition-name>.sql
For example, for this table (taken from the MySQL reference manual):
CREATE TABLE members (
    firstname VARCHAR(25) NOT NULL,
    lastname VARCHAR(25) NOT NULL,
    username VARCHAR(16) NOT NULL,
    email VARCHAR(35),
    joined DATE NOT NULL
)
PARTITION BY RANGE( YEAR(joined) ) (
    PARTITION p0 VALUES LESS THAN (1960),
    PARTITION p1 VALUES LESS THAN (1970),
    PARTITION p2 VALUES LESS THAN (1980),
    PARTITION p3 VALUES LESS THAN (1990),
    PARTITION p4 VALUES LESS THAN MAXVALUE
);
the script generates the following commands:
mysqldump --user=username --password=password --no-create-info --where=" YEAR(joined) < 1960" test members > test.members.p0.sql
mysqldump --user=username --password=password --no-create-info --where=" YEAR(joined) >= 1960 and  YEAR(joined) < 1970" test members > test.members.p1.sql
mysqldump --user=username --password=password --no-create-info --where=" YEAR(joined) >= 1970 and  YEAR(joined) < 1980" test members > test.members.p2.sql
mysqldump --user=username --password=password --no-create-info --where=" YEAR(joined) >= 1980 and  YEAR(joined) < 1990" test members > test.members.p3.sql
mysqldump --user=username --password=password --no-create-info --where=" YEAR(joined) >= 1990 and  YEAR(joined) < 18446744073709551615" test members > test.members.p4.sql
Tip: in order to obtain directly executable output from the mysql command line tool, run the script with the --skip-column-names (or -N) option.

Features

Currently, the script supports the following partitioning methods:

Dec 21, 2010

Selectively dumping data with mysqldump

mysqldump is a command line tool for outputting table structures and data and can be used for backups etc. By default mysqldump will dump all data from a table, but it is possible to select which data to be exported with mysqldump. This post looks at how to do this.

The examples in this post have a table called "mytable" in a database called "test". mytable has three columns: mytable_id, category_id and name, and we will be selectively exporting data that matches a specific category_id.
Using mysqldump to dump all data from the table would look like this, subsituting [username] for your username (the -t flag suppresses the table creation sql from the dump):
mysqldump -t -u [username] -p test mytable
The output from my example table looks like this, once we remove all the extra SQL commands (I've added linebreaks to make it more legible):
INSERT INTO `mytable` VALUES 
  (1,1,'Lorem ipsum dolor sit amet'),
  (2,1,'Ut purus est'),
  (3,2,'Leo sed condimentum semper'),
  (4,2,'Donec velit neque'),
  (5,3,'Maecenas ullamcorper');
If we only wanted to dump data from mytable in category_id 1, we would do this:
mysqldump -t -u [username] -p test mytable --where=category_id=1
which would output this:
INSERT INTO `mytable` VALUES 
  (1,1,'Lorem ipsum dolor sit amet'),
  (2,1,'Ut purus est');
You can also abbreviate --where as -w like so:
mysqldump -t -u [username] -p test mytable -wcategory_id=1
If you need to have spaces in the where query or other special shell characters (such as > and <) then you need to put quotes around the where clause like so:
mysqldump -t -u [username] -p test mytable --where="category_id = 1"
OR
mysqldump -t -u [username] -p test mytable -w"category_id = 1"
You can also use the --where flag to selectively dump data from more than one table, but obviously the columns specified in the where clause need to be in both tables.
An example of dumping data from two tables using the same where clause could look like this, where we are selecting category_id from tables "mytable" and "anothertable":
mysqldump -t -u [username] -p test mytable anothertable --where="category_id = 1"
If category_id exists in both tables then the dump will run without error. If the column doesn't exist, you'll see an error like this:
mysqldump: mysqldump: Couldn't execute 'SELECT /*!40001 SQL_NO_CACHE */ * FROM `anothertable` WHERE category_id=1': Unknown column 'category_id' in 'where clause' (1054)
mysqldump: Got error: 1054: Unknown column 'category_id' in 'where clause' when retrieving data from server
mysqldump is an excellent tool for exporting data from MySQL databases. Using the --where or -w flags allows you to selectively export data from one or more tables which saves you having to export all data from a table if you only need a specific subset.

MySQL Database Backup using mysqldump command.

Since its release in 1995, MySQL has became one of the most commonly used database in Internet world. A lot of small and medium businesses uses MySQL as their backend db.  Its popularity for use with web applications is closely tied to the popularity of PHP, which is often combined with MySQL. Wikipedia runs on MediaWiki software, which is written in PHP and uses a MySQL database. Several high-traffic web sites use MySQL for its data storage and logging of user data, including Flickr, Facebook, Wikipedia, Google, Nokia and YouTube.
MySQL provide a great command line utility to take backup of your MySQL database and restore it. mysqldump command line utility is available with MySQL installation (bin directory) that can be used to achieve this.

Getting backup of a MySQL database using mysqldump.

Use following command line for taking backup of your MySQL database using mysqldump utility.


mysqldump –-user [user name] –-password=[password] [database name] > [dump file]
  
or
  
mysqldump –u[user name] –p[password] [database name] > [dump file]


Example:


mysqldump –-user root –-password=myrootpassword db_test > db_test.sql
  
or
  
mysqldump –uroot –pmyrootpassword db_test > db_test.sql


Backup multiple databases in MySQL.

mysqldump –u[user name] –p[password] [database name 1] [database name 2] .. > [dump file]
Example:


mysqldump –-user root –-password=myrootpassword db_test db_second db_third > db_test.sql



Backup all databases in MySQL.


shell> mysqldump –u[user name] –p[password] –all-databases > [dump file]


Backup a specific table in MySQL.


shell> mysqldump --user [username] --password=[password] [database name] [table name] \
> /tmp/sugarcrm_accounts_contacts.sql


Example:


shell> mysqldump --user root --password=myrootpassword db_test customers \
> db_test_customers.sql

Restoring MySQL database.
The mysqldump utility is used only to take the MySQL dump. To restore the database from the dump file that you created in previous step, use mysql command.


shell> mysql --u [username] --password=[password] [database name] < [dump file]

Example:


shell> mysql --user root --password=myrootpassword new_db < db_test.sql

Backing Up and Restoring Your MySQL Database

The easiest way to backup your database would be to telnet to the your database server machine and use the mysqldump command to dump your whole database to a backup file. If you do not have telnet or shell access to your server, don't worry about it; I shall outline a method of doing so using the PHPMyAdmin web interface, which you can setup on any web server which executes PHP scripts.
Playing with mysqldump
If you have either a shell or telnet access to your database server, you can backup the database using mysqldump. By default, the output of the command will dump the contents of the database in SQL statements to your console. This output can then be piped or redirected to any location you want. If you plan to backup your database, you can pipe the output to a sql file, which will contain the SQL statements to recreate and populate the database tables when you wish to restore your database. There are more adventurous ways to use the output of mysqldump.
A Simple Database Backup:
You can use mysqldump to create a simple backup of your database using the following syntax.
mysqldump -u [username] -p [password] [databasename] > [backupfile.sql]
    • [username] - this is your database username
    • [password] - this is the password for your database
    • [databasename] - the name of your database
    • [backupfile.sql] - the file to which the backup should be written.
       
The resultant dump file will contain all the SQL statements needed to create the table and populate the table in a new database server. To backup your database 'Customers' with the username 'sadmin' and password 'pass21' to a file custback.sql, you would issue the command:
mysqldump -u sadmin -p pass21 Customers > custback.sql
You can also ask mysqldump to add a drop table command before every create command by using the option --add-drop-table. This option is useful if you would like to create a backup file which can rewrite an existing database without having to delete the older database manually first.
mysqldump --add-drop-table -u sadmin -p pass21 Customers > custback.sql
Backing up only specified tables
If you'd like restrict the backup to only certain tables of your database, you can also specify the tables you want to backup. Let's say that you want to backup only customer_master & customer_details from the Customers database, you do that by issuing
mysqldump --add-drop-table -u sadmin -p pass21 Customers customer_master customer_details> custback.sql
So the syntax for the command to issue is:
mysqldump -u [username] -p [password] [databasename] [table1 table2 ....]
    • [tables] - This is a list of tables to backup. Each table is separated by a space.

Mysqldump one table - Taking dump of only one table

Use of mysqldump for taking backup of one table
In this section you will see the example of mysqldump function which takes the backup of only one table.
The mysqldump utility provides many options to take the backup of data as per user requirement. You can specify the name of table be backup in while executing the mysqldump utility.
Let's assume we have to take the backup of table1 from the mydatabase, then you can issue the following command on the console:
mysqldump -u -p mydatabase table1 > table1.sql
To restore the backup you can use the following command:
mysql -u -p mydatabase < table1.sql
The mysqldump is very handy tool, it can be easily used to take the backup of only one table from the database.

MySQL Dump Example

In this tutorial you will come to know about mysqldump command and how to use this command, how to execute, the option it supports etc. Example will make this command more clear.
  MySQLDUMP:
Introduction:
In database we need to store our important data periodically or after certain period of time. MySQL provides several techniques to keep the backup of our important data. In the current and next tutorials we will study about MySQL dump and it's procedures to store the data. You will get several examples in this topic.
In the current tutorial we will study about how to store the data using MySQL dump.
We are assuming that you already have a little knowledge on MySQL and SQL language syntax, if you did not installed MySQL in your system then goto www.mysql.org and download the latest version.
What is MySQLDUMP?
The mysqldump is console based executable utility and it allows us to assign a host of options to get the backup of a database to a file, a different MySQL server running anywhere in the world .
In fact MySQL does not backup our data instead of that it executes a set of basic sql syntaxes like "create table" and "insert into" in the MySQL server to re-create the database/s.
The mysqldump utility is present in the root directory of mysql, let us assume it is c:\mysql and you could find a folder bin in that directory. Using the mysqldump utility we can provide several commands so that we can change the way of taking backups.
There are following ways to invoke mysqldump. Use the following command to take backups:
       prompt/shell> mysqldump [options] db_name [tables]
       prompt/shell> mysqldump [options] --databases DB1 [DB2 DB3...]
       prompt/shell> mysqldump [options] --all-databases

As in the above example  we can see that how to use the command, first of all goto the root directory of MySQL, as in the example it is under xampp directory, then type mysqldump followed by a space and --opt followed by a space --user=root(default user, type the valid username you want ) followed by a space, --password, if you have set the password previously then write the password after equal sign, put a space after that write down the database name, followed by a space greater than sign (>) specify a file name, in which the backup will be taken. The file will be stored in the same folder in which the mysqldump persists. In my example the rose database does not contain any table, and the output of the rose.sql file is as below:


-- MySQL dump 10.13 Distrib 5.1.41, for Win32 (ia32)
--
-- Host: localhost Database: rose
-- ------------------------------------------------------
-- Server version 5.1.41
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2010-04-07 17:10:52
Let us create a simple table and check the output, consider a table userdetails as follows:
`user_id` int(20) NOT NULL AUTO_INCREMENT,
`user_login`
varchar(32) NOT NULL,
`password`
varchar(64) NOT NULL,
PRIMARY KEY
(`user_id`)
Now again execute the command as mentioned above with following modification:
C:\xampp\mysql\bin>mysqldump --opt --user=root --password rose userdetails> rose.sql
Enter password:

Note: Enter password is not a command, as you type the command and press the return key, it will ask for the password of the current user.
If the table is previously build then the above command will rewrite the whole file.
If you check the output of the file rose.sql then it will display the following differences:
-- MySQL dump 10.13 Distrib 5.1.41, for Win32 (ia32)
--
-- Host: localhost Database: rose
-- ------------------------------------------------------
-- Server version 5.1.41
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `userdetails`
--
DROP TABLE IF EXISTS `userdetails`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userdetails` (
`user_id` int
(20) NOT NULL AUTO_INCREMENT,
`user_login`
varchar(32) NOT NULL,
`password`
varchar(64) NOT NULL,
PRIMARY KEY
(`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `userdetails`
--
LOCK TABLES `userdetails` WRITE;
/*!40000 ALTER TABLE `userdetails` DISABLE KEYS */;
INSERT INTO `userdetails` VALUES (1,'rose','india'),(2,'nie','jackson');
/*!40000 ALTER TABLE `userdetails` ENABLE KEYS */;
UNLOCK
TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2010-04-07 17:46:32
To get the output in the command prompt type the following code:
C:\xampp\mysql\bin>mysqldump --user=root --password rose < rose.sql
Enter password:
Note: Enter password is not a command, as you type the command and press the return key, it will ask for the password of the current user.

If we use --databases option or --all-databases option or do not specify the name of the table then entire databases are dumped. To get any kind of help or to check the options of the version you are currently using, execute mysqldump --help. Output would be as follows:

If mysqldump runs without --quick or --opt option, before dumping the result mysqldump loads the whole result into the system's memory. In MySQL 4.1, --opt is enabled by default  and it can be disabled by --skip-opt. It is recommended that if you are using  recent copy of mysqldump program to generate a dump which will be reloaded in the older version of MySQL, then you should not use the option --opt or -e options.
Few Options supported by mysqldump:
  • mysqldump -? = It displays a long list of options which are supported by mysqldump. To check the options one by one, type mysqldump -?|more.
  • mysqldump --version displays the version of the mysqldump which is in use. The command is as below: C:\xampp\mysql\bin>mysqldump --version
    mysqldump Ver 10.13 Distrib 5.1.41, for Win32 (ia32) 

How to find the mysql version

mysql> select version();
+------------------+
| version()        |
+------------------+
| 5.1.53-community |
+------------------+
1 row in set (0.01 sec)

Dec 16, 2010

Delete Triggers example

Delete Trigger
delimiter//
create TRIGGER v57node_delete before delete ON v57node
FOR EACH ROW
BEGIN
set @masteruuid=(select masterUUid from v20ucr_session_lookup where ucr_session_id=old.ucr_session_id);
set @masterTable=(select masterTable from v20ucr_session_lookup where ucr_session_id=old.ucr_session_id);
insert into v20ucr_record_master(tableName,recUUID,clientMask,masterUUID,ucr_session_id,masterTable)
values('v57node',old.uuid, old.clientmask,@masteruuid,old.ucr_session_id,@masterTable);
END;

Delete Triggers example

Delete Trigger
delimiter//
create TRIGGER v57node_delete before delete ON v57node
FOR EACH ROW
BEGIN
set @masteruuid=(select masterUUid from v20ucr_session_lookup where ucr_session_id=old.ucr_session_id);
set @masterTable=(select masterTable from v20ucr_session_lookup where ucr_session_id=old.ucr_session_id);
insert into v20ucr_record_master(tableName,recUUID,clientMask,masterUUID,ucr_session_id,masterTable)
values('v57node',old.uuid, old.clientmask,@masteruuid,old.ucr_session_id,@masterTable);
END;

UpdateTriggers example

update Trigger
delimiter//
create TRIGGER v57node_update before update ON v57node
FOR EACH ROW
BEGIN  
IF NEW.uuid  is null THEN
     SET NEW.uuid =unhex(REPLACE(UUID(),'-',''));
         END IF;
set @masteruuid=(select masterUUid from v20ucr_session_lookup where ucr_session_id=new.ucr_session_id);
set @masterTable=(select masterTable from v20ucr_session_lookup where ucr_session_id=new.ucr_session_id);
if@masteruuid is not null then
insert into v20ucr_record_master(tableName,recUUID,clientMask,masterUUID,ucr_session_id,masterTable)
values('v57node',new.uuid, new.clientmask,@masteruuid,new.ucr_session_id,@masterTable);
end if;
END;

Insert Triggers example

Insert Trigger
delimiter//
create TRIGGER v57node_insert before INSERT ON v57node
FOR EACH ROW
BEGIN  
IF NEW.uuid  is null THEN
     SET NEW.uuid =unhex(REPLACE(UUID(),'-',''));
         END IF;
set @masteruuid=(select masterUUid from v20ucr_session_lookup where ucr_session_id=new.ucr_session_id);
set @masterTable=(select masterTable from v20ucr_session_lookup where ucr_session_id=new.ucr_session_id);
if@masteruuid is not null then
insert into v20ucr_record_master(tableName,recUUID,clientMask,masterUUID,ucr_session_id,masterTable)
values('v57node',new.uuid, new.clientmask,@masteruuid,new.ucr_session_id,@masterTable);
end if;
END;

Indexes for Temporary tables Concept


Creating a Temporary table:
create table emp like employees
 This command creates emp table with the structure  like employees table
create table emp1  select * from employees
This command creates emp1 table with the structure and data  like employees table
you can create the table and add the index afterwards:
CREATE TEMPORARY TABLE temp_table(employeeNumber int)
ALTER TABLE temp_table ADD FULLTEXT INDEX (employeeNumber)
INSERT INTO temp_table SELECT * FROM regular_table
But the index will be, again, updated on every insert.
Probably the most efficient way would be to create the temp table, insert all, build index afterwards:
CREATE TEMPORARY TABLE temp_table

ALTER TABLE temp_table ADD FULLTEXT INDEX (employeeNumber)

ALTER TABLE temp_table DISABLE KEYS

INSERT INTO temp_table SELECT * FROM regular_table

ALTER TABLE temp_table ENABLE KEYS
Creating a MySQL Index - New Table:
CREATE TABLE employee_records
(
               name VARCHAR(50),
               employeeID INT, INDEX (employeeID)
);

Creating a MySQL Index - Existing Table:

CREATE TABLE employee_records2 (name VARCHAR(50), employeeID INT);
CREATE INDEX id_index ON employee_records2(employeeID);
ALTER TABLE  employee_records2 ADD INDEX (employeeID);

Droping a MySQL Index - Existing Table:

ALTER TABLE employee_records2   DROP INDEX (employeeID);

 Creating a multi-column MySQL table index:


CREATE INDEX idx_employee_records2  ON employee_records2 (name, employeeID);

The MySQL SHOW INDEX command :


show index from node;
This command shows the indexes from the database table named node